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