GNU Linux-libre 4.9.337-gnu1
[releases.git] / drivers / md / dm.c
1 /*
2  * Copyright (C) 2001, 2002 Sistina Software (UK) Limited.
3  * Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7
8 #include "dm-core.h"
9 #include "dm-rq.h"
10 #include "dm-uevent.h"
11
12 #include <linux/init.h>
13 #include <linux/module.h>
14 #include <linux/mutex.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/pr.h>
24 #include <linux/vmalloc.h>
25
26 #define DM_MSG_PREFIX "core"
27
28 #ifdef CONFIG_PRINTK
29 /*
30  * ratelimit state to be used in DMXXX_LIMIT().
31  */
32 DEFINE_RATELIMIT_STATE(dm_ratelimit_state,
33                        DEFAULT_RATELIMIT_INTERVAL,
34                        DEFAULT_RATELIMIT_BURST);
35 EXPORT_SYMBOL(dm_ratelimit_state);
36 #endif
37
38 /*
39  * Cookies are numeric values sent with CHANGE and REMOVE
40  * uevents while resuming, removing or renaming the device.
41  */
42 #define DM_COOKIE_ENV_VAR_NAME "DM_COOKIE"
43 #define DM_COOKIE_LENGTH 24
44
45 static const char *_name = DM_NAME;
46
47 static unsigned int major = 0;
48 static unsigned int _major = 0;
49
50 static DEFINE_IDR(_minor_idr);
51
52 static DEFINE_SPINLOCK(_minor_lock);
53
54 static void do_deferred_remove(struct work_struct *w);
55
56 static DECLARE_WORK(deferred_remove_work, do_deferred_remove);
57
58 static struct workqueue_struct *deferred_remove_workqueue;
59
60 /*
61  * One of these is allocated per bio.
62  */
63 struct dm_io {
64         struct mapped_device *md;
65         int error;
66         atomic_t io_count;
67         struct bio *bio;
68         unsigned long start_time;
69         spinlock_t endio_lock;
70         struct dm_stats_aux stats_aux;
71 };
72
73 #define MINOR_ALLOCED ((void *)-1)
74
75 /*
76  * Bits for the md->flags field.
77  */
78 #define DMF_BLOCK_IO_FOR_SUSPEND 0
79 #define DMF_SUSPENDED 1
80 #define DMF_FROZEN 2
81 #define DMF_FREEING 3
82 #define DMF_DELETING 4
83 #define DMF_NOFLUSH_SUSPENDING 5
84 #define DMF_DEFERRED_REMOVE 6
85 #define DMF_SUSPENDED_INTERNALLY 7
86
87 #define DM_NUMA_NODE NUMA_NO_NODE
88 static int dm_numa_node = DM_NUMA_NODE;
89
90 /*
91  * For mempools pre-allocation at the table loading time.
92  */
93 struct dm_md_mempools {
94         mempool_t *io_pool;
95         mempool_t *rq_pool;
96         struct bio_set *bs;
97 };
98
99 struct table_device {
100         struct list_head list;
101         atomic_t count;
102         struct dm_dev dm_dev;
103 };
104
105 static struct kmem_cache *_io_cache;
106 static struct kmem_cache *_rq_tio_cache;
107 static struct kmem_cache *_rq_cache;
108
109 /*
110  * Bio-based DM's mempools' reserved IOs set by the user.
111  */
112 #define RESERVED_BIO_BASED_IOS          16
113 static unsigned reserved_bio_based_ios = RESERVED_BIO_BASED_IOS;
114
115 static int __dm_get_module_param_int(int *module_param, int min, int max)
116 {
117         int param = ACCESS_ONCE(*module_param);
118         int modified_param = 0;
119         bool modified = true;
120
121         if (param < min)
122                 modified_param = min;
123         else if (param > max)
124                 modified_param = max;
125         else
126                 modified = false;
127
128         if (modified) {
129                 (void)cmpxchg(module_param, param, modified_param);
130                 param = modified_param;
131         }
132
133         return param;
134 }
135
136 unsigned __dm_get_module_param(unsigned *module_param,
137                                unsigned def, unsigned max)
138 {
139         unsigned param = ACCESS_ONCE(*module_param);
140         unsigned modified_param = 0;
141
142         if (!param)
143                 modified_param = def;
144         else if (param > max)
145                 modified_param = max;
146
147         if (modified_param) {
148                 (void)cmpxchg(module_param, param, modified_param);
149                 param = modified_param;
150         }
151
152         return param;
153 }
154
155 unsigned dm_get_reserved_bio_based_ios(void)
156 {
157         return __dm_get_module_param(&reserved_bio_based_ios,
158                                      RESERVED_BIO_BASED_IOS, DM_RESERVED_MAX_IOS);
159 }
160 EXPORT_SYMBOL_GPL(dm_get_reserved_bio_based_ios);
161
162 static unsigned dm_get_numa_node(void)
163 {
164         return __dm_get_module_param_int(&dm_numa_node,
165                                          DM_NUMA_NODE, num_online_nodes() - 1);
166 }
167
168 static int __init local_init(void)
169 {
170         int r = -ENOMEM;
171
172         /* allocate a slab for the dm_ios */
173         _io_cache = KMEM_CACHE(dm_io, 0);
174         if (!_io_cache)
175                 return r;
176
177         _rq_tio_cache = KMEM_CACHE(dm_rq_target_io, 0);
178         if (!_rq_tio_cache)
179                 goto out_free_io_cache;
180
181         _rq_cache = kmem_cache_create("dm_old_clone_request", sizeof(struct request),
182                                       __alignof__(struct request), 0, NULL);
183         if (!_rq_cache)
184                 goto out_free_rq_tio_cache;
185
186         r = dm_uevent_init();
187         if (r)
188                 goto out_free_rq_cache;
189
190         deferred_remove_workqueue = alloc_workqueue("kdmremove", WQ_UNBOUND, 1);
191         if (!deferred_remove_workqueue) {
192                 r = -ENOMEM;
193                 goto out_uevent_exit;
194         }
195
196         _major = major;
197         r = register_blkdev(_major, _name);
198         if (r < 0)
199                 goto out_free_workqueue;
200
201         if (!_major)
202                 _major = r;
203
204         return 0;
205
206 out_free_workqueue:
207         destroy_workqueue(deferred_remove_workqueue);
208 out_uevent_exit:
209         dm_uevent_exit();
210 out_free_rq_cache:
211         kmem_cache_destroy(_rq_cache);
212 out_free_rq_tio_cache:
213         kmem_cache_destroy(_rq_tio_cache);
214 out_free_io_cache:
215         kmem_cache_destroy(_io_cache);
216
217         return r;
218 }
219
220 static void local_exit(void)
221 {
222         flush_scheduled_work();
223         destroy_workqueue(deferred_remove_workqueue);
224
225         kmem_cache_destroy(_rq_cache);
226         kmem_cache_destroy(_rq_tio_cache);
227         kmem_cache_destroy(_io_cache);
228         unregister_blkdev(_major, _name);
229         dm_uevent_exit();
230
231         _major = 0;
232
233         DMINFO("cleaned up");
234 }
235
236 static int (*_inits[])(void) __initdata = {
237         local_init,
238         dm_target_init,
239         dm_linear_init,
240         dm_stripe_init,
241         dm_io_init,
242         dm_kcopyd_init,
243         dm_interface_init,
244         dm_statistics_init,
245 };
246
247 static void (*_exits[])(void) = {
248         local_exit,
249         dm_target_exit,
250         dm_linear_exit,
251         dm_stripe_exit,
252         dm_io_exit,
253         dm_kcopyd_exit,
254         dm_interface_exit,
255         dm_statistics_exit,
256 };
257
258 static int __init dm_init(void)
259 {
260         const int count = ARRAY_SIZE(_inits);
261
262         int r, i;
263
264         for (i = 0; i < count; i++) {
265                 r = _inits[i]();
266                 if (r)
267                         goto bad;
268         }
269
270         return 0;
271
272       bad:
273         while (i--)
274                 _exits[i]();
275
276         return r;
277 }
278
279 static void __exit dm_exit(void)
280 {
281         int i = ARRAY_SIZE(_exits);
282
283         while (i--)
284                 _exits[i]();
285
286         /*
287          * Should be empty by this point.
288          */
289         idr_destroy(&_minor_idr);
290 }
291
292 /*
293  * Block device functions
294  */
295 int dm_deleting_md(struct mapped_device *md)
296 {
297         return test_bit(DMF_DELETING, &md->flags);
298 }
299
300 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
301 {
302         struct mapped_device *md;
303
304         spin_lock(&_minor_lock);
305
306         md = bdev->bd_disk->private_data;
307         if (!md)
308                 goto out;
309
310         if (test_bit(DMF_FREEING, &md->flags) ||
311             dm_deleting_md(md)) {
312                 md = NULL;
313                 goto out;
314         }
315
316         dm_get(md);
317         atomic_inc(&md->open_count);
318 out:
319         spin_unlock(&_minor_lock);
320
321         return md ? 0 : -ENXIO;
322 }
323
324 static void dm_blk_close(struct gendisk *disk, fmode_t mode)
325 {
326         struct mapped_device *md;
327
328         spin_lock(&_minor_lock);
329
330         md = disk->private_data;
331         if (WARN_ON(!md))
332                 goto out;
333
334         if (atomic_dec_and_test(&md->open_count) &&
335             (test_bit(DMF_DEFERRED_REMOVE, &md->flags)))
336                 queue_work(deferred_remove_workqueue, &deferred_remove_work);
337
338         dm_put(md);
339 out:
340         spin_unlock(&_minor_lock);
341 }
342
343 int dm_open_count(struct mapped_device *md)
344 {
345         return atomic_read(&md->open_count);
346 }
347
348 /*
349  * Guarantees nothing is using the device before it's deleted.
350  */
351 int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
352 {
353         int r = 0;
354
355         spin_lock(&_minor_lock);
356
357         if (dm_open_count(md)) {
358                 r = -EBUSY;
359                 if (mark_deferred)
360                         set_bit(DMF_DEFERRED_REMOVE, &md->flags);
361         } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
362                 r = -EEXIST;
363         else
364                 set_bit(DMF_DELETING, &md->flags);
365
366         spin_unlock(&_minor_lock);
367
368         return r;
369 }
370
371 int dm_cancel_deferred_remove(struct mapped_device *md)
372 {
373         int r = 0;
374
375         spin_lock(&_minor_lock);
376
377         if (test_bit(DMF_DELETING, &md->flags))
378                 r = -EBUSY;
379         else
380                 clear_bit(DMF_DEFERRED_REMOVE, &md->flags);
381
382         spin_unlock(&_minor_lock);
383
384         return r;
385 }
386
387 static void do_deferred_remove(struct work_struct *w)
388 {
389         dm_deferred_remove();
390 }
391
392 sector_t dm_get_size(struct mapped_device *md)
393 {
394         return get_capacity(md->disk);
395 }
396
397 struct request_queue *dm_get_md_queue(struct mapped_device *md)
398 {
399         return md->queue;
400 }
401
402 struct dm_stats *dm_get_stats(struct mapped_device *md)
403 {
404         return &md->stats;
405 }
406
407 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
408 {
409         struct mapped_device *md = bdev->bd_disk->private_data;
410
411         return dm_get_geometry(md, geo);
412 }
413
414 static int dm_grab_bdev_for_ioctl(struct mapped_device *md,
415                                   struct block_device **bdev,
416                                   fmode_t *mode)
417 {
418         struct dm_target *tgt;
419         struct dm_table *map;
420         int srcu_idx, r;
421
422 retry:
423         r = -ENOTTY;
424         map = dm_get_live_table(md, &srcu_idx);
425         if (!map || !dm_table_get_size(map))
426                 goto out;
427
428         /* We only support devices that have a single target */
429         if (dm_table_get_num_targets(map) != 1)
430                 goto out;
431
432         tgt = dm_table_get_target(map, 0);
433         if (!tgt->type->prepare_ioctl)
434                 goto out;
435
436         if (dm_suspended_md(md)) {
437                 r = -EAGAIN;
438                 goto out;
439         }
440
441         r = tgt->type->prepare_ioctl(tgt, bdev, mode);
442         if (r < 0)
443                 goto out;
444
445         bdgrab(*bdev);
446         dm_put_live_table(md, srcu_idx);
447         return r;
448
449 out:
450         dm_put_live_table(md, srcu_idx);
451         if (r == -ENOTCONN && !fatal_signal_pending(current)) {
452                 msleep(10);
453                 goto retry;
454         }
455         return r;
456 }
457
458 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
459                         unsigned int cmd, unsigned long arg)
460 {
461         struct mapped_device *md = bdev->bd_disk->private_data;
462         int r;
463
464         r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
465         if (r < 0)
466                 return r;
467
468         if (r > 0) {
469                 /*
470                  * Target determined this ioctl is being issued against
471                  * a logical partition of the parent bdev; so extra
472                  * validation is needed.
473                  */
474                 r = scsi_verify_blk_ioctl(NULL, cmd);
475                 if (r)
476                         goto out;
477         }
478
479         r =  __blkdev_driver_ioctl(bdev, mode, cmd, arg);
480 out:
481         bdput(bdev);
482         return r;
483 }
484
485 static struct dm_io *alloc_io(struct mapped_device *md)
486 {
487         return mempool_alloc(md->io_pool, GFP_NOIO);
488 }
489
490 static void free_io(struct mapped_device *md, struct dm_io *io)
491 {
492         mempool_free(io, md->io_pool);
493 }
494
495 static void free_tio(struct dm_target_io *tio)
496 {
497         bio_put(&tio->clone);
498 }
499
500 int md_in_flight(struct mapped_device *md)
501 {
502         return atomic_read(&md->pending[READ]) +
503                atomic_read(&md->pending[WRITE]);
504 }
505
506 static void start_io_acct(struct dm_io *io)
507 {
508         struct mapped_device *md = io->md;
509         struct bio *bio = io->bio;
510         int cpu;
511         int rw = bio_data_dir(bio);
512
513         io->start_time = jiffies;
514
515         cpu = part_stat_lock();
516         part_round_stats(cpu, &dm_disk(md)->part0);
517         part_stat_unlock();
518         atomic_set(&dm_disk(md)->part0.in_flight[rw],
519                 atomic_inc_return(&md->pending[rw]));
520
521         if (unlikely(dm_stats_used(&md->stats)))
522                 dm_stats_account_io(&md->stats, bio_data_dir(bio),
523                                     bio->bi_iter.bi_sector, bio_sectors(bio),
524                                     false, 0, &io->stats_aux);
525 }
526
527 static void end_io_acct(struct mapped_device *md, struct bio *bio,
528                         unsigned long start_time, struct dm_stats_aux *stats_aux)
529 {
530         unsigned long duration = jiffies - start_time;
531         int pending;
532         int rw = bio_data_dir(bio);
533
534         generic_end_io_acct(rw, &dm_disk(md)->part0, start_time);
535
536         if (unlikely(dm_stats_used(&md->stats)))
537                 dm_stats_account_io(&md->stats, bio_data_dir(bio),
538                                     bio->bi_iter.bi_sector, bio_sectors(bio),
539                                     true, duration, stats_aux);
540
541         /*
542          * After this is decremented the bio must not be touched if it is
543          * a flush.
544          */
545         pending = atomic_dec_return(&md->pending[rw]);
546         atomic_set(&dm_disk(md)->part0.in_flight[rw], pending);
547         pending += atomic_read(&md->pending[rw^0x1]);
548
549         /* nudge anyone waiting on suspend queue */
550         if (!pending)
551                 wake_up(&md->wait);
552 }
553
554 /*
555  * Add the bio to the list of deferred io.
556  */
557 static void queue_io(struct mapped_device *md, struct bio *bio)
558 {
559         unsigned long flags;
560
561         spin_lock_irqsave(&md->deferred_lock, flags);
562         bio_list_add(&md->deferred, bio);
563         spin_unlock_irqrestore(&md->deferred_lock, flags);
564         queue_work(md->wq, &md->work);
565 }
566
567 /*
568  * Everyone (including functions in this file), should use this
569  * function to access the md->map field, and make sure they call
570  * dm_put_live_table() when finished.
571  */
572 struct dm_table *dm_get_live_table(struct mapped_device *md, int *srcu_idx) __acquires(md->io_barrier)
573 {
574         *srcu_idx = srcu_read_lock(&md->io_barrier);
575
576         return srcu_dereference(md->map, &md->io_barrier);
577 }
578
579 void dm_put_live_table(struct mapped_device *md, int srcu_idx) __releases(md->io_barrier)
580 {
581         srcu_read_unlock(&md->io_barrier, srcu_idx);
582 }
583
584 void dm_sync_table(struct mapped_device *md)
585 {
586         synchronize_srcu(&md->io_barrier);
587         synchronize_rcu_expedited();
588 }
589
590 /*
591  * A fast alternative to dm_get_live_table/dm_put_live_table.
592  * The caller must not block between these two functions.
593  */
594 static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
595 {
596         rcu_read_lock();
597         return rcu_dereference(md->map);
598 }
599
600 static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
601 {
602         rcu_read_unlock();
603 }
604
605 /*
606  * Open a table device so we can use it as a map destination.
607  */
608 static int open_table_device(struct table_device *td, dev_t dev,
609                              struct mapped_device *md)
610 {
611         static char *_claim_ptr = "I belong to device-mapper";
612         struct block_device *bdev;
613
614         int r;
615
616         BUG_ON(td->dm_dev.bdev);
617
618         bdev = blkdev_get_by_dev(dev, td->dm_dev.mode | FMODE_EXCL, _claim_ptr);
619         if (IS_ERR(bdev))
620                 return PTR_ERR(bdev);
621
622         r = bd_link_disk_holder(bdev, dm_disk(md));
623         if (r) {
624                 blkdev_put(bdev, td->dm_dev.mode | FMODE_EXCL);
625                 return r;
626         }
627
628         td->dm_dev.bdev = bdev;
629         return 0;
630 }
631
632 /*
633  * Close a table device that we've been using.
634  */
635 static void close_table_device(struct table_device *td, struct mapped_device *md)
636 {
637         if (!td->dm_dev.bdev)
638                 return;
639
640         bd_unlink_disk_holder(td->dm_dev.bdev, dm_disk(md));
641         blkdev_put(td->dm_dev.bdev, td->dm_dev.mode | FMODE_EXCL);
642         td->dm_dev.bdev = NULL;
643 }
644
645 static struct table_device *find_table_device(struct list_head *l, dev_t dev,
646                                               fmode_t mode) {
647         struct table_device *td;
648
649         list_for_each_entry(td, l, list)
650                 if (td->dm_dev.bdev->bd_dev == dev && td->dm_dev.mode == mode)
651                         return td;
652
653         return NULL;
654 }
655
656 int dm_get_table_device(struct mapped_device *md, dev_t dev, fmode_t mode,
657                         struct dm_dev **result) {
658         int r;
659         struct table_device *td;
660
661         mutex_lock(&md->table_devices_lock);
662         td = find_table_device(&md->table_devices, dev, mode);
663         if (!td) {
664                 td = kmalloc_node(sizeof(*td), GFP_KERNEL, md->numa_node_id);
665                 if (!td) {
666                         mutex_unlock(&md->table_devices_lock);
667                         return -ENOMEM;
668                 }
669
670                 td->dm_dev.mode = mode;
671                 td->dm_dev.bdev = NULL;
672
673                 if ((r = open_table_device(td, dev, md))) {
674                         mutex_unlock(&md->table_devices_lock);
675                         kfree(td);
676                         return r;
677                 }
678
679                 format_dev_t(td->dm_dev.name, dev);
680
681                 atomic_set(&td->count, 0);
682                 list_add(&td->list, &md->table_devices);
683         }
684         atomic_inc(&td->count);
685         mutex_unlock(&md->table_devices_lock);
686
687         *result = &td->dm_dev;
688         return 0;
689 }
690 EXPORT_SYMBOL_GPL(dm_get_table_device);
691
692 void dm_put_table_device(struct mapped_device *md, struct dm_dev *d)
693 {
694         struct table_device *td = container_of(d, struct table_device, dm_dev);
695
696         mutex_lock(&md->table_devices_lock);
697         if (atomic_dec_and_test(&td->count)) {
698                 close_table_device(td, md);
699                 list_del(&td->list);
700                 kfree(td);
701         }
702         mutex_unlock(&md->table_devices_lock);
703 }
704 EXPORT_SYMBOL(dm_put_table_device);
705
706 static void free_table_devices(struct list_head *devices)
707 {
708         struct list_head *tmp, *next;
709
710         list_for_each_safe(tmp, next, devices) {
711                 struct table_device *td = list_entry(tmp, struct table_device, list);
712
713                 DMWARN("dm_destroy: %s still exists with %d references",
714                        td->dm_dev.name, atomic_read(&td->count));
715                 kfree(td);
716         }
717 }
718
719 /*
720  * Get the geometry associated with a dm device
721  */
722 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
723 {
724         *geo = md->geometry;
725
726         return 0;
727 }
728
729 /*
730  * Set the geometry of a device.
731  */
732 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
733 {
734         sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
735
736         if (geo->start > sz) {
737                 DMWARN("Start sector is beyond the geometry limits.");
738                 return -EINVAL;
739         }
740
741         md->geometry = *geo;
742
743         return 0;
744 }
745
746 /*-----------------------------------------------------------------
747  * CRUD START:
748  *   A more elegant soln is in the works that uses the queue
749  *   merge fn, unfortunately there are a couple of changes to
750  *   the block layer that I want to make for this.  So in the
751  *   interests of getting something for people to use I give
752  *   you this clearly demarcated crap.
753  *---------------------------------------------------------------*/
754
755 static int __noflush_suspending(struct mapped_device *md)
756 {
757         return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
758 }
759
760 /*
761  * Decrements the number of outstanding ios that a bio has been
762  * cloned into, completing the original io if necc.
763  */
764 static void dec_pending(struct dm_io *io, int error)
765 {
766         unsigned long flags;
767         int io_error;
768         struct bio *bio;
769         struct mapped_device *md = io->md;
770         unsigned long start_time = 0;
771         struct dm_stats_aux stats_aux;
772
773         /* Push-back supersedes any I/O errors */
774         if (unlikely(error)) {
775                 spin_lock_irqsave(&io->endio_lock, flags);
776                 if (!(io->error > 0 && __noflush_suspending(md)))
777                         io->error = error;
778                 spin_unlock_irqrestore(&io->endio_lock, flags);
779         }
780
781         if (atomic_dec_and_test(&io->io_count)) {
782                 if (io->error == DM_ENDIO_REQUEUE) {
783                         /*
784                          * Target requested pushing back the I/O.
785                          */
786                         spin_lock_irqsave(&md->deferred_lock, flags);
787                         if (__noflush_suspending(md))
788                                 bio_list_add_head(&md->deferred, io->bio);
789                         else
790                                 /* noflush suspend was interrupted. */
791                                 io->error = -EIO;
792                         spin_unlock_irqrestore(&md->deferred_lock, flags);
793                 }
794
795                 io_error = io->error;
796                 bio = io->bio;
797                 start_time = io->start_time;
798                 stats_aux = io->stats_aux;
799                 free_io(md, io);
800                 end_io_acct(md, bio, start_time, &stats_aux);
801
802                 if (io_error == DM_ENDIO_REQUEUE)
803                         return;
804
805                 if ((bio->bi_opf & REQ_PREFLUSH) && bio->bi_iter.bi_size) {
806                         /*
807                          * Preflush done for flush with data, reissue
808                          * without REQ_PREFLUSH.
809                          */
810                         bio->bi_opf &= ~REQ_PREFLUSH;
811                         queue_io(md, bio);
812                 } else {
813                         /* done with normal IO or empty flush */
814                         trace_block_bio_complete(md->queue, bio, io_error);
815                         if (io_error)
816                                 bio->bi_error = io_error;
817                         bio_endio(bio);
818                 }
819         }
820 }
821
822 void disable_write_same(struct mapped_device *md)
823 {
824         struct queue_limits *limits = dm_get_queue_limits(md);
825
826         /* device doesn't really support WRITE SAME, disable it */
827         limits->max_write_same_sectors = 0;
828 }
829
830 static void clone_endio(struct bio *bio)
831 {
832         int error = bio->bi_error;
833         int r = error;
834         struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
835         struct dm_io *io = tio->io;
836         struct mapped_device *md = tio->io->md;
837         dm_endio_fn endio = tio->ti->type->end_io;
838
839         if (endio) {
840                 r = endio(tio->ti, bio, error);
841                 if (r < 0 || r == DM_ENDIO_REQUEUE)
842                         /*
843                          * error and requeue request are handled
844                          * in dec_pending().
845                          */
846                         error = r;
847                 else if (r == DM_ENDIO_INCOMPLETE)
848                         /* The target will handle the io */
849                         return;
850                 else if (r) {
851                         DMWARN("unimplemented target endio return value: %d", r);
852                         BUG();
853                 }
854         }
855
856         if (unlikely(r == -EREMOTEIO && (bio_op(bio) == REQ_OP_WRITE_SAME) &&
857                      !bdev_get_queue(bio->bi_bdev)->limits.max_write_same_sectors))
858                 disable_write_same(md);
859
860         free_tio(tio);
861         dec_pending(io, error);
862 }
863
864 /*
865  * Return maximum size of I/O possible at the supplied sector up to the current
866  * target boundary.
867  */
868 static sector_t max_io_len_target_boundary(sector_t sector, struct dm_target *ti)
869 {
870         sector_t target_offset = dm_target_offset(ti, sector);
871
872         return ti->len - target_offset;
873 }
874
875 static sector_t max_io_len(sector_t sector, struct dm_target *ti)
876 {
877         sector_t len = max_io_len_target_boundary(sector, ti);
878         sector_t offset, max_len;
879
880         /*
881          * Does the target need to split even further?
882          */
883         if (ti->max_io_len) {
884                 offset = dm_target_offset(ti, sector);
885                 if (unlikely(ti->max_io_len & (ti->max_io_len - 1)))
886                         max_len = sector_div(offset, ti->max_io_len);
887                 else
888                         max_len = offset & (ti->max_io_len - 1);
889                 max_len = ti->max_io_len - max_len;
890
891                 if (len > max_len)
892                         len = max_len;
893         }
894
895         return len;
896 }
897
898 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
899 {
900         if (len > UINT_MAX) {
901                 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
902                       (unsigned long long)len, UINT_MAX);
903                 ti->error = "Maximum size of target IO is too large";
904                 return -EINVAL;
905         }
906
907         ti->max_io_len = (uint32_t) len;
908
909         return 0;
910 }
911 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
912
913 static long dm_blk_direct_access(struct block_device *bdev, sector_t sector,
914                                  void **kaddr, pfn_t *pfn, long size)
915 {
916         struct mapped_device *md = bdev->bd_disk->private_data;
917         struct dm_table *map;
918         struct dm_target *ti;
919         int srcu_idx;
920         long len, ret = -EIO;
921
922         map = dm_get_live_table(md, &srcu_idx);
923         if (!map)
924                 goto out;
925
926         ti = dm_table_find_target(map, sector);
927         if (!dm_target_is_valid(ti))
928                 goto out;
929
930         len = max_io_len(sector, ti) << SECTOR_SHIFT;
931         size = min(len, size);
932
933         if (ti->type->direct_access)
934                 ret = ti->type->direct_access(ti, sector, kaddr, pfn, size);
935 out:
936         dm_put_live_table(md, srcu_idx);
937         return min(ret, size);
938 }
939
940 /*
941  * A target may call dm_accept_partial_bio only from the map routine.  It is
942  * allowed for all bio types except REQ_PREFLUSH.
943  *
944  * dm_accept_partial_bio informs the dm that the target only wants to process
945  * additional n_sectors sectors of the bio and the rest of the data should be
946  * sent in a next bio.
947  *
948  * A diagram that explains the arithmetics:
949  * +--------------------+---------------+-------+
950  * |         1          |       2       |   3   |
951  * +--------------------+---------------+-------+
952  *
953  * <-------------- *tio->len_ptr --------------->
954  *                      <------- bi_size ------->
955  *                      <-- n_sectors -->
956  *
957  * Region 1 was already iterated over with bio_advance or similar function.
958  *      (it may be empty if the target doesn't use bio_advance)
959  * Region 2 is the remaining bio size that the target wants to process.
960  *      (it may be empty if region 1 is non-empty, although there is no reason
961  *       to make it empty)
962  * The target requires that region 3 is to be sent in the next bio.
963  *
964  * If the target wants to receive multiple copies of the bio (via num_*bios, etc),
965  * the partially processed part (the sum of regions 1+2) must be the same for all
966  * copies of the bio.
967  */
968 void dm_accept_partial_bio(struct bio *bio, unsigned n_sectors)
969 {
970         struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
971         unsigned bi_size = bio->bi_iter.bi_size >> SECTOR_SHIFT;
972         BUG_ON(bio->bi_opf & REQ_PREFLUSH);
973         BUG_ON(bi_size > *tio->len_ptr);
974         BUG_ON(n_sectors > bi_size);
975         *tio->len_ptr -= bi_size - n_sectors;
976         bio->bi_iter.bi_size = n_sectors << SECTOR_SHIFT;
977 }
978 EXPORT_SYMBOL_GPL(dm_accept_partial_bio);
979
980 /*
981  * Flush current->bio_list when the target map method blocks.
982  * This fixes deadlocks in snapshot and possibly in other targets.
983  */
984 struct dm_offload {
985         struct blk_plug plug;
986         struct blk_plug_cb cb;
987 };
988
989 static void flush_current_bio_list(struct blk_plug_cb *cb, bool from_schedule)
990 {
991         struct dm_offload *o = container_of(cb, struct dm_offload, cb);
992         struct bio_list list;
993         struct bio *bio;
994         int i;
995
996         INIT_LIST_HEAD(&o->cb.list);
997
998         if (unlikely(!current->bio_list))
999                 return;
1000
1001         for (i = 0; i < 2; i++) {
1002                 list = current->bio_list[i];
1003                 bio_list_init(&current->bio_list[i]);
1004
1005                 while ((bio = bio_list_pop(&list))) {
1006                         struct bio_set *bs = bio->bi_pool;
1007                         if (unlikely(!bs) || bs == fs_bio_set) {
1008                                 bio_list_add(&current->bio_list[i], bio);
1009                                 continue;
1010                         }
1011
1012                         spin_lock(&bs->rescue_lock);
1013                         bio_list_add(&bs->rescue_list, bio);
1014                         queue_work(bs->rescue_workqueue, &bs->rescue_work);
1015                         spin_unlock(&bs->rescue_lock);
1016                 }
1017         }
1018 }
1019
1020 static void dm_offload_start(struct dm_offload *o)
1021 {
1022         blk_start_plug(&o->plug);
1023         o->cb.callback = flush_current_bio_list;
1024         list_add(&o->cb.list, &current->plug->cb_list);
1025 }
1026
1027 static void dm_offload_end(struct dm_offload *o)
1028 {
1029         list_del(&o->cb.list);
1030         blk_finish_plug(&o->plug);
1031 }
1032
1033 static void __map_bio(struct dm_target_io *tio)
1034 {
1035         int r;
1036         sector_t sector;
1037         struct dm_offload o;
1038         struct bio *clone = &tio->clone;
1039         struct dm_target *ti = tio->ti;
1040
1041         clone->bi_end_io = clone_endio;
1042
1043         /*
1044          * Map the clone.  If r == 0 we don't need to do
1045          * anything, the target has assumed ownership of
1046          * this io.
1047          */
1048         atomic_inc(&tio->io->io_count);
1049         sector = clone->bi_iter.bi_sector;
1050
1051         dm_offload_start(&o);
1052         r = ti->type->map(ti, clone);
1053         dm_offload_end(&o);
1054
1055         if (r == DM_MAPIO_REMAPPED) {
1056                 /* the bio has been remapped so dispatch it */
1057
1058                 trace_block_bio_remap(bdev_get_queue(clone->bi_bdev), clone,
1059                                       tio->io->bio->bi_bdev->bd_dev, sector);
1060
1061                 generic_make_request(clone);
1062         } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1063                 /* error the io and bail out, or requeue it if needed */
1064                 dec_pending(tio->io, r);
1065                 free_tio(tio);
1066         } else if (r != DM_MAPIO_SUBMITTED) {
1067                 DMWARN("unimplemented target map return value: %d", r);
1068                 BUG();
1069         }
1070 }
1071
1072 struct clone_info {
1073         struct mapped_device *md;
1074         struct dm_table *map;
1075         struct bio *bio;
1076         struct dm_io *io;
1077         sector_t sector;
1078         unsigned sector_count;
1079 };
1080
1081 static void bio_setup_sector(struct bio *bio, sector_t sector, unsigned len)
1082 {
1083         bio->bi_iter.bi_sector = sector;
1084         bio->bi_iter.bi_size = to_bytes(len);
1085 }
1086
1087 /*
1088  * Creates a bio that consists of range of complete bvecs.
1089  */
1090 static int clone_bio(struct dm_target_io *tio, struct bio *bio,
1091                      sector_t sector, unsigned len)
1092 {
1093         struct bio *clone = &tio->clone;
1094
1095         __bio_clone_fast(clone, bio);
1096
1097         if (bio_integrity(bio)) {
1098                 int r = bio_integrity_clone(clone, bio, GFP_NOIO);
1099                 if (r < 0)
1100                         return r;
1101         }
1102
1103         bio_advance(clone, to_bytes(sector - clone->bi_iter.bi_sector));
1104         clone->bi_iter.bi_size = to_bytes(len);
1105
1106         if (bio_integrity(bio))
1107                 bio_integrity_trim(clone, 0, len);
1108
1109         return 0;
1110 }
1111
1112 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1113                                       struct dm_target *ti,
1114                                       unsigned target_bio_nr)
1115 {
1116         struct dm_target_io *tio;
1117         struct bio *clone;
1118
1119         clone = bio_alloc_bioset(GFP_NOIO, 0, ci->md->bs);
1120         tio = container_of(clone, struct dm_target_io, clone);
1121
1122         tio->io = ci->io;
1123         tio->ti = ti;
1124         tio->target_bio_nr = target_bio_nr;
1125
1126         return tio;
1127 }
1128
1129 static void __clone_and_map_simple_bio(struct clone_info *ci,
1130                                        struct dm_target *ti,
1131                                        unsigned target_bio_nr, unsigned *len)
1132 {
1133         struct dm_target_io *tio = alloc_tio(ci, ti, target_bio_nr);
1134         struct bio *clone = &tio->clone;
1135
1136         tio->len_ptr = len;
1137
1138         __bio_clone_fast(clone, ci->bio);
1139         if (len)
1140                 bio_setup_sector(clone, ci->sector, *len);
1141
1142         __map_bio(tio);
1143 }
1144
1145 static void __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1146                                   unsigned num_bios, unsigned *len)
1147 {
1148         unsigned target_bio_nr;
1149
1150         for (target_bio_nr = 0; target_bio_nr < num_bios; target_bio_nr++)
1151                 __clone_and_map_simple_bio(ci, ti, target_bio_nr, len);
1152 }
1153
1154 static int __send_empty_flush(struct clone_info *ci)
1155 {
1156         unsigned target_nr = 0;
1157         struct dm_target *ti;
1158
1159         BUG_ON(bio_has_data(ci->bio));
1160         while ((ti = dm_table_get_target(ci->map, target_nr++)))
1161                 __send_duplicate_bios(ci, ti, ti->num_flush_bios, NULL);
1162
1163         return 0;
1164 }
1165
1166 static int __clone_and_map_data_bio(struct clone_info *ci, struct dm_target *ti,
1167                                      sector_t sector, unsigned *len)
1168 {
1169         struct bio *bio = ci->bio;
1170         struct dm_target_io *tio;
1171         unsigned target_bio_nr;
1172         unsigned num_target_bios = 1;
1173         int r = 0;
1174
1175         /*
1176          * Does the target want to receive duplicate copies of the bio?
1177          */
1178         if (bio_data_dir(bio) == WRITE && ti->num_write_bios)
1179                 num_target_bios = ti->num_write_bios(ti, bio);
1180
1181         for (target_bio_nr = 0; target_bio_nr < num_target_bios; target_bio_nr++) {
1182                 tio = alloc_tio(ci, ti, target_bio_nr);
1183                 tio->len_ptr = len;
1184                 r = clone_bio(tio, bio, sector, *len);
1185                 if (r < 0) {
1186                         free_tio(tio);
1187                         break;
1188                 }
1189                 __map_bio(tio);
1190         }
1191
1192         return r;
1193 }
1194
1195 typedef unsigned (*get_num_bios_fn)(struct dm_target *ti);
1196
1197 static unsigned get_num_discard_bios(struct dm_target *ti)
1198 {
1199         return ti->num_discard_bios;
1200 }
1201
1202 static unsigned get_num_write_same_bios(struct dm_target *ti)
1203 {
1204         return ti->num_write_same_bios;
1205 }
1206
1207 typedef bool (*is_split_required_fn)(struct dm_target *ti);
1208
1209 static bool is_split_required_for_discard(struct dm_target *ti)
1210 {
1211         return ti->split_discard_bios;
1212 }
1213
1214 static int __send_changing_extent_only(struct clone_info *ci,
1215                                        get_num_bios_fn get_num_bios,
1216                                        is_split_required_fn is_split_required)
1217 {
1218         struct dm_target *ti;
1219         unsigned len;
1220         unsigned num_bios;
1221
1222         do {
1223                 ti = dm_table_find_target(ci->map, ci->sector);
1224                 if (!dm_target_is_valid(ti))
1225                         return -EIO;
1226
1227                 /*
1228                  * Even though the device advertised support for this type of
1229                  * request, that does not mean every target supports it, and
1230                  * reconfiguration might also have changed that since the
1231                  * check was performed.
1232                  */
1233                 num_bios = get_num_bios ? get_num_bios(ti) : 0;
1234                 if (!num_bios)
1235                         return -EOPNOTSUPP;
1236
1237                 if (is_split_required && !is_split_required(ti))
1238                         len = min((sector_t)ci->sector_count, max_io_len_target_boundary(ci->sector, ti));
1239                 else
1240                         len = min((sector_t)ci->sector_count, max_io_len(ci->sector, ti));
1241
1242                 __send_duplicate_bios(ci, ti, num_bios, &len);
1243
1244                 ci->sector += len;
1245         } while (ci->sector_count -= len);
1246
1247         return 0;
1248 }
1249
1250 static int __send_discard(struct clone_info *ci)
1251 {
1252         return __send_changing_extent_only(ci, get_num_discard_bios,
1253                                            is_split_required_for_discard);
1254 }
1255
1256 static int __send_write_same(struct clone_info *ci)
1257 {
1258         return __send_changing_extent_only(ci, get_num_write_same_bios, NULL);
1259 }
1260
1261 /*
1262  * Select the correct strategy for processing a non-flush bio.
1263  */
1264 static int __split_and_process_non_flush(struct clone_info *ci)
1265 {
1266         struct bio *bio = ci->bio;
1267         struct dm_target *ti;
1268         unsigned len;
1269         int r;
1270
1271         if (unlikely(bio_op(bio) == REQ_OP_DISCARD))
1272                 return __send_discard(ci);
1273         else if (unlikely(bio_op(bio) == REQ_OP_WRITE_SAME))
1274                 return __send_write_same(ci);
1275
1276         ti = dm_table_find_target(ci->map, ci->sector);
1277         if (!dm_target_is_valid(ti))
1278                 return -EIO;
1279
1280         len = min_t(sector_t, max_io_len(ci->sector, ti), ci->sector_count);
1281
1282         r = __clone_and_map_data_bio(ci, ti, ci->sector, &len);
1283         if (r < 0)
1284                 return r;
1285
1286         ci->sector += len;
1287         ci->sector_count -= len;
1288
1289         return 0;
1290 }
1291
1292 /*
1293  * Entry point to split a bio into clones and submit them to the targets.
1294  */
1295 static void __split_and_process_bio(struct mapped_device *md,
1296                                     struct dm_table *map, struct bio *bio)
1297 {
1298         struct clone_info ci;
1299         int error = 0;
1300
1301         if (unlikely(!map)) {
1302                 bio_io_error(bio);
1303                 return;
1304         }
1305
1306         ci.map = map;
1307         ci.md = md;
1308         ci.io = alloc_io(md);
1309         ci.io->error = 0;
1310         atomic_set(&ci.io->io_count, 1);
1311         ci.io->bio = bio;
1312         ci.io->md = md;
1313         spin_lock_init(&ci.io->endio_lock);
1314         ci.sector = bio->bi_iter.bi_sector;
1315
1316         start_io_acct(ci.io);
1317
1318         if (bio->bi_opf & REQ_PREFLUSH) {
1319                 ci.bio = &ci.md->flush_bio;
1320                 ci.sector_count = 0;
1321                 error = __send_empty_flush(&ci);
1322                 /* dec_pending submits any data associated with flush */
1323         } else {
1324                 ci.bio = bio;
1325                 ci.sector_count = bio_sectors(bio);
1326                 while (ci.sector_count && !error)
1327                         error = __split_and_process_non_flush(&ci);
1328         }
1329
1330         /* drop the extra reference count */
1331         dec_pending(ci.io, error);
1332 }
1333 /*-----------------------------------------------------------------
1334  * CRUD END
1335  *---------------------------------------------------------------*/
1336
1337 /*
1338  * The request function that just remaps the bio built up by
1339  * dm_merge_bvec.
1340  */
1341 static blk_qc_t dm_make_request(struct request_queue *q, struct bio *bio)
1342 {
1343         int rw = bio_data_dir(bio);
1344         struct mapped_device *md = q->queuedata;
1345         int srcu_idx;
1346         struct dm_table *map;
1347
1348         map = dm_get_live_table(md, &srcu_idx);
1349
1350         generic_start_io_acct(rw, bio_sectors(bio), &dm_disk(md)->part0);
1351
1352         /* if we're suspended, we have to queue this io for later */
1353         if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
1354                 dm_put_live_table(md, srcu_idx);
1355
1356                 if (!(bio->bi_opf & REQ_RAHEAD))
1357                         queue_io(md, bio);
1358                 else
1359                         bio_io_error(bio);
1360                 return BLK_QC_T_NONE;
1361         }
1362
1363         __split_and_process_bio(md, map, bio);
1364         dm_put_live_table(md, srcu_idx);
1365         return BLK_QC_T_NONE;
1366 }
1367
1368 static int dm_any_congested(void *congested_data, int bdi_bits)
1369 {
1370         int r = bdi_bits;
1371         struct mapped_device *md = congested_data;
1372         struct dm_table *map;
1373
1374         if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
1375                 if (dm_request_based(md)) {
1376                         /*
1377                          * With request-based DM we only need to check the
1378                          * top-level queue for congestion.
1379                          */
1380                         r = md->queue->backing_dev_info.wb.state & bdi_bits;
1381                 } else {
1382                         map = dm_get_live_table_fast(md);
1383                         if (map)
1384                                 r = dm_table_any_congested(map, bdi_bits);
1385                         dm_put_live_table_fast(md);
1386                 }
1387         }
1388
1389         return r;
1390 }
1391
1392 /*-----------------------------------------------------------------
1393  * An IDR is used to keep track of allocated minor numbers.
1394  *---------------------------------------------------------------*/
1395 static void free_minor(int minor)
1396 {
1397         spin_lock(&_minor_lock);
1398         idr_remove(&_minor_idr, minor);
1399         spin_unlock(&_minor_lock);
1400 }
1401
1402 /*
1403  * See if the device with a specific minor # is free.
1404  */
1405 static int specific_minor(int minor)
1406 {
1407         int r;
1408
1409         if (minor >= (1 << MINORBITS))
1410                 return -EINVAL;
1411
1412         idr_preload(GFP_KERNEL);
1413         spin_lock(&_minor_lock);
1414
1415         r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
1416
1417         spin_unlock(&_minor_lock);
1418         idr_preload_end();
1419         if (r < 0)
1420                 return r == -ENOSPC ? -EBUSY : r;
1421         return 0;
1422 }
1423
1424 static int next_free_minor(int *minor)
1425 {
1426         int r;
1427
1428         idr_preload(GFP_KERNEL);
1429         spin_lock(&_minor_lock);
1430
1431         r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
1432
1433         spin_unlock(&_minor_lock);
1434         idr_preload_end();
1435         if (r < 0)
1436                 return r;
1437         *minor = r;
1438         return 0;
1439 }
1440
1441 static const struct block_device_operations dm_blk_dops;
1442
1443 static void dm_wq_work(struct work_struct *work);
1444
1445 void dm_init_md_queue(struct mapped_device *md)
1446 {
1447         /*
1448          * Request-based dm devices cannot be stacked on top of bio-based dm
1449          * devices.  The type of this dm device may not have been decided yet.
1450          * The type is decided at the first table loading time.
1451          * To prevent problematic device stacking, clear the queue flag
1452          * for request stacking support until then.
1453          *
1454          * This queue is new, so no concurrency on the queue_flags.
1455          */
1456         queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
1457
1458         /*
1459          * Initialize data that will only be used by a non-blk-mq DM queue
1460          * - must do so here (in alloc_dev callchain) before queue is used
1461          */
1462         md->queue->queuedata = md;
1463 }
1464
1465 void dm_init_normal_md_queue(struct mapped_device *md)
1466 {
1467         md->use_blk_mq = false;
1468         dm_init_md_queue(md);
1469
1470         /*
1471          * Initialize aspects of queue that aren't relevant for blk-mq
1472          */
1473         md->queue->backing_dev_info.congested_data = md;
1474         md->queue->backing_dev_info.congested_fn = dm_any_congested;
1475         blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
1476 }
1477
1478 static void cleanup_mapped_device(struct mapped_device *md)
1479 {
1480         if (md->wq)
1481                 destroy_workqueue(md->wq);
1482         if (md->kworker_task)
1483                 kthread_stop(md->kworker_task);
1484         mempool_destroy(md->io_pool);
1485         mempool_destroy(md->rq_pool);
1486         if (md->bs)
1487                 bioset_free(md->bs);
1488
1489         if (md->disk) {
1490                 spin_lock(&_minor_lock);
1491                 md->disk->private_data = NULL;
1492                 spin_unlock(&_minor_lock);
1493                 del_gendisk(md->disk);
1494                 put_disk(md->disk);
1495         }
1496
1497         if (md->queue)
1498                 blk_cleanup_queue(md->queue);
1499
1500         cleanup_srcu_struct(&md->io_barrier);
1501
1502         if (md->bdev) {
1503                 bdput(md->bdev);
1504                 md->bdev = NULL;
1505         }
1506
1507         dm_mq_cleanup_mapped_device(md);
1508 }
1509
1510 /*
1511  * Allocate and initialise a blank device with a given minor.
1512  */
1513 static struct mapped_device *alloc_dev(int minor)
1514 {
1515         int r, numa_node_id = dm_get_numa_node();
1516         struct mapped_device *md;
1517         void *old_md;
1518
1519         md = vzalloc_node(sizeof(*md), numa_node_id);
1520         if (!md) {
1521                 DMWARN("unable to allocate device, out of memory.");
1522                 return NULL;
1523         }
1524
1525         if (!try_module_get(THIS_MODULE))
1526                 goto bad_module_get;
1527
1528         /* get a minor number for the dev */
1529         if (minor == DM_ANY_MINOR)
1530                 r = next_free_minor(&minor);
1531         else
1532                 r = specific_minor(minor);
1533         if (r < 0)
1534                 goto bad_minor;
1535
1536         r = init_srcu_struct(&md->io_barrier);
1537         if (r < 0)
1538                 goto bad_io_barrier;
1539
1540         md->numa_node_id = numa_node_id;
1541         md->use_blk_mq = dm_use_blk_mq_default();
1542         md->init_tio_pdu = false;
1543         md->type = DM_TYPE_NONE;
1544         mutex_init(&md->suspend_lock);
1545         mutex_init(&md->type_lock);
1546         mutex_init(&md->table_devices_lock);
1547         spin_lock_init(&md->deferred_lock);
1548         atomic_set(&md->holders, 1);
1549         atomic_set(&md->open_count, 0);
1550         atomic_set(&md->event_nr, 0);
1551         atomic_set(&md->uevent_seq, 0);
1552         INIT_LIST_HEAD(&md->uevent_list);
1553         INIT_LIST_HEAD(&md->table_devices);
1554         spin_lock_init(&md->uevent_lock);
1555
1556         md->queue = blk_alloc_queue_node(GFP_KERNEL, numa_node_id);
1557         if (!md->queue)
1558                 goto bad;
1559
1560         dm_init_md_queue(md);
1561         /*
1562          * default to bio-based required ->make_request_fn until DM
1563          * table is loaded and md->type established. If request-based
1564          * table is loaded: blk-mq will override accordingly.
1565          */
1566         blk_queue_make_request(md->queue, dm_make_request);
1567
1568         md->disk = alloc_disk_node(1, numa_node_id);
1569         if (!md->disk)
1570                 goto bad;
1571
1572         atomic_set(&md->pending[0], 0);
1573         atomic_set(&md->pending[1], 0);
1574         init_waitqueue_head(&md->wait);
1575         INIT_WORK(&md->work, dm_wq_work);
1576         init_waitqueue_head(&md->eventq);
1577         init_completion(&md->kobj_holder.completion);
1578         md->kworker_task = NULL;
1579
1580         md->disk->major = _major;
1581         md->disk->first_minor = minor;
1582         md->disk->fops = &dm_blk_dops;
1583         md->disk->queue = md->queue;
1584         md->disk->private_data = md;
1585         sprintf(md->disk->disk_name, "dm-%d", minor);
1586         add_disk(md->disk);
1587         format_dev_t(md->name, MKDEV(_major, minor));
1588
1589         md->wq = alloc_workqueue("kdmflush", WQ_MEM_RECLAIM, 0);
1590         if (!md->wq)
1591                 goto bad;
1592
1593         md->bdev = bdget_disk(md->disk, 0);
1594         if (!md->bdev)
1595                 goto bad;
1596
1597         bio_init(&md->flush_bio);
1598         md->flush_bio.bi_bdev = md->bdev;
1599         bio_set_op_attrs(&md->flush_bio, REQ_OP_WRITE, WRITE_FLUSH);
1600
1601         dm_stats_init(&md->stats);
1602
1603         /* Populate the mapping, nobody knows we exist yet */
1604         spin_lock(&_minor_lock);
1605         old_md = idr_replace(&_minor_idr, md, minor);
1606         spin_unlock(&_minor_lock);
1607
1608         BUG_ON(old_md != MINOR_ALLOCED);
1609
1610         return md;
1611
1612 bad:
1613         cleanup_mapped_device(md);
1614 bad_io_barrier:
1615         free_minor(minor);
1616 bad_minor:
1617         module_put(THIS_MODULE);
1618 bad_module_get:
1619         kvfree(md);
1620         return NULL;
1621 }
1622
1623 static void unlock_fs(struct mapped_device *md);
1624
1625 static void free_dev(struct mapped_device *md)
1626 {
1627         int minor = MINOR(disk_devt(md->disk));
1628
1629         unlock_fs(md);
1630
1631         cleanup_mapped_device(md);
1632
1633         free_table_devices(&md->table_devices);
1634         dm_stats_cleanup(&md->stats);
1635         free_minor(minor);
1636
1637         module_put(THIS_MODULE);
1638         kvfree(md);
1639 }
1640
1641 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
1642 {
1643         struct dm_md_mempools *p = dm_table_get_md_mempools(t);
1644
1645         if (md->bs) {
1646                 /* The md already has necessary mempools. */
1647                 if (dm_table_bio_based(t)) {
1648                         /*
1649                          * Reload bioset because front_pad may have changed
1650                          * because a different table was loaded.
1651                          */
1652                         bioset_free(md->bs);
1653                         md->bs = p->bs;
1654                         p->bs = NULL;
1655                 }
1656                 /*
1657                  * There's no need to reload with request-based dm
1658                  * because the size of front_pad doesn't change.
1659                  * Note for future: If you are to reload bioset,
1660                  * prep-ed requests in the queue may refer
1661                  * to bio from the old bioset, so you must walk
1662                  * through the queue to unprep.
1663                  */
1664                 goto out;
1665         }
1666
1667         BUG_ON(!p || md->io_pool || md->rq_pool || md->bs);
1668
1669         md->io_pool = p->io_pool;
1670         p->io_pool = NULL;
1671         md->rq_pool = p->rq_pool;
1672         p->rq_pool = NULL;
1673         md->bs = p->bs;
1674         p->bs = NULL;
1675
1676 out:
1677         /* mempool bind completed, no longer need any mempools in the table */
1678         dm_table_free_md_mempools(t);
1679 }
1680
1681 /*
1682  * Bind a table to the device.
1683  */
1684 static void event_callback(void *context)
1685 {
1686         unsigned long flags;
1687         LIST_HEAD(uevents);
1688         struct mapped_device *md = (struct mapped_device *) context;
1689
1690         spin_lock_irqsave(&md->uevent_lock, flags);
1691         list_splice_init(&md->uevent_list, &uevents);
1692         spin_unlock_irqrestore(&md->uevent_lock, flags);
1693
1694         dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
1695
1696         atomic_inc(&md->event_nr);
1697         wake_up(&md->eventq);
1698 }
1699
1700 /*
1701  * Protected by md->suspend_lock obtained by dm_swap_table().
1702  */
1703 static void __set_size(struct mapped_device *md, sector_t size)
1704 {
1705         set_capacity(md->disk, size);
1706
1707         i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
1708 }
1709
1710 /*
1711  * Returns old map, which caller must destroy.
1712  */
1713 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
1714                                struct queue_limits *limits)
1715 {
1716         struct dm_table *old_map;
1717         struct request_queue *q = md->queue;
1718         sector_t size;
1719
1720         lockdep_assert_held(&md->suspend_lock);
1721
1722         size = dm_table_get_size(t);
1723
1724         /*
1725          * Wipe any geometry if the size of the table changed.
1726          */
1727         if (size != dm_get_size(md))
1728                 memset(&md->geometry, 0, sizeof(md->geometry));
1729
1730         __set_size(md, size);
1731
1732         dm_table_event_callback(t, event_callback, md);
1733
1734         /*
1735          * The queue hasn't been stopped yet, if the old table type wasn't
1736          * for request-based during suspension.  So stop it to prevent
1737          * I/O mapping before resume.
1738          * This must be done before setting the queue restrictions,
1739          * because request-based dm may be run just after the setting.
1740          */
1741         if (dm_table_request_based(t)) {
1742                 dm_stop_queue(q);
1743                 /*
1744                  * Leverage the fact that request-based DM targets are
1745                  * immutable singletons and establish md->immutable_target
1746                  * - used to optimize both dm_request_fn and dm_mq_queue_rq
1747                  */
1748                 md->immutable_target = dm_table_get_immutable_target(t);
1749         }
1750
1751         __bind_mempools(md, t);
1752
1753         old_map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
1754         rcu_assign_pointer(md->map, (void *)t);
1755         md->immutable_target_type = dm_table_get_immutable_target_type(t);
1756
1757         dm_table_set_restrictions(t, q, limits);
1758         if (old_map)
1759                 dm_sync_table(md);
1760
1761         return old_map;
1762 }
1763
1764 /*
1765  * Returns unbound table for the caller to free.
1766  */
1767 static struct dm_table *__unbind(struct mapped_device *md)
1768 {
1769         struct dm_table *map = rcu_dereference_protected(md->map, 1);
1770
1771         if (!map)
1772                 return NULL;
1773
1774         dm_table_event_callback(map, NULL, NULL);
1775         RCU_INIT_POINTER(md->map, NULL);
1776         dm_sync_table(md);
1777
1778         return map;
1779 }
1780
1781 /*
1782  * Constructor for a new device.
1783  */
1784 int dm_create(int minor, struct mapped_device **result)
1785 {
1786         struct mapped_device *md;
1787
1788         md = alloc_dev(minor);
1789         if (!md)
1790                 return -ENXIO;
1791
1792         dm_sysfs_init(md);
1793
1794         *result = md;
1795         return 0;
1796 }
1797
1798 /*
1799  * Functions to manage md->type.
1800  * All are required to hold md->type_lock.
1801  */
1802 void dm_lock_md_type(struct mapped_device *md)
1803 {
1804         mutex_lock(&md->type_lock);
1805 }
1806
1807 void dm_unlock_md_type(struct mapped_device *md)
1808 {
1809         mutex_unlock(&md->type_lock);
1810 }
1811
1812 void dm_set_md_type(struct mapped_device *md, unsigned type)
1813 {
1814         BUG_ON(!mutex_is_locked(&md->type_lock));
1815         md->type = type;
1816 }
1817
1818 unsigned dm_get_md_type(struct mapped_device *md)
1819 {
1820         return md->type;
1821 }
1822
1823 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
1824 {
1825         return md->immutable_target_type;
1826 }
1827
1828 /*
1829  * The queue_limits are only valid as long as you have a reference
1830  * count on 'md'.
1831  */
1832 struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
1833 {
1834         BUG_ON(!atomic_read(&md->holders));
1835         return &md->queue->limits;
1836 }
1837 EXPORT_SYMBOL_GPL(dm_get_queue_limits);
1838
1839 /*
1840  * Setup the DM device's queue based on md's type
1841  */
1842 int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t)
1843 {
1844         int r;
1845         unsigned type = dm_get_md_type(md);
1846
1847         switch (type) {
1848         case DM_TYPE_REQUEST_BASED:
1849                 r = dm_old_init_request_queue(md);
1850                 if (r) {
1851                         DMERR("Cannot initialize queue for request-based mapped device");
1852                         return r;
1853                 }
1854                 break;
1855         case DM_TYPE_MQ_REQUEST_BASED:
1856                 r = dm_mq_init_request_queue(md, t);
1857                 if (r) {
1858                         DMERR("Cannot initialize queue for request-based dm-mq mapped device");
1859                         return r;
1860                 }
1861                 break;
1862         case DM_TYPE_BIO_BASED:
1863         case DM_TYPE_DAX_BIO_BASED:
1864                 dm_init_normal_md_queue(md);
1865                 /*
1866                  * DM handles splitting bios as needed.  Free the bio_split bioset
1867                  * since it won't be used (saves 1 process per bio-based DM device).
1868                  */
1869                 bioset_free(md->queue->bio_split);
1870                 md->queue->bio_split = NULL;
1871
1872                 if (type == DM_TYPE_DAX_BIO_BASED)
1873                         queue_flag_set_unlocked(QUEUE_FLAG_DAX, md->queue);
1874                 break;
1875         }
1876
1877         return 0;
1878 }
1879
1880 struct mapped_device *dm_get_md(dev_t dev)
1881 {
1882         struct mapped_device *md;
1883         unsigned minor = MINOR(dev);
1884
1885         if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
1886                 return NULL;
1887
1888         spin_lock(&_minor_lock);
1889
1890         md = idr_find(&_minor_idr, minor);
1891         if (md) {
1892                 if ((md == MINOR_ALLOCED ||
1893                      (MINOR(disk_devt(dm_disk(md))) != minor) ||
1894                      dm_deleting_md(md) ||
1895                      test_bit(DMF_FREEING, &md->flags))) {
1896                         md = NULL;
1897                         goto out;
1898                 }
1899                 dm_get(md);
1900         }
1901
1902 out:
1903         spin_unlock(&_minor_lock);
1904
1905         return md;
1906 }
1907 EXPORT_SYMBOL_GPL(dm_get_md);
1908
1909 void *dm_get_mdptr(struct mapped_device *md)
1910 {
1911         return md->interface_ptr;
1912 }
1913
1914 void dm_set_mdptr(struct mapped_device *md, void *ptr)
1915 {
1916         md->interface_ptr = ptr;
1917 }
1918
1919 void dm_get(struct mapped_device *md)
1920 {
1921         atomic_inc(&md->holders);
1922         BUG_ON(test_bit(DMF_FREEING, &md->flags));
1923 }
1924
1925 int dm_hold(struct mapped_device *md)
1926 {
1927         spin_lock(&_minor_lock);
1928         if (test_bit(DMF_FREEING, &md->flags)) {
1929                 spin_unlock(&_minor_lock);
1930                 return -EBUSY;
1931         }
1932         dm_get(md);
1933         spin_unlock(&_minor_lock);
1934         return 0;
1935 }
1936 EXPORT_SYMBOL_GPL(dm_hold);
1937
1938 const char *dm_device_name(struct mapped_device *md)
1939 {
1940         return md->name;
1941 }
1942 EXPORT_SYMBOL_GPL(dm_device_name);
1943
1944 static void __dm_destroy(struct mapped_device *md, bool wait)
1945 {
1946         struct request_queue *q = dm_get_md_queue(md);
1947         struct dm_table *map;
1948         int srcu_idx;
1949
1950         might_sleep();
1951
1952         spin_lock(&_minor_lock);
1953         idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
1954         set_bit(DMF_FREEING, &md->flags);
1955         spin_unlock(&_minor_lock);
1956
1957         blk_set_queue_dying(q);
1958
1959         if (dm_request_based(md) && md->kworker_task)
1960                 kthread_flush_worker(&md->kworker);
1961
1962         /*
1963          * Take suspend_lock so that presuspend and postsuspend methods
1964          * do not race with internal suspend.
1965          */
1966         mutex_lock(&md->suspend_lock);
1967         map = dm_get_live_table(md, &srcu_idx);
1968         if (!dm_suspended_md(md)) {
1969                 dm_table_presuspend_targets(map);
1970                 dm_table_postsuspend_targets(map);
1971         }
1972         /* dm_put_live_table must be before msleep, otherwise deadlock is possible */
1973         dm_put_live_table(md, srcu_idx);
1974         mutex_unlock(&md->suspend_lock);
1975
1976         /*
1977          * Rare, but there may be I/O requests still going to complete,
1978          * for example.  Wait for all references to disappear.
1979          * No one should increment the reference count of the mapped_device,
1980          * after the mapped_device state becomes DMF_FREEING.
1981          */
1982         if (wait)
1983                 while (atomic_read(&md->holders))
1984                         msleep(1);
1985         else if (atomic_read(&md->holders))
1986                 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
1987                        dm_device_name(md), atomic_read(&md->holders));
1988
1989         dm_sysfs_exit(md);
1990         dm_table_destroy(__unbind(md));
1991         free_dev(md);
1992 }
1993
1994 void dm_destroy(struct mapped_device *md)
1995 {
1996         __dm_destroy(md, true);
1997 }
1998
1999 void dm_destroy_immediate(struct mapped_device *md)
2000 {
2001         __dm_destroy(md, false);
2002 }
2003
2004 void dm_put(struct mapped_device *md)
2005 {
2006         atomic_dec(&md->holders);
2007 }
2008 EXPORT_SYMBOL_GPL(dm_put);
2009
2010 static int dm_wait_for_completion(struct mapped_device *md, long task_state)
2011 {
2012         int r = 0;
2013         DEFINE_WAIT(wait);
2014
2015         while (1) {
2016                 prepare_to_wait(&md->wait, &wait, task_state);
2017
2018                 if (!md_in_flight(md))
2019                         break;
2020
2021                 if (signal_pending_state(task_state, current)) {
2022                         r = -EINTR;
2023                         break;
2024                 }
2025
2026                 io_schedule();
2027         }
2028         finish_wait(&md->wait, &wait);
2029
2030         smp_rmb(); /* paired with atomic_dec_return in end_io_acct */
2031
2032         return r;
2033 }
2034
2035 /*
2036  * Process the deferred bios
2037  */
2038 static void dm_wq_work(struct work_struct *work)
2039 {
2040         struct mapped_device *md = container_of(work, struct mapped_device,
2041                                                 work);
2042         struct bio *c;
2043         int srcu_idx;
2044         struct dm_table *map;
2045
2046         map = dm_get_live_table(md, &srcu_idx);
2047
2048         while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2049                 spin_lock_irq(&md->deferred_lock);
2050                 c = bio_list_pop(&md->deferred);
2051                 spin_unlock_irq(&md->deferred_lock);
2052
2053                 if (!c)
2054                         break;
2055
2056                 if (dm_request_based(md))
2057                         generic_make_request(c);
2058                 else
2059                         __split_and_process_bio(md, map, c);
2060         }
2061
2062         dm_put_live_table(md, srcu_idx);
2063 }
2064
2065 static void dm_queue_flush(struct mapped_device *md)
2066 {
2067         clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2068         smp_mb__after_atomic();
2069         queue_work(md->wq, &md->work);
2070 }
2071
2072 /*
2073  * Swap in a new table, returning the old one for the caller to destroy.
2074  */
2075 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
2076 {
2077         struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
2078         struct queue_limits limits;
2079         int r;
2080
2081         mutex_lock(&md->suspend_lock);
2082
2083         /* device must be suspended */
2084         if (!dm_suspended_md(md))
2085                 goto out;
2086
2087         /*
2088          * If the new table has no data devices, retain the existing limits.
2089          * This helps multipath with queue_if_no_path if all paths disappear,
2090          * then new I/O is queued based on these limits, and then some paths
2091          * reappear.
2092          */
2093         if (dm_table_has_no_data_devices(table)) {
2094                 live_map = dm_get_live_table_fast(md);
2095                 if (live_map)
2096                         limits = md->queue->limits;
2097                 dm_put_live_table_fast(md);
2098         }
2099
2100         if (!live_map) {
2101                 r = dm_calculate_queue_limits(table, &limits);
2102                 if (r) {
2103                         map = ERR_PTR(r);
2104                         goto out;
2105                 }
2106         }
2107
2108         map = __bind(md, table, &limits);
2109
2110 out:
2111         mutex_unlock(&md->suspend_lock);
2112         return map;
2113 }
2114
2115 /*
2116  * Functions to lock and unlock any filesystem running on the
2117  * device.
2118  */
2119 static int lock_fs(struct mapped_device *md)
2120 {
2121         int r;
2122
2123         WARN_ON(md->frozen_sb);
2124
2125         md->frozen_sb = freeze_bdev(md->bdev);
2126         if (IS_ERR(md->frozen_sb)) {
2127                 r = PTR_ERR(md->frozen_sb);
2128                 md->frozen_sb = NULL;
2129                 return r;
2130         }
2131
2132         set_bit(DMF_FROZEN, &md->flags);
2133
2134         return 0;
2135 }
2136
2137 static void unlock_fs(struct mapped_device *md)
2138 {
2139         if (!test_bit(DMF_FROZEN, &md->flags))
2140                 return;
2141
2142         thaw_bdev(md->bdev, md->frozen_sb);
2143         md->frozen_sb = NULL;
2144         clear_bit(DMF_FROZEN, &md->flags);
2145 }
2146
2147 /*
2148  * @suspend_flags: DM_SUSPEND_LOCKFS_FLAG and/or DM_SUSPEND_NOFLUSH_FLAG
2149  * @task_state: e.g. TASK_INTERRUPTIBLE or TASK_UNINTERRUPTIBLE
2150  * @dmf_suspended_flag: DMF_SUSPENDED or DMF_SUSPENDED_INTERNALLY
2151  *
2152  * If __dm_suspend returns 0, the device is completely quiescent
2153  * now. There is no request-processing activity. All new requests
2154  * are being added to md->deferred list.
2155  *
2156  * Caller must hold md->suspend_lock
2157  */
2158 static int __dm_suspend(struct mapped_device *md, struct dm_table *map,
2159                         unsigned suspend_flags, long task_state,
2160                         int dmf_suspended_flag)
2161 {
2162         bool do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG;
2163         bool noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG;
2164         int r;
2165
2166         lockdep_assert_held(&md->suspend_lock);
2167
2168         /*
2169          * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
2170          * This flag is cleared before dm_suspend returns.
2171          */
2172         if (noflush)
2173                 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2174
2175         /*
2176          * This gets reverted if there's an error later and the targets
2177          * provide the .presuspend_undo hook.
2178          */
2179         dm_table_presuspend_targets(map);
2180
2181         /*
2182          * Flush I/O to the device.
2183          * Any I/O submitted after lock_fs() may not be flushed.
2184          * noflush takes precedence over do_lockfs.
2185          * (lock_fs() flushes I/Os and waits for them to complete.)
2186          */
2187         if (!noflush && do_lockfs) {
2188                 r = lock_fs(md);
2189                 if (r) {
2190                         dm_table_presuspend_undo_targets(map);
2191                         return r;
2192                 }
2193         }
2194
2195         /*
2196          * Here we must make sure that no processes are submitting requests
2197          * to target drivers i.e. no one may be executing
2198          * __split_and_process_bio. This is called from dm_request and
2199          * dm_wq_work.
2200          *
2201          * To get all processes out of __split_and_process_bio in dm_request,
2202          * we take the write lock. To prevent any process from reentering
2203          * __split_and_process_bio from dm_request and quiesce the thread
2204          * (dm_wq_work), we set BMF_BLOCK_IO_FOR_SUSPEND and call
2205          * flush_workqueue(md->wq).
2206          */
2207         set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2208         if (map)
2209                 synchronize_srcu(&md->io_barrier);
2210
2211         /*
2212          * Stop md->queue before flushing md->wq in case request-based
2213          * dm defers requests to md->wq from md->queue.
2214          */
2215         if (dm_request_based(md)) {
2216                 dm_stop_queue(md->queue);
2217                 if (md->kworker_task)
2218                         kthread_flush_worker(&md->kworker);
2219         }
2220
2221         flush_workqueue(md->wq);
2222
2223         /*
2224          * At this point no more requests are entering target request routines.
2225          * We call dm_wait_for_completion to wait for all existing requests
2226          * to finish.
2227          */
2228         r = dm_wait_for_completion(md, task_state);
2229         if (!r)
2230                 set_bit(dmf_suspended_flag, &md->flags);
2231
2232         if (noflush)
2233                 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2234         if (map)
2235                 synchronize_srcu(&md->io_barrier);
2236
2237         /* were we interrupted ? */
2238         if (r < 0) {
2239                 dm_queue_flush(md);
2240
2241                 if (dm_request_based(md))
2242                         dm_start_queue(md->queue);
2243
2244                 unlock_fs(md);
2245                 dm_table_presuspend_undo_targets(map);
2246                 /* pushback list is already flushed, so skip flush */
2247         }
2248
2249         return r;
2250 }
2251
2252 /*
2253  * We need to be able to change a mapping table under a mounted
2254  * filesystem.  For example we might want to move some data in
2255  * the background.  Before the table can be swapped with
2256  * dm_bind_table, dm_suspend must be called to flush any in
2257  * flight bios and ensure that any further io gets deferred.
2258  */
2259 /*
2260  * Suspend mechanism in request-based dm.
2261  *
2262  * 1. Flush all I/Os by lock_fs() if needed.
2263  * 2. Stop dispatching any I/O by stopping the request_queue.
2264  * 3. Wait for all in-flight I/Os to be completed or requeued.
2265  *
2266  * To abort suspend, start the request_queue.
2267  */
2268 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
2269 {
2270         struct dm_table *map = NULL;
2271         int r = 0;
2272
2273 retry:
2274         mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
2275
2276         if (dm_suspended_md(md)) {
2277                 r = -EINVAL;
2278                 goto out_unlock;
2279         }
2280
2281         if (dm_suspended_internally_md(md)) {
2282                 /* already internally suspended, wait for internal resume */
2283                 mutex_unlock(&md->suspend_lock);
2284                 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
2285                 if (r)
2286                         return r;
2287                 goto retry;
2288         }
2289
2290         map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2291
2292         r = __dm_suspend(md, map, suspend_flags, TASK_INTERRUPTIBLE, DMF_SUSPENDED);
2293         if (r)
2294                 goto out_unlock;
2295
2296         dm_table_postsuspend_targets(map);
2297
2298 out_unlock:
2299         mutex_unlock(&md->suspend_lock);
2300         return r;
2301 }
2302
2303 static int __dm_resume(struct mapped_device *md, struct dm_table *map)
2304 {
2305         if (map) {
2306                 int r = dm_table_resume_targets(map);
2307                 if (r)
2308                         return r;
2309         }
2310
2311         dm_queue_flush(md);
2312
2313         /*
2314          * Flushing deferred I/Os must be done after targets are resumed
2315          * so that mapping of targets can work correctly.
2316          * Request-based dm is queueing the deferred I/Os in its request_queue.
2317          */
2318         if (dm_request_based(md))
2319                 dm_start_queue(md->queue);
2320
2321         unlock_fs(md);
2322
2323         return 0;
2324 }
2325
2326 int dm_resume(struct mapped_device *md)
2327 {
2328         int r;
2329         struct dm_table *map = NULL;
2330
2331 retry:
2332         r = -EINVAL;
2333         mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
2334
2335         if (!dm_suspended_md(md))
2336                 goto out;
2337
2338         if (dm_suspended_internally_md(md)) {
2339                 /* already internally suspended, wait for internal resume */
2340                 mutex_unlock(&md->suspend_lock);
2341                 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
2342                 if (r)
2343                         return r;
2344                 goto retry;
2345         }
2346
2347         map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2348         if (!map || !dm_table_get_size(map))
2349                 goto out;
2350
2351         r = __dm_resume(md, map);
2352         if (r)
2353                 goto out;
2354
2355         clear_bit(DMF_SUSPENDED, &md->flags);
2356 out:
2357         mutex_unlock(&md->suspend_lock);
2358
2359         return r;
2360 }
2361
2362 /*
2363  * Internal suspend/resume works like userspace-driven suspend. It waits
2364  * until all bios finish and prevents issuing new bios to the target drivers.
2365  * It may be used only from the kernel.
2366  */
2367
2368 static void __dm_internal_suspend(struct mapped_device *md, unsigned suspend_flags)
2369 {
2370         struct dm_table *map = NULL;
2371
2372         if (md->internal_suspend_count++)
2373                 return; /* nested internal suspend */
2374
2375         if (dm_suspended_md(md)) {
2376                 set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
2377                 return; /* nest suspend */
2378         }
2379
2380         map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2381
2382         /*
2383          * Using TASK_UNINTERRUPTIBLE because only NOFLUSH internal suspend is
2384          * supported.  Properly supporting a TASK_INTERRUPTIBLE internal suspend
2385          * would require changing .presuspend to return an error -- avoid this
2386          * until there is a need for more elaborate variants of internal suspend.
2387          */
2388         (void) __dm_suspend(md, map, suspend_flags, TASK_UNINTERRUPTIBLE,
2389                             DMF_SUSPENDED_INTERNALLY);
2390
2391         dm_table_postsuspend_targets(map);
2392 }
2393
2394 static void __dm_internal_resume(struct mapped_device *md)
2395 {
2396         BUG_ON(!md->internal_suspend_count);
2397
2398         if (--md->internal_suspend_count)
2399                 return; /* resume from nested internal suspend */
2400
2401         if (dm_suspended_md(md))
2402                 goto done; /* resume from nested suspend */
2403
2404         /*
2405          * NOTE: existing callers don't need to call dm_table_resume_targets
2406          * (which may fail -- so best to avoid it for now by passing NULL map)
2407          */
2408         (void) __dm_resume(md, NULL);
2409
2410 done:
2411         clear_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
2412         smp_mb__after_atomic();
2413         wake_up_bit(&md->flags, DMF_SUSPENDED_INTERNALLY);
2414 }
2415
2416 void dm_internal_suspend_noflush(struct mapped_device *md)
2417 {
2418         mutex_lock(&md->suspend_lock);
2419         __dm_internal_suspend(md, DM_SUSPEND_NOFLUSH_FLAG);
2420         mutex_unlock(&md->suspend_lock);
2421 }
2422 EXPORT_SYMBOL_GPL(dm_internal_suspend_noflush);
2423
2424 void dm_internal_resume(struct mapped_device *md)
2425 {
2426         mutex_lock(&md->suspend_lock);
2427         __dm_internal_resume(md);
2428         mutex_unlock(&md->suspend_lock);
2429 }
2430 EXPORT_SYMBOL_GPL(dm_internal_resume);
2431
2432 /*
2433  * Fast variants of internal suspend/resume hold md->suspend_lock,
2434  * which prevents interaction with userspace-driven suspend.
2435  */
2436
2437 void dm_internal_suspend_fast(struct mapped_device *md)
2438 {
2439         mutex_lock(&md->suspend_lock);
2440         if (dm_suspended_md(md) || dm_suspended_internally_md(md))
2441                 return;
2442
2443         set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2444         synchronize_srcu(&md->io_barrier);
2445         flush_workqueue(md->wq);
2446         dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
2447 }
2448 EXPORT_SYMBOL_GPL(dm_internal_suspend_fast);
2449
2450 void dm_internal_resume_fast(struct mapped_device *md)
2451 {
2452         if (dm_suspended_md(md) || dm_suspended_internally_md(md))
2453                 goto done;
2454
2455         dm_queue_flush(md);
2456
2457 done:
2458         mutex_unlock(&md->suspend_lock);
2459 }
2460 EXPORT_SYMBOL_GPL(dm_internal_resume_fast);
2461
2462 /*-----------------------------------------------------------------
2463  * Event notification.
2464  *---------------------------------------------------------------*/
2465 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
2466                        unsigned cookie)
2467 {
2468         char udev_cookie[DM_COOKIE_LENGTH];
2469         char *envp[] = { udev_cookie, NULL };
2470
2471         if (!cookie)
2472                 return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
2473         else {
2474                 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
2475                          DM_COOKIE_ENV_VAR_NAME, cookie);
2476                 return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
2477                                           action, envp);
2478         }
2479 }
2480
2481 uint32_t dm_next_uevent_seq(struct mapped_device *md)
2482 {
2483         return atomic_add_return(1, &md->uevent_seq);
2484 }
2485
2486 uint32_t dm_get_event_nr(struct mapped_device *md)
2487 {
2488         return atomic_read(&md->event_nr);
2489 }
2490
2491 int dm_wait_event(struct mapped_device *md, int event_nr)
2492 {
2493         return wait_event_interruptible(md->eventq,
2494                         (event_nr != atomic_read(&md->event_nr)));
2495 }
2496
2497 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
2498 {
2499         unsigned long flags;
2500
2501         spin_lock_irqsave(&md->uevent_lock, flags);
2502         list_add(elist, &md->uevent_list);
2503         spin_unlock_irqrestore(&md->uevent_lock, flags);
2504 }
2505
2506 /*
2507  * The gendisk is only valid as long as you have a reference
2508  * count on 'md'.
2509  */
2510 struct gendisk *dm_disk(struct mapped_device *md)
2511 {
2512         return md->disk;
2513 }
2514 EXPORT_SYMBOL_GPL(dm_disk);
2515
2516 struct kobject *dm_kobject(struct mapped_device *md)
2517 {
2518         return &md->kobj_holder.kobj;
2519 }
2520
2521 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
2522 {
2523         struct mapped_device *md;
2524
2525         md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
2526
2527         spin_lock(&_minor_lock);
2528         if (test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
2529                 md = NULL;
2530                 goto out;
2531         }
2532         dm_get(md);
2533 out:
2534         spin_unlock(&_minor_lock);
2535
2536         return md;
2537 }
2538
2539 int dm_suspended_md(struct mapped_device *md)
2540 {
2541         return test_bit(DMF_SUSPENDED, &md->flags);
2542 }
2543
2544 int dm_suspended_internally_md(struct mapped_device *md)
2545 {
2546         return test_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
2547 }
2548
2549 int dm_test_deferred_remove_flag(struct mapped_device *md)
2550 {
2551         return test_bit(DMF_DEFERRED_REMOVE, &md->flags);
2552 }
2553
2554 int dm_suspended(struct dm_target *ti)
2555 {
2556         return dm_suspended_md(dm_table_get_md(ti->table));
2557 }
2558 EXPORT_SYMBOL_GPL(dm_suspended);
2559
2560 int dm_noflush_suspending(struct dm_target *ti)
2561 {
2562         return __noflush_suspending(dm_table_get_md(ti->table));
2563 }
2564 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
2565
2566 struct dm_md_mempools *dm_alloc_md_mempools(struct mapped_device *md, unsigned type,
2567                                             unsigned integrity, unsigned per_io_data_size)
2568 {
2569         struct dm_md_mempools *pools = kzalloc_node(sizeof(*pools), GFP_KERNEL, md->numa_node_id);
2570         struct kmem_cache *cachep = NULL;
2571         unsigned int pool_size = 0;
2572         unsigned int front_pad;
2573
2574         if (!pools)
2575                 return NULL;
2576
2577         switch (type) {
2578         case DM_TYPE_BIO_BASED:
2579         case DM_TYPE_DAX_BIO_BASED:
2580                 cachep = _io_cache;
2581                 pool_size = dm_get_reserved_bio_based_ios();
2582                 front_pad = roundup(per_io_data_size, __alignof__(struct dm_target_io)) + offsetof(struct dm_target_io, clone);
2583                 break;
2584         case DM_TYPE_REQUEST_BASED:
2585                 cachep = _rq_tio_cache;
2586                 pool_size = dm_get_reserved_rq_based_ios();
2587                 pools->rq_pool = mempool_create_slab_pool(pool_size, _rq_cache);
2588                 if (!pools->rq_pool)
2589                         goto out;
2590                 /* fall through to setup remaining rq-based pools */
2591         case DM_TYPE_MQ_REQUEST_BASED:
2592                 if (!pool_size)
2593                         pool_size = dm_get_reserved_rq_based_ios();
2594                 front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
2595                 /* per_io_data_size is used for blk-mq pdu at queue allocation */
2596                 break;
2597         default:
2598                 BUG();
2599         }
2600
2601         if (cachep) {
2602                 pools->io_pool = mempool_create_slab_pool(pool_size, cachep);
2603                 if (!pools->io_pool)
2604                         goto out;
2605         }
2606
2607         pools->bs = bioset_create_nobvec(pool_size, front_pad);
2608         if (!pools->bs)
2609                 goto out;
2610
2611         if (integrity && bioset_integrity_create(pools->bs, pool_size))
2612                 goto out;
2613
2614         return pools;
2615
2616 out:
2617         dm_free_md_mempools(pools);
2618
2619         return NULL;
2620 }
2621
2622 void dm_free_md_mempools(struct dm_md_mempools *pools)
2623 {
2624         if (!pools)
2625                 return;
2626
2627         mempool_destroy(pools->io_pool);
2628         mempool_destroy(pools->rq_pool);
2629
2630         if (pools->bs)
2631                 bioset_free(pools->bs);
2632
2633         kfree(pools);
2634 }
2635
2636 struct dm_pr {
2637         u64     old_key;
2638         u64     new_key;
2639         u32     flags;
2640         bool    fail_early;
2641 };
2642
2643 static int dm_call_pr(struct block_device *bdev, iterate_devices_callout_fn fn,
2644                       void *data)
2645 {
2646         struct mapped_device *md = bdev->bd_disk->private_data;
2647         struct dm_table *table;
2648         struct dm_target *ti;
2649         int ret = -ENOTTY, srcu_idx;
2650
2651         table = dm_get_live_table(md, &srcu_idx);
2652         if (!table || !dm_table_get_size(table))
2653                 goto out;
2654
2655         /* We only support devices that have a single target */
2656         if (dm_table_get_num_targets(table) != 1)
2657                 goto out;
2658         ti = dm_table_get_target(table, 0);
2659
2660         ret = -EINVAL;
2661         if (!ti->type->iterate_devices)
2662                 goto out;
2663
2664         ret = ti->type->iterate_devices(ti, fn, data);
2665 out:
2666         dm_put_live_table(md, srcu_idx);
2667         return ret;
2668 }
2669
2670 /*
2671  * For register / unregister we need to manually call out to every path.
2672  */
2673 static int __dm_pr_register(struct dm_target *ti, struct dm_dev *dev,
2674                             sector_t start, sector_t len, void *data)
2675 {
2676         struct dm_pr *pr = data;
2677         const struct pr_ops *ops = dev->bdev->bd_disk->fops->pr_ops;
2678
2679         if (!ops || !ops->pr_register)
2680                 return -EOPNOTSUPP;
2681         return ops->pr_register(dev->bdev, pr->old_key, pr->new_key, pr->flags);
2682 }
2683
2684 static int dm_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
2685                           u32 flags)
2686 {
2687         struct dm_pr pr = {
2688                 .old_key        = old_key,
2689                 .new_key        = new_key,
2690                 .flags          = flags,
2691                 .fail_early     = true,
2692         };
2693         int ret;
2694
2695         ret = dm_call_pr(bdev, __dm_pr_register, &pr);
2696         if (ret && new_key) {
2697                 /* unregister all paths if we failed to register any path */
2698                 pr.old_key = new_key;
2699                 pr.new_key = 0;
2700                 pr.flags = 0;
2701                 pr.fail_early = false;
2702                 dm_call_pr(bdev, __dm_pr_register, &pr);
2703         }
2704
2705         return ret;
2706 }
2707
2708 static int dm_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
2709                          u32 flags)
2710 {
2711         struct mapped_device *md = bdev->bd_disk->private_data;
2712         const struct pr_ops *ops;
2713         fmode_t mode;
2714         int r;
2715
2716         r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
2717         if (r < 0)
2718                 return r;
2719
2720         ops = bdev->bd_disk->fops->pr_ops;
2721         if (ops && ops->pr_reserve)
2722                 r = ops->pr_reserve(bdev, key, type, flags);
2723         else
2724                 r = -EOPNOTSUPP;
2725
2726         bdput(bdev);
2727         return r;
2728 }
2729
2730 static int dm_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
2731 {
2732         struct mapped_device *md = bdev->bd_disk->private_data;
2733         const struct pr_ops *ops;
2734         fmode_t mode;
2735         int r;
2736
2737         r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
2738         if (r < 0)
2739                 return r;
2740
2741         ops = bdev->bd_disk->fops->pr_ops;
2742         if (ops && ops->pr_release)
2743                 r = ops->pr_release(bdev, key, type);
2744         else
2745                 r = -EOPNOTSUPP;
2746
2747         bdput(bdev);
2748         return r;
2749 }
2750
2751 static int dm_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
2752                          enum pr_type type, bool abort)
2753 {
2754         struct mapped_device *md = bdev->bd_disk->private_data;
2755         const struct pr_ops *ops;
2756         fmode_t mode;
2757         int r;
2758
2759         r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
2760         if (r < 0)
2761                 return r;
2762
2763         ops = bdev->bd_disk->fops->pr_ops;
2764         if (ops && ops->pr_preempt)
2765                 r = ops->pr_preempt(bdev, old_key, new_key, type, abort);
2766         else
2767                 r = -EOPNOTSUPP;
2768
2769         bdput(bdev);
2770         return r;
2771 }
2772
2773 static int dm_pr_clear(struct block_device *bdev, u64 key)
2774 {
2775         struct mapped_device *md = bdev->bd_disk->private_data;
2776         const struct pr_ops *ops;
2777         fmode_t mode;
2778         int r;
2779
2780         r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
2781         if (r < 0)
2782                 return r;
2783
2784         ops = bdev->bd_disk->fops->pr_ops;
2785         if (ops && ops->pr_clear)
2786                 r = ops->pr_clear(bdev, key);
2787         else
2788                 r = -EOPNOTSUPP;
2789
2790         bdput(bdev);
2791         return r;
2792 }
2793
2794 static const struct pr_ops dm_pr_ops = {
2795         .pr_register    = dm_pr_register,
2796         .pr_reserve     = dm_pr_reserve,
2797         .pr_release     = dm_pr_release,
2798         .pr_preempt     = dm_pr_preempt,
2799         .pr_clear       = dm_pr_clear,
2800 };
2801
2802 static const struct block_device_operations dm_blk_dops = {
2803         .open = dm_blk_open,
2804         .release = dm_blk_close,
2805         .ioctl = dm_blk_ioctl,
2806         .direct_access = dm_blk_direct_access,
2807         .getgeo = dm_blk_getgeo,
2808         .pr_ops = &dm_pr_ops,
2809         .owner = THIS_MODULE
2810 };
2811
2812 /*
2813  * module hooks
2814  */
2815 module_init(dm_init);
2816 module_exit(dm_exit);
2817
2818 module_param(major, uint, 0);
2819 MODULE_PARM_DESC(major, "The major number of the device mapper");
2820
2821 module_param(reserved_bio_based_ios, uint, S_IRUGO | S_IWUSR);
2822 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
2823
2824 module_param(dm_numa_node, int, S_IRUGO | S_IWUSR);
2825 MODULE_PARM_DESC(dm_numa_node, "NUMA node for DM device memory allocations");
2826
2827 MODULE_DESCRIPTION(DM_NAME " driver");
2828 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
2829 MODULE_LICENSE("GPL");