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