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