dm: fix a couple locking issues with use of block interfaces
[cascardo/linux.git] / drivers / md / dm.c
1 /*
2  * Copyright (C) 2001, 2002 Sistina Software (UK) Limited.
3  * Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7
8 #include "dm.h"
9 #include "dm-uevent.h"
10
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>
27 #include <linux/pr.h>
28
29 #include <trace/events/block.h>
30
31 #define DM_MSG_PREFIX "core"
32
33 #ifdef CONFIG_PRINTK
34 /*
35  * ratelimit state to be used in DMXXX_LIMIT().
36  */
37 DEFINE_RATELIMIT_STATE(dm_ratelimit_state,
38                        DEFAULT_RATELIMIT_INTERVAL,
39                        DEFAULT_RATELIMIT_BURST);
40 EXPORT_SYMBOL(dm_ratelimit_state);
41 #endif
42
43 /*
44  * Cookies are numeric values sent with CHANGE and REMOVE
45  * uevents while resuming, removing or renaming the device.
46  */
47 #define DM_COOKIE_ENV_VAR_NAME "DM_COOKIE"
48 #define DM_COOKIE_LENGTH 24
49
50 static const char *_name = DM_NAME;
51
52 static unsigned int major = 0;
53 static unsigned int _major = 0;
54
55 static DEFINE_IDR(_minor_idr);
56
57 static DEFINE_SPINLOCK(_minor_lock);
58
59 static void do_deferred_remove(struct work_struct *w);
60
61 static DECLARE_WORK(deferred_remove_work, do_deferred_remove);
62
63 static struct workqueue_struct *deferred_remove_workqueue;
64
65 /*
66  * For bio-based dm.
67  * One of these is allocated per bio.
68  */
69 struct dm_io {
70         struct mapped_device *md;
71         int error;
72         atomic_t io_count;
73         struct bio *bio;
74         unsigned long start_time;
75         spinlock_t endio_lock;
76         struct dm_stats_aux stats_aux;
77 };
78
79 /*
80  * For request-based dm.
81  * One of these is allocated per request.
82  */
83 struct dm_rq_target_io {
84         struct mapped_device *md;
85         struct dm_target *ti;
86         struct request *orig, *clone;
87         struct kthread_work work;
88         int error;
89         union map_info info;
90         struct dm_stats_aux stats_aux;
91         unsigned long duration_jiffies;
92         unsigned n_sectors;
93 };
94
95 /*
96  * For request-based dm - the bio clones we allocate are embedded in these
97  * structs.
98  *
99  * We allocate these with bio_alloc_bioset, using the front_pad parameter when
100  * the bioset is created - this means the bio has to come at the end of the
101  * struct.
102  */
103 struct dm_rq_clone_bio_info {
104         struct bio *orig;
105         struct dm_rq_target_io *tio;
106         struct bio clone;
107 };
108
109 #define MINOR_ALLOCED ((void *)-1)
110
111 /*
112  * Bits for the md->flags field.
113  */
114 #define DMF_BLOCK_IO_FOR_SUSPEND 0
115 #define DMF_SUSPENDED 1
116 #define DMF_FROZEN 2
117 #define DMF_FREEING 3
118 #define DMF_DELETING 4
119 #define DMF_NOFLUSH_SUSPENDING 5
120 #define DMF_DEFERRED_REMOVE 6
121 #define DMF_SUSPENDED_INTERNALLY 7
122
123 /*
124  * A dummy definition to make RCU happy.
125  * struct dm_table should never be dereferenced in this file.
126  */
127 struct dm_table {
128         int undefined__;
129 };
130
131 /*
132  * Work processed by per-device workqueue.
133  */
134 struct mapped_device {
135         struct srcu_struct io_barrier;
136         struct mutex suspend_lock;
137         atomic_t holders;
138         atomic_t open_count;
139
140         /*
141          * The current mapping.
142          * Use dm_get_live_table{_fast} or take suspend_lock for
143          * dereference.
144          */
145         struct dm_table __rcu *map;
146
147         struct list_head table_devices;
148         struct mutex table_devices_lock;
149
150         unsigned long flags;
151
152         struct request_queue *queue;
153         unsigned type;
154         /* Protect queue and type against concurrent access. */
155         struct mutex type_lock;
156
157         struct dm_target *immutable_target;
158         struct target_type *immutable_target_type;
159
160         struct gendisk *disk;
161         char name[16];
162
163         void *interface_ptr;
164
165         /*
166          * A list of ios that arrived while we were suspended.
167          */
168         atomic_t pending[2];
169         wait_queue_head_t wait;
170         struct work_struct work;
171         struct bio_list deferred;
172         spinlock_t deferred_lock;
173
174         /*
175          * Processing queue (flush)
176          */
177         struct workqueue_struct *wq;
178
179         /*
180          * io objects are allocated from here.
181          */
182         mempool_t *io_pool;
183         mempool_t *rq_pool;
184
185         struct bio_set *bs;
186
187         /*
188          * Event handling.
189          */
190         atomic_t event_nr;
191         wait_queue_head_t eventq;
192         atomic_t uevent_seq;
193         struct list_head uevent_list;
194         spinlock_t uevent_lock; /* Protect access to uevent_list */
195
196         /*
197          * freeze/thaw support require holding onto a super block
198          */
199         struct super_block *frozen_sb;
200         struct block_device *bdev;
201
202         /* forced geometry settings */
203         struct hd_geometry geometry;
204
205         /* kobject and completion */
206         struct dm_kobject_holder kobj_holder;
207
208         /* zero-length flush that will be cloned and submitted to targets */
209         struct bio flush_bio;
210
211         /* the number of internal suspends */
212         unsigned internal_suspend_count;
213
214         struct dm_stats stats;
215
216         struct kthread_worker kworker;
217         struct task_struct *kworker_task;
218
219         /* for request-based merge heuristic in dm_request_fn() */
220         unsigned seq_rq_merge_deadline_usecs;
221         int last_rq_rw;
222         sector_t last_rq_pos;
223         ktime_t last_rq_start_time;
224
225         /* for blk-mq request-based DM support */
226         struct blk_mq_tag_set *tag_set;
227         bool use_blk_mq;
228 };
229
230 #ifdef CONFIG_DM_MQ_DEFAULT
231 static bool use_blk_mq = true;
232 #else
233 static bool use_blk_mq = false;
234 #endif
235
236 #define DM_MQ_NR_HW_QUEUES 1
237 #define DM_MQ_QUEUE_DEPTH 2048
238
239 static unsigned dm_mq_nr_hw_queues = DM_MQ_NR_HW_QUEUES;
240 static unsigned dm_mq_queue_depth = DM_MQ_QUEUE_DEPTH;
241
242 bool dm_use_blk_mq(struct mapped_device *md)
243 {
244         return md->use_blk_mq;
245 }
246
247 /*
248  * For mempools pre-allocation at the table loading time.
249  */
250 struct dm_md_mempools {
251         mempool_t *io_pool;
252         mempool_t *rq_pool;
253         struct bio_set *bs;
254 };
255
256 struct table_device {
257         struct list_head list;
258         atomic_t count;
259         struct dm_dev dm_dev;
260 };
261
262 #define RESERVED_BIO_BASED_IOS          16
263 #define RESERVED_REQUEST_BASED_IOS      256
264 #define RESERVED_MAX_IOS                1024
265 static struct kmem_cache *_io_cache;
266 static struct kmem_cache *_rq_tio_cache;
267 static struct kmem_cache *_rq_cache;
268
269 /*
270  * Bio-based DM's mempools' reserved IOs set by the user.
271  */
272 static unsigned reserved_bio_based_ios = RESERVED_BIO_BASED_IOS;
273
274 /*
275  * Request-based DM's mempools' reserved IOs set by the user.
276  */
277 static unsigned reserved_rq_based_ios = RESERVED_REQUEST_BASED_IOS;
278
279 static unsigned __dm_get_module_param(unsigned *module_param,
280                                       unsigned def, unsigned max)
281 {
282         unsigned param = ACCESS_ONCE(*module_param);
283         unsigned modified_param = 0;
284
285         if (!param)
286                 modified_param = def;
287         else if (param > max)
288                 modified_param = max;
289
290         if (modified_param) {
291                 (void)cmpxchg(module_param, param, modified_param);
292                 param = modified_param;
293         }
294
295         return param;
296 }
297
298 unsigned dm_get_reserved_bio_based_ios(void)
299 {
300         return __dm_get_module_param(&reserved_bio_based_ios,
301                                      RESERVED_BIO_BASED_IOS, RESERVED_MAX_IOS);
302 }
303 EXPORT_SYMBOL_GPL(dm_get_reserved_bio_based_ios);
304
305 unsigned dm_get_reserved_rq_based_ios(void)
306 {
307         return __dm_get_module_param(&reserved_rq_based_ios,
308                                      RESERVED_REQUEST_BASED_IOS, RESERVED_MAX_IOS);
309 }
310 EXPORT_SYMBOL_GPL(dm_get_reserved_rq_based_ios);
311
312 static unsigned dm_get_blk_mq_nr_hw_queues(void)
313 {
314         return __dm_get_module_param(&dm_mq_nr_hw_queues, 1, 32);
315 }
316
317 static unsigned dm_get_blk_mq_queue_depth(void)
318 {
319         return __dm_get_module_param(&dm_mq_queue_depth,
320                                      DM_MQ_QUEUE_DEPTH, BLK_MQ_MAX_DEPTH);
321 }
322
323 static int __init local_init(void)
324 {
325         int r = -ENOMEM;
326
327         /* allocate a slab for the dm_ios */
328         _io_cache = KMEM_CACHE(dm_io, 0);
329         if (!_io_cache)
330                 return r;
331
332         _rq_tio_cache = KMEM_CACHE(dm_rq_target_io, 0);
333         if (!_rq_tio_cache)
334                 goto out_free_io_cache;
335
336         _rq_cache = kmem_cache_create("dm_clone_request", sizeof(struct request),
337                                       __alignof__(struct request), 0, NULL);
338         if (!_rq_cache)
339                 goto out_free_rq_tio_cache;
340
341         r = dm_uevent_init();
342         if (r)
343                 goto out_free_rq_cache;
344
345         deferred_remove_workqueue = alloc_workqueue("kdmremove", WQ_UNBOUND, 1);
346         if (!deferred_remove_workqueue) {
347                 r = -ENOMEM;
348                 goto out_uevent_exit;
349         }
350
351         _major = major;
352         r = register_blkdev(_major, _name);
353         if (r < 0)
354                 goto out_free_workqueue;
355
356         if (!_major)
357                 _major = r;
358
359         return 0;
360
361 out_free_workqueue:
362         destroy_workqueue(deferred_remove_workqueue);
363 out_uevent_exit:
364         dm_uevent_exit();
365 out_free_rq_cache:
366         kmem_cache_destroy(_rq_cache);
367 out_free_rq_tio_cache:
368         kmem_cache_destroy(_rq_tio_cache);
369 out_free_io_cache:
370         kmem_cache_destroy(_io_cache);
371
372         return r;
373 }
374
375 static void local_exit(void)
376 {
377         flush_scheduled_work();
378         destroy_workqueue(deferred_remove_workqueue);
379
380         kmem_cache_destroy(_rq_cache);
381         kmem_cache_destroy(_rq_tio_cache);
382         kmem_cache_destroy(_io_cache);
383         unregister_blkdev(_major, _name);
384         dm_uevent_exit();
385
386         _major = 0;
387
388         DMINFO("cleaned up");
389 }
390
391 static int (*_inits[])(void) __initdata = {
392         local_init,
393         dm_target_init,
394         dm_linear_init,
395         dm_stripe_init,
396         dm_io_init,
397         dm_kcopyd_init,
398         dm_interface_init,
399         dm_statistics_init,
400 };
401
402 static void (*_exits[])(void) = {
403         local_exit,
404         dm_target_exit,
405         dm_linear_exit,
406         dm_stripe_exit,
407         dm_io_exit,
408         dm_kcopyd_exit,
409         dm_interface_exit,
410         dm_statistics_exit,
411 };
412
413 static int __init dm_init(void)
414 {
415         const int count = ARRAY_SIZE(_inits);
416
417         int r, i;
418
419         for (i = 0; i < count; i++) {
420                 r = _inits[i]();
421                 if (r)
422                         goto bad;
423         }
424
425         return 0;
426
427       bad:
428         while (i--)
429                 _exits[i]();
430
431         return r;
432 }
433
434 static void __exit dm_exit(void)
435 {
436         int i = ARRAY_SIZE(_exits);
437
438         while (i--)
439                 _exits[i]();
440
441         /*
442          * Should be empty by this point.
443          */
444         idr_destroy(&_minor_idr);
445 }
446
447 /*
448  * Block device functions
449  */
450 int dm_deleting_md(struct mapped_device *md)
451 {
452         return test_bit(DMF_DELETING, &md->flags);
453 }
454
455 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
456 {
457         struct mapped_device *md;
458
459         spin_lock(&_minor_lock);
460
461         md = bdev->bd_disk->private_data;
462         if (!md)
463                 goto out;
464
465         if (test_bit(DMF_FREEING, &md->flags) ||
466             dm_deleting_md(md)) {
467                 md = NULL;
468                 goto out;
469         }
470
471         dm_get(md);
472         atomic_inc(&md->open_count);
473 out:
474         spin_unlock(&_minor_lock);
475
476         return md ? 0 : -ENXIO;
477 }
478
479 static void dm_blk_close(struct gendisk *disk, fmode_t mode)
480 {
481         struct mapped_device *md;
482
483         spin_lock(&_minor_lock);
484
485         md = disk->private_data;
486         if (WARN_ON(!md))
487                 goto out;
488
489         if (atomic_dec_and_test(&md->open_count) &&
490             (test_bit(DMF_DEFERRED_REMOVE, &md->flags)))
491                 queue_work(deferred_remove_workqueue, &deferred_remove_work);
492
493         dm_put(md);
494 out:
495         spin_unlock(&_minor_lock);
496 }
497
498 int dm_open_count(struct mapped_device *md)
499 {
500         return atomic_read(&md->open_count);
501 }
502
503 /*
504  * Guarantees nothing is using the device before it's deleted.
505  */
506 int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
507 {
508         int r = 0;
509
510         spin_lock(&_minor_lock);
511
512         if (dm_open_count(md)) {
513                 r = -EBUSY;
514                 if (mark_deferred)
515                         set_bit(DMF_DEFERRED_REMOVE, &md->flags);
516         } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
517                 r = -EEXIST;
518         else
519                 set_bit(DMF_DELETING, &md->flags);
520
521         spin_unlock(&_minor_lock);
522
523         return r;
524 }
525
526 int dm_cancel_deferred_remove(struct mapped_device *md)
527 {
528         int r = 0;
529
530         spin_lock(&_minor_lock);
531
532         if (test_bit(DMF_DELETING, &md->flags))
533                 r = -EBUSY;
534         else
535                 clear_bit(DMF_DEFERRED_REMOVE, &md->flags);
536
537         spin_unlock(&_minor_lock);
538
539         return r;
540 }
541
542 static void do_deferred_remove(struct work_struct *w)
543 {
544         dm_deferred_remove();
545 }
546
547 sector_t dm_get_size(struct mapped_device *md)
548 {
549         return get_capacity(md->disk);
550 }
551
552 struct request_queue *dm_get_md_queue(struct mapped_device *md)
553 {
554         return md->queue;
555 }
556
557 struct dm_stats *dm_get_stats(struct mapped_device *md)
558 {
559         return &md->stats;
560 }
561
562 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
563 {
564         struct mapped_device *md = bdev->bd_disk->private_data;
565
566         return dm_get_geometry(md, geo);
567 }
568
569 static int dm_grab_bdev_for_ioctl(struct mapped_device *md,
570                                   struct block_device **bdev,
571                                   fmode_t *mode)
572 {
573         struct dm_target *tgt;
574         struct dm_table *map;
575         int srcu_idx, r;
576
577 retry:
578         r = -ENOTTY;
579         map = dm_get_live_table(md, &srcu_idx);
580         if (!map || !dm_table_get_size(map))
581                 goto out;
582
583         /* We only support devices that have a single target */
584         if (dm_table_get_num_targets(map) != 1)
585                 goto out;
586
587         tgt = dm_table_get_target(map, 0);
588         if (!tgt->type->prepare_ioctl)
589                 goto out;
590
591         if (dm_suspended_md(md)) {
592                 r = -EAGAIN;
593                 goto out;
594         }
595
596         r = tgt->type->prepare_ioctl(tgt, bdev, mode);
597         if (r < 0)
598                 goto out;
599
600         bdgrab(*bdev);
601         dm_put_live_table(md, srcu_idx);
602         return r;
603
604 out:
605         dm_put_live_table(md, srcu_idx);
606         if (r == -ENOTCONN && !fatal_signal_pending(current)) {
607                 msleep(10);
608                 goto retry;
609         }
610         return r;
611 }
612
613 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
614                         unsigned int cmd, unsigned long arg)
615 {
616         struct mapped_device *md = bdev->bd_disk->private_data;
617         int r;
618
619         r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
620         if (r < 0)
621                 return r;
622
623         if (r > 0) {
624                 /*
625                  * Target determined this ioctl is being issued against
626                  * a logical partition of the parent bdev; so extra
627                  * validation is needed.
628                  */
629                 r = scsi_verify_blk_ioctl(NULL, cmd);
630                 if (r)
631                         goto out;
632         }
633
634         r =  __blkdev_driver_ioctl(bdev, mode, cmd, arg);
635 out:
636         bdput(bdev);
637         return r;
638 }
639
640 static struct dm_io *alloc_io(struct mapped_device *md)
641 {
642         return mempool_alloc(md->io_pool, GFP_NOIO);
643 }
644
645 static void free_io(struct mapped_device *md, struct dm_io *io)
646 {
647         mempool_free(io, md->io_pool);
648 }
649
650 static void free_tio(struct mapped_device *md, struct dm_target_io *tio)
651 {
652         bio_put(&tio->clone);
653 }
654
655 static struct dm_rq_target_io *alloc_rq_tio(struct mapped_device *md,
656                                             gfp_t gfp_mask)
657 {
658         return mempool_alloc(md->io_pool, gfp_mask);
659 }
660
661 static void free_rq_tio(struct dm_rq_target_io *tio)
662 {
663         mempool_free(tio, tio->md->io_pool);
664 }
665
666 static struct request *alloc_clone_request(struct mapped_device *md,
667                                            gfp_t gfp_mask)
668 {
669         return mempool_alloc(md->rq_pool, gfp_mask);
670 }
671
672 static void free_clone_request(struct mapped_device *md, struct request *rq)
673 {
674         mempool_free(rq, md->rq_pool);
675 }
676
677 static int md_in_flight(struct mapped_device *md)
678 {
679         return atomic_read(&md->pending[READ]) +
680                atomic_read(&md->pending[WRITE]);
681 }
682
683 static void start_io_acct(struct dm_io *io)
684 {
685         struct mapped_device *md = io->md;
686         struct bio *bio = io->bio;
687         int cpu;
688         int rw = bio_data_dir(bio);
689
690         io->start_time = jiffies;
691
692         cpu = part_stat_lock();
693         part_round_stats(cpu, &dm_disk(md)->part0);
694         part_stat_unlock();
695         atomic_set(&dm_disk(md)->part0.in_flight[rw],
696                 atomic_inc_return(&md->pending[rw]));
697
698         if (unlikely(dm_stats_used(&md->stats)))
699                 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_iter.bi_sector,
700                                     bio_sectors(bio), false, 0, &io->stats_aux);
701 }
702
703 static void end_io_acct(struct dm_io *io)
704 {
705         struct mapped_device *md = io->md;
706         struct bio *bio = io->bio;
707         unsigned long duration = jiffies - io->start_time;
708         int pending;
709         int rw = bio_data_dir(bio);
710
711         generic_end_io_acct(rw, &dm_disk(md)->part0, io->start_time);
712
713         if (unlikely(dm_stats_used(&md->stats)))
714                 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_iter.bi_sector,
715                                     bio_sectors(bio), true, duration, &io->stats_aux);
716
717         /*
718          * After this is decremented the bio must not be touched if it is
719          * a flush.
720          */
721         pending = atomic_dec_return(&md->pending[rw]);
722         atomic_set(&dm_disk(md)->part0.in_flight[rw], pending);
723         pending += atomic_read(&md->pending[rw^0x1]);
724
725         /* nudge anyone waiting on suspend queue */
726         if (!pending)
727                 wake_up(&md->wait);
728 }
729
730 /*
731  * Add the bio to the list of deferred io.
732  */
733 static void queue_io(struct mapped_device *md, struct bio *bio)
734 {
735         unsigned long flags;
736
737         spin_lock_irqsave(&md->deferred_lock, flags);
738         bio_list_add(&md->deferred, bio);
739         spin_unlock_irqrestore(&md->deferred_lock, flags);
740         queue_work(md->wq, &md->work);
741 }
742
743 /*
744  * Everyone (including functions in this file), should use this
745  * function to access the md->map field, and make sure they call
746  * dm_put_live_table() when finished.
747  */
748 struct dm_table *dm_get_live_table(struct mapped_device *md, int *srcu_idx) __acquires(md->io_barrier)
749 {
750         *srcu_idx = srcu_read_lock(&md->io_barrier);
751
752         return srcu_dereference(md->map, &md->io_barrier);
753 }
754
755 void dm_put_live_table(struct mapped_device *md, int srcu_idx) __releases(md->io_barrier)
756 {
757         srcu_read_unlock(&md->io_barrier, srcu_idx);
758 }
759
760 void dm_sync_table(struct mapped_device *md)
761 {
762         synchronize_srcu(&md->io_barrier);
763         synchronize_rcu_expedited();
764 }
765
766 /*
767  * A fast alternative to dm_get_live_table/dm_put_live_table.
768  * The caller must not block between these two functions.
769  */
770 static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
771 {
772         rcu_read_lock();
773         return rcu_dereference(md->map);
774 }
775
776 static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
777 {
778         rcu_read_unlock();
779 }
780
781 /*
782  * Open a table device so we can use it as a map destination.
783  */
784 static int open_table_device(struct table_device *td, dev_t dev,
785                              struct mapped_device *md)
786 {
787         static char *_claim_ptr = "I belong to device-mapper";
788         struct block_device *bdev;
789
790         int r;
791
792         BUG_ON(td->dm_dev.bdev);
793
794         bdev = blkdev_get_by_dev(dev, td->dm_dev.mode | FMODE_EXCL, _claim_ptr);
795         if (IS_ERR(bdev))
796                 return PTR_ERR(bdev);
797
798         r = bd_link_disk_holder(bdev, dm_disk(md));
799         if (r) {
800                 blkdev_put(bdev, td->dm_dev.mode | FMODE_EXCL);
801                 return r;
802         }
803
804         td->dm_dev.bdev = bdev;
805         return 0;
806 }
807
808 /*
809  * Close a table device that we've been using.
810  */
811 static void close_table_device(struct table_device *td, struct mapped_device *md)
812 {
813         if (!td->dm_dev.bdev)
814                 return;
815
816         bd_unlink_disk_holder(td->dm_dev.bdev, dm_disk(md));
817         blkdev_put(td->dm_dev.bdev, td->dm_dev.mode | FMODE_EXCL);
818         td->dm_dev.bdev = NULL;
819 }
820
821 static struct table_device *find_table_device(struct list_head *l, dev_t dev,
822                                               fmode_t mode) {
823         struct table_device *td;
824
825         list_for_each_entry(td, l, list)
826                 if (td->dm_dev.bdev->bd_dev == dev && td->dm_dev.mode == mode)
827                         return td;
828
829         return NULL;
830 }
831
832 int dm_get_table_device(struct mapped_device *md, dev_t dev, fmode_t mode,
833                         struct dm_dev **result) {
834         int r;
835         struct table_device *td;
836
837         mutex_lock(&md->table_devices_lock);
838         td = find_table_device(&md->table_devices, dev, mode);
839         if (!td) {
840                 td = kmalloc(sizeof(*td), GFP_KERNEL);
841                 if (!td) {
842                         mutex_unlock(&md->table_devices_lock);
843                         return -ENOMEM;
844                 }
845
846                 td->dm_dev.mode = mode;
847                 td->dm_dev.bdev = NULL;
848
849                 if ((r = open_table_device(td, dev, md))) {
850                         mutex_unlock(&md->table_devices_lock);
851                         kfree(td);
852                         return r;
853                 }
854
855                 format_dev_t(td->dm_dev.name, dev);
856
857                 atomic_set(&td->count, 0);
858                 list_add(&td->list, &md->table_devices);
859         }
860         atomic_inc(&td->count);
861         mutex_unlock(&md->table_devices_lock);
862
863         *result = &td->dm_dev;
864         return 0;
865 }
866 EXPORT_SYMBOL_GPL(dm_get_table_device);
867
868 void dm_put_table_device(struct mapped_device *md, struct dm_dev *d)
869 {
870         struct table_device *td = container_of(d, struct table_device, dm_dev);
871
872         mutex_lock(&md->table_devices_lock);
873         if (atomic_dec_and_test(&td->count)) {
874                 close_table_device(td, md);
875                 list_del(&td->list);
876                 kfree(td);
877         }
878         mutex_unlock(&md->table_devices_lock);
879 }
880 EXPORT_SYMBOL(dm_put_table_device);
881
882 static void free_table_devices(struct list_head *devices)
883 {
884         struct list_head *tmp, *next;
885
886         list_for_each_safe(tmp, next, devices) {
887                 struct table_device *td = list_entry(tmp, struct table_device, list);
888
889                 DMWARN("dm_destroy: %s still exists with %d references",
890                        td->dm_dev.name, atomic_read(&td->count));
891                 kfree(td);
892         }
893 }
894
895 /*
896  * Get the geometry associated with a dm device
897  */
898 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
899 {
900         *geo = md->geometry;
901
902         return 0;
903 }
904
905 /*
906  * Set the geometry of a device.
907  */
908 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
909 {
910         sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
911
912         if (geo->start > sz) {
913                 DMWARN("Start sector is beyond the geometry limits.");
914                 return -EINVAL;
915         }
916
917         md->geometry = *geo;
918
919         return 0;
920 }
921
922 /*-----------------------------------------------------------------
923  * CRUD START:
924  *   A more elegant soln is in the works that uses the queue
925  *   merge fn, unfortunately there are a couple of changes to
926  *   the block layer that I want to make for this.  So in the
927  *   interests of getting something for people to use I give
928  *   you this clearly demarcated crap.
929  *---------------------------------------------------------------*/
930
931 static int __noflush_suspending(struct mapped_device *md)
932 {
933         return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
934 }
935
936 /*
937  * Decrements the number of outstanding ios that a bio has been
938  * cloned into, completing the original io if necc.
939  */
940 static void dec_pending(struct dm_io *io, int error)
941 {
942         unsigned long flags;
943         int io_error;
944         struct bio *bio;
945         struct mapped_device *md = io->md;
946
947         /* Push-back supersedes any I/O errors */
948         if (unlikely(error)) {
949                 spin_lock_irqsave(&io->endio_lock, flags);
950                 if (!(io->error > 0 && __noflush_suspending(md)))
951                         io->error = error;
952                 spin_unlock_irqrestore(&io->endio_lock, flags);
953         }
954
955         if (atomic_dec_and_test(&io->io_count)) {
956                 if (io->error == DM_ENDIO_REQUEUE) {
957                         /*
958                          * Target requested pushing back the I/O.
959                          */
960                         spin_lock_irqsave(&md->deferred_lock, flags);
961                         if (__noflush_suspending(md))
962                                 bio_list_add_head(&md->deferred, io->bio);
963                         else
964                                 /* noflush suspend was interrupted. */
965                                 io->error = -EIO;
966                         spin_unlock_irqrestore(&md->deferred_lock, flags);
967                 }
968
969                 io_error = io->error;
970                 bio = io->bio;
971                 end_io_acct(io);
972                 free_io(md, io);
973
974                 if (io_error == DM_ENDIO_REQUEUE)
975                         return;
976
977                 if ((bio->bi_rw & REQ_FLUSH) && bio->bi_iter.bi_size) {
978                         /*
979                          * Preflush done for flush with data, reissue
980                          * without REQ_FLUSH.
981                          */
982                         bio->bi_rw &= ~REQ_FLUSH;
983                         queue_io(md, bio);
984                 } else {
985                         /* done with normal IO or empty flush */
986                         trace_block_bio_complete(md->queue, bio, io_error);
987                         bio->bi_error = io_error;
988                         bio_endio(bio);
989                 }
990         }
991 }
992
993 static void disable_write_same(struct mapped_device *md)
994 {
995         struct queue_limits *limits = dm_get_queue_limits(md);
996
997         /* device doesn't really support WRITE SAME, disable it */
998         limits->max_write_same_sectors = 0;
999 }
1000
1001 static void clone_endio(struct bio *bio)
1002 {
1003         int error = bio->bi_error;
1004         int r = error;
1005         struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
1006         struct dm_io *io = tio->io;
1007         struct mapped_device *md = tio->io->md;
1008         dm_endio_fn endio = tio->ti->type->end_io;
1009
1010         if (endio) {
1011                 r = endio(tio->ti, bio, error);
1012                 if (r < 0 || r == DM_ENDIO_REQUEUE)
1013                         /*
1014                          * error and requeue request are handled
1015                          * in dec_pending().
1016                          */
1017                         error = r;
1018                 else if (r == DM_ENDIO_INCOMPLETE)
1019                         /* The target will handle the io */
1020                         return;
1021                 else if (r) {
1022                         DMWARN("unimplemented target endio return value: %d", r);
1023                         BUG();
1024                 }
1025         }
1026
1027         if (unlikely(r == -EREMOTEIO && (bio->bi_rw & REQ_WRITE_SAME) &&
1028                      !bdev_get_queue(bio->bi_bdev)->limits.max_write_same_sectors))
1029                 disable_write_same(md);
1030
1031         free_tio(md, tio);
1032         dec_pending(io, error);
1033 }
1034
1035 /*
1036  * Partial completion handling for request-based dm
1037  */
1038 static void end_clone_bio(struct bio *clone)
1039 {
1040         struct dm_rq_clone_bio_info *info =
1041                 container_of(clone, struct dm_rq_clone_bio_info, clone);
1042         struct dm_rq_target_io *tio = info->tio;
1043         struct bio *bio = info->orig;
1044         unsigned int nr_bytes = info->orig->bi_iter.bi_size;
1045         int error = clone->bi_error;
1046
1047         bio_put(clone);
1048
1049         if (tio->error)
1050                 /*
1051                  * An error has already been detected on the request.
1052                  * Once error occurred, just let clone->end_io() handle
1053                  * the remainder.
1054                  */
1055                 return;
1056         else if (error) {
1057                 /*
1058                  * Don't notice the error to the upper layer yet.
1059                  * The error handling decision is made by the target driver,
1060                  * when the request is completed.
1061                  */
1062                 tio->error = error;
1063                 return;
1064         }
1065
1066         /*
1067          * I/O for the bio successfully completed.
1068          * Notice the data completion to the upper layer.
1069          */
1070
1071         /*
1072          * bios are processed from the head of the list.
1073          * So the completing bio should always be rq->bio.
1074          * If it's not, something wrong is happening.
1075          */
1076         if (tio->orig->bio != bio)
1077                 DMERR("bio completion is going in the middle of the request");
1078
1079         /*
1080          * Update the original request.
1081          * Do not use blk_end_request() here, because it may complete
1082          * the original request before the clone, and break the ordering.
1083          */
1084         blk_update_request(tio->orig, 0, nr_bytes);
1085 }
1086
1087 static struct dm_rq_target_io *tio_from_request(struct request *rq)
1088 {
1089         return (rq->q->mq_ops ? blk_mq_rq_to_pdu(rq) : rq->special);
1090 }
1091
1092 static void rq_end_stats(struct mapped_device *md, struct request *orig)
1093 {
1094         if (unlikely(dm_stats_used(&md->stats))) {
1095                 struct dm_rq_target_io *tio = tio_from_request(orig);
1096                 tio->duration_jiffies = jiffies - tio->duration_jiffies;
1097                 dm_stats_account_io(&md->stats, orig->cmd_flags, blk_rq_pos(orig),
1098                                     tio->n_sectors, true, tio->duration_jiffies,
1099                                     &tio->stats_aux);
1100         }
1101 }
1102
1103 /*
1104  * Don't touch any member of the md after calling this function because
1105  * the md may be freed in dm_put() at the end of this function.
1106  * Or do dm_get() before calling this function and dm_put() later.
1107  */
1108 static void rq_completed(struct mapped_device *md, int rw, bool run_queue)
1109 {
1110         atomic_dec(&md->pending[rw]);
1111
1112         /* nudge anyone waiting on suspend queue */
1113         if (!md_in_flight(md))
1114                 wake_up(&md->wait);
1115
1116         /*
1117          * Run this off this callpath, as drivers could invoke end_io while
1118          * inside their request_fn (and holding the queue lock). Calling
1119          * back into ->request_fn() could deadlock attempting to grab the
1120          * queue lock again.
1121          */
1122         if (!md->queue->mq_ops && run_queue)
1123                 blk_run_queue_async(md->queue);
1124
1125         /*
1126          * dm_put() must be at the end of this function. See the comment above
1127          */
1128         dm_put(md);
1129 }
1130
1131 static void free_rq_clone(struct request *clone)
1132 {
1133         struct dm_rq_target_io *tio = clone->end_io_data;
1134         struct mapped_device *md = tio->md;
1135
1136         blk_rq_unprep_clone(clone);
1137
1138         if (md->type == DM_TYPE_MQ_REQUEST_BASED)
1139                 /* stacked on blk-mq queue(s) */
1140                 tio->ti->type->release_clone_rq(clone);
1141         else if (!md->queue->mq_ops)
1142                 /* request_fn queue stacked on request_fn queue(s) */
1143                 free_clone_request(md, clone);
1144         /*
1145          * NOTE: for the blk-mq queue stacked on request_fn queue(s) case:
1146          * no need to call free_clone_request() because we leverage blk-mq by
1147          * allocating the clone at the end of the blk-mq pdu (see: clone_rq)
1148          */
1149
1150         if (!md->queue->mq_ops)
1151                 free_rq_tio(tio);
1152 }
1153
1154 /*
1155  * Complete the clone and the original request.
1156  * Must be called without clone's queue lock held,
1157  * see end_clone_request() for more details.
1158  */
1159 static void dm_end_request(struct request *clone, int error)
1160 {
1161         int rw = rq_data_dir(clone);
1162         struct dm_rq_target_io *tio = clone->end_io_data;
1163         struct mapped_device *md = tio->md;
1164         struct request *rq = tio->orig;
1165
1166         if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
1167                 rq->errors = clone->errors;
1168                 rq->resid_len = clone->resid_len;
1169
1170                 if (rq->sense)
1171                         /*
1172                          * We are using the sense buffer of the original
1173                          * request.
1174                          * So setting the length of the sense data is enough.
1175                          */
1176                         rq->sense_len = clone->sense_len;
1177         }
1178
1179         free_rq_clone(clone);
1180         rq_end_stats(md, rq);
1181         if (!rq->q->mq_ops)
1182                 blk_end_request_all(rq, error);
1183         else
1184                 blk_mq_end_request(rq, error);
1185         rq_completed(md, rw, true);
1186 }
1187
1188 static void dm_unprep_request(struct request *rq)
1189 {
1190         struct dm_rq_target_io *tio = tio_from_request(rq);
1191         struct request *clone = tio->clone;
1192
1193         if (!rq->q->mq_ops) {
1194                 rq->special = NULL;
1195                 rq->cmd_flags &= ~REQ_DONTPREP;
1196         }
1197
1198         if (clone)
1199                 free_rq_clone(clone);
1200         else if (!tio->md->queue->mq_ops)
1201                 free_rq_tio(tio);
1202 }
1203
1204 /*
1205  * Requeue the original request of a clone.
1206  */
1207 static void old_requeue_request(struct request *rq)
1208 {
1209         struct request_queue *q = rq->q;
1210         unsigned long flags;
1211
1212         spin_lock_irqsave(q->queue_lock, flags);
1213         blk_requeue_request(q, rq);
1214         blk_run_queue_async(q);
1215         spin_unlock_irqrestore(q->queue_lock, flags);
1216 }
1217
1218 static void dm_mq_requeue_request(struct request *rq)
1219 {
1220         struct request_queue *q = rq->q;
1221         unsigned long flags;
1222
1223         blk_mq_requeue_request(rq);
1224         spin_lock_irqsave(q->queue_lock, flags);
1225         if (!blk_queue_stopped(q))
1226                 blk_mq_kick_requeue_list(q);
1227         spin_unlock_irqrestore(q->queue_lock, flags);
1228 }
1229
1230 static void dm_requeue_original_request(struct mapped_device *md,
1231                                         struct request *rq)
1232 {
1233         int rw = rq_data_dir(rq);
1234
1235         dm_unprep_request(rq);
1236
1237         rq_end_stats(md, rq);
1238         if (!rq->q->mq_ops)
1239                 old_requeue_request(rq);
1240         else
1241                 dm_mq_requeue_request(rq);
1242
1243         rq_completed(md, rw, false);
1244 }
1245
1246 static void old_stop_queue(struct request_queue *q)
1247 {
1248         unsigned long flags;
1249
1250         spin_lock_irqsave(q->queue_lock, flags);
1251         if (blk_queue_stopped(q)) {
1252                 spin_unlock_irqrestore(q->queue_lock, flags);
1253                 return;
1254         }
1255
1256         blk_stop_queue(q);
1257         spin_unlock_irqrestore(q->queue_lock, flags);
1258 }
1259
1260 static void stop_queue(struct request_queue *q)
1261 {
1262         if (!q->mq_ops)
1263                 old_stop_queue(q);
1264         else
1265                 blk_mq_stop_hw_queues(q);
1266 }
1267
1268 static void old_start_queue(struct request_queue *q)
1269 {
1270         unsigned long flags;
1271
1272         spin_lock_irqsave(q->queue_lock, flags);
1273         if (blk_queue_stopped(q))
1274                 blk_start_queue(q);
1275         spin_unlock_irqrestore(q->queue_lock, flags);
1276 }
1277
1278 static void start_queue(struct request_queue *q)
1279 {
1280         if (!q->mq_ops)
1281                 old_start_queue(q);
1282         else {
1283                 blk_mq_start_stopped_hw_queues(q, true);
1284                 blk_mq_kick_requeue_list(q);
1285         }
1286 }
1287
1288 static void dm_done(struct request *clone, int error, bool mapped)
1289 {
1290         int r = error;
1291         struct dm_rq_target_io *tio = clone->end_io_data;
1292         dm_request_endio_fn rq_end_io = NULL;
1293
1294         if (tio->ti) {
1295                 rq_end_io = tio->ti->type->rq_end_io;
1296
1297                 if (mapped && rq_end_io)
1298                         r = rq_end_io(tio->ti, clone, error, &tio->info);
1299         }
1300
1301         if (unlikely(r == -EREMOTEIO && (clone->cmd_flags & REQ_WRITE_SAME) &&
1302                      !clone->q->limits.max_write_same_sectors))
1303                 disable_write_same(tio->md);
1304
1305         if (r <= 0)
1306                 /* The target wants to complete the I/O */
1307                 dm_end_request(clone, r);
1308         else if (r == DM_ENDIO_INCOMPLETE)
1309                 /* The target will handle the I/O */
1310                 return;
1311         else if (r == DM_ENDIO_REQUEUE)
1312                 /* The target wants to requeue the I/O */
1313                 dm_requeue_original_request(tio->md, tio->orig);
1314         else {
1315                 DMWARN("unimplemented target endio return value: %d", r);
1316                 BUG();
1317         }
1318 }
1319
1320 /*
1321  * Request completion handler for request-based dm
1322  */
1323 static void dm_softirq_done(struct request *rq)
1324 {
1325         bool mapped = true;
1326         struct dm_rq_target_io *tio = tio_from_request(rq);
1327         struct request *clone = tio->clone;
1328         int rw;
1329
1330         if (!clone) {
1331                 rq_end_stats(tio->md, rq);
1332                 rw = rq_data_dir(rq);
1333                 if (!rq->q->mq_ops) {
1334                         blk_end_request_all(rq, tio->error);
1335                         rq_completed(tio->md, rw, false);
1336                         free_rq_tio(tio);
1337                 } else {
1338                         blk_mq_end_request(rq, tio->error);
1339                         rq_completed(tio->md, rw, false);
1340                 }
1341                 return;
1342         }
1343
1344         if (rq->cmd_flags & REQ_FAILED)
1345                 mapped = false;
1346
1347         dm_done(clone, tio->error, mapped);
1348 }
1349
1350 /*
1351  * Complete the clone and the original request with the error status
1352  * through softirq context.
1353  */
1354 static void dm_complete_request(struct request *rq, int error)
1355 {
1356         struct dm_rq_target_io *tio = tio_from_request(rq);
1357
1358         tio->error = error;
1359         if (!rq->q->mq_ops)
1360                 blk_complete_request(rq);
1361         else
1362                 blk_mq_complete_request(rq, error);
1363 }
1364
1365 /*
1366  * Complete the not-mapped clone and the original request with the error status
1367  * through softirq context.
1368  * Target's rq_end_io() function isn't called.
1369  * This may be used when the target's map_rq() or clone_and_map_rq() functions fail.
1370  */
1371 static void dm_kill_unmapped_request(struct request *rq, int error)
1372 {
1373         rq->cmd_flags |= REQ_FAILED;
1374         dm_complete_request(rq, error);
1375 }
1376
1377 /*
1378  * Called with the clone's queue lock held (for non-blk-mq)
1379  */
1380 static void end_clone_request(struct request *clone, int error)
1381 {
1382         struct dm_rq_target_io *tio = clone->end_io_data;
1383
1384         if (!clone->q->mq_ops) {
1385                 /*
1386                  * For just cleaning up the information of the queue in which
1387                  * the clone was dispatched.
1388                  * The clone is *NOT* freed actually here because it is alloced
1389                  * from dm own mempool (REQ_ALLOCED isn't set).
1390                  */
1391                 __blk_put_request(clone->q, clone);
1392         }
1393
1394         /*
1395          * Actual request completion is done in a softirq context which doesn't
1396          * hold the clone's queue lock.  Otherwise, deadlock could occur because:
1397          *     - another request may be submitted by the upper level driver
1398          *       of the stacking during the completion
1399          *     - the submission which requires queue lock may be done
1400          *       against this clone's queue
1401          */
1402         dm_complete_request(tio->orig, error);
1403 }
1404
1405 /*
1406  * Return maximum size of I/O possible at the supplied sector up to the current
1407  * target boundary.
1408  */
1409 static sector_t max_io_len_target_boundary(sector_t sector, struct dm_target *ti)
1410 {
1411         sector_t target_offset = dm_target_offset(ti, sector);
1412
1413         return ti->len - target_offset;
1414 }
1415
1416 static sector_t max_io_len(sector_t sector, struct dm_target *ti)
1417 {
1418         sector_t len = max_io_len_target_boundary(sector, ti);
1419         sector_t offset, max_len;
1420
1421         /*
1422          * Does the target need to split even further?
1423          */
1424         if (ti->max_io_len) {
1425                 offset = dm_target_offset(ti, sector);
1426                 if (unlikely(ti->max_io_len & (ti->max_io_len - 1)))
1427                         max_len = sector_div(offset, ti->max_io_len);
1428                 else
1429                         max_len = offset & (ti->max_io_len - 1);
1430                 max_len = ti->max_io_len - max_len;
1431
1432                 if (len > max_len)
1433                         len = max_len;
1434         }
1435
1436         return len;
1437 }
1438
1439 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
1440 {
1441         if (len > UINT_MAX) {
1442                 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
1443                       (unsigned long long)len, UINT_MAX);
1444                 ti->error = "Maximum size of target IO is too large";
1445                 return -EINVAL;
1446         }
1447
1448         ti->max_io_len = (uint32_t) len;
1449
1450         return 0;
1451 }
1452 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
1453
1454 /*
1455  * A target may call dm_accept_partial_bio only from the map routine.  It is
1456  * allowed for all bio types except REQ_FLUSH.
1457  *
1458  * dm_accept_partial_bio informs the dm that the target only wants to process
1459  * additional n_sectors sectors of the bio and the rest of the data should be
1460  * sent in a next bio.
1461  *
1462  * A diagram that explains the arithmetics:
1463  * +--------------------+---------------+-------+
1464  * |         1          |       2       |   3   |
1465  * +--------------------+---------------+-------+
1466  *
1467  * <-------------- *tio->len_ptr --------------->
1468  *                      <------- bi_size ------->
1469  *                      <-- n_sectors -->
1470  *
1471  * Region 1 was already iterated over with bio_advance or similar function.
1472  *      (it may be empty if the target doesn't use bio_advance)
1473  * Region 2 is the remaining bio size that the target wants to process.
1474  *      (it may be empty if region 1 is non-empty, although there is no reason
1475  *       to make it empty)
1476  * The target requires that region 3 is to be sent in the next bio.
1477  *
1478  * If the target wants to receive multiple copies of the bio (via num_*bios, etc),
1479  * the partially processed part (the sum of regions 1+2) must be the same for all
1480  * copies of the bio.
1481  */
1482 void dm_accept_partial_bio(struct bio *bio, unsigned n_sectors)
1483 {
1484         struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
1485         unsigned bi_size = bio->bi_iter.bi_size >> SECTOR_SHIFT;
1486         BUG_ON(bio->bi_rw & REQ_FLUSH);
1487         BUG_ON(bi_size > *tio->len_ptr);
1488         BUG_ON(n_sectors > bi_size);
1489         *tio->len_ptr -= bi_size - n_sectors;
1490         bio->bi_iter.bi_size = n_sectors << SECTOR_SHIFT;
1491 }
1492 EXPORT_SYMBOL_GPL(dm_accept_partial_bio);
1493
1494 static void __map_bio(struct dm_target_io *tio)
1495 {
1496         int r;
1497         sector_t sector;
1498         struct mapped_device *md;
1499         struct bio *clone = &tio->clone;
1500         struct dm_target *ti = tio->ti;
1501
1502         clone->bi_end_io = clone_endio;
1503
1504         /*
1505          * Map the clone.  If r == 0 we don't need to do
1506          * anything, the target has assumed ownership of
1507          * this io.
1508          */
1509         atomic_inc(&tio->io->io_count);
1510         sector = clone->bi_iter.bi_sector;
1511         r = ti->type->map(ti, clone);
1512         if (r == DM_MAPIO_REMAPPED) {
1513                 /* the bio has been remapped so dispatch it */
1514
1515                 trace_block_bio_remap(bdev_get_queue(clone->bi_bdev), clone,
1516                                       tio->io->bio->bi_bdev->bd_dev, sector);
1517
1518                 generic_make_request(clone);
1519         } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1520                 /* error the io and bail out, or requeue it if needed */
1521                 md = tio->io->md;
1522                 dec_pending(tio->io, r);
1523                 free_tio(md, tio);
1524         } else if (r != DM_MAPIO_SUBMITTED) {
1525                 DMWARN("unimplemented target map return value: %d", r);
1526                 BUG();
1527         }
1528 }
1529
1530 struct clone_info {
1531         struct mapped_device *md;
1532         struct dm_table *map;
1533         struct bio *bio;
1534         struct dm_io *io;
1535         sector_t sector;
1536         unsigned sector_count;
1537 };
1538
1539 static void bio_setup_sector(struct bio *bio, sector_t sector, unsigned len)
1540 {
1541         bio->bi_iter.bi_sector = sector;
1542         bio->bi_iter.bi_size = to_bytes(len);
1543 }
1544
1545 /*
1546  * Creates a bio that consists of range of complete bvecs.
1547  */
1548 static void clone_bio(struct dm_target_io *tio, struct bio *bio,
1549                       sector_t sector, unsigned len)
1550 {
1551         struct bio *clone = &tio->clone;
1552
1553         __bio_clone_fast(clone, bio);
1554
1555         if (bio_integrity(bio))
1556                 bio_integrity_clone(clone, bio, GFP_NOIO);
1557
1558         bio_advance(clone, to_bytes(sector - clone->bi_iter.bi_sector));
1559         clone->bi_iter.bi_size = to_bytes(len);
1560
1561         if (bio_integrity(bio))
1562                 bio_integrity_trim(clone, 0, len);
1563 }
1564
1565 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1566                                       struct dm_target *ti,
1567                                       unsigned target_bio_nr)
1568 {
1569         struct dm_target_io *tio;
1570         struct bio *clone;
1571
1572         clone = bio_alloc_bioset(GFP_NOIO, 0, ci->md->bs);
1573         tio = container_of(clone, struct dm_target_io, clone);
1574
1575         tio->io = ci->io;
1576         tio->ti = ti;
1577         tio->target_bio_nr = target_bio_nr;
1578
1579         return tio;
1580 }
1581
1582 static void __clone_and_map_simple_bio(struct clone_info *ci,
1583                                        struct dm_target *ti,
1584                                        unsigned target_bio_nr, unsigned *len)
1585 {
1586         struct dm_target_io *tio = alloc_tio(ci, ti, target_bio_nr);
1587         struct bio *clone = &tio->clone;
1588
1589         tio->len_ptr = len;
1590
1591         __bio_clone_fast(clone, ci->bio);
1592         if (len)
1593                 bio_setup_sector(clone, ci->sector, *len);
1594
1595         __map_bio(tio);
1596 }
1597
1598 static void __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1599                                   unsigned num_bios, unsigned *len)
1600 {
1601         unsigned target_bio_nr;
1602
1603         for (target_bio_nr = 0; target_bio_nr < num_bios; target_bio_nr++)
1604                 __clone_and_map_simple_bio(ci, ti, target_bio_nr, len);
1605 }
1606
1607 static int __send_empty_flush(struct clone_info *ci)
1608 {
1609         unsigned target_nr = 0;
1610         struct dm_target *ti;
1611
1612         BUG_ON(bio_has_data(ci->bio));
1613         while ((ti = dm_table_get_target(ci->map, target_nr++)))
1614                 __send_duplicate_bios(ci, ti, ti->num_flush_bios, NULL);
1615
1616         return 0;
1617 }
1618
1619 static void __clone_and_map_data_bio(struct clone_info *ci, struct dm_target *ti,
1620                                      sector_t sector, unsigned *len)
1621 {
1622         struct bio *bio = ci->bio;
1623         struct dm_target_io *tio;
1624         unsigned target_bio_nr;
1625         unsigned num_target_bios = 1;
1626
1627         /*
1628          * Does the target want to receive duplicate copies of the bio?
1629          */
1630         if (bio_data_dir(bio) == WRITE && ti->num_write_bios)
1631                 num_target_bios = ti->num_write_bios(ti, bio);
1632
1633         for (target_bio_nr = 0; target_bio_nr < num_target_bios; target_bio_nr++) {
1634                 tio = alloc_tio(ci, ti, target_bio_nr);
1635                 tio->len_ptr = len;
1636                 clone_bio(tio, bio, sector, *len);
1637                 __map_bio(tio);
1638         }
1639 }
1640
1641 typedef unsigned (*get_num_bios_fn)(struct dm_target *ti);
1642
1643 static unsigned get_num_discard_bios(struct dm_target *ti)
1644 {
1645         return ti->num_discard_bios;
1646 }
1647
1648 static unsigned get_num_write_same_bios(struct dm_target *ti)
1649 {
1650         return ti->num_write_same_bios;
1651 }
1652
1653 typedef bool (*is_split_required_fn)(struct dm_target *ti);
1654
1655 static bool is_split_required_for_discard(struct dm_target *ti)
1656 {
1657         return ti->split_discard_bios;
1658 }
1659
1660 static int __send_changing_extent_only(struct clone_info *ci,
1661                                        get_num_bios_fn get_num_bios,
1662                                        is_split_required_fn is_split_required)
1663 {
1664         struct dm_target *ti;
1665         unsigned len;
1666         unsigned num_bios;
1667
1668         do {
1669                 ti = dm_table_find_target(ci->map, ci->sector);
1670                 if (!dm_target_is_valid(ti))
1671                         return -EIO;
1672
1673                 /*
1674                  * Even though the device advertised support for this type of
1675                  * request, that does not mean every target supports it, and
1676                  * reconfiguration might also have changed that since the
1677                  * check was performed.
1678                  */
1679                 num_bios = get_num_bios ? get_num_bios(ti) : 0;
1680                 if (!num_bios)
1681                         return -EOPNOTSUPP;
1682
1683                 if (is_split_required && !is_split_required(ti))
1684                         len = min((sector_t)ci->sector_count, max_io_len_target_boundary(ci->sector, ti));
1685                 else
1686                         len = min((sector_t)ci->sector_count, max_io_len(ci->sector, ti));
1687
1688                 __send_duplicate_bios(ci, ti, num_bios, &len);
1689
1690                 ci->sector += len;
1691         } while (ci->sector_count -= len);
1692
1693         return 0;
1694 }
1695
1696 static int __send_discard(struct clone_info *ci)
1697 {
1698         return __send_changing_extent_only(ci, get_num_discard_bios,
1699                                            is_split_required_for_discard);
1700 }
1701
1702 static int __send_write_same(struct clone_info *ci)
1703 {
1704         return __send_changing_extent_only(ci, get_num_write_same_bios, NULL);
1705 }
1706
1707 /*
1708  * Select the correct strategy for processing a non-flush bio.
1709  */
1710 static int __split_and_process_non_flush(struct clone_info *ci)
1711 {
1712         struct bio *bio = ci->bio;
1713         struct dm_target *ti;
1714         unsigned len;
1715
1716         if (unlikely(bio->bi_rw & REQ_DISCARD))
1717                 return __send_discard(ci);
1718         else if (unlikely(bio->bi_rw & REQ_WRITE_SAME))
1719                 return __send_write_same(ci);
1720
1721         ti = dm_table_find_target(ci->map, ci->sector);
1722         if (!dm_target_is_valid(ti))
1723                 return -EIO;
1724
1725         len = min_t(sector_t, max_io_len(ci->sector, ti), ci->sector_count);
1726
1727         __clone_and_map_data_bio(ci, ti, ci->sector, &len);
1728
1729         ci->sector += len;
1730         ci->sector_count -= len;
1731
1732         return 0;
1733 }
1734
1735 /*
1736  * Entry point to split a bio into clones and submit them to the targets.
1737  */
1738 static void __split_and_process_bio(struct mapped_device *md,
1739                                     struct dm_table *map, struct bio *bio)
1740 {
1741         struct clone_info ci;
1742         int error = 0;
1743
1744         if (unlikely(!map)) {
1745                 bio_io_error(bio);
1746                 return;
1747         }
1748
1749         ci.map = map;
1750         ci.md = md;
1751         ci.io = alloc_io(md);
1752         ci.io->error = 0;
1753         atomic_set(&ci.io->io_count, 1);
1754         ci.io->bio = bio;
1755         ci.io->md = md;
1756         spin_lock_init(&ci.io->endio_lock);
1757         ci.sector = bio->bi_iter.bi_sector;
1758
1759         start_io_acct(ci.io);
1760
1761         if (bio->bi_rw & REQ_FLUSH) {
1762                 ci.bio = &ci.md->flush_bio;
1763                 ci.sector_count = 0;
1764                 error = __send_empty_flush(&ci);
1765                 /* dec_pending submits any data associated with flush */
1766         } else {
1767                 ci.bio = bio;
1768                 ci.sector_count = bio_sectors(bio);
1769                 while (ci.sector_count && !error)
1770                         error = __split_and_process_non_flush(&ci);
1771         }
1772
1773         /* drop the extra reference count */
1774         dec_pending(ci.io, error);
1775 }
1776 /*-----------------------------------------------------------------
1777  * CRUD END
1778  *---------------------------------------------------------------*/
1779
1780 /*
1781  * The request function that just remaps the bio built up by
1782  * dm_merge_bvec.
1783  */
1784 static blk_qc_t dm_make_request(struct request_queue *q, struct bio *bio)
1785 {
1786         int rw = bio_data_dir(bio);
1787         struct mapped_device *md = q->queuedata;
1788         int srcu_idx;
1789         struct dm_table *map;
1790
1791         map = dm_get_live_table(md, &srcu_idx);
1792
1793         generic_start_io_acct(rw, bio_sectors(bio), &dm_disk(md)->part0);
1794
1795         /* if we're suspended, we have to queue this io for later */
1796         if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
1797                 dm_put_live_table(md, srcu_idx);
1798
1799                 if (bio_rw(bio) != READA)
1800                         queue_io(md, bio);
1801                 else
1802                         bio_io_error(bio);
1803                 return BLK_QC_T_NONE;
1804         }
1805
1806         __split_and_process_bio(md, map, bio);
1807         dm_put_live_table(md, srcu_idx);
1808         return BLK_QC_T_NONE;
1809 }
1810
1811 int dm_request_based(struct mapped_device *md)
1812 {
1813         return blk_queue_stackable(md->queue);
1814 }
1815
1816 static void dm_dispatch_clone_request(struct request *clone, struct request *rq)
1817 {
1818         int r;
1819
1820         if (blk_queue_io_stat(clone->q))
1821                 clone->cmd_flags |= REQ_IO_STAT;
1822
1823         clone->start_time = jiffies;
1824         r = blk_insert_cloned_request(clone->q, clone);
1825         if (r)
1826                 /* must complete clone in terms of original request */
1827                 dm_complete_request(rq, r);
1828 }
1829
1830 static int dm_rq_bio_constructor(struct bio *bio, struct bio *bio_orig,
1831                                  void *data)
1832 {
1833         struct dm_rq_target_io *tio = data;
1834         struct dm_rq_clone_bio_info *info =
1835                 container_of(bio, struct dm_rq_clone_bio_info, clone);
1836
1837         info->orig = bio_orig;
1838         info->tio = tio;
1839         bio->bi_end_io = end_clone_bio;
1840
1841         return 0;
1842 }
1843
1844 static int setup_clone(struct request *clone, struct request *rq,
1845                        struct dm_rq_target_io *tio, gfp_t gfp_mask)
1846 {
1847         int r;
1848
1849         r = blk_rq_prep_clone(clone, rq, tio->md->bs, gfp_mask,
1850                               dm_rq_bio_constructor, tio);
1851         if (r)
1852                 return r;
1853
1854         clone->cmd = rq->cmd;
1855         clone->cmd_len = rq->cmd_len;
1856         clone->sense = rq->sense;
1857         clone->end_io = end_clone_request;
1858         clone->end_io_data = tio;
1859
1860         tio->clone = clone;
1861
1862         return 0;
1863 }
1864
1865 static struct request *clone_rq(struct request *rq, struct mapped_device *md,
1866                                 struct dm_rq_target_io *tio, gfp_t gfp_mask)
1867 {
1868         /*
1869          * Do not allocate a clone if tio->clone was already set
1870          * (see: dm_mq_queue_rq).
1871          */
1872         bool alloc_clone = !tio->clone;
1873         struct request *clone;
1874
1875         if (alloc_clone) {
1876                 clone = alloc_clone_request(md, gfp_mask);
1877                 if (!clone)
1878                         return NULL;
1879         } else
1880                 clone = tio->clone;
1881
1882         blk_rq_init(NULL, clone);
1883         if (setup_clone(clone, rq, tio, gfp_mask)) {
1884                 /* -ENOMEM */
1885                 if (alloc_clone)
1886                         free_clone_request(md, clone);
1887                 return NULL;
1888         }
1889
1890         return clone;
1891 }
1892
1893 static void map_tio_request(struct kthread_work *work);
1894
1895 static void init_tio(struct dm_rq_target_io *tio, struct request *rq,
1896                      struct mapped_device *md)
1897 {
1898         tio->md = md;
1899         tio->ti = NULL;
1900         tio->clone = NULL;
1901         tio->orig = rq;
1902         tio->error = 0;
1903         memset(&tio->info, 0, sizeof(tio->info));
1904         if (md->kworker_task)
1905                 init_kthread_work(&tio->work, map_tio_request);
1906 }
1907
1908 static struct dm_rq_target_io *prep_tio(struct request *rq,
1909                                         struct mapped_device *md, gfp_t gfp_mask)
1910 {
1911         struct dm_rq_target_io *tio;
1912         int srcu_idx;
1913         struct dm_table *table;
1914
1915         tio = alloc_rq_tio(md, gfp_mask);
1916         if (!tio)
1917                 return NULL;
1918
1919         init_tio(tio, rq, md);
1920
1921         table = dm_get_live_table(md, &srcu_idx);
1922         if (!dm_table_mq_request_based(table)) {
1923                 if (!clone_rq(rq, md, tio, gfp_mask)) {
1924                         dm_put_live_table(md, srcu_idx);
1925                         free_rq_tio(tio);
1926                         return NULL;
1927                 }
1928         }
1929         dm_put_live_table(md, srcu_idx);
1930
1931         return tio;
1932 }
1933
1934 /*
1935  * Called with the queue lock held.
1936  */
1937 static int dm_prep_fn(struct request_queue *q, struct request *rq)
1938 {
1939         struct mapped_device *md = q->queuedata;
1940         struct dm_rq_target_io *tio;
1941
1942         if (unlikely(rq->special)) {
1943                 DMWARN("Already has something in rq->special.");
1944                 return BLKPREP_KILL;
1945         }
1946
1947         tio = prep_tio(rq, md, GFP_ATOMIC);
1948         if (!tio)
1949                 return BLKPREP_DEFER;
1950
1951         rq->special = tio;
1952         rq->cmd_flags |= REQ_DONTPREP;
1953
1954         return BLKPREP_OK;
1955 }
1956
1957 /*
1958  * Returns:
1959  * 0                : the request has been processed
1960  * DM_MAPIO_REQUEUE : the original request needs to be requeued
1961  * < 0              : the request was completed due to failure
1962  */
1963 static int map_request(struct dm_rq_target_io *tio, struct request *rq,
1964                        struct mapped_device *md)
1965 {
1966         int r;
1967         struct dm_target *ti = tio->ti;
1968         struct request *clone = NULL;
1969
1970         if (tio->clone) {
1971                 clone = tio->clone;
1972                 r = ti->type->map_rq(ti, clone, &tio->info);
1973         } else {
1974                 r = ti->type->clone_and_map_rq(ti, rq, &tio->info, &clone);
1975                 if (r < 0) {
1976                         /* The target wants to complete the I/O */
1977                         dm_kill_unmapped_request(rq, r);
1978                         return r;
1979                 }
1980                 if (r != DM_MAPIO_REMAPPED)
1981                         return r;
1982                 if (setup_clone(clone, rq, tio, GFP_ATOMIC)) {
1983                         /* -ENOMEM */
1984                         ti->type->release_clone_rq(clone);
1985                         return DM_MAPIO_REQUEUE;
1986                 }
1987         }
1988
1989         switch (r) {
1990         case DM_MAPIO_SUBMITTED:
1991                 /* The target has taken the I/O to submit by itself later */
1992                 break;
1993         case DM_MAPIO_REMAPPED:
1994                 /* The target has remapped the I/O so dispatch it */
1995                 trace_block_rq_remap(clone->q, clone, disk_devt(dm_disk(md)),
1996                                      blk_rq_pos(rq));
1997                 dm_dispatch_clone_request(clone, rq);
1998                 break;
1999         case DM_MAPIO_REQUEUE:
2000                 /* The target wants to requeue the I/O */
2001                 dm_requeue_original_request(md, tio->orig);
2002                 break;
2003         default:
2004                 if (r > 0) {
2005                         DMWARN("unimplemented target map return value: %d", r);
2006                         BUG();
2007                 }
2008
2009                 /* The target wants to complete the I/O */
2010                 dm_kill_unmapped_request(rq, r);
2011                 return r;
2012         }
2013
2014         return 0;
2015 }
2016
2017 static void map_tio_request(struct kthread_work *work)
2018 {
2019         struct dm_rq_target_io *tio = container_of(work, struct dm_rq_target_io, work);
2020         struct request *rq = tio->orig;
2021         struct mapped_device *md = tio->md;
2022
2023         if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE)
2024                 dm_requeue_original_request(md, rq);
2025 }
2026
2027 static void dm_start_request(struct mapped_device *md, struct request *orig)
2028 {
2029         if (!orig->q->mq_ops)
2030                 blk_start_request(orig);
2031         else
2032                 blk_mq_start_request(orig);
2033         atomic_inc(&md->pending[rq_data_dir(orig)]);
2034
2035         if (md->seq_rq_merge_deadline_usecs) {
2036                 md->last_rq_pos = rq_end_sector(orig);
2037                 md->last_rq_rw = rq_data_dir(orig);
2038                 md->last_rq_start_time = ktime_get();
2039         }
2040
2041         if (unlikely(dm_stats_used(&md->stats))) {
2042                 struct dm_rq_target_io *tio = tio_from_request(orig);
2043                 tio->duration_jiffies = jiffies;
2044                 tio->n_sectors = blk_rq_sectors(orig);
2045                 dm_stats_account_io(&md->stats, orig->cmd_flags, blk_rq_pos(orig),
2046                                     tio->n_sectors, false, 0, &tio->stats_aux);
2047         }
2048
2049         /*
2050          * Hold the md reference here for the in-flight I/O.
2051          * We can't rely on the reference count by device opener,
2052          * because the device may be closed during the request completion
2053          * when all bios are completed.
2054          * See the comment in rq_completed() too.
2055          */
2056         dm_get(md);
2057 }
2058
2059 #define MAX_SEQ_RQ_MERGE_DEADLINE_USECS 100000
2060
2061 ssize_t dm_attr_rq_based_seq_io_merge_deadline_show(struct mapped_device *md, char *buf)
2062 {
2063         return sprintf(buf, "%u\n", md->seq_rq_merge_deadline_usecs);
2064 }
2065
2066 ssize_t dm_attr_rq_based_seq_io_merge_deadline_store(struct mapped_device *md,
2067                                                      const char *buf, size_t count)
2068 {
2069         unsigned deadline;
2070
2071         if (!dm_request_based(md) || md->use_blk_mq)
2072                 return count;
2073
2074         if (kstrtouint(buf, 10, &deadline))
2075                 return -EINVAL;
2076
2077         if (deadline > MAX_SEQ_RQ_MERGE_DEADLINE_USECS)
2078                 deadline = MAX_SEQ_RQ_MERGE_DEADLINE_USECS;
2079
2080         md->seq_rq_merge_deadline_usecs = deadline;
2081
2082         return count;
2083 }
2084
2085 static bool dm_request_peeked_before_merge_deadline(struct mapped_device *md)
2086 {
2087         ktime_t kt_deadline;
2088
2089         if (!md->seq_rq_merge_deadline_usecs)
2090                 return false;
2091
2092         kt_deadline = ns_to_ktime((u64)md->seq_rq_merge_deadline_usecs * NSEC_PER_USEC);
2093         kt_deadline = ktime_add_safe(md->last_rq_start_time, kt_deadline);
2094
2095         return !ktime_after(ktime_get(), kt_deadline);
2096 }
2097
2098 /*
2099  * q->request_fn for request-based dm.
2100  * Called with the queue lock held.
2101  */
2102 static void dm_request_fn(struct request_queue *q)
2103 {
2104         struct mapped_device *md = q->queuedata;
2105         struct dm_target *ti = md->immutable_target;
2106         struct request *rq;
2107         struct dm_rq_target_io *tio;
2108         sector_t pos = 0;
2109
2110         if (unlikely(!ti)) {
2111                 int srcu_idx;
2112                 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2113
2114                 ti = dm_table_find_target(map, pos);
2115                 dm_put_live_table(md, srcu_idx);
2116         }
2117
2118         /*
2119          * For suspend, check blk_queue_stopped() and increment
2120          * ->pending within a single queue_lock not to increment the
2121          * number of in-flight I/Os after the queue is stopped in
2122          * dm_suspend().
2123          */
2124         while (!blk_queue_stopped(q)) {
2125                 rq = blk_peek_request(q);
2126                 if (!rq)
2127                         return;
2128
2129                 /* always use block 0 to find the target for flushes for now */
2130                 pos = 0;
2131                 if (!(rq->cmd_flags & REQ_FLUSH))
2132                         pos = blk_rq_pos(rq);
2133
2134                 if ((dm_request_peeked_before_merge_deadline(md) &&
2135                      md_in_flight(md) && rq->bio && rq->bio->bi_vcnt == 1 &&
2136                      md->last_rq_pos == pos && md->last_rq_rw == rq_data_dir(rq)) ||
2137                     (ti->type->busy && ti->type->busy(ti))) {
2138                         blk_delay_queue(q, HZ / 100);
2139                         return;
2140                 }
2141
2142                 dm_start_request(md, rq);
2143
2144                 tio = tio_from_request(rq);
2145                 /* Establish tio->ti before queuing work (map_tio_request) */
2146                 tio->ti = ti;
2147                 queue_kthread_work(&md->kworker, &tio->work);
2148                 BUG_ON(!irqs_disabled());
2149         }
2150 }
2151
2152 static int dm_any_congested(void *congested_data, int bdi_bits)
2153 {
2154         int r = bdi_bits;
2155         struct mapped_device *md = congested_data;
2156         struct dm_table *map;
2157
2158         if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2159                 if (dm_request_based(md)) {
2160                         /*
2161                          * With request-based DM we only need to check the
2162                          * top-level queue for congestion.
2163                          */
2164                         r = md->queue->backing_dev_info.wb.state & bdi_bits;
2165                 } else {
2166                         map = dm_get_live_table_fast(md);
2167                         if (map)
2168                                 r = dm_table_any_congested(map, bdi_bits);
2169                         dm_put_live_table_fast(md);
2170                 }
2171         }
2172
2173         return r;
2174 }
2175
2176 /*-----------------------------------------------------------------
2177  * An IDR is used to keep track of allocated minor numbers.
2178  *---------------------------------------------------------------*/
2179 static void free_minor(int minor)
2180 {
2181         spin_lock(&_minor_lock);
2182         idr_remove(&_minor_idr, minor);
2183         spin_unlock(&_minor_lock);
2184 }
2185
2186 /*
2187  * See if the device with a specific minor # is free.
2188  */
2189 static int specific_minor(int minor)
2190 {
2191         int r;
2192
2193         if (minor >= (1 << MINORBITS))
2194                 return -EINVAL;
2195
2196         idr_preload(GFP_KERNEL);
2197         spin_lock(&_minor_lock);
2198
2199         r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
2200
2201         spin_unlock(&_minor_lock);
2202         idr_preload_end();
2203         if (r < 0)
2204                 return r == -ENOSPC ? -EBUSY : r;
2205         return 0;
2206 }
2207
2208 static int next_free_minor(int *minor)
2209 {
2210         int r;
2211
2212         idr_preload(GFP_KERNEL);
2213         spin_lock(&_minor_lock);
2214
2215         r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
2216
2217         spin_unlock(&_minor_lock);
2218         idr_preload_end();
2219         if (r < 0)
2220                 return r;
2221         *minor = r;
2222         return 0;
2223 }
2224
2225 static const struct block_device_operations dm_blk_dops;
2226
2227 static void dm_wq_work(struct work_struct *work);
2228
2229 static void dm_init_md_queue(struct mapped_device *md)
2230 {
2231         /*
2232          * Request-based dm devices cannot be stacked on top of bio-based dm
2233          * devices.  The type of this dm device may not have been decided yet.
2234          * The type is decided at the first table loading time.
2235          * To prevent problematic device stacking, clear the queue flag
2236          * for request stacking support until then.
2237          *
2238          * This queue is new, so no concurrency on the queue_flags.
2239          */
2240         queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
2241
2242         /*
2243          * Initialize data that will only be used by a non-blk-mq DM queue
2244          * - must do so here (in alloc_dev callchain) before queue is used
2245          */
2246         md->queue->queuedata = md;
2247         md->queue->backing_dev_info.congested_data = md;
2248 }
2249
2250 static void dm_init_old_md_queue(struct mapped_device *md)
2251 {
2252         md->use_blk_mq = false;
2253         dm_init_md_queue(md);
2254
2255         /*
2256          * Initialize aspects of queue that aren't relevant for blk-mq
2257          */
2258         md->queue->backing_dev_info.congested_fn = dm_any_congested;
2259         blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
2260 }
2261
2262 static void cleanup_mapped_device(struct mapped_device *md)
2263 {
2264         if (md->wq)
2265                 destroy_workqueue(md->wq);
2266         if (md->kworker_task)
2267                 kthread_stop(md->kworker_task);
2268         mempool_destroy(md->io_pool);
2269         mempool_destroy(md->rq_pool);
2270         if (md->bs)
2271                 bioset_free(md->bs);
2272
2273         cleanup_srcu_struct(&md->io_barrier);
2274
2275         if (md->disk) {
2276                 spin_lock(&_minor_lock);
2277                 md->disk->private_data = NULL;
2278                 spin_unlock(&_minor_lock);
2279                 del_gendisk(md->disk);
2280                 put_disk(md->disk);
2281         }
2282
2283         if (md->queue)
2284                 blk_cleanup_queue(md->queue);
2285
2286         if (md->bdev) {
2287                 bdput(md->bdev);
2288                 md->bdev = NULL;
2289         }
2290 }
2291
2292 /*
2293  * Allocate and initialise a blank device with a given minor.
2294  */
2295 static struct mapped_device *alloc_dev(int minor)
2296 {
2297         int r;
2298         struct mapped_device *md = kzalloc(sizeof(*md), GFP_KERNEL);
2299         void *old_md;
2300
2301         if (!md) {
2302                 DMWARN("unable to allocate device, out of memory.");
2303                 return NULL;
2304         }
2305
2306         if (!try_module_get(THIS_MODULE))
2307                 goto bad_module_get;
2308
2309         /* get a minor number for the dev */
2310         if (minor == DM_ANY_MINOR)
2311                 r = next_free_minor(&minor);
2312         else
2313                 r = specific_minor(minor);
2314         if (r < 0)
2315                 goto bad_minor;
2316
2317         r = init_srcu_struct(&md->io_barrier);
2318         if (r < 0)
2319                 goto bad_io_barrier;
2320
2321         md->use_blk_mq = use_blk_mq;
2322         md->type = DM_TYPE_NONE;
2323         mutex_init(&md->suspend_lock);
2324         mutex_init(&md->type_lock);
2325         mutex_init(&md->table_devices_lock);
2326         spin_lock_init(&md->deferred_lock);
2327         atomic_set(&md->holders, 1);
2328         atomic_set(&md->open_count, 0);
2329         atomic_set(&md->event_nr, 0);
2330         atomic_set(&md->uevent_seq, 0);
2331         INIT_LIST_HEAD(&md->uevent_list);
2332         INIT_LIST_HEAD(&md->table_devices);
2333         spin_lock_init(&md->uevent_lock);
2334
2335         md->queue = blk_alloc_queue(GFP_KERNEL);
2336         if (!md->queue)
2337                 goto bad;
2338
2339         dm_init_md_queue(md);
2340
2341         md->disk = alloc_disk(1);
2342         if (!md->disk)
2343                 goto bad;
2344
2345         atomic_set(&md->pending[0], 0);
2346         atomic_set(&md->pending[1], 0);
2347         init_waitqueue_head(&md->wait);
2348         INIT_WORK(&md->work, dm_wq_work);
2349         init_waitqueue_head(&md->eventq);
2350         init_completion(&md->kobj_holder.completion);
2351         md->kworker_task = NULL;
2352
2353         md->disk->major = _major;
2354         md->disk->first_minor = minor;
2355         md->disk->fops = &dm_blk_dops;
2356         md->disk->queue = md->queue;
2357         md->disk->private_data = md;
2358         sprintf(md->disk->disk_name, "dm-%d", minor);
2359         add_disk(md->disk);
2360         format_dev_t(md->name, MKDEV(_major, minor));
2361
2362         md->wq = alloc_workqueue("kdmflush", WQ_MEM_RECLAIM, 0);
2363         if (!md->wq)
2364                 goto bad;
2365
2366         md->bdev = bdget_disk(md->disk, 0);
2367         if (!md->bdev)
2368                 goto bad;
2369
2370         bio_init(&md->flush_bio);
2371         md->flush_bio.bi_bdev = md->bdev;
2372         md->flush_bio.bi_rw = WRITE_FLUSH;
2373
2374         dm_stats_init(&md->stats);
2375
2376         /* Populate the mapping, nobody knows we exist yet */
2377         spin_lock(&_minor_lock);
2378         old_md = idr_replace(&_minor_idr, md, minor);
2379         spin_unlock(&_minor_lock);
2380
2381         BUG_ON(old_md != MINOR_ALLOCED);
2382
2383         return md;
2384
2385 bad:
2386         cleanup_mapped_device(md);
2387 bad_io_barrier:
2388         free_minor(minor);
2389 bad_minor:
2390         module_put(THIS_MODULE);
2391 bad_module_get:
2392         kfree(md);
2393         return NULL;
2394 }
2395
2396 static void unlock_fs(struct mapped_device *md);
2397
2398 static void free_dev(struct mapped_device *md)
2399 {
2400         int minor = MINOR(disk_devt(md->disk));
2401
2402         unlock_fs(md);
2403
2404         cleanup_mapped_device(md);
2405         if (md->tag_set) {
2406                 blk_mq_free_tag_set(md->tag_set);
2407                 kfree(md->tag_set);
2408         }
2409
2410         free_table_devices(&md->table_devices);
2411         dm_stats_cleanup(&md->stats);
2412         free_minor(minor);
2413
2414         module_put(THIS_MODULE);
2415         kfree(md);
2416 }
2417
2418 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
2419 {
2420         struct dm_md_mempools *p = dm_table_get_md_mempools(t);
2421
2422         if (md->bs) {
2423                 /* The md already has necessary mempools. */
2424                 if (dm_table_get_type(t) == DM_TYPE_BIO_BASED) {
2425                         /*
2426                          * Reload bioset because front_pad may have changed
2427                          * because a different table was loaded.
2428                          */
2429                         bioset_free(md->bs);
2430                         md->bs = p->bs;
2431                         p->bs = NULL;
2432                 }
2433                 /*
2434                  * There's no need to reload with request-based dm
2435                  * because the size of front_pad doesn't change.
2436                  * Note for future: If you are to reload bioset,
2437                  * prep-ed requests in the queue may refer
2438                  * to bio from the old bioset, so you must walk
2439                  * through the queue to unprep.
2440                  */
2441                 goto out;
2442         }
2443
2444         BUG_ON(!p || md->io_pool || md->rq_pool || md->bs);
2445
2446         md->io_pool = p->io_pool;
2447         p->io_pool = NULL;
2448         md->rq_pool = p->rq_pool;
2449         p->rq_pool = NULL;
2450         md->bs = p->bs;
2451         p->bs = NULL;
2452
2453 out:
2454         /* mempool bind completed, no longer need any mempools in the table */
2455         dm_table_free_md_mempools(t);
2456 }
2457
2458 /*
2459  * Bind a table to the device.
2460  */
2461 static void event_callback(void *context)
2462 {
2463         unsigned long flags;
2464         LIST_HEAD(uevents);
2465         struct mapped_device *md = (struct mapped_device *) context;
2466
2467         spin_lock_irqsave(&md->uevent_lock, flags);
2468         list_splice_init(&md->uevent_list, &uevents);
2469         spin_unlock_irqrestore(&md->uevent_lock, flags);
2470
2471         dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2472
2473         atomic_inc(&md->event_nr);
2474         wake_up(&md->eventq);
2475 }
2476
2477 /*
2478  * Protected by md->suspend_lock obtained by dm_swap_table().
2479  */
2480 static void __set_size(struct mapped_device *md, sector_t size)
2481 {
2482         set_capacity(md->disk, size);
2483
2484         i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
2485 }
2486
2487 /*
2488  * Returns old map, which caller must destroy.
2489  */
2490 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2491                                struct queue_limits *limits)
2492 {
2493         struct dm_table *old_map;
2494         struct request_queue *q = md->queue;
2495         sector_t size;
2496
2497         size = dm_table_get_size(t);
2498
2499         /*
2500          * Wipe any geometry if the size of the table changed.
2501          */
2502         if (size != dm_get_size(md))
2503                 memset(&md->geometry, 0, sizeof(md->geometry));
2504
2505         __set_size(md, size);
2506
2507         dm_table_event_callback(t, event_callback, md);
2508
2509         /*
2510          * The queue hasn't been stopped yet, if the old table type wasn't
2511          * for request-based during suspension.  So stop it to prevent
2512          * I/O mapping before resume.
2513          * This must be done before setting the queue restrictions,
2514          * because request-based dm may be run just after the setting.
2515          */
2516         if (dm_table_request_based(t)) {
2517                 stop_queue(q);
2518                 /*
2519                  * Leverage the fact that request-based DM targets are
2520                  * immutable singletons and establish md->immutable_target
2521                  * - used to optimize both dm_request_fn and dm_mq_queue_rq
2522                  */
2523                 md->immutable_target = dm_table_get_immutable_target(t);
2524         }
2525
2526         __bind_mempools(md, t);
2527
2528         old_map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2529         rcu_assign_pointer(md->map, t);
2530         md->immutable_target_type = dm_table_get_immutable_target_type(t);
2531
2532         dm_table_set_restrictions(t, q, limits);
2533         if (old_map)
2534                 dm_sync_table(md);
2535
2536         return old_map;
2537 }
2538
2539 /*
2540  * Returns unbound table for the caller to free.
2541  */
2542 static struct dm_table *__unbind(struct mapped_device *md)
2543 {
2544         struct dm_table *map = rcu_dereference_protected(md->map, 1);
2545
2546         if (!map)
2547                 return NULL;
2548
2549         dm_table_event_callback(map, NULL, NULL);
2550         RCU_INIT_POINTER(md->map, NULL);
2551         dm_sync_table(md);
2552
2553         return map;
2554 }
2555
2556 /*
2557  * Constructor for a new device.
2558  */
2559 int dm_create(int minor, struct mapped_device **result)
2560 {
2561         struct mapped_device *md;
2562
2563         md = alloc_dev(minor);
2564         if (!md)
2565                 return -ENXIO;
2566
2567         dm_sysfs_init(md);
2568
2569         *result = md;
2570         return 0;
2571 }
2572
2573 /*
2574  * Functions to manage md->type.
2575  * All are required to hold md->type_lock.
2576  */
2577 void dm_lock_md_type(struct mapped_device *md)
2578 {
2579         mutex_lock(&md->type_lock);
2580 }
2581
2582 void dm_unlock_md_type(struct mapped_device *md)
2583 {
2584         mutex_unlock(&md->type_lock);
2585 }
2586
2587 void dm_set_md_type(struct mapped_device *md, unsigned type)
2588 {
2589         BUG_ON(!mutex_is_locked(&md->type_lock));
2590         md->type = type;
2591 }
2592
2593 unsigned dm_get_md_type(struct mapped_device *md)
2594 {
2595         return md->type;
2596 }
2597
2598 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2599 {
2600         return md->immutable_target_type;
2601 }
2602
2603 /*
2604  * The queue_limits are only valid as long as you have a reference
2605  * count on 'md'.
2606  */
2607 struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
2608 {
2609         BUG_ON(!atomic_read(&md->holders));
2610         return &md->queue->limits;
2611 }
2612 EXPORT_SYMBOL_GPL(dm_get_queue_limits);
2613
2614 static void init_rq_based_worker_thread(struct mapped_device *md)
2615 {
2616         /* Initialize the request-based DM worker thread */
2617         init_kthread_worker(&md->kworker);
2618         md->kworker_task = kthread_run(kthread_worker_fn, &md->kworker,
2619                                        "kdmwork-%s", dm_device_name(md));
2620 }
2621
2622 /*
2623  * Fully initialize a request-based queue (->elevator, ->request_fn, etc).
2624  */
2625 static int dm_init_request_based_queue(struct mapped_device *md)
2626 {
2627         struct request_queue *q = NULL;
2628
2629         /* Fully initialize the queue */
2630         q = blk_init_allocated_queue(md->queue, dm_request_fn, NULL);
2631         if (!q)
2632                 return -EINVAL;
2633
2634         /* disable dm_request_fn's merge heuristic by default */
2635         md->seq_rq_merge_deadline_usecs = 0;
2636
2637         md->queue = q;
2638         dm_init_old_md_queue(md);
2639         blk_queue_softirq_done(md->queue, dm_softirq_done);
2640         blk_queue_prep_rq(md->queue, dm_prep_fn);
2641
2642         init_rq_based_worker_thread(md);
2643
2644         elv_register_queue(md->queue);
2645
2646         return 0;
2647 }
2648
2649 static int dm_mq_init_request(void *data, struct request *rq,
2650                               unsigned int hctx_idx, unsigned int request_idx,
2651                               unsigned int numa_node)
2652 {
2653         struct mapped_device *md = data;
2654         struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2655
2656         /*
2657          * Must initialize md member of tio, otherwise it won't
2658          * be available in dm_mq_queue_rq.
2659          */
2660         tio->md = md;
2661
2662         return 0;
2663 }
2664
2665 static int dm_mq_queue_rq(struct blk_mq_hw_ctx *hctx,
2666                           const struct blk_mq_queue_data *bd)
2667 {
2668         struct request *rq = bd->rq;
2669         struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2670         struct mapped_device *md = tio->md;
2671         struct dm_target *ti = md->immutable_target;
2672
2673         if (unlikely(!ti)) {
2674                 int srcu_idx;
2675                 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2676
2677                 ti = dm_table_find_target(map, 0);
2678                 dm_put_live_table(md, srcu_idx);
2679         }
2680
2681         if (ti->type->busy && ti->type->busy(ti))
2682                 return BLK_MQ_RQ_QUEUE_BUSY;
2683
2684         dm_start_request(md, rq);
2685
2686         /* Init tio using md established in .init_request */
2687         init_tio(tio, rq, md);
2688
2689         /*
2690          * Establish tio->ti before queuing work (map_tio_request)
2691          * or making direct call to map_request().
2692          */
2693         tio->ti = ti;
2694
2695         /*
2696          * Both the table and md type cannot change after initial table load
2697          */
2698         if (dm_get_md_type(md) == DM_TYPE_REQUEST_BASED) {
2699                 /* clone request is allocated at the end of the pdu */
2700                 tio->clone = (void *)blk_mq_rq_to_pdu(rq) + sizeof(struct dm_rq_target_io);
2701                 (void) clone_rq(rq, md, tio, GFP_ATOMIC);
2702                 queue_kthread_work(&md->kworker, &tio->work);
2703         } else {
2704                 /* Direct call is fine since .queue_rq allows allocations */
2705                 if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE) {
2706                         /* Undo dm_start_request() before requeuing */
2707                         rq_end_stats(md, rq);
2708                         rq_completed(md, rq_data_dir(rq), false);
2709                         return BLK_MQ_RQ_QUEUE_BUSY;
2710                 }
2711         }
2712
2713         return BLK_MQ_RQ_QUEUE_OK;
2714 }
2715
2716 static struct blk_mq_ops dm_mq_ops = {
2717         .queue_rq = dm_mq_queue_rq,
2718         .map_queue = blk_mq_map_queue,
2719         .complete = dm_softirq_done,
2720         .init_request = dm_mq_init_request,
2721 };
2722
2723 static int dm_init_request_based_blk_mq_queue(struct mapped_device *md)
2724 {
2725         unsigned md_type = dm_get_md_type(md);
2726         struct request_queue *q;
2727         int err;
2728
2729         md->tag_set = kzalloc(sizeof(struct blk_mq_tag_set), GFP_KERNEL);
2730         if (!md->tag_set)
2731                 return -ENOMEM;
2732
2733         md->tag_set->ops = &dm_mq_ops;
2734         md->tag_set->queue_depth = dm_get_blk_mq_queue_depth();
2735         md->tag_set->numa_node = NUMA_NO_NODE;
2736         md->tag_set->flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
2737         md->tag_set->nr_hw_queues = dm_get_blk_mq_nr_hw_queues();
2738         md->tag_set->driver_data = md;
2739
2740         md->tag_set->cmd_size = sizeof(struct dm_rq_target_io);
2741         if (md_type == DM_TYPE_REQUEST_BASED) {
2742                 /* put the memory for non-blk-mq clone at the end of the pdu */
2743                 md->tag_set->cmd_size += sizeof(struct request);
2744         }
2745
2746         err = blk_mq_alloc_tag_set(md->tag_set);
2747         if (err)
2748                 goto out_kfree_tag_set;
2749
2750         q = blk_mq_init_allocated_queue(md->tag_set, md->queue);
2751         if (IS_ERR(q)) {
2752                 err = PTR_ERR(q);
2753                 goto out_tag_set;
2754         }
2755         md->queue = q;
2756         dm_init_md_queue(md);
2757
2758         /* backfill 'mq' sysfs registration normally done in blk_register_queue */
2759         blk_mq_register_disk(md->disk);
2760
2761         if (md_type == DM_TYPE_REQUEST_BASED)
2762                 init_rq_based_worker_thread(md);
2763
2764         return 0;
2765
2766 out_tag_set:
2767         blk_mq_free_tag_set(md->tag_set);
2768 out_kfree_tag_set:
2769         kfree(md->tag_set);
2770
2771         return err;
2772 }
2773
2774 static unsigned filter_md_type(unsigned type, struct mapped_device *md)
2775 {
2776         if (type == DM_TYPE_BIO_BASED)
2777                 return type;
2778
2779         return !md->use_blk_mq ? DM_TYPE_REQUEST_BASED : DM_TYPE_MQ_REQUEST_BASED;
2780 }
2781
2782 /*
2783  * Setup the DM device's queue based on md's type
2784  */
2785 int dm_setup_md_queue(struct mapped_device *md)
2786 {
2787         int r;
2788         unsigned md_type = filter_md_type(dm_get_md_type(md), md);
2789
2790         switch (md_type) {
2791         case DM_TYPE_REQUEST_BASED:
2792                 r = dm_init_request_based_queue(md);
2793                 if (r) {
2794                         DMWARN("Cannot initialize queue for request-based mapped device");
2795                         return r;
2796                 }
2797                 break;
2798         case DM_TYPE_MQ_REQUEST_BASED:
2799                 r = dm_init_request_based_blk_mq_queue(md);
2800                 if (r) {
2801                         DMWARN("Cannot initialize queue for request-based blk-mq mapped device");
2802                         return r;
2803                 }
2804                 break;
2805         case DM_TYPE_BIO_BASED:
2806                 dm_init_old_md_queue(md);
2807                 blk_queue_make_request(md->queue, dm_make_request);
2808                 /*
2809                  * DM handles splitting bios as needed.  Free the bio_split bioset
2810                  * since it won't be used (saves 1 process per bio-based DM device).
2811                  */
2812                 bioset_free(md->queue->bio_split);
2813                 md->queue->bio_split = NULL;
2814                 break;
2815         }
2816
2817         return 0;
2818 }
2819
2820 struct mapped_device *dm_get_md(dev_t dev)
2821 {
2822         struct mapped_device *md;
2823         unsigned minor = MINOR(dev);
2824
2825         if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2826                 return NULL;
2827
2828         spin_lock(&_minor_lock);
2829
2830         md = idr_find(&_minor_idr, minor);
2831         if (md) {
2832                 if ((md == MINOR_ALLOCED ||
2833                      (MINOR(disk_devt(dm_disk(md))) != minor) ||
2834                      dm_deleting_md(md) ||
2835                      test_bit(DMF_FREEING, &md->flags))) {
2836                         md = NULL;
2837                         goto out;
2838                 }
2839                 dm_get(md);
2840         }
2841
2842 out:
2843         spin_unlock(&_minor_lock);
2844
2845         return md;
2846 }
2847 EXPORT_SYMBOL_GPL(dm_get_md);
2848
2849 void *dm_get_mdptr(struct mapped_device *md)
2850 {
2851         return md->interface_ptr;
2852 }
2853
2854 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2855 {
2856         md->interface_ptr = ptr;
2857 }
2858
2859 void dm_get(struct mapped_device *md)
2860 {
2861         atomic_inc(&md->holders);
2862         BUG_ON(test_bit(DMF_FREEING, &md->flags));
2863 }
2864
2865 int dm_hold(struct mapped_device *md)
2866 {
2867         spin_lock(&_minor_lock);
2868         if (test_bit(DMF_FREEING, &md->flags)) {
2869                 spin_unlock(&_minor_lock);
2870                 return -EBUSY;
2871         }
2872         dm_get(md);
2873         spin_unlock(&_minor_lock);
2874         return 0;
2875 }
2876 EXPORT_SYMBOL_GPL(dm_hold);
2877
2878 const char *dm_device_name(struct mapped_device *md)
2879 {
2880         return md->name;
2881 }
2882 EXPORT_SYMBOL_GPL(dm_device_name);
2883
2884 static void __dm_destroy(struct mapped_device *md, bool wait)
2885 {
2886         struct dm_table *map;
2887         int srcu_idx;
2888
2889         might_sleep();
2890
2891         spin_lock(&_minor_lock);
2892         idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2893         set_bit(DMF_FREEING, &md->flags);
2894         spin_unlock(&_minor_lock);
2895
2896         if (dm_request_based(md) && md->kworker_task)
2897                 flush_kthread_worker(&md->kworker);
2898
2899         /*
2900          * Take suspend_lock so that presuspend and postsuspend methods
2901          * do not race with internal suspend.
2902          */
2903         mutex_lock(&md->suspend_lock);
2904         map = dm_get_live_table(md, &srcu_idx);
2905         if (!dm_suspended_md(md)) {
2906                 dm_table_presuspend_targets(map);
2907                 dm_table_postsuspend_targets(map);
2908         }
2909         /* dm_put_live_table must be before msleep, otherwise deadlock is possible */
2910         dm_put_live_table(md, srcu_idx);
2911         mutex_unlock(&md->suspend_lock);
2912
2913         /*
2914          * Rare, but there may be I/O requests still going to complete,
2915          * for example.  Wait for all references to disappear.
2916          * No one should increment the reference count of the mapped_device,
2917          * after the mapped_device state becomes DMF_FREEING.
2918          */
2919         if (wait)
2920                 while (atomic_read(&md->holders))
2921                         msleep(1);
2922         else if (atomic_read(&md->holders))
2923                 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2924                        dm_device_name(md), atomic_read(&md->holders));
2925
2926         dm_sysfs_exit(md);
2927         dm_table_destroy(__unbind(md));
2928         free_dev(md);
2929 }
2930
2931 void dm_destroy(struct mapped_device *md)
2932 {
2933         __dm_destroy(md, true);
2934 }
2935
2936 void dm_destroy_immediate(struct mapped_device *md)
2937 {
2938         __dm_destroy(md, false);
2939 }
2940
2941 void dm_put(struct mapped_device *md)
2942 {
2943         atomic_dec(&md->holders);
2944 }
2945 EXPORT_SYMBOL_GPL(dm_put);
2946
2947 static int dm_wait_for_completion(struct mapped_device *md, int interruptible)
2948 {
2949         int r = 0;
2950         DECLARE_WAITQUEUE(wait, current);
2951
2952         add_wait_queue(&md->wait, &wait);
2953
2954         while (1) {
2955                 set_current_state(interruptible);
2956
2957                 if (!md_in_flight(md))
2958                         break;
2959
2960                 if (interruptible == TASK_INTERRUPTIBLE &&
2961                     signal_pending(current)) {
2962                         r = -EINTR;
2963                         break;
2964                 }
2965
2966                 io_schedule();
2967         }
2968         set_current_state(TASK_RUNNING);
2969
2970         remove_wait_queue(&md->wait, &wait);
2971
2972         return r;
2973 }
2974
2975 /*
2976  * Process the deferred bios
2977  */
2978 static void dm_wq_work(struct work_struct *work)
2979 {
2980         struct mapped_device *md = container_of(work, struct mapped_device,
2981                                                 work);
2982         struct bio *c;
2983         int srcu_idx;
2984         struct dm_table *map;
2985
2986         map = dm_get_live_table(md, &srcu_idx);
2987
2988         while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2989                 spin_lock_irq(&md->deferred_lock);
2990                 c = bio_list_pop(&md->deferred);
2991                 spin_unlock_irq(&md->deferred_lock);
2992
2993                 if (!c)
2994                         break;
2995
2996                 if (dm_request_based(md))
2997                         generic_make_request(c);
2998                 else
2999                         __split_and_process_bio(md, map, c);
3000         }
3001
3002         dm_put_live_table(md, srcu_idx);
3003 }
3004
3005 static void dm_queue_flush(struct mapped_device *md)
3006 {
3007         clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3008         smp_mb__after_atomic();
3009         queue_work(md->wq, &md->work);
3010 }
3011
3012 /*
3013  * Swap in a new table, returning the old one for the caller to destroy.
3014  */
3015 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
3016 {
3017         struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
3018         struct queue_limits limits;
3019         int r;
3020
3021         mutex_lock(&md->suspend_lock);
3022
3023         /* device must be suspended */
3024         if (!dm_suspended_md(md))
3025                 goto out;
3026
3027         /*
3028          * If the new table has no data devices, retain the existing limits.
3029          * This helps multipath with queue_if_no_path if all paths disappear,
3030          * then new I/O is queued based on these limits, and then some paths
3031          * reappear.
3032          */
3033         if (dm_table_has_no_data_devices(table)) {
3034                 live_map = dm_get_live_table_fast(md);
3035                 if (live_map)
3036                         limits = md->queue->limits;
3037                 dm_put_live_table_fast(md);
3038         }
3039
3040         if (!live_map) {
3041                 r = dm_calculate_queue_limits(table, &limits);
3042                 if (r) {
3043                         map = ERR_PTR(r);
3044                         goto out;
3045                 }
3046         }
3047
3048         map = __bind(md, table, &limits);
3049
3050 out:
3051         mutex_unlock(&md->suspend_lock);
3052         return map;
3053 }
3054
3055 /*
3056  * Functions to lock and unlock any filesystem running on the
3057  * device.
3058  */
3059 static int lock_fs(struct mapped_device *md)
3060 {
3061         int r;
3062
3063         WARN_ON(md->frozen_sb);
3064
3065         md->frozen_sb = freeze_bdev(md->bdev);
3066         if (IS_ERR(md->frozen_sb)) {
3067                 r = PTR_ERR(md->frozen_sb);
3068                 md->frozen_sb = NULL;
3069                 return r;
3070         }
3071
3072         set_bit(DMF_FROZEN, &md->flags);
3073
3074         return 0;
3075 }
3076
3077 static void unlock_fs(struct mapped_device *md)
3078 {
3079         if (!test_bit(DMF_FROZEN, &md->flags))
3080                 return;
3081
3082         thaw_bdev(md->bdev, md->frozen_sb);
3083         md->frozen_sb = NULL;
3084         clear_bit(DMF_FROZEN, &md->flags);
3085 }
3086
3087 /*
3088  * If __dm_suspend returns 0, the device is completely quiescent
3089  * now. There is no request-processing activity. All new requests
3090  * are being added to md->deferred list.
3091  *
3092  * Caller must hold md->suspend_lock
3093  */
3094 static int __dm_suspend(struct mapped_device *md, struct dm_table *map,
3095                         unsigned suspend_flags, int interruptible)
3096 {
3097         bool do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG;
3098         bool noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG;
3099         int r;
3100
3101         /*
3102          * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
3103          * This flag is cleared before dm_suspend returns.
3104          */
3105         if (noflush)
3106                 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3107
3108         /*
3109          * This gets reverted if there's an error later and the targets
3110          * provide the .presuspend_undo hook.
3111          */
3112         dm_table_presuspend_targets(map);
3113
3114         /*
3115          * Flush I/O to the device.
3116          * Any I/O submitted after lock_fs() may not be flushed.
3117          * noflush takes precedence over do_lockfs.
3118          * (lock_fs() flushes I/Os and waits for them to complete.)
3119          */
3120         if (!noflush && do_lockfs) {
3121                 r = lock_fs(md);
3122                 if (r) {
3123                         dm_table_presuspend_undo_targets(map);
3124                         return r;
3125                 }
3126         }
3127
3128         /*
3129          * Here we must make sure that no processes are submitting requests
3130          * to target drivers i.e. no one may be executing
3131          * __split_and_process_bio. This is called from dm_request and
3132          * dm_wq_work.
3133          *
3134          * To get all processes out of __split_and_process_bio in dm_request,
3135          * we take the write lock. To prevent any process from reentering
3136          * __split_and_process_bio from dm_request and quiesce the thread
3137          * (dm_wq_work), we set BMF_BLOCK_IO_FOR_SUSPEND and call
3138          * flush_workqueue(md->wq).
3139          */
3140         set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3141         if (map)
3142                 synchronize_srcu(&md->io_barrier);
3143
3144         /*
3145          * Stop md->queue before flushing md->wq in case request-based
3146          * dm defers requests to md->wq from md->queue.
3147          */
3148         if (dm_request_based(md)) {
3149                 stop_queue(md->queue);
3150                 if (md->kworker_task)
3151                         flush_kthread_worker(&md->kworker);
3152         }
3153
3154         flush_workqueue(md->wq);
3155
3156         /*
3157          * At this point no more requests are entering target request routines.
3158          * We call dm_wait_for_completion to wait for all existing requests
3159          * to finish.
3160          */
3161         r = dm_wait_for_completion(md, interruptible);
3162
3163         if (noflush)
3164                 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3165         if (map)
3166                 synchronize_srcu(&md->io_barrier);
3167
3168         /* were we interrupted ? */
3169         if (r < 0) {
3170                 dm_queue_flush(md);
3171
3172                 if (dm_request_based(md))
3173                         start_queue(md->queue);
3174
3175                 unlock_fs(md);
3176                 dm_table_presuspend_undo_targets(map);
3177                 /* pushback list is already flushed, so skip flush */
3178         }
3179
3180         return r;
3181 }
3182
3183 /*
3184  * We need to be able to change a mapping table under a mounted
3185  * filesystem.  For example we might want to move some data in
3186  * the background.  Before the table can be swapped with
3187  * dm_bind_table, dm_suspend must be called to flush any in
3188  * flight bios and ensure that any further io gets deferred.
3189  */
3190 /*
3191  * Suspend mechanism in request-based dm.
3192  *
3193  * 1. Flush all I/Os by lock_fs() if needed.
3194  * 2. Stop dispatching any I/O by stopping the request_queue.
3195  * 3. Wait for all in-flight I/Os to be completed or requeued.
3196  *
3197  * To abort suspend, start the request_queue.
3198  */
3199 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
3200 {
3201         struct dm_table *map = NULL;
3202         int r = 0;
3203
3204 retry:
3205         mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3206
3207         if (dm_suspended_md(md)) {
3208                 r = -EINVAL;
3209                 goto out_unlock;
3210         }
3211
3212         if (dm_suspended_internally_md(md)) {
3213                 /* already internally suspended, wait for internal resume */
3214                 mutex_unlock(&md->suspend_lock);
3215                 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3216                 if (r)
3217                         return r;
3218                 goto retry;
3219         }
3220
3221         map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3222
3223         r = __dm_suspend(md, map, suspend_flags, TASK_INTERRUPTIBLE);
3224         if (r)
3225                 goto out_unlock;
3226
3227         set_bit(DMF_SUSPENDED, &md->flags);
3228
3229         dm_table_postsuspend_targets(map);
3230
3231 out_unlock:
3232         mutex_unlock(&md->suspend_lock);
3233         return r;
3234 }
3235
3236 static int __dm_resume(struct mapped_device *md, struct dm_table *map)
3237 {
3238         if (map) {
3239                 int r = dm_table_resume_targets(map);
3240                 if (r)
3241                         return r;
3242         }
3243
3244         dm_queue_flush(md);
3245
3246         /*
3247          * Flushing deferred I/Os must be done after targets are resumed
3248          * so that mapping of targets can work correctly.
3249          * Request-based dm is queueing the deferred I/Os in its request_queue.
3250          */
3251         if (dm_request_based(md))
3252                 start_queue(md->queue);
3253
3254         unlock_fs(md);
3255
3256         return 0;
3257 }
3258
3259 int dm_resume(struct mapped_device *md)
3260 {
3261         int r = -EINVAL;
3262         struct dm_table *map = NULL;
3263
3264 retry:
3265         mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3266
3267         if (!dm_suspended_md(md))
3268                 goto out;
3269
3270         if (dm_suspended_internally_md(md)) {
3271                 /* already internally suspended, wait for internal resume */
3272                 mutex_unlock(&md->suspend_lock);
3273                 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3274                 if (r)
3275                         return r;
3276                 goto retry;
3277         }
3278
3279         map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3280         if (!map || !dm_table_get_size(map))
3281                 goto out;
3282
3283         r = __dm_resume(md, map);
3284         if (r)
3285                 goto out;
3286
3287         clear_bit(DMF_SUSPENDED, &md->flags);
3288
3289         r = 0;
3290 out:
3291         mutex_unlock(&md->suspend_lock);
3292
3293         return r;
3294 }
3295
3296 /*
3297  * Internal suspend/resume works like userspace-driven suspend. It waits
3298  * until all bios finish and prevents issuing new bios to the target drivers.
3299  * It may be used only from the kernel.
3300  */
3301
3302 static void __dm_internal_suspend(struct mapped_device *md, unsigned suspend_flags)
3303 {
3304         struct dm_table *map = NULL;
3305
3306         if (md->internal_suspend_count++)
3307                 return; /* nested internal suspend */
3308
3309         if (dm_suspended_md(md)) {
3310                 set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3311                 return; /* nest suspend */
3312         }
3313
3314         map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3315
3316         /*
3317          * Using TASK_UNINTERRUPTIBLE because only NOFLUSH internal suspend is
3318          * supported.  Properly supporting a TASK_INTERRUPTIBLE internal suspend
3319          * would require changing .presuspend to return an error -- avoid this
3320          * until there is a need for more elaborate variants of internal suspend.
3321          */
3322         (void) __dm_suspend(md, map, suspend_flags, TASK_UNINTERRUPTIBLE);
3323
3324         set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3325
3326         dm_table_postsuspend_targets(map);
3327 }
3328
3329 static void __dm_internal_resume(struct mapped_device *md)
3330 {
3331         BUG_ON(!md->internal_suspend_count);
3332
3333         if (--md->internal_suspend_count)
3334                 return; /* resume from nested internal suspend */
3335
3336         if (dm_suspended_md(md))
3337                 goto done; /* resume from nested suspend */
3338
3339         /*
3340          * NOTE: existing callers don't need to call dm_table_resume_targets
3341          * (which may fail -- so best to avoid it for now by passing NULL map)
3342          */
3343         (void) __dm_resume(md, NULL);
3344
3345 done:
3346         clear_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3347         smp_mb__after_atomic();
3348         wake_up_bit(&md->flags, DMF_SUSPENDED_INTERNALLY);
3349 }
3350
3351 void dm_internal_suspend_noflush(struct mapped_device *md)
3352 {
3353         mutex_lock(&md->suspend_lock);
3354         __dm_internal_suspend(md, DM_SUSPEND_NOFLUSH_FLAG);
3355         mutex_unlock(&md->suspend_lock);
3356 }
3357 EXPORT_SYMBOL_GPL(dm_internal_suspend_noflush);
3358
3359 void dm_internal_resume(struct mapped_device *md)
3360 {
3361         mutex_lock(&md->suspend_lock);
3362         __dm_internal_resume(md);
3363         mutex_unlock(&md->suspend_lock);
3364 }
3365 EXPORT_SYMBOL_GPL(dm_internal_resume);
3366
3367 /*
3368  * Fast variants of internal suspend/resume hold md->suspend_lock,
3369  * which prevents interaction with userspace-driven suspend.
3370  */
3371
3372 void dm_internal_suspend_fast(struct mapped_device *md)
3373 {
3374         mutex_lock(&md->suspend_lock);
3375         if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3376                 return;
3377
3378         set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3379         synchronize_srcu(&md->io_barrier);
3380         flush_workqueue(md->wq);
3381         dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
3382 }
3383 EXPORT_SYMBOL_GPL(dm_internal_suspend_fast);
3384
3385 void dm_internal_resume_fast(struct mapped_device *md)
3386 {
3387         if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3388                 goto done;
3389
3390         dm_queue_flush(md);
3391
3392 done:
3393         mutex_unlock(&md->suspend_lock);
3394 }
3395 EXPORT_SYMBOL_GPL(dm_internal_resume_fast);
3396
3397 /*-----------------------------------------------------------------
3398  * Event notification.
3399  *---------------------------------------------------------------*/
3400 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
3401                        unsigned cookie)
3402 {
3403         char udev_cookie[DM_COOKIE_LENGTH];
3404         char *envp[] = { udev_cookie, NULL };
3405
3406         if (!cookie)
3407                 return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
3408         else {
3409                 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
3410                          DM_COOKIE_ENV_VAR_NAME, cookie);
3411                 return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
3412                                           action, envp);
3413         }
3414 }
3415
3416 uint32_t dm_next_uevent_seq(struct mapped_device *md)
3417 {
3418         return atomic_add_return(1, &md->uevent_seq);
3419 }
3420
3421 uint32_t dm_get_event_nr(struct mapped_device *md)
3422 {
3423         return atomic_read(&md->event_nr);
3424 }
3425
3426 int dm_wait_event(struct mapped_device *md, int event_nr)
3427 {
3428         return wait_event_interruptible(md->eventq,
3429                         (event_nr != atomic_read(&md->event_nr)));
3430 }
3431
3432 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
3433 {
3434         unsigned long flags;
3435
3436         spin_lock_irqsave(&md->uevent_lock, flags);
3437         list_add(elist, &md->uevent_list);
3438         spin_unlock_irqrestore(&md->uevent_lock, flags);
3439 }
3440
3441 /*
3442  * The gendisk is only valid as long as you have a reference
3443  * count on 'md'.
3444  */
3445 struct gendisk *dm_disk(struct mapped_device *md)
3446 {
3447         return md->disk;
3448 }
3449 EXPORT_SYMBOL_GPL(dm_disk);
3450
3451 struct kobject *dm_kobject(struct mapped_device *md)
3452 {
3453         return &md->kobj_holder.kobj;
3454 }
3455
3456 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
3457 {
3458         struct mapped_device *md;
3459
3460         md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
3461
3462         if (test_bit(DMF_FREEING, &md->flags) ||
3463             dm_deleting_md(md))
3464                 return NULL;
3465
3466         dm_get(md);
3467         return md;
3468 }
3469
3470 int dm_suspended_md(struct mapped_device *md)
3471 {
3472         return test_bit(DMF_SUSPENDED, &md->flags);
3473 }
3474
3475 int dm_suspended_internally_md(struct mapped_device *md)
3476 {
3477         return test_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3478 }
3479
3480 int dm_test_deferred_remove_flag(struct mapped_device *md)
3481 {
3482         return test_bit(DMF_DEFERRED_REMOVE, &md->flags);
3483 }
3484
3485 int dm_suspended(struct dm_target *ti)
3486 {
3487         return dm_suspended_md(dm_table_get_md(ti->table));
3488 }
3489 EXPORT_SYMBOL_GPL(dm_suspended);
3490
3491 int dm_noflush_suspending(struct dm_target *ti)
3492 {
3493         return __noflush_suspending(dm_table_get_md(ti->table));
3494 }
3495 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
3496
3497 struct dm_md_mempools *dm_alloc_md_mempools(struct mapped_device *md, unsigned type,
3498                                             unsigned integrity, unsigned per_bio_data_size)
3499 {
3500         struct dm_md_mempools *pools = kzalloc(sizeof(*pools), GFP_KERNEL);
3501         struct kmem_cache *cachep = NULL;
3502         unsigned int pool_size = 0;
3503         unsigned int front_pad;
3504
3505         if (!pools)
3506                 return NULL;
3507
3508         type = filter_md_type(type, md);
3509
3510         switch (type) {
3511         case DM_TYPE_BIO_BASED:
3512                 cachep = _io_cache;
3513                 pool_size = dm_get_reserved_bio_based_ios();
3514                 front_pad = roundup(per_bio_data_size, __alignof__(struct dm_target_io)) + offsetof(struct dm_target_io, clone);
3515                 break;
3516         case DM_TYPE_REQUEST_BASED:
3517                 cachep = _rq_tio_cache;
3518                 pool_size = dm_get_reserved_rq_based_ios();
3519                 pools->rq_pool = mempool_create_slab_pool(pool_size, _rq_cache);
3520                 if (!pools->rq_pool)
3521                         goto out;
3522                 /* fall through to setup remaining rq-based pools */
3523         case DM_TYPE_MQ_REQUEST_BASED:
3524                 if (!pool_size)
3525                         pool_size = dm_get_reserved_rq_based_ios();
3526                 front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
3527                 /* per_bio_data_size is not used. See __bind_mempools(). */
3528                 WARN_ON(per_bio_data_size != 0);
3529                 break;
3530         default:
3531                 BUG();
3532         }
3533
3534         if (cachep) {
3535                 pools->io_pool = mempool_create_slab_pool(pool_size, cachep);
3536                 if (!pools->io_pool)
3537                         goto out;
3538         }
3539
3540         pools->bs = bioset_create_nobvec(pool_size, front_pad);
3541         if (!pools->bs)
3542                 goto out;
3543
3544         if (integrity && bioset_integrity_create(pools->bs, pool_size))
3545                 goto out;
3546
3547         return pools;
3548
3549 out:
3550         dm_free_md_mempools(pools);
3551
3552         return NULL;
3553 }
3554
3555 void dm_free_md_mempools(struct dm_md_mempools *pools)
3556 {
3557         if (!pools)
3558                 return;
3559
3560         mempool_destroy(pools->io_pool);
3561         mempool_destroy(pools->rq_pool);
3562
3563         if (pools->bs)
3564                 bioset_free(pools->bs);
3565
3566         kfree(pools);
3567 }
3568
3569 static int dm_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
3570                           u32 flags)
3571 {
3572         struct mapped_device *md = bdev->bd_disk->private_data;
3573         const struct pr_ops *ops;
3574         fmode_t mode;
3575         int r;
3576
3577         r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3578         if (r < 0)
3579                 return r;
3580
3581         ops = bdev->bd_disk->fops->pr_ops;
3582         if (ops && ops->pr_register)
3583                 r = ops->pr_register(bdev, old_key, new_key, flags);
3584         else
3585                 r = -EOPNOTSUPP;
3586
3587         bdput(bdev);
3588         return r;
3589 }
3590
3591 static int dm_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
3592                          u32 flags)
3593 {
3594         struct mapped_device *md = bdev->bd_disk->private_data;
3595         const struct pr_ops *ops;
3596         fmode_t mode;
3597         int r;
3598
3599         r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3600         if (r < 0)
3601                 return r;
3602
3603         ops = bdev->bd_disk->fops->pr_ops;
3604         if (ops && ops->pr_reserve)
3605                 r = ops->pr_reserve(bdev, key, type, flags);
3606         else
3607                 r = -EOPNOTSUPP;
3608
3609         bdput(bdev);
3610         return r;
3611 }
3612
3613 static int dm_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
3614 {
3615         struct mapped_device *md = bdev->bd_disk->private_data;
3616         const struct pr_ops *ops;
3617         fmode_t mode;
3618         int r;
3619
3620         r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3621         if (r < 0)
3622                 return r;
3623
3624         ops = bdev->bd_disk->fops->pr_ops;
3625         if (ops && ops->pr_release)
3626                 r = ops->pr_release(bdev, key, type);
3627         else
3628                 r = -EOPNOTSUPP;
3629
3630         bdput(bdev);
3631         return r;
3632 }
3633
3634 static int dm_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
3635                          enum pr_type type, bool abort)
3636 {
3637         struct mapped_device *md = bdev->bd_disk->private_data;
3638         const struct pr_ops *ops;
3639         fmode_t mode;
3640         int r;
3641
3642         r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3643         if (r < 0)
3644                 return r;
3645
3646         ops = bdev->bd_disk->fops->pr_ops;
3647         if (ops && ops->pr_preempt)
3648                 r = ops->pr_preempt(bdev, old_key, new_key, type, abort);
3649         else
3650                 r = -EOPNOTSUPP;
3651
3652         bdput(bdev);
3653         return r;
3654 }
3655
3656 static int dm_pr_clear(struct block_device *bdev, u64 key)
3657 {
3658         struct mapped_device *md = bdev->bd_disk->private_data;
3659         const struct pr_ops *ops;
3660         fmode_t mode;
3661         int r;
3662
3663         r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3664         if (r < 0)
3665                 return r;
3666
3667         ops = bdev->bd_disk->fops->pr_ops;
3668         if (ops && ops->pr_clear)
3669                 r = ops->pr_clear(bdev, key);
3670         else
3671                 r = -EOPNOTSUPP;
3672
3673         bdput(bdev);
3674         return r;
3675 }
3676
3677 static const struct pr_ops dm_pr_ops = {
3678         .pr_register    = dm_pr_register,
3679         .pr_reserve     = dm_pr_reserve,
3680         .pr_release     = dm_pr_release,
3681         .pr_preempt     = dm_pr_preempt,
3682         .pr_clear       = dm_pr_clear,
3683 };
3684
3685 static const struct block_device_operations dm_blk_dops = {
3686         .open = dm_blk_open,
3687         .release = dm_blk_close,
3688         .ioctl = dm_blk_ioctl,
3689         .getgeo = dm_blk_getgeo,
3690         .pr_ops = &dm_pr_ops,
3691         .owner = THIS_MODULE
3692 };
3693
3694 /*
3695  * module hooks
3696  */
3697 module_init(dm_init);
3698 module_exit(dm_exit);
3699
3700 module_param(major, uint, 0);
3701 MODULE_PARM_DESC(major, "The major number of the device mapper");
3702
3703 module_param(reserved_bio_based_ios, uint, S_IRUGO | S_IWUSR);
3704 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
3705
3706 module_param(reserved_rq_based_ios, uint, S_IRUGO | S_IWUSR);
3707 MODULE_PARM_DESC(reserved_rq_based_ios, "Reserved IOs in request-based mempools");
3708
3709 module_param(use_blk_mq, bool, S_IRUGO | S_IWUSR);
3710 MODULE_PARM_DESC(use_blk_mq, "Use block multiqueue for request-based DM devices");
3711
3712 module_param(dm_mq_nr_hw_queues, uint, S_IRUGO | S_IWUSR);
3713 MODULE_PARM_DESC(dm_mq_nr_hw_queues, "Number of hardware queues for request-based dm-mq devices");
3714
3715 module_param(dm_mq_queue_depth, uint, S_IRUGO | S_IWUSR);
3716 MODULE_PARM_DESC(dm_mq_queue_depth, "Queue depth for request-based dm-mq devices");
3717
3718 MODULE_DESCRIPTION(DM_NAME " driver");
3719 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
3720 MODULE_LICENSE("GPL");