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