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