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