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);
978 bio->bi_error = io_error;
984 static void disable_write_same(struct mapped_device *md)
986 struct queue_limits *limits = dm_get_queue_limits(md);
988 /* device doesn't really support WRITE SAME, disable it */
989 limits->max_write_same_sectors = 0;
992 static void clone_endio(struct bio *bio)
994 int error = bio->bi_error;
996 struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
997 struct dm_io *io = tio->io;
998 struct mapped_device *md = tio->io->md;
999 dm_endio_fn endio = tio->ti->type->end_io;
1002 r = endio(tio->ti, bio, error);
1003 if (r < 0 || r == DM_ENDIO_REQUEUE)
1005 * error and requeue request are handled
1009 else if (r == DM_ENDIO_INCOMPLETE)
1010 /* The target will handle the io */
1013 DMWARN("unimplemented target endio return value: %d", r);
1018 if (unlikely(r == -EREMOTEIO && (bio->bi_rw & REQ_WRITE_SAME) &&
1019 !bdev_get_queue(bio->bi_bdev)->limits.max_write_same_sectors))
1020 disable_write_same(md);
1023 dec_pending(io, error);
1027 * Partial completion handling for request-based dm
1029 static void end_clone_bio(struct bio *clone)
1031 struct dm_rq_clone_bio_info *info =
1032 container_of(clone, struct dm_rq_clone_bio_info, clone);
1033 struct dm_rq_target_io *tio = info->tio;
1034 struct bio *bio = info->orig;
1035 unsigned int nr_bytes = info->orig->bi_iter.bi_size;
1036 int error = clone->bi_error;
1042 * An error has already been detected on the request.
1043 * Once error occurred, just let clone->end_io() handle
1049 * Don't notice the error to the upper layer yet.
1050 * The error handling decision is made by the target driver,
1051 * when the request is completed.
1058 * I/O for the bio successfully completed.
1059 * Notice the data completion to the upper layer.
1063 * bios are processed from the head of the list.
1064 * So the completing bio should always be rq->bio.
1065 * If it's not, something wrong is happening.
1067 if (tio->orig->bio != bio)
1068 DMERR("bio completion is going in the middle of the request");
1071 * Update the original request.
1072 * Do not use blk_end_request() here, because it may complete
1073 * the original request before the clone, and break the ordering.
1075 blk_update_request(tio->orig, 0, nr_bytes);
1078 static struct dm_rq_target_io *tio_from_request(struct request *rq)
1080 return (rq->q->mq_ops ? blk_mq_rq_to_pdu(rq) : rq->special);
1083 static void rq_end_stats(struct mapped_device *md, struct request *orig)
1085 if (unlikely(dm_stats_used(&md->stats))) {
1086 struct dm_rq_target_io *tio = tio_from_request(orig);
1087 tio->duration_jiffies = jiffies - tio->duration_jiffies;
1088 dm_stats_account_io(&md->stats, orig->cmd_flags, blk_rq_pos(orig),
1089 tio->n_sectors, true, tio->duration_jiffies,
1095 * Don't touch any member of the md after calling this function because
1096 * the md may be freed in dm_put() at the end of this function.
1097 * Or do dm_get() before calling this function and dm_put() later.
1099 static void rq_completed(struct mapped_device *md, int rw, bool run_queue)
1101 atomic_dec(&md->pending[rw]);
1103 /* nudge anyone waiting on suspend queue */
1104 if (!md_in_flight(md))
1108 * Run this off this callpath, as drivers could invoke end_io while
1109 * inside their request_fn (and holding the queue lock). Calling
1110 * back into ->request_fn() could deadlock attempting to grab the
1113 if (!md->queue->mq_ops && run_queue)
1114 blk_run_queue_async(md->queue);
1117 * dm_put() must be at the end of this function. See the comment above
1122 static void free_rq_clone(struct request *clone)
1124 struct dm_rq_target_io *tio = clone->end_io_data;
1125 struct mapped_device *md = tio->md;
1127 blk_rq_unprep_clone(clone);
1129 if (md->type == DM_TYPE_MQ_REQUEST_BASED)
1130 /* stacked on blk-mq queue(s) */
1131 tio->ti->type->release_clone_rq(clone);
1132 else if (!md->queue->mq_ops)
1133 /* request_fn queue stacked on request_fn queue(s) */
1134 free_clone_request(md, clone);
1136 * NOTE: for the blk-mq queue stacked on request_fn queue(s) case:
1137 * no need to call free_clone_request() because we leverage blk-mq by
1138 * allocating the clone at the end of the blk-mq pdu (see: clone_rq)
1141 if (!md->queue->mq_ops)
1146 * Complete the clone and the original request.
1147 * Must be called without clone's queue lock held,
1148 * see end_clone_request() for more details.
1150 void dm_end_request(struct request *clone, int error)
1152 int rw = rq_data_dir(clone);
1153 struct dm_rq_target_io *tio = clone->end_io_data;
1154 struct mapped_device *md = tio->md;
1155 struct request *rq = tio->orig;
1157 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
1158 rq->errors = clone->errors;
1159 rq->resid_len = clone->resid_len;
1163 * We are using the sense buffer of the original
1165 * So setting the length of the sense data is enough.
1167 rq->sense_len = clone->sense_len;
1170 free_rq_clone(clone);
1171 rq_end_stats(md, rq);
1173 blk_end_request_all(rq, error);
1175 blk_mq_end_request(rq, error);
1176 rq_completed(md, rw, true);
1179 static void dm_unprep_request(struct request *rq)
1181 struct dm_rq_target_io *tio = tio_from_request(rq);
1182 struct request *clone = tio->clone;
1184 if (!rq->q->mq_ops) {
1186 rq->cmd_flags &= ~REQ_DONTPREP;
1190 free_rq_clone(clone);
1191 else if (!tio->md->queue->mq_ops)
1196 * Requeue the original request of a clone.
1198 static void old_requeue_request(struct request *rq)
1200 struct request_queue *q = rq->q;
1201 unsigned long flags;
1203 spin_lock_irqsave(q->queue_lock, flags);
1204 blk_requeue_request(q, rq);
1205 blk_run_queue_async(q);
1206 spin_unlock_irqrestore(q->queue_lock, flags);
1209 static void dm_requeue_original_request(struct mapped_device *md,
1212 int rw = rq_data_dir(rq);
1214 rq_end_stats(md, rq);
1215 dm_unprep_request(rq);
1218 old_requeue_request(rq);
1220 blk_mq_requeue_request(rq);
1221 blk_mq_kick_requeue_list(rq->q);
1224 rq_completed(md, rw, false);
1227 static void old_stop_queue(struct request_queue *q)
1229 unsigned long flags;
1231 if (blk_queue_stopped(q))
1234 spin_lock_irqsave(q->queue_lock, flags);
1236 spin_unlock_irqrestore(q->queue_lock, flags);
1239 static void stop_queue(struct request_queue *q)
1244 blk_mq_stop_hw_queues(q);
1247 static void old_start_queue(struct request_queue *q)
1249 unsigned long flags;
1251 spin_lock_irqsave(q->queue_lock, flags);
1252 if (blk_queue_stopped(q))
1254 spin_unlock_irqrestore(q->queue_lock, flags);
1257 static void start_queue(struct request_queue *q)
1262 blk_mq_start_stopped_hw_queues(q, true);
1265 static void dm_done(struct request *clone, int error, bool mapped)
1268 struct dm_rq_target_io *tio = clone->end_io_data;
1269 dm_request_endio_fn rq_end_io = NULL;
1272 rq_end_io = tio->ti->type->rq_end_io;
1274 if (mapped && rq_end_io)
1275 r = rq_end_io(tio->ti, clone, error, &tio->info);
1278 if (unlikely(r == -EREMOTEIO && (clone->cmd_flags & REQ_WRITE_SAME) &&
1279 !clone->q->limits.max_write_same_sectors))
1280 disable_write_same(tio->md);
1283 /* The target wants to complete the I/O */
1284 dm_end_request(clone, r);
1285 else if (r == DM_ENDIO_INCOMPLETE)
1286 /* The target will handle the I/O */
1288 else if (r == DM_ENDIO_REQUEUE)
1289 /* The target wants to requeue the I/O */
1290 dm_requeue_original_request(tio->md, tio->orig);
1292 DMWARN("unimplemented target endio return value: %d", r);
1298 * Request completion handler for request-based dm
1300 static void dm_softirq_done(struct request *rq)
1303 struct dm_rq_target_io *tio = tio_from_request(rq);
1304 struct request *clone = tio->clone;
1308 rq_end_stats(tio->md, rq);
1309 rw = rq_data_dir(rq);
1310 if (!rq->q->mq_ops) {
1311 blk_end_request_all(rq, tio->error);
1312 rq_completed(tio->md, rw, false);
1315 blk_mq_end_request(rq, tio->error);
1316 rq_completed(tio->md, rw, false);
1321 if (rq->cmd_flags & REQ_FAILED)
1324 dm_done(clone, tio->error, mapped);
1328 * Complete the clone and the original request with the error status
1329 * through softirq context.
1331 static void dm_complete_request(struct request *rq, int error)
1333 struct dm_rq_target_io *tio = tio_from_request(rq);
1337 blk_complete_request(rq);
1339 blk_mq_complete_request(rq, error);
1343 * Complete the not-mapped clone and the original request with the error status
1344 * through softirq context.
1345 * Target's rq_end_io() function isn't called.
1346 * This may be used when the target's map_rq() or clone_and_map_rq() functions fail.
1348 void dm_kill_unmapped_request(struct request *rq, int error)
1350 rq->cmd_flags |= REQ_FAILED;
1351 dm_complete_request(rq, error);
1355 * Called with the clone's queue lock held (for non-blk-mq)
1357 static void end_clone_request(struct request *clone, int error)
1359 struct dm_rq_target_io *tio = clone->end_io_data;
1361 if (!clone->q->mq_ops) {
1363 * For just cleaning up the information of the queue in which
1364 * the clone was dispatched.
1365 * The clone is *NOT* freed actually here because it is alloced
1366 * from dm own mempool (REQ_ALLOCED isn't set).
1368 __blk_put_request(clone->q, clone);
1372 * Actual request completion is done in a softirq context which doesn't
1373 * hold the clone's queue lock. Otherwise, deadlock could occur because:
1374 * - another request may be submitted by the upper level driver
1375 * of the stacking during the completion
1376 * - the submission which requires queue lock may be done
1377 * against this clone's queue
1379 dm_complete_request(tio->orig, error);
1383 * Return maximum size of I/O possible at the supplied sector up to the current
1386 static sector_t max_io_len_target_boundary(sector_t sector, struct dm_target *ti)
1388 sector_t target_offset = dm_target_offset(ti, sector);
1390 return ti->len - target_offset;
1393 static sector_t max_io_len(sector_t sector, struct dm_target *ti)
1395 sector_t len = max_io_len_target_boundary(sector, ti);
1396 sector_t offset, max_len;
1399 * Does the target need to split even further?
1401 if (ti->max_io_len) {
1402 offset = dm_target_offset(ti, sector);
1403 if (unlikely(ti->max_io_len & (ti->max_io_len - 1)))
1404 max_len = sector_div(offset, ti->max_io_len);
1406 max_len = offset & (ti->max_io_len - 1);
1407 max_len = ti->max_io_len - max_len;
1416 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
1418 if (len > UINT_MAX) {
1419 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
1420 (unsigned long long)len, UINT_MAX);
1421 ti->error = "Maximum size of target IO is too large";
1425 ti->max_io_len = (uint32_t) len;
1429 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
1432 * A target may call dm_accept_partial_bio only from the map routine. It is
1433 * allowed for all bio types except REQ_FLUSH.
1435 * dm_accept_partial_bio informs the dm that the target only wants to process
1436 * additional n_sectors sectors of the bio and the rest of the data should be
1437 * sent in a next bio.
1439 * A diagram that explains the arithmetics:
1440 * +--------------------+---------------+-------+
1442 * +--------------------+---------------+-------+
1444 * <-------------- *tio->len_ptr --------------->
1445 * <------- bi_size ------->
1448 * Region 1 was already iterated over with bio_advance or similar function.
1449 * (it may be empty if the target doesn't use bio_advance)
1450 * Region 2 is the remaining bio size that the target wants to process.
1451 * (it may be empty if region 1 is non-empty, although there is no reason
1453 * The target requires that region 3 is to be sent in the next bio.
1455 * If the target wants to receive multiple copies of the bio (via num_*bios, etc),
1456 * the partially processed part (the sum of regions 1+2) must be the same for all
1457 * copies of the bio.
1459 void dm_accept_partial_bio(struct bio *bio, unsigned n_sectors)
1461 struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
1462 unsigned bi_size = bio->bi_iter.bi_size >> SECTOR_SHIFT;
1463 BUG_ON(bio->bi_rw & REQ_FLUSH);
1464 BUG_ON(bi_size > *tio->len_ptr);
1465 BUG_ON(n_sectors > bi_size);
1466 *tio->len_ptr -= bi_size - n_sectors;
1467 bio->bi_iter.bi_size = n_sectors << SECTOR_SHIFT;
1469 EXPORT_SYMBOL_GPL(dm_accept_partial_bio);
1472 * Flush current->bio_list when the target map method blocks.
1473 * This fixes deadlocks in snapshot and possibly in other targets.
1476 struct blk_plug plug;
1477 struct blk_plug_cb cb;
1480 static void flush_current_bio_list(struct blk_plug_cb *cb, bool from_schedule)
1482 struct dm_offload *o = container_of(cb, struct dm_offload, cb);
1483 struct bio_list list;
1487 INIT_LIST_HEAD(&o->cb.list);
1489 if (unlikely(!current->bio_list))
1492 for (i = 0; i < 2; i++) {
1493 list = current->bio_list[i];
1494 bio_list_init(¤t->bio_list[i]);
1496 while ((bio = bio_list_pop(&list))) {
1497 struct bio_set *bs = bio->bi_pool;
1498 if (unlikely(!bs) || bs == fs_bio_set) {
1499 bio_list_add(¤t->bio_list[i], bio);
1503 spin_lock(&bs->rescue_lock);
1504 bio_list_add(&bs->rescue_list, bio);
1505 queue_work(bs->rescue_workqueue, &bs->rescue_work);
1506 spin_unlock(&bs->rescue_lock);
1511 static void dm_offload_start(struct dm_offload *o)
1513 blk_start_plug(&o->plug);
1514 o->cb.callback = flush_current_bio_list;
1515 list_add(&o->cb.list, ¤t->plug->cb_list);
1518 static void dm_offload_end(struct dm_offload *o)
1520 list_del(&o->cb.list);
1521 blk_finish_plug(&o->plug);
1524 static void __map_bio(struct dm_target_io *tio)
1528 struct mapped_device *md;
1529 struct dm_offload o;
1530 struct bio *clone = &tio->clone;
1531 struct dm_target *ti = tio->ti;
1533 clone->bi_end_io = clone_endio;
1536 * Map the clone. If r == 0 we don't need to do
1537 * anything, the target has assumed ownership of
1540 atomic_inc(&tio->io->io_count);
1541 sector = clone->bi_iter.bi_sector;
1543 dm_offload_start(&o);
1544 r = ti->type->map(ti, clone);
1547 if (r == DM_MAPIO_REMAPPED) {
1548 /* the bio has been remapped so dispatch it */
1550 trace_block_bio_remap(bdev_get_queue(clone->bi_bdev), clone,
1551 tio->io->bio->bi_bdev->bd_dev, sector);
1553 generic_make_request(clone);
1554 } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1555 /* error the io and bail out, or requeue it if needed */
1557 dec_pending(tio->io, r);
1559 } else if (r != DM_MAPIO_SUBMITTED) {
1560 DMWARN("unimplemented target map return value: %d", r);
1566 struct mapped_device *md;
1567 struct dm_table *map;
1571 unsigned sector_count;
1574 static void bio_setup_sector(struct bio *bio, sector_t sector, unsigned len)
1576 bio->bi_iter.bi_sector = sector;
1577 bio->bi_iter.bi_size = to_bytes(len);
1581 * Creates a bio that consists of range of complete bvecs.
1583 static void clone_bio(struct dm_target_io *tio, struct bio *bio,
1584 sector_t sector, unsigned len)
1586 struct bio *clone = &tio->clone;
1588 __bio_clone_fast(clone, bio);
1590 if (bio_integrity(bio))
1591 bio_integrity_clone(clone, bio, GFP_NOIO);
1593 bio_advance(clone, to_bytes(sector - clone->bi_iter.bi_sector));
1594 clone->bi_iter.bi_size = to_bytes(len);
1596 if (bio_integrity(bio))
1597 bio_integrity_trim(clone, 0, len);
1600 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1601 struct dm_target *ti,
1602 unsigned target_bio_nr)
1604 struct dm_target_io *tio;
1607 clone = bio_alloc_bioset(GFP_NOIO, 0, ci->md->bs);
1608 tio = container_of(clone, struct dm_target_io, clone);
1612 tio->target_bio_nr = target_bio_nr;
1617 static void __clone_and_map_simple_bio(struct clone_info *ci,
1618 struct dm_target *ti,
1619 unsigned target_bio_nr, unsigned *len)
1621 struct dm_target_io *tio = alloc_tio(ci, ti, target_bio_nr);
1622 struct bio *clone = &tio->clone;
1626 __bio_clone_fast(clone, ci->bio);
1628 bio_setup_sector(clone, ci->sector, *len);
1633 static void __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1634 unsigned num_bios, unsigned *len)
1636 unsigned target_bio_nr;
1638 for (target_bio_nr = 0; target_bio_nr < num_bios; target_bio_nr++)
1639 __clone_and_map_simple_bio(ci, ti, target_bio_nr, len);
1642 static int __send_empty_flush(struct clone_info *ci)
1644 unsigned target_nr = 0;
1645 struct dm_target *ti;
1647 BUG_ON(bio_has_data(ci->bio));
1648 while ((ti = dm_table_get_target(ci->map, target_nr++)))
1649 __send_duplicate_bios(ci, ti, ti->num_flush_bios, NULL);
1654 static void __clone_and_map_data_bio(struct clone_info *ci, struct dm_target *ti,
1655 sector_t sector, unsigned *len)
1657 struct bio *bio = ci->bio;
1658 struct dm_target_io *tio;
1659 unsigned target_bio_nr;
1660 unsigned num_target_bios = 1;
1663 * Does the target want to receive duplicate copies of the bio?
1665 if (bio_data_dir(bio) == WRITE && ti->num_write_bios)
1666 num_target_bios = ti->num_write_bios(ti, bio);
1668 for (target_bio_nr = 0; target_bio_nr < num_target_bios; target_bio_nr++) {
1669 tio = alloc_tio(ci, ti, target_bio_nr);
1671 clone_bio(tio, bio, sector, *len);
1676 typedef unsigned (*get_num_bios_fn)(struct dm_target *ti);
1678 static unsigned get_num_discard_bios(struct dm_target *ti)
1680 return ti->num_discard_bios;
1683 static unsigned get_num_write_same_bios(struct dm_target *ti)
1685 return ti->num_write_same_bios;
1688 typedef bool (*is_split_required_fn)(struct dm_target *ti);
1690 static bool is_split_required_for_discard(struct dm_target *ti)
1692 return ti->split_discard_bios;
1695 static int __send_changing_extent_only(struct clone_info *ci,
1696 get_num_bios_fn get_num_bios,
1697 is_split_required_fn is_split_required)
1699 struct dm_target *ti;
1704 ti = dm_table_find_target(ci->map, ci->sector);
1705 if (!dm_target_is_valid(ti))
1709 * Even though the device advertised support for this type of
1710 * request, that does not mean every target supports it, and
1711 * reconfiguration might also have changed that since the
1712 * check was performed.
1714 num_bios = get_num_bios ? get_num_bios(ti) : 0;
1718 if (is_split_required && !is_split_required(ti))
1719 len = min((sector_t)ci->sector_count, max_io_len_target_boundary(ci->sector, ti));
1721 len = min((sector_t)ci->sector_count, max_io_len(ci->sector, ti));
1723 __send_duplicate_bios(ci, ti, num_bios, &len);
1726 } while (ci->sector_count -= len);
1731 static int __send_discard(struct clone_info *ci)
1733 return __send_changing_extent_only(ci, get_num_discard_bios,
1734 is_split_required_for_discard);
1737 static int __send_write_same(struct clone_info *ci)
1739 return __send_changing_extent_only(ci, get_num_write_same_bios, NULL);
1743 * Select the correct strategy for processing a non-flush bio.
1745 static int __split_and_process_non_flush(struct clone_info *ci)
1747 struct bio *bio = ci->bio;
1748 struct dm_target *ti;
1751 if (unlikely(bio->bi_rw & REQ_DISCARD))
1752 return __send_discard(ci);
1753 else if (unlikely(bio->bi_rw & REQ_WRITE_SAME))
1754 return __send_write_same(ci);
1756 ti = dm_table_find_target(ci->map, ci->sector);
1757 if (!dm_target_is_valid(ti))
1760 len = min_t(sector_t, max_io_len(ci->sector, ti), ci->sector_count);
1762 __clone_and_map_data_bio(ci, ti, ci->sector, &len);
1765 ci->sector_count -= len;
1771 * Entry point to split a bio into clones and submit them to the targets.
1773 static void __split_and_process_bio(struct mapped_device *md,
1774 struct dm_table *map, struct bio *bio)
1776 struct clone_info ci;
1779 if (unlikely(!map)) {
1786 ci.io = alloc_io(md);
1788 atomic_set(&ci.io->io_count, 1);
1791 spin_lock_init(&ci.io->endio_lock);
1792 ci.sector = bio->bi_iter.bi_sector;
1794 start_io_acct(ci.io);
1796 if (bio->bi_rw & REQ_FLUSH) {
1797 ci.bio = &ci.md->flush_bio;
1798 ci.sector_count = 0;
1799 error = __send_empty_flush(&ci);
1800 /* dec_pending submits any data associated with flush */
1803 ci.sector_count = bio_sectors(bio);
1804 while (ci.sector_count && !error)
1805 error = __split_and_process_non_flush(&ci);
1808 /* drop the extra reference count */
1809 dec_pending(ci.io, error);
1811 /*-----------------------------------------------------------------
1813 *---------------------------------------------------------------*/
1816 * The request function that just remaps the bio built up by
1819 static blk_qc_t dm_make_request(struct request_queue *q, struct bio *bio)
1821 int rw = bio_data_dir(bio);
1822 struct mapped_device *md = q->queuedata;
1824 struct dm_table *map;
1826 map = dm_get_live_table(md, &srcu_idx);
1828 generic_start_io_acct(rw, bio_sectors(bio), &dm_disk(md)->part0);
1830 /* if we're suspended, we have to queue this io for later */
1831 if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
1832 dm_put_live_table(md, srcu_idx);
1834 if (bio_rw(bio) != READA)
1838 return BLK_QC_T_NONE;
1841 __split_and_process_bio(md, map, bio);
1842 dm_put_live_table(md, srcu_idx);
1843 return BLK_QC_T_NONE;
1846 int dm_request_based(struct mapped_device *md)
1848 return blk_queue_stackable(md->queue);
1851 static void dm_dispatch_clone_request(struct request *clone, struct request *rq)
1855 if (blk_queue_io_stat(clone->q))
1856 clone->cmd_flags |= REQ_IO_STAT;
1858 clone->start_time = jiffies;
1859 r = blk_insert_cloned_request(clone->q, clone);
1861 /* must complete clone in terms of original request */
1862 dm_complete_request(rq, r);
1865 void dm_dispatch_request(struct request *rq)
1867 struct dm_rq_target_io *tio = tio_from_request(rq);
1869 dm_dispatch_clone_request(tio->clone, rq);
1872 static int dm_rq_bio_constructor(struct bio *bio, struct bio *bio_orig,
1875 struct dm_rq_target_io *tio = data;
1876 struct dm_rq_clone_bio_info *info =
1877 container_of(bio, struct dm_rq_clone_bio_info, clone);
1879 info->orig = bio_orig;
1881 bio->bi_end_io = end_clone_bio;
1886 static int setup_clone(struct request *clone, struct request *rq,
1887 struct dm_rq_target_io *tio, gfp_t gfp_mask)
1891 r = blk_rq_prep_clone(clone, rq, tio->md->bs, gfp_mask,
1892 dm_rq_bio_constructor, tio);
1896 clone->cmd = rq->cmd;
1897 clone->cmd_len = rq->cmd_len;
1898 clone->sense = rq->sense;
1899 clone->end_io = end_clone_request;
1900 clone->end_io_data = tio;
1907 static struct request *clone_rq(struct request *rq, struct mapped_device *md,
1908 struct dm_rq_target_io *tio, gfp_t gfp_mask)
1911 * Do not allocate a clone if tio->clone was already set
1912 * (see: dm_mq_queue_rq).
1914 bool alloc_clone = !tio->clone;
1915 struct request *clone;
1918 clone = alloc_clone_request(md, gfp_mask);
1924 blk_rq_init(NULL, clone);
1925 if (setup_clone(clone, rq, tio, gfp_mask)) {
1928 free_clone_request(md, clone);
1935 static void map_tio_request(struct kthread_work *work);
1937 static void init_tio(struct dm_rq_target_io *tio, struct request *rq,
1938 struct mapped_device *md)
1945 memset(&tio->info, 0, sizeof(tio->info));
1946 if (md->kworker_task)
1947 init_kthread_work(&tio->work, map_tio_request);
1950 static struct dm_rq_target_io *prep_tio(struct request *rq,
1951 struct mapped_device *md, gfp_t gfp_mask)
1953 struct dm_rq_target_io *tio;
1955 struct dm_table *table;
1957 tio = alloc_rq_tio(md, gfp_mask);
1961 init_tio(tio, rq, md);
1963 table = dm_get_live_table(md, &srcu_idx);
1964 if (!dm_table_mq_request_based(table)) {
1965 if (!clone_rq(rq, md, tio, gfp_mask)) {
1966 dm_put_live_table(md, srcu_idx);
1971 dm_put_live_table(md, srcu_idx);
1977 * Called with the queue lock held.
1979 static int dm_prep_fn(struct request_queue *q, struct request *rq)
1981 struct mapped_device *md = q->queuedata;
1982 struct dm_rq_target_io *tio;
1984 if (unlikely(rq->special)) {
1985 DMWARN("Already has something in rq->special.");
1986 return BLKPREP_KILL;
1989 tio = prep_tio(rq, md, GFP_ATOMIC);
1991 return BLKPREP_DEFER;
1994 rq->cmd_flags |= REQ_DONTPREP;
2001 * 0 : the request has been processed
2002 * DM_MAPIO_REQUEUE : the original request needs to be requeued
2003 * < 0 : the request was completed due to failure
2005 static int map_request(struct dm_rq_target_io *tio, struct request *rq,
2006 struct mapped_device *md)
2009 struct dm_target *ti = tio->ti;
2010 struct request *clone = NULL;
2014 r = ti->type->map_rq(ti, clone, &tio->info);
2016 r = ti->type->clone_and_map_rq(ti, rq, &tio->info, &clone);
2018 /* The target wants to complete the I/O */
2019 dm_kill_unmapped_request(rq, r);
2022 if (r != DM_MAPIO_REMAPPED)
2024 if (setup_clone(clone, rq, tio, GFP_ATOMIC)) {
2026 ti->type->release_clone_rq(clone);
2027 return DM_MAPIO_REQUEUE;
2032 case DM_MAPIO_SUBMITTED:
2033 /* The target has taken the I/O to submit by itself later */
2035 case DM_MAPIO_REMAPPED:
2036 /* The target has remapped the I/O so dispatch it */
2037 trace_block_rq_remap(clone->q, clone, disk_devt(dm_disk(md)),
2039 dm_dispatch_clone_request(clone, rq);
2041 case DM_MAPIO_REQUEUE:
2042 /* The target wants to requeue the I/O */
2043 dm_requeue_original_request(md, tio->orig);
2047 DMWARN("unimplemented target map return value: %d", r);
2051 /* The target wants to complete the I/O */
2052 dm_kill_unmapped_request(rq, r);
2059 static void map_tio_request(struct kthread_work *work)
2061 struct dm_rq_target_io *tio = container_of(work, struct dm_rq_target_io, work);
2062 struct request *rq = tio->orig;
2063 struct mapped_device *md = tio->md;
2065 if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE)
2066 dm_requeue_original_request(md, rq);
2069 static void dm_start_request(struct mapped_device *md, struct request *orig)
2071 if (!orig->q->mq_ops)
2072 blk_start_request(orig);
2074 blk_mq_start_request(orig);
2075 atomic_inc(&md->pending[rq_data_dir(orig)]);
2077 if (md->seq_rq_merge_deadline_usecs) {
2078 md->last_rq_pos = rq_end_sector(orig);
2079 md->last_rq_rw = rq_data_dir(orig);
2080 md->last_rq_start_time = ktime_get();
2083 if (unlikely(dm_stats_used(&md->stats))) {
2084 struct dm_rq_target_io *tio = tio_from_request(orig);
2085 tio->duration_jiffies = jiffies;
2086 tio->n_sectors = blk_rq_sectors(orig);
2087 dm_stats_account_io(&md->stats, orig->cmd_flags, blk_rq_pos(orig),
2088 tio->n_sectors, false, 0, &tio->stats_aux);
2092 * Hold the md reference here for the in-flight I/O.
2093 * We can't rely on the reference count by device opener,
2094 * because the device may be closed during the request completion
2095 * when all bios are completed.
2096 * See the comment in rq_completed() too.
2101 #define MAX_SEQ_RQ_MERGE_DEADLINE_USECS 100000
2103 ssize_t dm_attr_rq_based_seq_io_merge_deadline_show(struct mapped_device *md, char *buf)
2105 return sprintf(buf, "%u\n", md->seq_rq_merge_deadline_usecs);
2108 ssize_t dm_attr_rq_based_seq_io_merge_deadline_store(struct mapped_device *md,
2109 const char *buf, size_t count)
2113 if (!dm_request_based(md) || md->use_blk_mq)
2116 if (kstrtouint(buf, 10, &deadline))
2119 if (deadline > MAX_SEQ_RQ_MERGE_DEADLINE_USECS)
2120 deadline = MAX_SEQ_RQ_MERGE_DEADLINE_USECS;
2122 md->seq_rq_merge_deadline_usecs = deadline;
2127 static bool dm_request_peeked_before_merge_deadline(struct mapped_device *md)
2129 ktime_t kt_deadline;
2131 if (!md->seq_rq_merge_deadline_usecs)
2134 kt_deadline = ns_to_ktime((u64)md->seq_rq_merge_deadline_usecs * NSEC_PER_USEC);
2135 kt_deadline = ktime_add_safe(md->last_rq_start_time, kt_deadline);
2137 return !ktime_after(ktime_get(), kt_deadline);
2141 * q->request_fn for request-based dm.
2142 * Called with the queue lock held.
2144 static void dm_request_fn(struct request_queue *q)
2146 struct mapped_device *md = q->queuedata;
2148 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2149 struct dm_target *ti;
2151 struct dm_rq_target_io *tio;
2155 * For suspend, check blk_queue_stopped() and increment
2156 * ->pending within a single queue_lock not to increment the
2157 * number of in-flight I/Os after the queue is stopped in
2160 while (!blk_queue_stopped(q)) {
2161 rq = blk_peek_request(q);
2165 /* always use block 0 to find the target for flushes for now */
2167 if (!(rq->cmd_flags & REQ_FLUSH))
2168 pos = blk_rq_pos(rq);
2170 ti = dm_table_find_target(map, pos);
2171 if (!dm_target_is_valid(ti)) {
2173 * Must perform setup, that rq_completed() requires,
2174 * before calling dm_kill_unmapped_request
2176 DMERR_LIMIT("request attempted access beyond the end of device");
2177 dm_start_request(md, rq);
2178 dm_kill_unmapped_request(rq, -EIO);
2182 if (dm_request_peeked_before_merge_deadline(md) &&
2183 md_in_flight(md) && rq->bio && rq->bio->bi_vcnt == 1 &&
2184 md->last_rq_pos == pos && md->last_rq_rw == rq_data_dir(rq))
2187 if (ti->type->busy && ti->type->busy(ti))
2190 dm_start_request(md, rq);
2192 tio = tio_from_request(rq);
2193 /* Establish tio->ti before queuing work (map_tio_request) */
2195 spin_unlock(q->queue_lock);
2196 if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE)
2197 dm_requeue_original_request(md, rq);
2198 BUG_ON(!irqs_disabled());
2199 spin_lock(q->queue_lock);
2205 blk_delay_queue(q, HZ / 100);
2207 dm_put_live_table(md, srcu_idx);
2210 static int dm_any_congested(void *congested_data, int bdi_bits)
2213 struct mapped_device *md = congested_data;
2214 struct dm_table *map;
2216 if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2217 map = dm_get_live_table_fast(md);
2220 * Request-based dm cares about only own queue for
2221 * the query about congestion status of request_queue
2223 if (dm_request_based(md))
2224 r = md->queue->backing_dev_info->wb.state &
2227 r = dm_table_any_congested(map, bdi_bits);
2229 dm_put_live_table_fast(md);
2235 /*-----------------------------------------------------------------
2236 * An IDR is used to keep track of allocated minor numbers.
2237 *---------------------------------------------------------------*/
2238 static void free_minor(int minor)
2240 spin_lock(&_minor_lock);
2241 idr_remove(&_minor_idr, minor);
2242 spin_unlock(&_minor_lock);
2246 * See if the device with a specific minor # is free.
2248 static int specific_minor(int minor)
2252 if (minor >= (1 << MINORBITS))
2255 idr_preload(GFP_KERNEL);
2256 spin_lock(&_minor_lock);
2258 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
2260 spin_unlock(&_minor_lock);
2263 return r == -ENOSPC ? -EBUSY : r;
2267 static int next_free_minor(int *minor)
2271 idr_preload(GFP_KERNEL);
2272 spin_lock(&_minor_lock);
2274 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
2276 spin_unlock(&_minor_lock);
2284 static const struct block_device_operations dm_blk_dops;
2286 static void dm_wq_work(struct work_struct *work);
2288 static void dm_init_md_queue(struct mapped_device *md)
2291 * Request-based dm devices cannot be stacked on top of bio-based dm
2292 * devices. The type of this dm device may not have been decided yet.
2293 * The type is decided at the first table loading time.
2294 * To prevent problematic device stacking, clear the queue flag
2295 * for request stacking support until then.
2297 * This queue is new, so no concurrency on the queue_flags.
2299 queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
2302 * Initialize data that will only be used by a non-blk-mq DM queue
2303 * - must do so here (in alloc_dev callchain) before queue is used
2305 md->queue->queuedata = md;
2308 static void dm_init_old_md_queue(struct mapped_device *md)
2310 md->use_blk_mq = false;
2311 dm_init_md_queue(md);
2314 * Initialize aspects of queue that aren't relevant for blk-mq
2316 md->queue->backing_dev_info->congested_data = md;
2317 md->queue->backing_dev_info->congested_fn = dm_any_congested;
2318 blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
2321 static void cleanup_mapped_device(struct mapped_device *md)
2324 destroy_workqueue(md->wq);
2325 if (md->kworker_task)
2326 kthread_stop(md->kworker_task);
2327 mempool_destroy(md->io_pool);
2328 mempool_destroy(md->rq_pool);
2330 bioset_free(md->bs);
2333 spin_lock(&_minor_lock);
2334 md->disk->private_data = NULL;
2335 spin_unlock(&_minor_lock);
2336 del_gendisk(md->disk);
2341 blk_cleanup_queue(md->queue);
2343 cleanup_srcu_struct(&md->io_barrier);
2352 * Allocate and initialise a blank device with a given minor.
2354 static struct mapped_device *alloc_dev(int minor)
2357 struct mapped_device *md = kzalloc(sizeof(*md), GFP_KERNEL);
2361 DMWARN("unable to allocate device, out of memory.");
2365 if (!try_module_get(THIS_MODULE))
2366 goto bad_module_get;
2368 /* get a minor number for the dev */
2369 if (minor == DM_ANY_MINOR)
2370 r = next_free_minor(&minor);
2372 r = specific_minor(minor);
2376 r = init_srcu_struct(&md->io_barrier);
2378 goto bad_io_barrier;
2380 md->use_blk_mq = use_blk_mq;
2381 md->type = DM_TYPE_NONE;
2382 mutex_init(&md->suspend_lock);
2383 mutex_init(&md->type_lock);
2384 mutex_init(&md->table_devices_lock);
2385 spin_lock_init(&md->deferred_lock);
2386 atomic_set(&md->holders, 1);
2387 atomic_set(&md->open_count, 0);
2388 atomic_set(&md->event_nr, 0);
2389 atomic_set(&md->uevent_seq, 0);
2390 INIT_LIST_HEAD(&md->uevent_list);
2391 INIT_LIST_HEAD(&md->table_devices);
2392 spin_lock_init(&md->uevent_lock);
2394 md->queue = blk_alloc_queue(GFP_KERNEL);
2398 dm_init_md_queue(md);
2400 * default to bio-based required ->make_request_fn until DM
2401 * table is loaded and md->type established. If request-based
2402 * table is loaded: blk-mq will override accordingly.
2404 blk_queue_make_request(md->queue, dm_make_request);
2406 md->disk = alloc_disk(1);
2410 atomic_set(&md->pending[0], 0);
2411 atomic_set(&md->pending[1], 0);
2412 init_waitqueue_head(&md->wait);
2413 INIT_WORK(&md->work, dm_wq_work);
2414 init_waitqueue_head(&md->eventq);
2415 init_completion(&md->kobj_holder.completion);
2416 md->kworker_task = NULL;
2418 md->disk->major = _major;
2419 md->disk->first_minor = minor;
2420 md->disk->fops = &dm_blk_dops;
2421 md->disk->queue = md->queue;
2422 md->disk->private_data = md;
2423 sprintf(md->disk->disk_name, "dm-%d", minor);
2425 format_dev_t(md->name, MKDEV(_major, minor));
2427 md->wq = alloc_workqueue("kdmflush", WQ_MEM_RECLAIM, 0);
2431 md->bdev = bdget_disk(md->disk, 0);
2435 bio_init(&md->flush_bio);
2436 md->flush_bio.bi_bdev = md->bdev;
2437 md->flush_bio.bi_rw = WRITE_FLUSH;
2439 dm_stats_init(&md->stats);
2441 /* Populate the mapping, nobody knows we exist yet */
2442 spin_lock(&_minor_lock);
2443 old_md = idr_replace(&_minor_idr, md, minor);
2444 spin_unlock(&_minor_lock);
2446 BUG_ON(old_md != MINOR_ALLOCED);
2451 cleanup_mapped_device(md);
2455 module_put(THIS_MODULE);
2461 static void unlock_fs(struct mapped_device *md);
2463 static void free_dev(struct mapped_device *md)
2465 int minor = MINOR(disk_devt(md->disk));
2469 cleanup_mapped_device(md);
2471 blk_mq_free_tag_set(&md->tag_set);
2473 free_table_devices(&md->table_devices);
2474 dm_stats_cleanup(&md->stats);
2477 module_put(THIS_MODULE);
2481 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
2483 struct dm_md_mempools *p = dm_table_get_md_mempools(t);
2486 /* The md already has necessary mempools. */
2487 if (dm_table_get_type(t) == DM_TYPE_BIO_BASED) {
2489 * Reload bioset because front_pad may have changed
2490 * because a different table was loaded.
2492 bioset_free(md->bs);
2497 * There's no need to reload with request-based dm
2498 * because the size of front_pad doesn't change.
2499 * Note for future: If you are to reload bioset,
2500 * prep-ed requests in the queue may refer
2501 * to bio from the old bioset, so you must walk
2502 * through the queue to unprep.
2507 BUG_ON(!p || md->io_pool || md->rq_pool || md->bs);
2509 md->io_pool = p->io_pool;
2511 md->rq_pool = p->rq_pool;
2517 /* mempool bind completed, no longer need any mempools in the table */
2518 dm_table_free_md_mempools(t);
2522 * Bind a table to the device.
2524 static void event_callback(void *context)
2526 unsigned long flags;
2528 struct mapped_device *md = (struct mapped_device *) context;
2530 spin_lock_irqsave(&md->uevent_lock, flags);
2531 list_splice_init(&md->uevent_list, &uevents);
2532 spin_unlock_irqrestore(&md->uevent_lock, flags);
2534 dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2536 atomic_inc(&md->event_nr);
2537 wake_up(&md->eventq);
2541 * Protected by md->suspend_lock obtained by dm_swap_table().
2543 static void __set_size(struct mapped_device *md, sector_t size)
2545 set_capacity(md->disk, size);
2547 i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
2551 * Returns old map, which caller must destroy.
2553 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2554 struct queue_limits *limits)
2556 struct dm_table *old_map;
2557 struct request_queue *q = md->queue;
2560 size = dm_table_get_size(t);
2563 * Wipe any geometry if the size of the table changed.
2565 if (size != dm_get_size(md))
2566 memset(&md->geometry, 0, sizeof(md->geometry));
2568 __set_size(md, size);
2570 dm_table_event_callback(t, event_callback, md);
2573 * The queue hasn't been stopped yet, if the old table type wasn't
2574 * for request-based during suspension. So stop it to prevent
2575 * I/O mapping before resume.
2576 * This must be done before setting the queue restrictions,
2577 * because request-based dm may be run just after the setting.
2579 if (dm_table_request_based(t))
2582 __bind_mempools(md, t);
2584 old_map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2585 rcu_assign_pointer(md->map, t);
2586 md->immutable_target_type = dm_table_get_immutable_target_type(t);
2588 dm_table_set_restrictions(t, q, limits);
2596 * Returns unbound table for the caller to free.
2598 static struct dm_table *__unbind(struct mapped_device *md)
2600 struct dm_table *map = rcu_dereference_protected(md->map, 1);
2605 dm_table_event_callback(map, NULL, NULL);
2606 RCU_INIT_POINTER(md->map, NULL);
2613 * Constructor for a new device.
2615 int dm_create(int minor, struct mapped_device **result)
2617 struct mapped_device *md;
2619 md = alloc_dev(minor);
2630 * Functions to manage md->type.
2631 * All are required to hold md->type_lock.
2633 void dm_lock_md_type(struct mapped_device *md)
2635 mutex_lock(&md->type_lock);
2638 void dm_unlock_md_type(struct mapped_device *md)
2640 mutex_unlock(&md->type_lock);
2643 void dm_set_md_type(struct mapped_device *md, unsigned type)
2645 BUG_ON(!mutex_is_locked(&md->type_lock));
2649 unsigned dm_get_md_type(struct mapped_device *md)
2651 BUG_ON(!mutex_is_locked(&md->type_lock));
2655 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2657 return md->immutable_target_type;
2661 * The queue_limits are only valid as long as you have a reference
2664 struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
2666 BUG_ON(!atomic_read(&md->holders));
2667 return &md->queue->limits;
2669 EXPORT_SYMBOL_GPL(dm_get_queue_limits);
2671 static void init_rq_based_worker_thread(struct mapped_device *md)
2673 /* Initialize the request-based DM worker thread */
2674 init_kthread_worker(&md->kworker);
2675 md->kworker_task = kthread_run(kthread_worker_fn, &md->kworker,
2676 "kdmwork-%s", dm_device_name(md));
2680 * Fully initialize a request-based queue (->elevator, ->request_fn, etc).
2682 static int dm_init_request_based_queue(struct mapped_device *md)
2684 struct request_queue *q = NULL;
2686 /* Fully initialize the queue */
2687 q = blk_init_allocated_queue(md->queue, dm_request_fn, NULL);
2691 /* disable dm_request_fn's merge heuristic by default */
2692 md->seq_rq_merge_deadline_usecs = 0;
2695 dm_init_old_md_queue(md);
2696 blk_queue_softirq_done(md->queue, dm_softirq_done);
2697 blk_queue_prep_rq(md->queue, dm_prep_fn);
2699 init_rq_based_worker_thread(md);
2701 elv_register_queue(md->queue);
2706 static int dm_mq_init_request(void *data, struct request *rq,
2707 unsigned int hctx_idx, unsigned int request_idx,
2708 unsigned int numa_node)
2710 struct mapped_device *md = data;
2711 struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2714 * Must initialize md member of tio, otherwise it won't
2715 * be available in dm_mq_queue_rq.
2722 static int dm_mq_queue_rq(struct blk_mq_hw_ctx *hctx,
2723 const struct blk_mq_queue_data *bd)
2725 struct request *rq = bd->rq;
2726 struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2727 struct mapped_device *md = tio->md;
2729 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2730 struct dm_target *ti;
2733 /* always use block 0 to find the target for flushes for now */
2735 if (!(rq->cmd_flags & REQ_FLUSH))
2736 pos = blk_rq_pos(rq);
2738 ti = dm_table_find_target(map, pos);
2739 if (!dm_target_is_valid(ti)) {
2740 dm_put_live_table(md, srcu_idx);
2741 DMERR_LIMIT("request attempted access beyond the end of device");
2743 * Must perform setup, that rq_completed() requires,
2744 * before returning BLK_MQ_RQ_QUEUE_ERROR
2746 dm_start_request(md, rq);
2747 return BLK_MQ_RQ_QUEUE_ERROR;
2749 dm_put_live_table(md, srcu_idx);
2751 if (ti->type->busy && ti->type->busy(ti))
2752 return BLK_MQ_RQ_QUEUE_BUSY;
2754 dm_start_request(md, rq);
2756 /* Init tio using md established in .init_request */
2757 init_tio(tio, rq, md);
2760 * Establish tio->ti before queuing work (map_tio_request)
2761 * or making direct call to map_request().
2765 /* Clone the request if underlying devices aren't blk-mq */
2766 if (dm_table_get_type(map) == DM_TYPE_REQUEST_BASED) {
2767 /* clone request is allocated at the end of the pdu */
2768 tio->clone = (void *)blk_mq_rq_to_pdu(rq) + sizeof(struct dm_rq_target_io);
2769 (void) clone_rq(rq, md, tio, GFP_ATOMIC);
2770 queue_kthread_work(&md->kworker, &tio->work);
2772 /* Direct call is fine since .queue_rq allows allocations */
2773 if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE) {
2774 /* Undo dm_start_request() before requeuing */
2775 rq_end_stats(md, rq);
2776 rq_completed(md, rq_data_dir(rq), false);
2777 return BLK_MQ_RQ_QUEUE_BUSY;
2781 return BLK_MQ_RQ_QUEUE_OK;
2784 static struct blk_mq_ops dm_mq_ops = {
2785 .queue_rq = dm_mq_queue_rq,
2786 .map_queue = blk_mq_map_queue,
2787 .complete = dm_softirq_done,
2788 .init_request = dm_mq_init_request,
2791 static int dm_init_request_based_blk_mq_queue(struct mapped_device *md)
2793 unsigned md_type = dm_get_md_type(md);
2794 struct request_queue *q;
2797 memset(&md->tag_set, 0, sizeof(md->tag_set));
2798 md->tag_set.ops = &dm_mq_ops;
2799 md->tag_set.queue_depth = BLKDEV_MAX_RQ;
2800 md->tag_set.numa_node = NUMA_NO_NODE;
2801 md->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
2802 md->tag_set.nr_hw_queues = 1;
2803 if (md_type == DM_TYPE_REQUEST_BASED) {
2804 /* make the memory for non-blk-mq clone part of the pdu */
2805 md->tag_set.cmd_size = sizeof(struct dm_rq_target_io) + sizeof(struct request);
2807 md->tag_set.cmd_size = sizeof(struct dm_rq_target_io);
2808 md->tag_set.driver_data = md;
2810 err = blk_mq_alloc_tag_set(&md->tag_set);
2814 q = blk_mq_init_allocated_queue(&md->tag_set, md->queue);
2820 dm_init_md_queue(md);
2822 /* backfill 'mq' sysfs registration normally done in blk_register_queue */
2823 blk_mq_register_disk(md->disk);
2825 if (md_type == DM_TYPE_REQUEST_BASED)
2826 init_rq_based_worker_thread(md);
2831 blk_mq_free_tag_set(&md->tag_set);
2835 static unsigned filter_md_type(unsigned type, struct mapped_device *md)
2837 if (type == DM_TYPE_BIO_BASED)
2840 return !md->use_blk_mq ? DM_TYPE_REQUEST_BASED : DM_TYPE_MQ_REQUEST_BASED;
2844 * Setup the DM device's queue based on md's type
2846 int dm_setup_md_queue(struct mapped_device *md)
2849 unsigned md_type = filter_md_type(dm_get_md_type(md), md);
2852 case DM_TYPE_REQUEST_BASED:
2853 r = dm_init_request_based_queue(md);
2855 DMWARN("Cannot initialize queue for request-based mapped device");
2859 case DM_TYPE_MQ_REQUEST_BASED:
2860 r = dm_init_request_based_blk_mq_queue(md);
2862 DMWARN("Cannot initialize queue for request-based blk-mq mapped device");
2866 case DM_TYPE_BIO_BASED:
2867 dm_init_old_md_queue(md);
2869 * DM handles splitting bios as needed. Free the bio_split bioset
2870 * since it won't be used (saves 1 process per bio-based DM device).
2872 bioset_free(md->queue->bio_split);
2873 md->queue->bio_split = NULL;
2880 struct mapped_device *dm_get_md(dev_t dev)
2882 struct mapped_device *md;
2883 unsigned minor = MINOR(dev);
2885 if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2888 spin_lock(&_minor_lock);
2890 md = idr_find(&_minor_idr, minor);
2892 if ((md == MINOR_ALLOCED ||
2893 (MINOR(disk_devt(dm_disk(md))) != minor) ||
2894 dm_deleting_md(md) ||
2895 test_bit(DMF_FREEING, &md->flags))) {
2903 spin_unlock(&_minor_lock);
2907 EXPORT_SYMBOL_GPL(dm_get_md);
2909 void *dm_get_mdptr(struct mapped_device *md)
2911 return md->interface_ptr;
2914 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2916 md->interface_ptr = ptr;
2919 void dm_get(struct mapped_device *md)
2921 atomic_inc(&md->holders);
2922 BUG_ON(test_bit(DMF_FREEING, &md->flags));
2925 int dm_hold(struct mapped_device *md)
2927 spin_lock(&_minor_lock);
2928 if (test_bit(DMF_FREEING, &md->flags)) {
2929 spin_unlock(&_minor_lock);
2933 spin_unlock(&_minor_lock);
2936 EXPORT_SYMBOL_GPL(dm_hold);
2938 const char *dm_device_name(struct mapped_device *md)
2942 EXPORT_SYMBOL_GPL(dm_device_name);
2944 static void __dm_destroy(struct mapped_device *md, bool wait)
2946 struct request_queue *q = dm_get_md_queue(md);
2947 struct dm_table *map;
2952 spin_lock(&_minor_lock);
2953 idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2954 set_bit(DMF_FREEING, &md->flags);
2955 spin_unlock(&_minor_lock);
2957 blk_set_queue_dying(q);
2959 if (dm_request_based(md) && md->kworker_task)
2960 flush_kthread_worker(&md->kworker);
2963 * Take suspend_lock so that presuspend and postsuspend methods
2964 * do not race with internal suspend.
2966 mutex_lock(&md->suspend_lock);
2967 map = dm_get_live_table(md, &srcu_idx);
2968 if (!dm_suspended_md(md)) {
2969 dm_table_presuspend_targets(map);
2970 dm_table_postsuspend_targets(map);
2972 /* dm_put_live_table must be before msleep, otherwise deadlock is possible */
2973 dm_put_live_table(md, srcu_idx);
2974 mutex_unlock(&md->suspend_lock);
2977 * Rare, but there may be I/O requests still going to complete,
2978 * for example. Wait for all references to disappear.
2979 * No one should increment the reference count of the mapped_device,
2980 * after the mapped_device state becomes DMF_FREEING.
2983 while (atomic_read(&md->holders))
2985 else if (atomic_read(&md->holders))
2986 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2987 dm_device_name(md), atomic_read(&md->holders));
2990 dm_table_destroy(__unbind(md));
2994 void dm_destroy(struct mapped_device *md)
2996 __dm_destroy(md, true);
2999 void dm_destroy_immediate(struct mapped_device *md)
3001 __dm_destroy(md, false);
3004 void dm_put(struct mapped_device *md)
3006 atomic_dec(&md->holders);
3008 EXPORT_SYMBOL_GPL(dm_put);
3010 static int dm_wait_for_completion(struct mapped_device *md, int interruptible)
3013 DECLARE_WAITQUEUE(wait, current);
3015 add_wait_queue(&md->wait, &wait);
3018 set_current_state(interruptible);
3020 if (!md_in_flight(md))
3023 if (interruptible == TASK_INTERRUPTIBLE &&
3024 signal_pending(current)) {
3031 set_current_state(TASK_RUNNING);
3033 remove_wait_queue(&md->wait, &wait);
3039 * Process the deferred bios
3041 static void dm_wq_work(struct work_struct *work)
3043 struct mapped_device *md = container_of(work, struct mapped_device,
3047 struct dm_table *map;
3049 map = dm_get_live_table(md, &srcu_idx);
3051 while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
3052 spin_lock_irq(&md->deferred_lock);
3053 c = bio_list_pop(&md->deferred);
3054 spin_unlock_irq(&md->deferred_lock);
3059 if (dm_request_based(md))
3060 generic_make_request(c);
3062 __split_and_process_bio(md, map, c);
3065 dm_put_live_table(md, srcu_idx);
3068 static void dm_queue_flush(struct mapped_device *md)
3070 clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3071 smp_mb__after_atomic();
3072 queue_work(md->wq, &md->work);
3076 * Swap in a new table, returning the old one for the caller to destroy.
3078 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
3080 struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
3081 struct queue_limits limits;
3084 mutex_lock(&md->suspend_lock);
3086 /* device must be suspended */
3087 if (!dm_suspended_md(md))
3091 * If the new table has no data devices, retain the existing limits.
3092 * This helps multipath with queue_if_no_path if all paths disappear,
3093 * then new I/O is queued based on these limits, and then some paths
3096 if (dm_table_has_no_data_devices(table)) {
3097 live_map = dm_get_live_table_fast(md);
3099 limits = md->queue->limits;
3100 dm_put_live_table_fast(md);
3104 r = dm_calculate_queue_limits(table, &limits);
3111 map = __bind(md, table, &limits);
3114 mutex_unlock(&md->suspend_lock);
3119 * Functions to lock and unlock any filesystem running on the
3122 static int lock_fs(struct mapped_device *md)
3126 WARN_ON(md->frozen_sb);
3128 md->frozen_sb = freeze_bdev(md->bdev);
3129 if (IS_ERR(md->frozen_sb)) {
3130 r = PTR_ERR(md->frozen_sb);
3131 md->frozen_sb = NULL;
3135 set_bit(DMF_FROZEN, &md->flags);
3140 static void unlock_fs(struct mapped_device *md)
3142 if (!test_bit(DMF_FROZEN, &md->flags))
3145 thaw_bdev(md->bdev, md->frozen_sb);
3146 md->frozen_sb = NULL;
3147 clear_bit(DMF_FROZEN, &md->flags);
3151 * If __dm_suspend returns 0, the device is completely quiescent
3152 * now. There is no request-processing activity. All new requests
3153 * are being added to md->deferred list.
3155 * Caller must hold md->suspend_lock
3157 static int __dm_suspend(struct mapped_device *md, struct dm_table *map,
3158 unsigned suspend_flags, int interruptible,
3159 int dmf_suspended_flag)
3161 bool do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG;
3162 bool noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG;
3166 * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
3167 * This flag is cleared before dm_suspend returns.
3170 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3173 * This gets reverted if there's an error later and the targets
3174 * provide the .presuspend_undo hook.
3176 dm_table_presuspend_targets(map);
3179 * Flush I/O to the device.
3180 * Any I/O submitted after lock_fs() may not be flushed.
3181 * noflush takes precedence over do_lockfs.
3182 * (lock_fs() flushes I/Os and waits for them to complete.)
3184 if (!noflush && do_lockfs) {
3187 dm_table_presuspend_undo_targets(map);
3193 * Here we must make sure that no processes are submitting requests
3194 * to target drivers i.e. no one may be executing
3195 * __split_and_process_bio. This is called from dm_request and
3198 * To get all processes out of __split_and_process_bio in dm_request,
3199 * we take the write lock. To prevent any process from reentering
3200 * __split_and_process_bio from dm_request and quiesce the thread
3201 * (dm_wq_work), we set BMF_BLOCK_IO_FOR_SUSPEND and call
3202 * flush_workqueue(md->wq).
3204 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3206 synchronize_srcu(&md->io_barrier);
3209 * Stop md->queue before flushing md->wq in case request-based
3210 * dm defers requests to md->wq from md->queue.
3212 if (dm_request_based(md)) {
3213 stop_queue(md->queue);
3214 if (md->kworker_task)
3215 flush_kthread_worker(&md->kworker);
3218 flush_workqueue(md->wq);
3221 * At this point no more requests are entering target request routines.
3222 * We call dm_wait_for_completion to wait for all existing requests
3225 r = dm_wait_for_completion(md, interruptible);
3227 set_bit(dmf_suspended_flag, &md->flags);
3230 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3232 synchronize_srcu(&md->io_barrier);
3234 /* were we interrupted ? */
3238 if (dm_request_based(md))
3239 start_queue(md->queue);
3242 dm_table_presuspend_undo_targets(map);
3243 /* pushback list is already flushed, so skip flush */
3250 * We need to be able to change a mapping table under a mounted
3251 * filesystem. For example we might want to move some data in
3252 * the background. Before the table can be swapped with
3253 * dm_bind_table, dm_suspend must be called to flush any in
3254 * flight bios and ensure that any further io gets deferred.
3257 * Suspend mechanism in request-based dm.
3259 * 1. Flush all I/Os by lock_fs() if needed.
3260 * 2. Stop dispatching any I/O by stopping the request_queue.
3261 * 3. Wait for all in-flight I/Os to be completed or requeued.
3263 * To abort suspend, start the request_queue.
3265 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
3267 struct dm_table *map = NULL;
3271 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3273 if (dm_suspended_md(md)) {
3278 if (dm_suspended_internally_md(md)) {
3279 /* already internally suspended, wait for internal resume */
3280 mutex_unlock(&md->suspend_lock);
3281 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3287 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3289 r = __dm_suspend(md, map, suspend_flags, TASK_INTERRUPTIBLE, DMF_SUSPENDED);
3293 dm_table_postsuspend_targets(map);
3296 mutex_unlock(&md->suspend_lock);
3300 static int __dm_resume(struct mapped_device *md, struct dm_table *map)
3303 int r = dm_table_resume_targets(map);
3311 * Flushing deferred I/Os must be done after targets are resumed
3312 * so that mapping of targets can work correctly.
3313 * Request-based dm is queueing the deferred I/Os in its request_queue.
3315 if (dm_request_based(md))
3316 start_queue(md->queue);
3323 int dm_resume(struct mapped_device *md)
3326 struct dm_table *map = NULL;
3330 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3332 if (!dm_suspended_md(md))
3335 if (dm_suspended_internally_md(md)) {
3336 /* already internally suspended, wait for internal resume */
3337 mutex_unlock(&md->suspend_lock);
3338 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3344 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3345 if (!map || !dm_table_get_size(map))
3348 r = __dm_resume(md, map);
3352 clear_bit(DMF_SUSPENDED, &md->flags);
3354 mutex_unlock(&md->suspend_lock);
3360 * Internal suspend/resume works like userspace-driven suspend. It waits
3361 * until all bios finish and prevents issuing new bios to the target drivers.
3362 * It may be used only from the kernel.
3365 static void __dm_internal_suspend(struct mapped_device *md, unsigned suspend_flags)
3367 struct dm_table *map = NULL;
3369 if (md->internal_suspend_count++)
3370 return; /* nested internal suspend */
3372 if (dm_suspended_md(md)) {
3373 set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3374 return; /* nest suspend */
3377 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3380 * Using TASK_UNINTERRUPTIBLE because only NOFLUSH internal suspend is
3381 * supported. Properly supporting a TASK_INTERRUPTIBLE internal suspend
3382 * would require changing .presuspend to return an error -- avoid this
3383 * until there is a need for more elaborate variants of internal suspend.
3385 (void) __dm_suspend(md, map, suspend_flags, TASK_UNINTERRUPTIBLE,
3386 DMF_SUSPENDED_INTERNALLY);
3388 dm_table_postsuspend_targets(map);
3391 static void __dm_internal_resume(struct mapped_device *md)
3393 BUG_ON(!md->internal_suspend_count);
3395 if (--md->internal_suspend_count)
3396 return; /* resume from nested internal suspend */
3398 if (dm_suspended_md(md))
3399 goto done; /* resume from nested suspend */
3402 * NOTE: existing callers don't need to call dm_table_resume_targets
3403 * (which may fail -- so best to avoid it for now by passing NULL map)
3405 (void) __dm_resume(md, NULL);
3408 clear_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3409 smp_mb__after_atomic();
3410 wake_up_bit(&md->flags, DMF_SUSPENDED_INTERNALLY);
3413 void dm_internal_suspend_noflush(struct mapped_device *md)
3415 mutex_lock(&md->suspend_lock);
3416 __dm_internal_suspend(md, DM_SUSPEND_NOFLUSH_FLAG);
3417 mutex_unlock(&md->suspend_lock);
3419 EXPORT_SYMBOL_GPL(dm_internal_suspend_noflush);
3421 void dm_internal_resume(struct mapped_device *md)
3423 mutex_lock(&md->suspend_lock);
3424 __dm_internal_resume(md);
3425 mutex_unlock(&md->suspend_lock);
3427 EXPORT_SYMBOL_GPL(dm_internal_resume);
3430 * Fast variants of internal suspend/resume hold md->suspend_lock,
3431 * which prevents interaction with userspace-driven suspend.
3434 void dm_internal_suspend_fast(struct mapped_device *md)
3436 mutex_lock(&md->suspend_lock);
3437 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3440 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3441 synchronize_srcu(&md->io_barrier);
3442 flush_workqueue(md->wq);
3443 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
3445 EXPORT_SYMBOL_GPL(dm_internal_suspend_fast);
3447 void dm_internal_resume_fast(struct mapped_device *md)
3449 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3455 mutex_unlock(&md->suspend_lock);
3457 EXPORT_SYMBOL_GPL(dm_internal_resume_fast);
3459 /*-----------------------------------------------------------------
3460 * Event notification.
3461 *---------------------------------------------------------------*/
3462 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
3465 char udev_cookie[DM_COOKIE_LENGTH];
3466 char *envp[] = { udev_cookie, NULL };
3469 return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
3471 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
3472 DM_COOKIE_ENV_VAR_NAME, cookie);
3473 return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
3478 uint32_t dm_next_uevent_seq(struct mapped_device *md)
3480 return atomic_add_return(1, &md->uevent_seq);
3483 uint32_t dm_get_event_nr(struct mapped_device *md)
3485 return atomic_read(&md->event_nr);
3488 int dm_wait_event(struct mapped_device *md, int event_nr)
3490 return wait_event_interruptible(md->eventq,
3491 (event_nr != atomic_read(&md->event_nr)));
3494 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
3496 unsigned long flags;
3498 spin_lock_irqsave(&md->uevent_lock, flags);
3499 list_add(elist, &md->uevent_list);
3500 spin_unlock_irqrestore(&md->uevent_lock, flags);
3504 * The gendisk is only valid as long as you have a reference
3507 struct gendisk *dm_disk(struct mapped_device *md)
3511 EXPORT_SYMBOL_GPL(dm_disk);
3513 struct kobject *dm_kobject(struct mapped_device *md)
3515 return &md->kobj_holder.kobj;
3518 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
3520 struct mapped_device *md;
3522 md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
3524 spin_lock(&_minor_lock);
3525 if (test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
3531 spin_unlock(&_minor_lock);
3536 int dm_suspended_md(struct mapped_device *md)
3538 return test_bit(DMF_SUSPENDED, &md->flags);
3541 int dm_suspended_internally_md(struct mapped_device *md)
3543 return test_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3546 int dm_test_deferred_remove_flag(struct mapped_device *md)
3548 return test_bit(DMF_DEFERRED_REMOVE, &md->flags);
3551 int dm_suspended(struct dm_target *ti)
3553 return dm_suspended_md(dm_table_get_md(ti->table));
3555 EXPORT_SYMBOL_GPL(dm_suspended);
3557 int dm_noflush_suspending(struct dm_target *ti)
3559 return __noflush_suspending(dm_table_get_md(ti->table));
3561 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
3563 struct dm_md_mempools *dm_alloc_md_mempools(struct mapped_device *md, unsigned type,
3564 unsigned integrity, unsigned per_bio_data_size)
3566 struct dm_md_mempools *pools = kzalloc(sizeof(*pools), GFP_KERNEL);
3567 struct kmem_cache *cachep = NULL;
3568 unsigned int pool_size = 0;
3569 unsigned int front_pad;
3574 type = filter_md_type(type, md);
3577 case DM_TYPE_BIO_BASED:
3579 pool_size = dm_get_reserved_bio_based_ios();
3580 front_pad = roundup(per_bio_data_size, __alignof__(struct dm_target_io)) + offsetof(struct dm_target_io, clone);
3582 case DM_TYPE_REQUEST_BASED:
3583 cachep = _rq_tio_cache;
3584 pool_size = dm_get_reserved_rq_based_ios();
3585 pools->rq_pool = mempool_create_slab_pool(pool_size, _rq_cache);
3586 if (!pools->rq_pool)
3588 /* fall through to setup remaining rq-based pools */
3589 case DM_TYPE_MQ_REQUEST_BASED:
3591 pool_size = dm_get_reserved_rq_based_ios();
3592 front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
3593 /* per_bio_data_size is not used. See __bind_mempools(). */
3594 WARN_ON(per_bio_data_size != 0);
3601 pools->io_pool = mempool_create_slab_pool(pool_size, cachep);
3602 if (!pools->io_pool)
3606 pools->bs = bioset_create_nobvec(pool_size, front_pad);
3610 if (integrity && bioset_integrity_create(pools->bs, pool_size))
3616 dm_free_md_mempools(pools);
3621 void dm_free_md_mempools(struct dm_md_mempools *pools)
3626 mempool_destroy(pools->io_pool);
3627 mempool_destroy(pools->rq_pool);
3630 bioset_free(pools->bs);
3635 static int dm_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
3638 struct mapped_device *md = bdev->bd_disk->private_data;
3639 const struct pr_ops *ops;
3640 struct dm_target *tgt;
3644 r = dm_get_live_table_for_ioctl(md, &tgt, &bdev, &mode, &srcu_idx);
3648 ops = bdev->bd_disk->fops->pr_ops;
3649 if (ops && ops->pr_register)
3650 r = ops->pr_register(bdev, old_key, new_key, flags);
3654 dm_put_live_table(md, srcu_idx);
3658 static int dm_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
3661 struct mapped_device *md = bdev->bd_disk->private_data;
3662 const struct pr_ops *ops;
3663 struct dm_target *tgt;
3667 r = dm_get_live_table_for_ioctl(md, &tgt, &bdev, &mode, &srcu_idx);
3671 ops = bdev->bd_disk->fops->pr_ops;
3672 if (ops && ops->pr_reserve)
3673 r = ops->pr_reserve(bdev, key, type, flags);
3677 dm_put_live_table(md, srcu_idx);
3681 static int dm_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
3683 struct mapped_device *md = bdev->bd_disk->private_data;
3684 const struct pr_ops *ops;
3685 struct dm_target *tgt;
3689 r = dm_get_live_table_for_ioctl(md, &tgt, &bdev, &mode, &srcu_idx);
3693 ops = bdev->bd_disk->fops->pr_ops;
3694 if (ops && ops->pr_release)
3695 r = ops->pr_release(bdev, key, type);
3699 dm_put_live_table(md, srcu_idx);
3703 static int dm_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
3704 enum pr_type type, bool abort)
3706 struct mapped_device *md = bdev->bd_disk->private_data;
3707 const struct pr_ops *ops;
3708 struct dm_target *tgt;
3712 r = dm_get_live_table_for_ioctl(md, &tgt, &bdev, &mode, &srcu_idx);
3716 ops = bdev->bd_disk->fops->pr_ops;
3717 if (ops && ops->pr_preempt)
3718 r = ops->pr_preempt(bdev, old_key, new_key, type, abort);
3722 dm_put_live_table(md, srcu_idx);
3726 static int dm_pr_clear(struct block_device *bdev, u64 key)
3728 struct mapped_device *md = bdev->bd_disk->private_data;
3729 const struct pr_ops *ops;
3730 struct dm_target *tgt;
3734 r = dm_get_live_table_for_ioctl(md, &tgt, &bdev, &mode, &srcu_idx);
3738 ops = bdev->bd_disk->fops->pr_ops;
3739 if (ops && ops->pr_clear)
3740 r = ops->pr_clear(bdev, key);
3744 dm_put_live_table(md, srcu_idx);
3748 static const struct pr_ops dm_pr_ops = {
3749 .pr_register = dm_pr_register,
3750 .pr_reserve = dm_pr_reserve,
3751 .pr_release = dm_pr_release,
3752 .pr_preempt = dm_pr_preempt,
3753 .pr_clear = dm_pr_clear,
3756 static const struct block_device_operations dm_blk_dops = {
3757 .open = dm_blk_open,
3758 .release = dm_blk_close,
3759 .ioctl = dm_blk_ioctl,
3760 .getgeo = dm_blk_getgeo,
3761 .pr_ops = &dm_pr_ops,
3762 .owner = THIS_MODULE
3768 module_init(dm_init);
3769 module_exit(dm_exit);
3771 module_param(major, uint, 0);
3772 MODULE_PARM_DESC(major, "The major number of the device mapper");
3774 module_param(reserved_bio_based_ios, uint, S_IRUGO | S_IWUSR);
3775 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
3777 module_param(reserved_rq_based_ios, uint, S_IRUGO | S_IWUSR);
3778 MODULE_PARM_DESC(reserved_rq_based_ios, "Reserved IOs in request-based mempools");
3780 module_param(use_blk_mq, bool, S_IRUGO | S_IWUSR);
3781 MODULE_PARM_DESC(use_blk_mq, "Use block multiqueue for request-based DM devices");
3783 MODULE_DESCRIPTION(DM_NAME " driver");
3784 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
3785 MODULE_LICENSE("GPL");