xref: /linux-6.15/drivers/md/dm-table.c (revision aaa53168)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2001 Sistina Software (UK) Limited.
4  * Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
5  *
6  * This file is released under the GPL.
7  */
8 
9 #include "dm-core.h"
10 #include "dm-rq.h"
11 
12 #include <linux/module.h>
13 #include <linux/vmalloc.h>
14 #include <linux/blkdev.h>
15 #include <linux/blk-integrity.h>
16 #include <linux/namei.h>
17 #include <linux/ctype.h>
18 #include <linux/string.h>
19 #include <linux/slab.h>
20 #include <linux/interrupt.h>
21 #include <linux/mutex.h>
22 #include <linux/delay.h>
23 #include <linux/atomic.h>
24 #include <linux/blk-mq.h>
25 #include <linux/mount.h>
26 #include <linux/dax.h>
27 
28 #define DM_MSG_PREFIX "table"
29 
30 #define NODE_SIZE L1_CACHE_BYTES
31 #define KEYS_PER_NODE (NODE_SIZE / sizeof(sector_t))
32 #define CHILDREN_PER_NODE (KEYS_PER_NODE + 1)
33 
34 /*
35  * Similar to ceiling(log_size(n))
36  */
37 static unsigned int int_log(unsigned int n, unsigned int base)
38 {
39 	int result = 0;
40 
41 	while (n > 1) {
42 		n = dm_div_up(n, base);
43 		result++;
44 	}
45 
46 	return result;
47 }
48 
49 /*
50  * Calculate the index of the child node of the n'th node k'th key.
51  */
52 static inline unsigned int get_child(unsigned int n, unsigned int k)
53 {
54 	return (n * CHILDREN_PER_NODE) + k;
55 }
56 
57 /*
58  * Return the n'th node of level l from table t.
59  */
60 static inline sector_t *get_node(struct dm_table *t,
61 				 unsigned int l, unsigned int n)
62 {
63 	return t->index[l] + (n * KEYS_PER_NODE);
64 }
65 
66 /*
67  * Return the highest key that you could lookup from the n'th
68  * node on level l of the btree.
69  */
70 static sector_t high(struct dm_table *t, unsigned int l, unsigned int n)
71 {
72 	for (; l < t->depth - 1; l++)
73 		n = get_child(n, CHILDREN_PER_NODE - 1);
74 
75 	if (n >= t->counts[l])
76 		return (sector_t) -1;
77 
78 	return get_node(t, l, n)[KEYS_PER_NODE - 1];
79 }
80 
81 /*
82  * Fills in a level of the btree based on the highs of the level
83  * below it.
84  */
85 static int setup_btree_index(unsigned int l, struct dm_table *t)
86 {
87 	unsigned int n, k;
88 	sector_t *node;
89 
90 	for (n = 0U; n < t->counts[l]; n++) {
91 		node = get_node(t, l, n);
92 
93 		for (k = 0U; k < KEYS_PER_NODE; k++)
94 			node[k] = high(t, l + 1, get_child(n, k));
95 	}
96 
97 	return 0;
98 }
99 
100 /*
101  * highs, and targets are managed as dynamic arrays during a
102  * table load.
103  */
104 static int alloc_targets(struct dm_table *t, unsigned int num)
105 {
106 	sector_t *n_highs;
107 	struct dm_target *n_targets;
108 
109 	/*
110 	 * Allocate both the target array and offset array at once.
111 	 */
112 	n_highs = kvcalloc(num, sizeof(struct dm_target) + sizeof(sector_t),
113 			   GFP_KERNEL);
114 	if (!n_highs)
115 		return -ENOMEM;
116 
117 	n_targets = (struct dm_target *) (n_highs + num);
118 
119 	memset(n_highs, -1, sizeof(*n_highs) * num);
120 	kvfree(t->highs);
121 
122 	t->num_allocated = num;
123 	t->highs = n_highs;
124 	t->targets = n_targets;
125 
126 	return 0;
127 }
128 
129 int dm_table_create(struct dm_table **result, blk_mode_t mode,
130 		    unsigned int num_targets, struct mapped_device *md)
131 {
132 	struct dm_table *t;
133 
134 	if (num_targets > DM_MAX_TARGETS)
135 		return -EOVERFLOW;
136 
137 	t = kzalloc(sizeof(*t), GFP_KERNEL);
138 
139 	if (!t)
140 		return -ENOMEM;
141 
142 	INIT_LIST_HEAD(&t->devices);
143 	init_rwsem(&t->devices_lock);
144 
145 	if (!num_targets)
146 		num_targets = KEYS_PER_NODE;
147 
148 	num_targets = dm_round_up(num_targets, KEYS_PER_NODE);
149 
150 	if (!num_targets) {
151 		kfree(t);
152 		return -EOVERFLOW;
153 	}
154 
155 	if (alloc_targets(t, num_targets)) {
156 		kfree(t);
157 		return -ENOMEM;
158 	}
159 
160 	t->type = DM_TYPE_NONE;
161 	t->mode = mode;
162 	t->md = md;
163 	t->flush_bypasses_map = true;
164 	*result = t;
165 	return 0;
166 }
167 
168 static void free_devices(struct list_head *devices, struct mapped_device *md)
169 {
170 	struct list_head *tmp, *next;
171 
172 	list_for_each_safe(tmp, next, devices) {
173 		struct dm_dev_internal *dd =
174 		    list_entry(tmp, struct dm_dev_internal, list);
175 		DMWARN("%s: dm_table_destroy: dm_put_device call missing for %s",
176 		       dm_device_name(md), dd->dm_dev->name);
177 		dm_put_table_device(md, dd->dm_dev);
178 		kfree(dd);
179 	}
180 }
181 
182 static void dm_table_destroy_crypto_profile(struct dm_table *t);
183 
184 void dm_table_destroy(struct dm_table *t)
185 {
186 	if (!t)
187 		return;
188 
189 	/* free the indexes */
190 	if (t->depth >= 2)
191 		kvfree(t->index[t->depth - 2]);
192 
193 	/* free the targets */
194 	for (unsigned int i = 0; i < t->num_targets; i++) {
195 		struct dm_target *ti = dm_table_get_target(t, i);
196 
197 		if (ti->type->dtr)
198 			ti->type->dtr(ti);
199 
200 		dm_put_target_type(ti->type);
201 	}
202 
203 	kvfree(t->highs);
204 
205 	/* free the device list */
206 	free_devices(&t->devices, t->md);
207 
208 	dm_free_md_mempools(t->mempools);
209 
210 	dm_table_destroy_crypto_profile(t);
211 
212 	kfree(t);
213 }
214 
215 /*
216  * See if we've already got a device in the list.
217  */
218 static struct dm_dev_internal *find_device(struct list_head *l, dev_t dev)
219 {
220 	struct dm_dev_internal *dd;
221 
222 	list_for_each_entry(dd, l, list)
223 		if (dd->dm_dev->bdev->bd_dev == dev)
224 			return dd;
225 
226 	return NULL;
227 }
228 
229 /*
230  * If possible, this checks an area of a destination device is invalid.
231  */
232 static int device_area_is_invalid(struct dm_target *ti, struct dm_dev *dev,
233 				  sector_t start, sector_t len, void *data)
234 {
235 	struct queue_limits *limits = data;
236 	struct block_device *bdev = dev->bdev;
237 	sector_t dev_size = bdev_nr_sectors(bdev);
238 	unsigned short logical_block_size_sectors =
239 		limits->logical_block_size >> SECTOR_SHIFT;
240 
241 	if (!dev_size)
242 		return 0;
243 
244 	if ((start >= dev_size) || (start + len > dev_size)) {
245 		DMERR("%s: %pg too small for target: start=%llu, len=%llu, dev_size=%llu",
246 		      dm_device_name(ti->table->md), bdev,
247 		      (unsigned long long)start,
248 		      (unsigned long long)len,
249 		      (unsigned long long)dev_size);
250 		return 1;
251 	}
252 
253 	/*
254 	 * If the target is mapped to zoned block device(s), check
255 	 * that the zones are not partially mapped.
256 	 */
257 	if (bdev_is_zoned(bdev)) {
258 		unsigned int zone_sectors = bdev_zone_sectors(bdev);
259 
260 		if (start & (zone_sectors - 1)) {
261 			DMERR("%s: start=%llu not aligned to h/w zone size %u of %pg",
262 			      dm_device_name(ti->table->md),
263 			      (unsigned long long)start,
264 			      zone_sectors, bdev);
265 			return 1;
266 		}
267 
268 		/*
269 		 * Note: The last zone of a zoned block device may be smaller
270 		 * than other zones. So for a target mapping the end of a
271 		 * zoned block device with such a zone, len would not be zone
272 		 * aligned. We do not allow such last smaller zone to be part
273 		 * of the mapping here to ensure that mappings with multiple
274 		 * devices do not end up with a smaller zone in the middle of
275 		 * the sector range.
276 		 */
277 		if (len & (zone_sectors - 1)) {
278 			DMERR("%s: len=%llu not aligned to h/w zone size %u of %pg",
279 			      dm_device_name(ti->table->md),
280 			      (unsigned long long)len,
281 			      zone_sectors, bdev);
282 			return 1;
283 		}
284 	}
285 
286 	if (logical_block_size_sectors <= 1)
287 		return 0;
288 
289 	if (start & (logical_block_size_sectors - 1)) {
290 		DMERR("%s: start=%llu not aligned to h/w logical block size %u of %pg",
291 		      dm_device_name(ti->table->md),
292 		      (unsigned long long)start,
293 		      limits->logical_block_size, bdev);
294 		return 1;
295 	}
296 
297 	if (len & (logical_block_size_sectors - 1)) {
298 		DMERR("%s: len=%llu not aligned to h/w logical block size %u of %pg",
299 		      dm_device_name(ti->table->md),
300 		      (unsigned long long)len,
301 		      limits->logical_block_size, bdev);
302 		return 1;
303 	}
304 
305 	return 0;
306 }
307 
308 /*
309  * This upgrades the mode on an already open dm_dev, being
310  * careful to leave things as they were if we fail to reopen the
311  * device and not to touch the existing bdev field in case
312  * it is accessed concurrently.
313  */
314 static int upgrade_mode(struct dm_dev_internal *dd, blk_mode_t new_mode,
315 			struct mapped_device *md)
316 {
317 	int r;
318 	struct dm_dev *old_dev, *new_dev;
319 
320 	old_dev = dd->dm_dev;
321 
322 	r = dm_get_table_device(md, dd->dm_dev->bdev->bd_dev,
323 				dd->dm_dev->mode | new_mode, &new_dev);
324 	if (r)
325 		return r;
326 
327 	dd->dm_dev = new_dev;
328 	dm_put_table_device(md, old_dev);
329 
330 	return 0;
331 }
332 
333 /*
334  * Add a device to the list, or just increment the usage count if
335  * it's already present.
336  *
337  * Note: the __ref annotation is because this function can call the __init
338  * marked early_lookup_bdev when called during early boot code from dm-init.c.
339  */
340 int __ref dm_get_device(struct dm_target *ti, const char *path, blk_mode_t mode,
341 		  struct dm_dev **result)
342 {
343 	int r;
344 	dev_t dev;
345 	unsigned int major, minor;
346 	char dummy;
347 	struct dm_dev_internal *dd;
348 	struct dm_table *t = ti->table;
349 
350 	BUG_ON(!t);
351 
352 	if (sscanf(path, "%u:%u%c", &major, &minor, &dummy) == 2) {
353 		/* Extract the major/minor numbers */
354 		dev = MKDEV(major, minor);
355 		if (MAJOR(dev) != major || MINOR(dev) != minor)
356 			return -EOVERFLOW;
357 	} else {
358 		r = lookup_bdev(path, &dev);
359 #ifndef MODULE
360 		if (r && system_state < SYSTEM_RUNNING)
361 			r = early_lookup_bdev(path, &dev);
362 #endif
363 		if (r)
364 			return r;
365 	}
366 	if (dev == disk_devt(t->md->disk))
367 		return -EINVAL;
368 
369 	down_write(&t->devices_lock);
370 
371 	dd = find_device(&t->devices, dev);
372 	if (!dd) {
373 		dd = kmalloc(sizeof(*dd), GFP_KERNEL);
374 		if (!dd) {
375 			r = -ENOMEM;
376 			goto unlock_ret_r;
377 		}
378 
379 		r = dm_get_table_device(t->md, dev, mode, &dd->dm_dev);
380 		if (r) {
381 			kfree(dd);
382 			goto unlock_ret_r;
383 		}
384 
385 		refcount_set(&dd->count, 1);
386 		list_add(&dd->list, &t->devices);
387 		goto out;
388 
389 	} else if (dd->dm_dev->mode != (mode | dd->dm_dev->mode)) {
390 		r = upgrade_mode(dd, mode, t->md);
391 		if (r)
392 			goto unlock_ret_r;
393 	}
394 	refcount_inc(&dd->count);
395 out:
396 	up_write(&t->devices_lock);
397 	*result = dd->dm_dev;
398 	return 0;
399 
400 unlock_ret_r:
401 	up_write(&t->devices_lock);
402 	return r;
403 }
404 EXPORT_SYMBOL(dm_get_device);
405 
406 static int dm_set_device_limits(struct dm_target *ti, struct dm_dev *dev,
407 				sector_t start, sector_t len, void *data)
408 {
409 	struct queue_limits *limits = data;
410 	struct block_device *bdev = dev->bdev;
411 	struct request_queue *q = bdev_get_queue(bdev);
412 
413 	if (unlikely(!q)) {
414 		DMWARN("%s: Cannot set limits for nonexistent device %pg",
415 		       dm_device_name(ti->table->md), bdev);
416 		return 0;
417 	}
418 
419 	if (blk_stack_limits(limits, &q->limits,
420 			get_start_sect(bdev) + start) < 0)
421 		DMWARN("%s: adding target device %pg caused an alignment inconsistency: "
422 		       "physical_block_size=%u, logical_block_size=%u, "
423 		       "alignment_offset=%u, start=%llu",
424 		       dm_device_name(ti->table->md), bdev,
425 		       q->limits.physical_block_size,
426 		       q->limits.logical_block_size,
427 		       q->limits.alignment_offset,
428 		       (unsigned long long) start << SECTOR_SHIFT);
429 
430 	/*
431 	 * Only stack the integrity profile if the target doesn't have native
432 	 * integrity support.
433 	 */
434 	if (!dm_target_has_integrity(ti->type))
435 		queue_limits_stack_integrity_bdev(limits, bdev);
436 	return 0;
437 }
438 
439 /*
440  * Decrement a device's use count and remove it if necessary.
441  */
442 void dm_put_device(struct dm_target *ti, struct dm_dev *d)
443 {
444 	int found = 0;
445 	struct dm_table *t = ti->table;
446 	struct list_head *devices = &t->devices;
447 	struct dm_dev_internal *dd;
448 
449 	down_write(&t->devices_lock);
450 
451 	list_for_each_entry(dd, devices, list) {
452 		if (dd->dm_dev == d) {
453 			found = 1;
454 			break;
455 		}
456 	}
457 	if (!found) {
458 		DMERR("%s: device %s not in table devices list",
459 		      dm_device_name(t->md), d->name);
460 		goto unlock_ret;
461 	}
462 	if (refcount_dec_and_test(&dd->count)) {
463 		dm_put_table_device(t->md, d);
464 		list_del(&dd->list);
465 		kfree(dd);
466 	}
467 
468 unlock_ret:
469 	up_write(&t->devices_lock);
470 }
471 EXPORT_SYMBOL(dm_put_device);
472 
473 /*
474  * Checks to see if the target joins onto the end of the table.
475  */
476 static int adjoin(struct dm_table *t, struct dm_target *ti)
477 {
478 	struct dm_target *prev;
479 
480 	if (!t->num_targets)
481 		return !ti->begin;
482 
483 	prev = &t->targets[t->num_targets - 1];
484 	return (ti->begin == (prev->begin + prev->len));
485 }
486 
487 /*
488  * Used to dynamically allocate the arg array.
489  *
490  * We do first allocation with GFP_NOIO because dm-mpath and dm-thin must
491  * process messages even if some device is suspended. These messages have a
492  * small fixed number of arguments.
493  *
494  * On the other hand, dm-switch needs to process bulk data using messages and
495  * excessive use of GFP_NOIO could cause trouble.
496  */
497 static char **realloc_argv(unsigned int *size, char **old_argv)
498 {
499 	char **argv;
500 	unsigned int new_size;
501 	gfp_t gfp;
502 
503 	if (*size) {
504 		new_size = *size * 2;
505 		gfp = GFP_KERNEL;
506 	} else {
507 		new_size = 8;
508 		gfp = GFP_NOIO;
509 	}
510 	argv = kmalloc_array(new_size, sizeof(*argv), gfp);
511 	if (argv && old_argv) {
512 		memcpy(argv, old_argv, *size * sizeof(*argv));
513 		*size = new_size;
514 	}
515 
516 	kfree(old_argv);
517 	return argv;
518 }
519 
520 /*
521  * Destructively splits up the argument list to pass to ctr.
522  */
523 int dm_split_args(int *argc, char ***argvp, char *input)
524 {
525 	char *start, *end = input, *out, **argv = NULL;
526 	unsigned int array_size = 0;
527 
528 	*argc = 0;
529 
530 	if (!input) {
531 		*argvp = NULL;
532 		return 0;
533 	}
534 
535 	argv = realloc_argv(&array_size, argv);
536 	if (!argv)
537 		return -ENOMEM;
538 
539 	while (1) {
540 		/* Skip whitespace */
541 		start = skip_spaces(end);
542 
543 		if (!*start)
544 			break;	/* success, we hit the end */
545 
546 		/* 'out' is used to remove any back-quotes */
547 		end = out = start;
548 		while (*end) {
549 			/* Everything apart from '\0' can be quoted */
550 			if (*end == '\\' && *(end + 1)) {
551 				*out++ = *(end + 1);
552 				end += 2;
553 				continue;
554 			}
555 
556 			if (isspace(*end))
557 				break;	/* end of token */
558 
559 			*out++ = *end++;
560 		}
561 
562 		/* have we already filled the array ? */
563 		if ((*argc + 1) > array_size) {
564 			argv = realloc_argv(&array_size, argv);
565 			if (!argv)
566 				return -ENOMEM;
567 		}
568 
569 		/* we know this is whitespace */
570 		if (*end)
571 			end++;
572 
573 		/* terminate the string and put it in the array */
574 		*out = '\0';
575 		argv[*argc] = start;
576 		(*argc)++;
577 	}
578 
579 	*argvp = argv;
580 	return 0;
581 }
582 
583 static void dm_set_stacking_limits(struct queue_limits *limits)
584 {
585 	blk_set_stacking_limits(limits);
586 	limits->features |= BLK_FEAT_IO_STAT | BLK_FEAT_NOWAIT | BLK_FEAT_POLL;
587 }
588 
589 /*
590  * Impose necessary and sufficient conditions on a devices's table such
591  * that any incoming bio which respects its logical_block_size can be
592  * processed successfully.  If it falls across the boundary between
593  * two or more targets, the size of each piece it gets split into must
594  * be compatible with the logical_block_size of the target processing it.
595  */
596 static int validate_hardware_logical_block_alignment(struct dm_table *t,
597 						     struct queue_limits *limits)
598 {
599 	/*
600 	 * This function uses arithmetic modulo the logical_block_size
601 	 * (in units of 512-byte sectors).
602 	 */
603 	unsigned short device_logical_block_size_sects =
604 		limits->logical_block_size >> SECTOR_SHIFT;
605 
606 	/*
607 	 * Offset of the start of the next table entry, mod logical_block_size.
608 	 */
609 	unsigned short next_target_start = 0;
610 
611 	/*
612 	 * Given an aligned bio that extends beyond the end of a
613 	 * target, how many sectors must the next target handle?
614 	 */
615 	unsigned short remaining = 0;
616 
617 	struct dm_target *ti;
618 	struct queue_limits ti_limits;
619 	unsigned int i;
620 
621 	/*
622 	 * Check each entry in the table in turn.
623 	 */
624 	for (i = 0; i < t->num_targets; i++) {
625 		ti = dm_table_get_target(t, i);
626 
627 		dm_set_stacking_limits(&ti_limits);
628 
629 		/* combine all target devices' limits */
630 		if (ti->type->iterate_devices)
631 			ti->type->iterate_devices(ti, dm_set_device_limits,
632 						  &ti_limits);
633 
634 		/*
635 		 * If the remaining sectors fall entirely within this
636 		 * table entry are they compatible with its logical_block_size?
637 		 */
638 		if (remaining < ti->len &&
639 		    remaining & ((ti_limits.logical_block_size >>
640 				  SECTOR_SHIFT) - 1))
641 			break;	/* Error */
642 
643 		next_target_start =
644 		    (unsigned short) ((next_target_start + ti->len) &
645 				      (device_logical_block_size_sects - 1));
646 		remaining = next_target_start ?
647 		    device_logical_block_size_sects - next_target_start : 0;
648 	}
649 
650 	if (remaining) {
651 		DMERR("%s: table line %u (start sect %llu len %llu) "
652 		      "not aligned to h/w logical block size %u",
653 		      dm_device_name(t->md), i,
654 		      (unsigned long long) ti->begin,
655 		      (unsigned long long) ti->len,
656 		      limits->logical_block_size);
657 		return -EINVAL;
658 	}
659 
660 	return 0;
661 }
662 
663 int dm_table_add_target(struct dm_table *t, const char *type,
664 			sector_t start, sector_t len, char *params)
665 {
666 	int r = -EINVAL, argc;
667 	char **argv;
668 	struct dm_target *ti;
669 
670 	if (t->singleton) {
671 		DMERR("%s: target type %s must appear alone in table",
672 		      dm_device_name(t->md), t->targets->type->name);
673 		return -EINVAL;
674 	}
675 
676 	BUG_ON(t->num_targets >= t->num_allocated);
677 
678 	ti = t->targets + t->num_targets;
679 	memset(ti, 0, sizeof(*ti));
680 
681 	if (!len) {
682 		DMERR("%s: zero-length target", dm_device_name(t->md));
683 		return -EINVAL;
684 	}
685 
686 	ti->type = dm_get_target_type(type);
687 	if (!ti->type) {
688 		DMERR("%s: %s: unknown target type", dm_device_name(t->md), type);
689 		return -EINVAL;
690 	}
691 
692 	if (dm_target_needs_singleton(ti->type)) {
693 		if (t->num_targets) {
694 			ti->error = "singleton target type must appear alone in table";
695 			goto bad;
696 		}
697 		t->singleton = true;
698 	}
699 
700 	if (dm_target_always_writeable(ti->type) &&
701 	    !(t->mode & BLK_OPEN_WRITE)) {
702 		ti->error = "target type may not be included in a read-only table";
703 		goto bad;
704 	}
705 
706 	if (t->immutable_target_type) {
707 		if (t->immutable_target_type != ti->type) {
708 			ti->error = "immutable target type cannot be mixed with other target types";
709 			goto bad;
710 		}
711 	} else if (dm_target_is_immutable(ti->type)) {
712 		if (t->num_targets) {
713 			ti->error = "immutable target type cannot be mixed with other target types";
714 			goto bad;
715 		}
716 		t->immutable_target_type = ti->type;
717 	}
718 
719 	ti->table = t;
720 	ti->begin = start;
721 	ti->len = len;
722 	ti->error = "Unknown error";
723 
724 	/*
725 	 * Does this target adjoin the previous one ?
726 	 */
727 	if (!adjoin(t, ti)) {
728 		ti->error = "Gap in table";
729 		goto bad;
730 	}
731 
732 	r = dm_split_args(&argc, &argv, params);
733 	if (r) {
734 		ti->error = "couldn't split parameters";
735 		goto bad;
736 	}
737 
738 	r = ti->type->ctr(ti, argc, argv);
739 	kfree(argv);
740 	if (r)
741 		goto bad;
742 
743 	t->highs[t->num_targets++] = ti->begin + ti->len - 1;
744 
745 	if (!ti->num_discard_bios && ti->discards_supported)
746 		DMWARN("%s: %s: ignoring discards_supported because num_discard_bios is zero.",
747 		       dm_device_name(t->md), type);
748 
749 	if (ti->limit_swap_bios && !static_key_enabled(&swap_bios_enabled.key))
750 		static_branch_enable(&swap_bios_enabled);
751 
752 	if (!ti->flush_bypasses_map)
753 		t->flush_bypasses_map = false;
754 
755 	return 0;
756 
757  bad:
758 	DMERR("%s: %s: %s (%pe)", dm_device_name(t->md), type, ti->error, ERR_PTR(r));
759 	dm_put_target_type(ti->type);
760 	return r;
761 }
762 
763 /*
764  * Target argument parsing helpers.
765  */
766 static int validate_next_arg(const struct dm_arg *arg, struct dm_arg_set *arg_set,
767 			     unsigned int *value, char **error, unsigned int grouped)
768 {
769 	const char *arg_str = dm_shift_arg(arg_set);
770 	char dummy;
771 
772 	if (!arg_str ||
773 	    (sscanf(arg_str, "%u%c", value, &dummy) != 1) ||
774 	    (*value < arg->min) ||
775 	    (*value > arg->max) ||
776 	    (grouped && arg_set->argc < *value)) {
777 		*error = arg->error;
778 		return -EINVAL;
779 	}
780 
781 	return 0;
782 }
783 
784 int dm_read_arg(const struct dm_arg *arg, struct dm_arg_set *arg_set,
785 		unsigned int *value, char **error)
786 {
787 	return validate_next_arg(arg, arg_set, value, error, 0);
788 }
789 EXPORT_SYMBOL(dm_read_arg);
790 
791 int dm_read_arg_group(const struct dm_arg *arg, struct dm_arg_set *arg_set,
792 		      unsigned int *value, char **error)
793 {
794 	return validate_next_arg(arg, arg_set, value, error, 1);
795 }
796 EXPORT_SYMBOL(dm_read_arg_group);
797 
798 const char *dm_shift_arg(struct dm_arg_set *as)
799 {
800 	char *r;
801 
802 	if (as->argc) {
803 		as->argc--;
804 		r = *as->argv;
805 		as->argv++;
806 		return r;
807 	}
808 
809 	return NULL;
810 }
811 EXPORT_SYMBOL(dm_shift_arg);
812 
813 void dm_consume_args(struct dm_arg_set *as, unsigned int num_args)
814 {
815 	BUG_ON(as->argc < num_args);
816 	as->argc -= num_args;
817 	as->argv += num_args;
818 }
819 EXPORT_SYMBOL(dm_consume_args);
820 
821 static bool __table_type_bio_based(enum dm_queue_mode table_type)
822 {
823 	return (table_type == DM_TYPE_BIO_BASED ||
824 		table_type == DM_TYPE_DAX_BIO_BASED);
825 }
826 
827 static bool __table_type_request_based(enum dm_queue_mode table_type)
828 {
829 	return table_type == DM_TYPE_REQUEST_BASED;
830 }
831 
832 void dm_table_set_type(struct dm_table *t, enum dm_queue_mode type)
833 {
834 	t->type = type;
835 }
836 EXPORT_SYMBOL_GPL(dm_table_set_type);
837 
838 /* validate the dax capability of the target device span */
839 static int device_not_dax_capable(struct dm_target *ti, struct dm_dev *dev,
840 			sector_t start, sector_t len, void *data)
841 {
842 	if (dev->dax_dev)
843 		return false;
844 
845 	DMDEBUG("%pg: error: dax unsupported by block device", dev->bdev);
846 	return true;
847 }
848 
849 /* Check devices support synchronous DAX */
850 static int device_not_dax_synchronous_capable(struct dm_target *ti, struct dm_dev *dev,
851 					      sector_t start, sector_t len, void *data)
852 {
853 	return !dev->dax_dev || !dax_synchronous(dev->dax_dev);
854 }
855 
856 static bool dm_table_supports_dax(struct dm_table *t,
857 				  iterate_devices_callout_fn iterate_fn)
858 {
859 	/* Ensure that all targets support DAX. */
860 	for (unsigned int i = 0; i < t->num_targets; i++) {
861 		struct dm_target *ti = dm_table_get_target(t, i);
862 
863 		if (!ti->type->direct_access)
864 			return false;
865 
866 		if (dm_target_is_wildcard(ti->type) ||
867 		    !ti->type->iterate_devices ||
868 		    ti->type->iterate_devices(ti, iterate_fn, NULL))
869 			return false;
870 	}
871 
872 	return true;
873 }
874 
875 static int device_is_rq_stackable(struct dm_target *ti, struct dm_dev *dev,
876 				  sector_t start, sector_t len, void *data)
877 {
878 	struct block_device *bdev = dev->bdev;
879 	struct request_queue *q = bdev_get_queue(bdev);
880 
881 	/* request-based cannot stack on partitions! */
882 	if (bdev_is_partition(bdev))
883 		return false;
884 
885 	return queue_is_mq(q);
886 }
887 
888 static int dm_table_determine_type(struct dm_table *t)
889 {
890 	unsigned int bio_based = 0, request_based = 0, hybrid = 0;
891 	struct dm_target *ti;
892 	struct list_head *devices = dm_table_get_devices(t);
893 	enum dm_queue_mode live_md_type = dm_get_md_type(t->md);
894 
895 	if (t->type != DM_TYPE_NONE) {
896 		/* target already set the table's type */
897 		if (t->type == DM_TYPE_BIO_BASED) {
898 			/* possibly upgrade to a variant of bio-based */
899 			goto verify_bio_based;
900 		}
901 		BUG_ON(t->type == DM_TYPE_DAX_BIO_BASED);
902 		goto verify_rq_based;
903 	}
904 
905 	for (unsigned int i = 0; i < t->num_targets; i++) {
906 		ti = dm_table_get_target(t, i);
907 		if (dm_target_hybrid(ti))
908 			hybrid = 1;
909 		else if (dm_target_request_based(ti))
910 			request_based = 1;
911 		else
912 			bio_based = 1;
913 
914 		if (bio_based && request_based) {
915 			DMERR("Inconsistent table: different target types can't be mixed up");
916 			return -EINVAL;
917 		}
918 	}
919 
920 	if (hybrid && !bio_based && !request_based) {
921 		/*
922 		 * The targets can work either way.
923 		 * Determine the type from the live device.
924 		 * Default to bio-based if device is new.
925 		 */
926 		if (__table_type_request_based(live_md_type))
927 			request_based = 1;
928 		else
929 			bio_based = 1;
930 	}
931 
932 	if (bio_based) {
933 verify_bio_based:
934 		/* We must use this table as bio-based */
935 		t->type = DM_TYPE_BIO_BASED;
936 		if (dm_table_supports_dax(t, device_not_dax_capable) ||
937 		    (list_empty(devices) && live_md_type == DM_TYPE_DAX_BIO_BASED)) {
938 			t->type = DM_TYPE_DAX_BIO_BASED;
939 		}
940 		return 0;
941 	}
942 
943 	BUG_ON(!request_based); /* No targets in this table */
944 
945 	t->type = DM_TYPE_REQUEST_BASED;
946 
947 verify_rq_based:
948 	/*
949 	 * Request-based dm supports only tables that have a single target now.
950 	 * To support multiple targets, request splitting support is needed,
951 	 * and that needs lots of changes in the block-layer.
952 	 * (e.g. request completion process for partial completion.)
953 	 */
954 	if (t->num_targets > 1) {
955 		DMERR("request-based DM doesn't support multiple targets");
956 		return -EINVAL;
957 	}
958 
959 	if (list_empty(devices)) {
960 		int srcu_idx;
961 		struct dm_table *live_table = dm_get_live_table(t->md, &srcu_idx);
962 
963 		/* inherit live table's type */
964 		if (live_table)
965 			t->type = live_table->type;
966 		dm_put_live_table(t->md, srcu_idx);
967 		return 0;
968 	}
969 
970 	ti = dm_table_get_immutable_target(t);
971 	if (!ti) {
972 		DMERR("table load rejected: immutable target is required");
973 		return -EINVAL;
974 	} else if (ti->max_io_len) {
975 		DMERR("table load rejected: immutable target that splits IO is not supported");
976 		return -EINVAL;
977 	}
978 
979 	/* Non-request-stackable devices can't be used for request-based dm */
980 	if (!ti->type->iterate_devices ||
981 	    !ti->type->iterate_devices(ti, device_is_rq_stackable, NULL)) {
982 		DMERR("table load rejected: including non-request-stackable devices");
983 		return -EINVAL;
984 	}
985 
986 	return 0;
987 }
988 
989 enum dm_queue_mode dm_table_get_type(struct dm_table *t)
990 {
991 	return t->type;
992 }
993 
994 struct target_type *dm_table_get_immutable_target_type(struct dm_table *t)
995 {
996 	return t->immutable_target_type;
997 }
998 
999 struct dm_target *dm_table_get_immutable_target(struct dm_table *t)
1000 {
1001 	/* Immutable target is implicitly a singleton */
1002 	if (t->num_targets > 1 ||
1003 	    !dm_target_is_immutable(t->targets[0].type))
1004 		return NULL;
1005 
1006 	return t->targets;
1007 }
1008 
1009 struct dm_target *dm_table_get_wildcard_target(struct dm_table *t)
1010 {
1011 	for (unsigned int i = 0; i < t->num_targets; i++) {
1012 		struct dm_target *ti = dm_table_get_target(t, i);
1013 
1014 		if (dm_target_is_wildcard(ti->type))
1015 			return ti;
1016 	}
1017 
1018 	return NULL;
1019 }
1020 
1021 bool dm_table_bio_based(struct dm_table *t)
1022 {
1023 	return __table_type_bio_based(dm_table_get_type(t));
1024 }
1025 
1026 bool dm_table_request_based(struct dm_table *t)
1027 {
1028 	return __table_type_request_based(dm_table_get_type(t));
1029 }
1030 
1031 static int dm_table_alloc_md_mempools(struct dm_table *t, struct mapped_device *md)
1032 {
1033 	enum dm_queue_mode type = dm_table_get_type(t);
1034 	unsigned int per_io_data_size = 0, front_pad, io_front_pad;
1035 	unsigned int min_pool_size = 0, pool_size;
1036 	struct dm_md_mempools *pools;
1037 	unsigned int bioset_flags = 0;
1038 
1039 	if (unlikely(type == DM_TYPE_NONE)) {
1040 		DMERR("no table type is set, can't allocate mempools");
1041 		return -EINVAL;
1042 	}
1043 
1044 	pools = kzalloc_node(sizeof(*pools), GFP_KERNEL, md->numa_node_id);
1045 	if (!pools)
1046 		return -ENOMEM;
1047 
1048 	if (type == DM_TYPE_REQUEST_BASED) {
1049 		pool_size = dm_get_reserved_rq_based_ios();
1050 		front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
1051 		goto init_bs;
1052 	}
1053 
1054 	if (md->queue->limits.features & BLK_FEAT_POLL)
1055 		bioset_flags |= BIOSET_PERCPU_CACHE;
1056 
1057 	for (unsigned int i = 0; i < t->num_targets; i++) {
1058 		struct dm_target *ti = dm_table_get_target(t, i);
1059 
1060 		per_io_data_size = max(per_io_data_size, ti->per_io_data_size);
1061 		min_pool_size = max(min_pool_size, ti->num_flush_bios);
1062 	}
1063 	pool_size = max(dm_get_reserved_bio_based_ios(), min_pool_size);
1064 	front_pad = roundup(per_io_data_size,
1065 		__alignof__(struct dm_target_io)) + DM_TARGET_IO_BIO_OFFSET;
1066 
1067 	io_front_pad = roundup(per_io_data_size,
1068 		__alignof__(struct dm_io)) + DM_IO_BIO_OFFSET;
1069 	if (bioset_init(&pools->io_bs, pool_size, io_front_pad, bioset_flags))
1070 		goto out_free_pools;
1071 	if (t->integrity_supported &&
1072 	    bioset_integrity_create(&pools->io_bs, pool_size))
1073 		goto out_free_pools;
1074 init_bs:
1075 	if (bioset_init(&pools->bs, pool_size, front_pad, 0))
1076 		goto out_free_pools;
1077 	if (t->integrity_supported &&
1078 	    bioset_integrity_create(&pools->bs, pool_size))
1079 		goto out_free_pools;
1080 
1081 	t->mempools = pools;
1082 	return 0;
1083 
1084 out_free_pools:
1085 	dm_free_md_mempools(pools);
1086 	return -ENOMEM;
1087 }
1088 
1089 static int setup_indexes(struct dm_table *t)
1090 {
1091 	int i;
1092 	unsigned int total = 0;
1093 	sector_t *indexes;
1094 
1095 	/* allocate the space for *all* the indexes */
1096 	for (i = t->depth - 2; i >= 0; i--) {
1097 		t->counts[i] = dm_div_up(t->counts[i + 1], CHILDREN_PER_NODE);
1098 		total += t->counts[i];
1099 	}
1100 
1101 	indexes = kvcalloc(total, NODE_SIZE, GFP_KERNEL);
1102 	if (!indexes)
1103 		return -ENOMEM;
1104 
1105 	/* set up internal nodes, bottom-up */
1106 	for (i = t->depth - 2; i >= 0; i--) {
1107 		t->index[i] = indexes;
1108 		indexes += (KEYS_PER_NODE * t->counts[i]);
1109 		setup_btree_index(i, t);
1110 	}
1111 
1112 	return 0;
1113 }
1114 
1115 /*
1116  * Builds the btree to index the map.
1117  */
1118 static int dm_table_build_index(struct dm_table *t)
1119 {
1120 	int r = 0;
1121 	unsigned int leaf_nodes;
1122 
1123 	/* how many indexes will the btree have ? */
1124 	leaf_nodes = dm_div_up(t->num_targets, KEYS_PER_NODE);
1125 	t->depth = 1 + int_log(leaf_nodes, CHILDREN_PER_NODE);
1126 
1127 	/* leaf layer has already been set up */
1128 	t->counts[t->depth - 1] = leaf_nodes;
1129 	t->index[t->depth - 1] = t->highs;
1130 
1131 	if (t->depth >= 2)
1132 		r = setup_indexes(t);
1133 
1134 	return r;
1135 }
1136 
1137 #ifdef CONFIG_BLK_INLINE_ENCRYPTION
1138 
1139 struct dm_crypto_profile {
1140 	struct blk_crypto_profile profile;
1141 	struct mapped_device *md;
1142 };
1143 
1144 static int dm_keyslot_evict_callback(struct dm_target *ti, struct dm_dev *dev,
1145 				     sector_t start, sector_t len, void *data)
1146 {
1147 	const struct blk_crypto_key *key = data;
1148 
1149 	blk_crypto_evict_key(dev->bdev, key);
1150 	return 0;
1151 }
1152 
1153 /*
1154  * When an inline encryption key is evicted from a device-mapper device, evict
1155  * it from all the underlying devices.
1156  */
1157 static int dm_keyslot_evict(struct blk_crypto_profile *profile,
1158 			    const struct blk_crypto_key *key, unsigned int slot)
1159 {
1160 	struct mapped_device *md =
1161 		container_of(profile, struct dm_crypto_profile, profile)->md;
1162 	struct dm_table *t;
1163 	int srcu_idx;
1164 
1165 	t = dm_get_live_table(md, &srcu_idx);
1166 	if (!t)
1167 		return 0;
1168 
1169 	for (unsigned int i = 0; i < t->num_targets; i++) {
1170 		struct dm_target *ti = dm_table_get_target(t, i);
1171 
1172 		if (!ti->type->iterate_devices)
1173 			continue;
1174 		ti->type->iterate_devices(ti, dm_keyslot_evict_callback,
1175 					  (void *)key);
1176 	}
1177 
1178 	dm_put_live_table(md, srcu_idx);
1179 	return 0;
1180 }
1181 
1182 static int
1183 device_intersect_crypto_capabilities(struct dm_target *ti, struct dm_dev *dev,
1184 				     sector_t start, sector_t len, void *data)
1185 {
1186 	struct blk_crypto_profile *parent = data;
1187 	struct blk_crypto_profile *child =
1188 		bdev_get_queue(dev->bdev)->crypto_profile;
1189 
1190 	blk_crypto_intersect_capabilities(parent, child);
1191 	return 0;
1192 }
1193 
1194 void dm_destroy_crypto_profile(struct blk_crypto_profile *profile)
1195 {
1196 	struct dm_crypto_profile *dmcp = container_of(profile,
1197 						      struct dm_crypto_profile,
1198 						      profile);
1199 
1200 	if (!profile)
1201 		return;
1202 
1203 	blk_crypto_profile_destroy(profile);
1204 	kfree(dmcp);
1205 }
1206 
1207 static void dm_table_destroy_crypto_profile(struct dm_table *t)
1208 {
1209 	dm_destroy_crypto_profile(t->crypto_profile);
1210 	t->crypto_profile = NULL;
1211 }
1212 
1213 /*
1214  * Constructs and initializes t->crypto_profile with a crypto profile that
1215  * represents the common set of crypto capabilities of the devices described by
1216  * the dm_table.  However, if the constructed crypto profile doesn't support all
1217  * crypto capabilities that are supported by the current mapped_device, it
1218  * returns an error instead, since we don't support removing crypto capabilities
1219  * on table changes.  Finally, if the constructed crypto profile is "empty" (has
1220  * no crypto capabilities at all), it just sets t->crypto_profile to NULL.
1221  */
1222 static int dm_table_construct_crypto_profile(struct dm_table *t)
1223 {
1224 	struct dm_crypto_profile *dmcp;
1225 	struct blk_crypto_profile *profile;
1226 	unsigned int i;
1227 	bool empty_profile = true;
1228 
1229 	dmcp = kmalloc(sizeof(*dmcp), GFP_KERNEL);
1230 	if (!dmcp)
1231 		return -ENOMEM;
1232 	dmcp->md = t->md;
1233 
1234 	profile = &dmcp->profile;
1235 	blk_crypto_profile_init(profile, 0);
1236 	profile->ll_ops.keyslot_evict = dm_keyslot_evict;
1237 	profile->max_dun_bytes_supported = UINT_MAX;
1238 	memset(profile->modes_supported, 0xFF,
1239 	       sizeof(profile->modes_supported));
1240 
1241 	for (i = 0; i < t->num_targets; i++) {
1242 		struct dm_target *ti = dm_table_get_target(t, i);
1243 
1244 		if (!dm_target_passes_crypto(ti->type)) {
1245 			blk_crypto_intersect_capabilities(profile, NULL);
1246 			break;
1247 		}
1248 		if (!ti->type->iterate_devices)
1249 			continue;
1250 		ti->type->iterate_devices(ti,
1251 					  device_intersect_crypto_capabilities,
1252 					  profile);
1253 	}
1254 
1255 	if (t->md->queue &&
1256 	    !blk_crypto_has_capabilities(profile,
1257 					 t->md->queue->crypto_profile)) {
1258 		DMERR("Inline encryption capabilities of new DM table were more restrictive than the old table's. This is not supported!");
1259 		dm_destroy_crypto_profile(profile);
1260 		return -EINVAL;
1261 	}
1262 
1263 	/*
1264 	 * If the new profile doesn't actually support any crypto capabilities,
1265 	 * we may as well represent it with a NULL profile.
1266 	 */
1267 	for (i = 0; i < ARRAY_SIZE(profile->modes_supported); i++) {
1268 		if (profile->modes_supported[i]) {
1269 			empty_profile = false;
1270 			break;
1271 		}
1272 	}
1273 
1274 	if (empty_profile) {
1275 		dm_destroy_crypto_profile(profile);
1276 		profile = NULL;
1277 	}
1278 
1279 	/*
1280 	 * t->crypto_profile is only set temporarily while the table is being
1281 	 * set up, and it gets set to NULL after the profile has been
1282 	 * transferred to the request_queue.
1283 	 */
1284 	t->crypto_profile = profile;
1285 
1286 	return 0;
1287 }
1288 
1289 static void dm_update_crypto_profile(struct request_queue *q,
1290 				     struct dm_table *t)
1291 {
1292 	if (!t->crypto_profile)
1293 		return;
1294 
1295 	/* Make the crypto profile less restrictive. */
1296 	if (!q->crypto_profile) {
1297 		blk_crypto_register(t->crypto_profile, q);
1298 	} else {
1299 		blk_crypto_update_capabilities(q->crypto_profile,
1300 					       t->crypto_profile);
1301 		dm_destroy_crypto_profile(t->crypto_profile);
1302 	}
1303 	t->crypto_profile = NULL;
1304 }
1305 
1306 #else /* CONFIG_BLK_INLINE_ENCRYPTION */
1307 
1308 static int dm_table_construct_crypto_profile(struct dm_table *t)
1309 {
1310 	return 0;
1311 }
1312 
1313 void dm_destroy_crypto_profile(struct blk_crypto_profile *profile)
1314 {
1315 }
1316 
1317 static void dm_table_destroy_crypto_profile(struct dm_table *t)
1318 {
1319 }
1320 
1321 static void dm_update_crypto_profile(struct request_queue *q,
1322 				     struct dm_table *t)
1323 {
1324 }
1325 
1326 #endif /* !CONFIG_BLK_INLINE_ENCRYPTION */
1327 
1328 /*
1329  * Prepares the table for use by building the indices,
1330  * setting the type, and allocating mempools.
1331  */
1332 int dm_table_complete(struct dm_table *t)
1333 {
1334 	int r;
1335 
1336 	r = dm_table_determine_type(t);
1337 	if (r) {
1338 		DMERR("unable to determine table type");
1339 		return r;
1340 	}
1341 
1342 	r = dm_table_build_index(t);
1343 	if (r) {
1344 		DMERR("unable to build btrees");
1345 		return r;
1346 	}
1347 
1348 	r = dm_table_construct_crypto_profile(t);
1349 	if (r) {
1350 		DMERR("could not construct crypto profile.");
1351 		return r;
1352 	}
1353 
1354 	r = dm_table_alloc_md_mempools(t, t->md);
1355 	if (r)
1356 		DMERR("unable to allocate mempools");
1357 
1358 	return r;
1359 }
1360 
1361 static DEFINE_MUTEX(_event_lock);
1362 void dm_table_event_callback(struct dm_table *t,
1363 			     void (*fn)(void *), void *context)
1364 {
1365 	mutex_lock(&_event_lock);
1366 	t->event_fn = fn;
1367 	t->event_context = context;
1368 	mutex_unlock(&_event_lock);
1369 }
1370 
1371 void dm_table_event(struct dm_table *t)
1372 {
1373 	mutex_lock(&_event_lock);
1374 	if (t->event_fn)
1375 		t->event_fn(t->event_context);
1376 	mutex_unlock(&_event_lock);
1377 }
1378 EXPORT_SYMBOL(dm_table_event);
1379 
1380 inline sector_t dm_table_get_size(struct dm_table *t)
1381 {
1382 	return t->num_targets ? (t->highs[t->num_targets - 1] + 1) : 0;
1383 }
1384 EXPORT_SYMBOL(dm_table_get_size);
1385 
1386 /*
1387  * Search the btree for the correct target.
1388  *
1389  * Caller should check returned pointer for NULL
1390  * to trap I/O beyond end of device.
1391  */
1392 struct dm_target *dm_table_find_target(struct dm_table *t, sector_t sector)
1393 {
1394 	unsigned int l, n = 0, k = 0;
1395 	sector_t *node;
1396 
1397 	if (unlikely(sector >= dm_table_get_size(t)))
1398 		return NULL;
1399 
1400 	for (l = 0; l < t->depth; l++) {
1401 		n = get_child(n, k);
1402 		node = get_node(t, l, n);
1403 
1404 		for (k = 0; k < KEYS_PER_NODE; k++)
1405 			if (node[k] >= sector)
1406 				break;
1407 	}
1408 
1409 	return &t->targets[(KEYS_PER_NODE * n) + k];
1410 }
1411 
1412 /*
1413  * type->iterate_devices() should be called when the sanity check needs to
1414  * iterate and check all underlying data devices. iterate_devices() will
1415  * iterate all underlying data devices until it encounters a non-zero return
1416  * code, returned by whether the input iterate_devices_callout_fn, or
1417  * iterate_devices() itself internally.
1418  *
1419  * For some target type (e.g. dm-stripe), one call of iterate_devices() may
1420  * iterate multiple underlying devices internally, in which case a non-zero
1421  * return code returned by iterate_devices_callout_fn will stop the iteration
1422  * in advance.
1423  *
1424  * Cases requiring _any_ underlying device supporting some kind of attribute,
1425  * should use the iteration structure like dm_table_any_dev_attr(), or call
1426  * it directly. @func should handle semantics of positive examples, e.g.
1427  * capable of something.
1428  *
1429  * Cases requiring _all_ underlying devices supporting some kind of attribute,
1430  * should use the iteration structure like dm_table_supports_nowait() or
1431  * dm_table_supports_discards(). Or introduce dm_table_all_devs_attr() that
1432  * uses an @anti_func that handle semantics of counter examples, e.g. not
1433  * capable of something. So: return !dm_table_any_dev_attr(t, anti_func, data);
1434  */
1435 static bool dm_table_any_dev_attr(struct dm_table *t,
1436 				  iterate_devices_callout_fn func, void *data)
1437 {
1438 	for (unsigned int i = 0; i < t->num_targets; i++) {
1439 		struct dm_target *ti = dm_table_get_target(t, i);
1440 
1441 		if (ti->type->iterate_devices &&
1442 		    ti->type->iterate_devices(ti, func, data))
1443 			return true;
1444 	}
1445 
1446 	return false;
1447 }
1448 
1449 static int count_device(struct dm_target *ti, struct dm_dev *dev,
1450 			sector_t start, sector_t len, void *data)
1451 {
1452 	unsigned int *num_devices = data;
1453 
1454 	(*num_devices)++;
1455 
1456 	return 0;
1457 }
1458 
1459 /*
1460  * Check whether a table has no data devices attached using each
1461  * target's iterate_devices method.
1462  * Returns false if the result is unknown because a target doesn't
1463  * support iterate_devices.
1464  */
1465 bool dm_table_has_no_data_devices(struct dm_table *t)
1466 {
1467 	for (unsigned int i = 0; i < t->num_targets; i++) {
1468 		struct dm_target *ti = dm_table_get_target(t, i);
1469 		unsigned int num_devices = 0;
1470 
1471 		if (!ti->type->iterate_devices)
1472 			return false;
1473 
1474 		ti->type->iterate_devices(ti, count_device, &num_devices);
1475 		if (num_devices)
1476 			return false;
1477 	}
1478 
1479 	return true;
1480 }
1481 
1482 static int device_not_zoned(struct dm_target *ti, struct dm_dev *dev,
1483 			    sector_t start, sector_t len, void *data)
1484 {
1485 	bool *zoned = data;
1486 
1487 	return bdev_is_zoned(dev->bdev) != *zoned;
1488 }
1489 
1490 static int device_is_zoned_model(struct dm_target *ti, struct dm_dev *dev,
1491 				 sector_t start, sector_t len, void *data)
1492 {
1493 	return bdev_is_zoned(dev->bdev);
1494 }
1495 
1496 /*
1497  * Check the device zoned model based on the target feature flag. If the target
1498  * has the DM_TARGET_ZONED_HM feature flag set, host-managed zoned devices are
1499  * also accepted but all devices must have the same zoned model. If the target
1500  * has the DM_TARGET_MIXED_ZONED_MODEL feature set, the devices can have any
1501  * zoned model with all zoned devices having the same zone size.
1502  */
1503 static bool dm_table_supports_zoned(struct dm_table *t, bool zoned)
1504 {
1505 	for (unsigned int i = 0; i < t->num_targets; i++) {
1506 		struct dm_target *ti = dm_table_get_target(t, i);
1507 
1508 		/*
1509 		 * For the wildcard target (dm-error), if we do not have a
1510 		 * backing device, we must always return false. If we have a
1511 		 * backing device, the result must depend on checking zoned
1512 		 * model, like for any other target. So for this, check directly
1513 		 * if the target backing device is zoned as we get "false" when
1514 		 * dm-error was set without a backing device.
1515 		 */
1516 		if (dm_target_is_wildcard(ti->type) &&
1517 		    !ti->type->iterate_devices(ti, device_is_zoned_model, NULL))
1518 			return false;
1519 
1520 		if (dm_target_supports_zoned_hm(ti->type)) {
1521 			if (!ti->type->iterate_devices ||
1522 			    ti->type->iterate_devices(ti, device_not_zoned,
1523 						      &zoned))
1524 				return false;
1525 		} else if (!dm_target_supports_mixed_zoned_model(ti->type)) {
1526 			if (zoned)
1527 				return false;
1528 		}
1529 	}
1530 
1531 	return true;
1532 }
1533 
1534 static int device_not_matches_zone_sectors(struct dm_target *ti, struct dm_dev *dev,
1535 					   sector_t start, sector_t len, void *data)
1536 {
1537 	unsigned int *zone_sectors = data;
1538 
1539 	if (!bdev_is_zoned(dev->bdev))
1540 		return 0;
1541 	return bdev_zone_sectors(dev->bdev) != *zone_sectors;
1542 }
1543 
1544 /*
1545  * Check consistency of zoned model and zone sectors across all targets. For
1546  * zone sectors, if the destination device is a zoned block device, it shall
1547  * have the specified zone_sectors.
1548  */
1549 static int validate_hardware_zoned(struct dm_table *t, bool zoned,
1550 				   unsigned int zone_sectors)
1551 {
1552 	if (!zoned)
1553 		return 0;
1554 
1555 	if (!dm_table_supports_zoned(t, zoned)) {
1556 		DMERR("%s: zoned model is not consistent across all devices",
1557 		      dm_device_name(t->md));
1558 		return -EINVAL;
1559 	}
1560 
1561 	/* Check zone size validity and compatibility */
1562 	if (!zone_sectors || !is_power_of_2(zone_sectors))
1563 		return -EINVAL;
1564 
1565 	if (dm_table_any_dev_attr(t, device_not_matches_zone_sectors, &zone_sectors)) {
1566 		DMERR("%s: zone sectors is not consistent across all zoned devices",
1567 		      dm_device_name(t->md));
1568 		return -EINVAL;
1569 	}
1570 
1571 	return 0;
1572 }
1573 
1574 /*
1575  * Establish the new table's queue_limits and validate them.
1576  */
1577 int dm_calculate_queue_limits(struct dm_table *t,
1578 			      struct queue_limits *limits)
1579 {
1580 	struct queue_limits ti_limits;
1581 	unsigned int zone_sectors = 0;
1582 	bool zoned = false;
1583 
1584 	dm_set_stacking_limits(limits);
1585 
1586 	t->integrity_supported = true;
1587 	for (unsigned int i = 0; i < t->num_targets; i++) {
1588 		struct dm_target *ti = dm_table_get_target(t, i);
1589 
1590 		if (!dm_target_passes_integrity(ti->type))
1591 			t->integrity_supported = false;
1592 	}
1593 
1594 	for (unsigned int i = 0; i < t->num_targets; i++) {
1595 		struct dm_target *ti = dm_table_get_target(t, i);
1596 
1597 		dm_set_stacking_limits(&ti_limits);
1598 
1599 		if (!ti->type->iterate_devices) {
1600 			/* Set I/O hints portion of queue limits */
1601 			if (ti->type->io_hints)
1602 				ti->type->io_hints(ti, &ti_limits);
1603 			goto combine_limits;
1604 		}
1605 
1606 		/*
1607 		 * Combine queue limits of all the devices this target uses.
1608 		 */
1609 		ti->type->iterate_devices(ti, dm_set_device_limits,
1610 					  &ti_limits);
1611 
1612 		if (!zoned && (ti_limits.features & BLK_FEAT_ZONED)) {
1613 			/*
1614 			 * After stacking all limits, validate all devices
1615 			 * in table support this zoned model and zone sectors.
1616 			 */
1617 			zoned = (ti_limits.features & BLK_FEAT_ZONED);
1618 			zone_sectors = ti_limits.chunk_sectors;
1619 		}
1620 
1621 		/* Set I/O hints portion of queue limits */
1622 		if (ti->type->io_hints)
1623 			ti->type->io_hints(ti, &ti_limits);
1624 
1625 		/*
1626 		 * Check each device area is consistent with the target's
1627 		 * overall queue limits.
1628 		 */
1629 		if (ti->type->iterate_devices(ti, device_area_is_invalid,
1630 					      &ti_limits))
1631 			return -EINVAL;
1632 
1633 combine_limits:
1634 		/*
1635 		 * Merge this target's queue limits into the overall limits
1636 		 * for the table.
1637 		 */
1638 		if (blk_stack_limits(limits, &ti_limits, 0) < 0)
1639 			DMWARN("%s: adding target device (start sect %llu len %llu) "
1640 			       "caused an alignment inconsistency",
1641 			       dm_device_name(t->md),
1642 			       (unsigned long long) ti->begin,
1643 			       (unsigned long long) ti->len);
1644 
1645 		if (t->integrity_supported ||
1646 		    dm_target_has_integrity(ti->type)) {
1647 			if (!queue_limits_stack_integrity(limits, &ti_limits)) {
1648 				DMWARN("%s: adding target device (start sect %llu len %llu) "
1649 				       "disabled integrity support due to incompatibility",
1650 				       dm_device_name(t->md),
1651 				       (unsigned long long) ti->begin,
1652 				       (unsigned long long) ti->len);
1653 				t->integrity_supported = false;
1654 			}
1655 		}
1656 	}
1657 
1658 	/*
1659 	 * Verify that the zoned model and zone sectors, as determined before
1660 	 * any .io_hints override, are the same across all devices in the table.
1661 	 * - this is especially relevant if .io_hints is emulating a disk-managed
1662 	 *   zoned model on host-managed zoned block devices.
1663 	 * BUT...
1664 	 */
1665 	if (limits->features & BLK_FEAT_ZONED) {
1666 		/*
1667 		 * ...IF the above limits stacking determined a zoned model
1668 		 * validate that all of the table's devices conform to it.
1669 		 */
1670 		zoned = limits->features & BLK_FEAT_ZONED;
1671 		zone_sectors = limits->chunk_sectors;
1672 	}
1673 	if (validate_hardware_zoned(t, zoned, zone_sectors))
1674 		return -EINVAL;
1675 
1676 	return validate_hardware_logical_block_alignment(t, limits);
1677 }
1678 
1679 /*
1680  * Check if a target requires flush support even if none of the underlying
1681  * devices need it (e.g. to persist target-specific metadata).
1682  */
1683 static bool dm_table_supports_flush(struct dm_table *t)
1684 {
1685 	for (unsigned int i = 0; i < t->num_targets; i++) {
1686 		struct dm_target *ti = dm_table_get_target(t, i);
1687 
1688 		if (ti->num_flush_bios && ti->flush_supported)
1689 			return true;
1690 	}
1691 
1692 	return false;
1693 }
1694 
1695 static int device_dax_write_cache_enabled(struct dm_target *ti,
1696 					  struct dm_dev *dev, sector_t start,
1697 					  sector_t len, void *data)
1698 {
1699 	struct dax_device *dax_dev = dev->dax_dev;
1700 
1701 	if (!dax_dev)
1702 		return false;
1703 
1704 	if (dax_write_cache_enabled(dax_dev))
1705 		return true;
1706 	return false;
1707 }
1708 
1709 static int device_not_write_zeroes_capable(struct dm_target *ti, struct dm_dev *dev,
1710 					   sector_t start, sector_t len, void *data)
1711 {
1712 	struct request_queue *q = bdev_get_queue(dev->bdev);
1713 
1714 	return !q->limits.max_write_zeroes_sectors;
1715 }
1716 
1717 static bool dm_table_supports_write_zeroes(struct dm_table *t)
1718 {
1719 	for (unsigned int i = 0; i < t->num_targets; i++) {
1720 		struct dm_target *ti = dm_table_get_target(t, i);
1721 
1722 		if (!ti->num_write_zeroes_bios)
1723 			return false;
1724 
1725 		if (!ti->type->iterate_devices ||
1726 		    ti->type->iterate_devices(ti, device_not_write_zeroes_capable, NULL))
1727 			return false;
1728 	}
1729 
1730 	return true;
1731 }
1732 
1733 static bool dm_table_supports_nowait(struct dm_table *t)
1734 {
1735 	for (unsigned int i = 0; i < t->num_targets; i++) {
1736 		struct dm_target *ti = dm_table_get_target(t, i);
1737 
1738 		if (!dm_target_supports_nowait(ti->type))
1739 			return false;
1740 	}
1741 
1742 	return true;
1743 }
1744 
1745 static int device_not_discard_capable(struct dm_target *ti, struct dm_dev *dev,
1746 				      sector_t start, sector_t len, void *data)
1747 {
1748 	return !bdev_max_discard_sectors(dev->bdev);
1749 }
1750 
1751 static bool dm_table_supports_discards(struct dm_table *t)
1752 {
1753 	for (unsigned int i = 0; i < t->num_targets; i++) {
1754 		struct dm_target *ti = dm_table_get_target(t, i);
1755 
1756 		if (!ti->num_discard_bios)
1757 			return false;
1758 
1759 		/*
1760 		 * Either the target provides discard support (as implied by setting
1761 		 * 'discards_supported') or it relies on _all_ data devices having
1762 		 * discard support.
1763 		 */
1764 		if (!ti->discards_supported &&
1765 		    (!ti->type->iterate_devices ||
1766 		     ti->type->iterate_devices(ti, device_not_discard_capable, NULL)))
1767 			return false;
1768 	}
1769 
1770 	return true;
1771 }
1772 
1773 static int device_not_secure_erase_capable(struct dm_target *ti,
1774 					   struct dm_dev *dev, sector_t start,
1775 					   sector_t len, void *data)
1776 {
1777 	return !bdev_max_secure_erase_sectors(dev->bdev);
1778 }
1779 
1780 static bool dm_table_supports_secure_erase(struct dm_table *t)
1781 {
1782 	for (unsigned int i = 0; i < t->num_targets; i++) {
1783 		struct dm_target *ti = dm_table_get_target(t, i);
1784 
1785 		if (!ti->num_secure_erase_bios)
1786 			return false;
1787 
1788 		if (!ti->type->iterate_devices ||
1789 		    ti->type->iterate_devices(ti, device_not_secure_erase_capable, NULL))
1790 			return false;
1791 	}
1792 
1793 	return true;
1794 }
1795 
1796 int dm_table_set_restrictions(struct dm_table *t, struct request_queue *q,
1797 			      struct queue_limits *limits)
1798 {
1799 	int r;
1800 
1801 	if (!dm_table_supports_nowait(t))
1802 		limits->features &= ~BLK_FEAT_NOWAIT;
1803 
1804 	/*
1805 	 * The current polling impementation does not support request based
1806 	 * stacking.
1807 	 */
1808 	if (!__table_type_bio_based(t->type))
1809 		limits->features &= ~BLK_FEAT_POLL;
1810 
1811 	if (!dm_table_supports_discards(t)) {
1812 		limits->max_hw_discard_sectors = 0;
1813 		limits->discard_granularity = 0;
1814 		limits->discard_alignment = 0;
1815 	}
1816 
1817 	if (!dm_table_supports_write_zeroes(t))
1818 		limits->max_write_zeroes_sectors = 0;
1819 
1820 	if (!dm_table_supports_secure_erase(t))
1821 		limits->max_secure_erase_sectors = 0;
1822 
1823 	if (dm_table_supports_flush(t))
1824 		limits->features |= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA;
1825 
1826 	if (dm_table_supports_dax(t, device_not_dax_capable)) {
1827 		limits->features |= BLK_FEAT_DAX;
1828 		if (dm_table_supports_dax(t, device_not_dax_synchronous_capable))
1829 			set_dax_synchronous(t->md->dax_dev);
1830 	} else
1831 		limits->features &= ~BLK_FEAT_DAX;
1832 
1833 	if (dm_table_any_dev_attr(t, device_dax_write_cache_enabled, NULL))
1834 		dax_write_cache(t->md->dax_dev, true);
1835 
1836 	/* For a zoned table, setup the zone related queue attributes. */
1837 	if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
1838 	    (limits->features & BLK_FEAT_ZONED)) {
1839 		r = dm_set_zones_restrictions(t, q, limits);
1840 		if (r)
1841 			return r;
1842 	}
1843 
1844 	r = queue_limits_set(q, limits);
1845 	if (r)
1846 		return r;
1847 
1848 	/*
1849 	 * Now that the limits are set, check the zones mapped by the table
1850 	 * and setup the resources for zone append emulation if necessary.
1851 	 */
1852 	if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
1853 	    (limits->features & BLK_FEAT_ZONED)) {
1854 		r = dm_revalidate_zones(t, q);
1855 		if (r)
1856 			return r;
1857 	}
1858 
1859 	dm_update_crypto_profile(q, t);
1860 	return 0;
1861 }
1862 
1863 struct list_head *dm_table_get_devices(struct dm_table *t)
1864 {
1865 	return &t->devices;
1866 }
1867 
1868 blk_mode_t dm_table_get_mode(struct dm_table *t)
1869 {
1870 	return t->mode;
1871 }
1872 EXPORT_SYMBOL(dm_table_get_mode);
1873 
1874 enum suspend_mode {
1875 	PRESUSPEND,
1876 	PRESUSPEND_UNDO,
1877 	POSTSUSPEND,
1878 };
1879 
1880 static void suspend_targets(struct dm_table *t, enum suspend_mode mode)
1881 {
1882 	lockdep_assert_held(&t->md->suspend_lock);
1883 
1884 	for (unsigned int i = 0; i < t->num_targets; i++) {
1885 		struct dm_target *ti = dm_table_get_target(t, i);
1886 
1887 		switch (mode) {
1888 		case PRESUSPEND:
1889 			if (ti->type->presuspend)
1890 				ti->type->presuspend(ti);
1891 			break;
1892 		case PRESUSPEND_UNDO:
1893 			if (ti->type->presuspend_undo)
1894 				ti->type->presuspend_undo(ti);
1895 			break;
1896 		case POSTSUSPEND:
1897 			if (ti->type->postsuspend)
1898 				ti->type->postsuspend(ti);
1899 			break;
1900 		}
1901 	}
1902 }
1903 
1904 void dm_table_presuspend_targets(struct dm_table *t)
1905 {
1906 	if (!t)
1907 		return;
1908 
1909 	suspend_targets(t, PRESUSPEND);
1910 }
1911 
1912 void dm_table_presuspend_undo_targets(struct dm_table *t)
1913 {
1914 	if (!t)
1915 		return;
1916 
1917 	suspend_targets(t, PRESUSPEND_UNDO);
1918 }
1919 
1920 void dm_table_postsuspend_targets(struct dm_table *t)
1921 {
1922 	if (!t)
1923 		return;
1924 
1925 	suspend_targets(t, POSTSUSPEND);
1926 }
1927 
1928 int dm_table_resume_targets(struct dm_table *t)
1929 {
1930 	unsigned int i;
1931 	int r = 0;
1932 
1933 	lockdep_assert_held(&t->md->suspend_lock);
1934 
1935 	for (i = 0; i < t->num_targets; i++) {
1936 		struct dm_target *ti = dm_table_get_target(t, i);
1937 
1938 		if (!ti->type->preresume)
1939 			continue;
1940 
1941 		r = ti->type->preresume(ti);
1942 		if (r) {
1943 			DMERR("%s: %s: preresume failed, error = %d",
1944 			      dm_device_name(t->md), ti->type->name, r);
1945 			return r;
1946 		}
1947 	}
1948 
1949 	for (i = 0; i < t->num_targets; i++) {
1950 		struct dm_target *ti = dm_table_get_target(t, i);
1951 
1952 		if (ti->type->resume)
1953 			ti->type->resume(ti);
1954 	}
1955 
1956 	return 0;
1957 }
1958 
1959 struct mapped_device *dm_table_get_md(struct dm_table *t)
1960 {
1961 	return t->md;
1962 }
1963 EXPORT_SYMBOL(dm_table_get_md);
1964 
1965 const char *dm_table_device_name(struct dm_table *t)
1966 {
1967 	return dm_device_name(t->md);
1968 }
1969 EXPORT_SYMBOL_GPL(dm_table_device_name);
1970 
1971 void dm_table_run_md_queue_async(struct dm_table *t)
1972 {
1973 	if (!dm_table_request_based(t))
1974 		return;
1975 
1976 	if (t->md->queue)
1977 		blk_mq_run_hw_queues(t->md->queue, true);
1978 }
1979 EXPORT_SYMBOL(dm_table_run_md_queue_async);
1980 
1981