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