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