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