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