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