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 #define MINOR_ALLOCED ((void *)-1)
112 * Bits for the md->flags field.
114 #define DMF_BLOCK_IO_FOR_SUSPEND 0
115 #define DMF_SUSPENDED 1
117 #define DMF_FREEING 3
118 #define DMF_DELETING 4
119 #define DMF_NOFLUSH_SUSPENDING 5
120 #define DMF_DEFERRED_REMOVE 6
121 #define DMF_SUSPENDED_INTERNALLY 7
124 * A dummy definition to make RCU happy.
125 * struct dm_table should never be dereferenced in this file.
132 * Work processed by per-device workqueue.
134 struct mapped_device {
135 struct srcu_struct io_barrier;
136 struct mutex suspend_lock;
141 * The current mapping.
142 * Use dm_get_live_table{_fast} or take suspend_lock for
145 struct dm_table __rcu *map;
147 struct list_head table_devices;
148 struct mutex table_devices_lock;
152 struct request_queue *queue;
154 /* Protect queue and type against concurrent access. */
155 struct mutex type_lock;
157 struct target_type *immutable_target_type;
159 struct gendisk *disk;
165 * A list of ios that arrived while we were suspended.
168 wait_queue_head_t wait;
169 struct work_struct work;
170 struct bio_list deferred;
171 spinlock_t deferred_lock;
174 * Processing queue (flush)
176 struct workqueue_struct *wq;
179 * io objects are allocated from here.
190 wait_queue_head_t eventq;
192 struct list_head uevent_list;
193 spinlock_t uevent_lock; /* Protect access to uevent_list */
196 * freeze/thaw support require holding onto a super block
198 struct super_block *frozen_sb;
199 struct block_device *bdev;
201 /* forced geometry settings */
202 struct hd_geometry geometry;
204 /* kobject and completion */
205 struct dm_kobject_holder kobj_holder;
207 /* zero-length flush that will be cloned and submitted to targets */
208 struct bio flush_bio;
210 /* the number of internal suspends */
211 unsigned internal_suspend_count;
213 struct dm_stats stats;
215 struct kthread_worker kworker;
216 struct task_struct *kworker_task;
218 /* for request-based merge heuristic in dm_request_fn() */
219 unsigned seq_rq_merge_deadline_usecs;
221 sector_t last_rq_pos;
222 ktime_t last_rq_start_time;
224 /* for blk-mq request-based DM support */
225 struct blk_mq_tag_set tag_set;
229 #ifdef CONFIG_DM_MQ_DEFAULT
230 static bool use_blk_mq = true;
232 static bool use_blk_mq = false;
235 bool dm_use_blk_mq(struct mapped_device *md)
237 return md->use_blk_mq;
241 * For mempools pre-allocation at the table loading time.
243 struct dm_md_mempools {
249 struct table_device {
250 struct list_head list;
252 struct dm_dev dm_dev;
255 #define RESERVED_BIO_BASED_IOS 16
256 #define RESERVED_REQUEST_BASED_IOS 256
257 #define RESERVED_MAX_IOS 1024
258 static struct kmem_cache *_io_cache;
259 static struct kmem_cache *_rq_tio_cache;
260 static struct kmem_cache *_rq_cache;
263 * Bio-based DM's mempools' reserved IOs set by the user.
265 static unsigned reserved_bio_based_ios = RESERVED_BIO_BASED_IOS;
268 * Request-based DM's mempools' reserved IOs set by the user.
270 static unsigned reserved_rq_based_ios = RESERVED_REQUEST_BASED_IOS;
272 static unsigned __dm_get_module_param(unsigned *module_param,
273 unsigned def, unsigned max)
275 unsigned param = ACCESS_ONCE(*module_param);
276 unsigned modified_param = 0;
279 modified_param = def;
280 else if (param > max)
281 modified_param = max;
283 if (modified_param) {
284 (void)cmpxchg(module_param, param, modified_param);
285 param = modified_param;
291 unsigned dm_get_reserved_bio_based_ios(void)
293 return __dm_get_module_param(&reserved_bio_based_ios,
294 RESERVED_BIO_BASED_IOS, RESERVED_MAX_IOS);
296 EXPORT_SYMBOL_GPL(dm_get_reserved_bio_based_ios);
298 unsigned dm_get_reserved_rq_based_ios(void)
300 return __dm_get_module_param(&reserved_rq_based_ios,
301 RESERVED_REQUEST_BASED_IOS, RESERVED_MAX_IOS);
303 EXPORT_SYMBOL_GPL(dm_get_reserved_rq_based_ios);
305 static int __init local_init(void)
309 /* allocate a slab for the dm_ios */
310 _io_cache = KMEM_CACHE(dm_io, 0);
314 _rq_tio_cache = KMEM_CACHE(dm_rq_target_io, 0);
316 goto out_free_io_cache;
318 _rq_cache = kmem_cache_create("dm_clone_request", sizeof(struct request),
319 __alignof__(struct request), 0, NULL);
321 goto out_free_rq_tio_cache;
323 r = dm_uevent_init();
325 goto out_free_rq_cache;
327 deferred_remove_workqueue = alloc_workqueue("kdmremove", WQ_UNBOUND, 1);
328 if (!deferred_remove_workqueue) {
330 goto out_uevent_exit;
334 r = register_blkdev(_major, _name);
336 goto out_free_workqueue;
344 destroy_workqueue(deferred_remove_workqueue);
348 kmem_cache_destroy(_rq_cache);
349 out_free_rq_tio_cache:
350 kmem_cache_destroy(_rq_tio_cache);
352 kmem_cache_destroy(_io_cache);
357 static void local_exit(void)
359 flush_scheduled_work();
360 destroy_workqueue(deferred_remove_workqueue);
362 kmem_cache_destroy(_rq_cache);
363 kmem_cache_destroy(_rq_tio_cache);
364 kmem_cache_destroy(_io_cache);
365 unregister_blkdev(_major, _name);
370 DMINFO("cleaned up");
373 static int (*_inits[])(void) __initdata = {
384 static void (*_exits[])(void) = {
395 static int __init dm_init(void)
397 const int count = ARRAY_SIZE(_inits);
401 for (i = 0; i < count; i++) {
416 static void __exit dm_exit(void)
418 int i = ARRAY_SIZE(_exits);
424 * Should be empty by this point.
426 idr_destroy(&_minor_idr);
430 * Block device functions
432 int dm_deleting_md(struct mapped_device *md)
434 return test_bit(DMF_DELETING, &md->flags);
437 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
439 struct mapped_device *md;
441 spin_lock(&_minor_lock);
443 md = bdev->bd_disk->private_data;
447 if (test_bit(DMF_FREEING, &md->flags) ||
448 dm_deleting_md(md)) {
454 atomic_inc(&md->open_count);
456 spin_unlock(&_minor_lock);
458 return md ? 0 : -ENXIO;
461 static void dm_blk_close(struct gendisk *disk, fmode_t mode)
463 struct mapped_device *md;
465 spin_lock(&_minor_lock);
467 md = disk->private_data;
471 if (atomic_dec_and_test(&md->open_count) &&
472 (test_bit(DMF_DEFERRED_REMOVE, &md->flags)))
473 queue_work(deferred_remove_workqueue, &deferred_remove_work);
477 spin_unlock(&_minor_lock);
480 int dm_open_count(struct mapped_device *md)
482 return atomic_read(&md->open_count);
486 * Guarantees nothing is using the device before it's deleted.
488 int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
492 spin_lock(&_minor_lock);
494 if (dm_open_count(md)) {
497 set_bit(DMF_DEFERRED_REMOVE, &md->flags);
498 } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
501 set_bit(DMF_DELETING, &md->flags);
503 spin_unlock(&_minor_lock);
508 int dm_cancel_deferred_remove(struct mapped_device *md)
512 spin_lock(&_minor_lock);
514 if (test_bit(DMF_DELETING, &md->flags))
517 clear_bit(DMF_DEFERRED_REMOVE, &md->flags);
519 spin_unlock(&_minor_lock);
524 static void do_deferred_remove(struct work_struct *w)
526 dm_deferred_remove();
529 sector_t dm_get_size(struct mapped_device *md)
531 return get_capacity(md->disk);
534 struct request_queue *dm_get_md_queue(struct mapped_device *md)
539 struct dm_stats *dm_get_stats(struct mapped_device *md)
544 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
546 struct mapped_device *md = bdev->bd_disk->private_data;
548 return dm_get_geometry(md, geo);
551 static int dm_grab_bdev_for_ioctl(struct mapped_device *md,
552 struct block_device **bdev,
555 struct dm_target *tgt;
556 struct dm_table *map;
561 map = dm_get_live_table(md, &srcu_idx);
562 if (!map || !dm_table_get_size(map))
565 /* We only support devices that have a single target */
566 if (dm_table_get_num_targets(map) != 1)
569 tgt = dm_table_get_target(map, 0);
570 if (!tgt->type->prepare_ioctl)
573 if (dm_suspended_md(md)) {
578 r = tgt->type->prepare_ioctl(tgt, bdev, mode);
583 dm_put_live_table(md, srcu_idx);
587 dm_put_live_table(md, srcu_idx);
588 if (r == -ENOTCONN && !fatal_signal_pending(current)) {
595 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
596 unsigned int cmd, unsigned long arg)
598 struct mapped_device *md = bdev->bd_disk->private_data;
601 r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
607 * Target determined this ioctl is being issued against
608 * a logical partition of the parent bdev; so extra
609 * validation is needed.
611 r = scsi_verify_blk_ioctl(NULL, cmd);
616 r = __blkdev_driver_ioctl(bdev, mode, cmd, arg);
622 static struct dm_io *alloc_io(struct mapped_device *md)
624 return mempool_alloc(md->io_pool, GFP_NOIO);
627 static void free_io(struct mapped_device *md, struct dm_io *io)
629 mempool_free(io, md->io_pool);
632 static void free_tio(struct mapped_device *md, struct dm_target_io *tio)
634 bio_put(&tio->clone);
637 static struct dm_rq_target_io *alloc_rq_tio(struct mapped_device *md,
640 return mempool_alloc(md->io_pool, gfp_mask);
643 static void free_rq_tio(struct dm_rq_target_io *tio)
645 mempool_free(tio, tio->md->io_pool);
648 static struct request *alloc_clone_request(struct mapped_device *md,
651 return mempool_alloc(md->rq_pool, gfp_mask);
654 static void free_clone_request(struct mapped_device *md, struct request *rq)
656 mempool_free(rq, md->rq_pool);
659 static int md_in_flight(struct mapped_device *md)
661 return atomic_read(&md->pending[READ]) +
662 atomic_read(&md->pending[WRITE]);
665 static void start_io_acct(struct dm_io *io)
667 struct mapped_device *md = io->md;
668 struct bio *bio = io->bio;
670 int rw = bio_data_dir(bio);
672 io->start_time = jiffies;
674 cpu = part_stat_lock();
675 part_round_stats(cpu, &dm_disk(md)->part0);
677 atomic_set(&dm_disk(md)->part0.in_flight[rw],
678 atomic_inc_return(&md->pending[rw]));
680 if (unlikely(dm_stats_used(&md->stats)))
681 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_iter.bi_sector,
682 bio_sectors(bio), false, 0, &io->stats_aux);
685 static void end_io_acct(struct dm_io *io)
687 struct mapped_device *md = io->md;
688 struct bio *bio = io->bio;
689 unsigned long duration = jiffies - io->start_time;
691 int rw = bio_data_dir(bio);
693 generic_end_io_acct(rw, &dm_disk(md)->part0, io->start_time);
695 if (unlikely(dm_stats_used(&md->stats)))
696 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_iter.bi_sector,
697 bio_sectors(bio), true, duration, &io->stats_aux);
700 * After this is decremented the bio must not be touched if it is
703 pending = atomic_dec_return(&md->pending[rw]);
704 atomic_set(&dm_disk(md)->part0.in_flight[rw], pending);
705 pending += atomic_read(&md->pending[rw^0x1]);
707 /* nudge anyone waiting on suspend queue */
713 * Add the bio to the list of deferred io.
715 static void queue_io(struct mapped_device *md, struct bio *bio)
719 spin_lock_irqsave(&md->deferred_lock, flags);
720 bio_list_add(&md->deferred, bio);
721 spin_unlock_irqrestore(&md->deferred_lock, flags);
722 queue_work(md->wq, &md->work);
726 * Everyone (including functions in this file), should use this
727 * function to access the md->map field, and make sure they call
728 * dm_put_live_table() when finished.
730 struct dm_table *dm_get_live_table(struct mapped_device *md, int *srcu_idx) __acquires(md->io_barrier)
732 *srcu_idx = srcu_read_lock(&md->io_barrier);
734 return srcu_dereference(md->map, &md->io_barrier);
737 void dm_put_live_table(struct mapped_device *md, int srcu_idx) __releases(md->io_barrier)
739 srcu_read_unlock(&md->io_barrier, srcu_idx);
742 void dm_sync_table(struct mapped_device *md)
744 synchronize_srcu(&md->io_barrier);
745 synchronize_rcu_expedited();
749 * A fast alternative to dm_get_live_table/dm_put_live_table.
750 * The caller must not block between these two functions.
752 static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
755 return rcu_dereference(md->map);
758 static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
764 * Open a table device so we can use it as a map destination.
766 static int open_table_device(struct table_device *td, dev_t dev,
767 struct mapped_device *md)
769 static char *_claim_ptr = "I belong to device-mapper";
770 struct block_device *bdev;
774 BUG_ON(td->dm_dev.bdev);
776 bdev = blkdev_get_by_dev(dev, td->dm_dev.mode | FMODE_EXCL, _claim_ptr);
778 return PTR_ERR(bdev);
780 r = bd_link_disk_holder(bdev, dm_disk(md));
782 blkdev_put(bdev, td->dm_dev.mode | FMODE_EXCL);
786 td->dm_dev.bdev = bdev;
791 * Close a table device that we've been using.
793 static void close_table_device(struct table_device *td, struct mapped_device *md)
795 if (!td->dm_dev.bdev)
798 bd_unlink_disk_holder(td->dm_dev.bdev, dm_disk(md));
799 blkdev_put(td->dm_dev.bdev, td->dm_dev.mode | FMODE_EXCL);
800 td->dm_dev.bdev = NULL;
803 static struct table_device *find_table_device(struct list_head *l, dev_t dev,
805 struct table_device *td;
807 list_for_each_entry(td, l, list)
808 if (td->dm_dev.bdev->bd_dev == dev && td->dm_dev.mode == mode)
814 int dm_get_table_device(struct mapped_device *md, dev_t dev, fmode_t mode,
815 struct dm_dev **result) {
817 struct table_device *td;
819 mutex_lock(&md->table_devices_lock);
820 td = find_table_device(&md->table_devices, dev, mode);
822 td = kmalloc(sizeof(*td), GFP_KERNEL);
824 mutex_unlock(&md->table_devices_lock);
828 td->dm_dev.mode = mode;
829 td->dm_dev.bdev = NULL;
831 if ((r = open_table_device(td, dev, md))) {
832 mutex_unlock(&md->table_devices_lock);
837 format_dev_t(td->dm_dev.name, dev);
839 atomic_set(&td->count, 0);
840 list_add(&td->list, &md->table_devices);
842 atomic_inc(&td->count);
843 mutex_unlock(&md->table_devices_lock);
845 *result = &td->dm_dev;
848 EXPORT_SYMBOL_GPL(dm_get_table_device);
850 void dm_put_table_device(struct mapped_device *md, struct dm_dev *d)
852 struct table_device *td = container_of(d, struct table_device, dm_dev);
854 mutex_lock(&md->table_devices_lock);
855 if (atomic_dec_and_test(&td->count)) {
856 close_table_device(td, md);
860 mutex_unlock(&md->table_devices_lock);
862 EXPORT_SYMBOL(dm_put_table_device);
864 static void free_table_devices(struct list_head *devices)
866 struct list_head *tmp, *next;
868 list_for_each_safe(tmp, next, devices) {
869 struct table_device *td = list_entry(tmp, struct table_device, list);
871 DMWARN("dm_destroy: %s still exists with %d references",
872 td->dm_dev.name, atomic_read(&td->count));
878 * Get the geometry associated with a dm device
880 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
888 * Set the geometry of a device.
890 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
892 sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
894 if (geo->start > sz) {
895 DMWARN("Start sector is beyond the geometry limits.");
904 /*-----------------------------------------------------------------
906 * A more elegant soln is in the works that uses the queue
907 * merge fn, unfortunately there are a couple of changes to
908 * the block layer that I want to make for this. So in the
909 * interests of getting something for people to use I give
910 * you this clearly demarcated crap.
911 *---------------------------------------------------------------*/
913 static int __noflush_suspending(struct mapped_device *md)
915 return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
919 * Decrements the number of outstanding ios that a bio has been
920 * cloned into, completing the original io if necc.
922 static void dec_pending(struct dm_io *io, int error)
927 struct mapped_device *md = io->md;
929 /* Push-back supersedes any I/O errors */
930 if (unlikely(error)) {
931 spin_lock_irqsave(&io->endio_lock, flags);
932 if (!(io->error > 0 && __noflush_suspending(md)))
934 spin_unlock_irqrestore(&io->endio_lock, flags);
937 if (atomic_dec_and_test(&io->io_count)) {
938 if (io->error == DM_ENDIO_REQUEUE) {
940 * Target requested pushing back the I/O.
942 spin_lock_irqsave(&md->deferred_lock, flags);
943 if (__noflush_suspending(md))
944 bio_list_add_head(&md->deferred, io->bio);
946 /* noflush suspend was interrupted. */
948 spin_unlock_irqrestore(&md->deferred_lock, flags);
951 io_error = io->error;
956 if (io_error == DM_ENDIO_REQUEUE)
959 if ((bio->bi_rw & REQ_FLUSH) && bio->bi_iter.bi_size) {
961 * Preflush done for flush with data, reissue
964 bio->bi_rw &= ~REQ_FLUSH;
967 /* done with normal IO or empty flush */
968 trace_block_bio_complete(md->queue, bio, io_error);
969 bio->bi_error = io_error;
975 static void disable_write_same(struct mapped_device *md)
977 struct queue_limits *limits = dm_get_queue_limits(md);
979 /* device doesn't really support WRITE SAME, disable it */
980 limits->max_write_same_sectors = 0;
983 static void clone_endio(struct bio *bio)
985 int error = bio->bi_error;
987 struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
988 struct dm_io *io = tio->io;
989 struct mapped_device *md = tio->io->md;
990 dm_endio_fn endio = tio->ti->type->end_io;
993 r = endio(tio->ti, bio, error);
994 if (r < 0 || r == DM_ENDIO_REQUEUE)
996 * error and requeue request are handled
1000 else if (r == DM_ENDIO_INCOMPLETE)
1001 /* The target will handle the io */
1004 DMWARN("unimplemented target endio return value: %d", r);
1009 if (unlikely(r == -EREMOTEIO && (bio->bi_rw & REQ_WRITE_SAME) &&
1010 !bdev_get_queue(bio->bi_bdev)->limits.max_write_same_sectors))
1011 disable_write_same(md);
1014 dec_pending(io, error);
1018 * Partial completion handling for request-based dm
1020 static void end_clone_bio(struct bio *clone)
1022 struct dm_rq_clone_bio_info *info =
1023 container_of(clone, struct dm_rq_clone_bio_info, clone);
1024 struct dm_rq_target_io *tio = info->tio;
1025 struct bio *bio = info->orig;
1026 unsigned int nr_bytes = info->orig->bi_iter.bi_size;
1027 int error = clone->bi_error;
1033 * An error has already been detected on the request.
1034 * Once error occurred, just let clone->end_io() handle
1040 * Don't notice the error to the upper layer yet.
1041 * The error handling decision is made by the target driver,
1042 * when the request is completed.
1049 * I/O for the bio successfully completed.
1050 * Notice the data completion to the upper layer.
1054 * bios are processed from the head of the list.
1055 * So the completing bio should always be rq->bio.
1056 * If it's not, something wrong is happening.
1058 if (tio->orig->bio != bio)
1059 DMERR("bio completion is going in the middle of the request");
1062 * Update the original request.
1063 * Do not use blk_end_request() here, because it may complete
1064 * the original request before the clone, and break the ordering.
1066 blk_update_request(tio->orig, 0, nr_bytes);
1069 static struct dm_rq_target_io *tio_from_request(struct request *rq)
1071 return (rq->q->mq_ops ? blk_mq_rq_to_pdu(rq) : rq->special);
1074 static void rq_end_stats(struct mapped_device *md, struct request *orig)
1076 if (unlikely(dm_stats_used(&md->stats))) {
1077 struct dm_rq_target_io *tio = tio_from_request(orig);
1078 tio->duration_jiffies = jiffies - tio->duration_jiffies;
1079 dm_stats_account_io(&md->stats, orig->cmd_flags, blk_rq_pos(orig),
1080 tio->n_sectors, true, tio->duration_jiffies,
1086 * Don't touch any member of the md after calling this function because
1087 * the md may be freed in dm_put() at the end of this function.
1088 * Or do dm_get() before calling this function and dm_put() later.
1090 static void rq_completed(struct mapped_device *md, int rw, bool run_queue)
1092 atomic_dec(&md->pending[rw]);
1094 /* nudge anyone waiting on suspend queue */
1095 if (!md_in_flight(md))
1099 * Run this off this callpath, as drivers could invoke end_io while
1100 * inside their request_fn (and holding the queue lock). Calling
1101 * back into ->request_fn() could deadlock attempting to grab the
1104 if (!md->queue->mq_ops && run_queue)
1105 blk_run_queue_async(md->queue);
1108 * dm_put() must be at the end of this function. See the comment above
1113 static void free_rq_clone(struct request *clone)
1115 struct dm_rq_target_io *tio = clone->end_io_data;
1116 struct mapped_device *md = tio->md;
1118 blk_rq_unprep_clone(clone);
1120 if (md->type == DM_TYPE_MQ_REQUEST_BASED)
1121 /* stacked on blk-mq queue(s) */
1122 tio->ti->type->release_clone_rq(clone);
1123 else if (!md->queue->mq_ops)
1124 /* request_fn queue stacked on request_fn queue(s) */
1125 free_clone_request(md, clone);
1127 * NOTE: for the blk-mq queue stacked on request_fn queue(s) case:
1128 * no need to call free_clone_request() because we leverage blk-mq by
1129 * allocating the clone at the end of the blk-mq pdu (see: clone_rq)
1132 if (!md->queue->mq_ops)
1137 * Complete the clone and the original request.
1138 * Must be called without clone's queue lock held,
1139 * see end_clone_request() for more details.
1141 static void dm_end_request(struct request *clone, int error)
1143 int rw = rq_data_dir(clone);
1144 struct dm_rq_target_io *tio = clone->end_io_data;
1145 struct mapped_device *md = tio->md;
1146 struct request *rq = tio->orig;
1148 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
1149 rq->errors = clone->errors;
1150 rq->resid_len = clone->resid_len;
1154 * We are using the sense buffer of the original
1156 * So setting the length of the sense data is enough.
1158 rq->sense_len = clone->sense_len;
1161 free_rq_clone(clone);
1162 rq_end_stats(md, rq);
1164 blk_end_request_all(rq, error);
1166 blk_mq_end_request(rq, error);
1167 rq_completed(md, rw, true);
1170 static void dm_unprep_request(struct request *rq)
1172 struct dm_rq_target_io *tio = tio_from_request(rq);
1173 struct request *clone = tio->clone;
1175 if (!rq->q->mq_ops) {
1177 rq->cmd_flags &= ~REQ_DONTPREP;
1181 free_rq_clone(clone);
1182 else if (!tio->md->queue->mq_ops)
1187 * Requeue the original request of a clone.
1189 static void old_requeue_request(struct request *rq)
1191 struct request_queue *q = rq->q;
1192 unsigned long flags;
1194 spin_lock_irqsave(q->queue_lock, flags);
1195 blk_requeue_request(q, rq);
1196 blk_run_queue_async(q);
1197 spin_unlock_irqrestore(q->queue_lock, flags);
1200 static void dm_requeue_original_request(struct mapped_device *md,
1203 int rw = rq_data_dir(rq);
1205 dm_unprep_request(rq);
1207 rq_end_stats(md, rq);
1209 old_requeue_request(rq);
1211 blk_mq_requeue_request(rq);
1212 blk_mq_kick_requeue_list(rq->q);
1215 rq_completed(md, rw, false);
1218 static void old_stop_queue(struct request_queue *q)
1220 unsigned long flags;
1222 if (blk_queue_stopped(q))
1225 spin_lock_irqsave(q->queue_lock, flags);
1227 spin_unlock_irqrestore(q->queue_lock, flags);
1230 static void stop_queue(struct request_queue *q)
1235 blk_mq_stop_hw_queues(q);
1238 static void old_start_queue(struct request_queue *q)
1240 unsigned long flags;
1242 spin_lock_irqsave(q->queue_lock, flags);
1243 if (blk_queue_stopped(q))
1245 spin_unlock_irqrestore(q->queue_lock, flags);
1248 static void start_queue(struct request_queue *q)
1253 blk_mq_start_stopped_hw_queues(q, true);
1256 static void dm_done(struct request *clone, int error, bool mapped)
1259 struct dm_rq_target_io *tio = clone->end_io_data;
1260 dm_request_endio_fn rq_end_io = NULL;
1263 rq_end_io = tio->ti->type->rq_end_io;
1265 if (mapped && rq_end_io)
1266 r = rq_end_io(tio->ti, clone, error, &tio->info);
1269 if (unlikely(r == -EREMOTEIO && (clone->cmd_flags & REQ_WRITE_SAME) &&
1270 !clone->q->limits.max_write_same_sectors))
1271 disable_write_same(tio->md);
1274 /* The target wants to complete the I/O */
1275 dm_end_request(clone, r);
1276 else if (r == DM_ENDIO_INCOMPLETE)
1277 /* The target will handle the I/O */
1279 else if (r == DM_ENDIO_REQUEUE)
1280 /* The target wants to requeue the I/O */
1281 dm_requeue_original_request(tio->md, tio->orig);
1283 DMWARN("unimplemented target endio return value: %d", r);
1289 * Request completion handler for request-based dm
1291 static void dm_softirq_done(struct request *rq)
1294 struct dm_rq_target_io *tio = tio_from_request(rq);
1295 struct request *clone = tio->clone;
1299 rq_end_stats(tio->md, rq);
1300 rw = rq_data_dir(rq);
1301 if (!rq->q->mq_ops) {
1302 blk_end_request_all(rq, tio->error);
1303 rq_completed(tio->md, rw, false);
1306 blk_mq_end_request(rq, tio->error);
1307 rq_completed(tio->md, rw, false);
1312 if (rq->cmd_flags & REQ_FAILED)
1315 dm_done(clone, tio->error, mapped);
1319 * Complete the clone and the original request with the error status
1320 * through softirq context.
1322 static void dm_complete_request(struct request *rq, int error)
1324 struct dm_rq_target_io *tio = tio_from_request(rq);
1328 blk_complete_request(rq);
1330 blk_mq_complete_request(rq, error);
1334 * Complete the not-mapped clone and the original request with the error status
1335 * through softirq context.
1336 * Target's rq_end_io() function isn't called.
1337 * This may be used when the target's map_rq() or clone_and_map_rq() functions fail.
1339 static void dm_kill_unmapped_request(struct request *rq, int error)
1341 rq->cmd_flags |= REQ_FAILED;
1342 dm_complete_request(rq, error);
1346 * Called with the clone's queue lock held (for non-blk-mq)
1348 static void end_clone_request(struct request *clone, int error)
1350 struct dm_rq_target_io *tio = clone->end_io_data;
1352 if (!clone->q->mq_ops) {
1354 * For just cleaning up the information of the queue in which
1355 * the clone was dispatched.
1356 * The clone is *NOT* freed actually here because it is alloced
1357 * from dm own mempool (REQ_ALLOCED isn't set).
1359 __blk_put_request(clone->q, clone);
1363 * Actual request completion is done in a softirq context which doesn't
1364 * hold the clone's queue lock. Otherwise, deadlock could occur because:
1365 * - another request may be submitted by the upper level driver
1366 * of the stacking during the completion
1367 * - the submission which requires queue lock may be done
1368 * against this clone's queue
1370 dm_complete_request(tio->orig, error);
1374 * Return maximum size of I/O possible at the supplied sector up to the current
1377 static sector_t max_io_len_target_boundary(sector_t sector, struct dm_target *ti)
1379 sector_t target_offset = dm_target_offset(ti, sector);
1381 return ti->len - target_offset;
1384 static sector_t max_io_len(sector_t sector, struct dm_target *ti)
1386 sector_t len = max_io_len_target_boundary(sector, ti);
1387 sector_t offset, max_len;
1390 * Does the target need to split even further?
1392 if (ti->max_io_len) {
1393 offset = dm_target_offset(ti, sector);
1394 if (unlikely(ti->max_io_len & (ti->max_io_len - 1)))
1395 max_len = sector_div(offset, ti->max_io_len);
1397 max_len = offset & (ti->max_io_len - 1);
1398 max_len = ti->max_io_len - max_len;
1407 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
1409 if (len > UINT_MAX) {
1410 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
1411 (unsigned long long)len, UINT_MAX);
1412 ti->error = "Maximum size of target IO is too large";
1416 ti->max_io_len = (uint32_t) len;
1420 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
1423 * A target may call dm_accept_partial_bio only from the map routine. It is
1424 * allowed for all bio types except REQ_FLUSH.
1426 * dm_accept_partial_bio informs the dm that the target only wants to process
1427 * additional n_sectors sectors of the bio and the rest of the data should be
1428 * sent in a next bio.
1430 * A diagram that explains the arithmetics:
1431 * +--------------------+---------------+-------+
1433 * +--------------------+---------------+-------+
1435 * <-------------- *tio->len_ptr --------------->
1436 * <------- bi_size ------->
1439 * Region 1 was already iterated over with bio_advance or similar function.
1440 * (it may be empty if the target doesn't use bio_advance)
1441 * Region 2 is the remaining bio size that the target wants to process.
1442 * (it may be empty if region 1 is non-empty, although there is no reason
1444 * The target requires that region 3 is to be sent in the next bio.
1446 * If the target wants to receive multiple copies of the bio (via num_*bios, etc),
1447 * the partially processed part (the sum of regions 1+2) must be the same for all
1448 * copies of the bio.
1450 void dm_accept_partial_bio(struct bio *bio, unsigned n_sectors)
1452 struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
1453 unsigned bi_size = bio->bi_iter.bi_size >> SECTOR_SHIFT;
1454 BUG_ON(bio->bi_rw & REQ_FLUSH);
1455 BUG_ON(bi_size > *tio->len_ptr);
1456 BUG_ON(n_sectors > bi_size);
1457 *tio->len_ptr -= bi_size - n_sectors;
1458 bio->bi_iter.bi_size = n_sectors << SECTOR_SHIFT;
1460 EXPORT_SYMBOL_GPL(dm_accept_partial_bio);
1462 static void __map_bio(struct dm_target_io *tio)
1466 struct mapped_device *md;
1467 struct bio *clone = &tio->clone;
1468 struct dm_target *ti = tio->ti;
1470 clone->bi_end_io = clone_endio;
1473 * Map the clone. If r == 0 we don't need to do
1474 * anything, the target has assumed ownership of
1477 atomic_inc(&tio->io->io_count);
1478 sector = clone->bi_iter.bi_sector;
1479 r = ti->type->map(ti, clone);
1480 if (r == DM_MAPIO_REMAPPED) {
1481 /* the bio has been remapped so dispatch it */
1483 trace_block_bio_remap(bdev_get_queue(clone->bi_bdev), clone,
1484 tio->io->bio->bi_bdev->bd_dev, sector);
1486 generic_make_request(clone);
1487 } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1488 /* error the io and bail out, or requeue it if needed */
1490 dec_pending(tio->io, r);
1492 } else if (r != DM_MAPIO_SUBMITTED) {
1493 DMWARN("unimplemented target map return value: %d", r);
1499 struct mapped_device *md;
1500 struct dm_table *map;
1504 unsigned sector_count;
1507 static void bio_setup_sector(struct bio *bio, sector_t sector, unsigned len)
1509 bio->bi_iter.bi_sector = sector;
1510 bio->bi_iter.bi_size = to_bytes(len);
1514 * Creates a bio that consists of range of complete bvecs.
1516 static void clone_bio(struct dm_target_io *tio, struct bio *bio,
1517 sector_t sector, unsigned len)
1519 struct bio *clone = &tio->clone;
1521 __bio_clone_fast(clone, bio);
1523 if (bio_integrity(bio))
1524 bio_integrity_clone(clone, bio, GFP_NOIO);
1526 bio_advance(clone, to_bytes(sector - clone->bi_iter.bi_sector));
1527 clone->bi_iter.bi_size = to_bytes(len);
1529 if (bio_integrity(bio))
1530 bio_integrity_trim(clone, 0, len);
1533 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1534 struct dm_target *ti,
1535 unsigned target_bio_nr)
1537 struct dm_target_io *tio;
1540 clone = bio_alloc_bioset(GFP_NOIO, 0, ci->md->bs);
1541 tio = container_of(clone, struct dm_target_io, clone);
1545 tio->target_bio_nr = target_bio_nr;
1550 static void __clone_and_map_simple_bio(struct clone_info *ci,
1551 struct dm_target *ti,
1552 unsigned target_bio_nr, unsigned *len)
1554 struct dm_target_io *tio = alloc_tio(ci, ti, target_bio_nr);
1555 struct bio *clone = &tio->clone;
1559 __bio_clone_fast(clone, ci->bio);
1561 bio_setup_sector(clone, ci->sector, *len);
1566 static void __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1567 unsigned num_bios, unsigned *len)
1569 unsigned target_bio_nr;
1571 for (target_bio_nr = 0; target_bio_nr < num_bios; target_bio_nr++)
1572 __clone_and_map_simple_bio(ci, ti, target_bio_nr, len);
1575 static int __send_empty_flush(struct clone_info *ci)
1577 unsigned target_nr = 0;
1578 struct dm_target *ti;
1580 BUG_ON(bio_has_data(ci->bio));
1581 while ((ti = dm_table_get_target(ci->map, target_nr++)))
1582 __send_duplicate_bios(ci, ti, ti->num_flush_bios, NULL);
1587 static void __clone_and_map_data_bio(struct clone_info *ci, struct dm_target *ti,
1588 sector_t sector, unsigned *len)
1590 struct bio *bio = ci->bio;
1591 struct dm_target_io *tio;
1592 unsigned target_bio_nr;
1593 unsigned num_target_bios = 1;
1596 * Does the target want to receive duplicate copies of the bio?
1598 if (bio_data_dir(bio) == WRITE && ti->num_write_bios)
1599 num_target_bios = ti->num_write_bios(ti, bio);
1601 for (target_bio_nr = 0; target_bio_nr < num_target_bios; target_bio_nr++) {
1602 tio = alloc_tio(ci, ti, target_bio_nr);
1604 clone_bio(tio, bio, sector, *len);
1609 typedef unsigned (*get_num_bios_fn)(struct dm_target *ti);
1611 static unsigned get_num_discard_bios(struct dm_target *ti)
1613 return ti->num_discard_bios;
1616 static unsigned get_num_write_same_bios(struct dm_target *ti)
1618 return ti->num_write_same_bios;
1621 typedef bool (*is_split_required_fn)(struct dm_target *ti);
1623 static bool is_split_required_for_discard(struct dm_target *ti)
1625 return ti->split_discard_bios;
1628 static int __send_changing_extent_only(struct clone_info *ci,
1629 get_num_bios_fn get_num_bios,
1630 is_split_required_fn is_split_required)
1632 struct dm_target *ti;
1637 ti = dm_table_find_target(ci->map, ci->sector);
1638 if (!dm_target_is_valid(ti))
1642 * Even though the device advertised support for this type of
1643 * request, that does not mean every target supports it, and
1644 * reconfiguration might also have changed that since the
1645 * check was performed.
1647 num_bios = get_num_bios ? get_num_bios(ti) : 0;
1651 if (is_split_required && !is_split_required(ti))
1652 len = min((sector_t)ci->sector_count, max_io_len_target_boundary(ci->sector, ti));
1654 len = min((sector_t)ci->sector_count, max_io_len(ci->sector, ti));
1656 __send_duplicate_bios(ci, ti, num_bios, &len);
1659 } while (ci->sector_count -= len);
1664 static int __send_discard(struct clone_info *ci)
1666 return __send_changing_extent_only(ci, get_num_discard_bios,
1667 is_split_required_for_discard);
1670 static int __send_write_same(struct clone_info *ci)
1672 return __send_changing_extent_only(ci, get_num_write_same_bios, NULL);
1676 * Select the correct strategy for processing a non-flush bio.
1678 static int __split_and_process_non_flush(struct clone_info *ci)
1680 struct bio *bio = ci->bio;
1681 struct dm_target *ti;
1684 if (unlikely(bio->bi_rw & REQ_DISCARD))
1685 return __send_discard(ci);
1686 else if (unlikely(bio->bi_rw & REQ_WRITE_SAME))
1687 return __send_write_same(ci);
1689 ti = dm_table_find_target(ci->map, ci->sector);
1690 if (!dm_target_is_valid(ti))
1693 len = min_t(sector_t, max_io_len(ci->sector, ti), ci->sector_count);
1695 __clone_and_map_data_bio(ci, ti, ci->sector, &len);
1698 ci->sector_count -= len;
1704 * Entry point to split a bio into clones and submit them to the targets.
1706 static void __split_and_process_bio(struct mapped_device *md,
1707 struct dm_table *map, struct bio *bio)
1709 struct clone_info ci;
1712 if (unlikely(!map)) {
1719 ci.io = alloc_io(md);
1721 atomic_set(&ci.io->io_count, 1);
1724 spin_lock_init(&ci.io->endio_lock);
1725 ci.sector = bio->bi_iter.bi_sector;
1727 start_io_acct(ci.io);
1729 if (bio->bi_rw & REQ_FLUSH) {
1730 ci.bio = &ci.md->flush_bio;
1731 ci.sector_count = 0;
1732 error = __send_empty_flush(&ci);
1733 /* dec_pending submits any data associated with flush */
1736 ci.sector_count = bio_sectors(bio);
1737 while (ci.sector_count && !error)
1738 error = __split_and_process_non_flush(&ci);
1741 /* drop the extra reference count */
1742 dec_pending(ci.io, error);
1744 /*-----------------------------------------------------------------
1746 *---------------------------------------------------------------*/
1749 * The request function that just remaps the bio built up by
1752 static blk_qc_t dm_make_request(struct request_queue *q, struct bio *bio)
1754 int rw = bio_data_dir(bio);
1755 struct mapped_device *md = q->queuedata;
1757 struct dm_table *map;
1759 map = dm_get_live_table(md, &srcu_idx);
1761 generic_start_io_acct(rw, bio_sectors(bio), &dm_disk(md)->part0);
1763 /* if we're suspended, we have to queue this io for later */
1764 if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
1765 dm_put_live_table(md, srcu_idx);
1767 if (bio_rw(bio) != READA)
1771 return BLK_QC_T_NONE;
1774 __split_and_process_bio(md, map, bio);
1775 dm_put_live_table(md, srcu_idx);
1776 return BLK_QC_T_NONE;
1779 int dm_request_based(struct mapped_device *md)
1781 return blk_queue_stackable(md->queue);
1784 static void dm_dispatch_clone_request(struct request *clone, struct request *rq)
1788 if (blk_queue_io_stat(clone->q))
1789 clone->cmd_flags |= REQ_IO_STAT;
1791 clone->start_time = jiffies;
1792 r = blk_insert_cloned_request(clone->q, clone);
1794 /* must complete clone in terms of original request */
1795 dm_complete_request(rq, r);
1798 static int dm_rq_bio_constructor(struct bio *bio, struct bio *bio_orig,
1801 struct dm_rq_target_io *tio = data;
1802 struct dm_rq_clone_bio_info *info =
1803 container_of(bio, struct dm_rq_clone_bio_info, clone);
1805 info->orig = bio_orig;
1807 bio->bi_end_io = end_clone_bio;
1812 static int setup_clone(struct request *clone, struct request *rq,
1813 struct dm_rq_target_io *tio, gfp_t gfp_mask)
1817 r = blk_rq_prep_clone(clone, rq, tio->md->bs, gfp_mask,
1818 dm_rq_bio_constructor, tio);
1822 clone->cmd = rq->cmd;
1823 clone->cmd_len = rq->cmd_len;
1824 clone->sense = rq->sense;
1825 clone->end_io = end_clone_request;
1826 clone->end_io_data = tio;
1833 static struct request *clone_rq(struct request *rq, struct mapped_device *md,
1834 struct dm_rq_target_io *tio, gfp_t gfp_mask)
1837 * Do not allocate a clone if tio->clone was already set
1838 * (see: dm_mq_queue_rq).
1840 bool alloc_clone = !tio->clone;
1841 struct request *clone;
1844 clone = alloc_clone_request(md, gfp_mask);
1850 blk_rq_init(NULL, clone);
1851 if (setup_clone(clone, rq, tio, gfp_mask)) {
1854 free_clone_request(md, clone);
1861 static void map_tio_request(struct kthread_work *work);
1863 static void init_tio(struct dm_rq_target_io *tio, struct request *rq,
1864 struct mapped_device *md)
1871 memset(&tio->info, 0, sizeof(tio->info));
1872 if (md->kworker_task)
1873 init_kthread_work(&tio->work, map_tio_request);
1876 static struct dm_rq_target_io *prep_tio(struct request *rq,
1877 struct mapped_device *md, gfp_t gfp_mask)
1879 struct dm_rq_target_io *tio;
1881 struct dm_table *table;
1883 tio = alloc_rq_tio(md, gfp_mask);
1887 init_tio(tio, rq, md);
1889 table = dm_get_live_table(md, &srcu_idx);
1890 if (!dm_table_mq_request_based(table)) {
1891 if (!clone_rq(rq, md, tio, gfp_mask)) {
1892 dm_put_live_table(md, srcu_idx);
1897 dm_put_live_table(md, srcu_idx);
1903 * Called with the queue lock held.
1905 static int dm_prep_fn(struct request_queue *q, struct request *rq)
1907 struct mapped_device *md = q->queuedata;
1908 struct dm_rq_target_io *tio;
1910 if (unlikely(rq->special)) {
1911 DMWARN("Already has something in rq->special.");
1912 return BLKPREP_KILL;
1915 tio = prep_tio(rq, md, GFP_ATOMIC);
1917 return BLKPREP_DEFER;
1920 rq->cmd_flags |= REQ_DONTPREP;
1927 * 0 : the request has been processed
1928 * DM_MAPIO_REQUEUE : the original request needs to be requeued
1929 * < 0 : the request was completed due to failure
1931 static int map_request(struct dm_rq_target_io *tio, struct request *rq,
1932 struct mapped_device *md)
1935 struct dm_target *ti = tio->ti;
1936 struct request *clone = NULL;
1940 r = ti->type->map_rq(ti, clone, &tio->info);
1942 r = ti->type->clone_and_map_rq(ti, rq, &tio->info, &clone);
1944 /* The target wants to complete the I/O */
1945 dm_kill_unmapped_request(rq, r);
1948 if (r != DM_MAPIO_REMAPPED)
1950 if (setup_clone(clone, rq, tio, GFP_ATOMIC)) {
1952 ti->type->release_clone_rq(clone);
1953 return DM_MAPIO_REQUEUE;
1958 case DM_MAPIO_SUBMITTED:
1959 /* The target has taken the I/O to submit by itself later */
1961 case DM_MAPIO_REMAPPED:
1962 /* The target has remapped the I/O so dispatch it */
1963 trace_block_rq_remap(clone->q, clone, disk_devt(dm_disk(md)),
1965 dm_dispatch_clone_request(clone, rq);
1967 case DM_MAPIO_REQUEUE:
1968 /* The target wants to requeue the I/O */
1969 dm_requeue_original_request(md, tio->orig);
1973 DMWARN("unimplemented target map return value: %d", r);
1977 /* The target wants to complete the I/O */
1978 dm_kill_unmapped_request(rq, r);
1985 static void map_tio_request(struct kthread_work *work)
1987 struct dm_rq_target_io *tio = container_of(work, struct dm_rq_target_io, work);
1988 struct request *rq = tio->orig;
1989 struct mapped_device *md = tio->md;
1991 if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE)
1992 dm_requeue_original_request(md, rq);
1995 static void dm_start_request(struct mapped_device *md, struct request *orig)
1997 if (!orig->q->mq_ops)
1998 blk_start_request(orig);
2000 blk_mq_start_request(orig);
2001 atomic_inc(&md->pending[rq_data_dir(orig)]);
2003 if (md->seq_rq_merge_deadline_usecs) {
2004 md->last_rq_pos = rq_end_sector(orig);
2005 md->last_rq_rw = rq_data_dir(orig);
2006 md->last_rq_start_time = ktime_get();
2009 if (unlikely(dm_stats_used(&md->stats))) {
2010 struct dm_rq_target_io *tio = tio_from_request(orig);
2011 tio->duration_jiffies = jiffies;
2012 tio->n_sectors = blk_rq_sectors(orig);
2013 dm_stats_account_io(&md->stats, orig->cmd_flags, blk_rq_pos(orig),
2014 tio->n_sectors, false, 0, &tio->stats_aux);
2018 * Hold the md reference here for the in-flight I/O.
2019 * We can't rely on the reference count by device opener,
2020 * because the device may be closed during the request completion
2021 * when all bios are completed.
2022 * See the comment in rq_completed() too.
2027 #define MAX_SEQ_RQ_MERGE_DEADLINE_USECS 100000
2029 ssize_t dm_attr_rq_based_seq_io_merge_deadline_show(struct mapped_device *md, char *buf)
2031 return sprintf(buf, "%u\n", md->seq_rq_merge_deadline_usecs);
2034 ssize_t dm_attr_rq_based_seq_io_merge_deadline_store(struct mapped_device *md,
2035 const char *buf, size_t count)
2039 if (!dm_request_based(md) || md->use_blk_mq)
2042 if (kstrtouint(buf, 10, &deadline))
2045 if (deadline > MAX_SEQ_RQ_MERGE_DEADLINE_USECS)
2046 deadline = MAX_SEQ_RQ_MERGE_DEADLINE_USECS;
2048 md->seq_rq_merge_deadline_usecs = deadline;
2053 static bool dm_request_peeked_before_merge_deadline(struct mapped_device *md)
2055 ktime_t kt_deadline;
2057 if (!md->seq_rq_merge_deadline_usecs)
2060 kt_deadline = ns_to_ktime((u64)md->seq_rq_merge_deadline_usecs * NSEC_PER_USEC);
2061 kt_deadline = ktime_add_safe(md->last_rq_start_time, kt_deadline);
2063 return !ktime_after(ktime_get(), kt_deadline);
2067 * q->request_fn for request-based dm.
2068 * Called with the queue lock held.
2070 static void dm_request_fn(struct request_queue *q)
2072 struct mapped_device *md = q->queuedata;
2074 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2075 struct dm_target *ti;
2077 struct dm_rq_target_io *tio;
2081 * For suspend, check blk_queue_stopped() and increment
2082 * ->pending within a single queue_lock not to increment the
2083 * number of in-flight I/Os after the queue is stopped in
2086 while (!blk_queue_stopped(q)) {
2087 rq = blk_peek_request(q);
2091 /* always use block 0 to find the target for flushes for now */
2093 if (!(rq->cmd_flags & REQ_FLUSH))
2094 pos = blk_rq_pos(rq);
2096 ti = dm_table_find_target(map, pos);
2097 if (!dm_target_is_valid(ti)) {
2099 * Must perform setup, that rq_completed() requires,
2100 * before calling dm_kill_unmapped_request
2102 DMERR_LIMIT("request attempted access beyond the end of device");
2103 dm_start_request(md, rq);
2104 dm_kill_unmapped_request(rq, -EIO);
2108 if (dm_request_peeked_before_merge_deadline(md) &&
2109 md_in_flight(md) && rq->bio && rq->bio->bi_vcnt == 1 &&
2110 md->last_rq_pos == pos && md->last_rq_rw == rq_data_dir(rq))
2113 if (ti->type->busy && ti->type->busy(ti))
2116 dm_start_request(md, rq);
2118 tio = tio_from_request(rq);
2119 /* Establish tio->ti before queuing work (map_tio_request) */
2121 queue_kthread_work(&md->kworker, &tio->work);
2122 BUG_ON(!irqs_disabled());
2128 blk_delay_queue(q, HZ / 100);
2130 dm_put_live_table(md, srcu_idx);
2133 static int dm_any_congested(void *congested_data, int bdi_bits)
2136 struct mapped_device *md = congested_data;
2137 struct dm_table *map;
2139 if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2140 if (dm_request_based(md)) {
2142 * With request-based DM we only need to check the
2143 * top-level queue for congestion.
2145 r = md->queue->backing_dev_info.wb.state & bdi_bits;
2147 map = dm_get_live_table_fast(md);
2149 r = dm_table_any_congested(map, bdi_bits);
2150 dm_put_live_table_fast(md);
2157 /*-----------------------------------------------------------------
2158 * An IDR is used to keep track of allocated minor numbers.
2159 *---------------------------------------------------------------*/
2160 static void free_minor(int minor)
2162 spin_lock(&_minor_lock);
2163 idr_remove(&_minor_idr, minor);
2164 spin_unlock(&_minor_lock);
2168 * See if the device with a specific minor # is free.
2170 static int specific_minor(int minor)
2174 if (minor >= (1 << MINORBITS))
2177 idr_preload(GFP_KERNEL);
2178 spin_lock(&_minor_lock);
2180 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
2182 spin_unlock(&_minor_lock);
2185 return r == -ENOSPC ? -EBUSY : r;
2189 static int next_free_minor(int *minor)
2193 idr_preload(GFP_KERNEL);
2194 spin_lock(&_minor_lock);
2196 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
2198 spin_unlock(&_minor_lock);
2206 static const struct block_device_operations dm_blk_dops;
2208 static void dm_wq_work(struct work_struct *work);
2210 static void dm_init_md_queue(struct mapped_device *md)
2213 * Request-based dm devices cannot be stacked on top of bio-based dm
2214 * devices. The type of this dm device may not have been decided yet.
2215 * The type is decided at the first table loading time.
2216 * To prevent problematic device stacking, clear the queue flag
2217 * for request stacking support until then.
2219 * This queue is new, so no concurrency on the queue_flags.
2221 queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
2224 * Initialize data that will only be used by a non-blk-mq DM queue
2225 * - must do so here (in alloc_dev callchain) before queue is used
2227 md->queue->queuedata = md;
2228 md->queue->backing_dev_info.congested_data = md;
2231 static void dm_init_old_md_queue(struct mapped_device *md)
2233 md->use_blk_mq = false;
2234 dm_init_md_queue(md);
2237 * Initialize aspects of queue that aren't relevant for blk-mq
2239 md->queue->backing_dev_info.congested_fn = dm_any_congested;
2240 blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
2243 static void cleanup_mapped_device(struct mapped_device *md)
2246 destroy_workqueue(md->wq);
2247 if (md->kworker_task)
2248 kthread_stop(md->kworker_task);
2249 mempool_destroy(md->io_pool);
2250 mempool_destroy(md->rq_pool);
2252 bioset_free(md->bs);
2254 cleanup_srcu_struct(&md->io_barrier);
2257 spin_lock(&_minor_lock);
2258 md->disk->private_data = NULL;
2259 spin_unlock(&_minor_lock);
2260 del_gendisk(md->disk);
2265 blk_cleanup_queue(md->queue);
2274 * Allocate and initialise a blank device with a given minor.
2276 static struct mapped_device *alloc_dev(int minor)
2279 struct mapped_device *md = kzalloc(sizeof(*md), GFP_KERNEL);
2283 DMWARN("unable to allocate device, out of memory.");
2287 if (!try_module_get(THIS_MODULE))
2288 goto bad_module_get;
2290 /* get a minor number for the dev */
2291 if (minor == DM_ANY_MINOR)
2292 r = next_free_minor(&minor);
2294 r = specific_minor(minor);
2298 r = init_srcu_struct(&md->io_barrier);
2300 goto bad_io_barrier;
2302 md->use_blk_mq = use_blk_mq;
2303 md->type = DM_TYPE_NONE;
2304 mutex_init(&md->suspend_lock);
2305 mutex_init(&md->type_lock);
2306 mutex_init(&md->table_devices_lock);
2307 spin_lock_init(&md->deferred_lock);
2308 atomic_set(&md->holders, 1);
2309 atomic_set(&md->open_count, 0);
2310 atomic_set(&md->event_nr, 0);
2311 atomic_set(&md->uevent_seq, 0);
2312 INIT_LIST_HEAD(&md->uevent_list);
2313 INIT_LIST_HEAD(&md->table_devices);
2314 spin_lock_init(&md->uevent_lock);
2316 md->queue = blk_alloc_queue(GFP_KERNEL);
2320 dm_init_md_queue(md);
2322 md->disk = alloc_disk(1);
2326 atomic_set(&md->pending[0], 0);
2327 atomic_set(&md->pending[1], 0);
2328 init_waitqueue_head(&md->wait);
2329 INIT_WORK(&md->work, dm_wq_work);
2330 init_waitqueue_head(&md->eventq);
2331 init_completion(&md->kobj_holder.completion);
2332 md->kworker_task = NULL;
2334 md->disk->major = _major;
2335 md->disk->first_minor = minor;
2336 md->disk->fops = &dm_blk_dops;
2337 md->disk->queue = md->queue;
2338 md->disk->private_data = md;
2339 sprintf(md->disk->disk_name, "dm-%d", minor);
2341 format_dev_t(md->name, MKDEV(_major, minor));
2343 md->wq = alloc_workqueue("kdmflush", WQ_MEM_RECLAIM, 0);
2347 md->bdev = bdget_disk(md->disk, 0);
2351 bio_init(&md->flush_bio);
2352 md->flush_bio.bi_bdev = md->bdev;
2353 md->flush_bio.bi_rw = WRITE_FLUSH;
2355 dm_stats_init(&md->stats);
2357 /* Populate the mapping, nobody knows we exist yet */
2358 spin_lock(&_minor_lock);
2359 old_md = idr_replace(&_minor_idr, md, minor);
2360 spin_unlock(&_minor_lock);
2362 BUG_ON(old_md != MINOR_ALLOCED);
2367 cleanup_mapped_device(md);
2371 module_put(THIS_MODULE);
2377 static void unlock_fs(struct mapped_device *md);
2379 static void free_dev(struct mapped_device *md)
2381 int minor = MINOR(disk_devt(md->disk));
2385 cleanup_mapped_device(md);
2387 blk_mq_free_tag_set(&md->tag_set);
2389 free_table_devices(&md->table_devices);
2390 dm_stats_cleanup(&md->stats);
2393 module_put(THIS_MODULE);
2397 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
2399 struct dm_md_mempools *p = dm_table_get_md_mempools(t);
2402 /* The md already has necessary mempools. */
2403 if (dm_table_get_type(t) == DM_TYPE_BIO_BASED) {
2405 * Reload bioset because front_pad may have changed
2406 * because a different table was loaded.
2408 bioset_free(md->bs);
2413 * There's no need to reload with request-based dm
2414 * because the size of front_pad doesn't change.
2415 * Note for future: If you are to reload bioset,
2416 * prep-ed requests in the queue may refer
2417 * to bio from the old bioset, so you must walk
2418 * through the queue to unprep.
2423 BUG_ON(!p || md->io_pool || md->rq_pool || md->bs);
2425 md->io_pool = p->io_pool;
2427 md->rq_pool = p->rq_pool;
2433 /* mempool bind completed, no longer need any mempools in the table */
2434 dm_table_free_md_mempools(t);
2438 * Bind a table to the device.
2440 static void event_callback(void *context)
2442 unsigned long flags;
2444 struct mapped_device *md = (struct mapped_device *) context;
2446 spin_lock_irqsave(&md->uevent_lock, flags);
2447 list_splice_init(&md->uevent_list, &uevents);
2448 spin_unlock_irqrestore(&md->uevent_lock, flags);
2450 dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2452 atomic_inc(&md->event_nr);
2453 wake_up(&md->eventq);
2457 * Protected by md->suspend_lock obtained by dm_swap_table().
2459 static void __set_size(struct mapped_device *md, sector_t size)
2461 set_capacity(md->disk, size);
2463 i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
2467 * Returns old map, which caller must destroy.
2469 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2470 struct queue_limits *limits)
2472 struct dm_table *old_map;
2473 struct request_queue *q = md->queue;
2476 size = dm_table_get_size(t);
2479 * Wipe any geometry if the size of the table changed.
2481 if (size != dm_get_size(md))
2482 memset(&md->geometry, 0, sizeof(md->geometry));
2484 __set_size(md, size);
2486 dm_table_event_callback(t, event_callback, md);
2489 * The queue hasn't been stopped yet, if the old table type wasn't
2490 * for request-based during suspension. So stop it to prevent
2491 * I/O mapping before resume.
2492 * This must be done before setting the queue restrictions,
2493 * because request-based dm may be run just after the setting.
2495 if (dm_table_request_based(t))
2498 __bind_mempools(md, t);
2500 old_map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2501 rcu_assign_pointer(md->map, t);
2502 md->immutable_target_type = dm_table_get_immutable_target_type(t);
2504 dm_table_set_restrictions(t, q, limits);
2512 * Returns unbound table for the caller to free.
2514 static struct dm_table *__unbind(struct mapped_device *md)
2516 struct dm_table *map = rcu_dereference_protected(md->map, 1);
2521 dm_table_event_callback(map, NULL, NULL);
2522 RCU_INIT_POINTER(md->map, NULL);
2529 * Constructor for a new device.
2531 int dm_create(int minor, struct mapped_device **result)
2533 struct mapped_device *md;
2535 md = alloc_dev(minor);
2546 * Functions to manage md->type.
2547 * All are required to hold md->type_lock.
2549 void dm_lock_md_type(struct mapped_device *md)
2551 mutex_lock(&md->type_lock);
2554 void dm_unlock_md_type(struct mapped_device *md)
2556 mutex_unlock(&md->type_lock);
2559 void dm_set_md_type(struct mapped_device *md, unsigned type)
2561 BUG_ON(!mutex_is_locked(&md->type_lock));
2565 unsigned dm_get_md_type(struct mapped_device *md)
2567 BUG_ON(!mutex_is_locked(&md->type_lock));
2571 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2573 return md->immutable_target_type;
2577 * The queue_limits are only valid as long as you have a reference
2580 struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
2582 BUG_ON(!atomic_read(&md->holders));
2583 return &md->queue->limits;
2585 EXPORT_SYMBOL_GPL(dm_get_queue_limits);
2587 static void init_rq_based_worker_thread(struct mapped_device *md)
2589 /* Initialize the request-based DM worker thread */
2590 init_kthread_worker(&md->kworker);
2591 md->kworker_task = kthread_run(kthread_worker_fn, &md->kworker,
2592 "kdmwork-%s", dm_device_name(md));
2596 * Fully initialize a request-based queue (->elevator, ->request_fn, etc).
2598 static int dm_init_request_based_queue(struct mapped_device *md)
2600 struct request_queue *q = NULL;
2602 /* Fully initialize the queue */
2603 q = blk_init_allocated_queue(md->queue, dm_request_fn, NULL);
2607 /* disable dm_request_fn's merge heuristic by default */
2608 md->seq_rq_merge_deadline_usecs = 0;
2611 dm_init_old_md_queue(md);
2612 blk_queue_softirq_done(md->queue, dm_softirq_done);
2613 blk_queue_prep_rq(md->queue, dm_prep_fn);
2615 init_rq_based_worker_thread(md);
2617 elv_register_queue(md->queue);
2622 static int dm_mq_init_request(void *data, struct request *rq,
2623 unsigned int hctx_idx, unsigned int request_idx,
2624 unsigned int numa_node)
2626 struct mapped_device *md = data;
2627 struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2630 * Must initialize md member of tio, otherwise it won't
2631 * be available in dm_mq_queue_rq.
2638 static int dm_mq_queue_rq(struct blk_mq_hw_ctx *hctx,
2639 const struct blk_mq_queue_data *bd)
2641 struct request *rq = bd->rq;
2642 struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2643 struct mapped_device *md = tio->md;
2645 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2646 struct dm_target *ti;
2649 /* always use block 0 to find the target for flushes for now */
2651 if (!(rq->cmd_flags & REQ_FLUSH))
2652 pos = blk_rq_pos(rq);
2654 ti = dm_table_find_target(map, pos);
2655 if (!dm_target_is_valid(ti)) {
2656 dm_put_live_table(md, srcu_idx);
2657 DMERR_LIMIT("request attempted access beyond the end of device");
2659 * Must perform setup, that rq_completed() requires,
2660 * before returning BLK_MQ_RQ_QUEUE_ERROR
2662 dm_start_request(md, rq);
2663 return BLK_MQ_RQ_QUEUE_ERROR;
2665 dm_put_live_table(md, srcu_idx);
2667 if (ti->type->busy && ti->type->busy(ti))
2668 return BLK_MQ_RQ_QUEUE_BUSY;
2670 dm_start_request(md, rq);
2672 /* Init tio using md established in .init_request */
2673 init_tio(tio, rq, md);
2676 * Establish tio->ti before queuing work (map_tio_request)
2677 * or making direct call to map_request().
2681 /* Clone the request if underlying devices aren't blk-mq */
2682 if (dm_table_get_type(map) == DM_TYPE_REQUEST_BASED) {
2683 /* clone request is allocated at the end of the pdu */
2684 tio->clone = (void *)blk_mq_rq_to_pdu(rq) + sizeof(struct dm_rq_target_io);
2685 (void) clone_rq(rq, md, tio, GFP_ATOMIC);
2686 queue_kthread_work(&md->kworker, &tio->work);
2688 /* Direct call is fine since .queue_rq allows allocations */
2689 if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE) {
2690 /* Undo dm_start_request() before requeuing */
2691 rq_end_stats(md, rq);
2692 rq_completed(md, rq_data_dir(rq), false);
2693 return BLK_MQ_RQ_QUEUE_BUSY;
2697 return BLK_MQ_RQ_QUEUE_OK;
2700 static struct blk_mq_ops dm_mq_ops = {
2701 .queue_rq = dm_mq_queue_rq,
2702 .map_queue = blk_mq_map_queue,
2703 .complete = dm_softirq_done,
2704 .init_request = dm_mq_init_request,
2707 static int dm_init_request_based_blk_mq_queue(struct mapped_device *md)
2709 unsigned md_type = dm_get_md_type(md);
2710 struct request_queue *q;
2713 memset(&md->tag_set, 0, sizeof(md->tag_set));
2714 md->tag_set.ops = &dm_mq_ops;
2715 md->tag_set.queue_depth = BLKDEV_MAX_RQ;
2716 md->tag_set.numa_node = NUMA_NO_NODE;
2717 md->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
2718 md->tag_set.nr_hw_queues = 1;
2719 if (md_type == DM_TYPE_REQUEST_BASED) {
2720 /* make the memory for non-blk-mq clone part of the pdu */
2721 md->tag_set.cmd_size = sizeof(struct dm_rq_target_io) + sizeof(struct request);
2723 md->tag_set.cmd_size = sizeof(struct dm_rq_target_io);
2724 md->tag_set.driver_data = md;
2726 err = blk_mq_alloc_tag_set(&md->tag_set);
2730 q = blk_mq_init_allocated_queue(&md->tag_set, md->queue);
2736 dm_init_md_queue(md);
2738 /* backfill 'mq' sysfs registration normally done in blk_register_queue */
2739 blk_mq_register_disk(md->disk);
2741 if (md_type == DM_TYPE_REQUEST_BASED)
2742 init_rq_based_worker_thread(md);
2747 blk_mq_free_tag_set(&md->tag_set);
2751 static unsigned filter_md_type(unsigned type, struct mapped_device *md)
2753 if (type == DM_TYPE_BIO_BASED)
2756 return !md->use_blk_mq ? DM_TYPE_REQUEST_BASED : DM_TYPE_MQ_REQUEST_BASED;
2760 * Setup the DM device's queue based on md's type
2762 int dm_setup_md_queue(struct mapped_device *md)
2765 unsigned md_type = filter_md_type(dm_get_md_type(md), md);
2768 case DM_TYPE_REQUEST_BASED:
2769 r = dm_init_request_based_queue(md);
2771 DMWARN("Cannot initialize queue for request-based mapped device");
2775 case DM_TYPE_MQ_REQUEST_BASED:
2776 r = dm_init_request_based_blk_mq_queue(md);
2778 DMWARN("Cannot initialize queue for request-based blk-mq mapped device");
2782 case DM_TYPE_BIO_BASED:
2783 dm_init_old_md_queue(md);
2784 blk_queue_make_request(md->queue, dm_make_request);
2786 * DM handles splitting bios as needed. Free the bio_split bioset
2787 * since it won't be used (saves 1 process per bio-based DM device).
2789 bioset_free(md->queue->bio_split);
2790 md->queue->bio_split = NULL;
2797 struct mapped_device *dm_get_md(dev_t dev)
2799 struct mapped_device *md;
2800 unsigned minor = MINOR(dev);
2802 if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2805 spin_lock(&_minor_lock);
2807 md = idr_find(&_minor_idr, minor);
2809 if ((md == MINOR_ALLOCED ||
2810 (MINOR(disk_devt(dm_disk(md))) != minor) ||
2811 dm_deleting_md(md) ||
2812 test_bit(DMF_FREEING, &md->flags))) {
2820 spin_unlock(&_minor_lock);
2824 EXPORT_SYMBOL_GPL(dm_get_md);
2826 void *dm_get_mdptr(struct mapped_device *md)
2828 return md->interface_ptr;
2831 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2833 md->interface_ptr = ptr;
2836 void dm_get(struct mapped_device *md)
2838 atomic_inc(&md->holders);
2839 BUG_ON(test_bit(DMF_FREEING, &md->flags));
2842 int dm_hold(struct mapped_device *md)
2844 spin_lock(&_minor_lock);
2845 if (test_bit(DMF_FREEING, &md->flags)) {
2846 spin_unlock(&_minor_lock);
2850 spin_unlock(&_minor_lock);
2853 EXPORT_SYMBOL_GPL(dm_hold);
2855 const char *dm_device_name(struct mapped_device *md)
2859 EXPORT_SYMBOL_GPL(dm_device_name);
2861 static void __dm_destroy(struct mapped_device *md, bool wait)
2863 struct dm_table *map;
2868 spin_lock(&_minor_lock);
2869 idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2870 set_bit(DMF_FREEING, &md->flags);
2871 spin_unlock(&_minor_lock);
2873 if (dm_request_based(md) && md->kworker_task)
2874 flush_kthread_worker(&md->kworker);
2877 * Take suspend_lock so that presuspend and postsuspend methods
2878 * do not race with internal suspend.
2880 mutex_lock(&md->suspend_lock);
2881 map = dm_get_live_table(md, &srcu_idx);
2882 if (!dm_suspended_md(md)) {
2883 dm_table_presuspend_targets(map);
2884 dm_table_postsuspend_targets(map);
2886 /* dm_put_live_table must be before msleep, otherwise deadlock is possible */
2887 dm_put_live_table(md, srcu_idx);
2888 mutex_unlock(&md->suspend_lock);
2891 * Rare, but there may be I/O requests still going to complete,
2892 * for example. Wait for all references to disappear.
2893 * No one should increment the reference count of the mapped_device,
2894 * after the mapped_device state becomes DMF_FREEING.
2897 while (atomic_read(&md->holders))
2899 else if (atomic_read(&md->holders))
2900 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2901 dm_device_name(md), atomic_read(&md->holders));
2904 dm_table_destroy(__unbind(md));
2908 void dm_destroy(struct mapped_device *md)
2910 __dm_destroy(md, true);
2913 void dm_destroy_immediate(struct mapped_device *md)
2915 __dm_destroy(md, false);
2918 void dm_put(struct mapped_device *md)
2920 atomic_dec(&md->holders);
2922 EXPORT_SYMBOL_GPL(dm_put);
2924 static int dm_wait_for_completion(struct mapped_device *md, int interruptible)
2927 DECLARE_WAITQUEUE(wait, current);
2929 add_wait_queue(&md->wait, &wait);
2932 set_current_state(interruptible);
2934 if (!md_in_flight(md))
2937 if (interruptible == TASK_INTERRUPTIBLE &&
2938 signal_pending(current)) {
2945 set_current_state(TASK_RUNNING);
2947 remove_wait_queue(&md->wait, &wait);
2953 * Process the deferred bios
2955 static void dm_wq_work(struct work_struct *work)
2957 struct mapped_device *md = container_of(work, struct mapped_device,
2961 struct dm_table *map;
2963 map = dm_get_live_table(md, &srcu_idx);
2965 while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2966 spin_lock_irq(&md->deferred_lock);
2967 c = bio_list_pop(&md->deferred);
2968 spin_unlock_irq(&md->deferred_lock);
2973 if (dm_request_based(md))
2974 generic_make_request(c);
2976 __split_and_process_bio(md, map, c);
2979 dm_put_live_table(md, srcu_idx);
2982 static void dm_queue_flush(struct mapped_device *md)
2984 clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2985 smp_mb__after_atomic();
2986 queue_work(md->wq, &md->work);
2990 * Swap in a new table, returning the old one for the caller to destroy.
2992 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
2994 struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
2995 struct queue_limits limits;
2998 mutex_lock(&md->suspend_lock);
3000 /* device must be suspended */
3001 if (!dm_suspended_md(md))
3005 * If the new table has no data devices, retain the existing limits.
3006 * This helps multipath with queue_if_no_path if all paths disappear,
3007 * then new I/O is queued based on these limits, and then some paths
3010 if (dm_table_has_no_data_devices(table)) {
3011 live_map = dm_get_live_table_fast(md);
3013 limits = md->queue->limits;
3014 dm_put_live_table_fast(md);
3018 r = dm_calculate_queue_limits(table, &limits);
3025 map = __bind(md, table, &limits);
3028 mutex_unlock(&md->suspend_lock);
3033 * Functions to lock and unlock any filesystem running on the
3036 static int lock_fs(struct mapped_device *md)
3040 WARN_ON(md->frozen_sb);
3042 md->frozen_sb = freeze_bdev(md->bdev);
3043 if (IS_ERR(md->frozen_sb)) {
3044 r = PTR_ERR(md->frozen_sb);
3045 md->frozen_sb = NULL;
3049 set_bit(DMF_FROZEN, &md->flags);
3054 static void unlock_fs(struct mapped_device *md)
3056 if (!test_bit(DMF_FROZEN, &md->flags))
3059 thaw_bdev(md->bdev, md->frozen_sb);
3060 md->frozen_sb = NULL;
3061 clear_bit(DMF_FROZEN, &md->flags);
3065 * If __dm_suspend returns 0, the device is completely quiescent
3066 * now. There is no request-processing activity. All new requests
3067 * are being added to md->deferred list.
3069 * Caller must hold md->suspend_lock
3071 static int __dm_suspend(struct mapped_device *md, struct dm_table *map,
3072 unsigned suspend_flags, int interruptible)
3074 bool do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG;
3075 bool noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG;
3079 * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
3080 * This flag is cleared before dm_suspend returns.
3083 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3086 * This gets reverted if there's an error later and the targets
3087 * provide the .presuspend_undo hook.
3089 dm_table_presuspend_targets(map);
3092 * Flush I/O to the device.
3093 * Any I/O submitted after lock_fs() may not be flushed.
3094 * noflush takes precedence over do_lockfs.
3095 * (lock_fs() flushes I/Os and waits for them to complete.)
3097 if (!noflush && do_lockfs) {
3100 dm_table_presuspend_undo_targets(map);
3106 * Here we must make sure that no processes are submitting requests
3107 * to target drivers i.e. no one may be executing
3108 * __split_and_process_bio. This is called from dm_request and
3111 * To get all processes out of __split_and_process_bio in dm_request,
3112 * we take the write lock. To prevent any process from reentering
3113 * __split_and_process_bio from dm_request and quiesce the thread
3114 * (dm_wq_work), we set BMF_BLOCK_IO_FOR_SUSPEND and call
3115 * flush_workqueue(md->wq).
3117 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3119 synchronize_srcu(&md->io_barrier);
3122 * Stop md->queue before flushing md->wq in case request-based
3123 * dm defers requests to md->wq from md->queue.
3125 if (dm_request_based(md)) {
3126 stop_queue(md->queue);
3127 if (md->kworker_task)
3128 flush_kthread_worker(&md->kworker);
3131 flush_workqueue(md->wq);
3134 * At this point no more requests are entering target request routines.
3135 * We call dm_wait_for_completion to wait for all existing requests
3138 r = dm_wait_for_completion(md, interruptible);
3141 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3143 synchronize_srcu(&md->io_barrier);
3145 /* were we interrupted ? */
3149 if (dm_request_based(md))
3150 start_queue(md->queue);
3153 dm_table_presuspend_undo_targets(map);
3154 /* pushback list is already flushed, so skip flush */
3161 * We need to be able to change a mapping table under a mounted
3162 * filesystem. For example we might want to move some data in
3163 * the background. Before the table can be swapped with
3164 * dm_bind_table, dm_suspend must be called to flush any in
3165 * flight bios and ensure that any further io gets deferred.
3168 * Suspend mechanism in request-based dm.
3170 * 1. Flush all I/Os by lock_fs() if needed.
3171 * 2. Stop dispatching any I/O by stopping the request_queue.
3172 * 3. Wait for all in-flight I/Os to be completed or requeued.
3174 * To abort suspend, start the request_queue.
3176 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
3178 struct dm_table *map = NULL;
3182 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3184 if (dm_suspended_md(md)) {
3189 if (dm_suspended_internally_md(md)) {
3190 /* already internally suspended, wait for internal resume */
3191 mutex_unlock(&md->suspend_lock);
3192 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3198 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3200 r = __dm_suspend(md, map, suspend_flags, TASK_INTERRUPTIBLE);
3204 set_bit(DMF_SUSPENDED, &md->flags);
3206 dm_table_postsuspend_targets(map);
3209 mutex_unlock(&md->suspend_lock);
3213 static int __dm_resume(struct mapped_device *md, struct dm_table *map)
3216 int r = dm_table_resume_targets(map);
3224 * Flushing deferred I/Os must be done after targets are resumed
3225 * so that mapping of targets can work correctly.
3226 * Request-based dm is queueing the deferred I/Os in its request_queue.
3228 if (dm_request_based(md))
3229 start_queue(md->queue);
3236 int dm_resume(struct mapped_device *md)
3239 struct dm_table *map = NULL;
3242 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3244 if (!dm_suspended_md(md))
3247 if (dm_suspended_internally_md(md)) {
3248 /* already internally suspended, wait for internal resume */
3249 mutex_unlock(&md->suspend_lock);
3250 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3256 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3257 if (!map || !dm_table_get_size(map))
3260 r = __dm_resume(md, map);
3264 clear_bit(DMF_SUSPENDED, &md->flags);
3268 mutex_unlock(&md->suspend_lock);
3274 * Internal suspend/resume works like userspace-driven suspend. It waits
3275 * until all bios finish and prevents issuing new bios to the target drivers.
3276 * It may be used only from the kernel.
3279 static void __dm_internal_suspend(struct mapped_device *md, unsigned suspend_flags)
3281 struct dm_table *map = NULL;
3283 if (md->internal_suspend_count++)
3284 return; /* nested internal suspend */
3286 if (dm_suspended_md(md)) {
3287 set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3288 return; /* nest suspend */
3291 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3294 * Using TASK_UNINTERRUPTIBLE because only NOFLUSH internal suspend is
3295 * supported. Properly supporting a TASK_INTERRUPTIBLE internal suspend
3296 * would require changing .presuspend to return an error -- avoid this
3297 * until there is a need for more elaborate variants of internal suspend.
3299 (void) __dm_suspend(md, map, suspend_flags, TASK_UNINTERRUPTIBLE);
3301 set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3303 dm_table_postsuspend_targets(map);
3306 static void __dm_internal_resume(struct mapped_device *md)
3308 BUG_ON(!md->internal_suspend_count);
3310 if (--md->internal_suspend_count)
3311 return; /* resume from nested internal suspend */
3313 if (dm_suspended_md(md))
3314 goto done; /* resume from nested suspend */
3317 * NOTE: existing callers don't need to call dm_table_resume_targets
3318 * (which may fail -- so best to avoid it for now by passing NULL map)
3320 (void) __dm_resume(md, NULL);
3323 clear_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3324 smp_mb__after_atomic();
3325 wake_up_bit(&md->flags, DMF_SUSPENDED_INTERNALLY);
3328 void dm_internal_suspend_noflush(struct mapped_device *md)
3330 mutex_lock(&md->suspend_lock);
3331 __dm_internal_suspend(md, DM_SUSPEND_NOFLUSH_FLAG);
3332 mutex_unlock(&md->suspend_lock);
3334 EXPORT_SYMBOL_GPL(dm_internal_suspend_noflush);
3336 void dm_internal_resume(struct mapped_device *md)
3338 mutex_lock(&md->suspend_lock);
3339 __dm_internal_resume(md);
3340 mutex_unlock(&md->suspend_lock);
3342 EXPORT_SYMBOL_GPL(dm_internal_resume);
3345 * Fast variants of internal suspend/resume hold md->suspend_lock,
3346 * which prevents interaction with userspace-driven suspend.
3349 void dm_internal_suspend_fast(struct mapped_device *md)
3351 mutex_lock(&md->suspend_lock);
3352 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3355 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3356 synchronize_srcu(&md->io_barrier);
3357 flush_workqueue(md->wq);
3358 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
3360 EXPORT_SYMBOL_GPL(dm_internal_suspend_fast);
3362 void dm_internal_resume_fast(struct mapped_device *md)
3364 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3370 mutex_unlock(&md->suspend_lock);
3372 EXPORT_SYMBOL_GPL(dm_internal_resume_fast);
3374 /*-----------------------------------------------------------------
3375 * Event notification.
3376 *---------------------------------------------------------------*/
3377 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
3380 char udev_cookie[DM_COOKIE_LENGTH];
3381 char *envp[] = { udev_cookie, NULL };
3384 return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
3386 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
3387 DM_COOKIE_ENV_VAR_NAME, cookie);
3388 return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
3393 uint32_t dm_next_uevent_seq(struct mapped_device *md)
3395 return atomic_add_return(1, &md->uevent_seq);
3398 uint32_t dm_get_event_nr(struct mapped_device *md)
3400 return atomic_read(&md->event_nr);
3403 int dm_wait_event(struct mapped_device *md, int event_nr)
3405 return wait_event_interruptible(md->eventq,
3406 (event_nr != atomic_read(&md->event_nr)));
3409 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
3411 unsigned long flags;
3413 spin_lock_irqsave(&md->uevent_lock, flags);
3414 list_add(elist, &md->uevent_list);
3415 spin_unlock_irqrestore(&md->uevent_lock, flags);
3419 * The gendisk is only valid as long as you have a reference
3422 struct gendisk *dm_disk(struct mapped_device *md)
3426 EXPORT_SYMBOL_GPL(dm_disk);
3428 struct kobject *dm_kobject(struct mapped_device *md)
3430 return &md->kobj_holder.kobj;
3433 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
3435 struct mapped_device *md;
3437 md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
3439 if (test_bit(DMF_FREEING, &md->flags) ||
3447 int dm_suspended_md(struct mapped_device *md)
3449 return test_bit(DMF_SUSPENDED, &md->flags);
3452 int dm_suspended_internally_md(struct mapped_device *md)
3454 return test_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3457 int dm_test_deferred_remove_flag(struct mapped_device *md)
3459 return test_bit(DMF_DEFERRED_REMOVE, &md->flags);
3462 int dm_suspended(struct dm_target *ti)
3464 return dm_suspended_md(dm_table_get_md(ti->table));
3466 EXPORT_SYMBOL_GPL(dm_suspended);
3468 int dm_noflush_suspending(struct dm_target *ti)
3470 return __noflush_suspending(dm_table_get_md(ti->table));
3472 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
3474 struct dm_md_mempools *dm_alloc_md_mempools(struct mapped_device *md, unsigned type,
3475 unsigned integrity, unsigned per_bio_data_size)
3477 struct dm_md_mempools *pools = kzalloc(sizeof(*pools), GFP_KERNEL);
3478 struct kmem_cache *cachep = NULL;
3479 unsigned int pool_size = 0;
3480 unsigned int front_pad;
3485 type = filter_md_type(type, md);
3488 case DM_TYPE_BIO_BASED:
3490 pool_size = dm_get_reserved_bio_based_ios();
3491 front_pad = roundup(per_bio_data_size, __alignof__(struct dm_target_io)) + offsetof(struct dm_target_io, clone);
3493 case DM_TYPE_REQUEST_BASED:
3494 cachep = _rq_tio_cache;
3495 pool_size = dm_get_reserved_rq_based_ios();
3496 pools->rq_pool = mempool_create_slab_pool(pool_size, _rq_cache);
3497 if (!pools->rq_pool)
3499 /* fall through to setup remaining rq-based pools */
3500 case DM_TYPE_MQ_REQUEST_BASED:
3502 pool_size = dm_get_reserved_rq_based_ios();
3503 front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
3504 /* per_bio_data_size is not used. See __bind_mempools(). */
3505 WARN_ON(per_bio_data_size != 0);
3512 pools->io_pool = mempool_create_slab_pool(pool_size, cachep);
3513 if (!pools->io_pool)
3517 pools->bs = bioset_create_nobvec(pool_size, front_pad);
3521 if (integrity && bioset_integrity_create(pools->bs, pool_size))
3527 dm_free_md_mempools(pools);
3532 void dm_free_md_mempools(struct dm_md_mempools *pools)
3537 mempool_destroy(pools->io_pool);
3538 mempool_destroy(pools->rq_pool);
3541 bioset_free(pools->bs);
3546 static int dm_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
3549 struct mapped_device *md = bdev->bd_disk->private_data;
3550 const struct pr_ops *ops;
3554 r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3558 ops = bdev->bd_disk->fops->pr_ops;
3559 if (ops && ops->pr_register)
3560 r = ops->pr_register(bdev, old_key, new_key, flags);
3568 static int dm_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
3571 struct mapped_device *md = bdev->bd_disk->private_data;
3572 const struct pr_ops *ops;
3576 r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3580 ops = bdev->bd_disk->fops->pr_ops;
3581 if (ops && ops->pr_reserve)
3582 r = ops->pr_reserve(bdev, key, type, flags);
3590 static int dm_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
3592 struct mapped_device *md = bdev->bd_disk->private_data;
3593 const struct pr_ops *ops;
3597 r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3601 ops = bdev->bd_disk->fops->pr_ops;
3602 if (ops && ops->pr_release)
3603 r = ops->pr_release(bdev, key, type);
3611 static int dm_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
3612 enum pr_type type, bool abort)
3614 struct mapped_device *md = bdev->bd_disk->private_data;
3615 const struct pr_ops *ops;
3619 r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3623 ops = bdev->bd_disk->fops->pr_ops;
3624 if (ops && ops->pr_preempt)
3625 r = ops->pr_preempt(bdev, old_key, new_key, type, abort);
3633 static int dm_pr_clear(struct block_device *bdev, u64 key)
3635 struct mapped_device *md = bdev->bd_disk->private_data;
3636 const struct pr_ops *ops;
3640 r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3644 ops = bdev->bd_disk->fops->pr_ops;
3645 if (ops && ops->pr_clear)
3646 r = ops->pr_clear(bdev, key);
3654 static const struct pr_ops dm_pr_ops = {
3655 .pr_register = dm_pr_register,
3656 .pr_reserve = dm_pr_reserve,
3657 .pr_release = dm_pr_release,
3658 .pr_preempt = dm_pr_preempt,
3659 .pr_clear = dm_pr_clear,
3662 static const struct block_device_operations dm_blk_dops = {
3663 .open = dm_blk_open,
3664 .release = dm_blk_close,
3665 .ioctl = dm_blk_ioctl,
3666 .getgeo = dm_blk_getgeo,
3667 .pr_ops = &dm_pr_ops,
3668 .owner = THIS_MODULE
3674 module_init(dm_init);
3675 module_exit(dm_exit);
3677 module_param(major, uint, 0);
3678 MODULE_PARM_DESC(major, "The major number of the device mapper");
3680 module_param(reserved_bio_based_ios, uint, S_IRUGO | S_IWUSR);
3681 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
3683 module_param(reserved_rq_based_ios, uint, S_IRUGO | S_IWUSR);
3684 MODULE_PARM_DESC(reserved_rq_based_ios, "Reserved IOs in request-based mempools");
3686 module_param(use_blk_mq, bool, S_IRUGO | S_IWUSR);
3687 MODULE_PARM_DESC(use_blk_mq, "Use block multiqueue for request-based DM devices");
3689 MODULE_DESCRIPTION(DM_NAME " driver");
3690 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
3691 MODULE_LICENSE("GPL");