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