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