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"
13 #include <linux/init.h>
14 #include <linux/module.h>
15 #include <linux/mutex.h>
16 #include <linux/sched/mm.h>
17 #include <linux/sched/signal.h>
18 #include <linux/blkpg.h>
19 #include <linux/bio.h>
20 #include <linux/mempool.h>
21 #include <linux/dax.h>
22 #include <linux/slab.h>
23 #include <linux/idr.h>
24 #include <linux/uio.h>
25 #include <linux/hdreg.h>
26 #include <linux/delay.h>
27 #include <linux/wait.h>
29 #include <linux/refcount.h>
30 #include <linux/part_stat.h>
31 #include <linux/blk-crypto.h>
32 #include <linux/blk-crypto-profile.h>
34 #define DM_MSG_PREFIX "core"
37 * Cookies are numeric values sent with CHANGE and REMOVE
38 * uevents while resuming, removing or renaming the device.
40 #define DM_COOKIE_ENV_VAR_NAME "DM_COOKIE"
41 #define DM_COOKIE_LENGTH 24
44 * For REQ_POLLED fs bio, this flag is set if we link mapped underlying
45 * dm_io into one list, and reuse bio->bi_private as the list head. Before
46 * ending this fs bio, we will recover its ->bi_private.
48 #define REQ_DM_POLL_LIST REQ_DRV
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;
65 atomic_t dm_global_event_nr = ATOMIC_INIT(0);
66 DECLARE_WAIT_QUEUE_HEAD(dm_global_eventq);
68 void dm_issue_global_event(void)
70 atomic_inc(&dm_global_event_nr);
71 wake_up(&dm_global_eventq);
74 DEFINE_STATIC_KEY_FALSE(stats_enabled);
75 DEFINE_STATIC_KEY_FALSE(swap_bios_enabled);
76 DEFINE_STATIC_KEY_FALSE(zoned_enabled);
79 * One of these is allocated (on-stack) per original bio.
86 unsigned sector_count;
87 bool is_abnormal_io:1;
88 bool submit_as_polled:1;
91 #define DM_TARGET_IO_BIO_OFFSET (offsetof(struct dm_target_io, clone))
92 #define DM_IO_BIO_OFFSET \
93 (offsetof(struct dm_target_io, clone) + offsetof(struct dm_io, tio))
95 static inline struct dm_target_io *clone_to_tio(struct bio *clone)
97 return container_of(clone, struct dm_target_io, clone);
100 void *dm_per_bio_data(struct bio *bio, size_t data_size)
102 if (!dm_tio_flagged(clone_to_tio(bio), DM_TIO_INSIDE_DM_IO))
103 return (char *)bio - DM_TARGET_IO_BIO_OFFSET - data_size;
104 return (char *)bio - DM_IO_BIO_OFFSET - data_size;
106 EXPORT_SYMBOL_GPL(dm_per_bio_data);
108 struct bio *dm_bio_from_per_bio_data(void *data, size_t data_size)
110 struct dm_io *io = (struct dm_io *)((char *)data + data_size);
111 if (io->magic == DM_IO_MAGIC)
112 return (struct bio *)((char *)io + DM_IO_BIO_OFFSET);
113 BUG_ON(io->magic != DM_TIO_MAGIC);
114 return (struct bio *)((char *)io + DM_TARGET_IO_BIO_OFFSET);
116 EXPORT_SYMBOL_GPL(dm_bio_from_per_bio_data);
118 unsigned dm_bio_get_target_bio_nr(const struct bio *bio)
120 return container_of(bio, struct dm_target_io, clone)->target_bio_nr;
122 EXPORT_SYMBOL_GPL(dm_bio_get_target_bio_nr);
124 #define MINOR_ALLOCED ((void *)-1)
126 #define DM_NUMA_NODE NUMA_NO_NODE
127 static int dm_numa_node = DM_NUMA_NODE;
129 #define DEFAULT_SWAP_BIOS (8 * 1048576 / PAGE_SIZE)
130 static int swap_bios = DEFAULT_SWAP_BIOS;
131 static int get_swap_bios(void)
133 int latch = READ_ONCE(swap_bios);
134 if (unlikely(latch <= 0))
135 latch = DEFAULT_SWAP_BIOS;
140 * For mempools pre-allocation at the table loading time.
142 struct dm_md_mempools {
144 struct bio_set io_bs;
147 struct table_device {
148 struct list_head list;
150 struct dm_dev dm_dev;
154 * Bio-based DM's mempools' reserved IOs set by the user.
156 #define RESERVED_BIO_BASED_IOS 16
157 static unsigned reserved_bio_based_ios = RESERVED_BIO_BASED_IOS;
159 static int __dm_get_module_param_int(int *module_param, int min, int max)
161 int param = READ_ONCE(*module_param);
162 int modified_param = 0;
163 bool modified = true;
166 modified_param = min;
167 else if (param > max)
168 modified_param = max;
173 (void)cmpxchg(module_param, param, modified_param);
174 param = modified_param;
180 unsigned __dm_get_module_param(unsigned *module_param,
181 unsigned def, unsigned max)
183 unsigned param = READ_ONCE(*module_param);
184 unsigned modified_param = 0;
187 modified_param = def;
188 else if (param > max)
189 modified_param = max;
191 if (modified_param) {
192 (void)cmpxchg(module_param, param, modified_param);
193 param = modified_param;
199 unsigned dm_get_reserved_bio_based_ios(void)
201 return __dm_get_module_param(&reserved_bio_based_ios,
202 RESERVED_BIO_BASED_IOS, DM_RESERVED_MAX_IOS);
204 EXPORT_SYMBOL_GPL(dm_get_reserved_bio_based_ios);
206 static unsigned dm_get_numa_node(void)
208 return __dm_get_module_param_int(&dm_numa_node,
209 DM_NUMA_NODE, num_online_nodes() - 1);
212 static int __init local_init(void)
216 r = dm_uevent_init();
220 deferred_remove_workqueue = alloc_workqueue("kdmremove", WQ_UNBOUND, 1);
221 if (!deferred_remove_workqueue) {
223 goto out_uevent_exit;
227 r = register_blkdev(_major, _name);
229 goto out_free_workqueue;
237 destroy_workqueue(deferred_remove_workqueue);
244 static void local_exit(void)
246 flush_scheduled_work();
247 destroy_workqueue(deferred_remove_workqueue);
249 unregister_blkdev(_major, _name);
254 DMINFO("cleaned up");
257 static int (*_inits[])(void) __initdata = {
268 static void (*_exits[])(void) = {
279 static int __init dm_init(void)
281 const int count = ARRAY_SIZE(_inits);
284 #if (IS_ENABLED(CONFIG_IMA) && !IS_ENABLED(CONFIG_IMA_DISABLE_HTABLE))
285 DMWARN("CONFIG_IMA_DISABLE_HTABLE is disabled."
286 " Duplicate IMA measurements will not be recorded in the IMA log.");
289 for (i = 0; i < count; i++) {
303 static void __exit dm_exit(void)
305 int i = ARRAY_SIZE(_exits);
311 * Should be empty by this point.
313 idr_destroy(&_minor_idr);
317 * Block device functions
319 int dm_deleting_md(struct mapped_device *md)
321 return test_bit(DMF_DELETING, &md->flags);
324 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
326 struct mapped_device *md;
328 spin_lock(&_minor_lock);
330 md = bdev->bd_disk->private_data;
334 if (test_bit(DMF_FREEING, &md->flags) ||
335 dm_deleting_md(md)) {
341 atomic_inc(&md->open_count);
343 spin_unlock(&_minor_lock);
345 return md ? 0 : -ENXIO;
348 static void dm_blk_close(struct gendisk *disk, fmode_t mode)
350 struct mapped_device *md;
352 spin_lock(&_minor_lock);
354 md = disk->private_data;
358 if (atomic_dec_and_test(&md->open_count) &&
359 (test_bit(DMF_DEFERRED_REMOVE, &md->flags)))
360 queue_work(deferred_remove_workqueue, &deferred_remove_work);
364 spin_unlock(&_minor_lock);
367 int dm_open_count(struct mapped_device *md)
369 return atomic_read(&md->open_count);
373 * Guarantees nothing is using the device before it's deleted.
375 int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
379 spin_lock(&_minor_lock);
381 if (dm_open_count(md)) {
384 set_bit(DMF_DEFERRED_REMOVE, &md->flags);
385 } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
388 set_bit(DMF_DELETING, &md->flags);
390 spin_unlock(&_minor_lock);
395 int dm_cancel_deferred_remove(struct mapped_device *md)
399 spin_lock(&_minor_lock);
401 if (test_bit(DMF_DELETING, &md->flags))
404 clear_bit(DMF_DEFERRED_REMOVE, &md->flags);
406 spin_unlock(&_minor_lock);
411 static void do_deferred_remove(struct work_struct *w)
413 dm_deferred_remove();
416 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
418 struct mapped_device *md = bdev->bd_disk->private_data;
420 return dm_get_geometry(md, geo);
423 static int dm_prepare_ioctl(struct mapped_device *md, int *srcu_idx,
424 struct block_device **bdev)
426 struct dm_target *tgt;
427 struct dm_table *map;
432 map = dm_get_live_table(md, srcu_idx);
433 if (!map || !dm_table_get_size(map))
436 /* We only support devices that have a single target */
437 if (dm_table_get_num_targets(map) != 1)
440 tgt = dm_table_get_target(map, 0);
441 if (!tgt->type->prepare_ioctl)
444 if (dm_suspended_md(md))
447 r = tgt->type->prepare_ioctl(tgt, bdev);
448 if (r == -ENOTCONN && !fatal_signal_pending(current)) {
449 dm_put_live_table(md, *srcu_idx);
457 static void dm_unprepare_ioctl(struct mapped_device *md, int srcu_idx)
459 dm_put_live_table(md, srcu_idx);
462 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
463 unsigned int cmd, unsigned long arg)
465 struct mapped_device *md = bdev->bd_disk->private_data;
468 r = dm_prepare_ioctl(md, &srcu_idx, &bdev);
474 * Target determined this ioctl is being issued against a
475 * subset of the parent bdev; require extra privileges.
477 if (!capable(CAP_SYS_RAWIO)) {
479 "%s: sending ioctl %x to DM device without required privilege.",
486 if (!bdev->bd_disk->fops->ioctl)
489 r = bdev->bd_disk->fops->ioctl(bdev, mode, cmd, arg);
491 dm_unprepare_ioctl(md, srcu_idx);
495 u64 dm_start_time_ns_from_clone(struct bio *bio)
497 return jiffies_to_nsecs(clone_to_tio(bio)->io->start_time);
499 EXPORT_SYMBOL_GPL(dm_start_time_ns_from_clone);
501 static bool bio_is_flush_with_data(struct bio *bio)
503 return ((bio->bi_opf & REQ_PREFLUSH) && bio->bi_iter.bi_size);
506 static void dm_io_acct(struct dm_io *io, bool end)
508 struct dm_stats_aux *stats_aux = &io->stats_aux;
509 unsigned long start_time = io->start_time;
510 struct mapped_device *md = io->md;
511 struct bio *bio = io->orig_bio;
512 unsigned int sectors;
515 * If REQ_PREFLUSH set, don't account payload, it will be
516 * submitted (and accounted) after this flush completes.
518 if (bio_is_flush_with_data(bio))
520 else if (likely(!(dm_io_flagged(io, DM_IO_WAS_SPLIT))))
521 sectors = bio_sectors(bio);
523 sectors = io->sectors;
526 bdev_start_io_acct(bio->bi_bdev, sectors, bio_op(bio),
529 bdev_end_io_acct(bio->bi_bdev, bio_op(bio), start_time);
531 if (static_branch_unlikely(&stats_enabled) &&
532 unlikely(dm_stats_used(&md->stats))) {
535 if (likely(!dm_io_flagged(io, DM_IO_WAS_SPLIT)))
536 sector = bio->bi_iter.bi_sector;
538 sector = bio_end_sector(bio) - io->sector_offset;
540 dm_stats_account_io(&md->stats, bio_data_dir(bio),
542 end, start_time, stats_aux);
546 static void __dm_start_io_acct(struct dm_io *io)
548 dm_io_acct(io, false);
551 static void dm_start_io_acct(struct dm_io *io, struct bio *clone)
554 * Ensure IO accounting is only ever started once.
556 if (dm_io_flagged(io, DM_IO_ACCOUNTED))
559 /* Expect no possibility for race unless DM_TIO_IS_DUPLICATE_BIO. */
560 if (!clone || likely(dm_tio_is_normal(clone_to_tio(clone)))) {
561 dm_io_set_flag(io, DM_IO_ACCOUNTED);
564 /* Can afford locking given DM_TIO_IS_DUPLICATE_BIO */
565 spin_lock_irqsave(&io->lock, flags);
566 dm_io_set_flag(io, DM_IO_ACCOUNTED);
567 spin_unlock_irqrestore(&io->lock, flags);
570 __dm_start_io_acct(io);
573 static void dm_end_io_acct(struct dm_io *io)
575 dm_io_acct(io, true);
578 static struct dm_io *alloc_io(struct mapped_device *md, struct bio *bio)
581 struct dm_target_io *tio;
584 clone = bio_alloc_clone(NULL, bio, GFP_NOIO, &md->io_bs);
585 /* Set default bdev, but target must bio_set_dev() before issuing IO */
586 clone->bi_bdev = md->disk->part0;
588 tio = clone_to_tio(clone);
590 dm_tio_set_flag(tio, DM_TIO_INSIDE_DM_IO);
593 io = container_of(tio, struct dm_io, tio);
594 io->magic = DM_IO_MAGIC;
595 io->status = BLK_STS_OK;
597 /* one ref is for submission, the other is for completion */
598 atomic_set(&io->io_count, 2);
599 this_cpu_inc(*md->pending_io);
602 spin_lock_init(&io->lock);
603 io->start_time = jiffies;
606 if (static_branch_unlikely(&stats_enabled))
607 dm_stats_record_start(&md->stats, &io->stats_aux);
612 static void free_io(struct dm_io *io)
614 bio_put(&io->tio.clone);
617 static struct bio *alloc_tio(struct clone_info *ci, struct dm_target *ti,
618 unsigned target_bio_nr, unsigned *len, gfp_t gfp_mask)
620 struct dm_target_io *tio;
623 if (!ci->io->tio.io) {
624 /* the dm_target_io embedded in ci->io is available */
626 /* alloc_io() already initialized embedded clone */
629 struct mapped_device *md = ci->io->md;
631 clone = bio_alloc_clone(NULL, ci->bio, gfp_mask, &md->bs);
634 /* Set default bdev, but target must bio_set_dev() before issuing IO */
635 clone->bi_bdev = md->disk->part0;
637 /* REQ_DM_POLL_LIST shouldn't be inherited */
638 clone->bi_opf &= ~REQ_DM_POLL_LIST;
640 tio = clone_to_tio(clone);
641 tio->flags = 0; /* also clears DM_TIO_INSIDE_DM_IO */
644 tio->magic = DM_TIO_MAGIC;
647 tio->target_bio_nr = target_bio_nr;
652 clone->bi_iter.bi_size = to_bytes(*len);
653 if (bio_integrity(clone))
654 bio_integrity_trim(clone);
660 static void free_tio(struct bio *clone)
662 if (dm_tio_flagged(clone_to_tio(clone), DM_TIO_INSIDE_DM_IO))
668 * Add the bio to the list of deferred io.
670 static void queue_io(struct mapped_device *md, struct bio *bio)
674 spin_lock_irqsave(&md->deferred_lock, flags);
675 bio_list_add(&md->deferred, bio);
676 spin_unlock_irqrestore(&md->deferred_lock, flags);
677 queue_work(md->wq, &md->work);
681 * Everyone (including functions in this file), should use this
682 * function to access the md->map field, and make sure they call
683 * dm_put_live_table() when finished.
685 struct dm_table *dm_get_live_table(struct mapped_device *md,
686 int *srcu_idx) __acquires(md->io_barrier)
688 *srcu_idx = srcu_read_lock(&md->io_barrier);
690 return srcu_dereference(md->map, &md->io_barrier);
693 void dm_put_live_table(struct mapped_device *md,
694 int srcu_idx) __releases(md->io_barrier)
696 srcu_read_unlock(&md->io_barrier, srcu_idx);
699 void dm_sync_table(struct mapped_device *md)
701 synchronize_srcu(&md->io_barrier);
702 synchronize_rcu_expedited();
706 * A fast alternative to dm_get_live_table/dm_put_live_table.
707 * The caller must not block between these two functions.
709 static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
712 return rcu_dereference(md->map);
715 static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
720 static inline struct dm_table *dm_get_live_table_bio(struct mapped_device *md,
721 int *srcu_idx, struct bio *bio)
723 if (bio->bi_opf & REQ_NOWAIT)
724 return dm_get_live_table_fast(md);
726 return dm_get_live_table(md, srcu_idx);
729 static inline void dm_put_live_table_bio(struct mapped_device *md, int srcu_idx,
732 if (bio->bi_opf & REQ_NOWAIT)
733 dm_put_live_table_fast(md);
735 dm_put_live_table(md, srcu_idx);
738 static char *_dm_claim_ptr = "I belong to device-mapper";
741 * Open a table device so we can use it as a map destination.
743 static int open_table_device(struct table_device *td, dev_t dev,
744 struct mapped_device *md)
746 struct block_device *bdev;
750 BUG_ON(td->dm_dev.bdev);
752 bdev = blkdev_get_by_dev(dev, td->dm_dev.mode | FMODE_EXCL, _dm_claim_ptr);
754 return PTR_ERR(bdev);
756 r = bd_link_disk_holder(bdev, dm_disk(md));
758 blkdev_put(bdev, td->dm_dev.mode | FMODE_EXCL);
762 td->dm_dev.bdev = bdev;
763 td->dm_dev.dax_dev = fs_dax_get_by_bdev(bdev, &part_off);
768 * Close a table device that we've been using.
770 static void close_table_device(struct table_device *td, struct mapped_device *md)
772 if (!td->dm_dev.bdev)
775 bd_unlink_disk_holder(td->dm_dev.bdev, dm_disk(md));
776 blkdev_put(td->dm_dev.bdev, td->dm_dev.mode | FMODE_EXCL);
777 put_dax(td->dm_dev.dax_dev);
778 td->dm_dev.bdev = NULL;
779 td->dm_dev.dax_dev = NULL;
782 static struct table_device *find_table_device(struct list_head *l, dev_t dev,
785 struct table_device *td;
787 list_for_each_entry(td, l, list)
788 if (td->dm_dev.bdev->bd_dev == dev && td->dm_dev.mode == mode)
794 int dm_get_table_device(struct mapped_device *md, dev_t dev, fmode_t mode,
795 struct dm_dev **result)
798 struct table_device *td;
800 mutex_lock(&md->table_devices_lock);
801 td = find_table_device(&md->table_devices, dev, mode);
803 td = kmalloc_node(sizeof(*td), GFP_KERNEL, md->numa_node_id);
805 mutex_unlock(&md->table_devices_lock);
809 td->dm_dev.mode = mode;
810 td->dm_dev.bdev = NULL;
812 if ((r = open_table_device(td, dev, md))) {
813 mutex_unlock(&md->table_devices_lock);
818 format_dev_t(td->dm_dev.name, dev);
820 refcount_set(&td->count, 1);
821 list_add(&td->list, &md->table_devices);
823 refcount_inc(&td->count);
825 mutex_unlock(&md->table_devices_lock);
827 *result = &td->dm_dev;
831 void dm_put_table_device(struct mapped_device *md, struct dm_dev *d)
833 struct table_device *td = container_of(d, struct table_device, dm_dev);
835 mutex_lock(&md->table_devices_lock);
836 if (refcount_dec_and_test(&td->count)) {
837 close_table_device(td, md);
841 mutex_unlock(&md->table_devices_lock);
844 static void free_table_devices(struct list_head *devices)
846 struct list_head *tmp, *next;
848 list_for_each_safe(tmp, next, devices) {
849 struct table_device *td = list_entry(tmp, struct table_device, list);
851 DMWARN("dm_destroy: %s still exists with %d references",
852 td->dm_dev.name, refcount_read(&td->count));
858 * Get the geometry associated with a dm device
860 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
868 * Set the geometry of a device.
870 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
872 sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
874 if (geo->start > sz) {
875 DMWARN("Start sector is beyond the geometry limits.");
884 static int __noflush_suspending(struct mapped_device *md)
886 return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
889 static void dm_io_complete(struct dm_io *io)
891 blk_status_t io_error;
892 struct mapped_device *md = io->md;
893 struct bio *bio = io->orig_bio;
895 if (io->status == BLK_STS_DM_REQUEUE) {
898 * Target requested pushing back the I/O.
900 spin_lock_irqsave(&md->deferred_lock, flags);
901 if (__noflush_suspending(md) &&
902 !WARN_ON_ONCE(dm_is_zone_write(md, bio))) {
903 /* NOTE early return due to BLK_STS_DM_REQUEUE below */
904 bio_list_add_head(&md->deferred, bio);
907 * noflush suspend was interrupted or this is
908 * a write to a zoned target.
910 io->status = BLK_STS_IOERR;
912 spin_unlock_irqrestore(&md->deferred_lock, flags);
915 io_error = io->status;
916 if (dm_io_flagged(io, DM_IO_ACCOUNTED))
918 else if (!io_error) {
920 * Must handle target that DM_MAPIO_SUBMITTED only to
921 * then bio_endio() rather than dm_submit_bio_remap()
923 __dm_start_io_acct(io);
928 this_cpu_dec(*md->pending_io);
930 /* nudge anyone waiting on suspend queue */
931 if (unlikely(wq_has_sleeper(&md->wait)))
934 if (io_error == BLK_STS_DM_REQUEUE || io_error == BLK_STS_AGAIN) {
935 if (bio->bi_opf & REQ_POLLED) {
937 * Upper layer won't help us poll split bio (io->orig_bio
938 * may only reflect a subset of the pre-split original)
939 * so clear REQ_POLLED in case of requeue.
941 bio_clear_polled(bio);
942 if (io_error == BLK_STS_AGAIN) {
943 /* io_uring doesn't handle BLK_STS_AGAIN (yet) */
950 if (bio_is_flush_with_data(bio)) {
952 * Preflush done for flush with data, reissue
953 * without REQ_PREFLUSH.
955 bio->bi_opf &= ~REQ_PREFLUSH;
958 /* done with normal IO or empty flush */
960 bio->bi_status = io_error;
966 * Decrements the number of outstanding ios that a bio has been
967 * cloned into, completing the original io if necc.
969 static inline void __dm_io_dec_pending(struct dm_io *io)
971 if (atomic_dec_and_test(&io->io_count))
975 static void dm_io_set_error(struct dm_io *io, blk_status_t error)
979 /* Push-back supersedes any I/O errors */
980 spin_lock_irqsave(&io->lock, flags);
981 if (!(io->status == BLK_STS_DM_REQUEUE &&
982 __noflush_suspending(io->md))) {
985 spin_unlock_irqrestore(&io->lock, flags);
988 static void dm_io_dec_pending(struct dm_io *io, blk_status_t error)
991 dm_io_set_error(io, error);
993 __dm_io_dec_pending(io);
996 void disable_discard(struct mapped_device *md)
998 struct queue_limits *limits = dm_get_queue_limits(md);
1000 /* device doesn't really support DISCARD, disable it */
1001 limits->max_discard_sectors = 0;
1004 void disable_write_zeroes(struct mapped_device *md)
1006 struct queue_limits *limits = dm_get_queue_limits(md);
1008 /* device doesn't really support WRITE ZEROES, disable it */
1009 limits->max_write_zeroes_sectors = 0;
1012 static bool swap_bios_limit(struct dm_target *ti, struct bio *bio)
1014 return unlikely((bio->bi_opf & REQ_SWAP) != 0) && unlikely(ti->limit_swap_bios);
1017 static void clone_endio(struct bio *bio)
1019 blk_status_t error = bio->bi_status;
1020 struct dm_target_io *tio = clone_to_tio(bio);
1021 struct dm_target *ti = tio->ti;
1022 dm_endio_fn endio = ti->type->end_io;
1023 struct dm_io *io = tio->io;
1024 struct mapped_device *md = io->md;
1026 if (likely(bio->bi_bdev != md->disk->part0)) {
1027 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
1029 if (unlikely(error == BLK_STS_TARGET)) {
1030 if (bio_op(bio) == REQ_OP_DISCARD &&
1031 !bdev_max_discard_sectors(bio->bi_bdev))
1032 disable_discard(md);
1033 else if (bio_op(bio) == REQ_OP_WRITE_ZEROES &&
1034 !q->limits.max_write_zeroes_sectors)
1035 disable_write_zeroes(md);
1038 if (static_branch_unlikely(&zoned_enabled) &&
1039 unlikely(blk_queue_is_zoned(q)))
1040 dm_zone_endio(io, bio);
1044 int r = endio(ti, bio, &error);
1046 case DM_ENDIO_REQUEUE:
1047 if (static_branch_unlikely(&zoned_enabled)) {
1049 * Requeuing writes to a sequential zone of a zoned
1050 * target will break the sequential write pattern:
1053 if (WARN_ON_ONCE(dm_is_zone_write(md, bio)))
1054 error = BLK_STS_IOERR;
1056 error = BLK_STS_DM_REQUEUE;
1058 error = BLK_STS_DM_REQUEUE;
1062 case DM_ENDIO_INCOMPLETE:
1063 /* The target will handle the io */
1066 DMWARN("unimplemented target endio return value: %d", r);
1071 if (static_branch_unlikely(&swap_bios_enabled) &&
1072 unlikely(swap_bios_limit(ti, bio)))
1073 up(&md->swap_bios_semaphore);
1076 dm_io_dec_pending(io, error);
1080 * Return maximum size of I/O possible at the supplied sector up to the current
1083 static inline sector_t max_io_len_target_boundary(struct dm_target *ti,
1084 sector_t target_offset)
1086 return ti->len - target_offset;
1089 static sector_t max_io_len(struct dm_target *ti, sector_t sector)
1091 sector_t target_offset = dm_target_offset(ti, sector);
1092 sector_t len = max_io_len_target_boundary(ti, target_offset);
1096 * Does the target need to split IO even further?
1097 * - varied (per target) IO splitting is a tenet of DM; this
1098 * explains why stacked chunk_sectors based splitting via
1099 * blk_max_size_offset() isn't possible here. So pass in
1100 * ti->max_io_len to override stacked chunk_sectors.
1102 if (ti->max_io_len) {
1103 max_len = blk_max_size_offset(ti->table->md->queue,
1104 target_offset, ti->max_io_len);
1112 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
1114 if (len > UINT_MAX) {
1115 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
1116 (unsigned long long)len, UINT_MAX);
1117 ti->error = "Maximum size of target IO is too large";
1121 ti->max_io_len = (uint32_t) len;
1125 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
1127 static struct dm_target *dm_dax_get_live_target(struct mapped_device *md,
1128 sector_t sector, int *srcu_idx)
1129 __acquires(md->io_barrier)
1131 struct dm_table *map;
1132 struct dm_target *ti;
1134 map = dm_get_live_table(md, srcu_idx);
1138 ti = dm_table_find_target(map, sector);
1145 static long dm_dax_direct_access(struct dax_device *dax_dev, pgoff_t pgoff,
1146 long nr_pages, enum dax_access_mode mode, void **kaddr,
1149 struct mapped_device *md = dax_get_private(dax_dev);
1150 sector_t sector = pgoff * PAGE_SECTORS;
1151 struct dm_target *ti;
1152 long len, ret = -EIO;
1155 ti = dm_dax_get_live_target(md, sector, &srcu_idx);
1159 if (!ti->type->direct_access)
1161 len = max_io_len(ti, sector) / PAGE_SECTORS;
1164 nr_pages = min(len, nr_pages);
1165 ret = ti->type->direct_access(ti, pgoff, nr_pages, mode, kaddr, pfn);
1168 dm_put_live_table(md, srcu_idx);
1173 static int dm_dax_zero_page_range(struct dax_device *dax_dev, pgoff_t pgoff,
1176 struct mapped_device *md = dax_get_private(dax_dev);
1177 sector_t sector = pgoff * PAGE_SECTORS;
1178 struct dm_target *ti;
1182 ti = dm_dax_get_live_target(md, sector, &srcu_idx);
1186 if (WARN_ON(!ti->type->dax_zero_page_range)) {
1188 * ->zero_page_range() is mandatory dax operation. If we are
1189 * here, something is wrong.
1193 ret = ti->type->dax_zero_page_range(ti, pgoff, nr_pages);
1195 dm_put_live_table(md, srcu_idx);
1200 static size_t dm_dax_recovery_write(struct dax_device *dax_dev, pgoff_t pgoff,
1201 void *addr, size_t bytes, struct iov_iter *i)
1203 struct mapped_device *md = dax_get_private(dax_dev);
1204 sector_t sector = pgoff * PAGE_SECTORS;
1205 struct dm_target *ti;
1209 ti = dm_dax_get_live_target(md, sector, &srcu_idx);
1210 if (!ti || !ti->type->dax_recovery_write)
1213 ret = ti->type->dax_recovery_write(ti, pgoff, addr, bytes, i);
1215 dm_put_live_table(md, srcu_idx);
1220 * A target may call dm_accept_partial_bio only from the map routine. It is
1221 * allowed for all bio types except REQ_PREFLUSH, REQ_OP_ZONE_* zone management
1222 * operations, REQ_OP_ZONE_APPEND (zone append writes) and any bio serviced by
1223 * __send_duplicate_bios().
1225 * dm_accept_partial_bio informs the dm that the target only wants to process
1226 * additional n_sectors sectors of the bio and the rest of the data should be
1227 * sent in a next bio.
1229 * A diagram that explains the arithmetics:
1230 * +--------------------+---------------+-------+
1232 * +--------------------+---------------+-------+
1234 * <-------------- *tio->len_ptr --------------->
1235 * <----- bio_sectors ----->
1238 * Region 1 was already iterated over with bio_advance or similar function.
1239 * (it may be empty if the target doesn't use bio_advance)
1240 * Region 2 is the remaining bio size that the target wants to process.
1241 * (it may be empty if region 1 is non-empty, although there is no reason
1243 * The target requires that region 3 is to be sent in the next bio.
1245 * If the target wants to receive multiple copies of the bio (via num_*bios, etc),
1246 * the partially processed part (the sum of regions 1+2) must be the same for all
1247 * copies of the bio.
1249 void dm_accept_partial_bio(struct bio *bio, unsigned n_sectors)
1251 struct dm_target_io *tio = clone_to_tio(bio);
1252 unsigned bio_sectors = bio_sectors(bio);
1254 BUG_ON(dm_tio_flagged(tio, DM_TIO_IS_DUPLICATE_BIO));
1255 BUG_ON(op_is_zone_mgmt(bio_op(bio)));
1256 BUG_ON(bio_op(bio) == REQ_OP_ZONE_APPEND);
1257 BUG_ON(bio_sectors > *tio->len_ptr);
1258 BUG_ON(n_sectors > bio_sectors);
1260 *tio->len_ptr -= bio_sectors - n_sectors;
1261 bio->bi_iter.bi_size = n_sectors << SECTOR_SHIFT;
1264 * __split_and_process_bio() may have already saved mapped part
1265 * for accounting but it is being reduced so update accordingly.
1267 dm_io_set_flag(tio->io, DM_IO_WAS_SPLIT);
1268 tio->io->sectors = n_sectors;
1270 EXPORT_SYMBOL_GPL(dm_accept_partial_bio);
1273 * @clone: clone bio that DM core passed to target's .map function
1274 * @tgt_clone: clone of @clone bio that target needs submitted
1276 * Targets should use this interface to submit bios they take
1277 * ownership of when returning DM_MAPIO_SUBMITTED.
1279 * Target should also enable ti->accounts_remapped_io
1281 void dm_submit_bio_remap(struct bio *clone, struct bio *tgt_clone)
1283 struct dm_target_io *tio = clone_to_tio(clone);
1284 struct dm_io *io = tio->io;
1286 /* establish bio that will get submitted */
1291 * Account io->origin_bio to DM dev on behalf of target
1292 * that took ownership of IO with DM_MAPIO_SUBMITTED.
1294 dm_start_io_acct(io, clone);
1296 trace_block_bio_remap(tgt_clone, disk_devt(io->md->disk),
1298 submit_bio_noacct(tgt_clone);
1300 EXPORT_SYMBOL_GPL(dm_submit_bio_remap);
1302 static noinline void __set_swap_bios_limit(struct mapped_device *md, int latch)
1304 mutex_lock(&md->swap_bios_lock);
1305 while (latch < md->swap_bios) {
1307 down(&md->swap_bios_semaphore);
1310 while (latch > md->swap_bios) {
1312 up(&md->swap_bios_semaphore);
1315 mutex_unlock(&md->swap_bios_lock);
1318 static void __map_bio(struct bio *clone)
1320 struct dm_target_io *tio = clone_to_tio(clone);
1321 struct dm_target *ti = tio->ti;
1322 struct dm_io *io = tio->io;
1323 struct mapped_device *md = io->md;
1326 clone->bi_end_io = clone_endio;
1331 tio->old_sector = clone->bi_iter.bi_sector;
1333 if (static_branch_unlikely(&swap_bios_enabled) &&
1334 unlikely(swap_bios_limit(ti, clone))) {
1335 int latch = get_swap_bios();
1336 if (unlikely(latch != md->swap_bios))
1337 __set_swap_bios_limit(md, latch);
1338 down(&md->swap_bios_semaphore);
1341 if (static_branch_unlikely(&zoned_enabled)) {
1343 * Check if the IO needs a special mapping due to zone append
1344 * emulation on zoned target. In this case, dm_zone_map_bio()
1345 * calls the target map operation.
1347 if (unlikely(dm_emulate_zone_append(md)))
1348 r = dm_zone_map_bio(tio);
1350 r = ti->type->map(ti, clone);
1352 r = ti->type->map(ti, clone);
1355 case DM_MAPIO_SUBMITTED:
1356 /* target has assumed ownership of this io */
1357 if (!ti->accounts_remapped_io)
1358 dm_start_io_acct(io, clone);
1360 case DM_MAPIO_REMAPPED:
1361 dm_submit_bio_remap(clone, NULL);
1364 case DM_MAPIO_REQUEUE:
1365 if (static_branch_unlikely(&swap_bios_enabled) &&
1366 unlikely(swap_bios_limit(ti, clone)))
1367 up(&md->swap_bios_semaphore);
1369 if (r == DM_MAPIO_KILL)
1370 dm_io_dec_pending(io, BLK_STS_IOERR);
1372 dm_io_dec_pending(io, BLK_STS_DM_REQUEUE);
1375 DMWARN("unimplemented target map return value: %d", r);
1380 static void setup_split_accounting(struct clone_info *ci, unsigned len)
1382 struct dm_io *io = ci->io;
1384 if (ci->sector_count > len) {
1386 * Split needed, save the mapped part for accounting.
1387 * NOTE: dm_accept_partial_bio() will update accordingly.
1389 dm_io_set_flag(io, DM_IO_WAS_SPLIT);
1393 if (static_branch_unlikely(&stats_enabled) &&
1394 unlikely(dm_stats_used(&io->md->stats))) {
1396 * Save bi_sector in terms of its offset from end of
1397 * original bio, only needed for DM-stats' benefit.
1398 * - saved regardless of whether split needed so that
1399 * dm_accept_partial_bio() doesn't need to.
1401 io->sector_offset = bio_end_sector(ci->bio) - ci->sector;
1405 static void alloc_multiple_bios(struct bio_list *blist, struct clone_info *ci,
1406 struct dm_target *ti, unsigned num_bios)
1411 for (try = 0; try < 2; try++) {
1415 mutex_lock(&ci->io->md->table_devices_lock);
1416 for (bio_nr = 0; bio_nr < num_bios; bio_nr++) {
1417 bio = alloc_tio(ci, ti, bio_nr, NULL,
1418 try ? GFP_NOIO : GFP_NOWAIT);
1422 bio_list_add(blist, bio);
1425 mutex_unlock(&ci->io->md->table_devices_lock);
1426 if (bio_nr == num_bios)
1429 while ((bio = bio_list_pop(blist)))
1434 static int __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1435 unsigned num_bios, unsigned *len)
1437 struct bio_list blist = BIO_EMPTY_LIST;
1446 setup_split_accounting(ci, *len);
1447 clone = alloc_tio(ci, ti, 0, len, GFP_NOIO);
1452 /* dm_accept_partial_bio() is not supported with shared tio->len_ptr */
1453 alloc_multiple_bios(&blist, ci, ti, num_bios);
1454 while ((clone = bio_list_pop(&blist))) {
1455 dm_tio_set_flag(clone_to_tio(clone), DM_TIO_IS_DUPLICATE_BIO);
1465 static void __send_empty_flush(struct clone_info *ci)
1467 unsigned target_nr = 0;
1468 struct dm_target *ti;
1469 struct bio flush_bio;
1472 * Use an on-stack bio for this, it's safe since we don't
1473 * need to reference it after submit. It's just used as
1474 * the basis for the clone(s).
1476 bio_init(&flush_bio, ci->io->md->disk->part0, NULL, 0,
1477 REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC);
1479 ci->bio = &flush_bio;
1480 ci->sector_count = 0;
1481 ci->io->tio.clone.bi_iter.bi_size = 0;
1483 while ((ti = dm_table_get_target(ci->map, target_nr++))) {
1486 atomic_add(ti->num_flush_bios, &ci->io->io_count);
1487 bios = __send_duplicate_bios(ci, ti, ti->num_flush_bios, NULL);
1488 atomic_sub(ti->num_flush_bios - bios, &ci->io->io_count);
1492 * alloc_io() takes one extra reference for submission, so the
1493 * reference won't reach 0 without the following subtraction
1495 atomic_sub(1, &ci->io->io_count);
1497 bio_uninit(ci->bio);
1500 static void __send_changing_extent_only(struct clone_info *ci, struct dm_target *ti,
1506 len = min_t(sector_t, ci->sector_count,
1507 max_io_len_target_boundary(ti, dm_target_offset(ti, ci->sector)));
1509 atomic_add(num_bios, &ci->io->io_count);
1510 bios = __send_duplicate_bios(ci, ti, num_bios, &len);
1512 * alloc_io() takes one extra reference for submission, so the
1513 * reference won't reach 0 without the following (+1) subtraction
1515 atomic_sub(num_bios - bios + 1, &ci->io->io_count);
1518 ci->sector_count -= len;
1521 static bool is_abnormal_io(struct bio *bio)
1523 unsigned int op = bio_op(bio);
1525 if (op != REQ_OP_READ && op != REQ_OP_WRITE && op != REQ_OP_FLUSH) {
1527 case REQ_OP_DISCARD:
1528 case REQ_OP_SECURE_ERASE:
1529 case REQ_OP_WRITE_ZEROES:
1539 static blk_status_t __process_abnormal_io(struct clone_info *ci,
1540 struct dm_target *ti)
1542 unsigned num_bios = 0;
1544 switch (bio_op(ci->bio)) {
1545 case REQ_OP_DISCARD:
1546 num_bios = ti->num_discard_bios;
1548 case REQ_OP_SECURE_ERASE:
1549 num_bios = ti->num_secure_erase_bios;
1551 case REQ_OP_WRITE_ZEROES:
1552 num_bios = ti->num_write_zeroes_bios;
1557 * Even though the device advertised support for this type of
1558 * request, that does not mean every target supports it, and
1559 * reconfiguration might also have changed that since the
1560 * check was performed.
1562 if (unlikely(!num_bios))
1563 return BLK_STS_NOTSUPP;
1565 __send_changing_extent_only(ci, ti, num_bios);
1570 * Reuse ->bi_private as dm_io list head for storing all dm_io instances
1571 * associated with this bio, and this bio's bi_private needs to be
1572 * stored in dm_io->data before the reuse.
1574 * bio->bi_private is owned by fs or upper layer, so block layer won't
1575 * touch it after splitting. Meantime it won't be changed by anyone after
1576 * bio is submitted. So this reuse is safe.
1578 static inline struct dm_io **dm_poll_list_head(struct bio *bio)
1580 return (struct dm_io **)&bio->bi_private;
1583 static void dm_queue_poll_io(struct bio *bio, struct dm_io *io)
1585 struct dm_io **head = dm_poll_list_head(bio);
1587 if (!(bio->bi_opf & REQ_DM_POLL_LIST)) {
1588 bio->bi_opf |= REQ_DM_POLL_LIST;
1590 * Save .bi_private into dm_io, so that we can reuse
1591 * .bi_private as dm_io list head for storing dm_io list
1593 io->data = bio->bi_private;
1595 /* tell block layer to poll for completion */
1596 bio->bi_cookie = ~BLK_QC_T_NONE;
1601 * bio recursed due to split, reuse original poll list,
1602 * and save bio->bi_private too.
1604 io->data = (*head)->data;
1612 * Select the correct strategy for processing a non-flush bio.
1614 static blk_status_t __split_and_process_bio(struct clone_info *ci)
1617 struct dm_target *ti;
1620 ti = dm_table_find_target(ci->map, ci->sector);
1622 return BLK_STS_IOERR;
1623 else if (unlikely(ci->is_abnormal_io))
1624 return __process_abnormal_io(ci, ti);
1627 * Only support bio polling for normal IO, and the target io is
1628 * exactly inside the dm_io instance (verified in dm_poll_dm_io)
1630 ci->submit_as_polled = ci->bio->bi_opf & REQ_POLLED;
1632 len = min_t(sector_t, max_io_len(ti, ci->sector), ci->sector_count);
1633 setup_split_accounting(ci, len);
1634 clone = alloc_tio(ci, ti, 0, &len, GFP_NOIO);
1638 ci->sector_count -= len;
1643 static void init_clone_info(struct clone_info *ci, struct mapped_device *md,
1644 struct dm_table *map, struct bio *bio, bool is_abnormal)
1647 ci->io = alloc_io(md, bio);
1649 ci->is_abnormal_io = is_abnormal;
1650 ci->submit_as_polled = false;
1651 ci->sector = bio->bi_iter.bi_sector;
1652 ci->sector_count = bio_sectors(bio);
1654 /* Shouldn't happen but sector_count was being set to 0 so... */
1655 if (static_branch_unlikely(&zoned_enabled) &&
1656 WARN_ON_ONCE(op_is_zone_mgmt(bio_op(bio)) && ci->sector_count))
1657 ci->sector_count = 0;
1661 * Entry point to split a bio into clones and submit them to the targets.
1663 static void dm_split_and_process_bio(struct mapped_device *md,
1664 struct dm_table *map, struct bio *bio)
1666 struct clone_info ci;
1668 blk_status_t error = BLK_STS_OK;
1671 is_abnormal = is_abnormal_io(bio);
1672 if (unlikely(is_abnormal)) {
1674 * Use blk_queue_split() for abnormal IO (e.g. discard, etc)
1675 * otherwise associated queue_limits won't be imposed.
1677 blk_queue_split(&bio);
1680 init_clone_info(&ci, md, map, bio, is_abnormal);
1683 if (bio->bi_opf & REQ_PREFLUSH) {
1684 __send_empty_flush(&ci);
1685 /* dm_io_complete submits any data associated with flush */
1689 error = __split_and_process_bio(&ci);
1690 if (error || !ci.sector_count)
1693 * Remainder must be passed to submit_bio_noacct() so it gets handled
1694 * *after* bios already submitted have been completely processed.
1696 bio_trim(bio, io->sectors, ci.sector_count);
1697 trace_block_split(bio, bio->bi_iter.bi_sector);
1698 bio_inc_remaining(bio);
1699 submit_bio_noacct(bio);
1702 * Drop the extra reference count for non-POLLED bio, and hold one
1703 * reference for POLLED bio, which will be released in dm_poll_bio
1705 * Add every dm_io instance into the dm_io list head which is stored
1706 * in bio->bi_private, so that dm_poll_bio can poll them all.
1708 if (error || !ci.submit_as_polled) {
1710 * In case of submission failure, the extra reference for
1711 * submitting io isn't consumed yet
1714 atomic_dec(&io->io_count);
1715 dm_io_dec_pending(io, error);
1717 dm_queue_poll_io(bio, io);
1720 static void dm_submit_bio(struct bio *bio)
1722 struct mapped_device *md = bio->bi_bdev->bd_disk->private_data;
1724 struct dm_table *map;
1726 map = dm_get_live_table_bio(md, &srcu_idx, bio);
1728 /* If suspended, or map not yet available, queue this IO for later */
1729 if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) ||
1731 if (bio->bi_opf & REQ_NOWAIT)
1732 bio_wouldblock_error(bio);
1733 else if (bio->bi_opf & REQ_RAHEAD)
1740 dm_split_and_process_bio(md, map, bio);
1742 dm_put_live_table_bio(md, srcu_idx, bio);
1745 static bool dm_poll_dm_io(struct dm_io *io, struct io_comp_batch *iob,
1748 WARN_ON_ONCE(!dm_tio_is_normal(&io->tio));
1750 /* don't poll if the mapped io is done */
1751 if (atomic_read(&io->io_count) > 1)
1752 bio_poll(&io->tio.clone, iob, flags);
1754 /* bio_poll holds the last reference */
1755 return atomic_read(&io->io_count) == 1;
1758 static int dm_poll_bio(struct bio *bio, struct io_comp_batch *iob,
1761 struct dm_io **head = dm_poll_list_head(bio);
1762 struct dm_io *list = *head;
1763 struct dm_io *tmp = NULL;
1764 struct dm_io *curr, *next;
1766 /* Only poll normal bio which was marked as REQ_DM_POLL_LIST */
1767 if (!(bio->bi_opf & REQ_DM_POLL_LIST))
1770 WARN_ON_ONCE(!list);
1773 * Restore .bi_private before possibly completing dm_io.
1775 * bio_poll() is only possible once @bio has been completely
1776 * submitted via submit_bio_noacct()'s depth-first submission.
1777 * So there is no dm_queue_poll_io() race associated with
1778 * clearing REQ_DM_POLL_LIST here.
1780 bio->bi_opf &= ~REQ_DM_POLL_LIST;
1781 bio->bi_private = list->data;
1783 for (curr = list, next = curr->next; curr; curr = next, next =
1784 curr ? curr->next : NULL) {
1785 if (dm_poll_dm_io(curr, iob, flags)) {
1787 * clone_endio() has already occurred, so no
1788 * error handling is needed here.
1790 __dm_io_dec_pending(curr);
1799 bio->bi_opf |= REQ_DM_POLL_LIST;
1800 /* Reset bio->bi_private to dm_io list head */
1807 /*-----------------------------------------------------------------
1808 * An IDR is used to keep track of allocated minor numbers.
1809 *---------------------------------------------------------------*/
1810 static void free_minor(int minor)
1812 spin_lock(&_minor_lock);
1813 idr_remove(&_minor_idr, minor);
1814 spin_unlock(&_minor_lock);
1818 * See if the device with a specific minor # is free.
1820 static int specific_minor(int minor)
1824 if (minor >= (1 << MINORBITS))
1827 idr_preload(GFP_KERNEL);
1828 spin_lock(&_minor_lock);
1830 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
1832 spin_unlock(&_minor_lock);
1835 return r == -ENOSPC ? -EBUSY : r;
1839 static int next_free_minor(int *minor)
1843 idr_preload(GFP_KERNEL);
1844 spin_lock(&_minor_lock);
1846 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
1848 spin_unlock(&_minor_lock);
1856 static const struct block_device_operations dm_blk_dops;
1857 static const struct block_device_operations dm_rq_blk_dops;
1858 static const struct dax_operations dm_dax_ops;
1860 static void dm_wq_work(struct work_struct *work);
1862 #ifdef CONFIG_BLK_INLINE_ENCRYPTION
1863 static void dm_queue_destroy_crypto_profile(struct request_queue *q)
1865 dm_destroy_crypto_profile(q->crypto_profile);
1868 #else /* CONFIG_BLK_INLINE_ENCRYPTION */
1870 static inline void dm_queue_destroy_crypto_profile(struct request_queue *q)
1873 #endif /* !CONFIG_BLK_INLINE_ENCRYPTION */
1875 static void cleanup_mapped_device(struct mapped_device *md)
1878 destroy_workqueue(md->wq);
1879 bioset_exit(&md->bs);
1880 bioset_exit(&md->io_bs);
1883 dax_remove_host(md->disk);
1884 kill_dax(md->dax_dev);
1885 put_dax(md->dax_dev);
1889 dm_cleanup_zoned_dev(md);
1891 spin_lock(&_minor_lock);
1892 md->disk->private_data = NULL;
1893 spin_unlock(&_minor_lock);
1894 if (dm_get_md_type(md) != DM_TYPE_NONE) {
1896 del_gendisk(md->disk);
1898 dm_queue_destroy_crypto_profile(md->queue);
1899 blk_cleanup_disk(md->disk);
1902 if (md->pending_io) {
1903 free_percpu(md->pending_io);
1904 md->pending_io = NULL;
1907 cleanup_srcu_struct(&md->io_barrier);
1909 mutex_destroy(&md->suspend_lock);
1910 mutex_destroy(&md->type_lock);
1911 mutex_destroy(&md->table_devices_lock);
1912 mutex_destroy(&md->swap_bios_lock);
1914 dm_mq_cleanup_mapped_device(md);
1918 * Allocate and initialise a blank device with a given minor.
1920 static struct mapped_device *alloc_dev(int minor)
1922 int r, numa_node_id = dm_get_numa_node();
1923 struct mapped_device *md;
1926 md = kvzalloc_node(sizeof(*md), GFP_KERNEL, numa_node_id);
1928 DMWARN("unable to allocate device, out of memory.");
1932 if (!try_module_get(THIS_MODULE))
1933 goto bad_module_get;
1935 /* get a minor number for the dev */
1936 if (minor == DM_ANY_MINOR)
1937 r = next_free_minor(&minor);
1939 r = specific_minor(minor);
1943 r = init_srcu_struct(&md->io_barrier);
1945 goto bad_io_barrier;
1947 md->numa_node_id = numa_node_id;
1948 md->init_tio_pdu = false;
1949 md->type = DM_TYPE_NONE;
1950 mutex_init(&md->suspend_lock);
1951 mutex_init(&md->type_lock);
1952 mutex_init(&md->table_devices_lock);
1953 spin_lock_init(&md->deferred_lock);
1954 atomic_set(&md->holders, 1);
1955 atomic_set(&md->open_count, 0);
1956 atomic_set(&md->event_nr, 0);
1957 atomic_set(&md->uevent_seq, 0);
1958 INIT_LIST_HEAD(&md->uevent_list);
1959 INIT_LIST_HEAD(&md->table_devices);
1960 spin_lock_init(&md->uevent_lock);
1963 * default to bio-based until DM table is loaded and md->type
1964 * established. If request-based table is loaded: blk-mq will
1965 * override accordingly.
1967 md->disk = blk_alloc_disk(md->numa_node_id);
1970 md->queue = md->disk->queue;
1972 init_waitqueue_head(&md->wait);
1973 INIT_WORK(&md->work, dm_wq_work);
1974 init_waitqueue_head(&md->eventq);
1975 init_completion(&md->kobj_holder.completion);
1977 md->swap_bios = get_swap_bios();
1978 sema_init(&md->swap_bios_semaphore, md->swap_bios);
1979 mutex_init(&md->swap_bios_lock);
1981 md->disk->major = _major;
1982 md->disk->first_minor = minor;
1983 md->disk->minors = 1;
1984 md->disk->flags |= GENHD_FL_NO_PART;
1985 md->disk->fops = &dm_blk_dops;
1986 md->disk->queue = md->queue;
1987 md->disk->private_data = md;
1988 sprintf(md->disk->disk_name, "dm-%d", minor);
1990 if (IS_ENABLED(CONFIG_FS_DAX)) {
1991 md->dax_dev = alloc_dax(md, &dm_dax_ops);
1992 if (IS_ERR(md->dax_dev)) {
1996 set_dax_nocache(md->dax_dev);
1997 set_dax_nomc(md->dax_dev);
1998 if (dax_add_host(md->dax_dev, md->disk))
2002 format_dev_t(md->name, MKDEV(_major, minor));
2004 md->wq = alloc_workqueue("kdmflush/%s", WQ_MEM_RECLAIM, 0, md->name);
2008 md->pending_io = alloc_percpu(unsigned long);
2009 if (!md->pending_io)
2012 dm_stats_init(&md->stats);
2014 /* Populate the mapping, nobody knows we exist yet */
2015 spin_lock(&_minor_lock);
2016 old_md = idr_replace(&_minor_idr, md, minor);
2017 spin_unlock(&_minor_lock);
2019 BUG_ON(old_md != MINOR_ALLOCED);
2024 cleanup_mapped_device(md);
2028 module_put(THIS_MODULE);
2034 static void unlock_fs(struct mapped_device *md);
2036 static void free_dev(struct mapped_device *md)
2038 int minor = MINOR(disk_devt(md->disk));
2042 cleanup_mapped_device(md);
2044 free_table_devices(&md->table_devices);
2045 dm_stats_cleanup(&md->stats);
2048 module_put(THIS_MODULE);
2052 static int __bind_mempools(struct mapped_device *md, struct dm_table *t)
2054 struct dm_md_mempools *p = dm_table_get_md_mempools(t);
2057 if (dm_table_bio_based(t)) {
2059 * The md may already have mempools that need changing.
2060 * If so, reload bioset because front_pad may have changed
2061 * because a different table was loaded.
2063 bioset_exit(&md->bs);
2064 bioset_exit(&md->io_bs);
2066 } else if (bioset_initialized(&md->bs)) {
2068 * There's no need to reload with request-based dm
2069 * because the size of front_pad doesn't change.
2070 * Note for future: If you are to reload bioset,
2071 * prep-ed requests in the queue may refer
2072 * to bio from the old bioset, so you must walk
2073 * through the queue to unprep.
2079 bioset_initialized(&md->bs) ||
2080 bioset_initialized(&md->io_bs));
2082 ret = bioset_init_from_src(&md->bs, &p->bs);
2085 ret = bioset_init_from_src(&md->io_bs, &p->io_bs);
2087 bioset_exit(&md->bs);
2089 /* mempool bind completed, no longer need any mempools in the table */
2090 dm_table_free_md_mempools(t);
2095 * Bind a table to the device.
2097 static void event_callback(void *context)
2099 unsigned long flags;
2101 struct mapped_device *md = (struct mapped_device *) context;
2103 spin_lock_irqsave(&md->uevent_lock, flags);
2104 list_splice_init(&md->uevent_list, &uevents);
2105 spin_unlock_irqrestore(&md->uevent_lock, flags);
2107 dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2109 atomic_inc(&md->event_nr);
2110 wake_up(&md->eventq);
2111 dm_issue_global_event();
2115 * Returns old map, which caller must destroy.
2117 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2118 struct queue_limits *limits)
2120 struct dm_table *old_map;
2124 lockdep_assert_held(&md->suspend_lock);
2126 size = dm_table_get_size(t);
2129 * Wipe any geometry if the size of the table changed.
2131 if (size != dm_get_size(md))
2132 memset(&md->geometry, 0, sizeof(md->geometry));
2134 if (!get_capacity(md->disk))
2135 set_capacity(md->disk, size);
2137 set_capacity_and_notify(md->disk, size);
2139 dm_table_event_callback(t, event_callback, md);
2141 if (dm_table_request_based(t)) {
2143 * Leverage the fact that request-based DM targets are
2144 * immutable singletons - used to optimize dm_mq_queue_rq.
2146 md->immutable_target = dm_table_get_immutable_target(t);
2149 ret = __bind_mempools(md, t);
2151 old_map = ERR_PTR(ret);
2155 ret = dm_table_set_restrictions(t, md->queue, limits);
2157 old_map = ERR_PTR(ret);
2161 old_map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2162 rcu_assign_pointer(md->map, (void *)t);
2163 md->immutable_target_type = dm_table_get_immutable_target_type(t);
2172 * Returns unbound table for the caller to free.
2174 static struct dm_table *__unbind(struct mapped_device *md)
2176 struct dm_table *map = rcu_dereference_protected(md->map, 1);
2181 dm_table_event_callback(map, NULL, NULL);
2182 RCU_INIT_POINTER(md->map, NULL);
2189 * Constructor for a new device.
2191 int dm_create(int minor, struct mapped_device **result)
2193 struct mapped_device *md;
2195 md = alloc_dev(minor);
2199 dm_ima_reset_data(md);
2206 * Functions to manage md->type.
2207 * All are required to hold md->type_lock.
2209 void dm_lock_md_type(struct mapped_device *md)
2211 mutex_lock(&md->type_lock);
2214 void dm_unlock_md_type(struct mapped_device *md)
2216 mutex_unlock(&md->type_lock);
2219 void dm_set_md_type(struct mapped_device *md, enum dm_queue_mode type)
2221 BUG_ON(!mutex_is_locked(&md->type_lock));
2225 enum dm_queue_mode dm_get_md_type(struct mapped_device *md)
2230 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2232 return md->immutable_target_type;
2236 * The queue_limits are only valid as long as you have a reference
2239 struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
2241 BUG_ON(!atomic_read(&md->holders));
2242 return &md->queue->limits;
2244 EXPORT_SYMBOL_GPL(dm_get_queue_limits);
2247 * Setup the DM device's queue based on md's type
2249 int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t)
2251 enum dm_queue_mode type = dm_table_get_type(t);
2252 struct queue_limits limits;
2256 case DM_TYPE_REQUEST_BASED:
2257 md->disk->fops = &dm_rq_blk_dops;
2258 r = dm_mq_init_request_queue(md, t);
2260 DMERR("Cannot initialize queue for request-based dm mapped device");
2264 case DM_TYPE_BIO_BASED:
2265 case DM_TYPE_DAX_BIO_BASED:
2272 r = dm_calculate_queue_limits(t, &limits);
2274 DMERR("Cannot calculate initial queue limits");
2277 r = dm_table_set_restrictions(t, md->queue, &limits);
2281 r = add_disk(md->disk);
2285 r = dm_sysfs_init(md);
2287 del_gendisk(md->disk);
2294 struct mapped_device *dm_get_md(dev_t dev)
2296 struct mapped_device *md;
2297 unsigned minor = MINOR(dev);
2299 if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2302 spin_lock(&_minor_lock);
2304 md = idr_find(&_minor_idr, minor);
2305 if (!md || md == MINOR_ALLOCED || (MINOR(disk_devt(dm_disk(md))) != minor) ||
2306 test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
2312 spin_unlock(&_minor_lock);
2316 EXPORT_SYMBOL_GPL(dm_get_md);
2318 void *dm_get_mdptr(struct mapped_device *md)
2320 return md->interface_ptr;
2323 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2325 md->interface_ptr = ptr;
2328 void dm_get(struct mapped_device *md)
2330 atomic_inc(&md->holders);
2331 BUG_ON(test_bit(DMF_FREEING, &md->flags));
2334 int dm_hold(struct mapped_device *md)
2336 spin_lock(&_minor_lock);
2337 if (test_bit(DMF_FREEING, &md->flags)) {
2338 spin_unlock(&_minor_lock);
2342 spin_unlock(&_minor_lock);
2345 EXPORT_SYMBOL_GPL(dm_hold);
2347 const char *dm_device_name(struct mapped_device *md)
2351 EXPORT_SYMBOL_GPL(dm_device_name);
2353 static void __dm_destroy(struct mapped_device *md, bool wait)
2355 struct dm_table *map;
2360 spin_lock(&_minor_lock);
2361 idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2362 set_bit(DMF_FREEING, &md->flags);
2363 spin_unlock(&_minor_lock);
2365 blk_mark_disk_dead(md->disk);
2368 * Take suspend_lock so that presuspend and postsuspend methods
2369 * do not race with internal suspend.
2371 mutex_lock(&md->suspend_lock);
2372 map = dm_get_live_table(md, &srcu_idx);
2373 if (!dm_suspended_md(md)) {
2374 dm_table_presuspend_targets(map);
2375 set_bit(DMF_SUSPENDED, &md->flags);
2376 set_bit(DMF_POST_SUSPENDING, &md->flags);
2377 dm_table_postsuspend_targets(map);
2379 /* dm_put_live_table must be before msleep, otherwise deadlock is possible */
2380 dm_put_live_table(md, srcu_idx);
2381 mutex_unlock(&md->suspend_lock);
2384 * Rare, but there may be I/O requests still going to complete,
2385 * for example. Wait for all references to disappear.
2386 * No one should increment the reference count of the mapped_device,
2387 * after the mapped_device state becomes DMF_FREEING.
2390 while (atomic_read(&md->holders))
2392 else if (atomic_read(&md->holders))
2393 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2394 dm_device_name(md), atomic_read(&md->holders));
2396 dm_table_destroy(__unbind(md));
2400 void dm_destroy(struct mapped_device *md)
2402 __dm_destroy(md, true);
2405 void dm_destroy_immediate(struct mapped_device *md)
2407 __dm_destroy(md, false);
2410 void dm_put(struct mapped_device *md)
2412 atomic_dec(&md->holders);
2414 EXPORT_SYMBOL_GPL(dm_put);
2416 static bool dm_in_flight_bios(struct mapped_device *md)
2419 unsigned long sum = 0;
2421 for_each_possible_cpu(cpu)
2422 sum += *per_cpu_ptr(md->pending_io, cpu);
2427 static int dm_wait_for_bios_completion(struct mapped_device *md, unsigned int task_state)
2433 prepare_to_wait(&md->wait, &wait, task_state);
2435 if (!dm_in_flight_bios(md))
2438 if (signal_pending_state(task_state, current)) {
2445 finish_wait(&md->wait, &wait);
2452 static int dm_wait_for_completion(struct mapped_device *md, unsigned int task_state)
2456 if (!queue_is_mq(md->queue))
2457 return dm_wait_for_bios_completion(md, task_state);
2460 if (!blk_mq_queue_inflight(md->queue))
2463 if (signal_pending_state(task_state, current)) {
2475 * Process the deferred bios
2477 static void dm_wq_work(struct work_struct *work)
2479 struct mapped_device *md = container_of(work, struct mapped_device, work);
2482 while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2483 spin_lock_irq(&md->deferred_lock);
2484 bio = bio_list_pop(&md->deferred);
2485 spin_unlock_irq(&md->deferred_lock);
2490 submit_bio_noacct(bio);
2494 static void dm_queue_flush(struct mapped_device *md)
2496 clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2497 smp_mb__after_atomic();
2498 queue_work(md->wq, &md->work);
2502 * Swap in a new table, returning the old one for the caller to destroy.
2504 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
2506 struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
2507 struct queue_limits limits;
2510 mutex_lock(&md->suspend_lock);
2512 /* device must be suspended */
2513 if (!dm_suspended_md(md))
2517 * If the new table has no data devices, retain the existing limits.
2518 * This helps multipath with queue_if_no_path if all paths disappear,
2519 * then new I/O is queued based on these limits, and then some paths
2522 if (dm_table_has_no_data_devices(table)) {
2523 live_map = dm_get_live_table_fast(md);
2525 limits = md->queue->limits;
2526 dm_put_live_table_fast(md);
2530 r = dm_calculate_queue_limits(table, &limits);
2537 map = __bind(md, table, &limits);
2538 dm_issue_global_event();
2541 mutex_unlock(&md->suspend_lock);
2546 * Functions to lock and unlock any filesystem running on the
2549 static int lock_fs(struct mapped_device *md)
2553 WARN_ON(test_bit(DMF_FROZEN, &md->flags));
2555 r = freeze_bdev(md->disk->part0);
2557 set_bit(DMF_FROZEN, &md->flags);
2561 static void unlock_fs(struct mapped_device *md)
2563 if (!test_bit(DMF_FROZEN, &md->flags))
2565 thaw_bdev(md->disk->part0);
2566 clear_bit(DMF_FROZEN, &md->flags);
2570 * @suspend_flags: DM_SUSPEND_LOCKFS_FLAG and/or DM_SUSPEND_NOFLUSH_FLAG
2571 * @task_state: e.g. TASK_INTERRUPTIBLE or TASK_UNINTERRUPTIBLE
2572 * @dmf_suspended_flag: DMF_SUSPENDED or DMF_SUSPENDED_INTERNALLY
2574 * If __dm_suspend returns 0, the device is completely quiescent
2575 * now. There is no request-processing activity. All new requests
2576 * are being added to md->deferred list.
2578 static int __dm_suspend(struct mapped_device *md, struct dm_table *map,
2579 unsigned suspend_flags, unsigned int task_state,
2580 int dmf_suspended_flag)
2582 bool do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG;
2583 bool noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG;
2586 lockdep_assert_held(&md->suspend_lock);
2589 * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
2590 * This flag is cleared before dm_suspend returns.
2593 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2595 DMDEBUG("%s: suspending with flush", dm_device_name(md));
2598 * This gets reverted if there's an error later and the targets
2599 * provide the .presuspend_undo hook.
2601 dm_table_presuspend_targets(map);
2604 * Flush I/O to the device.
2605 * Any I/O submitted after lock_fs() may not be flushed.
2606 * noflush takes precedence over do_lockfs.
2607 * (lock_fs() flushes I/Os and waits for them to complete.)
2609 if (!noflush && do_lockfs) {
2612 dm_table_presuspend_undo_targets(map);
2618 * Here we must make sure that no processes are submitting requests
2619 * to target drivers i.e. no one may be executing
2620 * dm_split_and_process_bio from dm_submit_bio.
2622 * To get all processes out of dm_split_and_process_bio in dm_submit_bio,
2623 * we take the write lock. To prevent any process from reentering
2624 * dm_split_and_process_bio from dm_submit_bio and quiesce the thread
2625 * (dm_wq_work), we set DMF_BLOCK_IO_FOR_SUSPEND and call
2626 * flush_workqueue(md->wq).
2628 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2630 synchronize_srcu(&md->io_barrier);
2633 * Stop md->queue before flushing md->wq in case request-based
2634 * dm defers requests to md->wq from md->queue.
2636 if (dm_request_based(md))
2637 dm_stop_queue(md->queue);
2639 flush_workqueue(md->wq);
2642 * At this point no more requests are entering target request routines.
2643 * We call dm_wait_for_completion to wait for all existing requests
2646 r = dm_wait_for_completion(md, task_state);
2648 set_bit(dmf_suspended_flag, &md->flags);
2651 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2653 synchronize_srcu(&md->io_barrier);
2655 /* were we interrupted ? */
2659 if (dm_request_based(md))
2660 dm_start_queue(md->queue);
2663 dm_table_presuspend_undo_targets(map);
2664 /* pushback list is already flushed, so skip flush */
2671 * We need to be able to change a mapping table under a mounted
2672 * filesystem. For example we might want to move some data in
2673 * the background. Before the table can be swapped with
2674 * dm_bind_table, dm_suspend must be called to flush any in
2675 * flight bios and ensure that any further io gets deferred.
2678 * Suspend mechanism in request-based dm.
2680 * 1. Flush all I/Os by lock_fs() if needed.
2681 * 2. Stop dispatching any I/O by stopping the request_queue.
2682 * 3. Wait for all in-flight I/Os to be completed or requeued.
2684 * To abort suspend, start the request_queue.
2686 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
2688 struct dm_table *map = NULL;
2692 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
2694 if (dm_suspended_md(md)) {
2699 if (dm_suspended_internally_md(md)) {
2700 /* already internally suspended, wait for internal resume */
2701 mutex_unlock(&md->suspend_lock);
2702 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
2708 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2710 r = __dm_suspend(md, map, suspend_flags, TASK_INTERRUPTIBLE, DMF_SUSPENDED);
2714 set_bit(DMF_POST_SUSPENDING, &md->flags);
2715 dm_table_postsuspend_targets(map);
2716 clear_bit(DMF_POST_SUSPENDING, &md->flags);
2719 mutex_unlock(&md->suspend_lock);
2723 static int __dm_resume(struct mapped_device *md, struct dm_table *map)
2726 int r = dm_table_resume_targets(map);
2734 * Flushing deferred I/Os must be done after targets are resumed
2735 * so that mapping of targets can work correctly.
2736 * Request-based dm is queueing the deferred I/Os in its request_queue.
2738 if (dm_request_based(md))
2739 dm_start_queue(md->queue);
2746 int dm_resume(struct mapped_device *md)
2749 struct dm_table *map = NULL;
2753 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
2755 if (!dm_suspended_md(md))
2758 if (dm_suspended_internally_md(md)) {
2759 /* already internally suspended, wait for internal resume */
2760 mutex_unlock(&md->suspend_lock);
2761 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
2767 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2768 if (!map || !dm_table_get_size(map))
2771 r = __dm_resume(md, map);
2775 clear_bit(DMF_SUSPENDED, &md->flags);
2777 mutex_unlock(&md->suspend_lock);
2783 * Internal suspend/resume works like userspace-driven suspend. It waits
2784 * until all bios finish and prevents issuing new bios to the target drivers.
2785 * It may be used only from the kernel.
2788 static void __dm_internal_suspend(struct mapped_device *md, unsigned suspend_flags)
2790 struct dm_table *map = NULL;
2792 lockdep_assert_held(&md->suspend_lock);
2794 if (md->internal_suspend_count++)
2795 return; /* nested internal suspend */
2797 if (dm_suspended_md(md)) {
2798 set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
2799 return; /* nest suspend */
2802 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2805 * Using TASK_UNINTERRUPTIBLE because only NOFLUSH internal suspend is
2806 * supported. Properly supporting a TASK_INTERRUPTIBLE internal suspend
2807 * would require changing .presuspend to return an error -- avoid this
2808 * until there is a need for more elaborate variants of internal suspend.
2810 (void) __dm_suspend(md, map, suspend_flags, TASK_UNINTERRUPTIBLE,
2811 DMF_SUSPENDED_INTERNALLY);
2813 set_bit(DMF_POST_SUSPENDING, &md->flags);
2814 dm_table_postsuspend_targets(map);
2815 clear_bit(DMF_POST_SUSPENDING, &md->flags);
2818 static void __dm_internal_resume(struct mapped_device *md)
2820 BUG_ON(!md->internal_suspend_count);
2822 if (--md->internal_suspend_count)
2823 return; /* resume from nested internal suspend */
2825 if (dm_suspended_md(md))
2826 goto done; /* resume from nested suspend */
2829 * NOTE: existing callers don't need to call dm_table_resume_targets
2830 * (which may fail -- so best to avoid it for now by passing NULL map)
2832 (void) __dm_resume(md, NULL);
2835 clear_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
2836 smp_mb__after_atomic();
2837 wake_up_bit(&md->flags, DMF_SUSPENDED_INTERNALLY);
2840 void dm_internal_suspend_noflush(struct mapped_device *md)
2842 mutex_lock(&md->suspend_lock);
2843 __dm_internal_suspend(md, DM_SUSPEND_NOFLUSH_FLAG);
2844 mutex_unlock(&md->suspend_lock);
2846 EXPORT_SYMBOL_GPL(dm_internal_suspend_noflush);
2848 void dm_internal_resume(struct mapped_device *md)
2850 mutex_lock(&md->suspend_lock);
2851 __dm_internal_resume(md);
2852 mutex_unlock(&md->suspend_lock);
2854 EXPORT_SYMBOL_GPL(dm_internal_resume);
2857 * Fast variants of internal suspend/resume hold md->suspend_lock,
2858 * which prevents interaction with userspace-driven suspend.
2861 void dm_internal_suspend_fast(struct mapped_device *md)
2863 mutex_lock(&md->suspend_lock);
2864 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
2867 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2868 synchronize_srcu(&md->io_barrier);
2869 flush_workqueue(md->wq);
2870 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
2872 EXPORT_SYMBOL_GPL(dm_internal_suspend_fast);
2874 void dm_internal_resume_fast(struct mapped_device *md)
2876 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
2882 mutex_unlock(&md->suspend_lock);
2884 EXPORT_SYMBOL_GPL(dm_internal_resume_fast);
2886 /*-----------------------------------------------------------------
2887 * Event notification.
2888 *---------------------------------------------------------------*/
2889 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
2894 char udev_cookie[DM_COOKIE_LENGTH];
2895 char *envp[] = { udev_cookie, NULL };
2897 noio_flag = memalloc_noio_save();
2900 r = kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
2902 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
2903 DM_COOKIE_ENV_VAR_NAME, cookie);
2904 r = kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
2908 memalloc_noio_restore(noio_flag);
2913 uint32_t dm_next_uevent_seq(struct mapped_device *md)
2915 return atomic_add_return(1, &md->uevent_seq);
2918 uint32_t dm_get_event_nr(struct mapped_device *md)
2920 return atomic_read(&md->event_nr);
2923 int dm_wait_event(struct mapped_device *md, int event_nr)
2925 return wait_event_interruptible(md->eventq,
2926 (event_nr != atomic_read(&md->event_nr)));
2929 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
2931 unsigned long flags;
2933 spin_lock_irqsave(&md->uevent_lock, flags);
2934 list_add(elist, &md->uevent_list);
2935 spin_unlock_irqrestore(&md->uevent_lock, flags);
2939 * The gendisk is only valid as long as you have a reference
2942 struct gendisk *dm_disk(struct mapped_device *md)
2946 EXPORT_SYMBOL_GPL(dm_disk);
2948 struct kobject *dm_kobject(struct mapped_device *md)
2950 return &md->kobj_holder.kobj;
2953 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
2955 struct mapped_device *md;
2957 md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
2959 spin_lock(&_minor_lock);
2960 if (test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
2966 spin_unlock(&_minor_lock);
2971 int dm_suspended_md(struct mapped_device *md)
2973 return test_bit(DMF_SUSPENDED, &md->flags);
2976 static int dm_post_suspending_md(struct mapped_device *md)
2978 return test_bit(DMF_POST_SUSPENDING, &md->flags);
2981 int dm_suspended_internally_md(struct mapped_device *md)
2983 return test_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
2986 int dm_test_deferred_remove_flag(struct mapped_device *md)
2988 return test_bit(DMF_DEFERRED_REMOVE, &md->flags);
2991 int dm_suspended(struct dm_target *ti)
2993 return dm_suspended_md(ti->table->md);
2995 EXPORT_SYMBOL_GPL(dm_suspended);
2997 int dm_post_suspending(struct dm_target *ti)
2999 return dm_post_suspending_md(ti->table->md);
3001 EXPORT_SYMBOL_GPL(dm_post_suspending);
3003 int dm_noflush_suspending(struct dm_target *ti)
3005 return __noflush_suspending(ti->table->md);
3007 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
3009 struct dm_md_mempools *dm_alloc_md_mempools(struct mapped_device *md, enum dm_queue_mode type,
3010 unsigned per_io_data_size, unsigned min_pool_size,
3011 bool integrity, bool poll)
3013 struct dm_md_mempools *pools = kzalloc_node(sizeof(*pools), GFP_KERNEL, md->numa_node_id);
3014 unsigned int pool_size = 0;
3015 unsigned int front_pad, io_front_pad;
3022 case DM_TYPE_BIO_BASED:
3023 case DM_TYPE_DAX_BIO_BASED:
3024 pool_size = max(dm_get_reserved_bio_based_ios(), min_pool_size);
3025 front_pad = roundup(per_io_data_size, __alignof__(struct dm_target_io)) + DM_TARGET_IO_BIO_OFFSET;
3026 io_front_pad = roundup(per_io_data_size, __alignof__(struct dm_io)) + DM_IO_BIO_OFFSET;
3027 ret = bioset_init(&pools->io_bs, pool_size, io_front_pad, poll ? BIOSET_PERCPU_CACHE : 0);
3030 if (integrity && bioset_integrity_create(&pools->io_bs, pool_size))
3033 case DM_TYPE_REQUEST_BASED:
3034 pool_size = max(dm_get_reserved_rq_based_ios(), min_pool_size);
3035 front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
3036 /* per_io_data_size is used for blk-mq pdu at queue allocation */
3042 ret = bioset_init(&pools->bs, pool_size, front_pad, 0);
3046 if (integrity && bioset_integrity_create(&pools->bs, pool_size))
3052 dm_free_md_mempools(pools);
3057 void dm_free_md_mempools(struct dm_md_mempools *pools)
3062 bioset_exit(&pools->bs);
3063 bioset_exit(&pools->io_bs);
3075 static int dm_call_pr(struct block_device *bdev, iterate_devices_callout_fn fn,
3078 struct mapped_device *md = bdev->bd_disk->private_data;
3079 struct dm_table *table;
3080 struct dm_target *ti;
3081 int ret = -ENOTTY, srcu_idx;
3083 table = dm_get_live_table(md, &srcu_idx);
3084 if (!table || !dm_table_get_size(table))
3087 /* We only support devices that have a single target */
3088 if (dm_table_get_num_targets(table) != 1)
3090 ti = dm_table_get_target(table, 0);
3093 if (!ti->type->iterate_devices)
3096 ret = ti->type->iterate_devices(ti, fn, data);
3098 dm_put_live_table(md, srcu_idx);
3103 * For register / unregister we need to manually call out to every path.
3105 static int __dm_pr_register(struct dm_target *ti, struct dm_dev *dev,
3106 sector_t start, sector_t len, void *data)
3108 struct dm_pr *pr = data;
3109 const struct pr_ops *ops = dev->bdev->bd_disk->fops->pr_ops;
3111 if (!ops || !ops->pr_register)
3113 return ops->pr_register(dev->bdev, pr->old_key, pr->new_key, pr->flags);
3116 static int dm_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
3127 ret = dm_call_pr(bdev, __dm_pr_register, &pr);
3128 if (ret && new_key) {
3129 /* unregister all paths if we failed to register any path */
3130 pr.old_key = new_key;
3133 pr.fail_early = false;
3134 dm_call_pr(bdev, __dm_pr_register, &pr);
3140 static int dm_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
3143 struct mapped_device *md = bdev->bd_disk->private_data;
3144 const struct pr_ops *ops;
3147 r = dm_prepare_ioctl(md, &srcu_idx, &bdev);
3151 ops = bdev->bd_disk->fops->pr_ops;
3152 if (ops && ops->pr_reserve)
3153 r = ops->pr_reserve(bdev, key, type, flags);
3157 dm_unprepare_ioctl(md, srcu_idx);
3161 static int dm_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
3163 struct mapped_device *md = bdev->bd_disk->private_data;
3164 const struct pr_ops *ops;
3167 r = dm_prepare_ioctl(md, &srcu_idx, &bdev);
3171 ops = bdev->bd_disk->fops->pr_ops;
3172 if (ops && ops->pr_release)
3173 r = ops->pr_release(bdev, key, type);
3177 dm_unprepare_ioctl(md, srcu_idx);
3181 static int dm_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
3182 enum pr_type type, bool abort)
3184 struct mapped_device *md = bdev->bd_disk->private_data;
3185 const struct pr_ops *ops;
3188 r = dm_prepare_ioctl(md, &srcu_idx, &bdev);
3192 ops = bdev->bd_disk->fops->pr_ops;
3193 if (ops && ops->pr_preempt)
3194 r = ops->pr_preempt(bdev, old_key, new_key, type, abort);
3198 dm_unprepare_ioctl(md, srcu_idx);
3202 static int dm_pr_clear(struct block_device *bdev, u64 key)
3204 struct mapped_device *md = bdev->bd_disk->private_data;
3205 const struct pr_ops *ops;
3208 r = dm_prepare_ioctl(md, &srcu_idx, &bdev);
3212 ops = bdev->bd_disk->fops->pr_ops;
3213 if (ops && ops->pr_clear)
3214 r = ops->pr_clear(bdev, key);
3218 dm_unprepare_ioctl(md, srcu_idx);
3222 static const struct pr_ops dm_pr_ops = {
3223 .pr_register = dm_pr_register,
3224 .pr_reserve = dm_pr_reserve,
3225 .pr_release = dm_pr_release,
3226 .pr_preempt = dm_pr_preempt,
3227 .pr_clear = dm_pr_clear,
3230 static const struct block_device_operations dm_blk_dops = {
3231 .submit_bio = dm_submit_bio,
3232 .poll_bio = dm_poll_bio,
3233 .open = dm_blk_open,
3234 .release = dm_blk_close,
3235 .ioctl = dm_blk_ioctl,
3236 .getgeo = dm_blk_getgeo,
3237 .report_zones = dm_blk_report_zones,
3238 .pr_ops = &dm_pr_ops,
3239 .owner = THIS_MODULE
3242 static const struct block_device_operations dm_rq_blk_dops = {
3243 .open = dm_blk_open,
3244 .release = dm_blk_close,
3245 .ioctl = dm_blk_ioctl,
3246 .getgeo = dm_blk_getgeo,
3247 .pr_ops = &dm_pr_ops,
3248 .owner = THIS_MODULE
3251 static const struct dax_operations dm_dax_ops = {
3252 .direct_access = dm_dax_direct_access,
3253 .zero_page_range = dm_dax_zero_page_range,
3254 .recovery_write = dm_dax_recovery_write,
3260 module_init(dm_init);
3261 module_exit(dm_exit);
3263 module_param(major, uint, 0);
3264 MODULE_PARM_DESC(major, "The major number of the device mapper");
3266 module_param(reserved_bio_based_ios, uint, S_IRUGO | S_IWUSR);
3267 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
3269 module_param(dm_numa_node, int, S_IRUGO | S_IWUSR);
3270 MODULE_PARM_DESC(dm_numa_node, "NUMA node for DM device memory allocations");
3272 module_param(swap_bios, int, S_IRUGO | S_IWUSR);
3273 MODULE_PARM_DESC(swap_bios, "Maximum allowed inflight swap IOs");
3275 MODULE_DESCRIPTION(DM_NAME " driver");
3276 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
3277 MODULE_LICENSE("GPL");