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