2 * Copyright (C) 2001, 2002 Sistina Software (UK) Limited.
3 * Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
5 * This file is released under the GPL.
11 #include <linux/init.h>
12 #include <linux/module.h>
13 #include <linux/mutex.h>
14 #include <linux/moduleparam.h>
15 #include <linux/blkpg.h>
16 #include <linux/bio.h>
17 #include <linux/mempool.h>
18 #include <linux/slab.h>
19 #include <linux/idr.h>
20 #include <linux/hdreg.h>
21 #include <linux/delay.h>
22 #include <linux/wait.h>
23 #include <linux/kthread.h>
24 #include <linux/ktime.h>
25 #include <linux/elevator.h> /* for rq_end_sector() */
26 #include <linux/blk-mq.h>
29 #include <trace/events/block.h>
31 #define DM_MSG_PREFIX "core"
35 * ratelimit state to be used in DMXXX_LIMIT().
37 DEFINE_RATELIMIT_STATE(dm_ratelimit_state,
38 DEFAULT_RATELIMIT_INTERVAL,
39 DEFAULT_RATELIMIT_BURST);
40 EXPORT_SYMBOL(dm_ratelimit_state);
44 * Cookies are numeric values sent with CHANGE and REMOVE
45 * uevents while resuming, removing or renaming the device.
47 #define DM_COOKIE_ENV_VAR_NAME "DM_COOKIE"
48 #define DM_COOKIE_LENGTH 24
50 static const char *_name = DM_NAME;
52 static unsigned int major = 0;
53 static unsigned int _major = 0;
55 static DEFINE_IDR(_minor_idr);
57 static DEFINE_SPINLOCK(_minor_lock);
59 static void do_deferred_remove(struct work_struct *w);
61 static DECLARE_WORK(deferred_remove_work, do_deferred_remove);
63 static struct workqueue_struct *deferred_remove_workqueue;
67 * One of these is allocated per bio.
70 struct mapped_device *md;
74 unsigned long start_time;
75 spinlock_t endio_lock;
76 struct dm_stats_aux stats_aux;
80 * For request-based dm.
81 * One of these is allocated per request.
83 struct dm_rq_target_io {
84 struct mapped_device *md;
86 struct request *orig, *clone;
87 struct kthread_work work;
90 struct dm_stats_aux stats_aux;
91 unsigned long duration_jiffies;
96 * For request-based dm - the bio clones we allocate are embedded in these
99 * We allocate these with bio_alloc_bioset, using the front_pad parameter when
100 * the bioset is created - this means the bio has to come at the end of the
103 struct dm_rq_clone_bio_info {
105 struct dm_rq_target_io *tio;
109 union map_info *dm_get_rq_mapinfo(struct request *rq)
111 if (rq && rq->end_io_data)
112 return &((struct dm_rq_target_io *)rq->end_io_data)->info;
115 EXPORT_SYMBOL_GPL(dm_get_rq_mapinfo);
117 #define MINOR_ALLOCED ((void *)-1)
120 * Bits for the md->flags field.
122 #define DMF_BLOCK_IO_FOR_SUSPEND 0
123 #define DMF_SUSPENDED 1
125 #define DMF_FREEING 3
126 #define DMF_DELETING 4
127 #define DMF_NOFLUSH_SUSPENDING 5
128 #define DMF_DEFERRED_REMOVE 6
129 #define DMF_SUSPENDED_INTERNALLY 7
132 * A dummy definition to make RCU happy.
133 * struct dm_table should never be dereferenced in this file.
140 * Work processed by per-device workqueue.
142 struct mapped_device {
143 struct srcu_struct io_barrier;
144 struct mutex suspend_lock;
149 * The current mapping.
150 * Use dm_get_live_table{_fast} or take suspend_lock for
153 struct dm_table __rcu *map;
155 struct list_head table_devices;
156 struct mutex table_devices_lock;
160 struct request_queue *queue;
162 /* Protect queue and type against concurrent access. */
163 struct mutex type_lock;
165 struct target_type *immutable_target_type;
167 struct gendisk *disk;
173 * A list of ios that arrived while we were suspended.
176 wait_queue_head_t wait;
177 struct work_struct work;
178 struct bio_list deferred;
179 spinlock_t deferred_lock;
182 * Processing queue (flush)
184 struct workqueue_struct *wq;
187 * io objects are allocated from here.
198 wait_queue_head_t eventq;
200 struct list_head uevent_list;
201 spinlock_t uevent_lock; /* Protect access to uevent_list */
204 * freeze/thaw support require holding onto a super block
206 struct super_block *frozen_sb;
207 struct block_device *bdev;
209 /* forced geometry settings */
210 struct hd_geometry geometry;
212 /* kobject and completion */
213 struct dm_kobject_holder kobj_holder;
215 /* zero-length flush that will be cloned and submitted to targets */
216 struct bio flush_bio;
218 /* the number of internal suspends */
219 unsigned internal_suspend_count;
221 struct dm_stats stats;
223 struct kthread_worker kworker;
224 struct task_struct *kworker_task;
226 /* for request-based merge heuristic in dm_request_fn() */
227 unsigned seq_rq_merge_deadline_usecs;
229 sector_t last_rq_pos;
230 ktime_t last_rq_start_time;
232 /* for blk-mq request-based DM support */
233 struct blk_mq_tag_set tag_set;
237 #ifdef CONFIG_DM_MQ_DEFAULT
238 static bool use_blk_mq = true;
240 static bool use_blk_mq = false;
243 bool dm_use_blk_mq(struct mapped_device *md)
245 return md->use_blk_mq;
249 * For mempools pre-allocation at the table loading time.
251 struct dm_md_mempools {
257 struct table_device {
258 struct list_head list;
260 struct dm_dev dm_dev;
263 #define RESERVED_BIO_BASED_IOS 16
264 #define RESERVED_REQUEST_BASED_IOS 256
265 #define RESERVED_MAX_IOS 1024
266 static struct kmem_cache *_io_cache;
267 static struct kmem_cache *_rq_tio_cache;
268 static struct kmem_cache *_rq_cache;
271 * Bio-based DM's mempools' reserved IOs set by the user.
273 static unsigned reserved_bio_based_ios = RESERVED_BIO_BASED_IOS;
276 * Request-based DM's mempools' reserved IOs set by the user.
278 static unsigned reserved_rq_based_ios = RESERVED_REQUEST_BASED_IOS;
280 static unsigned __dm_get_module_param(unsigned *module_param,
281 unsigned def, unsigned max)
283 unsigned param = ACCESS_ONCE(*module_param);
284 unsigned modified_param = 0;
287 modified_param = def;
288 else if (param > max)
289 modified_param = max;
291 if (modified_param) {
292 (void)cmpxchg(module_param, param, modified_param);
293 param = modified_param;
299 unsigned dm_get_reserved_bio_based_ios(void)
301 return __dm_get_module_param(&reserved_bio_based_ios,
302 RESERVED_BIO_BASED_IOS, RESERVED_MAX_IOS);
304 EXPORT_SYMBOL_GPL(dm_get_reserved_bio_based_ios);
306 unsigned dm_get_reserved_rq_based_ios(void)
308 return __dm_get_module_param(&reserved_rq_based_ios,
309 RESERVED_REQUEST_BASED_IOS, RESERVED_MAX_IOS);
311 EXPORT_SYMBOL_GPL(dm_get_reserved_rq_based_ios);
313 static int __init local_init(void)
317 /* allocate a slab for the dm_ios */
318 _io_cache = KMEM_CACHE(dm_io, 0);
322 _rq_tio_cache = KMEM_CACHE(dm_rq_target_io, 0);
324 goto out_free_io_cache;
326 _rq_cache = kmem_cache_create("dm_clone_request", sizeof(struct request),
327 __alignof__(struct request), 0, NULL);
329 goto out_free_rq_tio_cache;
331 r = dm_uevent_init();
333 goto out_free_rq_cache;
335 deferred_remove_workqueue = alloc_workqueue("kdmremove", WQ_UNBOUND, 1);
336 if (!deferred_remove_workqueue) {
338 goto out_uevent_exit;
342 r = register_blkdev(_major, _name);
344 goto out_free_workqueue;
352 destroy_workqueue(deferred_remove_workqueue);
356 kmem_cache_destroy(_rq_cache);
357 out_free_rq_tio_cache:
358 kmem_cache_destroy(_rq_tio_cache);
360 kmem_cache_destroy(_io_cache);
365 static void local_exit(void)
367 flush_scheduled_work();
368 destroy_workqueue(deferred_remove_workqueue);
370 kmem_cache_destroy(_rq_cache);
371 kmem_cache_destroy(_rq_tio_cache);
372 kmem_cache_destroy(_io_cache);
373 unregister_blkdev(_major, _name);
378 DMINFO("cleaned up");
381 static int (*_inits[])(void) __initdata = {
392 static void (*_exits[])(void) = {
403 static int __init dm_init(void)
405 const int count = ARRAY_SIZE(_inits);
409 for (i = 0; i < count; i++) {
424 static void __exit dm_exit(void)
426 int i = ARRAY_SIZE(_exits);
432 * Should be empty by this point.
434 idr_destroy(&_minor_idr);
438 * Block device functions
440 int dm_deleting_md(struct mapped_device *md)
442 return test_bit(DMF_DELETING, &md->flags);
445 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
447 struct mapped_device *md;
449 spin_lock(&_minor_lock);
451 md = bdev->bd_disk->private_data;
455 if (test_bit(DMF_FREEING, &md->flags) ||
456 dm_deleting_md(md)) {
462 atomic_inc(&md->open_count);
464 spin_unlock(&_minor_lock);
466 return md ? 0 : -ENXIO;
469 static void dm_blk_close(struct gendisk *disk, fmode_t mode)
471 struct mapped_device *md;
473 spin_lock(&_minor_lock);
475 md = disk->private_data;
479 if (atomic_dec_and_test(&md->open_count) &&
480 (test_bit(DMF_DEFERRED_REMOVE, &md->flags)))
481 queue_work(deferred_remove_workqueue, &deferred_remove_work);
485 spin_unlock(&_minor_lock);
488 int dm_open_count(struct mapped_device *md)
490 return atomic_read(&md->open_count);
494 * Guarantees nothing is using the device before it's deleted.
496 int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
500 spin_lock(&_minor_lock);
502 if (dm_open_count(md)) {
505 set_bit(DMF_DEFERRED_REMOVE, &md->flags);
506 } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
509 set_bit(DMF_DELETING, &md->flags);
511 spin_unlock(&_minor_lock);
516 int dm_cancel_deferred_remove(struct mapped_device *md)
520 spin_lock(&_minor_lock);
522 if (test_bit(DMF_DELETING, &md->flags))
525 clear_bit(DMF_DEFERRED_REMOVE, &md->flags);
527 spin_unlock(&_minor_lock);
532 static void do_deferred_remove(struct work_struct *w)
534 dm_deferred_remove();
537 sector_t dm_get_size(struct mapped_device *md)
539 return get_capacity(md->disk);
542 struct request_queue *dm_get_md_queue(struct mapped_device *md)
547 struct dm_stats *dm_get_stats(struct mapped_device *md)
552 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
554 struct mapped_device *md = bdev->bd_disk->private_data;
556 return dm_get_geometry(md, geo);
559 static int dm_get_live_table_for_ioctl(struct mapped_device *md,
560 struct dm_target **tgt, struct block_device **bdev,
561 fmode_t *mode, int *srcu_idx)
563 struct dm_table *map;
568 map = dm_get_live_table(md, srcu_idx);
569 if (!map || !dm_table_get_size(map))
572 /* We only support devices that have a single target */
573 if (dm_table_get_num_targets(map) != 1)
576 *tgt = dm_table_get_target(map, 0);
578 if (!(*tgt)->type->prepare_ioctl)
581 if (dm_suspended_md(md)) {
586 r = (*tgt)->type->prepare_ioctl(*tgt, bdev, mode);
593 dm_put_live_table(md, *srcu_idx);
594 if (r == -ENOTCONN && !fatal_signal_pending(current)) {
601 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
602 unsigned int cmd, unsigned long arg)
604 struct mapped_device *md = bdev->bd_disk->private_data;
605 struct dm_target *tgt;
606 struct block_device *tgt_bdev = NULL;
609 r = dm_get_live_table_for_ioctl(md, &tgt, &tgt_bdev, &mode, &srcu_idx);
615 * Target determined this ioctl is being issued against
616 * a logical partition of the parent bdev; so extra
617 * validation is needed.
619 r = scsi_verify_blk_ioctl(NULL, cmd);
624 r = __blkdev_driver_ioctl(tgt_bdev, mode, cmd, arg);
626 dm_put_live_table(md, srcu_idx);
630 static struct dm_io *alloc_io(struct mapped_device *md)
632 return mempool_alloc(md->io_pool, GFP_NOIO);
635 static void free_io(struct mapped_device *md, struct dm_io *io)
637 mempool_free(io, md->io_pool);
640 static void free_tio(struct mapped_device *md, struct dm_target_io *tio)
642 bio_put(&tio->clone);
645 static struct dm_rq_target_io *alloc_rq_tio(struct mapped_device *md,
648 return mempool_alloc(md->io_pool, gfp_mask);
651 static void free_rq_tio(struct dm_rq_target_io *tio)
653 mempool_free(tio, tio->md->io_pool);
656 static struct request *alloc_clone_request(struct mapped_device *md,
659 return mempool_alloc(md->rq_pool, gfp_mask);
662 static void free_clone_request(struct mapped_device *md, struct request *rq)
664 mempool_free(rq, md->rq_pool);
667 static int md_in_flight(struct mapped_device *md)
669 return atomic_read(&md->pending[READ]) +
670 atomic_read(&md->pending[WRITE]);
673 static void start_io_acct(struct dm_io *io)
675 struct mapped_device *md = io->md;
676 struct bio *bio = io->bio;
678 int rw = bio_data_dir(bio);
680 io->start_time = jiffies;
682 cpu = part_stat_lock();
683 part_round_stats(cpu, &dm_disk(md)->part0);
685 atomic_set(&dm_disk(md)->part0.in_flight[rw],
686 atomic_inc_return(&md->pending[rw]));
688 if (unlikely(dm_stats_used(&md->stats)))
689 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_iter.bi_sector,
690 bio_sectors(bio), false, 0, &io->stats_aux);
693 static void end_io_acct(struct dm_io *io)
695 struct mapped_device *md = io->md;
696 struct bio *bio = io->bio;
697 unsigned long duration = jiffies - io->start_time;
699 int rw = bio_data_dir(bio);
701 generic_end_io_acct(rw, &dm_disk(md)->part0, io->start_time);
703 if (unlikely(dm_stats_used(&md->stats)))
704 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_iter.bi_sector,
705 bio_sectors(bio), true, duration, &io->stats_aux);
708 * After this is decremented the bio must not be touched if it is
711 pending = atomic_dec_return(&md->pending[rw]);
712 atomic_set(&dm_disk(md)->part0.in_flight[rw], pending);
713 pending += atomic_read(&md->pending[rw^0x1]);
715 /* nudge anyone waiting on suspend queue */
721 * Add the bio to the list of deferred io.
723 static void queue_io(struct mapped_device *md, struct bio *bio)
727 spin_lock_irqsave(&md->deferred_lock, flags);
728 bio_list_add(&md->deferred, bio);
729 spin_unlock_irqrestore(&md->deferred_lock, flags);
730 queue_work(md->wq, &md->work);
734 * Everyone (including functions in this file), should use this
735 * function to access the md->map field, and make sure they call
736 * dm_put_live_table() when finished.
738 struct dm_table *dm_get_live_table(struct mapped_device *md, int *srcu_idx) __acquires(md->io_barrier)
740 *srcu_idx = srcu_read_lock(&md->io_barrier);
742 return srcu_dereference(md->map, &md->io_barrier);
745 void dm_put_live_table(struct mapped_device *md, int srcu_idx) __releases(md->io_barrier)
747 srcu_read_unlock(&md->io_barrier, srcu_idx);
750 void dm_sync_table(struct mapped_device *md)
752 synchronize_srcu(&md->io_barrier);
753 synchronize_rcu_expedited();
757 * A fast alternative to dm_get_live_table/dm_put_live_table.
758 * The caller must not block between these two functions.
760 static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
763 return rcu_dereference(md->map);
766 static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
772 * Open a table device so we can use it as a map destination.
774 static int open_table_device(struct table_device *td, dev_t dev,
775 struct mapped_device *md)
777 static char *_claim_ptr = "I belong to device-mapper";
778 struct block_device *bdev;
782 BUG_ON(td->dm_dev.bdev);
784 bdev = blkdev_get_by_dev(dev, td->dm_dev.mode | FMODE_EXCL, _claim_ptr);
786 return PTR_ERR(bdev);
788 r = bd_link_disk_holder(bdev, dm_disk(md));
790 blkdev_put(bdev, td->dm_dev.mode | FMODE_EXCL);
794 td->dm_dev.bdev = bdev;
799 * Close a table device that we've been using.
801 static void close_table_device(struct table_device *td, struct mapped_device *md)
803 if (!td->dm_dev.bdev)
806 bd_unlink_disk_holder(td->dm_dev.bdev, dm_disk(md));
807 blkdev_put(td->dm_dev.bdev, td->dm_dev.mode | FMODE_EXCL);
808 td->dm_dev.bdev = NULL;
811 static struct table_device *find_table_device(struct list_head *l, dev_t dev,
813 struct table_device *td;
815 list_for_each_entry(td, l, list)
816 if (td->dm_dev.bdev->bd_dev == dev && td->dm_dev.mode == mode)
822 int dm_get_table_device(struct mapped_device *md, dev_t dev, fmode_t mode,
823 struct dm_dev **result) {
825 struct table_device *td;
827 mutex_lock(&md->table_devices_lock);
828 td = find_table_device(&md->table_devices, dev, mode);
830 td = kmalloc(sizeof(*td), GFP_KERNEL);
832 mutex_unlock(&md->table_devices_lock);
836 td->dm_dev.mode = mode;
837 td->dm_dev.bdev = NULL;
839 if ((r = open_table_device(td, dev, md))) {
840 mutex_unlock(&md->table_devices_lock);
845 format_dev_t(td->dm_dev.name, dev);
847 atomic_set(&td->count, 0);
848 list_add(&td->list, &md->table_devices);
850 atomic_inc(&td->count);
851 mutex_unlock(&md->table_devices_lock);
853 *result = &td->dm_dev;
856 EXPORT_SYMBOL_GPL(dm_get_table_device);
858 void dm_put_table_device(struct mapped_device *md, struct dm_dev *d)
860 struct table_device *td = container_of(d, struct table_device, dm_dev);
862 mutex_lock(&md->table_devices_lock);
863 if (atomic_dec_and_test(&td->count)) {
864 close_table_device(td, md);
868 mutex_unlock(&md->table_devices_lock);
870 EXPORT_SYMBOL(dm_put_table_device);
872 static void free_table_devices(struct list_head *devices)
874 struct list_head *tmp, *next;
876 list_for_each_safe(tmp, next, devices) {
877 struct table_device *td = list_entry(tmp, struct table_device, list);
879 DMWARN("dm_destroy: %s still exists with %d references",
880 td->dm_dev.name, atomic_read(&td->count));
886 * Get the geometry associated with a dm device
888 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
896 * Set the geometry of a device.
898 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
900 sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
902 if (geo->start > sz) {
903 DMWARN("Start sector is beyond the geometry limits.");
912 /*-----------------------------------------------------------------
914 * A more elegant soln is in the works that uses the queue
915 * merge fn, unfortunately there are a couple of changes to
916 * the block layer that I want to make for this. So in the
917 * interests of getting something for people to use I give
918 * you this clearly demarcated crap.
919 *---------------------------------------------------------------*/
921 static int __noflush_suspending(struct mapped_device *md)
923 return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
927 * Decrements the number of outstanding ios that a bio has been
928 * cloned into, completing the original io if necc.
930 static void dec_pending(struct dm_io *io, int error)
935 struct mapped_device *md = io->md;
937 /* Push-back supersedes any I/O errors */
938 if (unlikely(error)) {
939 spin_lock_irqsave(&io->endio_lock, flags);
940 if (!(io->error > 0 && __noflush_suspending(md)))
942 spin_unlock_irqrestore(&io->endio_lock, flags);
945 if (atomic_dec_and_test(&io->io_count)) {
946 if (io->error == DM_ENDIO_REQUEUE) {
948 * Target requested pushing back the I/O.
950 spin_lock_irqsave(&md->deferred_lock, flags);
951 if (__noflush_suspending(md))
952 bio_list_add_head(&md->deferred, io->bio);
954 /* noflush suspend was interrupted. */
956 spin_unlock_irqrestore(&md->deferred_lock, flags);
959 io_error = io->error;
964 if (io_error == DM_ENDIO_REQUEUE)
967 if ((bio->bi_rw & REQ_FLUSH) && bio->bi_iter.bi_size) {
969 * Preflush done for flush with data, reissue
972 bio->bi_rw &= ~REQ_FLUSH;
975 /* done with normal IO or empty flush */
976 trace_block_bio_complete(md->queue, bio, io_error);
977 bio->bi_error = io_error;
983 static void disable_write_same(struct mapped_device *md)
985 struct queue_limits *limits = dm_get_queue_limits(md);
987 /* device doesn't really support WRITE SAME, disable it */
988 limits->max_write_same_sectors = 0;
991 static void clone_endio(struct bio *bio)
993 int error = bio->bi_error;
995 struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
996 struct dm_io *io = tio->io;
997 struct mapped_device *md = tio->io->md;
998 dm_endio_fn endio = tio->ti->type->end_io;
1001 r = endio(tio->ti, bio, error);
1002 if (r < 0 || r == DM_ENDIO_REQUEUE)
1004 * error and requeue request are handled
1008 else if (r == DM_ENDIO_INCOMPLETE)
1009 /* The target will handle the io */
1012 DMWARN("unimplemented target endio return value: %d", r);
1017 if (unlikely(r == -EREMOTEIO && (bio->bi_rw & REQ_WRITE_SAME) &&
1018 !bdev_get_queue(bio->bi_bdev)->limits.max_write_same_sectors))
1019 disable_write_same(md);
1022 dec_pending(io, error);
1026 * Partial completion handling for request-based dm
1028 static void end_clone_bio(struct bio *clone)
1030 struct dm_rq_clone_bio_info *info =
1031 container_of(clone, struct dm_rq_clone_bio_info, clone);
1032 struct dm_rq_target_io *tio = info->tio;
1033 struct bio *bio = info->orig;
1034 unsigned int nr_bytes = info->orig->bi_iter.bi_size;
1035 int error = clone->bi_error;
1041 * An error has already been detected on the request.
1042 * Once error occurred, just let clone->end_io() handle
1048 * Don't notice the error to the upper layer yet.
1049 * The error handling decision is made by the target driver,
1050 * when the request is completed.
1057 * I/O for the bio successfully completed.
1058 * Notice the data completion to the upper layer.
1062 * bios are processed from the head of the list.
1063 * So the completing bio should always be rq->bio.
1064 * If it's not, something wrong is happening.
1066 if (tio->orig->bio != bio)
1067 DMERR("bio completion is going in the middle of the request");
1070 * Update the original request.
1071 * Do not use blk_end_request() here, because it may complete
1072 * the original request before the clone, and break the ordering.
1074 blk_update_request(tio->orig, 0, nr_bytes);
1077 static struct dm_rq_target_io *tio_from_request(struct request *rq)
1079 return (rq->q->mq_ops ? blk_mq_rq_to_pdu(rq) : rq->special);
1082 static void rq_end_stats(struct mapped_device *md, struct request *orig)
1084 if (unlikely(dm_stats_used(&md->stats))) {
1085 struct dm_rq_target_io *tio = tio_from_request(orig);
1086 tio->duration_jiffies = jiffies - tio->duration_jiffies;
1087 dm_stats_account_io(&md->stats, orig->cmd_flags, blk_rq_pos(orig),
1088 tio->n_sectors, true, tio->duration_jiffies,
1094 * Don't touch any member of the md after calling this function because
1095 * the md may be freed in dm_put() at the end of this function.
1096 * Or do dm_get() before calling this function and dm_put() later.
1098 static void rq_completed(struct mapped_device *md, int rw, bool run_queue)
1100 atomic_dec(&md->pending[rw]);
1102 /* nudge anyone waiting on suspend queue */
1103 if (!md_in_flight(md))
1107 * Run this off this callpath, as drivers could invoke end_io while
1108 * inside their request_fn (and holding the queue lock). Calling
1109 * back into ->request_fn() could deadlock attempting to grab the
1112 if (!md->queue->mq_ops && run_queue)
1113 blk_run_queue_async(md->queue);
1116 * dm_put() must be at the end of this function. See the comment above
1121 static void free_rq_clone(struct request *clone)
1123 struct dm_rq_target_io *tio = clone->end_io_data;
1124 struct mapped_device *md = tio->md;
1126 blk_rq_unprep_clone(clone);
1128 if (md->type == DM_TYPE_MQ_REQUEST_BASED)
1129 /* stacked on blk-mq queue(s) */
1130 tio->ti->type->release_clone_rq(clone);
1131 else if (!md->queue->mq_ops)
1132 /* request_fn queue stacked on request_fn queue(s) */
1133 free_clone_request(md, clone);
1135 * NOTE: for the blk-mq queue stacked on request_fn queue(s) case:
1136 * no need to call free_clone_request() because we leverage blk-mq by
1137 * allocating the clone at the end of the blk-mq pdu (see: clone_rq)
1140 if (!md->queue->mq_ops)
1145 * Complete the clone and the original request.
1146 * Must be called without clone's queue lock held,
1147 * see end_clone_request() for more details.
1149 static void dm_end_request(struct request *clone, int error)
1151 int rw = rq_data_dir(clone);
1152 struct dm_rq_target_io *tio = clone->end_io_data;
1153 struct mapped_device *md = tio->md;
1154 struct request *rq = tio->orig;
1156 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
1157 rq->errors = clone->errors;
1158 rq->resid_len = clone->resid_len;
1162 * We are using the sense buffer of the original
1164 * So setting the length of the sense data is enough.
1166 rq->sense_len = clone->sense_len;
1169 free_rq_clone(clone);
1170 rq_end_stats(md, rq);
1172 blk_end_request_all(rq, error);
1174 blk_mq_end_request(rq, error);
1175 rq_completed(md, rw, true);
1178 static void dm_unprep_request(struct request *rq)
1180 struct dm_rq_target_io *tio = tio_from_request(rq);
1181 struct request *clone = tio->clone;
1183 if (!rq->q->mq_ops) {
1185 rq->cmd_flags &= ~REQ_DONTPREP;
1189 free_rq_clone(clone);
1190 else if (!tio->md->queue->mq_ops)
1195 * Requeue the original request of a clone.
1197 static void old_requeue_request(struct request *rq)
1199 struct request_queue *q = rq->q;
1200 unsigned long flags;
1202 spin_lock_irqsave(q->queue_lock, flags);
1203 blk_requeue_request(q, rq);
1204 blk_run_queue_async(q);
1205 spin_unlock_irqrestore(q->queue_lock, flags);
1208 static void dm_requeue_original_request(struct mapped_device *md,
1211 int rw = rq_data_dir(rq);
1213 rq_end_stats(md, rq);
1214 dm_unprep_request(rq);
1217 old_requeue_request(rq);
1219 blk_mq_requeue_request(rq);
1220 blk_mq_kick_requeue_list(rq->q);
1223 rq_completed(md, rw, false);
1226 static void old_stop_queue(struct request_queue *q)
1228 unsigned long flags;
1230 if (blk_queue_stopped(q))
1233 spin_lock_irqsave(q->queue_lock, flags);
1235 spin_unlock_irqrestore(q->queue_lock, flags);
1238 static void stop_queue(struct request_queue *q)
1243 blk_mq_stop_hw_queues(q);
1246 static void old_start_queue(struct request_queue *q)
1248 unsigned long flags;
1250 spin_lock_irqsave(q->queue_lock, flags);
1251 if (blk_queue_stopped(q))
1253 spin_unlock_irqrestore(q->queue_lock, flags);
1256 static void start_queue(struct request_queue *q)
1261 blk_mq_start_stopped_hw_queues(q, true);
1264 static void dm_done(struct request *clone, int error, bool mapped)
1267 struct dm_rq_target_io *tio = clone->end_io_data;
1268 dm_request_endio_fn rq_end_io = NULL;
1271 rq_end_io = tio->ti->type->rq_end_io;
1273 if (mapped && rq_end_io)
1274 r = rq_end_io(tio->ti, clone, error, &tio->info);
1277 if (unlikely(r == -EREMOTEIO && (clone->cmd_flags & REQ_WRITE_SAME) &&
1278 !clone->q->limits.max_write_same_sectors))
1279 disable_write_same(tio->md);
1282 /* The target wants to complete the I/O */
1283 dm_end_request(clone, r);
1284 else if (r == DM_ENDIO_INCOMPLETE)
1285 /* The target will handle the I/O */
1287 else if (r == DM_ENDIO_REQUEUE)
1288 /* The target wants to requeue the I/O */
1289 dm_requeue_original_request(tio->md, tio->orig);
1291 DMWARN("unimplemented target endio return value: %d", r);
1297 * Request completion handler for request-based dm
1299 static void dm_softirq_done(struct request *rq)
1302 struct dm_rq_target_io *tio = tio_from_request(rq);
1303 struct request *clone = tio->clone;
1307 rq_end_stats(tio->md, rq);
1308 rw = rq_data_dir(rq);
1309 if (!rq->q->mq_ops) {
1310 blk_end_request_all(rq, tio->error);
1311 rq_completed(tio->md, rw, false);
1314 blk_mq_end_request(rq, tio->error);
1315 rq_completed(tio->md, rw, false);
1320 if (rq->cmd_flags & REQ_FAILED)
1323 dm_done(clone, tio->error, mapped);
1327 * Complete the clone and the original request with the error status
1328 * through softirq context.
1330 static void dm_complete_request(struct request *rq, int error)
1332 struct dm_rq_target_io *tio = tio_from_request(rq);
1336 blk_complete_request(rq);
1338 blk_mq_complete_request(rq, error);
1342 * Complete the not-mapped clone and the original request with the error status
1343 * through softirq context.
1344 * Target's rq_end_io() function isn't called.
1345 * This may be used when the target's map_rq() or clone_and_map_rq() functions fail.
1347 static void dm_kill_unmapped_request(struct request *rq, int error)
1349 rq->cmd_flags |= REQ_FAILED;
1350 dm_complete_request(rq, error);
1354 * Called with the clone's queue lock held (for non-blk-mq)
1356 static void end_clone_request(struct request *clone, int error)
1358 struct dm_rq_target_io *tio = clone->end_io_data;
1360 if (!clone->q->mq_ops) {
1362 * For just cleaning up the information of the queue in which
1363 * the clone was dispatched.
1364 * The clone is *NOT* freed actually here because it is alloced
1365 * from dm own mempool (REQ_ALLOCED isn't set).
1367 __blk_put_request(clone->q, clone);
1371 * Actual request completion is done in a softirq context which doesn't
1372 * hold the clone's queue lock. Otherwise, deadlock could occur because:
1373 * - another request may be submitted by the upper level driver
1374 * of the stacking during the completion
1375 * - the submission which requires queue lock may be done
1376 * against this clone's queue
1378 dm_complete_request(tio->orig, error);
1382 * Return maximum size of I/O possible at the supplied sector up to the current
1385 static sector_t max_io_len_target_boundary(sector_t sector, struct dm_target *ti)
1387 sector_t target_offset = dm_target_offset(ti, sector);
1389 return ti->len - target_offset;
1392 static sector_t max_io_len(sector_t sector, struct dm_target *ti)
1394 sector_t len = max_io_len_target_boundary(sector, ti);
1395 sector_t offset, max_len;
1398 * Does the target need to split even further?
1400 if (ti->max_io_len) {
1401 offset = dm_target_offset(ti, sector);
1402 if (unlikely(ti->max_io_len & (ti->max_io_len - 1)))
1403 max_len = sector_div(offset, ti->max_io_len);
1405 max_len = offset & (ti->max_io_len - 1);
1406 max_len = ti->max_io_len - max_len;
1415 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
1417 if (len > UINT_MAX) {
1418 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
1419 (unsigned long long)len, UINT_MAX);
1420 ti->error = "Maximum size of target IO is too large";
1424 ti->max_io_len = (uint32_t) len;
1428 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
1431 * A target may call dm_accept_partial_bio only from the map routine. It is
1432 * allowed for all bio types except REQ_FLUSH.
1434 * dm_accept_partial_bio informs the dm that the target only wants to process
1435 * additional n_sectors sectors of the bio and the rest of the data should be
1436 * sent in a next bio.
1438 * A diagram that explains the arithmetics:
1439 * +--------------------+---------------+-------+
1441 * +--------------------+---------------+-------+
1443 * <-------------- *tio->len_ptr --------------->
1444 * <------- bi_size ------->
1447 * Region 1 was already iterated over with bio_advance or similar function.
1448 * (it may be empty if the target doesn't use bio_advance)
1449 * Region 2 is the remaining bio size that the target wants to process.
1450 * (it may be empty if region 1 is non-empty, although there is no reason
1452 * The target requires that region 3 is to be sent in the next bio.
1454 * If the target wants to receive multiple copies of the bio (via num_*bios, etc),
1455 * the partially processed part (the sum of regions 1+2) must be the same for all
1456 * copies of the bio.
1458 void dm_accept_partial_bio(struct bio *bio, unsigned n_sectors)
1460 struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
1461 unsigned bi_size = bio->bi_iter.bi_size >> SECTOR_SHIFT;
1462 BUG_ON(bio->bi_rw & REQ_FLUSH);
1463 BUG_ON(bi_size > *tio->len_ptr);
1464 BUG_ON(n_sectors > bi_size);
1465 *tio->len_ptr -= bi_size - n_sectors;
1466 bio->bi_iter.bi_size = n_sectors << SECTOR_SHIFT;
1468 EXPORT_SYMBOL_GPL(dm_accept_partial_bio);
1470 static void __map_bio(struct dm_target_io *tio)
1474 struct mapped_device *md;
1475 struct bio *clone = &tio->clone;
1476 struct dm_target *ti = tio->ti;
1478 clone->bi_end_io = clone_endio;
1481 * Map the clone. If r == 0 we don't need to do
1482 * anything, the target has assumed ownership of
1485 atomic_inc(&tio->io->io_count);
1486 sector = clone->bi_iter.bi_sector;
1487 r = ti->type->map(ti, clone);
1488 if (r == DM_MAPIO_REMAPPED) {
1489 /* the bio has been remapped so dispatch it */
1491 trace_block_bio_remap(bdev_get_queue(clone->bi_bdev), clone,
1492 tio->io->bio->bi_bdev->bd_dev, sector);
1494 generic_make_request(clone);
1495 } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1496 /* error the io and bail out, or requeue it if needed */
1498 dec_pending(tio->io, r);
1500 } else if (r != DM_MAPIO_SUBMITTED) {
1501 DMWARN("unimplemented target map return value: %d", r);
1507 struct mapped_device *md;
1508 struct dm_table *map;
1512 unsigned sector_count;
1515 static void bio_setup_sector(struct bio *bio, sector_t sector, unsigned len)
1517 bio->bi_iter.bi_sector = sector;
1518 bio->bi_iter.bi_size = to_bytes(len);
1522 * Creates a bio that consists of range of complete bvecs.
1524 static void clone_bio(struct dm_target_io *tio, struct bio *bio,
1525 sector_t sector, unsigned len)
1527 struct bio *clone = &tio->clone;
1529 __bio_clone_fast(clone, bio);
1531 if (bio_integrity(bio))
1532 bio_integrity_clone(clone, bio, GFP_NOIO);
1534 bio_advance(clone, to_bytes(sector - clone->bi_iter.bi_sector));
1535 clone->bi_iter.bi_size = to_bytes(len);
1537 if (bio_integrity(bio))
1538 bio_integrity_trim(clone, 0, len);
1541 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1542 struct dm_target *ti,
1543 unsigned target_bio_nr)
1545 struct dm_target_io *tio;
1548 clone = bio_alloc_bioset(GFP_NOIO, 0, ci->md->bs);
1549 tio = container_of(clone, struct dm_target_io, clone);
1553 tio->target_bio_nr = target_bio_nr;
1558 static void __clone_and_map_simple_bio(struct clone_info *ci,
1559 struct dm_target *ti,
1560 unsigned target_bio_nr, unsigned *len)
1562 struct dm_target_io *tio = alloc_tio(ci, ti, target_bio_nr);
1563 struct bio *clone = &tio->clone;
1567 __bio_clone_fast(clone, ci->bio);
1569 bio_setup_sector(clone, ci->sector, *len);
1574 static void __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1575 unsigned num_bios, unsigned *len)
1577 unsigned target_bio_nr;
1579 for (target_bio_nr = 0; target_bio_nr < num_bios; target_bio_nr++)
1580 __clone_and_map_simple_bio(ci, ti, target_bio_nr, len);
1583 static int __send_empty_flush(struct clone_info *ci)
1585 unsigned target_nr = 0;
1586 struct dm_target *ti;
1588 BUG_ON(bio_has_data(ci->bio));
1589 while ((ti = dm_table_get_target(ci->map, target_nr++)))
1590 __send_duplicate_bios(ci, ti, ti->num_flush_bios, NULL);
1595 static void __clone_and_map_data_bio(struct clone_info *ci, struct dm_target *ti,
1596 sector_t sector, unsigned *len)
1598 struct bio *bio = ci->bio;
1599 struct dm_target_io *tio;
1600 unsigned target_bio_nr;
1601 unsigned num_target_bios = 1;
1604 * Does the target want to receive duplicate copies of the bio?
1606 if (bio_data_dir(bio) == WRITE && ti->num_write_bios)
1607 num_target_bios = ti->num_write_bios(ti, bio);
1609 for (target_bio_nr = 0; target_bio_nr < num_target_bios; target_bio_nr++) {
1610 tio = alloc_tio(ci, ti, target_bio_nr);
1612 clone_bio(tio, bio, sector, *len);
1617 typedef unsigned (*get_num_bios_fn)(struct dm_target *ti);
1619 static unsigned get_num_discard_bios(struct dm_target *ti)
1621 return ti->num_discard_bios;
1624 static unsigned get_num_write_same_bios(struct dm_target *ti)
1626 return ti->num_write_same_bios;
1629 typedef bool (*is_split_required_fn)(struct dm_target *ti);
1631 static bool is_split_required_for_discard(struct dm_target *ti)
1633 return ti->split_discard_bios;
1636 static int __send_changing_extent_only(struct clone_info *ci,
1637 get_num_bios_fn get_num_bios,
1638 is_split_required_fn is_split_required)
1640 struct dm_target *ti;
1645 ti = dm_table_find_target(ci->map, ci->sector);
1646 if (!dm_target_is_valid(ti))
1650 * Even though the device advertised support for this type of
1651 * request, that does not mean every target supports it, and
1652 * reconfiguration might also have changed that since the
1653 * check was performed.
1655 num_bios = get_num_bios ? get_num_bios(ti) : 0;
1659 if (is_split_required && !is_split_required(ti))
1660 len = min((sector_t)ci->sector_count, max_io_len_target_boundary(ci->sector, ti));
1662 len = min((sector_t)ci->sector_count, max_io_len(ci->sector, ti));
1664 __send_duplicate_bios(ci, ti, num_bios, &len);
1667 } while (ci->sector_count -= len);
1672 static int __send_discard(struct clone_info *ci)
1674 return __send_changing_extent_only(ci, get_num_discard_bios,
1675 is_split_required_for_discard);
1678 static int __send_write_same(struct clone_info *ci)
1680 return __send_changing_extent_only(ci, get_num_write_same_bios, NULL);
1684 * Select the correct strategy for processing a non-flush bio.
1686 static int __split_and_process_non_flush(struct clone_info *ci)
1688 struct bio *bio = ci->bio;
1689 struct dm_target *ti;
1692 if (unlikely(bio->bi_rw & REQ_DISCARD))
1693 return __send_discard(ci);
1694 else if (unlikely(bio->bi_rw & REQ_WRITE_SAME))
1695 return __send_write_same(ci);
1697 ti = dm_table_find_target(ci->map, ci->sector);
1698 if (!dm_target_is_valid(ti))
1701 len = min_t(sector_t, max_io_len(ci->sector, ti), ci->sector_count);
1703 __clone_and_map_data_bio(ci, ti, ci->sector, &len);
1706 ci->sector_count -= len;
1712 * Entry point to split a bio into clones and submit them to the targets.
1714 static void __split_and_process_bio(struct mapped_device *md,
1715 struct dm_table *map, struct bio *bio)
1717 struct clone_info ci;
1720 if (unlikely(!map)) {
1727 ci.io = alloc_io(md);
1729 atomic_set(&ci.io->io_count, 1);
1732 spin_lock_init(&ci.io->endio_lock);
1733 ci.sector = bio->bi_iter.bi_sector;
1735 start_io_acct(ci.io);
1737 if (bio->bi_rw & REQ_FLUSH) {
1738 ci.bio = &ci.md->flush_bio;
1739 ci.sector_count = 0;
1740 error = __send_empty_flush(&ci);
1741 /* dec_pending submits any data associated with flush */
1744 ci.sector_count = bio_sectors(bio);
1745 while (ci.sector_count && !error)
1746 error = __split_and_process_non_flush(&ci);
1749 /* drop the extra reference count */
1750 dec_pending(ci.io, error);
1752 /*-----------------------------------------------------------------
1754 *---------------------------------------------------------------*/
1757 * The request function that just remaps the bio built up by
1760 static blk_qc_t dm_make_request(struct request_queue *q, struct bio *bio)
1762 int rw = bio_data_dir(bio);
1763 struct mapped_device *md = q->queuedata;
1765 struct dm_table *map;
1767 map = dm_get_live_table(md, &srcu_idx);
1769 generic_start_io_acct(rw, bio_sectors(bio), &dm_disk(md)->part0);
1771 /* if we're suspended, we have to queue this io for later */
1772 if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
1773 dm_put_live_table(md, srcu_idx);
1775 if (bio_rw(bio) != READA)
1779 return BLK_QC_T_NONE;
1782 __split_and_process_bio(md, map, bio);
1783 dm_put_live_table(md, srcu_idx);
1784 return BLK_QC_T_NONE;
1787 int dm_request_based(struct mapped_device *md)
1789 return blk_queue_stackable(md->queue);
1792 static void dm_dispatch_clone_request(struct request *clone, struct request *rq)
1796 if (blk_queue_io_stat(clone->q))
1797 clone->cmd_flags |= REQ_IO_STAT;
1799 clone->start_time = jiffies;
1800 r = blk_insert_cloned_request(clone->q, clone);
1802 /* must complete clone in terms of original request */
1803 dm_complete_request(rq, r);
1806 static int dm_rq_bio_constructor(struct bio *bio, struct bio *bio_orig,
1809 struct dm_rq_target_io *tio = data;
1810 struct dm_rq_clone_bio_info *info =
1811 container_of(bio, struct dm_rq_clone_bio_info, clone);
1813 info->orig = bio_orig;
1815 bio->bi_end_io = end_clone_bio;
1820 static int setup_clone(struct request *clone, struct request *rq,
1821 struct dm_rq_target_io *tio, gfp_t gfp_mask)
1825 r = blk_rq_prep_clone(clone, rq, tio->md->bs, gfp_mask,
1826 dm_rq_bio_constructor, tio);
1830 clone->cmd = rq->cmd;
1831 clone->cmd_len = rq->cmd_len;
1832 clone->sense = rq->sense;
1833 clone->end_io = end_clone_request;
1834 clone->end_io_data = tio;
1841 static struct request *clone_rq(struct request *rq, struct mapped_device *md,
1842 struct dm_rq_target_io *tio, gfp_t gfp_mask)
1845 * Do not allocate a clone if tio->clone was already set
1846 * (see: dm_mq_queue_rq).
1848 bool alloc_clone = !tio->clone;
1849 struct request *clone;
1852 clone = alloc_clone_request(md, gfp_mask);
1858 blk_rq_init(NULL, clone);
1859 if (setup_clone(clone, rq, tio, gfp_mask)) {
1862 free_clone_request(md, clone);
1869 static void map_tio_request(struct kthread_work *work);
1871 static void init_tio(struct dm_rq_target_io *tio, struct request *rq,
1872 struct mapped_device *md)
1879 memset(&tio->info, 0, sizeof(tio->info));
1880 if (md->kworker_task)
1881 init_kthread_work(&tio->work, map_tio_request);
1884 static struct dm_rq_target_io *prep_tio(struct request *rq,
1885 struct mapped_device *md, gfp_t gfp_mask)
1887 struct dm_rq_target_io *tio;
1889 struct dm_table *table;
1891 tio = alloc_rq_tio(md, gfp_mask);
1895 init_tio(tio, rq, md);
1897 table = dm_get_live_table(md, &srcu_idx);
1898 if (!dm_table_mq_request_based(table)) {
1899 if (!clone_rq(rq, md, tio, gfp_mask)) {
1900 dm_put_live_table(md, srcu_idx);
1905 dm_put_live_table(md, srcu_idx);
1911 * Called with the queue lock held.
1913 static int dm_prep_fn(struct request_queue *q, struct request *rq)
1915 struct mapped_device *md = q->queuedata;
1916 struct dm_rq_target_io *tio;
1918 if (unlikely(rq->special)) {
1919 DMWARN("Already has something in rq->special.");
1920 return BLKPREP_KILL;
1923 tio = prep_tio(rq, md, GFP_ATOMIC);
1925 return BLKPREP_DEFER;
1928 rq->cmd_flags |= REQ_DONTPREP;
1935 * 0 : the request has been processed
1936 * DM_MAPIO_REQUEUE : the original request needs to be requeued
1937 * < 0 : the request was completed due to failure
1939 static int map_request(struct dm_rq_target_io *tio, struct request *rq,
1940 struct mapped_device *md)
1943 struct dm_target *ti = tio->ti;
1944 struct request *clone = NULL;
1948 r = ti->type->map_rq(ti, clone, &tio->info);
1950 r = ti->type->clone_and_map_rq(ti, rq, &tio->info, &clone);
1952 /* The target wants to complete the I/O */
1953 dm_kill_unmapped_request(rq, r);
1956 if (r != DM_MAPIO_REMAPPED)
1958 if (setup_clone(clone, rq, tio, GFP_ATOMIC)) {
1960 ti->type->release_clone_rq(clone);
1961 return DM_MAPIO_REQUEUE;
1966 case DM_MAPIO_SUBMITTED:
1967 /* The target has taken the I/O to submit by itself later */
1969 case DM_MAPIO_REMAPPED:
1970 /* The target has remapped the I/O so dispatch it */
1971 trace_block_rq_remap(clone->q, clone, disk_devt(dm_disk(md)),
1973 dm_dispatch_clone_request(clone, rq);
1975 case DM_MAPIO_REQUEUE:
1976 /* The target wants to requeue the I/O */
1977 dm_requeue_original_request(md, tio->orig);
1981 DMWARN("unimplemented target map return value: %d", r);
1985 /* The target wants to complete the I/O */
1986 dm_kill_unmapped_request(rq, r);
1993 static void map_tio_request(struct kthread_work *work)
1995 struct dm_rq_target_io *tio = container_of(work, struct dm_rq_target_io, work);
1996 struct request *rq = tio->orig;
1997 struct mapped_device *md = tio->md;
1999 if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE)
2000 dm_requeue_original_request(md, rq);
2003 static void dm_start_request(struct mapped_device *md, struct request *orig)
2005 if (!orig->q->mq_ops)
2006 blk_start_request(orig);
2008 blk_mq_start_request(orig);
2009 atomic_inc(&md->pending[rq_data_dir(orig)]);
2011 if (md->seq_rq_merge_deadline_usecs) {
2012 md->last_rq_pos = rq_end_sector(orig);
2013 md->last_rq_rw = rq_data_dir(orig);
2014 md->last_rq_start_time = ktime_get();
2017 if (unlikely(dm_stats_used(&md->stats))) {
2018 struct dm_rq_target_io *tio = tio_from_request(orig);
2019 tio->duration_jiffies = jiffies;
2020 tio->n_sectors = blk_rq_sectors(orig);
2021 dm_stats_account_io(&md->stats, orig->cmd_flags, blk_rq_pos(orig),
2022 tio->n_sectors, false, 0, &tio->stats_aux);
2026 * Hold the md reference here for the in-flight I/O.
2027 * We can't rely on the reference count by device opener,
2028 * because the device may be closed during the request completion
2029 * when all bios are completed.
2030 * See the comment in rq_completed() too.
2035 #define MAX_SEQ_RQ_MERGE_DEADLINE_USECS 100000
2037 ssize_t dm_attr_rq_based_seq_io_merge_deadline_show(struct mapped_device *md, char *buf)
2039 return sprintf(buf, "%u\n", md->seq_rq_merge_deadline_usecs);
2042 ssize_t dm_attr_rq_based_seq_io_merge_deadline_store(struct mapped_device *md,
2043 const char *buf, size_t count)
2047 if (!dm_request_based(md) || md->use_blk_mq)
2050 if (kstrtouint(buf, 10, &deadline))
2053 if (deadline > MAX_SEQ_RQ_MERGE_DEADLINE_USECS)
2054 deadline = MAX_SEQ_RQ_MERGE_DEADLINE_USECS;
2056 md->seq_rq_merge_deadline_usecs = deadline;
2061 static bool dm_request_peeked_before_merge_deadline(struct mapped_device *md)
2063 ktime_t kt_deadline;
2065 if (!md->seq_rq_merge_deadline_usecs)
2068 kt_deadline = ns_to_ktime((u64)md->seq_rq_merge_deadline_usecs * NSEC_PER_USEC);
2069 kt_deadline = ktime_add_safe(md->last_rq_start_time, kt_deadline);
2071 return !ktime_after(ktime_get(), kt_deadline);
2075 * q->request_fn for request-based dm.
2076 * Called with the queue lock held.
2078 static void dm_request_fn(struct request_queue *q)
2080 struct mapped_device *md = q->queuedata;
2082 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2083 struct dm_target *ti;
2085 struct dm_rq_target_io *tio;
2089 * For suspend, check blk_queue_stopped() and increment
2090 * ->pending within a single queue_lock not to increment the
2091 * number of in-flight I/Os after the queue is stopped in
2094 while (!blk_queue_stopped(q)) {
2095 rq = blk_peek_request(q);
2099 /* always use block 0 to find the target for flushes for now */
2101 if (!(rq->cmd_flags & REQ_FLUSH))
2102 pos = blk_rq_pos(rq);
2104 ti = dm_table_find_target(map, pos);
2105 if (!dm_target_is_valid(ti)) {
2107 * Must perform setup, that rq_completed() requires,
2108 * before calling dm_kill_unmapped_request
2110 DMERR_LIMIT("request attempted access beyond the end of device");
2111 dm_start_request(md, rq);
2112 dm_kill_unmapped_request(rq, -EIO);
2116 if (dm_request_peeked_before_merge_deadline(md) &&
2117 md_in_flight(md) && rq->bio && rq->bio->bi_vcnt == 1 &&
2118 md->last_rq_pos == pos && md->last_rq_rw == rq_data_dir(rq))
2121 if (ti->type->busy && ti->type->busy(ti))
2124 dm_start_request(md, rq);
2126 tio = tio_from_request(rq);
2127 /* Establish tio->ti before queuing work (map_tio_request) */
2129 queue_kthread_work(&md->kworker, &tio->work);
2130 BUG_ON(!irqs_disabled());
2136 blk_delay_queue(q, HZ / 100);
2138 dm_put_live_table(md, srcu_idx);
2141 static int dm_any_congested(void *congested_data, int bdi_bits)
2144 struct mapped_device *md = congested_data;
2145 struct dm_table *map;
2147 if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2148 map = dm_get_live_table_fast(md);
2151 * Request-based dm cares about only own queue for
2152 * the query about congestion status of request_queue
2154 if (dm_request_based(md))
2155 r = md->queue->backing_dev_info.wb.state &
2158 r = dm_table_any_congested(map, bdi_bits);
2160 dm_put_live_table_fast(md);
2166 /*-----------------------------------------------------------------
2167 * An IDR is used to keep track of allocated minor numbers.
2168 *---------------------------------------------------------------*/
2169 static void free_minor(int minor)
2171 spin_lock(&_minor_lock);
2172 idr_remove(&_minor_idr, minor);
2173 spin_unlock(&_minor_lock);
2177 * See if the device with a specific minor # is free.
2179 static int specific_minor(int minor)
2183 if (minor >= (1 << MINORBITS))
2186 idr_preload(GFP_KERNEL);
2187 spin_lock(&_minor_lock);
2189 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
2191 spin_unlock(&_minor_lock);
2194 return r == -ENOSPC ? -EBUSY : r;
2198 static int next_free_minor(int *minor)
2202 idr_preload(GFP_KERNEL);
2203 spin_lock(&_minor_lock);
2205 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
2207 spin_unlock(&_minor_lock);
2215 static const struct block_device_operations dm_blk_dops;
2217 static void dm_wq_work(struct work_struct *work);
2219 static void dm_init_md_queue(struct mapped_device *md)
2222 * Request-based dm devices cannot be stacked on top of bio-based dm
2223 * devices. The type of this dm device may not have been decided yet.
2224 * The type is decided at the first table loading time.
2225 * To prevent problematic device stacking, clear the queue flag
2226 * for request stacking support until then.
2228 * This queue is new, so no concurrency on the queue_flags.
2230 queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
2233 * Initialize data that will only be used by a non-blk-mq DM queue
2234 * - must do so here (in alloc_dev callchain) before queue is used
2236 md->queue->queuedata = md;
2237 md->queue->backing_dev_info.congested_data = md;
2240 static void dm_init_old_md_queue(struct mapped_device *md)
2242 md->use_blk_mq = false;
2243 dm_init_md_queue(md);
2246 * Initialize aspects of queue that aren't relevant for blk-mq
2248 md->queue->backing_dev_info.congested_fn = dm_any_congested;
2249 blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
2252 static void cleanup_mapped_device(struct mapped_device *md)
2255 destroy_workqueue(md->wq);
2256 if (md->kworker_task)
2257 kthread_stop(md->kworker_task);
2258 mempool_destroy(md->io_pool);
2259 mempool_destroy(md->rq_pool);
2261 bioset_free(md->bs);
2263 cleanup_srcu_struct(&md->io_barrier);
2266 spin_lock(&_minor_lock);
2267 md->disk->private_data = NULL;
2268 spin_unlock(&_minor_lock);
2269 del_gendisk(md->disk);
2274 blk_cleanup_queue(md->queue);
2283 * Allocate and initialise a blank device with a given minor.
2285 static struct mapped_device *alloc_dev(int minor)
2288 struct mapped_device *md = kzalloc(sizeof(*md), GFP_KERNEL);
2292 DMWARN("unable to allocate device, out of memory.");
2296 if (!try_module_get(THIS_MODULE))
2297 goto bad_module_get;
2299 /* get a minor number for the dev */
2300 if (minor == DM_ANY_MINOR)
2301 r = next_free_minor(&minor);
2303 r = specific_minor(minor);
2307 r = init_srcu_struct(&md->io_barrier);
2309 goto bad_io_barrier;
2311 md->use_blk_mq = use_blk_mq;
2312 md->type = DM_TYPE_NONE;
2313 mutex_init(&md->suspend_lock);
2314 mutex_init(&md->type_lock);
2315 mutex_init(&md->table_devices_lock);
2316 spin_lock_init(&md->deferred_lock);
2317 atomic_set(&md->holders, 1);
2318 atomic_set(&md->open_count, 0);
2319 atomic_set(&md->event_nr, 0);
2320 atomic_set(&md->uevent_seq, 0);
2321 INIT_LIST_HEAD(&md->uevent_list);
2322 INIT_LIST_HEAD(&md->table_devices);
2323 spin_lock_init(&md->uevent_lock);
2325 md->queue = blk_alloc_queue(GFP_KERNEL);
2329 dm_init_md_queue(md);
2331 md->disk = alloc_disk(1);
2335 atomic_set(&md->pending[0], 0);
2336 atomic_set(&md->pending[1], 0);
2337 init_waitqueue_head(&md->wait);
2338 INIT_WORK(&md->work, dm_wq_work);
2339 init_waitqueue_head(&md->eventq);
2340 init_completion(&md->kobj_holder.completion);
2341 md->kworker_task = NULL;
2343 md->disk->major = _major;
2344 md->disk->first_minor = minor;
2345 md->disk->fops = &dm_blk_dops;
2346 md->disk->queue = md->queue;
2347 md->disk->private_data = md;
2348 sprintf(md->disk->disk_name, "dm-%d", minor);
2350 format_dev_t(md->name, MKDEV(_major, minor));
2352 md->wq = alloc_workqueue("kdmflush", WQ_MEM_RECLAIM, 0);
2356 md->bdev = bdget_disk(md->disk, 0);
2360 bio_init(&md->flush_bio);
2361 md->flush_bio.bi_bdev = md->bdev;
2362 md->flush_bio.bi_rw = WRITE_FLUSH;
2364 dm_stats_init(&md->stats);
2366 /* Populate the mapping, nobody knows we exist yet */
2367 spin_lock(&_minor_lock);
2368 old_md = idr_replace(&_minor_idr, md, minor);
2369 spin_unlock(&_minor_lock);
2371 BUG_ON(old_md != MINOR_ALLOCED);
2376 cleanup_mapped_device(md);
2380 module_put(THIS_MODULE);
2386 static void unlock_fs(struct mapped_device *md);
2388 static void free_dev(struct mapped_device *md)
2390 int minor = MINOR(disk_devt(md->disk));
2394 cleanup_mapped_device(md);
2396 blk_mq_free_tag_set(&md->tag_set);
2398 free_table_devices(&md->table_devices);
2399 dm_stats_cleanup(&md->stats);
2402 module_put(THIS_MODULE);
2406 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
2408 struct dm_md_mempools *p = dm_table_get_md_mempools(t);
2411 /* The md already has necessary mempools. */
2412 if (dm_table_get_type(t) == DM_TYPE_BIO_BASED) {
2414 * Reload bioset because front_pad may have changed
2415 * because a different table was loaded.
2417 bioset_free(md->bs);
2422 * There's no need to reload with request-based dm
2423 * because the size of front_pad doesn't change.
2424 * Note for future: If you are to reload bioset,
2425 * prep-ed requests in the queue may refer
2426 * to bio from the old bioset, so you must walk
2427 * through the queue to unprep.
2432 BUG_ON(!p || md->io_pool || md->rq_pool || md->bs);
2434 md->io_pool = p->io_pool;
2436 md->rq_pool = p->rq_pool;
2442 /* mempool bind completed, no longer need any mempools in the table */
2443 dm_table_free_md_mempools(t);
2447 * Bind a table to the device.
2449 static void event_callback(void *context)
2451 unsigned long flags;
2453 struct mapped_device *md = (struct mapped_device *) context;
2455 spin_lock_irqsave(&md->uevent_lock, flags);
2456 list_splice_init(&md->uevent_list, &uevents);
2457 spin_unlock_irqrestore(&md->uevent_lock, flags);
2459 dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2461 atomic_inc(&md->event_nr);
2462 wake_up(&md->eventq);
2466 * Protected by md->suspend_lock obtained by dm_swap_table().
2468 static void __set_size(struct mapped_device *md, sector_t size)
2470 set_capacity(md->disk, size);
2472 i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
2476 * Returns old map, which caller must destroy.
2478 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2479 struct queue_limits *limits)
2481 struct dm_table *old_map;
2482 struct request_queue *q = md->queue;
2485 size = dm_table_get_size(t);
2488 * Wipe any geometry if the size of the table changed.
2490 if (size != dm_get_size(md))
2491 memset(&md->geometry, 0, sizeof(md->geometry));
2493 __set_size(md, size);
2495 dm_table_event_callback(t, event_callback, md);
2498 * The queue hasn't been stopped yet, if the old table type wasn't
2499 * for request-based during suspension. So stop it to prevent
2500 * I/O mapping before resume.
2501 * This must be done before setting the queue restrictions,
2502 * because request-based dm may be run just after the setting.
2504 if (dm_table_request_based(t))
2507 __bind_mempools(md, t);
2509 old_map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2510 rcu_assign_pointer(md->map, t);
2511 md->immutable_target_type = dm_table_get_immutable_target_type(t);
2513 dm_table_set_restrictions(t, q, limits);
2521 * Returns unbound table for the caller to free.
2523 static struct dm_table *__unbind(struct mapped_device *md)
2525 struct dm_table *map = rcu_dereference_protected(md->map, 1);
2530 dm_table_event_callback(map, NULL, NULL);
2531 RCU_INIT_POINTER(md->map, NULL);
2538 * Constructor for a new device.
2540 int dm_create(int minor, struct mapped_device **result)
2542 struct mapped_device *md;
2544 md = alloc_dev(minor);
2555 * Functions to manage md->type.
2556 * All are required to hold md->type_lock.
2558 void dm_lock_md_type(struct mapped_device *md)
2560 mutex_lock(&md->type_lock);
2563 void dm_unlock_md_type(struct mapped_device *md)
2565 mutex_unlock(&md->type_lock);
2568 void dm_set_md_type(struct mapped_device *md, unsigned type)
2570 BUG_ON(!mutex_is_locked(&md->type_lock));
2574 unsigned dm_get_md_type(struct mapped_device *md)
2576 BUG_ON(!mutex_is_locked(&md->type_lock));
2580 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2582 return md->immutable_target_type;
2586 * The queue_limits are only valid as long as you have a reference
2589 struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
2591 BUG_ON(!atomic_read(&md->holders));
2592 return &md->queue->limits;
2594 EXPORT_SYMBOL_GPL(dm_get_queue_limits);
2596 static void init_rq_based_worker_thread(struct mapped_device *md)
2598 /* Initialize the request-based DM worker thread */
2599 init_kthread_worker(&md->kworker);
2600 md->kworker_task = kthread_run(kthread_worker_fn, &md->kworker,
2601 "kdmwork-%s", dm_device_name(md));
2605 * Fully initialize a request-based queue (->elevator, ->request_fn, etc).
2607 static int dm_init_request_based_queue(struct mapped_device *md)
2609 struct request_queue *q = NULL;
2611 /* Fully initialize the queue */
2612 q = blk_init_allocated_queue(md->queue, dm_request_fn, NULL);
2616 /* disable dm_request_fn's merge heuristic by default */
2617 md->seq_rq_merge_deadline_usecs = 0;
2620 dm_init_old_md_queue(md);
2621 blk_queue_softirq_done(md->queue, dm_softirq_done);
2622 blk_queue_prep_rq(md->queue, dm_prep_fn);
2624 init_rq_based_worker_thread(md);
2626 elv_register_queue(md->queue);
2631 static int dm_mq_init_request(void *data, struct request *rq,
2632 unsigned int hctx_idx, unsigned int request_idx,
2633 unsigned int numa_node)
2635 struct mapped_device *md = data;
2636 struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2639 * Must initialize md member of tio, otherwise it won't
2640 * be available in dm_mq_queue_rq.
2647 static int dm_mq_queue_rq(struct blk_mq_hw_ctx *hctx,
2648 const struct blk_mq_queue_data *bd)
2650 struct request *rq = bd->rq;
2651 struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2652 struct mapped_device *md = tio->md;
2654 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2655 struct dm_target *ti;
2658 /* always use block 0 to find the target for flushes for now */
2660 if (!(rq->cmd_flags & REQ_FLUSH))
2661 pos = blk_rq_pos(rq);
2663 ti = dm_table_find_target(map, pos);
2664 if (!dm_target_is_valid(ti)) {
2665 dm_put_live_table(md, srcu_idx);
2666 DMERR_LIMIT("request attempted access beyond the end of device");
2668 * Must perform setup, that rq_completed() requires,
2669 * before returning BLK_MQ_RQ_QUEUE_ERROR
2671 dm_start_request(md, rq);
2672 return BLK_MQ_RQ_QUEUE_ERROR;
2674 dm_put_live_table(md, srcu_idx);
2676 if (ti->type->busy && ti->type->busy(ti))
2677 return BLK_MQ_RQ_QUEUE_BUSY;
2679 dm_start_request(md, rq);
2681 /* Init tio using md established in .init_request */
2682 init_tio(tio, rq, md);
2685 * Establish tio->ti before queuing work (map_tio_request)
2686 * or making direct call to map_request().
2690 /* Clone the request if underlying devices aren't blk-mq */
2691 if (dm_table_get_type(map) == DM_TYPE_REQUEST_BASED) {
2692 /* clone request is allocated at the end of the pdu */
2693 tio->clone = (void *)blk_mq_rq_to_pdu(rq) + sizeof(struct dm_rq_target_io);
2694 (void) clone_rq(rq, md, tio, GFP_ATOMIC);
2695 queue_kthread_work(&md->kworker, &tio->work);
2697 /* Direct call is fine since .queue_rq allows allocations */
2698 if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE) {
2699 /* Undo dm_start_request() before requeuing */
2700 rq_end_stats(md, rq);
2701 rq_completed(md, rq_data_dir(rq), false);
2702 return BLK_MQ_RQ_QUEUE_BUSY;
2706 return BLK_MQ_RQ_QUEUE_OK;
2709 static struct blk_mq_ops dm_mq_ops = {
2710 .queue_rq = dm_mq_queue_rq,
2711 .map_queue = blk_mq_map_queue,
2712 .complete = dm_softirq_done,
2713 .init_request = dm_mq_init_request,
2716 static int dm_init_request_based_blk_mq_queue(struct mapped_device *md)
2718 unsigned md_type = dm_get_md_type(md);
2719 struct request_queue *q;
2722 memset(&md->tag_set, 0, sizeof(md->tag_set));
2723 md->tag_set.ops = &dm_mq_ops;
2724 md->tag_set.queue_depth = BLKDEV_MAX_RQ;
2725 md->tag_set.numa_node = NUMA_NO_NODE;
2726 md->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
2727 md->tag_set.nr_hw_queues = 1;
2728 if (md_type == DM_TYPE_REQUEST_BASED) {
2729 /* make the memory for non-blk-mq clone part of the pdu */
2730 md->tag_set.cmd_size = sizeof(struct dm_rq_target_io) + sizeof(struct request);
2732 md->tag_set.cmd_size = sizeof(struct dm_rq_target_io);
2733 md->tag_set.driver_data = md;
2735 err = blk_mq_alloc_tag_set(&md->tag_set);
2739 q = blk_mq_init_allocated_queue(&md->tag_set, md->queue);
2745 dm_init_md_queue(md);
2747 /* backfill 'mq' sysfs registration normally done in blk_register_queue */
2748 blk_mq_register_disk(md->disk);
2750 if (md_type == DM_TYPE_REQUEST_BASED)
2751 init_rq_based_worker_thread(md);
2756 blk_mq_free_tag_set(&md->tag_set);
2760 static unsigned filter_md_type(unsigned type, struct mapped_device *md)
2762 if (type == DM_TYPE_BIO_BASED)
2765 return !md->use_blk_mq ? DM_TYPE_REQUEST_BASED : DM_TYPE_MQ_REQUEST_BASED;
2769 * Setup the DM device's queue based on md's type
2771 int dm_setup_md_queue(struct mapped_device *md)
2774 unsigned md_type = filter_md_type(dm_get_md_type(md), md);
2777 case DM_TYPE_REQUEST_BASED:
2778 r = dm_init_request_based_queue(md);
2780 DMWARN("Cannot initialize queue for request-based mapped device");
2784 case DM_TYPE_MQ_REQUEST_BASED:
2785 r = dm_init_request_based_blk_mq_queue(md);
2787 DMWARN("Cannot initialize queue for request-based blk-mq mapped device");
2791 case DM_TYPE_BIO_BASED:
2792 dm_init_old_md_queue(md);
2793 blk_queue_make_request(md->queue, dm_make_request);
2795 * DM handles splitting bios as needed. Free the bio_split bioset
2796 * since it won't be used (saves 1 process per bio-based DM device).
2798 bioset_free(md->queue->bio_split);
2799 md->queue->bio_split = NULL;
2806 struct mapped_device *dm_get_md(dev_t dev)
2808 struct mapped_device *md;
2809 unsigned minor = MINOR(dev);
2811 if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2814 spin_lock(&_minor_lock);
2816 md = idr_find(&_minor_idr, minor);
2818 if ((md == MINOR_ALLOCED ||
2819 (MINOR(disk_devt(dm_disk(md))) != minor) ||
2820 dm_deleting_md(md) ||
2821 test_bit(DMF_FREEING, &md->flags))) {
2829 spin_unlock(&_minor_lock);
2833 EXPORT_SYMBOL_GPL(dm_get_md);
2835 void *dm_get_mdptr(struct mapped_device *md)
2837 return md->interface_ptr;
2840 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2842 md->interface_ptr = ptr;
2845 void dm_get(struct mapped_device *md)
2847 atomic_inc(&md->holders);
2848 BUG_ON(test_bit(DMF_FREEING, &md->flags));
2851 int dm_hold(struct mapped_device *md)
2853 spin_lock(&_minor_lock);
2854 if (test_bit(DMF_FREEING, &md->flags)) {
2855 spin_unlock(&_minor_lock);
2859 spin_unlock(&_minor_lock);
2862 EXPORT_SYMBOL_GPL(dm_hold);
2864 const char *dm_device_name(struct mapped_device *md)
2868 EXPORT_SYMBOL_GPL(dm_device_name);
2870 static void __dm_destroy(struct mapped_device *md, bool wait)
2872 struct dm_table *map;
2877 spin_lock(&_minor_lock);
2878 idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2879 set_bit(DMF_FREEING, &md->flags);
2880 spin_unlock(&_minor_lock);
2882 if (dm_request_based(md) && md->kworker_task)
2883 flush_kthread_worker(&md->kworker);
2886 * Take suspend_lock so that presuspend and postsuspend methods
2887 * do not race with internal suspend.
2889 mutex_lock(&md->suspend_lock);
2890 map = dm_get_live_table(md, &srcu_idx);
2891 if (!dm_suspended_md(md)) {
2892 dm_table_presuspend_targets(map);
2893 dm_table_postsuspend_targets(map);
2895 /* dm_put_live_table must be before msleep, otherwise deadlock is possible */
2896 dm_put_live_table(md, srcu_idx);
2897 mutex_unlock(&md->suspend_lock);
2900 * Rare, but there may be I/O requests still going to complete,
2901 * for example. Wait for all references to disappear.
2902 * No one should increment the reference count of the mapped_device,
2903 * after the mapped_device state becomes DMF_FREEING.
2906 while (atomic_read(&md->holders))
2908 else if (atomic_read(&md->holders))
2909 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2910 dm_device_name(md), atomic_read(&md->holders));
2913 dm_table_destroy(__unbind(md));
2917 void dm_destroy(struct mapped_device *md)
2919 __dm_destroy(md, true);
2922 void dm_destroy_immediate(struct mapped_device *md)
2924 __dm_destroy(md, false);
2927 void dm_put(struct mapped_device *md)
2929 atomic_dec(&md->holders);
2931 EXPORT_SYMBOL_GPL(dm_put);
2933 static int dm_wait_for_completion(struct mapped_device *md, int interruptible)
2936 DECLARE_WAITQUEUE(wait, current);
2938 add_wait_queue(&md->wait, &wait);
2941 set_current_state(interruptible);
2943 if (!md_in_flight(md))
2946 if (interruptible == TASK_INTERRUPTIBLE &&
2947 signal_pending(current)) {
2954 set_current_state(TASK_RUNNING);
2956 remove_wait_queue(&md->wait, &wait);
2962 * Process the deferred bios
2964 static void dm_wq_work(struct work_struct *work)
2966 struct mapped_device *md = container_of(work, struct mapped_device,
2970 struct dm_table *map;
2972 map = dm_get_live_table(md, &srcu_idx);
2974 while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2975 spin_lock_irq(&md->deferred_lock);
2976 c = bio_list_pop(&md->deferred);
2977 spin_unlock_irq(&md->deferred_lock);
2982 if (dm_request_based(md))
2983 generic_make_request(c);
2985 __split_and_process_bio(md, map, c);
2988 dm_put_live_table(md, srcu_idx);
2991 static void dm_queue_flush(struct mapped_device *md)
2993 clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2994 smp_mb__after_atomic();
2995 queue_work(md->wq, &md->work);
2999 * Swap in a new table, returning the old one for the caller to destroy.
3001 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
3003 struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
3004 struct queue_limits limits;
3007 mutex_lock(&md->suspend_lock);
3009 /* device must be suspended */
3010 if (!dm_suspended_md(md))
3014 * If the new table has no data devices, retain the existing limits.
3015 * This helps multipath with queue_if_no_path if all paths disappear,
3016 * then new I/O is queued based on these limits, and then some paths
3019 if (dm_table_has_no_data_devices(table)) {
3020 live_map = dm_get_live_table_fast(md);
3022 limits = md->queue->limits;
3023 dm_put_live_table_fast(md);
3027 r = dm_calculate_queue_limits(table, &limits);
3034 map = __bind(md, table, &limits);
3037 mutex_unlock(&md->suspend_lock);
3042 * Functions to lock and unlock any filesystem running on the
3045 static int lock_fs(struct mapped_device *md)
3049 WARN_ON(md->frozen_sb);
3051 md->frozen_sb = freeze_bdev(md->bdev);
3052 if (IS_ERR(md->frozen_sb)) {
3053 r = PTR_ERR(md->frozen_sb);
3054 md->frozen_sb = NULL;
3058 set_bit(DMF_FROZEN, &md->flags);
3063 static void unlock_fs(struct mapped_device *md)
3065 if (!test_bit(DMF_FROZEN, &md->flags))
3068 thaw_bdev(md->bdev, md->frozen_sb);
3069 md->frozen_sb = NULL;
3070 clear_bit(DMF_FROZEN, &md->flags);
3074 * If __dm_suspend returns 0, the device is completely quiescent
3075 * now. There is no request-processing activity. All new requests
3076 * are being added to md->deferred list.
3078 * Caller must hold md->suspend_lock
3080 static int __dm_suspend(struct mapped_device *md, struct dm_table *map,
3081 unsigned suspend_flags, int interruptible)
3083 bool do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG;
3084 bool noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG;
3088 * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
3089 * This flag is cleared before dm_suspend returns.
3092 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3095 * This gets reverted if there's an error later and the targets
3096 * provide the .presuspend_undo hook.
3098 dm_table_presuspend_targets(map);
3101 * Flush I/O to the device.
3102 * Any I/O submitted after lock_fs() may not be flushed.
3103 * noflush takes precedence over do_lockfs.
3104 * (lock_fs() flushes I/Os and waits for them to complete.)
3106 if (!noflush && do_lockfs) {
3109 dm_table_presuspend_undo_targets(map);
3115 * Here we must make sure that no processes are submitting requests
3116 * to target drivers i.e. no one may be executing
3117 * __split_and_process_bio. This is called from dm_request and
3120 * To get all processes out of __split_and_process_bio in dm_request,
3121 * we take the write lock. To prevent any process from reentering
3122 * __split_and_process_bio from dm_request and quiesce the thread
3123 * (dm_wq_work), we set BMF_BLOCK_IO_FOR_SUSPEND and call
3124 * flush_workqueue(md->wq).
3126 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3128 synchronize_srcu(&md->io_barrier);
3131 * Stop md->queue before flushing md->wq in case request-based
3132 * dm defers requests to md->wq from md->queue.
3134 if (dm_request_based(md)) {
3135 stop_queue(md->queue);
3136 if (md->kworker_task)
3137 flush_kthread_worker(&md->kworker);
3140 flush_workqueue(md->wq);
3143 * At this point no more requests are entering target request routines.
3144 * We call dm_wait_for_completion to wait for all existing requests
3147 r = dm_wait_for_completion(md, interruptible);
3150 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3152 synchronize_srcu(&md->io_barrier);
3154 /* were we interrupted ? */
3158 if (dm_request_based(md))
3159 start_queue(md->queue);
3162 dm_table_presuspend_undo_targets(map);
3163 /* pushback list is already flushed, so skip flush */
3170 * We need to be able to change a mapping table under a mounted
3171 * filesystem. For example we might want to move some data in
3172 * the background. Before the table can be swapped with
3173 * dm_bind_table, dm_suspend must be called to flush any in
3174 * flight bios and ensure that any further io gets deferred.
3177 * Suspend mechanism in request-based dm.
3179 * 1. Flush all I/Os by lock_fs() if needed.
3180 * 2. Stop dispatching any I/O by stopping the request_queue.
3181 * 3. Wait for all in-flight I/Os to be completed or requeued.
3183 * To abort suspend, start the request_queue.
3185 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
3187 struct dm_table *map = NULL;
3191 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3193 if (dm_suspended_md(md)) {
3198 if (dm_suspended_internally_md(md)) {
3199 /* already internally suspended, wait for internal resume */
3200 mutex_unlock(&md->suspend_lock);
3201 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3207 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3209 r = __dm_suspend(md, map, suspend_flags, TASK_INTERRUPTIBLE);
3213 set_bit(DMF_SUSPENDED, &md->flags);
3215 dm_table_postsuspend_targets(map);
3218 mutex_unlock(&md->suspend_lock);
3222 static int __dm_resume(struct mapped_device *md, struct dm_table *map)
3225 int r = dm_table_resume_targets(map);
3233 * Flushing deferred I/Os must be done after targets are resumed
3234 * so that mapping of targets can work correctly.
3235 * Request-based dm is queueing the deferred I/Os in its request_queue.
3237 if (dm_request_based(md))
3238 start_queue(md->queue);
3245 int dm_resume(struct mapped_device *md)
3248 struct dm_table *map = NULL;
3251 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3253 if (!dm_suspended_md(md))
3256 if (dm_suspended_internally_md(md)) {
3257 /* already internally suspended, wait for internal resume */
3258 mutex_unlock(&md->suspend_lock);
3259 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3265 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3266 if (!map || !dm_table_get_size(map))
3269 r = __dm_resume(md, map);
3273 clear_bit(DMF_SUSPENDED, &md->flags);
3277 mutex_unlock(&md->suspend_lock);
3283 * Internal suspend/resume works like userspace-driven suspend. It waits
3284 * until all bios finish and prevents issuing new bios to the target drivers.
3285 * It may be used only from the kernel.
3288 static void __dm_internal_suspend(struct mapped_device *md, unsigned suspend_flags)
3290 struct dm_table *map = NULL;
3292 if (md->internal_suspend_count++)
3293 return; /* nested internal suspend */
3295 if (dm_suspended_md(md)) {
3296 set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3297 return; /* nest suspend */
3300 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3303 * Using TASK_UNINTERRUPTIBLE because only NOFLUSH internal suspend is
3304 * supported. Properly supporting a TASK_INTERRUPTIBLE internal suspend
3305 * would require changing .presuspend to return an error -- avoid this
3306 * until there is a need for more elaborate variants of internal suspend.
3308 (void) __dm_suspend(md, map, suspend_flags, TASK_UNINTERRUPTIBLE);
3310 set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3312 dm_table_postsuspend_targets(map);
3315 static void __dm_internal_resume(struct mapped_device *md)
3317 BUG_ON(!md->internal_suspend_count);
3319 if (--md->internal_suspend_count)
3320 return; /* resume from nested internal suspend */
3322 if (dm_suspended_md(md))
3323 goto done; /* resume from nested suspend */
3326 * NOTE: existing callers don't need to call dm_table_resume_targets
3327 * (which may fail -- so best to avoid it for now by passing NULL map)
3329 (void) __dm_resume(md, NULL);
3332 clear_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3333 smp_mb__after_atomic();
3334 wake_up_bit(&md->flags, DMF_SUSPENDED_INTERNALLY);
3337 void dm_internal_suspend_noflush(struct mapped_device *md)
3339 mutex_lock(&md->suspend_lock);
3340 __dm_internal_suspend(md, DM_SUSPEND_NOFLUSH_FLAG);
3341 mutex_unlock(&md->suspend_lock);
3343 EXPORT_SYMBOL_GPL(dm_internal_suspend_noflush);
3345 void dm_internal_resume(struct mapped_device *md)
3347 mutex_lock(&md->suspend_lock);
3348 __dm_internal_resume(md);
3349 mutex_unlock(&md->suspend_lock);
3351 EXPORT_SYMBOL_GPL(dm_internal_resume);
3354 * Fast variants of internal suspend/resume hold md->suspend_lock,
3355 * which prevents interaction with userspace-driven suspend.
3358 void dm_internal_suspend_fast(struct mapped_device *md)
3360 mutex_lock(&md->suspend_lock);
3361 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3364 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3365 synchronize_srcu(&md->io_barrier);
3366 flush_workqueue(md->wq);
3367 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
3369 EXPORT_SYMBOL_GPL(dm_internal_suspend_fast);
3371 void dm_internal_resume_fast(struct mapped_device *md)
3373 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3379 mutex_unlock(&md->suspend_lock);
3381 EXPORT_SYMBOL_GPL(dm_internal_resume_fast);
3383 /*-----------------------------------------------------------------
3384 * Event notification.
3385 *---------------------------------------------------------------*/
3386 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
3389 char udev_cookie[DM_COOKIE_LENGTH];
3390 char *envp[] = { udev_cookie, NULL };
3393 return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
3395 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
3396 DM_COOKIE_ENV_VAR_NAME, cookie);
3397 return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
3402 uint32_t dm_next_uevent_seq(struct mapped_device *md)
3404 return atomic_add_return(1, &md->uevent_seq);
3407 uint32_t dm_get_event_nr(struct mapped_device *md)
3409 return atomic_read(&md->event_nr);
3412 int dm_wait_event(struct mapped_device *md, int event_nr)
3414 return wait_event_interruptible(md->eventq,
3415 (event_nr != atomic_read(&md->event_nr)));
3418 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
3420 unsigned long flags;
3422 spin_lock_irqsave(&md->uevent_lock, flags);
3423 list_add(elist, &md->uevent_list);
3424 spin_unlock_irqrestore(&md->uevent_lock, flags);
3428 * The gendisk is only valid as long as you have a reference
3431 struct gendisk *dm_disk(struct mapped_device *md)
3435 EXPORT_SYMBOL_GPL(dm_disk);
3437 struct kobject *dm_kobject(struct mapped_device *md)
3439 return &md->kobj_holder.kobj;
3442 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
3444 struct mapped_device *md;
3446 md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
3448 if (test_bit(DMF_FREEING, &md->flags) ||
3456 int dm_suspended_md(struct mapped_device *md)
3458 return test_bit(DMF_SUSPENDED, &md->flags);
3461 int dm_suspended_internally_md(struct mapped_device *md)
3463 return test_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3466 int dm_test_deferred_remove_flag(struct mapped_device *md)
3468 return test_bit(DMF_DEFERRED_REMOVE, &md->flags);
3471 int dm_suspended(struct dm_target *ti)
3473 return dm_suspended_md(dm_table_get_md(ti->table));
3475 EXPORT_SYMBOL_GPL(dm_suspended);
3477 int dm_noflush_suspending(struct dm_target *ti)
3479 return __noflush_suspending(dm_table_get_md(ti->table));
3481 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
3483 struct dm_md_mempools *dm_alloc_md_mempools(struct mapped_device *md, unsigned type,
3484 unsigned integrity, unsigned per_bio_data_size)
3486 struct dm_md_mempools *pools = kzalloc(sizeof(*pools), GFP_KERNEL);
3487 struct kmem_cache *cachep = NULL;
3488 unsigned int pool_size = 0;
3489 unsigned int front_pad;
3494 type = filter_md_type(type, md);
3497 case DM_TYPE_BIO_BASED:
3499 pool_size = dm_get_reserved_bio_based_ios();
3500 front_pad = roundup(per_bio_data_size, __alignof__(struct dm_target_io)) + offsetof(struct dm_target_io, clone);
3502 case DM_TYPE_REQUEST_BASED:
3503 cachep = _rq_tio_cache;
3504 pool_size = dm_get_reserved_rq_based_ios();
3505 pools->rq_pool = mempool_create_slab_pool(pool_size, _rq_cache);
3506 if (!pools->rq_pool)
3508 /* fall through to setup remaining rq-based pools */
3509 case DM_TYPE_MQ_REQUEST_BASED:
3511 pool_size = dm_get_reserved_rq_based_ios();
3512 front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
3513 /* per_bio_data_size is not used. See __bind_mempools(). */
3514 WARN_ON(per_bio_data_size != 0);
3521 pools->io_pool = mempool_create_slab_pool(pool_size, cachep);
3522 if (!pools->io_pool)
3526 pools->bs = bioset_create_nobvec(pool_size, front_pad);
3530 if (integrity && bioset_integrity_create(pools->bs, pool_size))
3536 dm_free_md_mempools(pools);
3541 void dm_free_md_mempools(struct dm_md_mempools *pools)
3546 mempool_destroy(pools->io_pool);
3547 mempool_destroy(pools->rq_pool);
3550 bioset_free(pools->bs);
3555 static int dm_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
3558 struct mapped_device *md = bdev->bd_disk->private_data;
3559 const struct pr_ops *ops;
3560 struct dm_target *tgt;
3564 r = dm_get_live_table_for_ioctl(md, &tgt, &bdev, &mode, &srcu_idx);
3568 ops = bdev->bd_disk->fops->pr_ops;
3569 if (ops && ops->pr_register)
3570 r = ops->pr_register(bdev, old_key, new_key, flags);
3574 dm_put_live_table(md, srcu_idx);
3578 static int dm_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
3581 struct mapped_device *md = bdev->bd_disk->private_data;
3582 const struct pr_ops *ops;
3583 struct dm_target *tgt;
3587 r = dm_get_live_table_for_ioctl(md, &tgt, &bdev, &mode, &srcu_idx);
3591 ops = bdev->bd_disk->fops->pr_ops;
3592 if (ops && ops->pr_reserve)
3593 r = ops->pr_reserve(bdev, key, type, flags);
3597 dm_put_live_table(md, srcu_idx);
3601 static int dm_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
3603 struct mapped_device *md = bdev->bd_disk->private_data;
3604 const struct pr_ops *ops;
3605 struct dm_target *tgt;
3609 r = dm_get_live_table_for_ioctl(md, &tgt, &bdev, &mode, &srcu_idx);
3613 ops = bdev->bd_disk->fops->pr_ops;
3614 if (ops && ops->pr_release)
3615 r = ops->pr_release(bdev, key, type);
3619 dm_put_live_table(md, srcu_idx);
3623 static int dm_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
3624 enum pr_type type, bool abort)
3626 struct mapped_device *md = bdev->bd_disk->private_data;
3627 const struct pr_ops *ops;
3628 struct dm_target *tgt;
3632 r = dm_get_live_table_for_ioctl(md, &tgt, &bdev, &mode, &srcu_idx);
3636 ops = bdev->bd_disk->fops->pr_ops;
3637 if (ops && ops->pr_preempt)
3638 r = ops->pr_preempt(bdev, old_key, new_key, type, abort);
3642 dm_put_live_table(md, srcu_idx);
3646 static int dm_pr_clear(struct block_device *bdev, u64 key)
3648 struct mapped_device *md = bdev->bd_disk->private_data;
3649 const struct pr_ops *ops;
3650 struct dm_target *tgt;
3654 r = dm_get_live_table_for_ioctl(md, &tgt, &bdev, &mode, &srcu_idx);
3658 ops = bdev->bd_disk->fops->pr_ops;
3659 if (ops && ops->pr_clear)
3660 r = ops->pr_clear(bdev, key);
3664 dm_put_live_table(md, srcu_idx);
3668 static const struct pr_ops dm_pr_ops = {
3669 .pr_register = dm_pr_register,
3670 .pr_reserve = dm_pr_reserve,
3671 .pr_release = dm_pr_release,
3672 .pr_preempt = dm_pr_preempt,
3673 .pr_clear = dm_pr_clear,
3676 static const struct block_device_operations dm_blk_dops = {
3677 .open = dm_blk_open,
3678 .release = dm_blk_close,
3679 .ioctl = dm_blk_ioctl,
3680 .getgeo = dm_blk_getgeo,
3681 .pr_ops = &dm_pr_ops,
3682 .owner = THIS_MODULE
3688 module_init(dm_init);
3689 module_exit(dm_exit);
3691 module_param(major, uint, 0);
3692 MODULE_PARM_DESC(major, "The major number of the device mapper");
3694 module_param(reserved_bio_based_ios, uint, S_IRUGO | S_IWUSR);
3695 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
3697 module_param(reserved_rq_based_ios, uint, S_IRUGO | S_IWUSR);
3698 MODULE_PARM_DESC(reserved_rq_based_ios, "Reserved IOs in request-based mempools");
3700 module_param(use_blk_mq, bool, S_IRUGO | S_IWUSR);
3701 MODULE_PARM_DESC(use_blk_mq, "Use block multiqueue for request-based DM devices");
3703 MODULE_DESCRIPTION(DM_NAME " driver");
3704 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
3705 MODULE_LICENSE("GPL");