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