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