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