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