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