gro: Allow tunnel stacking in the case of FOU/GUE
[linux/fpc-iii.git] / drivers / md / dm.c
blob87de9a0848b7cb7b09360b659797e7fffae0d01b
1 /*
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.
6 */
8 #include "dm.h"
9 #include "dm-uevent.h"
11 #include <linux/init.h>
12 #include <linux/module.h>
13 #include <linux/mutex.h>
14 #include <linux/moduleparam.h>
15 #include <linux/blkpg.h>
16 #include <linux/bio.h>
17 #include <linux/mempool.h>
18 #include <linux/slab.h>
19 #include <linux/idr.h>
20 #include <linux/hdreg.h>
21 #include <linux/delay.h>
22 #include <linux/wait.h>
23 #include <linux/kthread.h>
24 #include <linux/ktime.h>
25 #include <linux/elevator.h> /* for rq_end_sector() */
26 #include <linux/blk-mq.h>
28 #include <trace/events/block.h>
30 #define DM_MSG_PREFIX "core"
32 #ifdef CONFIG_PRINTK
34 * ratelimit state to be used in DMXXX_LIMIT().
36 DEFINE_RATELIMIT_STATE(dm_ratelimit_state,
37 DEFAULT_RATELIMIT_INTERVAL,
38 DEFAULT_RATELIMIT_BURST);
39 EXPORT_SYMBOL(dm_ratelimit_state);
40 #endif
43 * Cookies are numeric values sent with CHANGE and REMOVE
44 * uevents while resuming, removing or renaming the device.
46 #define DM_COOKIE_ENV_VAR_NAME "DM_COOKIE"
47 #define DM_COOKIE_LENGTH 24
49 static const char *_name = DM_NAME;
51 static unsigned int major = 0;
52 static unsigned int _major = 0;
54 static DEFINE_IDR(_minor_idr);
56 static DEFINE_SPINLOCK(_minor_lock);
58 static void do_deferred_remove(struct work_struct *w);
60 static DECLARE_WORK(deferred_remove_work, do_deferred_remove);
62 static struct workqueue_struct *deferred_remove_workqueue;
65 * For bio-based dm.
66 * One of these is allocated per bio.
68 struct dm_io {
69 struct mapped_device *md;
70 int error;
71 atomic_t io_count;
72 struct bio *bio;
73 unsigned long start_time;
74 spinlock_t endio_lock;
75 struct dm_stats_aux stats_aux;
79 * For request-based dm.
80 * One of these is allocated per request.
82 struct dm_rq_target_io {
83 struct mapped_device *md;
84 struct dm_target *ti;
85 struct request *orig, *clone;
86 struct kthread_work work;
87 int error;
88 union map_info info;
92 * For request-based dm - the bio clones we allocate are embedded in these
93 * structs.
95 * We allocate these with bio_alloc_bioset, using the front_pad parameter when
96 * the bioset is created - this means the bio has to come at the end of the
97 * struct.
99 struct dm_rq_clone_bio_info {
100 struct bio *orig;
101 struct dm_rq_target_io *tio;
102 struct bio clone;
105 union map_info *dm_get_rq_mapinfo(struct request *rq)
107 if (rq && rq->end_io_data)
108 return &((struct dm_rq_target_io *)rq->end_io_data)->info;
109 return NULL;
111 EXPORT_SYMBOL_GPL(dm_get_rq_mapinfo);
113 #define MINOR_ALLOCED ((void *)-1)
116 * Bits for the md->flags field.
118 #define DMF_BLOCK_IO_FOR_SUSPEND 0
119 #define DMF_SUSPENDED 1
120 #define DMF_FROZEN 2
121 #define DMF_FREEING 3
122 #define DMF_DELETING 4
123 #define DMF_NOFLUSH_SUSPENDING 5
124 #define DMF_MERGE_IS_OPTIONAL 6
125 #define DMF_DEFERRED_REMOVE 7
126 #define DMF_SUSPENDED_INTERNALLY 8
129 * A dummy definition to make RCU happy.
130 * struct dm_table should never be dereferenced in this file.
132 struct dm_table {
133 int undefined__;
137 * Work processed by per-device workqueue.
139 struct mapped_device {
140 struct srcu_struct io_barrier;
141 struct mutex suspend_lock;
142 atomic_t holders;
143 atomic_t open_count;
146 * The current mapping.
147 * Use dm_get_live_table{_fast} or take suspend_lock for
148 * dereference.
150 struct dm_table __rcu *map;
152 struct list_head table_devices;
153 struct mutex table_devices_lock;
155 unsigned long flags;
157 struct request_queue *queue;
158 unsigned type;
159 /* Protect queue and type against concurrent access. */
160 struct mutex type_lock;
162 struct target_type *immutable_target_type;
164 struct gendisk *disk;
165 char name[16];
167 void *interface_ptr;
170 * A list of ios that arrived while we were suspended.
172 atomic_t pending[2];
173 wait_queue_head_t wait;
174 struct work_struct work;
175 struct bio_list deferred;
176 spinlock_t deferred_lock;
179 * Processing queue (flush)
181 struct workqueue_struct *wq;
184 * io objects are allocated from here.
186 mempool_t *io_pool;
187 mempool_t *rq_pool;
189 struct bio_set *bs;
192 * Event handling.
194 atomic_t event_nr;
195 wait_queue_head_t eventq;
196 atomic_t uevent_seq;
197 struct list_head uevent_list;
198 spinlock_t uevent_lock; /* Protect access to uevent_list */
201 * freeze/thaw support require holding onto a super block
203 struct super_block *frozen_sb;
204 struct block_device *bdev;
206 /* forced geometry settings */
207 struct hd_geometry geometry;
209 /* kobject and completion */
210 struct dm_kobject_holder kobj_holder;
212 /* zero-length flush that will be cloned and submitted to targets */
213 struct bio flush_bio;
215 /* the number of internal suspends */
216 unsigned internal_suspend_count;
218 struct dm_stats stats;
220 struct kthread_worker kworker;
221 struct task_struct *kworker_task;
223 /* for request-based merge heuristic in dm_request_fn() */
224 unsigned seq_rq_merge_deadline_usecs;
225 int last_rq_rw;
226 sector_t last_rq_pos;
227 ktime_t last_rq_start_time;
229 /* for blk-mq request-based DM support */
230 struct blk_mq_tag_set tag_set;
231 bool use_blk_mq;
234 #ifdef CONFIG_DM_MQ_DEFAULT
235 static bool use_blk_mq = true;
236 #else
237 static bool use_blk_mq = false;
238 #endif
240 bool dm_use_blk_mq(struct mapped_device *md)
242 return md->use_blk_mq;
246 * For mempools pre-allocation at the table loading time.
248 struct dm_md_mempools {
249 mempool_t *io_pool;
250 mempool_t *rq_pool;
251 struct bio_set *bs;
254 struct table_device {
255 struct list_head list;
256 atomic_t count;
257 struct dm_dev dm_dev;
260 #define RESERVED_BIO_BASED_IOS 16
261 #define RESERVED_REQUEST_BASED_IOS 256
262 #define RESERVED_MAX_IOS 1024
263 static struct kmem_cache *_io_cache;
264 static struct kmem_cache *_rq_tio_cache;
265 static struct kmem_cache *_rq_cache;
268 * Bio-based DM's mempools' reserved IOs set by the user.
270 static unsigned reserved_bio_based_ios = RESERVED_BIO_BASED_IOS;
273 * Request-based DM's mempools' reserved IOs set by the user.
275 static unsigned reserved_rq_based_ios = RESERVED_REQUEST_BASED_IOS;
277 static unsigned __dm_get_module_param(unsigned *module_param,
278 unsigned def, unsigned max)
280 unsigned param = ACCESS_ONCE(*module_param);
281 unsigned modified_param = 0;
283 if (!param)
284 modified_param = def;
285 else if (param > max)
286 modified_param = max;
288 if (modified_param) {
289 (void)cmpxchg(module_param, param, modified_param);
290 param = modified_param;
293 return param;
296 unsigned dm_get_reserved_bio_based_ios(void)
298 return __dm_get_module_param(&reserved_bio_based_ios,
299 RESERVED_BIO_BASED_IOS, RESERVED_MAX_IOS);
301 EXPORT_SYMBOL_GPL(dm_get_reserved_bio_based_ios);
303 unsigned dm_get_reserved_rq_based_ios(void)
305 return __dm_get_module_param(&reserved_rq_based_ios,
306 RESERVED_REQUEST_BASED_IOS, RESERVED_MAX_IOS);
308 EXPORT_SYMBOL_GPL(dm_get_reserved_rq_based_ios);
310 static int __init local_init(void)
312 int r = -ENOMEM;
314 /* allocate a slab for the dm_ios */
315 _io_cache = KMEM_CACHE(dm_io, 0);
316 if (!_io_cache)
317 return r;
319 _rq_tio_cache = KMEM_CACHE(dm_rq_target_io, 0);
320 if (!_rq_tio_cache)
321 goto out_free_io_cache;
323 _rq_cache = kmem_cache_create("dm_clone_request", sizeof(struct request),
324 __alignof__(struct request), 0, NULL);
325 if (!_rq_cache)
326 goto out_free_rq_tio_cache;
328 r = dm_uevent_init();
329 if (r)
330 goto out_free_rq_cache;
332 deferred_remove_workqueue = alloc_workqueue("kdmremove", WQ_UNBOUND, 1);
333 if (!deferred_remove_workqueue) {
334 r = -ENOMEM;
335 goto out_uevent_exit;
338 _major = major;
339 r = register_blkdev(_major, _name);
340 if (r < 0)
341 goto out_free_workqueue;
343 if (!_major)
344 _major = r;
346 return 0;
348 out_free_workqueue:
349 destroy_workqueue(deferred_remove_workqueue);
350 out_uevent_exit:
351 dm_uevent_exit();
352 out_free_rq_cache:
353 kmem_cache_destroy(_rq_cache);
354 out_free_rq_tio_cache:
355 kmem_cache_destroy(_rq_tio_cache);
356 out_free_io_cache:
357 kmem_cache_destroy(_io_cache);
359 return r;
362 static void local_exit(void)
364 flush_scheduled_work();
365 destroy_workqueue(deferred_remove_workqueue);
367 kmem_cache_destroy(_rq_cache);
368 kmem_cache_destroy(_rq_tio_cache);
369 kmem_cache_destroy(_io_cache);
370 unregister_blkdev(_major, _name);
371 dm_uevent_exit();
373 _major = 0;
375 DMINFO("cleaned up");
378 static int (*_inits[])(void) __initdata = {
379 local_init,
380 dm_target_init,
381 dm_linear_init,
382 dm_stripe_init,
383 dm_io_init,
384 dm_kcopyd_init,
385 dm_interface_init,
386 dm_statistics_init,
389 static void (*_exits[])(void) = {
390 local_exit,
391 dm_target_exit,
392 dm_linear_exit,
393 dm_stripe_exit,
394 dm_io_exit,
395 dm_kcopyd_exit,
396 dm_interface_exit,
397 dm_statistics_exit,
400 static int __init dm_init(void)
402 const int count = ARRAY_SIZE(_inits);
404 int r, i;
406 for (i = 0; i < count; i++) {
407 r = _inits[i]();
408 if (r)
409 goto bad;
412 return 0;
414 bad:
415 while (i--)
416 _exits[i]();
418 return r;
421 static void __exit dm_exit(void)
423 int i = ARRAY_SIZE(_exits);
425 while (i--)
426 _exits[i]();
429 * Should be empty by this point.
431 idr_destroy(&_minor_idr);
435 * Block device functions
437 int dm_deleting_md(struct mapped_device *md)
439 return test_bit(DMF_DELETING, &md->flags);
442 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
444 struct mapped_device *md;
446 spin_lock(&_minor_lock);
448 md = bdev->bd_disk->private_data;
449 if (!md)
450 goto out;
452 if (test_bit(DMF_FREEING, &md->flags) ||
453 dm_deleting_md(md)) {
454 md = NULL;
455 goto out;
458 dm_get(md);
459 atomic_inc(&md->open_count);
460 out:
461 spin_unlock(&_minor_lock);
463 return md ? 0 : -ENXIO;
466 static void dm_blk_close(struct gendisk *disk, fmode_t mode)
468 struct mapped_device *md;
470 spin_lock(&_minor_lock);
472 md = disk->private_data;
473 if (WARN_ON(!md))
474 goto out;
476 if (atomic_dec_and_test(&md->open_count) &&
477 (test_bit(DMF_DEFERRED_REMOVE, &md->flags)))
478 queue_work(deferred_remove_workqueue, &deferred_remove_work);
480 dm_put(md);
481 out:
482 spin_unlock(&_minor_lock);
485 int dm_open_count(struct mapped_device *md)
487 return atomic_read(&md->open_count);
491 * Guarantees nothing is using the device before it's deleted.
493 int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
495 int r = 0;
497 spin_lock(&_minor_lock);
499 if (dm_open_count(md)) {
500 r = -EBUSY;
501 if (mark_deferred)
502 set_bit(DMF_DEFERRED_REMOVE, &md->flags);
503 } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
504 r = -EEXIST;
505 else
506 set_bit(DMF_DELETING, &md->flags);
508 spin_unlock(&_minor_lock);
510 return r;
513 int dm_cancel_deferred_remove(struct mapped_device *md)
515 int r = 0;
517 spin_lock(&_minor_lock);
519 if (test_bit(DMF_DELETING, &md->flags))
520 r = -EBUSY;
521 else
522 clear_bit(DMF_DEFERRED_REMOVE, &md->flags);
524 spin_unlock(&_minor_lock);
526 return r;
529 static void do_deferred_remove(struct work_struct *w)
531 dm_deferred_remove();
534 sector_t dm_get_size(struct mapped_device *md)
536 return get_capacity(md->disk);
539 struct request_queue *dm_get_md_queue(struct mapped_device *md)
541 return md->queue;
544 struct dm_stats *dm_get_stats(struct mapped_device *md)
546 return &md->stats;
549 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
551 struct mapped_device *md = bdev->bd_disk->private_data;
553 return dm_get_geometry(md, geo);
556 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
557 unsigned int cmd, unsigned long arg)
559 struct mapped_device *md = bdev->bd_disk->private_data;
560 int srcu_idx;
561 struct dm_table *map;
562 struct dm_target *tgt;
563 int r = -ENOTTY;
565 retry:
566 map = dm_get_live_table(md, &srcu_idx);
568 if (!map || !dm_table_get_size(map))
569 goto out;
571 /* We only support devices that have a single target */
572 if (dm_table_get_num_targets(map) != 1)
573 goto out;
575 tgt = dm_table_get_target(map, 0);
576 if (!tgt->type->ioctl)
577 goto out;
579 if (dm_suspended_md(md)) {
580 r = -EAGAIN;
581 goto out;
584 r = tgt->type->ioctl(tgt, cmd, arg);
586 out:
587 dm_put_live_table(md, srcu_idx);
589 if (r == -ENOTCONN) {
590 msleep(10);
591 goto retry;
594 return r;
597 static struct dm_io *alloc_io(struct mapped_device *md)
599 return mempool_alloc(md->io_pool, GFP_NOIO);
602 static void free_io(struct mapped_device *md, struct dm_io *io)
604 mempool_free(io, md->io_pool);
607 static void free_tio(struct mapped_device *md, struct dm_target_io *tio)
609 bio_put(&tio->clone);
612 static struct dm_rq_target_io *alloc_rq_tio(struct mapped_device *md,
613 gfp_t gfp_mask)
615 return mempool_alloc(md->io_pool, gfp_mask);
618 static void free_rq_tio(struct dm_rq_target_io *tio)
620 mempool_free(tio, tio->md->io_pool);
623 static struct request *alloc_clone_request(struct mapped_device *md,
624 gfp_t gfp_mask)
626 return mempool_alloc(md->rq_pool, gfp_mask);
629 static void free_clone_request(struct mapped_device *md, struct request *rq)
631 mempool_free(rq, md->rq_pool);
634 static int md_in_flight(struct mapped_device *md)
636 return atomic_read(&md->pending[READ]) +
637 atomic_read(&md->pending[WRITE]);
640 static void start_io_acct(struct dm_io *io)
642 struct mapped_device *md = io->md;
643 struct bio *bio = io->bio;
644 int cpu;
645 int rw = bio_data_dir(bio);
647 io->start_time = jiffies;
649 cpu = part_stat_lock();
650 part_round_stats(cpu, &dm_disk(md)->part0);
651 part_stat_unlock();
652 atomic_set(&dm_disk(md)->part0.in_flight[rw],
653 atomic_inc_return(&md->pending[rw]));
655 if (unlikely(dm_stats_used(&md->stats)))
656 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_iter.bi_sector,
657 bio_sectors(bio), false, 0, &io->stats_aux);
660 static void end_io_acct(struct dm_io *io)
662 struct mapped_device *md = io->md;
663 struct bio *bio = io->bio;
664 unsigned long duration = jiffies - io->start_time;
665 int pending;
666 int rw = bio_data_dir(bio);
668 generic_end_io_acct(rw, &dm_disk(md)->part0, io->start_time);
670 if (unlikely(dm_stats_used(&md->stats)))
671 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_iter.bi_sector,
672 bio_sectors(bio), true, duration, &io->stats_aux);
675 * After this is decremented the bio must not be touched if it is
676 * a flush.
678 pending = atomic_dec_return(&md->pending[rw]);
679 atomic_set(&dm_disk(md)->part0.in_flight[rw], pending);
680 pending += atomic_read(&md->pending[rw^0x1]);
682 /* nudge anyone waiting on suspend queue */
683 if (!pending)
684 wake_up(&md->wait);
688 * Add the bio to the list of deferred io.
690 static void queue_io(struct mapped_device *md, struct bio *bio)
692 unsigned long flags;
694 spin_lock_irqsave(&md->deferred_lock, flags);
695 bio_list_add(&md->deferred, bio);
696 spin_unlock_irqrestore(&md->deferred_lock, flags);
697 queue_work(md->wq, &md->work);
701 * Everyone (including functions in this file), should use this
702 * function to access the md->map field, and make sure they call
703 * dm_put_live_table() when finished.
705 struct dm_table *dm_get_live_table(struct mapped_device *md, int *srcu_idx) __acquires(md->io_barrier)
707 *srcu_idx = srcu_read_lock(&md->io_barrier);
709 return srcu_dereference(md->map, &md->io_barrier);
712 void dm_put_live_table(struct mapped_device *md, int srcu_idx) __releases(md->io_barrier)
714 srcu_read_unlock(&md->io_barrier, srcu_idx);
717 void dm_sync_table(struct mapped_device *md)
719 synchronize_srcu(&md->io_barrier);
720 synchronize_rcu_expedited();
724 * A fast alternative to dm_get_live_table/dm_put_live_table.
725 * The caller must not block between these two functions.
727 static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
729 rcu_read_lock();
730 return rcu_dereference(md->map);
733 static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
735 rcu_read_unlock();
739 * Open a table device so we can use it as a map destination.
741 static int open_table_device(struct table_device *td, dev_t dev,
742 struct mapped_device *md)
744 static char *_claim_ptr = "I belong to device-mapper";
745 struct block_device *bdev;
747 int r;
749 BUG_ON(td->dm_dev.bdev);
751 bdev = blkdev_get_by_dev(dev, td->dm_dev.mode | FMODE_EXCL, _claim_ptr);
752 if (IS_ERR(bdev))
753 return PTR_ERR(bdev);
755 r = bd_link_disk_holder(bdev, dm_disk(md));
756 if (r) {
757 blkdev_put(bdev, td->dm_dev.mode | FMODE_EXCL);
758 return r;
761 td->dm_dev.bdev = bdev;
762 return 0;
766 * Close a table device that we've been using.
768 static void close_table_device(struct table_device *td, struct mapped_device *md)
770 if (!td->dm_dev.bdev)
771 return;
773 bd_unlink_disk_holder(td->dm_dev.bdev, dm_disk(md));
774 blkdev_put(td->dm_dev.bdev, td->dm_dev.mode | FMODE_EXCL);
775 td->dm_dev.bdev = NULL;
778 static struct table_device *find_table_device(struct list_head *l, dev_t dev,
779 fmode_t mode) {
780 struct table_device *td;
782 list_for_each_entry(td, l, list)
783 if (td->dm_dev.bdev->bd_dev == dev && td->dm_dev.mode == mode)
784 return td;
786 return NULL;
789 int dm_get_table_device(struct mapped_device *md, dev_t dev, fmode_t mode,
790 struct dm_dev **result) {
791 int r;
792 struct table_device *td;
794 mutex_lock(&md->table_devices_lock);
795 td = find_table_device(&md->table_devices, dev, mode);
796 if (!td) {
797 td = kmalloc(sizeof(*td), GFP_KERNEL);
798 if (!td) {
799 mutex_unlock(&md->table_devices_lock);
800 return -ENOMEM;
803 td->dm_dev.mode = mode;
804 td->dm_dev.bdev = NULL;
806 if ((r = open_table_device(td, dev, md))) {
807 mutex_unlock(&md->table_devices_lock);
808 kfree(td);
809 return r;
812 format_dev_t(td->dm_dev.name, dev);
814 atomic_set(&td->count, 0);
815 list_add(&td->list, &md->table_devices);
817 atomic_inc(&td->count);
818 mutex_unlock(&md->table_devices_lock);
820 *result = &td->dm_dev;
821 return 0;
823 EXPORT_SYMBOL_GPL(dm_get_table_device);
825 void dm_put_table_device(struct mapped_device *md, struct dm_dev *d)
827 struct table_device *td = container_of(d, struct table_device, dm_dev);
829 mutex_lock(&md->table_devices_lock);
830 if (atomic_dec_and_test(&td->count)) {
831 close_table_device(td, md);
832 list_del(&td->list);
833 kfree(td);
835 mutex_unlock(&md->table_devices_lock);
837 EXPORT_SYMBOL(dm_put_table_device);
839 static void free_table_devices(struct list_head *devices)
841 struct list_head *tmp, *next;
843 list_for_each_safe(tmp, next, devices) {
844 struct table_device *td = list_entry(tmp, struct table_device, list);
846 DMWARN("dm_destroy: %s still exists with %d references",
847 td->dm_dev.name, atomic_read(&td->count));
848 kfree(td);
853 * Get the geometry associated with a dm device
855 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
857 *geo = md->geometry;
859 return 0;
863 * Set the geometry of a device.
865 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
867 sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
869 if (geo->start > sz) {
870 DMWARN("Start sector is beyond the geometry limits.");
871 return -EINVAL;
874 md->geometry = *geo;
876 return 0;
879 /*-----------------------------------------------------------------
880 * CRUD START:
881 * A more elegant soln is in the works that uses the queue
882 * merge fn, unfortunately there are a couple of changes to
883 * the block layer that I want to make for this. So in the
884 * interests of getting something for people to use I give
885 * you this clearly demarcated crap.
886 *---------------------------------------------------------------*/
888 static int __noflush_suspending(struct mapped_device *md)
890 return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
894 * Decrements the number of outstanding ios that a bio has been
895 * cloned into, completing the original io if necc.
897 static void dec_pending(struct dm_io *io, int error)
899 unsigned long flags;
900 int io_error;
901 struct bio *bio;
902 struct mapped_device *md = io->md;
904 /* Push-back supersedes any I/O errors */
905 if (unlikely(error)) {
906 spin_lock_irqsave(&io->endio_lock, flags);
907 if (!(io->error > 0 && __noflush_suspending(md)))
908 io->error = error;
909 spin_unlock_irqrestore(&io->endio_lock, flags);
912 if (atomic_dec_and_test(&io->io_count)) {
913 if (io->error == DM_ENDIO_REQUEUE) {
915 * Target requested pushing back the I/O.
917 spin_lock_irqsave(&md->deferred_lock, flags);
918 if (__noflush_suspending(md))
919 bio_list_add_head(&md->deferred, io->bio);
920 else
921 /* noflush suspend was interrupted. */
922 io->error = -EIO;
923 spin_unlock_irqrestore(&md->deferred_lock, flags);
926 io_error = io->error;
927 bio = io->bio;
928 end_io_acct(io);
929 free_io(md, io);
931 if (io_error == DM_ENDIO_REQUEUE)
932 return;
934 if ((bio->bi_rw & REQ_FLUSH) && bio->bi_iter.bi_size) {
936 * Preflush done for flush with data, reissue
937 * without REQ_FLUSH.
939 bio->bi_rw &= ~REQ_FLUSH;
940 queue_io(md, bio);
941 } else {
942 /* done with normal IO or empty flush */
943 trace_block_bio_complete(md->queue, bio, io_error);
944 bio_endio(bio, io_error);
949 static void disable_write_same(struct mapped_device *md)
951 struct queue_limits *limits = dm_get_queue_limits(md);
953 /* device doesn't really support WRITE SAME, disable it */
954 limits->max_write_same_sectors = 0;
957 static void clone_endio(struct bio *bio, int error)
959 int r = error;
960 struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
961 struct dm_io *io = tio->io;
962 struct mapped_device *md = tio->io->md;
963 dm_endio_fn endio = tio->ti->type->end_io;
965 if (!bio_flagged(bio, BIO_UPTODATE) && !error)
966 error = -EIO;
968 if (endio) {
969 r = endio(tio->ti, bio, error);
970 if (r < 0 || r == DM_ENDIO_REQUEUE)
972 * error and requeue request are handled
973 * in dec_pending().
975 error = r;
976 else if (r == DM_ENDIO_INCOMPLETE)
977 /* The target will handle the io */
978 return;
979 else if (r) {
980 DMWARN("unimplemented target endio return value: %d", r);
981 BUG();
985 if (unlikely(r == -EREMOTEIO && (bio->bi_rw & REQ_WRITE_SAME) &&
986 !bdev_get_queue(bio->bi_bdev)->limits.max_write_same_sectors))
987 disable_write_same(md);
989 free_tio(md, tio);
990 dec_pending(io, error);
994 * Partial completion handling for request-based dm
996 static void end_clone_bio(struct bio *clone, int error)
998 struct dm_rq_clone_bio_info *info =
999 container_of(clone, struct dm_rq_clone_bio_info, clone);
1000 struct dm_rq_target_io *tio = info->tio;
1001 struct bio *bio = info->orig;
1002 unsigned int nr_bytes = info->orig->bi_iter.bi_size;
1004 bio_put(clone);
1006 if (tio->error)
1008 * An error has already been detected on the request.
1009 * Once error occurred, just let clone->end_io() handle
1010 * the remainder.
1012 return;
1013 else if (error) {
1015 * Don't notice the error to the upper layer yet.
1016 * The error handling decision is made by the target driver,
1017 * when the request is completed.
1019 tio->error = error;
1020 return;
1024 * I/O for the bio successfully completed.
1025 * Notice the data completion to the upper layer.
1029 * bios are processed from the head of the list.
1030 * So the completing bio should always be rq->bio.
1031 * If it's not, something wrong is happening.
1033 if (tio->orig->bio != bio)
1034 DMERR("bio completion is going in the middle of the request");
1037 * Update the original request.
1038 * Do not use blk_end_request() here, because it may complete
1039 * the original request before the clone, and break the ordering.
1041 blk_update_request(tio->orig, 0, nr_bytes);
1044 static struct dm_rq_target_io *tio_from_request(struct request *rq)
1046 return (rq->q->mq_ops ? blk_mq_rq_to_pdu(rq) : rq->special);
1050 * Don't touch any member of the md after calling this function because
1051 * the md may be freed in dm_put() at the end of this function.
1052 * Or do dm_get() before calling this function and dm_put() later.
1054 static void rq_completed(struct mapped_device *md, int rw, bool run_queue)
1056 atomic_dec(&md->pending[rw]);
1058 /* nudge anyone waiting on suspend queue */
1059 if (!md_in_flight(md))
1060 wake_up(&md->wait);
1063 * Run this off this callpath, as drivers could invoke end_io while
1064 * inside their request_fn (and holding the queue lock). Calling
1065 * back into ->request_fn() could deadlock attempting to grab the
1066 * queue lock again.
1068 if (!md->queue->mq_ops && run_queue)
1069 blk_run_queue_async(md->queue);
1072 * dm_put() must be at the end of this function. See the comment above
1074 dm_put(md);
1077 static void free_rq_clone(struct request *clone)
1079 struct dm_rq_target_io *tio = clone->end_io_data;
1080 struct mapped_device *md = tio->md;
1082 blk_rq_unprep_clone(clone);
1084 if (md->type == DM_TYPE_MQ_REQUEST_BASED)
1085 /* stacked on blk-mq queue(s) */
1086 tio->ti->type->release_clone_rq(clone);
1087 else if (!md->queue->mq_ops)
1088 /* request_fn queue stacked on request_fn queue(s) */
1089 free_clone_request(md, clone);
1091 * NOTE: for the blk-mq queue stacked on request_fn queue(s) case:
1092 * no need to call free_clone_request() because we leverage blk-mq by
1093 * allocating the clone at the end of the blk-mq pdu (see: clone_rq)
1096 if (!md->queue->mq_ops)
1097 free_rq_tio(tio);
1101 * Complete the clone and the original request.
1102 * Must be called without clone's queue lock held,
1103 * see end_clone_request() for more details.
1105 static void dm_end_request(struct request *clone, int error)
1107 int rw = rq_data_dir(clone);
1108 struct dm_rq_target_io *tio = clone->end_io_data;
1109 struct mapped_device *md = tio->md;
1110 struct request *rq = tio->orig;
1112 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
1113 rq->errors = clone->errors;
1114 rq->resid_len = clone->resid_len;
1116 if (rq->sense)
1118 * We are using the sense buffer of the original
1119 * request.
1120 * So setting the length of the sense data is enough.
1122 rq->sense_len = clone->sense_len;
1125 free_rq_clone(clone);
1126 if (!rq->q->mq_ops)
1127 blk_end_request_all(rq, error);
1128 else
1129 blk_mq_end_request(rq, error);
1130 rq_completed(md, rw, true);
1133 static void dm_unprep_request(struct request *rq)
1135 struct dm_rq_target_io *tio = tio_from_request(rq);
1136 struct request *clone = tio->clone;
1138 if (!rq->q->mq_ops) {
1139 rq->special = NULL;
1140 rq->cmd_flags &= ~REQ_DONTPREP;
1143 if (clone)
1144 free_rq_clone(clone);
1145 else if (!tio->md->queue->mq_ops)
1146 free_rq_tio(tio);
1150 * Requeue the original request of a clone.
1152 static void old_requeue_request(struct request *rq)
1154 struct request_queue *q = rq->q;
1155 unsigned long flags;
1157 spin_lock_irqsave(q->queue_lock, flags);
1158 blk_requeue_request(q, rq);
1159 blk_run_queue_async(q);
1160 spin_unlock_irqrestore(q->queue_lock, flags);
1163 static void dm_requeue_unmapped_original_request(struct mapped_device *md,
1164 struct request *rq)
1166 int rw = rq_data_dir(rq);
1168 dm_unprep_request(rq);
1170 if (!rq->q->mq_ops)
1171 old_requeue_request(rq);
1172 else {
1173 blk_mq_requeue_request(rq);
1174 blk_mq_kick_requeue_list(rq->q);
1177 rq_completed(md, rw, false);
1180 static void dm_requeue_unmapped_request(struct request *clone)
1182 struct dm_rq_target_io *tio = clone->end_io_data;
1184 dm_requeue_unmapped_original_request(tio->md, tio->orig);
1187 static void old_stop_queue(struct request_queue *q)
1189 unsigned long flags;
1191 if (blk_queue_stopped(q))
1192 return;
1194 spin_lock_irqsave(q->queue_lock, flags);
1195 blk_stop_queue(q);
1196 spin_unlock_irqrestore(q->queue_lock, flags);
1199 static void stop_queue(struct request_queue *q)
1201 if (!q->mq_ops)
1202 old_stop_queue(q);
1203 else {
1204 spin_lock_irq(q->queue_lock);
1205 queue_flag_set(QUEUE_FLAG_STOPPED, q);
1206 spin_unlock_irq(q->queue_lock);
1208 blk_mq_cancel_requeue_work(q);
1209 blk_mq_stop_hw_queues(q);
1213 static void old_start_queue(struct request_queue *q)
1215 unsigned long flags;
1217 spin_lock_irqsave(q->queue_lock, flags);
1218 if (blk_queue_stopped(q))
1219 blk_start_queue(q);
1220 spin_unlock_irqrestore(q->queue_lock, flags);
1223 static void start_queue(struct request_queue *q)
1225 if (!q->mq_ops)
1226 old_start_queue(q);
1227 else {
1228 queue_flag_clear_unlocked(QUEUE_FLAG_STOPPED, q);
1229 blk_mq_start_stopped_hw_queues(q, true);
1233 static void dm_done(struct request *clone, int error, bool mapped)
1235 int r = error;
1236 struct dm_rq_target_io *tio = clone->end_io_data;
1237 dm_request_endio_fn rq_end_io = NULL;
1239 if (tio->ti) {
1240 rq_end_io = tio->ti->type->rq_end_io;
1242 if (mapped && rq_end_io)
1243 r = rq_end_io(tio->ti, clone, error, &tio->info);
1246 if (unlikely(r == -EREMOTEIO && (clone->cmd_flags & REQ_WRITE_SAME) &&
1247 !clone->q->limits.max_write_same_sectors))
1248 disable_write_same(tio->md);
1250 if (r <= 0)
1251 /* The target wants to complete the I/O */
1252 dm_end_request(clone, r);
1253 else if (r == DM_ENDIO_INCOMPLETE)
1254 /* The target will handle the I/O */
1255 return;
1256 else if (r == DM_ENDIO_REQUEUE)
1257 /* The target wants to requeue the I/O */
1258 dm_requeue_unmapped_request(clone);
1259 else {
1260 DMWARN("unimplemented target endio return value: %d", r);
1261 BUG();
1266 * Request completion handler for request-based dm
1268 static void dm_softirq_done(struct request *rq)
1270 bool mapped = true;
1271 struct dm_rq_target_io *tio = tio_from_request(rq);
1272 struct request *clone = tio->clone;
1273 int rw;
1275 if (!clone) {
1276 rw = rq_data_dir(rq);
1277 if (!rq->q->mq_ops) {
1278 blk_end_request_all(rq, tio->error);
1279 rq_completed(tio->md, rw, false);
1280 free_rq_tio(tio);
1281 } else {
1282 blk_mq_end_request(rq, tio->error);
1283 rq_completed(tio->md, rw, false);
1285 return;
1288 if (rq->cmd_flags & REQ_FAILED)
1289 mapped = false;
1291 dm_done(clone, tio->error, mapped);
1295 * Complete the clone and the original request with the error status
1296 * through softirq context.
1298 static void dm_complete_request(struct request *rq, int error)
1300 struct dm_rq_target_io *tio = tio_from_request(rq);
1302 tio->error = error;
1303 if (!rq->q->mq_ops)
1304 blk_complete_request(rq);
1305 else
1306 blk_mq_complete_request(rq);
1310 * Complete the not-mapped clone and the original request with the error status
1311 * through softirq context.
1312 * Target's rq_end_io() function isn't called.
1313 * This may be used when the target's map_rq() or clone_and_map_rq() functions fail.
1315 static void dm_kill_unmapped_request(struct request *rq, int error)
1317 rq->cmd_flags |= REQ_FAILED;
1318 dm_complete_request(rq, error);
1322 * Called with the clone's queue lock held (for non-blk-mq)
1324 static void end_clone_request(struct request *clone, int error)
1326 struct dm_rq_target_io *tio = clone->end_io_data;
1328 if (!clone->q->mq_ops) {
1330 * For just cleaning up the information of the queue in which
1331 * the clone was dispatched.
1332 * The clone is *NOT* freed actually here because it is alloced
1333 * from dm own mempool (REQ_ALLOCED isn't set).
1335 __blk_put_request(clone->q, clone);
1339 * Actual request completion is done in a softirq context which doesn't
1340 * hold the clone's queue lock. Otherwise, deadlock could occur because:
1341 * - another request may be submitted by the upper level driver
1342 * of the stacking during the completion
1343 * - the submission which requires queue lock may be done
1344 * against this clone's queue
1346 dm_complete_request(tio->orig, error);
1350 * Return maximum size of I/O possible at the supplied sector up to the current
1351 * target boundary.
1353 static sector_t max_io_len_target_boundary(sector_t sector, struct dm_target *ti)
1355 sector_t target_offset = dm_target_offset(ti, sector);
1357 return ti->len - target_offset;
1360 static sector_t max_io_len(sector_t sector, struct dm_target *ti)
1362 sector_t len = max_io_len_target_boundary(sector, ti);
1363 sector_t offset, max_len;
1366 * Does the target need to split even further?
1368 if (ti->max_io_len) {
1369 offset = dm_target_offset(ti, sector);
1370 if (unlikely(ti->max_io_len & (ti->max_io_len - 1)))
1371 max_len = sector_div(offset, ti->max_io_len);
1372 else
1373 max_len = offset & (ti->max_io_len - 1);
1374 max_len = ti->max_io_len - max_len;
1376 if (len > max_len)
1377 len = max_len;
1380 return len;
1383 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
1385 if (len > UINT_MAX) {
1386 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
1387 (unsigned long long)len, UINT_MAX);
1388 ti->error = "Maximum size of target IO is too large";
1389 return -EINVAL;
1392 ti->max_io_len = (uint32_t) len;
1394 return 0;
1396 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
1399 * A target may call dm_accept_partial_bio only from the map routine. It is
1400 * allowed for all bio types except REQ_FLUSH.
1402 * dm_accept_partial_bio informs the dm that the target only wants to process
1403 * additional n_sectors sectors of the bio and the rest of the data should be
1404 * sent in a next bio.
1406 * A diagram that explains the arithmetics:
1407 * +--------------------+---------------+-------+
1408 * | 1 | 2 | 3 |
1409 * +--------------------+---------------+-------+
1411 * <-------------- *tio->len_ptr --------------->
1412 * <------- bi_size ------->
1413 * <-- n_sectors -->
1415 * Region 1 was already iterated over with bio_advance or similar function.
1416 * (it may be empty if the target doesn't use bio_advance)
1417 * Region 2 is the remaining bio size that the target wants to process.
1418 * (it may be empty if region 1 is non-empty, although there is no reason
1419 * to make it empty)
1420 * The target requires that region 3 is to be sent in the next bio.
1422 * If the target wants to receive multiple copies of the bio (via num_*bios, etc),
1423 * the partially processed part (the sum of regions 1+2) must be the same for all
1424 * copies of the bio.
1426 void dm_accept_partial_bio(struct bio *bio, unsigned n_sectors)
1428 struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
1429 unsigned bi_size = bio->bi_iter.bi_size >> SECTOR_SHIFT;
1430 BUG_ON(bio->bi_rw & REQ_FLUSH);
1431 BUG_ON(bi_size > *tio->len_ptr);
1432 BUG_ON(n_sectors > bi_size);
1433 *tio->len_ptr -= bi_size - n_sectors;
1434 bio->bi_iter.bi_size = n_sectors << SECTOR_SHIFT;
1436 EXPORT_SYMBOL_GPL(dm_accept_partial_bio);
1438 static void __map_bio(struct dm_target_io *tio)
1440 int r;
1441 sector_t sector;
1442 struct mapped_device *md;
1443 struct bio *clone = &tio->clone;
1444 struct dm_target *ti = tio->ti;
1446 clone->bi_end_io = clone_endio;
1449 * Map the clone. If r == 0 we don't need to do
1450 * anything, the target has assumed ownership of
1451 * this io.
1453 atomic_inc(&tio->io->io_count);
1454 sector = clone->bi_iter.bi_sector;
1455 r = ti->type->map(ti, clone);
1456 if (r == DM_MAPIO_REMAPPED) {
1457 /* the bio has been remapped so dispatch it */
1459 trace_block_bio_remap(bdev_get_queue(clone->bi_bdev), clone,
1460 tio->io->bio->bi_bdev->bd_dev, sector);
1462 generic_make_request(clone);
1463 } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1464 /* error the io and bail out, or requeue it if needed */
1465 md = tio->io->md;
1466 dec_pending(tio->io, r);
1467 free_tio(md, tio);
1468 } else if (r) {
1469 DMWARN("unimplemented target map return value: %d", r);
1470 BUG();
1474 struct clone_info {
1475 struct mapped_device *md;
1476 struct dm_table *map;
1477 struct bio *bio;
1478 struct dm_io *io;
1479 sector_t sector;
1480 unsigned sector_count;
1483 static void bio_setup_sector(struct bio *bio, sector_t sector, unsigned len)
1485 bio->bi_iter.bi_sector = sector;
1486 bio->bi_iter.bi_size = to_bytes(len);
1490 * Creates a bio that consists of range of complete bvecs.
1492 static void clone_bio(struct dm_target_io *tio, struct bio *bio,
1493 sector_t sector, unsigned len)
1495 struct bio *clone = &tio->clone;
1497 __bio_clone_fast(clone, bio);
1499 if (bio_integrity(bio))
1500 bio_integrity_clone(clone, bio, GFP_NOIO);
1502 bio_advance(clone, to_bytes(sector - clone->bi_iter.bi_sector));
1503 clone->bi_iter.bi_size = to_bytes(len);
1505 if (bio_integrity(bio))
1506 bio_integrity_trim(clone, 0, len);
1509 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1510 struct dm_target *ti,
1511 unsigned target_bio_nr)
1513 struct dm_target_io *tio;
1514 struct bio *clone;
1516 clone = bio_alloc_bioset(GFP_NOIO, 0, ci->md->bs);
1517 tio = container_of(clone, struct dm_target_io, clone);
1519 tio->io = ci->io;
1520 tio->ti = ti;
1521 tio->target_bio_nr = target_bio_nr;
1523 return tio;
1526 static void __clone_and_map_simple_bio(struct clone_info *ci,
1527 struct dm_target *ti,
1528 unsigned target_bio_nr, unsigned *len)
1530 struct dm_target_io *tio = alloc_tio(ci, ti, target_bio_nr);
1531 struct bio *clone = &tio->clone;
1533 tio->len_ptr = len;
1535 __bio_clone_fast(clone, ci->bio);
1536 if (len)
1537 bio_setup_sector(clone, ci->sector, *len);
1539 __map_bio(tio);
1542 static void __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1543 unsigned num_bios, unsigned *len)
1545 unsigned target_bio_nr;
1547 for (target_bio_nr = 0; target_bio_nr < num_bios; target_bio_nr++)
1548 __clone_and_map_simple_bio(ci, ti, target_bio_nr, len);
1551 static int __send_empty_flush(struct clone_info *ci)
1553 unsigned target_nr = 0;
1554 struct dm_target *ti;
1556 BUG_ON(bio_has_data(ci->bio));
1557 while ((ti = dm_table_get_target(ci->map, target_nr++)))
1558 __send_duplicate_bios(ci, ti, ti->num_flush_bios, NULL);
1560 return 0;
1563 static void __clone_and_map_data_bio(struct clone_info *ci, struct dm_target *ti,
1564 sector_t sector, unsigned *len)
1566 struct bio *bio = ci->bio;
1567 struct dm_target_io *tio;
1568 unsigned target_bio_nr;
1569 unsigned num_target_bios = 1;
1572 * Does the target want to receive duplicate copies of the bio?
1574 if (bio_data_dir(bio) == WRITE && ti->num_write_bios)
1575 num_target_bios = ti->num_write_bios(ti, bio);
1577 for (target_bio_nr = 0; target_bio_nr < num_target_bios; target_bio_nr++) {
1578 tio = alloc_tio(ci, ti, target_bio_nr);
1579 tio->len_ptr = len;
1580 clone_bio(tio, bio, sector, *len);
1581 __map_bio(tio);
1585 typedef unsigned (*get_num_bios_fn)(struct dm_target *ti);
1587 static unsigned get_num_discard_bios(struct dm_target *ti)
1589 return ti->num_discard_bios;
1592 static unsigned get_num_write_same_bios(struct dm_target *ti)
1594 return ti->num_write_same_bios;
1597 typedef bool (*is_split_required_fn)(struct dm_target *ti);
1599 static bool is_split_required_for_discard(struct dm_target *ti)
1601 return ti->split_discard_bios;
1604 static int __send_changing_extent_only(struct clone_info *ci,
1605 get_num_bios_fn get_num_bios,
1606 is_split_required_fn is_split_required)
1608 struct dm_target *ti;
1609 unsigned len;
1610 unsigned num_bios;
1612 do {
1613 ti = dm_table_find_target(ci->map, ci->sector);
1614 if (!dm_target_is_valid(ti))
1615 return -EIO;
1618 * Even though the device advertised support for this type of
1619 * request, that does not mean every target supports it, and
1620 * reconfiguration might also have changed that since the
1621 * check was performed.
1623 num_bios = get_num_bios ? get_num_bios(ti) : 0;
1624 if (!num_bios)
1625 return -EOPNOTSUPP;
1627 if (is_split_required && !is_split_required(ti))
1628 len = min((sector_t)ci->sector_count, max_io_len_target_boundary(ci->sector, ti));
1629 else
1630 len = min((sector_t)ci->sector_count, max_io_len(ci->sector, ti));
1632 __send_duplicate_bios(ci, ti, num_bios, &len);
1634 ci->sector += len;
1635 } while (ci->sector_count -= len);
1637 return 0;
1640 static int __send_discard(struct clone_info *ci)
1642 return __send_changing_extent_only(ci, get_num_discard_bios,
1643 is_split_required_for_discard);
1646 static int __send_write_same(struct clone_info *ci)
1648 return __send_changing_extent_only(ci, get_num_write_same_bios, NULL);
1652 * Select the correct strategy for processing a non-flush bio.
1654 static int __split_and_process_non_flush(struct clone_info *ci)
1656 struct bio *bio = ci->bio;
1657 struct dm_target *ti;
1658 unsigned len;
1660 if (unlikely(bio->bi_rw & REQ_DISCARD))
1661 return __send_discard(ci);
1662 else if (unlikely(bio->bi_rw & REQ_WRITE_SAME))
1663 return __send_write_same(ci);
1665 ti = dm_table_find_target(ci->map, ci->sector);
1666 if (!dm_target_is_valid(ti))
1667 return -EIO;
1669 len = min_t(sector_t, max_io_len(ci->sector, ti), ci->sector_count);
1671 __clone_and_map_data_bio(ci, ti, ci->sector, &len);
1673 ci->sector += len;
1674 ci->sector_count -= len;
1676 return 0;
1680 * Entry point to split a bio into clones and submit them to the targets.
1682 static void __split_and_process_bio(struct mapped_device *md,
1683 struct dm_table *map, struct bio *bio)
1685 struct clone_info ci;
1686 int error = 0;
1688 if (unlikely(!map)) {
1689 bio_io_error(bio);
1690 return;
1693 ci.map = map;
1694 ci.md = md;
1695 ci.io = alloc_io(md);
1696 ci.io->error = 0;
1697 atomic_set(&ci.io->io_count, 1);
1698 ci.io->bio = bio;
1699 ci.io->md = md;
1700 spin_lock_init(&ci.io->endio_lock);
1701 ci.sector = bio->bi_iter.bi_sector;
1703 start_io_acct(ci.io);
1705 if (bio->bi_rw & REQ_FLUSH) {
1706 ci.bio = &ci.md->flush_bio;
1707 ci.sector_count = 0;
1708 error = __send_empty_flush(&ci);
1709 /* dec_pending submits any data associated with flush */
1710 } else {
1711 ci.bio = bio;
1712 ci.sector_count = bio_sectors(bio);
1713 while (ci.sector_count && !error)
1714 error = __split_and_process_non_flush(&ci);
1717 /* drop the extra reference count */
1718 dec_pending(ci.io, error);
1720 /*-----------------------------------------------------------------
1721 * CRUD END
1722 *---------------------------------------------------------------*/
1724 static int dm_merge_bvec(struct request_queue *q,
1725 struct bvec_merge_data *bvm,
1726 struct bio_vec *biovec)
1728 struct mapped_device *md = q->queuedata;
1729 struct dm_table *map = dm_get_live_table_fast(md);
1730 struct dm_target *ti;
1731 sector_t max_sectors;
1732 int max_size = 0;
1734 if (unlikely(!map))
1735 goto out;
1737 ti = dm_table_find_target(map, bvm->bi_sector);
1738 if (!dm_target_is_valid(ti))
1739 goto out;
1742 * Find maximum amount of I/O that won't need splitting
1744 max_sectors = min(max_io_len(bvm->bi_sector, ti),
1745 (sector_t) BIO_MAX_SECTORS);
1746 max_size = (max_sectors << SECTOR_SHIFT) - bvm->bi_size;
1747 if (max_size < 0)
1748 max_size = 0;
1751 * merge_bvec_fn() returns number of bytes
1752 * it can accept at this offset
1753 * max is precomputed maximal io size
1755 if (max_size && ti->type->merge)
1756 max_size = ti->type->merge(ti, bvm, biovec, max_size);
1758 * If the target doesn't support merge method and some of the devices
1759 * provided their merge_bvec method (we know this by looking at
1760 * queue_max_hw_sectors), then we can't allow bios with multiple vector
1761 * entries. So always set max_size to 0, and the code below allows
1762 * just one page.
1764 else if (queue_max_hw_sectors(q) <= PAGE_SIZE >> 9)
1765 max_size = 0;
1767 out:
1768 dm_put_live_table_fast(md);
1770 * Always allow an entire first page
1772 if (max_size <= biovec->bv_len && !(bvm->bi_size >> SECTOR_SHIFT))
1773 max_size = biovec->bv_len;
1775 return max_size;
1779 * The request function that just remaps the bio built up by
1780 * dm_merge_bvec.
1782 static void dm_make_request(struct request_queue *q, struct bio *bio)
1784 int rw = bio_data_dir(bio);
1785 struct mapped_device *md = q->queuedata;
1786 int srcu_idx;
1787 struct dm_table *map;
1789 map = dm_get_live_table(md, &srcu_idx);
1791 generic_start_io_acct(rw, bio_sectors(bio), &dm_disk(md)->part0);
1793 /* if we're suspended, we have to queue this io for later */
1794 if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
1795 dm_put_live_table(md, srcu_idx);
1797 if (bio_rw(bio) != READA)
1798 queue_io(md, bio);
1799 else
1800 bio_io_error(bio);
1801 return;
1804 __split_and_process_bio(md, map, bio);
1805 dm_put_live_table(md, srcu_idx);
1806 return;
1809 int dm_request_based(struct mapped_device *md)
1811 return blk_queue_stackable(md->queue);
1814 static void dm_dispatch_clone_request(struct request *clone, struct request *rq)
1816 int r;
1818 if (blk_queue_io_stat(clone->q))
1819 clone->cmd_flags |= REQ_IO_STAT;
1821 clone->start_time = jiffies;
1822 r = blk_insert_cloned_request(clone->q, clone);
1823 if (r)
1824 /* must complete clone in terms of original request */
1825 dm_complete_request(rq, r);
1828 static int dm_rq_bio_constructor(struct bio *bio, struct bio *bio_orig,
1829 void *data)
1831 struct dm_rq_target_io *tio = data;
1832 struct dm_rq_clone_bio_info *info =
1833 container_of(bio, struct dm_rq_clone_bio_info, clone);
1835 info->orig = bio_orig;
1836 info->tio = tio;
1837 bio->bi_end_io = end_clone_bio;
1839 return 0;
1842 static int setup_clone(struct request *clone, struct request *rq,
1843 struct dm_rq_target_io *tio, gfp_t gfp_mask)
1845 int r;
1847 r = blk_rq_prep_clone(clone, rq, tio->md->bs, gfp_mask,
1848 dm_rq_bio_constructor, tio);
1849 if (r)
1850 return r;
1852 clone->cmd = rq->cmd;
1853 clone->cmd_len = rq->cmd_len;
1854 clone->sense = rq->sense;
1855 clone->end_io = end_clone_request;
1856 clone->end_io_data = tio;
1858 tio->clone = clone;
1860 return 0;
1863 static struct request *clone_rq(struct request *rq, struct mapped_device *md,
1864 struct dm_rq_target_io *tio, gfp_t gfp_mask)
1867 * Do not allocate a clone if tio->clone was already set
1868 * (see: dm_mq_queue_rq).
1870 bool alloc_clone = !tio->clone;
1871 struct request *clone;
1873 if (alloc_clone) {
1874 clone = alloc_clone_request(md, gfp_mask);
1875 if (!clone)
1876 return NULL;
1877 } else
1878 clone = tio->clone;
1880 blk_rq_init(NULL, clone);
1881 if (setup_clone(clone, rq, tio, gfp_mask)) {
1882 /* -ENOMEM */
1883 if (alloc_clone)
1884 free_clone_request(md, clone);
1885 return NULL;
1888 return clone;
1891 static void map_tio_request(struct kthread_work *work);
1893 static void init_tio(struct dm_rq_target_io *tio, struct request *rq,
1894 struct mapped_device *md)
1896 tio->md = md;
1897 tio->ti = NULL;
1898 tio->clone = NULL;
1899 tio->orig = rq;
1900 tio->error = 0;
1901 memset(&tio->info, 0, sizeof(tio->info));
1902 if (md->kworker_task)
1903 init_kthread_work(&tio->work, map_tio_request);
1906 static struct dm_rq_target_io *prep_tio(struct request *rq,
1907 struct mapped_device *md, gfp_t gfp_mask)
1909 struct dm_rq_target_io *tio;
1910 int srcu_idx;
1911 struct dm_table *table;
1913 tio = alloc_rq_tio(md, gfp_mask);
1914 if (!tio)
1915 return NULL;
1917 init_tio(tio, rq, md);
1919 table = dm_get_live_table(md, &srcu_idx);
1920 if (!dm_table_mq_request_based(table)) {
1921 if (!clone_rq(rq, md, tio, gfp_mask)) {
1922 dm_put_live_table(md, srcu_idx);
1923 free_rq_tio(tio);
1924 return NULL;
1927 dm_put_live_table(md, srcu_idx);
1929 return tio;
1933 * Called with the queue lock held.
1935 static int dm_prep_fn(struct request_queue *q, struct request *rq)
1937 struct mapped_device *md = q->queuedata;
1938 struct dm_rq_target_io *tio;
1940 if (unlikely(rq->special)) {
1941 DMWARN("Already has something in rq->special.");
1942 return BLKPREP_KILL;
1945 tio = prep_tio(rq, md, GFP_ATOMIC);
1946 if (!tio)
1947 return BLKPREP_DEFER;
1949 rq->special = tio;
1950 rq->cmd_flags |= REQ_DONTPREP;
1952 return BLKPREP_OK;
1956 * Returns:
1957 * 0 : the request has been processed
1958 * DM_MAPIO_REQUEUE : the original request needs to be requeued
1959 * < 0 : the request was completed due to failure
1961 static int map_request(struct dm_rq_target_io *tio, struct request *rq,
1962 struct mapped_device *md)
1964 int r;
1965 struct dm_target *ti = tio->ti;
1966 struct request *clone = NULL;
1968 if (tio->clone) {
1969 clone = tio->clone;
1970 r = ti->type->map_rq(ti, clone, &tio->info);
1971 } else {
1972 r = ti->type->clone_and_map_rq(ti, rq, &tio->info, &clone);
1973 if (r < 0) {
1974 /* The target wants to complete the I/O */
1975 dm_kill_unmapped_request(rq, r);
1976 return r;
1978 if (r != DM_MAPIO_REMAPPED)
1979 return r;
1980 if (setup_clone(clone, rq, tio, GFP_ATOMIC)) {
1981 /* -ENOMEM */
1982 ti->type->release_clone_rq(clone);
1983 return DM_MAPIO_REQUEUE;
1987 switch (r) {
1988 case DM_MAPIO_SUBMITTED:
1989 /* The target has taken the I/O to submit by itself later */
1990 break;
1991 case DM_MAPIO_REMAPPED:
1992 /* The target has remapped the I/O so dispatch it */
1993 trace_block_rq_remap(clone->q, clone, disk_devt(dm_disk(md)),
1994 blk_rq_pos(rq));
1995 dm_dispatch_clone_request(clone, rq);
1996 break;
1997 case DM_MAPIO_REQUEUE:
1998 /* The target wants to requeue the I/O */
1999 dm_requeue_unmapped_request(clone);
2000 break;
2001 default:
2002 if (r > 0) {
2003 DMWARN("unimplemented target map return value: %d", r);
2004 BUG();
2007 /* The target wants to complete the I/O */
2008 dm_kill_unmapped_request(rq, r);
2009 return r;
2012 return 0;
2015 static void map_tio_request(struct kthread_work *work)
2017 struct dm_rq_target_io *tio = container_of(work, struct dm_rq_target_io, work);
2018 struct request *rq = tio->orig;
2019 struct mapped_device *md = tio->md;
2021 if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE)
2022 dm_requeue_unmapped_original_request(md, rq);
2025 static void dm_start_request(struct mapped_device *md, struct request *orig)
2027 if (!orig->q->mq_ops)
2028 blk_start_request(orig);
2029 else
2030 blk_mq_start_request(orig);
2031 atomic_inc(&md->pending[rq_data_dir(orig)]);
2033 if (md->seq_rq_merge_deadline_usecs) {
2034 md->last_rq_pos = rq_end_sector(orig);
2035 md->last_rq_rw = rq_data_dir(orig);
2036 md->last_rq_start_time = ktime_get();
2040 * Hold the md reference here for the in-flight I/O.
2041 * We can't rely on the reference count by device opener,
2042 * because the device may be closed during the request completion
2043 * when all bios are completed.
2044 * See the comment in rq_completed() too.
2046 dm_get(md);
2049 #define MAX_SEQ_RQ_MERGE_DEADLINE_USECS 100000
2051 ssize_t dm_attr_rq_based_seq_io_merge_deadline_show(struct mapped_device *md, char *buf)
2053 return sprintf(buf, "%u\n", md->seq_rq_merge_deadline_usecs);
2056 ssize_t dm_attr_rq_based_seq_io_merge_deadline_store(struct mapped_device *md,
2057 const char *buf, size_t count)
2059 unsigned deadline;
2061 if (!dm_request_based(md) || md->use_blk_mq)
2062 return count;
2064 if (kstrtouint(buf, 10, &deadline))
2065 return -EINVAL;
2067 if (deadline > MAX_SEQ_RQ_MERGE_DEADLINE_USECS)
2068 deadline = MAX_SEQ_RQ_MERGE_DEADLINE_USECS;
2070 md->seq_rq_merge_deadline_usecs = deadline;
2072 return count;
2075 static bool dm_request_peeked_before_merge_deadline(struct mapped_device *md)
2077 ktime_t kt_deadline;
2079 if (!md->seq_rq_merge_deadline_usecs)
2080 return false;
2082 kt_deadline = ns_to_ktime((u64)md->seq_rq_merge_deadline_usecs * NSEC_PER_USEC);
2083 kt_deadline = ktime_add_safe(md->last_rq_start_time, kt_deadline);
2085 return !ktime_after(ktime_get(), kt_deadline);
2089 * q->request_fn for request-based dm.
2090 * Called with the queue lock held.
2092 static void dm_request_fn(struct request_queue *q)
2094 struct mapped_device *md = q->queuedata;
2095 int srcu_idx;
2096 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2097 struct dm_target *ti;
2098 struct request *rq;
2099 struct dm_rq_target_io *tio;
2100 sector_t pos;
2103 * For suspend, check blk_queue_stopped() and increment
2104 * ->pending within a single queue_lock not to increment the
2105 * number of in-flight I/Os after the queue is stopped in
2106 * dm_suspend().
2108 while (!blk_queue_stopped(q)) {
2109 rq = blk_peek_request(q);
2110 if (!rq)
2111 goto out;
2113 /* always use block 0 to find the target for flushes for now */
2114 pos = 0;
2115 if (!(rq->cmd_flags & REQ_FLUSH))
2116 pos = blk_rq_pos(rq);
2118 ti = dm_table_find_target(map, pos);
2119 if (!dm_target_is_valid(ti)) {
2121 * Must perform setup, that rq_completed() requires,
2122 * before calling dm_kill_unmapped_request
2124 DMERR_LIMIT("request attempted access beyond the end of device");
2125 dm_start_request(md, rq);
2126 dm_kill_unmapped_request(rq, -EIO);
2127 continue;
2130 if (dm_request_peeked_before_merge_deadline(md) &&
2131 md_in_flight(md) && rq->bio && rq->bio->bi_vcnt == 1 &&
2132 md->last_rq_pos == pos && md->last_rq_rw == rq_data_dir(rq))
2133 goto delay_and_out;
2135 if (ti->type->busy && ti->type->busy(ti))
2136 goto delay_and_out;
2138 dm_start_request(md, rq);
2140 tio = tio_from_request(rq);
2141 /* Establish tio->ti before queuing work (map_tio_request) */
2142 tio->ti = ti;
2143 queue_kthread_work(&md->kworker, &tio->work);
2144 BUG_ON(!irqs_disabled());
2147 goto out;
2149 delay_and_out:
2150 blk_delay_queue(q, 10);
2151 out:
2152 dm_put_live_table(md, srcu_idx);
2155 static int dm_any_congested(void *congested_data, int bdi_bits)
2157 int r = bdi_bits;
2158 struct mapped_device *md = congested_data;
2159 struct dm_table *map;
2161 if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2162 map = dm_get_live_table_fast(md);
2163 if (map) {
2165 * Request-based dm cares about only own queue for
2166 * the query about congestion status of request_queue
2168 if (dm_request_based(md))
2169 r = md->queue->backing_dev_info.state &
2170 bdi_bits;
2171 else
2172 r = dm_table_any_congested(map, bdi_bits);
2174 dm_put_live_table_fast(md);
2177 return r;
2180 /*-----------------------------------------------------------------
2181 * An IDR is used to keep track of allocated minor numbers.
2182 *---------------------------------------------------------------*/
2183 static void free_minor(int minor)
2185 spin_lock(&_minor_lock);
2186 idr_remove(&_minor_idr, minor);
2187 spin_unlock(&_minor_lock);
2191 * See if the device with a specific minor # is free.
2193 static int specific_minor(int minor)
2195 int r;
2197 if (minor >= (1 << MINORBITS))
2198 return -EINVAL;
2200 idr_preload(GFP_KERNEL);
2201 spin_lock(&_minor_lock);
2203 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
2205 spin_unlock(&_minor_lock);
2206 idr_preload_end();
2207 if (r < 0)
2208 return r == -ENOSPC ? -EBUSY : r;
2209 return 0;
2212 static int next_free_minor(int *minor)
2214 int r;
2216 idr_preload(GFP_KERNEL);
2217 spin_lock(&_minor_lock);
2219 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
2221 spin_unlock(&_minor_lock);
2222 idr_preload_end();
2223 if (r < 0)
2224 return r;
2225 *minor = r;
2226 return 0;
2229 static const struct block_device_operations dm_blk_dops;
2231 static void dm_wq_work(struct work_struct *work);
2233 static void dm_init_md_queue(struct mapped_device *md)
2236 * Request-based dm devices cannot be stacked on top of bio-based dm
2237 * devices. The type of this dm device may not have been decided yet.
2238 * The type is decided at the first table loading time.
2239 * To prevent problematic device stacking, clear the queue flag
2240 * for request stacking support until then.
2242 * This queue is new, so no concurrency on the queue_flags.
2244 queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
2247 static void dm_init_old_md_queue(struct mapped_device *md)
2249 md->use_blk_mq = false;
2250 dm_init_md_queue(md);
2253 * Initialize aspects of queue that aren't relevant for blk-mq
2255 md->queue->queuedata = md;
2256 md->queue->backing_dev_info.congested_fn = dm_any_congested;
2257 md->queue->backing_dev_info.congested_data = md;
2259 blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
2263 * Allocate and initialise a blank device with a given minor.
2265 static struct mapped_device *alloc_dev(int minor)
2267 int r;
2268 struct mapped_device *md = kzalloc(sizeof(*md), GFP_KERNEL);
2269 void *old_md;
2271 if (!md) {
2272 DMWARN("unable to allocate device, out of memory.");
2273 return NULL;
2276 if (!try_module_get(THIS_MODULE))
2277 goto bad_module_get;
2279 /* get a minor number for the dev */
2280 if (minor == DM_ANY_MINOR)
2281 r = next_free_minor(&minor);
2282 else
2283 r = specific_minor(minor);
2284 if (r < 0)
2285 goto bad_minor;
2287 r = init_srcu_struct(&md->io_barrier);
2288 if (r < 0)
2289 goto bad_io_barrier;
2291 md->use_blk_mq = use_blk_mq;
2292 md->type = DM_TYPE_NONE;
2293 mutex_init(&md->suspend_lock);
2294 mutex_init(&md->type_lock);
2295 mutex_init(&md->table_devices_lock);
2296 spin_lock_init(&md->deferred_lock);
2297 atomic_set(&md->holders, 1);
2298 atomic_set(&md->open_count, 0);
2299 atomic_set(&md->event_nr, 0);
2300 atomic_set(&md->uevent_seq, 0);
2301 INIT_LIST_HEAD(&md->uevent_list);
2302 INIT_LIST_HEAD(&md->table_devices);
2303 spin_lock_init(&md->uevent_lock);
2305 md->queue = blk_alloc_queue(GFP_KERNEL);
2306 if (!md->queue)
2307 goto bad_queue;
2309 dm_init_md_queue(md);
2311 md->disk = alloc_disk(1);
2312 if (!md->disk)
2313 goto bad_disk;
2315 atomic_set(&md->pending[0], 0);
2316 atomic_set(&md->pending[1], 0);
2317 init_waitqueue_head(&md->wait);
2318 INIT_WORK(&md->work, dm_wq_work);
2319 init_waitqueue_head(&md->eventq);
2320 init_completion(&md->kobj_holder.completion);
2321 md->kworker_task = NULL;
2323 md->disk->major = _major;
2324 md->disk->first_minor = minor;
2325 md->disk->fops = &dm_blk_dops;
2326 md->disk->queue = md->queue;
2327 md->disk->private_data = md;
2328 sprintf(md->disk->disk_name, "dm-%d", minor);
2329 add_disk(md->disk);
2330 format_dev_t(md->name, MKDEV(_major, minor));
2332 md->wq = alloc_workqueue("kdmflush", WQ_MEM_RECLAIM, 0);
2333 if (!md->wq)
2334 goto bad_thread;
2336 md->bdev = bdget_disk(md->disk, 0);
2337 if (!md->bdev)
2338 goto bad_bdev;
2340 bio_init(&md->flush_bio);
2341 md->flush_bio.bi_bdev = md->bdev;
2342 md->flush_bio.bi_rw = WRITE_FLUSH;
2344 dm_stats_init(&md->stats);
2346 /* Populate the mapping, nobody knows we exist yet */
2347 spin_lock(&_minor_lock);
2348 old_md = idr_replace(&_minor_idr, md, minor);
2349 spin_unlock(&_minor_lock);
2351 BUG_ON(old_md != MINOR_ALLOCED);
2353 return md;
2355 bad_bdev:
2356 destroy_workqueue(md->wq);
2357 bad_thread:
2358 del_gendisk(md->disk);
2359 put_disk(md->disk);
2360 bad_disk:
2361 blk_cleanup_queue(md->queue);
2362 bad_queue:
2363 cleanup_srcu_struct(&md->io_barrier);
2364 bad_io_barrier:
2365 free_minor(minor);
2366 bad_minor:
2367 module_put(THIS_MODULE);
2368 bad_module_get:
2369 kfree(md);
2370 return NULL;
2373 static void unlock_fs(struct mapped_device *md);
2375 static void free_dev(struct mapped_device *md)
2377 int minor = MINOR(disk_devt(md->disk));
2379 unlock_fs(md);
2380 destroy_workqueue(md->wq);
2382 if (md->kworker_task)
2383 kthread_stop(md->kworker_task);
2384 if (md->io_pool)
2385 mempool_destroy(md->io_pool);
2386 if (md->rq_pool)
2387 mempool_destroy(md->rq_pool);
2388 if (md->bs)
2389 bioset_free(md->bs);
2391 cleanup_srcu_struct(&md->io_barrier);
2392 free_table_devices(&md->table_devices);
2393 dm_stats_cleanup(&md->stats);
2395 spin_lock(&_minor_lock);
2396 md->disk->private_data = NULL;
2397 spin_unlock(&_minor_lock);
2398 if (blk_get_integrity(md->disk))
2399 blk_integrity_unregister(md->disk);
2400 del_gendisk(md->disk);
2401 put_disk(md->disk);
2402 blk_cleanup_queue(md->queue);
2403 if (md->use_blk_mq)
2404 blk_mq_free_tag_set(&md->tag_set);
2405 bdput(md->bdev);
2406 free_minor(minor);
2408 module_put(THIS_MODULE);
2409 kfree(md);
2412 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
2414 struct dm_md_mempools *p = dm_table_get_md_mempools(t);
2416 if (md->bs) {
2417 /* The md already has necessary mempools. */
2418 if (dm_table_get_type(t) == DM_TYPE_BIO_BASED) {
2420 * Reload bioset because front_pad may have changed
2421 * because a different table was loaded.
2423 bioset_free(md->bs);
2424 md->bs = p->bs;
2425 p->bs = NULL;
2428 * There's no need to reload with request-based dm
2429 * because the size of front_pad doesn't change.
2430 * Note for future: If you are to reload bioset,
2431 * prep-ed requests in the queue may refer
2432 * to bio from the old bioset, so you must walk
2433 * through the queue to unprep.
2435 goto out;
2438 BUG_ON(!p || md->io_pool || md->rq_pool || md->bs);
2440 md->io_pool = p->io_pool;
2441 p->io_pool = NULL;
2442 md->rq_pool = p->rq_pool;
2443 p->rq_pool = NULL;
2444 md->bs = p->bs;
2445 p->bs = NULL;
2447 out:
2448 /* mempool bind completed, no longer need any mempools in the table */
2449 dm_table_free_md_mempools(t);
2453 * Bind a table to the device.
2455 static void event_callback(void *context)
2457 unsigned long flags;
2458 LIST_HEAD(uevents);
2459 struct mapped_device *md = (struct mapped_device *) context;
2461 spin_lock_irqsave(&md->uevent_lock, flags);
2462 list_splice_init(&md->uevent_list, &uevents);
2463 spin_unlock_irqrestore(&md->uevent_lock, flags);
2465 dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2467 atomic_inc(&md->event_nr);
2468 wake_up(&md->eventq);
2472 * Protected by md->suspend_lock obtained by dm_swap_table().
2474 static void __set_size(struct mapped_device *md, sector_t size)
2476 set_capacity(md->disk, size);
2478 i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
2482 * Return 1 if the queue has a compulsory merge_bvec_fn function.
2484 * If this function returns 0, then the device is either a non-dm
2485 * device without a merge_bvec_fn, or it is a dm device that is
2486 * able to split any bios it receives that are too big.
2488 int dm_queue_merge_is_compulsory(struct request_queue *q)
2490 struct mapped_device *dev_md;
2492 if (!q->merge_bvec_fn)
2493 return 0;
2495 if (q->make_request_fn == dm_make_request) {
2496 dev_md = q->queuedata;
2497 if (test_bit(DMF_MERGE_IS_OPTIONAL, &dev_md->flags))
2498 return 0;
2501 return 1;
2504 static int dm_device_merge_is_compulsory(struct dm_target *ti,
2505 struct dm_dev *dev, sector_t start,
2506 sector_t len, void *data)
2508 struct block_device *bdev = dev->bdev;
2509 struct request_queue *q = bdev_get_queue(bdev);
2511 return dm_queue_merge_is_compulsory(q);
2515 * Return 1 if it is acceptable to ignore merge_bvec_fn based
2516 * on the properties of the underlying devices.
2518 static int dm_table_merge_is_optional(struct dm_table *table)
2520 unsigned i = 0;
2521 struct dm_target *ti;
2523 while (i < dm_table_get_num_targets(table)) {
2524 ti = dm_table_get_target(table, i++);
2526 if (ti->type->iterate_devices &&
2527 ti->type->iterate_devices(ti, dm_device_merge_is_compulsory, NULL))
2528 return 0;
2531 return 1;
2535 * Returns old map, which caller must destroy.
2537 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2538 struct queue_limits *limits)
2540 struct dm_table *old_map;
2541 struct request_queue *q = md->queue;
2542 sector_t size;
2543 int merge_is_optional;
2545 size = dm_table_get_size(t);
2548 * Wipe any geometry if the size of the table changed.
2550 if (size != dm_get_size(md))
2551 memset(&md->geometry, 0, sizeof(md->geometry));
2553 __set_size(md, size);
2555 dm_table_event_callback(t, event_callback, md);
2558 * The queue hasn't been stopped yet, if the old table type wasn't
2559 * for request-based during suspension. So stop it to prevent
2560 * I/O mapping before resume.
2561 * This must be done before setting the queue restrictions,
2562 * because request-based dm may be run just after the setting.
2564 if (dm_table_request_based(t))
2565 stop_queue(q);
2567 __bind_mempools(md, t);
2569 merge_is_optional = dm_table_merge_is_optional(t);
2571 old_map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2572 rcu_assign_pointer(md->map, t);
2573 md->immutable_target_type = dm_table_get_immutable_target_type(t);
2575 dm_table_set_restrictions(t, q, limits);
2576 if (merge_is_optional)
2577 set_bit(DMF_MERGE_IS_OPTIONAL, &md->flags);
2578 else
2579 clear_bit(DMF_MERGE_IS_OPTIONAL, &md->flags);
2580 if (old_map)
2581 dm_sync_table(md);
2583 return old_map;
2587 * Returns unbound table for the caller to free.
2589 static struct dm_table *__unbind(struct mapped_device *md)
2591 struct dm_table *map = rcu_dereference_protected(md->map, 1);
2593 if (!map)
2594 return NULL;
2596 dm_table_event_callback(map, NULL, NULL);
2597 RCU_INIT_POINTER(md->map, NULL);
2598 dm_sync_table(md);
2600 return map;
2604 * Constructor for a new device.
2606 int dm_create(int minor, struct mapped_device **result)
2608 struct mapped_device *md;
2610 md = alloc_dev(minor);
2611 if (!md)
2612 return -ENXIO;
2614 dm_sysfs_init(md);
2616 *result = md;
2617 return 0;
2621 * Functions to manage md->type.
2622 * All are required to hold md->type_lock.
2624 void dm_lock_md_type(struct mapped_device *md)
2626 mutex_lock(&md->type_lock);
2629 void dm_unlock_md_type(struct mapped_device *md)
2631 mutex_unlock(&md->type_lock);
2634 void dm_set_md_type(struct mapped_device *md, unsigned type)
2636 BUG_ON(!mutex_is_locked(&md->type_lock));
2637 md->type = type;
2640 unsigned dm_get_md_type(struct mapped_device *md)
2642 BUG_ON(!mutex_is_locked(&md->type_lock));
2643 return md->type;
2646 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2648 return md->immutable_target_type;
2652 * The queue_limits are only valid as long as you have a reference
2653 * count on 'md'.
2655 struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
2657 BUG_ON(!atomic_read(&md->holders));
2658 return &md->queue->limits;
2660 EXPORT_SYMBOL_GPL(dm_get_queue_limits);
2662 static void init_rq_based_worker_thread(struct mapped_device *md)
2664 /* Initialize the request-based DM worker thread */
2665 init_kthread_worker(&md->kworker);
2666 md->kworker_task = kthread_run(kthread_worker_fn, &md->kworker,
2667 "kdmwork-%s", dm_device_name(md));
2671 * Fully initialize a request-based queue (->elevator, ->request_fn, etc).
2673 static int dm_init_request_based_queue(struct mapped_device *md)
2675 struct request_queue *q = NULL;
2677 /* Fully initialize the queue */
2678 q = blk_init_allocated_queue(md->queue, dm_request_fn, NULL);
2679 if (!q)
2680 return -EINVAL;
2682 /* disable dm_request_fn's merge heuristic by default */
2683 md->seq_rq_merge_deadline_usecs = 0;
2685 md->queue = q;
2686 dm_init_old_md_queue(md);
2687 blk_queue_softirq_done(md->queue, dm_softirq_done);
2688 blk_queue_prep_rq(md->queue, dm_prep_fn);
2690 init_rq_based_worker_thread(md);
2692 elv_register_queue(md->queue);
2694 return 0;
2697 static int dm_mq_init_request(void *data, struct request *rq,
2698 unsigned int hctx_idx, unsigned int request_idx,
2699 unsigned int numa_node)
2701 struct mapped_device *md = data;
2702 struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2705 * Must initialize md member of tio, otherwise it won't
2706 * be available in dm_mq_queue_rq.
2708 tio->md = md;
2710 return 0;
2713 static int dm_mq_queue_rq(struct blk_mq_hw_ctx *hctx,
2714 const struct blk_mq_queue_data *bd)
2716 struct request *rq = bd->rq;
2717 struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2718 struct mapped_device *md = tio->md;
2719 int srcu_idx;
2720 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2721 struct dm_target *ti;
2722 sector_t pos;
2724 /* always use block 0 to find the target for flushes for now */
2725 pos = 0;
2726 if (!(rq->cmd_flags & REQ_FLUSH))
2727 pos = blk_rq_pos(rq);
2729 ti = dm_table_find_target(map, pos);
2730 if (!dm_target_is_valid(ti)) {
2731 dm_put_live_table(md, srcu_idx);
2732 DMERR_LIMIT("request attempted access beyond the end of device");
2734 * Must perform setup, that rq_completed() requires,
2735 * before returning BLK_MQ_RQ_QUEUE_ERROR
2737 dm_start_request(md, rq);
2738 return BLK_MQ_RQ_QUEUE_ERROR;
2740 dm_put_live_table(md, srcu_idx);
2743 * On suspend dm_stop_queue() handles stopping the blk-mq
2744 * request_queue BUT: even though the hw_queues are marked
2745 * BLK_MQ_S_STOPPED at that point there is still a race that
2746 * is allowing block/blk-mq.c to call ->queue_rq against a
2747 * hctx that it really shouldn't. The following check guards
2748 * against this rarity (albeit _not_ race-free).
2750 if (unlikely(test_bit(BLK_MQ_S_STOPPED, &hctx->state)))
2751 return BLK_MQ_RQ_QUEUE_BUSY;
2753 if (ti->type->busy && ti->type->busy(ti))
2754 return BLK_MQ_RQ_QUEUE_BUSY;
2756 dm_start_request(md, rq);
2758 /* Init tio using md established in .init_request */
2759 init_tio(tio, rq, md);
2762 * Establish tio->ti before queuing work (map_tio_request)
2763 * or making direct call to map_request().
2765 tio->ti = ti;
2767 /* Clone the request if underlying devices aren't blk-mq */
2768 if (dm_table_get_type(map) == DM_TYPE_REQUEST_BASED) {
2769 /* clone request is allocated at the end of the pdu */
2770 tio->clone = (void *)blk_mq_rq_to_pdu(rq) + sizeof(struct dm_rq_target_io);
2771 (void) clone_rq(rq, md, tio, GFP_ATOMIC);
2772 queue_kthread_work(&md->kworker, &tio->work);
2773 } else {
2774 /* Direct call is fine since .queue_rq allows allocations */
2775 if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE) {
2776 /* Undo dm_start_request() before requeuing */
2777 rq_completed(md, rq_data_dir(rq), false);
2778 return BLK_MQ_RQ_QUEUE_BUSY;
2782 return BLK_MQ_RQ_QUEUE_OK;
2785 static struct blk_mq_ops dm_mq_ops = {
2786 .queue_rq = dm_mq_queue_rq,
2787 .map_queue = blk_mq_map_queue,
2788 .complete = dm_softirq_done,
2789 .init_request = dm_mq_init_request,
2792 static int dm_init_request_based_blk_mq_queue(struct mapped_device *md)
2794 unsigned md_type = dm_get_md_type(md);
2795 struct request_queue *q;
2796 int err;
2798 memset(&md->tag_set, 0, sizeof(md->tag_set));
2799 md->tag_set.ops = &dm_mq_ops;
2800 md->tag_set.queue_depth = BLKDEV_MAX_RQ;
2801 md->tag_set.numa_node = NUMA_NO_NODE;
2802 md->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
2803 md->tag_set.nr_hw_queues = 1;
2804 if (md_type == DM_TYPE_REQUEST_BASED) {
2805 /* make the memory for non-blk-mq clone part of the pdu */
2806 md->tag_set.cmd_size = sizeof(struct dm_rq_target_io) + sizeof(struct request);
2807 } else
2808 md->tag_set.cmd_size = sizeof(struct dm_rq_target_io);
2809 md->tag_set.driver_data = md;
2811 err = blk_mq_alloc_tag_set(&md->tag_set);
2812 if (err)
2813 return err;
2815 q = blk_mq_init_allocated_queue(&md->tag_set, md->queue);
2816 if (IS_ERR(q)) {
2817 err = PTR_ERR(q);
2818 goto out_tag_set;
2820 md->queue = q;
2821 dm_init_md_queue(md);
2823 /* backfill 'mq' sysfs registration normally done in blk_register_queue */
2824 blk_mq_register_disk(md->disk);
2826 if (md_type == DM_TYPE_REQUEST_BASED)
2827 init_rq_based_worker_thread(md);
2829 return 0;
2831 out_tag_set:
2832 blk_mq_free_tag_set(&md->tag_set);
2833 return err;
2836 static unsigned filter_md_type(unsigned type, struct mapped_device *md)
2838 if (type == DM_TYPE_BIO_BASED)
2839 return type;
2841 return !md->use_blk_mq ? DM_TYPE_REQUEST_BASED : DM_TYPE_MQ_REQUEST_BASED;
2845 * Setup the DM device's queue based on md's type
2847 int dm_setup_md_queue(struct mapped_device *md)
2849 int r;
2850 unsigned md_type = filter_md_type(dm_get_md_type(md), md);
2852 switch (md_type) {
2853 case DM_TYPE_REQUEST_BASED:
2854 r = dm_init_request_based_queue(md);
2855 if (r) {
2856 DMWARN("Cannot initialize queue for request-based mapped device");
2857 return r;
2859 break;
2860 case DM_TYPE_MQ_REQUEST_BASED:
2861 r = dm_init_request_based_blk_mq_queue(md);
2862 if (r) {
2863 DMWARN("Cannot initialize queue for request-based blk-mq mapped device");
2864 return r;
2866 break;
2867 case DM_TYPE_BIO_BASED:
2868 dm_init_old_md_queue(md);
2869 blk_queue_make_request(md->queue, dm_make_request);
2870 blk_queue_merge_bvec(md->queue, dm_merge_bvec);
2871 break;
2874 return 0;
2877 struct mapped_device *dm_get_md(dev_t dev)
2879 struct mapped_device *md;
2880 unsigned minor = MINOR(dev);
2882 if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2883 return NULL;
2885 spin_lock(&_minor_lock);
2887 md = idr_find(&_minor_idr, minor);
2888 if (md) {
2889 if ((md == MINOR_ALLOCED ||
2890 (MINOR(disk_devt(dm_disk(md))) != minor) ||
2891 dm_deleting_md(md) ||
2892 test_bit(DMF_FREEING, &md->flags))) {
2893 md = NULL;
2894 goto out;
2896 dm_get(md);
2899 out:
2900 spin_unlock(&_minor_lock);
2902 return md;
2904 EXPORT_SYMBOL_GPL(dm_get_md);
2906 void *dm_get_mdptr(struct mapped_device *md)
2908 return md->interface_ptr;
2911 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2913 md->interface_ptr = ptr;
2916 void dm_get(struct mapped_device *md)
2918 atomic_inc(&md->holders);
2919 BUG_ON(test_bit(DMF_FREEING, &md->flags));
2922 int dm_hold(struct mapped_device *md)
2924 spin_lock(&_minor_lock);
2925 if (test_bit(DMF_FREEING, &md->flags)) {
2926 spin_unlock(&_minor_lock);
2927 return -EBUSY;
2929 dm_get(md);
2930 spin_unlock(&_minor_lock);
2931 return 0;
2933 EXPORT_SYMBOL_GPL(dm_hold);
2935 const char *dm_device_name(struct mapped_device *md)
2937 return md->name;
2939 EXPORT_SYMBOL_GPL(dm_device_name);
2941 static void __dm_destroy(struct mapped_device *md, bool wait)
2943 struct dm_table *map;
2944 int srcu_idx;
2946 might_sleep();
2948 spin_lock(&_minor_lock);
2949 idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2950 set_bit(DMF_FREEING, &md->flags);
2951 spin_unlock(&_minor_lock);
2953 if (dm_request_based(md) && md->kworker_task)
2954 flush_kthread_worker(&md->kworker);
2957 * Take suspend_lock so that presuspend and postsuspend methods
2958 * do not race with internal suspend.
2960 mutex_lock(&md->suspend_lock);
2961 map = dm_get_live_table(md, &srcu_idx);
2962 if (!dm_suspended_md(md)) {
2963 dm_table_presuspend_targets(map);
2964 dm_table_postsuspend_targets(map);
2966 /* dm_put_live_table must be before msleep, otherwise deadlock is possible */
2967 dm_put_live_table(md, srcu_idx);
2968 mutex_unlock(&md->suspend_lock);
2971 * Rare, but there may be I/O requests still going to complete,
2972 * for example. Wait for all references to disappear.
2973 * No one should increment the reference count of the mapped_device,
2974 * after the mapped_device state becomes DMF_FREEING.
2976 if (wait)
2977 while (atomic_read(&md->holders))
2978 msleep(1);
2979 else if (atomic_read(&md->holders))
2980 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2981 dm_device_name(md), atomic_read(&md->holders));
2983 dm_sysfs_exit(md);
2984 dm_table_destroy(__unbind(md));
2985 free_dev(md);
2988 void dm_destroy(struct mapped_device *md)
2990 __dm_destroy(md, true);
2993 void dm_destroy_immediate(struct mapped_device *md)
2995 __dm_destroy(md, false);
2998 void dm_put(struct mapped_device *md)
3000 atomic_dec(&md->holders);
3002 EXPORT_SYMBOL_GPL(dm_put);
3004 static int dm_wait_for_completion(struct mapped_device *md, int interruptible)
3006 int r = 0;
3007 DECLARE_WAITQUEUE(wait, current);
3009 add_wait_queue(&md->wait, &wait);
3011 while (1) {
3012 set_current_state(interruptible);
3014 if (!md_in_flight(md))
3015 break;
3017 if (interruptible == TASK_INTERRUPTIBLE &&
3018 signal_pending(current)) {
3019 r = -EINTR;
3020 break;
3023 io_schedule();
3025 set_current_state(TASK_RUNNING);
3027 remove_wait_queue(&md->wait, &wait);
3029 return r;
3033 * Process the deferred bios
3035 static void dm_wq_work(struct work_struct *work)
3037 struct mapped_device *md = container_of(work, struct mapped_device,
3038 work);
3039 struct bio *c;
3040 int srcu_idx;
3041 struct dm_table *map;
3043 map = dm_get_live_table(md, &srcu_idx);
3045 while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
3046 spin_lock_irq(&md->deferred_lock);
3047 c = bio_list_pop(&md->deferred);
3048 spin_unlock_irq(&md->deferred_lock);
3050 if (!c)
3051 break;
3053 if (dm_request_based(md))
3054 generic_make_request(c);
3055 else
3056 __split_and_process_bio(md, map, c);
3059 dm_put_live_table(md, srcu_idx);
3062 static void dm_queue_flush(struct mapped_device *md)
3064 clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3065 smp_mb__after_atomic();
3066 queue_work(md->wq, &md->work);
3070 * Swap in a new table, returning the old one for the caller to destroy.
3072 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
3074 struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
3075 struct queue_limits limits;
3076 int r;
3078 mutex_lock(&md->suspend_lock);
3080 /* device must be suspended */
3081 if (!dm_suspended_md(md))
3082 goto out;
3085 * If the new table has no data devices, retain the existing limits.
3086 * This helps multipath with queue_if_no_path if all paths disappear,
3087 * then new I/O is queued based on these limits, and then some paths
3088 * reappear.
3090 if (dm_table_has_no_data_devices(table)) {
3091 live_map = dm_get_live_table_fast(md);
3092 if (live_map)
3093 limits = md->queue->limits;
3094 dm_put_live_table_fast(md);
3097 if (!live_map) {
3098 r = dm_calculate_queue_limits(table, &limits);
3099 if (r) {
3100 map = ERR_PTR(r);
3101 goto out;
3105 map = __bind(md, table, &limits);
3107 out:
3108 mutex_unlock(&md->suspend_lock);
3109 return map;
3113 * Functions to lock and unlock any filesystem running on the
3114 * device.
3116 static int lock_fs(struct mapped_device *md)
3118 int r;
3120 WARN_ON(md->frozen_sb);
3122 md->frozen_sb = freeze_bdev(md->bdev);
3123 if (IS_ERR(md->frozen_sb)) {
3124 r = PTR_ERR(md->frozen_sb);
3125 md->frozen_sb = NULL;
3126 return r;
3129 set_bit(DMF_FROZEN, &md->flags);
3131 return 0;
3134 static void unlock_fs(struct mapped_device *md)
3136 if (!test_bit(DMF_FROZEN, &md->flags))
3137 return;
3139 thaw_bdev(md->bdev, md->frozen_sb);
3140 md->frozen_sb = NULL;
3141 clear_bit(DMF_FROZEN, &md->flags);
3145 * If __dm_suspend returns 0, the device is completely quiescent
3146 * now. There is no request-processing activity. All new requests
3147 * are being added to md->deferred list.
3149 * Caller must hold md->suspend_lock
3151 static int __dm_suspend(struct mapped_device *md, struct dm_table *map,
3152 unsigned suspend_flags, int interruptible,
3153 int dmf_suspended_flag)
3155 bool do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG;
3156 bool noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG;
3157 int r;
3160 * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
3161 * This flag is cleared before dm_suspend returns.
3163 if (noflush)
3164 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3167 * This gets reverted if there's an error later and the targets
3168 * provide the .presuspend_undo hook.
3170 dm_table_presuspend_targets(map);
3173 * Flush I/O to the device.
3174 * Any I/O submitted after lock_fs() may not be flushed.
3175 * noflush takes precedence over do_lockfs.
3176 * (lock_fs() flushes I/Os and waits for them to complete.)
3178 if (!noflush && do_lockfs) {
3179 r = lock_fs(md);
3180 if (r) {
3181 dm_table_presuspend_undo_targets(map);
3182 return r;
3187 * Here we must make sure that no processes are submitting requests
3188 * to target drivers i.e. no one may be executing
3189 * __split_and_process_bio. This is called from dm_request and
3190 * dm_wq_work.
3192 * To get all processes out of __split_and_process_bio in dm_request,
3193 * we take the write lock. To prevent any process from reentering
3194 * __split_and_process_bio from dm_request and quiesce the thread
3195 * (dm_wq_work), we set BMF_BLOCK_IO_FOR_SUSPEND and call
3196 * flush_workqueue(md->wq).
3198 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3199 if (map)
3200 synchronize_srcu(&md->io_barrier);
3203 * Stop md->queue before flushing md->wq in case request-based
3204 * dm defers requests to md->wq from md->queue.
3206 if (dm_request_based(md)) {
3207 stop_queue(md->queue);
3208 if (md->kworker_task)
3209 flush_kthread_worker(&md->kworker);
3212 flush_workqueue(md->wq);
3215 * At this point no more requests are entering target request routines.
3216 * We call dm_wait_for_completion to wait for all existing requests
3217 * to finish.
3219 r = dm_wait_for_completion(md, interruptible);
3220 if (!r)
3221 set_bit(dmf_suspended_flag, &md->flags);
3223 if (noflush)
3224 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3225 if (map)
3226 synchronize_srcu(&md->io_barrier);
3228 /* were we interrupted ? */
3229 if (r < 0) {
3230 dm_queue_flush(md);
3232 if (dm_request_based(md))
3233 start_queue(md->queue);
3235 unlock_fs(md);
3236 dm_table_presuspend_undo_targets(map);
3237 /* pushback list is already flushed, so skip flush */
3240 return r;
3244 * We need to be able to change a mapping table under a mounted
3245 * filesystem. For example we might want to move some data in
3246 * the background. Before the table can be swapped with
3247 * dm_bind_table, dm_suspend must be called to flush any in
3248 * flight bios and ensure that any further io gets deferred.
3251 * Suspend mechanism in request-based dm.
3253 * 1. Flush all I/Os by lock_fs() if needed.
3254 * 2. Stop dispatching any I/O by stopping the request_queue.
3255 * 3. Wait for all in-flight I/Os to be completed or requeued.
3257 * To abort suspend, start the request_queue.
3259 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
3261 struct dm_table *map = NULL;
3262 int r = 0;
3264 retry:
3265 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3267 if (dm_suspended_md(md)) {
3268 r = -EINVAL;
3269 goto out_unlock;
3272 if (dm_suspended_internally_md(md)) {
3273 /* already internally suspended, wait for internal resume */
3274 mutex_unlock(&md->suspend_lock);
3275 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3276 if (r)
3277 return r;
3278 goto retry;
3281 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3283 r = __dm_suspend(md, map, suspend_flags, TASK_INTERRUPTIBLE, DMF_SUSPENDED);
3284 if (r)
3285 goto out_unlock;
3287 dm_table_postsuspend_targets(map);
3289 out_unlock:
3290 mutex_unlock(&md->suspend_lock);
3291 return r;
3294 static int __dm_resume(struct mapped_device *md, struct dm_table *map)
3296 if (map) {
3297 int r = dm_table_resume_targets(map);
3298 if (r)
3299 return r;
3302 dm_queue_flush(md);
3305 * Flushing deferred I/Os must be done after targets are resumed
3306 * so that mapping of targets can work correctly.
3307 * Request-based dm is queueing the deferred I/Os in its request_queue.
3309 if (dm_request_based(md))
3310 start_queue(md->queue);
3312 unlock_fs(md);
3314 return 0;
3317 int dm_resume(struct mapped_device *md)
3319 int r = -EINVAL;
3320 struct dm_table *map = NULL;
3322 retry:
3323 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3325 if (!dm_suspended_md(md))
3326 goto out;
3328 if (dm_suspended_internally_md(md)) {
3329 /* already internally suspended, wait for internal resume */
3330 mutex_unlock(&md->suspend_lock);
3331 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3332 if (r)
3333 return r;
3334 goto retry;
3337 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3338 if (!map || !dm_table_get_size(map))
3339 goto out;
3341 r = __dm_resume(md, map);
3342 if (r)
3343 goto out;
3345 clear_bit(DMF_SUSPENDED, &md->flags);
3347 r = 0;
3348 out:
3349 mutex_unlock(&md->suspend_lock);
3351 return r;
3355 * Internal suspend/resume works like userspace-driven suspend. It waits
3356 * until all bios finish and prevents issuing new bios to the target drivers.
3357 * It may be used only from the kernel.
3360 static void __dm_internal_suspend(struct mapped_device *md, unsigned suspend_flags)
3362 struct dm_table *map = NULL;
3364 if (md->internal_suspend_count++)
3365 return; /* nested internal suspend */
3367 if (dm_suspended_md(md)) {
3368 set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3369 return; /* nest suspend */
3372 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3375 * Using TASK_UNINTERRUPTIBLE because only NOFLUSH internal suspend is
3376 * supported. Properly supporting a TASK_INTERRUPTIBLE internal suspend
3377 * would require changing .presuspend to return an error -- avoid this
3378 * until there is a need for more elaborate variants of internal suspend.
3380 (void) __dm_suspend(md, map, suspend_flags, TASK_UNINTERRUPTIBLE,
3381 DMF_SUSPENDED_INTERNALLY);
3383 dm_table_postsuspend_targets(map);
3386 static void __dm_internal_resume(struct mapped_device *md)
3388 BUG_ON(!md->internal_suspend_count);
3390 if (--md->internal_suspend_count)
3391 return; /* resume from nested internal suspend */
3393 if (dm_suspended_md(md))
3394 goto done; /* resume from nested suspend */
3397 * NOTE: existing callers don't need to call dm_table_resume_targets
3398 * (which may fail -- so best to avoid it for now by passing NULL map)
3400 (void) __dm_resume(md, NULL);
3402 done:
3403 clear_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3404 smp_mb__after_atomic();
3405 wake_up_bit(&md->flags, DMF_SUSPENDED_INTERNALLY);
3408 void dm_internal_suspend_noflush(struct mapped_device *md)
3410 mutex_lock(&md->suspend_lock);
3411 __dm_internal_suspend(md, DM_SUSPEND_NOFLUSH_FLAG);
3412 mutex_unlock(&md->suspend_lock);
3414 EXPORT_SYMBOL_GPL(dm_internal_suspend_noflush);
3416 void dm_internal_resume(struct mapped_device *md)
3418 mutex_lock(&md->suspend_lock);
3419 __dm_internal_resume(md);
3420 mutex_unlock(&md->suspend_lock);
3422 EXPORT_SYMBOL_GPL(dm_internal_resume);
3425 * Fast variants of internal suspend/resume hold md->suspend_lock,
3426 * which prevents interaction with userspace-driven suspend.
3429 void dm_internal_suspend_fast(struct mapped_device *md)
3431 mutex_lock(&md->suspend_lock);
3432 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3433 return;
3435 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3436 synchronize_srcu(&md->io_barrier);
3437 flush_workqueue(md->wq);
3438 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
3440 EXPORT_SYMBOL_GPL(dm_internal_suspend_fast);
3442 void dm_internal_resume_fast(struct mapped_device *md)
3444 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3445 goto done;
3447 dm_queue_flush(md);
3449 done:
3450 mutex_unlock(&md->suspend_lock);
3452 EXPORT_SYMBOL_GPL(dm_internal_resume_fast);
3454 /*-----------------------------------------------------------------
3455 * Event notification.
3456 *---------------------------------------------------------------*/
3457 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
3458 unsigned cookie)
3460 char udev_cookie[DM_COOKIE_LENGTH];
3461 char *envp[] = { udev_cookie, NULL };
3463 if (!cookie)
3464 return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
3465 else {
3466 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
3467 DM_COOKIE_ENV_VAR_NAME, cookie);
3468 return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
3469 action, envp);
3473 uint32_t dm_next_uevent_seq(struct mapped_device *md)
3475 return atomic_add_return(1, &md->uevent_seq);
3478 uint32_t dm_get_event_nr(struct mapped_device *md)
3480 return atomic_read(&md->event_nr);
3483 int dm_wait_event(struct mapped_device *md, int event_nr)
3485 return wait_event_interruptible(md->eventq,
3486 (event_nr != atomic_read(&md->event_nr)));
3489 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
3491 unsigned long flags;
3493 spin_lock_irqsave(&md->uevent_lock, flags);
3494 list_add(elist, &md->uevent_list);
3495 spin_unlock_irqrestore(&md->uevent_lock, flags);
3499 * The gendisk is only valid as long as you have a reference
3500 * count on 'md'.
3502 struct gendisk *dm_disk(struct mapped_device *md)
3504 return md->disk;
3506 EXPORT_SYMBOL_GPL(dm_disk);
3508 struct kobject *dm_kobject(struct mapped_device *md)
3510 return &md->kobj_holder.kobj;
3513 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
3515 struct mapped_device *md;
3517 md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
3519 if (test_bit(DMF_FREEING, &md->flags) ||
3520 dm_deleting_md(md))
3521 return NULL;
3523 dm_get(md);
3524 return md;
3527 int dm_suspended_md(struct mapped_device *md)
3529 return test_bit(DMF_SUSPENDED, &md->flags);
3532 int dm_suspended_internally_md(struct mapped_device *md)
3534 return test_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3537 int dm_test_deferred_remove_flag(struct mapped_device *md)
3539 return test_bit(DMF_DEFERRED_REMOVE, &md->flags);
3542 int dm_suspended(struct dm_target *ti)
3544 return dm_suspended_md(dm_table_get_md(ti->table));
3546 EXPORT_SYMBOL_GPL(dm_suspended);
3548 int dm_noflush_suspending(struct dm_target *ti)
3550 return __noflush_suspending(dm_table_get_md(ti->table));
3552 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
3554 struct dm_md_mempools *dm_alloc_md_mempools(struct mapped_device *md, unsigned type,
3555 unsigned integrity, unsigned per_bio_data_size)
3557 struct dm_md_mempools *pools = kzalloc(sizeof(*pools), GFP_KERNEL);
3558 struct kmem_cache *cachep = NULL;
3559 unsigned int pool_size = 0;
3560 unsigned int front_pad;
3562 if (!pools)
3563 return NULL;
3565 type = filter_md_type(type, md);
3567 switch (type) {
3568 case DM_TYPE_BIO_BASED:
3569 cachep = _io_cache;
3570 pool_size = dm_get_reserved_bio_based_ios();
3571 front_pad = roundup(per_bio_data_size, __alignof__(struct dm_target_io)) + offsetof(struct dm_target_io, clone);
3572 break;
3573 case DM_TYPE_REQUEST_BASED:
3574 cachep = _rq_tio_cache;
3575 pool_size = dm_get_reserved_rq_based_ios();
3576 pools->rq_pool = mempool_create_slab_pool(pool_size, _rq_cache);
3577 if (!pools->rq_pool)
3578 goto out;
3579 /* fall through to setup remaining rq-based pools */
3580 case DM_TYPE_MQ_REQUEST_BASED:
3581 if (!pool_size)
3582 pool_size = dm_get_reserved_rq_based_ios();
3583 front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
3584 /* per_bio_data_size is not used. See __bind_mempools(). */
3585 WARN_ON(per_bio_data_size != 0);
3586 break;
3587 default:
3588 BUG();
3591 if (cachep) {
3592 pools->io_pool = mempool_create_slab_pool(pool_size, cachep);
3593 if (!pools->io_pool)
3594 goto out;
3597 pools->bs = bioset_create_nobvec(pool_size, front_pad);
3598 if (!pools->bs)
3599 goto out;
3601 if (integrity && bioset_integrity_create(pools->bs, pool_size))
3602 goto out;
3604 return pools;
3606 out:
3607 dm_free_md_mempools(pools);
3609 return NULL;
3612 void dm_free_md_mempools(struct dm_md_mempools *pools)
3614 if (!pools)
3615 return;
3617 if (pools->io_pool)
3618 mempool_destroy(pools->io_pool);
3620 if (pools->rq_pool)
3621 mempool_destroy(pools->rq_pool);
3623 if (pools->bs)
3624 bioset_free(pools->bs);
3626 kfree(pools);
3629 static const struct block_device_operations dm_blk_dops = {
3630 .open = dm_blk_open,
3631 .release = dm_blk_close,
3632 .ioctl = dm_blk_ioctl,
3633 .getgeo = dm_blk_getgeo,
3634 .owner = THIS_MODULE
3638 * module hooks
3640 module_init(dm_init);
3641 module_exit(dm_exit);
3643 module_param(major, uint, 0);
3644 MODULE_PARM_DESC(major, "The major number of the device mapper");
3646 module_param(reserved_bio_based_ios, uint, S_IRUGO | S_IWUSR);
3647 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
3649 module_param(reserved_rq_based_ios, uint, S_IRUGO | S_IWUSR);
3650 MODULE_PARM_DESC(reserved_rq_based_ios, "Reserved IOs in request-based mempools");
3652 module_param(use_blk_mq, bool, S_IRUGO | S_IWUSR);
3653 MODULE_PARM_DESC(use_blk_mq, "Use block multiqueue for request-based DM devices");
3655 MODULE_DESCRIPTION(DM_NAME " driver");
3656 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
3657 MODULE_LICENSE("GPL");