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