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.
10 #include "dm-uevent.h"
12 #include <linux/init.h>
13 #include <linux/module.h>
14 #include <linux/mutex.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>
24 #include <linux/vmalloc.h>
26 #define DM_MSG_PREFIX "core"
30 * ratelimit state to be used in DMXXX_LIMIT().
32 DEFINE_RATELIMIT_STATE(dm_ratelimit_state,
33 DEFAULT_RATELIMIT_INTERVAL,
34 DEFAULT_RATELIMIT_BURST);
35 EXPORT_SYMBOL(dm_ratelimit_state);
39 * Cookies are numeric values sent with CHANGE and REMOVE
40 * uevents while resuming, removing or renaming the device.
42 #define DM_COOKIE_ENV_VAR_NAME "DM_COOKIE"
43 #define DM_COOKIE_LENGTH 24
45 static const char *_name = DM_NAME;
47 static unsigned int major = 0;
48 static unsigned int _major = 0;
50 static DEFINE_IDR(_minor_idr);
52 static DEFINE_SPINLOCK(_minor_lock);
54 static void do_deferred_remove(struct work_struct *w);
56 static DECLARE_WORK(deferred_remove_work, do_deferred_remove);
58 static struct workqueue_struct *deferred_remove_workqueue;
61 * One of these is allocated per bio.
64 struct mapped_device *md;
68 unsigned long start_time;
69 spinlock_t endio_lock;
70 struct dm_stats_aux stats_aux;
73 #define MINOR_ALLOCED ((void *)-1)
76 * Bits for the md->flags field.
78 #define DMF_BLOCK_IO_FOR_SUSPEND 0
79 #define DMF_SUSPENDED 1
82 #define DMF_DELETING 4
83 #define DMF_NOFLUSH_SUSPENDING 5
84 #define DMF_DEFERRED_REMOVE 6
85 #define DMF_SUSPENDED_INTERNALLY 7
87 #define DM_NUMA_NODE NUMA_NO_NODE
88 static int dm_numa_node = DM_NUMA_NODE;
91 * For mempools pre-allocation at the table loading time.
93 struct dm_md_mempools {
100 struct list_head list;
102 struct dm_dev dm_dev;
105 static struct kmem_cache *_io_cache;
106 static struct kmem_cache *_rq_tio_cache;
107 static struct kmem_cache *_rq_cache;
110 * Bio-based DM's mempools' reserved IOs set by the user.
112 #define RESERVED_BIO_BASED_IOS 16
113 static unsigned reserved_bio_based_ios = RESERVED_BIO_BASED_IOS;
115 static int __dm_get_module_param_int(int *module_param, int min, int max)
117 int param = ACCESS_ONCE(*module_param);
118 int modified_param = 0;
119 bool modified = true;
122 modified_param = min;
123 else if (param > max)
124 modified_param = max;
129 (void)cmpxchg(module_param, param, modified_param);
130 param = modified_param;
136 unsigned __dm_get_module_param(unsigned *module_param,
137 unsigned def, unsigned max)
139 unsigned param = ACCESS_ONCE(*module_param);
140 unsigned modified_param = 0;
143 modified_param = def;
144 else if (param > max)
145 modified_param = max;
147 if (modified_param) {
148 (void)cmpxchg(module_param, param, modified_param);
149 param = modified_param;
155 unsigned dm_get_reserved_bio_based_ios(void)
157 return __dm_get_module_param(&reserved_bio_based_ios,
158 RESERVED_BIO_BASED_IOS, DM_RESERVED_MAX_IOS);
160 EXPORT_SYMBOL_GPL(dm_get_reserved_bio_based_ios);
162 static unsigned dm_get_numa_node(void)
164 return __dm_get_module_param_int(&dm_numa_node,
165 DM_NUMA_NODE, num_online_nodes() - 1);
168 static int __init local_init(void)
172 /* allocate a slab for the dm_ios */
173 _io_cache = KMEM_CACHE(dm_io, 0);
177 _rq_tio_cache = KMEM_CACHE(dm_rq_target_io, 0);
179 goto out_free_io_cache;
181 _rq_cache = kmem_cache_create("dm_old_clone_request", sizeof(struct request),
182 __alignof__(struct request), 0, NULL);
184 goto out_free_rq_tio_cache;
186 r = dm_uevent_init();
188 goto out_free_rq_cache;
190 deferred_remove_workqueue = alloc_workqueue("kdmremove", WQ_UNBOUND, 1);
191 if (!deferred_remove_workqueue) {
193 goto out_uevent_exit;
197 r = register_blkdev(_major, _name);
199 goto out_free_workqueue;
207 destroy_workqueue(deferred_remove_workqueue);
211 kmem_cache_destroy(_rq_cache);
212 out_free_rq_tio_cache:
213 kmem_cache_destroy(_rq_tio_cache);
215 kmem_cache_destroy(_io_cache);
220 static void local_exit(void)
222 flush_scheduled_work();
223 destroy_workqueue(deferred_remove_workqueue);
225 kmem_cache_destroy(_rq_cache);
226 kmem_cache_destroy(_rq_tio_cache);
227 kmem_cache_destroy(_io_cache);
228 unregister_blkdev(_major, _name);
233 DMINFO("cleaned up");
236 static int (*_inits[])(void) __initdata = {
247 static void (*_exits[])(void) = {
258 static int __init dm_init(void)
260 const int count = ARRAY_SIZE(_inits);
264 for (i = 0; i < count; i++) {
279 static void __exit dm_exit(void)
281 int i = ARRAY_SIZE(_exits);
287 * Should be empty by this point.
289 idr_destroy(&_minor_idr);
293 * Block device functions
295 int dm_deleting_md(struct mapped_device *md)
297 return test_bit(DMF_DELETING, &md->flags);
300 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
302 struct mapped_device *md;
304 spin_lock(&_minor_lock);
306 md = bdev->bd_disk->private_data;
310 if (test_bit(DMF_FREEING, &md->flags) ||
311 dm_deleting_md(md)) {
317 atomic_inc(&md->open_count);
319 spin_unlock(&_minor_lock);
321 return md ? 0 : -ENXIO;
324 static void dm_blk_close(struct gendisk *disk, fmode_t mode)
326 struct mapped_device *md;
328 spin_lock(&_minor_lock);
330 md = disk->private_data;
334 if (atomic_dec_and_test(&md->open_count) &&
335 (test_bit(DMF_DEFERRED_REMOVE, &md->flags)))
336 queue_work(deferred_remove_workqueue, &deferred_remove_work);
340 spin_unlock(&_minor_lock);
343 int dm_open_count(struct mapped_device *md)
345 return atomic_read(&md->open_count);
349 * Guarantees nothing is using the device before it's deleted.
351 int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
355 spin_lock(&_minor_lock);
357 if (dm_open_count(md)) {
360 set_bit(DMF_DEFERRED_REMOVE, &md->flags);
361 } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
364 set_bit(DMF_DELETING, &md->flags);
366 spin_unlock(&_minor_lock);
371 int dm_cancel_deferred_remove(struct mapped_device *md)
375 spin_lock(&_minor_lock);
377 if (test_bit(DMF_DELETING, &md->flags))
380 clear_bit(DMF_DEFERRED_REMOVE, &md->flags);
382 spin_unlock(&_minor_lock);
387 static void do_deferred_remove(struct work_struct *w)
389 dm_deferred_remove();
392 sector_t dm_get_size(struct mapped_device *md)
394 return get_capacity(md->disk);
397 struct request_queue *dm_get_md_queue(struct mapped_device *md)
402 struct dm_stats *dm_get_stats(struct mapped_device *md)
407 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
409 struct mapped_device *md = bdev->bd_disk->private_data;
411 return dm_get_geometry(md, geo);
414 static int dm_grab_bdev_for_ioctl(struct mapped_device *md,
415 struct block_device **bdev,
418 struct dm_target *tgt;
419 struct dm_table *map;
424 map = dm_get_live_table(md, &srcu_idx);
425 if (!map || !dm_table_get_size(map))
428 /* We only support devices that have a single target */
429 if (dm_table_get_num_targets(map) != 1)
432 tgt = dm_table_get_target(map, 0);
433 if (!tgt->type->prepare_ioctl)
436 if (dm_suspended_md(md)) {
441 r = tgt->type->prepare_ioctl(tgt, bdev, mode);
446 dm_put_live_table(md, srcu_idx);
450 dm_put_live_table(md, srcu_idx);
451 if (r == -ENOTCONN && !fatal_signal_pending(current)) {
458 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
459 unsigned int cmd, unsigned long arg)
461 struct mapped_device *md = bdev->bd_disk->private_data;
464 r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
470 * Target determined this ioctl is being issued against
471 * a logical partition of the parent bdev; so extra
472 * validation is needed.
474 r = scsi_verify_blk_ioctl(NULL, cmd);
479 r = __blkdev_driver_ioctl(bdev, mode, cmd, arg);
485 static struct dm_io *alloc_io(struct mapped_device *md)
487 return mempool_alloc(md->io_pool, GFP_NOIO);
490 static void free_io(struct mapped_device *md, struct dm_io *io)
492 mempool_free(io, md->io_pool);
495 static void free_tio(struct dm_target_io *tio)
497 bio_put(&tio->clone);
500 int md_in_flight(struct mapped_device *md)
502 return atomic_read(&md->pending[READ]) +
503 atomic_read(&md->pending[WRITE]);
506 static void start_io_acct(struct dm_io *io)
508 struct mapped_device *md = io->md;
509 struct bio *bio = io->bio;
511 int rw = bio_data_dir(bio);
513 io->start_time = jiffies;
515 cpu = part_stat_lock();
516 part_round_stats(cpu, &dm_disk(md)->part0);
518 atomic_set(&dm_disk(md)->part0.in_flight[rw],
519 atomic_inc_return(&md->pending[rw]));
521 if (unlikely(dm_stats_used(&md->stats)))
522 dm_stats_account_io(&md->stats, bio_data_dir(bio),
523 bio->bi_iter.bi_sector, bio_sectors(bio),
524 false, 0, &io->stats_aux);
527 static void end_io_acct(struct mapped_device *md, struct bio *bio,
528 unsigned long start_time, struct dm_stats_aux *stats_aux)
530 unsigned long duration = jiffies - start_time;
532 int rw = bio_data_dir(bio);
534 generic_end_io_acct(rw, &dm_disk(md)->part0, start_time);
536 if (unlikely(dm_stats_used(&md->stats)))
537 dm_stats_account_io(&md->stats, bio_data_dir(bio),
538 bio->bi_iter.bi_sector, bio_sectors(bio),
539 true, duration, stats_aux);
542 * After this is decremented the bio must not be touched if it is
545 pending = atomic_dec_return(&md->pending[rw]);
546 atomic_set(&dm_disk(md)->part0.in_flight[rw], pending);
547 pending += atomic_read(&md->pending[rw^0x1]);
549 /* nudge anyone waiting on suspend queue */
555 * Add the bio to the list of deferred io.
557 static void queue_io(struct mapped_device *md, struct bio *bio)
561 spin_lock_irqsave(&md->deferred_lock, flags);
562 bio_list_add(&md->deferred, bio);
563 spin_unlock_irqrestore(&md->deferred_lock, flags);
564 queue_work(md->wq, &md->work);
568 * Everyone (including functions in this file), should use this
569 * function to access the md->map field, and make sure they call
570 * dm_put_live_table() when finished.
572 struct dm_table *dm_get_live_table(struct mapped_device *md, int *srcu_idx) __acquires(md->io_barrier)
574 *srcu_idx = srcu_read_lock(&md->io_barrier);
576 return srcu_dereference(md->map, &md->io_barrier);
579 void dm_put_live_table(struct mapped_device *md, int srcu_idx) __releases(md->io_barrier)
581 srcu_read_unlock(&md->io_barrier, srcu_idx);
584 void dm_sync_table(struct mapped_device *md)
586 synchronize_srcu(&md->io_barrier);
587 synchronize_rcu_expedited();
591 * A fast alternative to dm_get_live_table/dm_put_live_table.
592 * The caller must not block between these two functions.
594 static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
597 return rcu_dereference(md->map);
600 static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
606 * Open a table device so we can use it as a map destination.
608 static int open_table_device(struct table_device *td, dev_t dev,
609 struct mapped_device *md)
611 static char *_claim_ptr = "I belong to device-mapper";
612 struct block_device *bdev;
616 BUG_ON(td->dm_dev.bdev);
618 bdev = blkdev_get_by_dev(dev, td->dm_dev.mode | FMODE_EXCL, _claim_ptr);
620 return PTR_ERR(bdev);
622 r = bd_link_disk_holder(bdev, dm_disk(md));
624 blkdev_put(bdev, td->dm_dev.mode | FMODE_EXCL);
628 td->dm_dev.bdev = bdev;
633 * Close a table device that we've been using.
635 static void close_table_device(struct table_device *td, struct mapped_device *md)
637 if (!td->dm_dev.bdev)
640 bd_unlink_disk_holder(td->dm_dev.bdev, dm_disk(md));
641 blkdev_put(td->dm_dev.bdev, td->dm_dev.mode | FMODE_EXCL);
642 td->dm_dev.bdev = NULL;
645 static struct table_device *find_table_device(struct list_head *l, dev_t dev,
647 struct table_device *td;
649 list_for_each_entry(td, l, list)
650 if (td->dm_dev.bdev->bd_dev == dev && td->dm_dev.mode == mode)
656 int dm_get_table_device(struct mapped_device *md, dev_t dev, fmode_t mode,
657 struct dm_dev **result) {
659 struct table_device *td;
661 mutex_lock(&md->table_devices_lock);
662 td = find_table_device(&md->table_devices, dev, mode);
664 td = kmalloc_node(sizeof(*td), GFP_KERNEL, md->numa_node_id);
666 mutex_unlock(&md->table_devices_lock);
670 td->dm_dev.mode = mode;
671 td->dm_dev.bdev = NULL;
673 if ((r = open_table_device(td, dev, md))) {
674 mutex_unlock(&md->table_devices_lock);
679 format_dev_t(td->dm_dev.name, dev);
681 atomic_set(&td->count, 0);
682 list_add(&td->list, &md->table_devices);
684 atomic_inc(&td->count);
685 mutex_unlock(&md->table_devices_lock);
687 *result = &td->dm_dev;
690 EXPORT_SYMBOL_GPL(dm_get_table_device);
692 void dm_put_table_device(struct mapped_device *md, struct dm_dev *d)
694 struct table_device *td = container_of(d, struct table_device, dm_dev);
696 mutex_lock(&md->table_devices_lock);
697 if (atomic_dec_and_test(&td->count)) {
698 close_table_device(td, md);
702 mutex_unlock(&md->table_devices_lock);
704 EXPORT_SYMBOL(dm_put_table_device);
706 static void free_table_devices(struct list_head *devices)
708 struct list_head *tmp, *next;
710 list_for_each_safe(tmp, next, devices) {
711 struct table_device *td = list_entry(tmp, struct table_device, list);
713 DMWARN("dm_destroy: %s still exists with %d references",
714 td->dm_dev.name, atomic_read(&td->count));
720 * Get the geometry associated with a dm device
722 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
730 * Set the geometry of a device.
732 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
734 sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
736 if (geo->start > sz) {
737 DMWARN("Start sector is beyond the geometry limits.");
746 /*-----------------------------------------------------------------
748 * A more elegant soln is in the works that uses the queue
749 * merge fn, unfortunately there are a couple of changes to
750 * the block layer that I want to make for this. So in the
751 * interests of getting something for people to use I give
752 * you this clearly demarcated crap.
753 *---------------------------------------------------------------*/
755 static int __noflush_suspending(struct mapped_device *md)
757 return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
761 * Decrements the number of outstanding ios that a bio has been
762 * cloned into, completing the original io if necc.
764 static void dec_pending(struct dm_io *io, int error)
769 struct mapped_device *md = io->md;
770 unsigned long start_time = 0;
771 struct dm_stats_aux stats_aux;
773 /* Push-back supersedes any I/O errors */
774 if (unlikely(error)) {
775 spin_lock_irqsave(&io->endio_lock, flags);
776 if (!(io->error > 0 && __noflush_suspending(md)))
778 spin_unlock_irqrestore(&io->endio_lock, flags);
781 if (atomic_dec_and_test(&io->io_count)) {
782 if (io->error == DM_ENDIO_REQUEUE) {
784 * Target requested pushing back the I/O.
786 spin_lock_irqsave(&md->deferred_lock, flags);
787 if (__noflush_suspending(md))
788 bio_list_add_head(&md->deferred, io->bio);
790 /* noflush suspend was interrupted. */
792 spin_unlock_irqrestore(&md->deferred_lock, flags);
795 io_error = io->error;
797 start_time = io->start_time;
798 stats_aux = io->stats_aux;
800 end_io_acct(md, bio, start_time, &stats_aux);
802 if (io_error == DM_ENDIO_REQUEUE)
805 if ((bio->bi_opf & REQ_PREFLUSH) && bio->bi_iter.bi_size) {
807 * Preflush done for flush with data, reissue
808 * without REQ_PREFLUSH.
810 bio->bi_opf &= ~REQ_PREFLUSH;
813 /* done with normal IO or empty flush */
814 trace_block_bio_complete(md->queue, bio, io_error);
816 bio->bi_error = io_error;
822 void disable_write_same(struct mapped_device *md)
824 struct queue_limits *limits = dm_get_queue_limits(md);
826 /* device doesn't really support WRITE SAME, disable it */
827 limits->max_write_same_sectors = 0;
830 static void clone_endio(struct bio *bio)
832 int error = bio->bi_error;
834 struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
835 struct dm_io *io = tio->io;
836 struct mapped_device *md = tio->io->md;
837 dm_endio_fn endio = tio->ti->type->end_io;
840 r = endio(tio->ti, bio, error);
841 if (r < 0 || r == DM_ENDIO_REQUEUE)
843 * error and requeue request are handled
847 else if (r == DM_ENDIO_INCOMPLETE)
848 /* The target will handle the io */
851 DMWARN("unimplemented target endio return value: %d", r);
856 if (unlikely(r == -EREMOTEIO && (bio_op(bio) == REQ_OP_WRITE_SAME) &&
857 !bdev_get_queue(bio->bi_bdev)->limits.max_write_same_sectors))
858 disable_write_same(md);
861 dec_pending(io, error);
865 * Return maximum size of I/O possible at the supplied sector up to the current
868 static sector_t max_io_len_target_boundary(sector_t sector, struct dm_target *ti)
870 sector_t target_offset = dm_target_offset(ti, sector);
872 return ti->len - target_offset;
875 static sector_t max_io_len(sector_t sector, struct dm_target *ti)
877 sector_t len = max_io_len_target_boundary(sector, ti);
878 sector_t offset, max_len;
881 * Does the target need to split even further?
883 if (ti->max_io_len) {
884 offset = dm_target_offset(ti, sector);
885 if (unlikely(ti->max_io_len & (ti->max_io_len - 1)))
886 max_len = sector_div(offset, ti->max_io_len);
888 max_len = offset & (ti->max_io_len - 1);
889 max_len = ti->max_io_len - max_len;
898 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
900 if (len > UINT_MAX) {
901 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
902 (unsigned long long)len, UINT_MAX);
903 ti->error = "Maximum size of target IO is too large";
907 ti->max_io_len = (uint32_t) len;
911 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
913 static long dm_blk_direct_access(struct block_device *bdev, sector_t sector,
914 void **kaddr, pfn_t *pfn, long size)
916 struct mapped_device *md = bdev->bd_disk->private_data;
917 struct dm_table *map;
918 struct dm_target *ti;
920 long len, ret = -EIO;
922 map = dm_get_live_table(md, &srcu_idx);
926 ti = dm_table_find_target(map, sector);
927 if (!dm_target_is_valid(ti))
930 len = max_io_len(sector, ti) << SECTOR_SHIFT;
931 size = min(len, size);
933 if (ti->type->direct_access)
934 ret = ti->type->direct_access(ti, sector, kaddr, pfn, size);
936 dm_put_live_table(md, srcu_idx);
937 return min(ret, size);
941 * A target may call dm_accept_partial_bio only from the map routine. It is
942 * allowed for all bio types except REQ_PREFLUSH.
944 * dm_accept_partial_bio informs the dm that the target only wants to process
945 * additional n_sectors sectors of the bio and the rest of the data should be
946 * sent in a next bio.
948 * A diagram that explains the arithmetics:
949 * +--------------------+---------------+-------+
951 * +--------------------+---------------+-------+
953 * <-------------- *tio->len_ptr --------------->
954 * <------- bi_size ------->
957 * Region 1 was already iterated over with bio_advance or similar function.
958 * (it may be empty if the target doesn't use bio_advance)
959 * Region 2 is the remaining bio size that the target wants to process.
960 * (it may be empty if region 1 is non-empty, although there is no reason
962 * The target requires that region 3 is to be sent in the next bio.
964 * If the target wants to receive multiple copies of the bio (via num_*bios, etc),
965 * the partially processed part (the sum of regions 1+2) must be the same for all
968 void dm_accept_partial_bio(struct bio *bio, unsigned n_sectors)
970 struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
971 unsigned bi_size = bio->bi_iter.bi_size >> SECTOR_SHIFT;
972 BUG_ON(bio->bi_opf & REQ_PREFLUSH);
973 BUG_ON(bi_size > *tio->len_ptr);
974 BUG_ON(n_sectors > bi_size);
975 *tio->len_ptr -= bi_size - n_sectors;
976 bio->bi_iter.bi_size = n_sectors << SECTOR_SHIFT;
978 EXPORT_SYMBOL_GPL(dm_accept_partial_bio);
981 * Flush current->bio_list when the target map method blocks.
982 * This fixes deadlocks in snapshot and possibly in other targets.
985 struct blk_plug plug;
986 struct blk_plug_cb cb;
989 static void flush_current_bio_list(struct blk_plug_cb *cb, bool from_schedule)
991 struct dm_offload *o = container_of(cb, struct dm_offload, cb);
992 struct bio_list list;
996 INIT_LIST_HEAD(&o->cb.list);
998 if (unlikely(!current->bio_list))
1001 for (i = 0; i < 2; i++) {
1002 list = current->bio_list[i];
1003 bio_list_init(¤t->bio_list[i]);
1005 while ((bio = bio_list_pop(&list))) {
1006 struct bio_set *bs = bio->bi_pool;
1007 if (unlikely(!bs) || bs == fs_bio_set) {
1008 bio_list_add(¤t->bio_list[i], bio);
1012 spin_lock(&bs->rescue_lock);
1013 bio_list_add(&bs->rescue_list, bio);
1014 queue_work(bs->rescue_workqueue, &bs->rescue_work);
1015 spin_unlock(&bs->rescue_lock);
1020 static void dm_offload_start(struct dm_offload *o)
1022 blk_start_plug(&o->plug);
1023 o->cb.callback = flush_current_bio_list;
1024 list_add(&o->cb.list, ¤t->plug->cb_list);
1027 static void dm_offload_end(struct dm_offload *o)
1029 list_del(&o->cb.list);
1030 blk_finish_plug(&o->plug);
1033 static void __map_bio(struct dm_target_io *tio)
1037 struct dm_offload o;
1038 struct bio *clone = &tio->clone;
1039 struct dm_target *ti = tio->ti;
1041 clone->bi_end_io = clone_endio;
1044 * Map the clone. If r == 0 we don't need to do
1045 * anything, the target has assumed ownership of
1048 atomic_inc(&tio->io->io_count);
1049 sector = clone->bi_iter.bi_sector;
1051 dm_offload_start(&o);
1052 r = ti->type->map(ti, clone);
1055 if (r == DM_MAPIO_REMAPPED) {
1056 /* the bio has been remapped so dispatch it */
1058 trace_block_bio_remap(bdev_get_queue(clone->bi_bdev), clone,
1059 tio->io->bio->bi_bdev->bd_dev, sector);
1061 generic_make_request(clone);
1062 } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1063 /* error the io and bail out, or requeue it if needed */
1064 dec_pending(tio->io, r);
1066 } else if (r != DM_MAPIO_SUBMITTED) {
1067 DMWARN("unimplemented target map return value: %d", r);
1073 struct mapped_device *md;
1074 struct dm_table *map;
1078 unsigned sector_count;
1081 static void bio_setup_sector(struct bio *bio, sector_t sector, unsigned len)
1083 bio->bi_iter.bi_sector = sector;
1084 bio->bi_iter.bi_size = to_bytes(len);
1088 * Creates a bio that consists of range of complete bvecs.
1090 static int clone_bio(struct dm_target_io *tio, struct bio *bio,
1091 sector_t sector, unsigned len)
1093 struct bio *clone = &tio->clone;
1095 __bio_clone_fast(clone, bio);
1097 if (bio_integrity(bio)) {
1098 int r = bio_integrity_clone(clone, bio, GFP_NOIO);
1103 bio_advance(clone, to_bytes(sector - clone->bi_iter.bi_sector));
1104 clone->bi_iter.bi_size = to_bytes(len);
1106 if (bio_integrity(bio))
1107 bio_integrity_trim(clone, 0, len);
1112 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1113 struct dm_target *ti,
1114 unsigned target_bio_nr)
1116 struct dm_target_io *tio;
1119 clone = bio_alloc_bioset(GFP_NOIO, 0, ci->md->bs);
1120 tio = container_of(clone, struct dm_target_io, clone);
1124 tio->target_bio_nr = target_bio_nr;
1129 static void __clone_and_map_simple_bio(struct clone_info *ci,
1130 struct dm_target *ti,
1131 unsigned target_bio_nr, unsigned *len)
1133 struct dm_target_io *tio = alloc_tio(ci, ti, target_bio_nr);
1134 struct bio *clone = &tio->clone;
1138 __bio_clone_fast(clone, ci->bio);
1140 bio_setup_sector(clone, ci->sector, *len);
1145 static void __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1146 unsigned num_bios, unsigned *len)
1148 unsigned target_bio_nr;
1150 for (target_bio_nr = 0; target_bio_nr < num_bios; target_bio_nr++)
1151 __clone_and_map_simple_bio(ci, ti, target_bio_nr, len);
1154 static int __send_empty_flush(struct clone_info *ci)
1156 unsigned target_nr = 0;
1157 struct dm_target *ti;
1159 BUG_ON(bio_has_data(ci->bio));
1160 while ((ti = dm_table_get_target(ci->map, target_nr++)))
1161 __send_duplicate_bios(ci, ti, ti->num_flush_bios, NULL);
1166 static int __clone_and_map_data_bio(struct clone_info *ci, struct dm_target *ti,
1167 sector_t sector, unsigned *len)
1169 struct bio *bio = ci->bio;
1170 struct dm_target_io *tio;
1171 unsigned target_bio_nr;
1172 unsigned num_target_bios = 1;
1176 * Does the target want to receive duplicate copies of the bio?
1178 if (bio_data_dir(bio) == WRITE && ti->num_write_bios)
1179 num_target_bios = ti->num_write_bios(ti, bio);
1181 for (target_bio_nr = 0; target_bio_nr < num_target_bios; target_bio_nr++) {
1182 tio = alloc_tio(ci, ti, target_bio_nr);
1184 r = clone_bio(tio, bio, sector, *len);
1195 typedef unsigned (*get_num_bios_fn)(struct dm_target *ti);
1197 static unsigned get_num_discard_bios(struct dm_target *ti)
1199 return ti->num_discard_bios;
1202 static unsigned get_num_write_same_bios(struct dm_target *ti)
1204 return ti->num_write_same_bios;
1207 typedef bool (*is_split_required_fn)(struct dm_target *ti);
1209 static bool is_split_required_for_discard(struct dm_target *ti)
1211 return ti->split_discard_bios;
1214 static int __send_changing_extent_only(struct clone_info *ci,
1215 get_num_bios_fn get_num_bios,
1216 is_split_required_fn is_split_required)
1218 struct dm_target *ti;
1223 ti = dm_table_find_target(ci->map, ci->sector);
1224 if (!dm_target_is_valid(ti))
1228 * Even though the device advertised support for this type of
1229 * request, that does not mean every target supports it, and
1230 * reconfiguration might also have changed that since the
1231 * check was performed.
1233 num_bios = get_num_bios ? get_num_bios(ti) : 0;
1237 if (is_split_required && !is_split_required(ti))
1238 len = min((sector_t)ci->sector_count, max_io_len_target_boundary(ci->sector, ti));
1240 len = min((sector_t)ci->sector_count, max_io_len(ci->sector, ti));
1242 __send_duplicate_bios(ci, ti, num_bios, &len);
1245 } while (ci->sector_count -= len);
1250 static int __send_discard(struct clone_info *ci)
1252 return __send_changing_extent_only(ci, get_num_discard_bios,
1253 is_split_required_for_discard);
1256 static int __send_write_same(struct clone_info *ci)
1258 return __send_changing_extent_only(ci, get_num_write_same_bios, NULL);
1262 * Select the correct strategy for processing a non-flush bio.
1264 static int __split_and_process_non_flush(struct clone_info *ci)
1266 struct bio *bio = ci->bio;
1267 struct dm_target *ti;
1271 if (unlikely(bio_op(bio) == REQ_OP_DISCARD))
1272 return __send_discard(ci);
1273 else if (unlikely(bio_op(bio) == REQ_OP_WRITE_SAME))
1274 return __send_write_same(ci);
1276 ti = dm_table_find_target(ci->map, ci->sector);
1277 if (!dm_target_is_valid(ti))
1280 len = min_t(sector_t, max_io_len(ci->sector, ti), ci->sector_count);
1282 r = __clone_and_map_data_bio(ci, ti, ci->sector, &len);
1287 ci->sector_count -= len;
1293 * Entry point to split a bio into clones and submit them to the targets.
1295 static void __split_and_process_bio(struct mapped_device *md,
1296 struct dm_table *map, struct bio *bio)
1298 struct clone_info ci;
1301 if (unlikely(!map)) {
1308 ci.io = alloc_io(md);
1310 atomic_set(&ci.io->io_count, 1);
1313 spin_lock_init(&ci.io->endio_lock);
1314 ci.sector = bio->bi_iter.bi_sector;
1316 start_io_acct(ci.io);
1318 if (bio->bi_opf & REQ_PREFLUSH) {
1319 ci.bio = &ci.md->flush_bio;
1320 ci.sector_count = 0;
1321 error = __send_empty_flush(&ci);
1322 /* dec_pending submits any data associated with flush */
1325 ci.sector_count = bio_sectors(bio);
1326 while (ci.sector_count && !error)
1327 error = __split_and_process_non_flush(&ci);
1330 /* drop the extra reference count */
1331 dec_pending(ci.io, error);
1333 /*-----------------------------------------------------------------
1335 *---------------------------------------------------------------*/
1338 * The request function that just remaps the bio built up by
1341 static blk_qc_t dm_make_request(struct request_queue *q, struct bio *bio)
1343 int rw = bio_data_dir(bio);
1344 struct mapped_device *md = q->queuedata;
1346 struct dm_table *map;
1348 map = dm_get_live_table(md, &srcu_idx);
1350 generic_start_io_acct(rw, bio_sectors(bio), &dm_disk(md)->part0);
1352 /* if we're suspended, we have to queue this io for later */
1353 if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
1354 dm_put_live_table(md, srcu_idx);
1356 if (!(bio->bi_opf & REQ_RAHEAD))
1360 return BLK_QC_T_NONE;
1363 __split_and_process_bio(md, map, bio);
1364 dm_put_live_table(md, srcu_idx);
1365 return BLK_QC_T_NONE;
1368 static int dm_any_congested(void *congested_data, int bdi_bits)
1371 struct mapped_device *md = congested_data;
1372 struct dm_table *map;
1374 if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
1375 if (dm_request_based(md)) {
1377 * With request-based DM we only need to check the
1378 * top-level queue for congestion.
1380 r = md->queue->backing_dev_info.wb.state & bdi_bits;
1382 map = dm_get_live_table_fast(md);
1384 r = dm_table_any_congested(map, bdi_bits);
1385 dm_put_live_table_fast(md);
1392 /*-----------------------------------------------------------------
1393 * An IDR is used to keep track of allocated minor numbers.
1394 *---------------------------------------------------------------*/
1395 static void free_minor(int minor)
1397 spin_lock(&_minor_lock);
1398 idr_remove(&_minor_idr, minor);
1399 spin_unlock(&_minor_lock);
1403 * See if the device with a specific minor # is free.
1405 static int specific_minor(int minor)
1409 if (minor >= (1 << MINORBITS))
1412 idr_preload(GFP_KERNEL);
1413 spin_lock(&_minor_lock);
1415 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
1417 spin_unlock(&_minor_lock);
1420 return r == -ENOSPC ? -EBUSY : r;
1424 static int next_free_minor(int *minor)
1428 idr_preload(GFP_KERNEL);
1429 spin_lock(&_minor_lock);
1431 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
1433 spin_unlock(&_minor_lock);
1441 static const struct block_device_operations dm_blk_dops;
1443 static void dm_wq_work(struct work_struct *work);
1445 void dm_init_md_queue(struct mapped_device *md)
1448 * Request-based dm devices cannot be stacked on top of bio-based dm
1449 * devices. The type of this dm device may not have been decided yet.
1450 * The type is decided at the first table loading time.
1451 * To prevent problematic device stacking, clear the queue flag
1452 * for request stacking support until then.
1454 * This queue is new, so no concurrency on the queue_flags.
1456 queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
1459 * Initialize data that will only be used by a non-blk-mq DM queue
1460 * - must do so here (in alloc_dev callchain) before queue is used
1462 md->queue->queuedata = md;
1465 void dm_init_normal_md_queue(struct mapped_device *md)
1467 md->use_blk_mq = false;
1468 dm_init_md_queue(md);
1471 * Initialize aspects of queue that aren't relevant for blk-mq
1473 md->queue->backing_dev_info.congested_data = md;
1474 md->queue->backing_dev_info.congested_fn = dm_any_congested;
1475 blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
1478 static void cleanup_mapped_device(struct mapped_device *md)
1481 destroy_workqueue(md->wq);
1482 if (md->kworker_task)
1483 kthread_stop(md->kworker_task);
1484 mempool_destroy(md->io_pool);
1485 mempool_destroy(md->rq_pool);
1487 bioset_free(md->bs);
1490 spin_lock(&_minor_lock);
1491 md->disk->private_data = NULL;
1492 spin_unlock(&_minor_lock);
1493 del_gendisk(md->disk);
1498 blk_cleanup_queue(md->queue);
1500 cleanup_srcu_struct(&md->io_barrier);
1507 dm_mq_cleanup_mapped_device(md);
1511 * Allocate and initialise a blank device with a given minor.
1513 static struct mapped_device *alloc_dev(int minor)
1515 int r, numa_node_id = dm_get_numa_node();
1516 struct mapped_device *md;
1519 md = vzalloc_node(sizeof(*md), numa_node_id);
1521 DMWARN("unable to allocate device, out of memory.");
1525 if (!try_module_get(THIS_MODULE))
1526 goto bad_module_get;
1528 /* get a minor number for the dev */
1529 if (minor == DM_ANY_MINOR)
1530 r = next_free_minor(&minor);
1532 r = specific_minor(minor);
1536 r = init_srcu_struct(&md->io_barrier);
1538 goto bad_io_barrier;
1540 md->numa_node_id = numa_node_id;
1541 md->use_blk_mq = dm_use_blk_mq_default();
1542 md->init_tio_pdu = false;
1543 md->type = DM_TYPE_NONE;
1544 mutex_init(&md->suspend_lock);
1545 mutex_init(&md->type_lock);
1546 mutex_init(&md->table_devices_lock);
1547 spin_lock_init(&md->deferred_lock);
1548 atomic_set(&md->holders, 1);
1549 atomic_set(&md->open_count, 0);
1550 atomic_set(&md->event_nr, 0);
1551 atomic_set(&md->uevent_seq, 0);
1552 INIT_LIST_HEAD(&md->uevent_list);
1553 INIT_LIST_HEAD(&md->table_devices);
1554 spin_lock_init(&md->uevent_lock);
1556 md->queue = blk_alloc_queue_node(GFP_KERNEL, numa_node_id);
1560 dm_init_md_queue(md);
1562 * default to bio-based required ->make_request_fn until DM
1563 * table is loaded and md->type established. If request-based
1564 * table is loaded: blk-mq will override accordingly.
1566 blk_queue_make_request(md->queue, dm_make_request);
1568 md->disk = alloc_disk_node(1, numa_node_id);
1572 atomic_set(&md->pending[0], 0);
1573 atomic_set(&md->pending[1], 0);
1574 init_waitqueue_head(&md->wait);
1575 INIT_WORK(&md->work, dm_wq_work);
1576 init_waitqueue_head(&md->eventq);
1577 init_completion(&md->kobj_holder.completion);
1578 md->kworker_task = NULL;
1580 md->disk->major = _major;
1581 md->disk->first_minor = minor;
1582 md->disk->fops = &dm_blk_dops;
1583 md->disk->queue = md->queue;
1584 md->disk->private_data = md;
1585 sprintf(md->disk->disk_name, "dm-%d", minor);
1587 format_dev_t(md->name, MKDEV(_major, minor));
1589 md->wq = alloc_workqueue("kdmflush", WQ_MEM_RECLAIM, 0);
1593 md->bdev = bdget_disk(md->disk, 0);
1597 bio_init(&md->flush_bio);
1598 md->flush_bio.bi_bdev = md->bdev;
1599 bio_set_op_attrs(&md->flush_bio, REQ_OP_WRITE, WRITE_FLUSH);
1601 dm_stats_init(&md->stats);
1603 /* Populate the mapping, nobody knows we exist yet */
1604 spin_lock(&_minor_lock);
1605 old_md = idr_replace(&_minor_idr, md, minor);
1606 spin_unlock(&_minor_lock);
1608 BUG_ON(old_md != MINOR_ALLOCED);
1613 cleanup_mapped_device(md);
1617 module_put(THIS_MODULE);
1623 static void unlock_fs(struct mapped_device *md);
1625 static void free_dev(struct mapped_device *md)
1627 int minor = MINOR(disk_devt(md->disk));
1631 cleanup_mapped_device(md);
1633 free_table_devices(&md->table_devices);
1634 dm_stats_cleanup(&md->stats);
1637 module_put(THIS_MODULE);
1641 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
1643 struct dm_md_mempools *p = dm_table_get_md_mempools(t);
1646 /* The md already has necessary mempools. */
1647 if (dm_table_bio_based(t)) {
1649 * Reload bioset because front_pad may have changed
1650 * because a different table was loaded.
1652 bioset_free(md->bs);
1657 * There's no need to reload with request-based dm
1658 * because the size of front_pad doesn't change.
1659 * Note for future: If you are to reload bioset,
1660 * prep-ed requests in the queue may refer
1661 * to bio from the old bioset, so you must walk
1662 * through the queue to unprep.
1667 BUG_ON(!p || md->io_pool || md->rq_pool || md->bs);
1669 md->io_pool = p->io_pool;
1671 md->rq_pool = p->rq_pool;
1677 /* mempool bind completed, no longer need any mempools in the table */
1678 dm_table_free_md_mempools(t);
1682 * Bind a table to the device.
1684 static void event_callback(void *context)
1686 unsigned long flags;
1688 struct mapped_device *md = (struct mapped_device *) context;
1690 spin_lock_irqsave(&md->uevent_lock, flags);
1691 list_splice_init(&md->uevent_list, &uevents);
1692 spin_unlock_irqrestore(&md->uevent_lock, flags);
1694 dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
1696 atomic_inc(&md->event_nr);
1697 wake_up(&md->eventq);
1701 * Protected by md->suspend_lock obtained by dm_swap_table().
1703 static void __set_size(struct mapped_device *md, sector_t size)
1705 set_capacity(md->disk, size);
1707 i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
1711 * Returns old map, which caller must destroy.
1713 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
1714 struct queue_limits *limits)
1716 struct dm_table *old_map;
1717 struct request_queue *q = md->queue;
1720 lockdep_assert_held(&md->suspend_lock);
1722 size = dm_table_get_size(t);
1725 * Wipe any geometry if the size of the table changed.
1727 if (size != dm_get_size(md))
1728 memset(&md->geometry, 0, sizeof(md->geometry));
1730 __set_size(md, size);
1732 dm_table_event_callback(t, event_callback, md);
1735 * The queue hasn't been stopped yet, if the old table type wasn't
1736 * for request-based during suspension. So stop it to prevent
1737 * I/O mapping before resume.
1738 * This must be done before setting the queue restrictions,
1739 * because request-based dm may be run just after the setting.
1741 if (dm_table_request_based(t)) {
1744 * Leverage the fact that request-based DM targets are
1745 * immutable singletons and establish md->immutable_target
1746 * - used to optimize both dm_request_fn and dm_mq_queue_rq
1748 md->immutable_target = dm_table_get_immutable_target(t);
1751 __bind_mempools(md, t);
1753 old_map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
1754 rcu_assign_pointer(md->map, (void *)t);
1755 md->immutable_target_type = dm_table_get_immutable_target_type(t);
1757 dm_table_set_restrictions(t, q, limits);
1765 * Returns unbound table for the caller to free.
1767 static struct dm_table *__unbind(struct mapped_device *md)
1769 struct dm_table *map = rcu_dereference_protected(md->map, 1);
1774 dm_table_event_callback(map, NULL, NULL);
1775 RCU_INIT_POINTER(md->map, NULL);
1782 * Constructor for a new device.
1784 int dm_create(int minor, struct mapped_device **result)
1786 struct mapped_device *md;
1788 md = alloc_dev(minor);
1799 * Functions to manage md->type.
1800 * All are required to hold md->type_lock.
1802 void dm_lock_md_type(struct mapped_device *md)
1804 mutex_lock(&md->type_lock);
1807 void dm_unlock_md_type(struct mapped_device *md)
1809 mutex_unlock(&md->type_lock);
1812 void dm_set_md_type(struct mapped_device *md, unsigned type)
1814 BUG_ON(!mutex_is_locked(&md->type_lock));
1818 unsigned dm_get_md_type(struct mapped_device *md)
1823 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
1825 return md->immutable_target_type;
1829 * The queue_limits are only valid as long as you have a reference
1832 struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
1834 BUG_ON(!atomic_read(&md->holders));
1835 return &md->queue->limits;
1837 EXPORT_SYMBOL_GPL(dm_get_queue_limits);
1840 * Setup the DM device's queue based on md's type
1842 int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t)
1845 unsigned type = dm_get_md_type(md);
1848 case DM_TYPE_REQUEST_BASED:
1849 r = dm_old_init_request_queue(md);
1851 DMERR("Cannot initialize queue for request-based mapped device");
1855 case DM_TYPE_MQ_REQUEST_BASED:
1856 r = dm_mq_init_request_queue(md, t);
1858 DMERR("Cannot initialize queue for request-based dm-mq mapped device");
1862 case DM_TYPE_BIO_BASED:
1863 case DM_TYPE_DAX_BIO_BASED:
1864 dm_init_normal_md_queue(md);
1866 * DM handles splitting bios as needed. Free the bio_split bioset
1867 * since it won't be used (saves 1 process per bio-based DM device).
1869 bioset_free(md->queue->bio_split);
1870 md->queue->bio_split = NULL;
1872 if (type == DM_TYPE_DAX_BIO_BASED)
1873 queue_flag_set_unlocked(QUEUE_FLAG_DAX, md->queue);
1880 struct mapped_device *dm_get_md(dev_t dev)
1882 struct mapped_device *md;
1883 unsigned minor = MINOR(dev);
1885 if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
1888 spin_lock(&_minor_lock);
1890 md = idr_find(&_minor_idr, minor);
1892 if ((md == MINOR_ALLOCED ||
1893 (MINOR(disk_devt(dm_disk(md))) != minor) ||
1894 dm_deleting_md(md) ||
1895 test_bit(DMF_FREEING, &md->flags))) {
1903 spin_unlock(&_minor_lock);
1907 EXPORT_SYMBOL_GPL(dm_get_md);
1909 void *dm_get_mdptr(struct mapped_device *md)
1911 return md->interface_ptr;
1914 void dm_set_mdptr(struct mapped_device *md, void *ptr)
1916 md->interface_ptr = ptr;
1919 void dm_get(struct mapped_device *md)
1921 atomic_inc(&md->holders);
1922 BUG_ON(test_bit(DMF_FREEING, &md->flags));
1925 int dm_hold(struct mapped_device *md)
1927 spin_lock(&_minor_lock);
1928 if (test_bit(DMF_FREEING, &md->flags)) {
1929 spin_unlock(&_minor_lock);
1933 spin_unlock(&_minor_lock);
1936 EXPORT_SYMBOL_GPL(dm_hold);
1938 const char *dm_device_name(struct mapped_device *md)
1942 EXPORT_SYMBOL_GPL(dm_device_name);
1944 static void __dm_destroy(struct mapped_device *md, bool wait)
1946 struct request_queue *q = dm_get_md_queue(md);
1947 struct dm_table *map;
1952 spin_lock(&_minor_lock);
1953 idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
1954 set_bit(DMF_FREEING, &md->flags);
1955 spin_unlock(&_minor_lock);
1957 blk_set_queue_dying(q);
1959 if (dm_request_based(md) && md->kworker_task)
1960 kthread_flush_worker(&md->kworker);
1963 * Take suspend_lock so that presuspend and postsuspend methods
1964 * do not race with internal suspend.
1966 mutex_lock(&md->suspend_lock);
1967 map = dm_get_live_table(md, &srcu_idx);
1968 if (!dm_suspended_md(md)) {
1969 dm_table_presuspend_targets(map);
1970 dm_table_postsuspend_targets(map);
1972 /* dm_put_live_table must be before msleep, otherwise deadlock is possible */
1973 dm_put_live_table(md, srcu_idx);
1974 mutex_unlock(&md->suspend_lock);
1977 * Rare, but there may be I/O requests still going to complete,
1978 * for example. Wait for all references to disappear.
1979 * No one should increment the reference count of the mapped_device,
1980 * after the mapped_device state becomes DMF_FREEING.
1983 while (atomic_read(&md->holders))
1985 else if (atomic_read(&md->holders))
1986 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
1987 dm_device_name(md), atomic_read(&md->holders));
1990 dm_table_destroy(__unbind(md));
1994 void dm_destroy(struct mapped_device *md)
1996 __dm_destroy(md, true);
1999 void dm_destroy_immediate(struct mapped_device *md)
2001 __dm_destroy(md, false);
2004 void dm_put(struct mapped_device *md)
2006 atomic_dec(&md->holders);
2008 EXPORT_SYMBOL_GPL(dm_put);
2010 static int dm_wait_for_completion(struct mapped_device *md, long task_state)
2016 prepare_to_wait(&md->wait, &wait, task_state);
2018 if (!md_in_flight(md))
2021 if (signal_pending_state(task_state, current)) {
2028 finish_wait(&md->wait, &wait);
2030 smp_rmb(); /* paired with atomic_dec_return in end_io_acct */
2036 * Process the deferred bios
2038 static void dm_wq_work(struct work_struct *work)
2040 struct mapped_device *md = container_of(work, struct mapped_device,
2044 struct dm_table *map;
2046 map = dm_get_live_table(md, &srcu_idx);
2048 while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2049 spin_lock_irq(&md->deferred_lock);
2050 c = bio_list_pop(&md->deferred);
2051 spin_unlock_irq(&md->deferred_lock);
2056 if (dm_request_based(md))
2057 generic_make_request(c);
2059 __split_and_process_bio(md, map, c);
2062 dm_put_live_table(md, srcu_idx);
2065 static void dm_queue_flush(struct mapped_device *md)
2067 clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2068 smp_mb__after_atomic();
2069 queue_work(md->wq, &md->work);
2073 * Swap in a new table, returning the old one for the caller to destroy.
2075 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
2077 struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
2078 struct queue_limits limits;
2081 mutex_lock(&md->suspend_lock);
2083 /* device must be suspended */
2084 if (!dm_suspended_md(md))
2088 * If the new table has no data devices, retain the existing limits.
2089 * This helps multipath with queue_if_no_path if all paths disappear,
2090 * then new I/O is queued based on these limits, and then some paths
2093 if (dm_table_has_no_data_devices(table)) {
2094 live_map = dm_get_live_table_fast(md);
2096 limits = md->queue->limits;
2097 dm_put_live_table_fast(md);
2101 r = dm_calculate_queue_limits(table, &limits);
2108 map = __bind(md, table, &limits);
2111 mutex_unlock(&md->suspend_lock);
2116 * Functions to lock and unlock any filesystem running on the
2119 static int lock_fs(struct mapped_device *md)
2123 WARN_ON(md->frozen_sb);
2125 md->frozen_sb = freeze_bdev(md->bdev);
2126 if (IS_ERR(md->frozen_sb)) {
2127 r = PTR_ERR(md->frozen_sb);
2128 md->frozen_sb = NULL;
2132 set_bit(DMF_FROZEN, &md->flags);
2137 static void unlock_fs(struct mapped_device *md)
2139 if (!test_bit(DMF_FROZEN, &md->flags))
2142 thaw_bdev(md->bdev, md->frozen_sb);
2143 md->frozen_sb = NULL;
2144 clear_bit(DMF_FROZEN, &md->flags);
2148 * @suspend_flags: DM_SUSPEND_LOCKFS_FLAG and/or DM_SUSPEND_NOFLUSH_FLAG
2149 * @task_state: e.g. TASK_INTERRUPTIBLE or TASK_UNINTERRUPTIBLE
2150 * @dmf_suspended_flag: DMF_SUSPENDED or DMF_SUSPENDED_INTERNALLY
2152 * If __dm_suspend returns 0, the device is completely quiescent
2153 * now. There is no request-processing activity. All new requests
2154 * are being added to md->deferred list.
2156 * Caller must hold md->suspend_lock
2158 static int __dm_suspend(struct mapped_device *md, struct dm_table *map,
2159 unsigned suspend_flags, long task_state,
2160 int dmf_suspended_flag)
2162 bool do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG;
2163 bool noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG;
2166 lockdep_assert_held(&md->suspend_lock);
2169 * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
2170 * This flag is cleared before dm_suspend returns.
2173 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2176 * This gets reverted if there's an error later and the targets
2177 * provide the .presuspend_undo hook.
2179 dm_table_presuspend_targets(map);
2182 * Flush I/O to the device.
2183 * Any I/O submitted after lock_fs() may not be flushed.
2184 * noflush takes precedence over do_lockfs.
2185 * (lock_fs() flushes I/Os and waits for them to complete.)
2187 if (!noflush && do_lockfs) {
2190 dm_table_presuspend_undo_targets(map);
2196 * Here we must make sure that no processes are submitting requests
2197 * to target drivers i.e. no one may be executing
2198 * __split_and_process_bio. This is called from dm_request and
2201 * To get all processes out of __split_and_process_bio in dm_request,
2202 * we take the write lock. To prevent any process from reentering
2203 * __split_and_process_bio from dm_request and quiesce the thread
2204 * (dm_wq_work), we set BMF_BLOCK_IO_FOR_SUSPEND and call
2205 * flush_workqueue(md->wq).
2207 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2209 synchronize_srcu(&md->io_barrier);
2212 * Stop md->queue before flushing md->wq in case request-based
2213 * dm defers requests to md->wq from md->queue.
2215 if (dm_request_based(md)) {
2216 dm_stop_queue(md->queue);
2217 if (md->kworker_task)
2218 kthread_flush_worker(&md->kworker);
2221 flush_workqueue(md->wq);
2224 * At this point no more requests are entering target request routines.
2225 * We call dm_wait_for_completion to wait for all existing requests
2228 r = dm_wait_for_completion(md, task_state);
2230 set_bit(dmf_suspended_flag, &md->flags);
2233 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2235 synchronize_srcu(&md->io_barrier);
2237 /* were we interrupted ? */
2241 if (dm_request_based(md))
2242 dm_start_queue(md->queue);
2245 dm_table_presuspend_undo_targets(map);
2246 /* pushback list is already flushed, so skip flush */
2253 * We need to be able to change a mapping table under a mounted
2254 * filesystem. For example we might want to move some data in
2255 * the background. Before the table can be swapped with
2256 * dm_bind_table, dm_suspend must be called to flush any in
2257 * flight bios and ensure that any further io gets deferred.
2260 * Suspend mechanism in request-based dm.
2262 * 1. Flush all I/Os by lock_fs() if needed.
2263 * 2. Stop dispatching any I/O by stopping the request_queue.
2264 * 3. Wait for all in-flight I/Os to be completed or requeued.
2266 * To abort suspend, start the request_queue.
2268 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
2270 struct dm_table *map = NULL;
2274 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
2276 if (dm_suspended_md(md)) {
2281 if (dm_suspended_internally_md(md)) {
2282 /* already internally suspended, wait for internal resume */
2283 mutex_unlock(&md->suspend_lock);
2284 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
2290 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2292 r = __dm_suspend(md, map, suspend_flags, TASK_INTERRUPTIBLE, DMF_SUSPENDED);
2296 dm_table_postsuspend_targets(map);
2299 mutex_unlock(&md->suspend_lock);
2303 static int __dm_resume(struct mapped_device *md, struct dm_table *map)
2306 int r = dm_table_resume_targets(map);
2314 * Flushing deferred I/Os must be done after targets are resumed
2315 * so that mapping of targets can work correctly.
2316 * Request-based dm is queueing the deferred I/Os in its request_queue.
2318 if (dm_request_based(md))
2319 dm_start_queue(md->queue);
2326 int dm_resume(struct mapped_device *md)
2329 struct dm_table *map = NULL;
2333 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
2335 if (!dm_suspended_md(md))
2338 if (dm_suspended_internally_md(md)) {
2339 /* already internally suspended, wait for internal resume */
2340 mutex_unlock(&md->suspend_lock);
2341 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
2347 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2348 if (!map || !dm_table_get_size(map))
2351 r = __dm_resume(md, map);
2355 clear_bit(DMF_SUSPENDED, &md->flags);
2357 mutex_unlock(&md->suspend_lock);
2363 * Internal suspend/resume works like userspace-driven suspend. It waits
2364 * until all bios finish and prevents issuing new bios to the target drivers.
2365 * It may be used only from the kernel.
2368 static void __dm_internal_suspend(struct mapped_device *md, unsigned suspend_flags)
2370 struct dm_table *map = NULL;
2372 if (md->internal_suspend_count++)
2373 return; /* nested internal suspend */
2375 if (dm_suspended_md(md)) {
2376 set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
2377 return; /* nest suspend */
2380 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2383 * Using TASK_UNINTERRUPTIBLE because only NOFLUSH internal suspend is
2384 * supported. Properly supporting a TASK_INTERRUPTIBLE internal suspend
2385 * would require changing .presuspend to return an error -- avoid this
2386 * until there is a need for more elaborate variants of internal suspend.
2388 (void) __dm_suspend(md, map, suspend_flags, TASK_UNINTERRUPTIBLE,
2389 DMF_SUSPENDED_INTERNALLY);
2391 dm_table_postsuspend_targets(map);
2394 static void __dm_internal_resume(struct mapped_device *md)
2396 BUG_ON(!md->internal_suspend_count);
2398 if (--md->internal_suspend_count)
2399 return; /* resume from nested internal suspend */
2401 if (dm_suspended_md(md))
2402 goto done; /* resume from nested suspend */
2405 * NOTE: existing callers don't need to call dm_table_resume_targets
2406 * (which may fail -- so best to avoid it for now by passing NULL map)
2408 (void) __dm_resume(md, NULL);
2411 clear_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
2412 smp_mb__after_atomic();
2413 wake_up_bit(&md->flags, DMF_SUSPENDED_INTERNALLY);
2416 void dm_internal_suspend_noflush(struct mapped_device *md)
2418 mutex_lock(&md->suspend_lock);
2419 __dm_internal_suspend(md, DM_SUSPEND_NOFLUSH_FLAG);
2420 mutex_unlock(&md->suspend_lock);
2422 EXPORT_SYMBOL_GPL(dm_internal_suspend_noflush);
2424 void dm_internal_resume(struct mapped_device *md)
2426 mutex_lock(&md->suspend_lock);
2427 __dm_internal_resume(md);
2428 mutex_unlock(&md->suspend_lock);
2430 EXPORT_SYMBOL_GPL(dm_internal_resume);
2433 * Fast variants of internal suspend/resume hold md->suspend_lock,
2434 * which prevents interaction with userspace-driven suspend.
2437 void dm_internal_suspend_fast(struct mapped_device *md)
2439 mutex_lock(&md->suspend_lock);
2440 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
2443 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2444 synchronize_srcu(&md->io_barrier);
2445 flush_workqueue(md->wq);
2446 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
2448 EXPORT_SYMBOL_GPL(dm_internal_suspend_fast);
2450 void dm_internal_resume_fast(struct mapped_device *md)
2452 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
2458 mutex_unlock(&md->suspend_lock);
2460 EXPORT_SYMBOL_GPL(dm_internal_resume_fast);
2462 /*-----------------------------------------------------------------
2463 * Event notification.
2464 *---------------------------------------------------------------*/
2465 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
2468 char udev_cookie[DM_COOKIE_LENGTH];
2469 char *envp[] = { udev_cookie, NULL };
2472 return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
2474 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
2475 DM_COOKIE_ENV_VAR_NAME, cookie);
2476 return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
2481 uint32_t dm_next_uevent_seq(struct mapped_device *md)
2483 return atomic_add_return(1, &md->uevent_seq);
2486 uint32_t dm_get_event_nr(struct mapped_device *md)
2488 return atomic_read(&md->event_nr);
2491 int dm_wait_event(struct mapped_device *md, int event_nr)
2493 return wait_event_interruptible(md->eventq,
2494 (event_nr != atomic_read(&md->event_nr)));
2497 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
2499 unsigned long flags;
2501 spin_lock_irqsave(&md->uevent_lock, flags);
2502 list_add(elist, &md->uevent_list);
2503 spin_unlock_irqrestore(&md->uevent_lock, flags);
2507 * The gendisk is only valid as long as you have a reference
2510 struct gendisk *dm_disk(struct mapped_device *md)
2514 EXPORT_SYMBOL_GPL(dm_disk);
2516 struct kobject *dm_kobject(struct mapped_device *md)
2518 return &md->kobj_holder.kobj;
2521 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
2523 struct mapped_device *md;
2525 md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
2527 spin_lock(&_minor_lock);
2528 if (test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
2534 spin_unlock(&_minor_lock);
2539 int dm_suspended_md(struct mapped_device *md)
2541 return test_bit(DMF_SUSPENDED, &md->flags);
2544 int dm_suspended_internally_md(struct mapped_device *md)
2546 return test_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
2549 int dm_test_deferred_remove_flag(struct mapped_device *md)
2551 return test_bit(DMF_DEFERRED_REMOVE, &md->flags);
2554 int dm_suspended(struct dm_target *ti)
2556 return dm_suspended_md(dm_table_get_md(ti->table));
2558 EXPORT_SYMBOL_GPL(dm_suspended);
2560 int dm_noflush_suspending(struct dm_target *ti)
2562 return __noflush_suspending(dm_table_get_md(ti->table));
2564 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
2566 struct dm_md_mempools *dm_alloc_md_mempools(struct mapped_device *md, unsigned type,
2567 unsigned integrity, unsigned per_io_data_size)
2569 struct dm_md_mempools *pools = kzalloc_node(sizeof(*pools), GFP_KERNEL, md->numa_node_id);
2570 struct kmem_cache *cachep = NULL;
2571 unsigned int pool_size = 0;
2572 unsigned int front_pad;
2578 case DM_TYPE_BIO_BASED:
2579 case DM_TYPE_DAX_BIO_BASED:
2581 pool_size = dm_get_reserved_bio_based_ios();
2582 front_pad = roundup(per_io_data_size, __alignof__(struct dm_target_io)) + offsetof(struct dm_target_io, clone);
2584 case DM_TYPE_REQUEST_BASED:
2585 cachep = _rq_tio_cache;
2586 pool_size = dm_get_reserved_rq_based_ios();
2587 pools->rq_pool = mempool_create_slab_pool(pool_size, _rq_cache);
2588 if (!pools->rq_pool)
2590 /* fall through to setup remaining rq-based pools */
2591 case DM_TYPE_MQ_REQUEST_BASED:
2593 pool_size = dm_get_reserved_rq_based_ios();
2594 front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
2595 /* per_io_data_size is used for blk-mq pdu at queue allocation */
2602 pools->io_pool = mempool_create_slab_pool(pool_size, cachep);
2603 if (!pools->io_pool)
2607 pools->bs = bioset_create_nobvec(pool_size, front_pad);
2611 if (integrity && bioset_integrity_create(pools->bs, pool_size))
2617 dm_free_md_mempools(pools);
2622 void dm_free_md_mempools(struct dm_md_mempools *pools)
2627 mempool_destroy(pools->io_pool);
2628 mempool_destroy(pools->rq_pool);
2631 bioset_free(pools->bs);
2643 static int dm_call_pr(struct block_device *bdev, iterate_devices_callout_fn fn,
2646 struct mapped_device *md = bdev->bd_disk->private_data;
2647 struct dm_table *table;
2648 struct dm_target *ti;
2649 int ret = -ENOTTY, srcu_idx;
2651 table = dm_get_live_table(md, &srcu_idx);
2652 if (!table || !dm_table_get_size(table))
2655 /* We only support devices that have a single target */
2656 if (dm_table_get_num_targets(table) != 1)
2658 ti = dm_table_get_target(table, 0);
2661 if (!ti->type->iterate_devices)
2664 ret = ti->type->iterate_devices(ti, fn, data);
2666 dm_put_live_table(md, srcu_idx);
2671 * For register / unregister we need to manually call out to every path.
2673 static int __dm_pr_register(struct dm_target *ti, struct dm_dev *dev,
2674 sector_t start, sector_t len, void *data)
2676 struct dm_pr *pr = data;
2677 const struct pr_ops *ops = dev->bdev->bd_disk->fops->pr_ops;
2679 if (!ops || !ops->pr_register)
2681 return ops->pr_register(dev->bdev, pr->old_key, pr->new_key, pr->flags);
2684 static int dm_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
2695 ret = dm_call_pr(bdev, __dm_pr_register, &pr);
2696 if (ret && new_key) {
2697 /* unregister all paths if we failed to register any path */
2698 pr.old_key = new_key;
2701 pr.fail_early = false;
2702 dm_call_pr(bdev, __dm_pr_register, &pr);
2708 static int dm_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
2711 struct mapped_device *md = bdev->bd_disk->private_data;
2712 const struct pr_ops *ops;
2716 r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
2720 ops = bdev->bd_disk->fops->pr_ops;
2721 if (ops && ops->pr_reserve)
2722 r = ops->pr_reserve(bdev, key, type, flags);
2730 static int dm_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
2732 struct mapped_device *md = bdev->bd_disk->private_data;
2733 const struct pr_ops *ops;
2737 r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
2741 ops = bdev->bd_disk->fops->pr_ops;
2742 if (ops && ops->pr_release)
2743 r = ops->pr_release(bdev, key, type);
2751 static int dm_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
2752 enum pr_type type, bool abort)
2754 struct mapped_device *md = bdev->bd_disk->private_data;
2755 const struct pr_ops *ops;
2759 r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
2763 ops = bdev->bd_disk->fops->pr_ops;
2764 if (ops && ops->pr_preempt)
2765 r = ops->pr_preempt(bdev, old_key, new_key, type, abort);
2773 static int dm_pr_clear(struct block_device *bdev, u64 key)
2775 struct mapped_device *md = bdev->bd_disk->private_data;
2776 const struct pr_ops *ops;
2780 r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
2784 ops = bdev->bd_disk->fops->pr_ops;
2785 if (ops && ops->pr_clear)
2786 r = ops->pr_clear(bdev, key);
2794 static const struct pr_ops dm_pr_ops = {
2795 .pr_register = dm_pr_register,
2796 .pr_reserve = dm_pr_reserve,
2797 .pr_release = dm_pr_release,
2798 .pr_preempt = dm_pr_preempt,
2799 .pr_clear = dm_pr_clear,
2802 static const struct block_device_operations dm_blk_dops = {
2803 .open = dm_blk_open,
2804 .release = dm_blk_close,
2805 .ioctl = dm_blk_ioctl,
2806 .direct_access = dm_blk_direct_access,
2807 .getgeo = dm_blk_getgeo,
2808 .pr_ops = &dm_pr_ops,
2809 .owner = THIS_MODULE
2815 module_init(dm_init);
2816 module_exit(dm_exit);
2818 module_param(major, uint, 0);
2819 MODULE_PARM_DESC(major, "The major number of the device mapper");
2821 module_param(reserved_bio_based_ios, uint, S_IRUGO | S_IWUSR);
2822 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
2824 module_param(dm_numa_node, int, S_IRUGO | S_IWUSR);
2825 MODULE_PARM_DESC(dm_numa_node, "NUMA node for DM device memory allocations");
2827 MODULE_DESCRIPTION(DM_NAME " driver");
2828 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
2829 MODULE_LICENSE("GPL");