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