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