xref: /freebsd/sys/contrib/openzfs/module/zfs/vdev.c (revision 38a52bd3)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or https://opensource.org/licenses/CDDL-1.0.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2021 by Delphix. All rights reserved.
25  * Copyright 2017 Nexenta Systems, Inc.
26  * Copyright (c) 2014 Integros [integros.com]
27  * Copyright 2016 Toomas Soome <tsoome@me.com>
28  * Copyright 2017 Joyent, Inc.
29  * Copyright (c) 2017, Intel Corporation.
30  * Copyright (c) 2019, Datto Inc. All rights reserved.
31  * Copyright (c) 2021, Klara Inc.
32  * Copyright [2021] Hewlett Packard Enterprise Development LP
33  */
34 
35 #include <sys/zfs_context.h>
36 #include <sys/fm/fs/zfs.h>
37 #include <sys/spa.h>
38 #include <sys/spa_impl.h>
39 #include <sys/bpobj.h>
40 #include <sys/dmu.h>
41 #include <sys/dmu_tx.h>
42 #include <sys/dsl_dir.h>
43 #include <sys/vdev_impl.h>
44 #include <sys/vdev_rebuild.h>
45 #include <sys/vdev_draid.h>
46 #include <sys/uberblock_impl.h>
47 #include <sys/metaslab.h>
48 #include <sys/metaslab_impl.h>
49 #include <sys/space_map.h>
50 #include <sys/space_reftree.h>
51 #include <sys/zio.h>
52 #include <sys/zap.h>
53 #include <sys/fs/zfs.h>
54 #include <sys/arc.h>
55 #include <sys/zil.h>
56 #include <sys/dsl_scan.h>
57 #include <sys/vdev_raidz.h>
58 #include <sys/abd.h>
59 #include <sys/vdev_initialize.h>
60 #include <sys/vdev_trim.h>
61 #include <sys/zvol.h>
62 #include <sys/zfs_ratelimit.h>
63 #include "zfs_prop.h"
64 
65 /*
66  * One metaslab from each (normal-class) vdev is used by the ZIL.  These are
67  * called "embedded slog metaslabs", are referenced by vdev_log_mg, and are
68  * part of the spa_embedded_log_class.  The metaslab with the most free space
69  * in each vdev is selected for this purpose when the pool is opened (or a
70  * vdev is added).  See vdev_metaslab_init().
71  *
72  * Log blocks can be allocated from the following locations.  Each one is tried
73  * in order until the allocation succeeds:
74  * 1. dedicated log vdevs, aka "slog" (spa_log_class)
75  * 2. embedded slog metaslabs (spa_embedded_log_class)
76  * 3. other metaslabs in normal vdevs (spa_normal_class)
77  *
78  * zfs_embedded_slog_min_ms disables the embedded slog if there are fewer
79  * than this number of metaslabs in the vdev.  This ensures that we don't set
80  * aside an unreasonable amount of space for the ZIL.  If set to less than
81  * 1 << (spa_slop_shift + 1), on small pools the usable space may be reduced
82  * (by more than 1<<spa_slop_shift) due to the embedded slog metaslab.
83  */
84 static uint_t zfs_embedded_slog_min_ms = 64;
85 
86 /* default target for number of metaslabs per top-level vdev */
87 static uint_t zfs_vdev_default_ms_count = 200;
88 
89 /* minimum number of metaslabs per top-level vdev */
90 static uint_t zfs_vdev_min_ms_count = 16;
91 
92 /* practical upper limit of total metaslabs per top-level vdev */
93 static uint_t zfs_vdev_ms_count_limit = 1ULL << 17;
94 
95 /* lower limit for metaslab size (512M) */
96 static uint_t zfs_vdev_default_ms_shift = 29;
97 
98 /* upper limit for metaslab size (16G) */
99 static const uint_t zfs_vdev_max_ms_shift = 34;
100 
101 int vdev_validate_skip = B_FALSE;
102 
103 /*
104  * Since the DTL space map of a vdev is not expected to have a lot of
105  * entries, we default its block size to 4K.
106  */
107 int zfs_vdev_dtl_sm_blksz = (1 << 12);
108 
109 /*
110  * Rate limit slow IO (delay) events to this many per second.
111  */
112 static unsigned int zfs_slow_io_events_per_second = 20;
113 
114 /*
115  * Rate limit checksum events after this many checksum errors per second.
116  */
117 static unsigned int zfs_checksum_events_per_second = 20;
118 
119 /*
120  * Ignore errors during scrub/resilver.  Allows to work around resilver
121  * upon import when there are pool errors.
122  */
123 static int zfs_scan_ignore_errors = 0;
124 
125 /*
126  * vdev-wide space maps that have lots of entries written to them at
127  * the end of each transaction can benefit from a higher I/O bandwidth
128  * (e.g. vdev_obsolete_sm), thus we default their block size to 128K.
129  */
130 int zfs_vdev_standard_sm_blksz = (1 << 17);
131 
132 /*
133  * Tunable parameter for debugging or performance analysis. Setting this
134  * will cause pool corruption on power loss if a volatile out-of-order
135  * write cache is enabled.
136  */
137 int zfs_nocacheflush = 0;
138 
139 /*
140  * Maximum and minimum ashift values that can be automatically set based on
141  * vdev's physical ashift (disk's physical sector size).  While ASHIFT_MAX
142  * is higher than the maximum value, it is intentionally limited here to not
143  * excessively impact pool space efficiency.  Higher ashift values may still
144  * be forced by vdev logical ashift or by user via ashift property, but won't
145  * be set automatically as a performance optimization.
146  */
147 uint64_t zfs_vdev_max_auto_ashift = 14;
148 uint64_t zfs_vdev_min_auto_ashift = ASHIFT_MIN;
149 
150 void
151 vdev_dbgmsg(vdev_t *vd, const char *fmt, ...)
152 {
153 	va_list adx;
154 	char buf[256];
155 
156 	va_start(adx, fmt);
157 	(void) vsnprintf(buf, sizeof (buf), fmt, adx);
158 	va_end(adx);
159 
160 	if (vd->vdev_path != NULL) {
161 		zfs_dbgmsg("%s vdev '%s': %s", vd->vdev_ops->vdev_op_type,
162 		    vd->vdev_path, buf);
163 	} else {
164 		zfs_dbgmsg("%s-%llu vdev (guid %llu): %s",
165 		    vd->vdev_ops->vdev_op_type,
166 		    (u_longlong_t)vd->vdev_id,
167 		    (u_longlong_t)vd->vdev_guid, buf);
168 	}
169 }
170 
171 void
172 vdev_dbgmsg_print_tree(vdev_t *vd, int indent)
173 {
174 	char state[20];
175 
176 	if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops) {
177 		zfs_dbgmsg("%*svdev %llu: %s", indent, "",
178 		    (u_longlong_t)vd->vdev_id,
179 		    vd->vdev_ops->vdev_op_type);
180 		return;
181 	}
182 
183 	switch (vd->vdev_state) {
184 	case VDEV_STATE_UNKNOWN:
185 		(void) snprintf(state, sizeof (state), "unknown");
186 		break;
187 	case VDEV_STATE_CLOSED:
188 		(void) snprintf(state, sizeof (state), "closed");
189 		break;
190 	case VDEV_STATE_OFFLINE:
191 		(void) snprintf(state, sizeof (state), "offline");
192 		break;
193 	case VDEV_STATE_REMOVED:
194 		(void) snprintf(state, sizeof (state), "removed");
195 		break;
196 	case VDEV_STATE_CANT_OPEN:
197 		(void) snprintf(state, sizeof (state), "can't open");
198 		break;
199 	case VDEV_STATE_FAULTED:
200 		(void) snprintf(state, sizeof (state), "faulted");
201 		break;
202 	case VDEV_STATE_DEGRADED:
203 		(void) snprintf(state, sizeof (state), "degraded");
204 		break;
205 	case VDEV_STATE_HEALTHY:
206 		(void) snprintf(state, sizeof (state), "healthy");
207 		break;
208 	default:
209 		(void) snprintf(state, sizeof (state), "<state %u>",
210 		    (uint_t)vd->vdev_state);
211 	}
212 
213 	zfs_dbgmsg("%*svdev %u: %s%s, guid: %llu, path: %s, %s", indent,
214 	    "", (int)vd->vdev_id, vd->vdev_ops->vdev_op_type,
215 	    vd->vdev_islog ? " (log)" : "",
216 	    (u_longlong_t)vd->vdev_guid,
217 	    vd->vdev_path ? vd->vdev_path : "N/A", state);
218 
219 	for (uint64_t i = 0; i < vd->vdev_children; i++)
220 		vdev_dbgmsg_print_tree(vd->vdev_child[i], indent + 2);
221 }
222 
223 /*
224  * Virtual device management.
225  */
226 
227 static vdev_ops_t *const vdev_ops_table[] = {
228 	&vdev_root_ops,
229 	&vdev_raidz_ops,
230 	&vdev_draid_ops,
231 	&vdev_draid_spare_ops,
232 	&vdev_mirror_ops,
233 	&vdev_replacing_ops,
234 	&vdev_spare_ops,
235 	&vdev_disk_ops,
236 	&vdev_file_ops,
237 	&vdev_missing_ops,
238 	&vdev_hole_ops,
239 	&vdev_indirect_ops,
240 	NULL
241 };
242 
243 /*
244  * Given a vdev type, return the appropriate ops vector.
245  */
246 static vdev_ops_t *
247 vdev_getops(const char *type)
248 {
249 	vdev_ops_t *ops, *const *opspp;
250 
251 	for (opspp = vdev_ops_table; (ops = *opspp) != NULL; opspp++)
252 		if (strcmp(ops->vdev_op_type, type) == 0)
253 			break;
254 
255 	return (ops);
256 }
257 
258 /*
259  * Given a vdev and a metaslab class, find which metaslab group we're
260  * interested in. All vdevs may belong to two different metaslab classes.
261  * Dedicated slog devices use only the primary metaslab group, rather than a
262  * separate log group. For embedded slogs, the vdev_log_mg will be non-NULL.
263  */
264 metaslab_group_t *
265 vdev_get_mg(vdev_t *vd, metaslab_class_t *mc)
266 {
267 	if (mc == spa_embedded_log_class(vd->vdev_spa) &&
268 	    vd->vdev_log_mg != NULL)
269 		return (vd->vdev_log_mg);
270 	else
271 		return (vd->vdev_mg);
272 }
273 
274 void
275 vdev_default_xlate(vdev_t *vd, const range_seg64_t *logical_rs,
276     range_seg64_t *physical_rs, range_seg64_t *remain_rs)
277 {
278 	(void) vd, (void) remain_rs;
279 
280 	physical_rs->rs_start = logical_rs->rs_start;
281 	physical_rs->rs_end = logical_rs->rs_end;
282 }
283 
284 /*
285  * Derive the enumerated allocation bias from string input.
286  * String origin is either the per-vdev zap or zpool(8).
287  */
288 static vdev_alloc_bias_t
289 vdev_derive_alloc_bias(const char *bias)
290 {
291 	vdev_alloc_bias_t alloc_bias = VDEV_BIAS_NONE;
292 
293 	if (strcmp(bias, VDEV_ALLOC_BIAS_LOG) == 0)
294 		alloc_bias = VDEV_BIAS_LOG;
295 	else if (strcmp(bias, VDEV_ALLOC_BIAS_SPECIAL) == 0)
296 		alloc_bias = VDEV_BIAS_SPECIAL;
297 	else if (strcmp(bias, VDEV_ALLOC_BIAS_DEDUP) == 0)
298 		alloc_bias = VDEV_BIAS_DEDUP;
299 
300 	return (alloc_bias);
301 }
302 
303 /*
304  * Default asize function: return the MAX of psize with the asize of
305  * all children.  This is what's used by anything other than RAID-Z.
306  */
307 uint64_t
308 vdev_default_asize(vdev_t *vd, uint64_t psize)
309 {
310 	uint64_t asize = P2ROUNDUP(psize, 1ULL << vd->vdev_top->vdev_ashift);
311 	uint64_t csize;
312 
313 	for (int c = 0; c < vd->vdev_children; c++) {
314 		csize = vdev_psize_to_asize(vd->vdev_child[c], psize);
315 		asize = MAX(asize, csize);
316 	}
317 
318 	return (asize);
319 }
320 
321 uint64_t
322 vdev_default_min_asize(vdev_t *vd)
323 {
324 	return (vd->vdev_min_asize);
325 }
326 
327 /*
328  * Get the minimum allocatable size. We define the allocatable size as
329  * the vdev's asize rounded to the nearest metaslab. This allows us to
330  * replace or attach devices which don't have the same physical size but
331  * can still satisfy the same number of allocations.
332  */
333 uint64_t
334 vdev_get_min_asize(vdev_t *vd)
335 {
336 	vdev_t *pvd = vd->vdev_parent;
337 
338 	/*
339 	 * If our parent is NULL (inactive spare or cache) or is the root,
340 	 * just return our own asize.
341 	 */
342 	if (pvd == NULL)
343 		return (vd->vdev_asize);
344 
345 	/*
346 	 * The top-level vdev just returns the allocatable size rounded
347 	 * to the nearest metaslab.
348 	 */
349 	if (vd == vd->vdev_top)
350 		return (P2ALIGN(vd->vdev_asize, 1ULL << vd->vdev_ms_shift));
351 
352 	return (pvd->vdev_ops->vdev_op_min_asize(pvd));
353 }
354 
355 void
356 vdev_set_min_asize(vdev_t *vd)
357 {
358 	vd->vdev_min_asize = vdev_get_min_asize(vd);
359 
360 	for (int c = 0; c < vd->vdev_children; c++)
361 		vdev_set_min_asize(vd->vdev_child[c]);
362 }
363 
364 /*
365  * Get the minimal allocation size for the top-level vdev.
366  */
367 uint64_t
368 vdev_get_min_alloc(vdev_t *vd)
369 {
370 	uint64_t min_alloc = 1ULL << vd->vdev_ashift;
371 
372 	if (vd->vdev_ops->vdev_op_min_alloc != NULL)
373 		min_alloc = vd->vdev_ops->vdev_op_min_alloc(vd);
374 
375 	return (min_alloc);
376 }
377 
378 /*
379  * Get the parity level for a top-level vdev.
380  */
381 uint64_t
382 vdev_get_nparity(vdev_t *vd)
383 {
384 	uint64_t nparity = 0;
385 
386 	if (vd->vdev_ops->vdev_op_nparity != NULL)
387 		nparity = vd->vdev_ops->vdev_op_nparity(vd);
388 
389 	return (nparity);
390 }
391 
392 /*
393  * Get the number of data disks for a top-level vdev.
394  */
395 uint64_t
396 vdev_get_ndisks(vdev_t *vd)
397 {
398 	uint64_t ndisks = 1;
399 
400 	if (vd->vdev_ops->vdev_op_ndisks != NULL)
401 		ndisks = vd->vdev_ops->vdev_op_ndisks(vd);
402 
403 	return (ndisks);
404 }
405 
406 vdev_t *
407 vdev_lookup_top(spa_t *spa, uint64_t vdev)
408 {
409 	vdev_t *rvd = spa->spa_root_vdev;
410 
411 	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
412 
413 	if (vdev < rvd->vdev_children) {
414 		ASSERT(rvd->vdev_child[vdev] != NULL);
415 		return (rvd->vdev_child[vdev]);
416 	}
417 
418 	return (NULL);
419 }
420 
421 vdev_t *
422 vdev_lookup_by_guid(vdev_t *vd, uint64_t guid)
423 {
424 	vdev_t *mvd;
425 
426 	if (vd->vdev_guid == guid)
427 		return (vd);
428 
429 	for (int c = 0; c < vd->vdev_children; c++)
430 		if ((mvd = vdev_lookup_by_guid(vd->vdev_child[c], guid)) !=
431 		    NULL)
432 			return (mvd);
433 
434 	return (NULL);
435 }
436 
437 static int
438 vdev_count_leaves_impl(vdev_t *vd)
439 {
440 	int n = 0;
441 
442 	if (vd->vdev_ops->vdev_op_leaf)
443 		return (1);
444 
445 	for (int c = 0; c < vd->vdev_children; c++)
446 		n += vdev_count_leaves_impl(vd->vdev_child[c]);
447 
448 	return (n);
449 }
450 
451 int
452 vdev_count_leaves(spa_t *spa)
453 {
454 	int rc;
455 
456 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
457 	rc = vdev_count_leaves_impl(spa->spa_root_vdev);
458 	spa_config_exit(spa, SCL_VDEV, FTAG);
459 
460 	return (rc);
461 }
462 
463 void
464 vdev_add_child(vdev_t *pvd, vdev_t *cvd)
465 {
466 	size_t oldsize, newsize;
467 	uint64_t id = cvd->vdev_id;
468 	vdev_t **newchild;
469 
470 	ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
471 	ASSERT(cvd->vdev_parent == NULL);
472 
473 	cvd->vdev_parent = pvd;
474 
475 	if (pvd == NULL)
476 		return;
477 
478 	ASSERT(id >= pvd->vdev_children || pvd->vdev_child[id] == NULL);
479 
480 	oldsize = pvd->vdev_children * sizeof (vdev_t *);
481 	pvd->vdev_children = MAX(pvd->vdev_children, id + 1);
482 	newsize = pvd->vdev_children * sizeof (vdev_t *);
483 
484 	newchild = kmem_alloc(newsize, KM_SLEEP);
485 	if (pvd->vdev_child != NULL) {
486 		memcpy(newchild, pvd->vdev_child, oldsize);
487 		kmem_free(pvd->vdev_child, oldsize);
488 	}
489 
490 	pvd->vdev_child = newchild;
491 	pvd->vdev_child[id] = cvd;
492 
493 	cvd->vdev_top = (pvd->vdev_top ? pvd->vdev_top: cvd);
494 	ASSERT(cvd->vdev_top->vdev_parent->vdev_parent == NULL);
495 
496 	/*
497 	 * Walk up all ancestors to update guid sum.
498 	 */
499 	for (; pvd != NULL; pvd = pvd->vdev_parent)
500 		pvd->vdev_guid_sum += cvd->vdev_guid_sum;
501 
502 	if (cvd->vdev_ops->vdev_op_leaf) {
503 		list_insert_head(&cvd->vdev_spa->spa_leaf_list, cvd);
504 		cvd->vdev_spa->spa_leaf_list_gen++;
505 	}
506 }
507 
508 void
509 vdev_remove_child(vdev_t *pvd, vdev_t *cvd)
510 {
511 	int c;
512 	uint_t id = cvd->vdev_id;
513 
514 	ASSERT(cvd->vdev_parent == pvd);
515 
516 	if (pvd == NULL)
517 		return;
518 
519 	ASSERT(id < pvd->vdev_children);
520 	ASSERT(pvd->vdev_child[id] == cvd);
521 
522 	pvd->vdev_child[id] = NULL;
523 	cvd->vdev_parent = NULL;
524 
525 	for (c = 0; c < pvd->vdev_children; c++)
526 		if (pvd->vdev_child[c])
527 			break;
528 
529 	if (c == pvd->vdev_children) {
530 		kmem_free(pvd->vdev_child, c * sizeof (vdev_t *));
531 		pvd->vdev_child = NULL;
532 		pvd->vdev_children = 0;
533 	}
534 
535 	if (cvd->vdev_ops->vdev_op_leaf) {
536 		spa_t *spa = cvd->vdev_spa;
537 		list_remove(&spa->spa_leaf_list, cvd);
538 		spa->spa_leaf_list_gen++;
539 	}
540 
541 	/*
542 	 * Walk up all ancestors to update guid sum.
543 	 */
544 	for (; pvd != NULL; pvd = pvd->vdev_parent)
545 		pvd->vdev_guid_sum -= cvd->vdev_guid_sum;
546 }
547 
548 /*
549  * Remove any holes in the child array.
550  */
551 void
552 vdev_compact_children(vdev_t *pvd)
553 {
554 	vdev_t **newchild, *cvd;
555 	int oldc = pvd->vdev_children;
556 	int newc;
557 
558 	ASSERT(spa_config_held(pvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
559 
560 	if (oldc == 0)
561 		return;
562 
563 	for (int c = newc = 0; c < oldc; c++)
564 		if (pvd->vdev_child[c])
565 			newc++;
566 
567 	if (newc > 0) {
568 		newchild = kmem_zalloc(newc * sizeof (vdev_t *), KM_SLEEP);
569 
570 		for (int c = newc = 0; c < oldc; c++) {
571 			if ((cvd = pvd->vdev_child[c]) != NULL) {
572 				newchild[newc] = cvd;
573 				cvd->vdev_id = newc++;
574 			}
575 		}
576 	} else {
577 		newchild = NULL;
578 	}
579 
580 	kmem_free(pvd->vdev_child, oldc * sizeof (vdev_t *));
581 	pvd->vdev_child = newchild;
582 	pvd->vdev_children = newc;
583 }
584 
585 /*
586  * Allocate and minimally initialize a vdev_t.
587  */
588 vdev_t *
589 vdev_alloc_common(spa_t *spa, uint_t id, uint64_t guid, vdev_ops_t *ops)
590 {
591 	vdev_t *vd;
592 	vdev_indirect_config_t *vic;
593 
594 	vd = kmem_zalloc(sizeof (vdev_t), KM_SLEEP);
595 	vic = &vd->vdev_indirect_config;
596 
597 	if (spa->spa_root_vdev == NULL) {
598 		ASSERT(ops == &vdev_root_ops);
599 		spa->spa_root_vdev = vd;
600 		spa->spa_load_guid = spa_generate_guid(NULL);
601 	}
602 
603 	if (guid == 0 && ops != &vdev_hole_ops) {
604 		if (spa->spa_root_vdev == vd) {
605 			/*
606 			 * The root vdev's guid will also be the pool guid,
607 			 * which must be unique among all pools.
608 			 */
609 			guid = spa_generate_guid(NULL);
610 		} else {
611 			/*
612 			 * Any other vdev's guid must be unique within the pool.
613 			 */
614 			guid = spa_generate_guid(spa);
615 		}
616 		ASSERT(!spa_guid_exists(spa_guid(spa), guid));
617 	}
618 
619 	vd->vdev_spa = spa;
620 	vd->vdev_id = id;
621 	vd->vdev_guid = guid;
622 	vd->vdev_guid_sum = guid;
623 	vd->vdev_ops = ops;
624 	vd->vdev_state = VDEV_STATE_CLOSED;
625 	vd->vdev_ishole = (ops == &vdev_hole_ops);
626 	vic->vic_prev_indirect_vdev = UINT64_MAX;
627 
628 	rw_init(&vd->vdev_indirect_rwlock, NULL, RW_DEFAULT, NULL);
629 	mutex_init(&vd->vdev_obsolete_lock, NULL, MUTEX_DEFAULT, NULL);
630 	vd->vdev_obsolete_segments = range_tree_create(NULL, RANGE_SEG64, NULL,
631 	    0, 0);
632 
633 	/*
634 	 * Initialize rate limit structs for events.  We rate limit ZIO delay
635 	 * and checksum events so that we don't overwhelm ZED with thousands
636 	 * of events when a disk is acting up.
637 	 */
638 	zfs_ratelimit_init(&vd->vdev_delay_rl, &zfs_slow_io_events_per_second,
639 	    1);
640 	zfs_ratelimit_init(&vd->vdev_deadman_rl, &zfs_slow_io_events_per_second,
641 	    1);
642 	zfs_ratelimit_init(&vd->vdev_checksum_rl,
643 	    &zfs_checksum_events_per_second, 1);
644 
645 	list_link_init(&vd->vdev_config_dirty_node);
646 	list_link_init(&vd->vdev_state_dirty_node);
647 	list_link_init(&vd->vdev_initialize_node);
648 	list_link_init(&vd->vdev_leaf_node);
649 	list_link_init(&vd->vdev_trim_node);
650 
651 	mutex_init(&vd->vdev_dtl_lock, NULL, MUTEX_NOLOCKDEP, NULL);
652 	mutex_init(&vd->vdev_stat_lock, NULL, MUTEX_DEFAULT, NULL);
653 	mutex_init(&vd->vdev_probe_lock, NULL, MUTEX_DEFAULT, NULL);
654 	mutex_init(&vd->vdev_scan_io_queue_lock, NULL, MUTEX_DEFAULT, NULL);
655 
656 	mutex_init(&vd->vdev_initialize_lock, NULL, MUTEX_DEFAULT, NULL);
657 	mutex_init(&vd->vdev_initialize_io_lock, NULL, MUTEX_DEFAULT, NULL);
658 	cv_init(&vd->vdev_initialize_cv, NULL, CV_DEFAULT, NULL);
659 	cv_init(&vd->vdev_initialize_io_cv, NULL, CV_DEFAULT, NULL);
660 
661 	mutex_init(&vd->vdev_trim_lock, NULL, MUTEX_DEFAULT, NULL);
662 	mutex_init(&vd->vdev_autotrim_lock, NULL, MUTEX_DEFAULT, NULL);
663 	mutex_init(&vd->vdev_trim_io_lock, NULL, MUTEX_DEFAULT, NULL);
664 	cv_init(&vd->vdev_trim_cv, NULL, CV_DEFAULT, NULL);
665 	cv_init(&vd->vdev_autotrim_cv, NULL, CV_DEFAULT, NULL);
666 	cv_init(&vd->vdev_trim_io_cv, NULL, CV_DEFAULT, NULL);
667 
668 	mutex_init(&vd->vdev_rebuild_lock, NULL, MUTEX_DEFAULT, NULL);
669 	cv_init(&vd->vdev_rebuild_cv, NULL, CV_DEFAULT, NULL);
670 
671 	for (int t = 0; t < DTL_TYPES; t++) {
672 		vd->vdev_dtl[t] = range_tree_create(NULL, RANGE_SEG64, NULL, 0,
673 		    0);
674 	}
675 
676 	txg_list_create(&vd->vdev_ms_list, spa,
677 	    offsetof(struct metaslab, ms_txg_node));
678 	txg_list_create(&vd->vdev_dtl_list, spa,
679 	    offsetof(struct vdev, vdev_dtl_node));
680 	vd->vdev_stat.vs_timestamp = gethrtime();
681 	vdev_queue_init(vd);
682 	vdev_cache_init(vd);
683 
684 	return (vd);
685 }
686 
687 /*
688  * Allocate a new vdev.  The 'alloctype' is used to control whether we are
689  * creating a new vdev or loading an existing one - the behavior is slightly
690  * different for each case.
691  */
692 int
693 vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
694     int alloctype)
695 {
696 	vdev_ops_t *ops;
697 	char *type;
698 	uint64_t guid = 0, islog;
699 	vdev_t *vd;
700 	vdev_indirect_config_t *vic;
701 	char *tmp = NULL;
702 	int rc;
703 	vdev_alloc_bias_t alloc_bias = VDEV_BIAS_NONE;
704 	boolean_t top_level = (parent && !parent->vdev_parent);
705 
706 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
707 
708 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
709 		return (SET_ERROR(EINVAL));
710 
711 	if ((ops = vdev_getops(type)) == NULL)
712 		return (SET_ERROR(EINVAL));
713 
714 	/*
715 	 * If this is a load, get the vdev guid from the nvlist.
716 	 * Otherwise, vdev_alloc_common() will generate one for us.
717 	 */
718 	if (alloctype == VDEV_ALLOC_LOAD) {
719 		uint64_t label_id;
720 
721 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID, &label_id) ||
722 		    label_id != id)
723 			return (SET_ERROR(EINVAL));
724 
725 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
726 			return (SET_ERROR(EINVAL));
727 	} else if (alloctype == VDEV_ALLOC_SPARE) {
728 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
729 			return (SET_ERROR(EINVAL));
730 	} else if (alloctype == VDEV_ALLOC_L2CACHE) {
731 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
732 			return (SET_ERROR(EINVAL));
733 	} else if (alloctype == VDEV_ALLOC_ROOTPOOL) {
734 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
735 			return (SET_ERROR(EINVAL));
736 	}
737 
738 	/*
739 	 * The first allocated vdev must be of type 'root'.
740 	 */
741 	if (ops != &vdev_root_ops && spa->spa_root_vdev == NULL)
742 		return (SET_ERROR(EINVAL));
743 
744 	/*
745 	 * Determine whether we're a log vdev.
746 	 */
747 	islog = 0;
748 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &islog);
749 	if (islog && spa_version(spa) < SPA_VERSION_SLOGS)
750 		return (SET_ERROR(ENOTSUP));
751 
752 	if (ops == &vdev_hole_ops && spa_version(spa) < SPA_VERSION_HOLES)
753 		return (SET_ERROR(ENOTSUP));
754 
755 	if (top_level && alloctype == VDEV_ALLOC_ADD) {
756 		char *bias;
757 
758 		/*
759 		 * If creating a top-level vdev, check for allocation
760 		 * classes input.
761 		 */
762 		if (nvlist_lookup_string(nv, ZPOOL_CONFIG_ALLOCATION_BIAS,
763 		    &bias) == 0) {
764 			alloc_bias = vdev_derive_alloc_bias(bias);
765 
766 			/* spa_vdev_add() expects feature to be enabled */
767 			if (spa->spa_load_state != SPA_LOAD_CREATE &&
768 			    !spa_feature_is_enabled(spa,
769 			    SPA_FEATURE_ALLOCATION_CLASSES)) {
770 				return (SET_ERROR(ENOTSUP));
771 			}
772 		}
773 
774 		/* spa_vdev_add() expects feature to be enabled */
775 		if (ops == &vdev_draid_ops &&
776 		    spa->spa_load_state != SPA_LOAD_CREATE &&
777 		    !spa_feature_is_enabled(spa, SPA_FEATURE_DRAID)) {
778 			return (SET_ERROR(ENOTSUP));
779 		}
780 	}
781 
782 	/*
783 	 * Initialize the vdev specific data.  This is done before calling
784 	 * vdev_alloc_common() since it may fail and this simplifies the
785 	 * error reporting and cleanup code paths.
786 	 */
787 	void *tsd = NULL;
788 	if (ops->vdev_op_init != NULL) {
789 		rc = ops->vdev_op_init(spa, nv, &tsd);
790 		if (rc != 0) {
791 			return (rc);
792 		}
793 	}
794 
795 	vd = vdev_alloc_common(spa, id, guid, ops);
796 	vd->vdev_tsd = tsd;
797 	vd->vdev_islog = islog;
798 
799 	if (top_level && alloc_bias != VDEV_BIAS_NONE)
800 		vd->vdev_alloc_bias = alloc_bias;
801 
802 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &vd->vdev_path) == 0)
803 		vd->vdev_path = spa_strdup(vd->vdev_path);
804 
805 	/*
806 	 * ZPOOL_CONFIG_AUX_STATE = "external" means we previously forced a
807 	 * fault on a vdev and want it to persist across imports (like with
808 	 * zpool offline -f).
809 	 */
810 	rc = nvlist_lookup_string(nv, ZPOOL_CONFIG_AUX_STATE, &tmp);
811 	if (rc == 0 && tmp != NULL && strcmp(tmp, "external") == 0) {
812 		vd->vdev_stat.vs_aux = VDEV_AUX_EXTERNAL;
813 		vd->vdev_faulted = 1;
814 		vd->vdev_label_aux = VDEV_AUX_EXTERNAL;
815 	}
816 
817 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &vd->vdev_devid) == 0)
818 		vd->vdev_devid = spa_strdup(vd->vdev_devid);
819 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PHYS_PATH,
820 	    &vd->vdev_physpath) == 0)
821 		vd->vdev_physpath = spa_strdup(vd->vdev_physpath);
822 
823 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_VDEV_ENC_SYSFS_PATH,
824 	    &vd->vdev_enc_sysfs_path) == 0)
825 		vd->vdev_enc_sysfs_path = spa_strdup(vd->vdev_enc_sysfs_path);
826 
827 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_FRU, &vd->vdev_fru) == 0)
828 		vd->vdev_fru = spa_strdup(vd->vdev_fru);
829 
830 	/*
831 	 * Set the whole_disk property.  If it's not specified, leave the value
832 	 * as -1.
833 	 */
834 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
835 	    &vd->vdev_wholedisk) != 0)
836 		vd->vdev_wholedisk = -1ULL;
837 
838 	vic = &vd->vdev_indirect_config;
839 
840 	ASSERT0(vic->vic_mapping_object);
841 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_INDIRECT_OBJECT,
842 	    &vic->vic_mapping_object);
843 	ASSERT0(vic->vic_births_object);
844 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_INDIRECT_BIRTHS,
845 	    &vic->vic_births_object);
846 	ASSERT3U(vic->vic_prev_indirect_vdev, ==, UINT64_MAX);
847 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_PREV_INDIRECT_VDEV,
848 	    &vic->vic_prev_indirect_vdev);
849 
850 	/*
851 	 * Look for the 'not present' flag.  This will only be set if the device
852 	 * was not present at the time of import.
853 	 */
854 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
855 	    &vd->vdev_not_present);
856 
857 	/*
858 	 * Get the alignment requirement.
859 	 */
860 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT, &vd->vdev_ashift);
861 
862 	/*
863 	 * Retrieve the vdev creation time.
864 	 */
865 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_CREATE_TXG,
866 	    &vd->vdev_crtxg);
867 
868 	/*
869 	 * If we're a top-level vdev, try to load the allocation parameters.
870 	 */
871 	if (top_level &&
872 	    (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
873 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
874 		    &vd->vdev_ms_array);
875 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
876 		    &vd->vdev_ms_shift);
877 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASIZE,
878 		    &vd->vdev_asize);
879 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NONALLOCATING,
880 		    &vd->vdev_noalloc);
881 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVING,
882 		    &vd->vdev_removing);
883 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_VDEV_TOP_ZAP,
884 		    &vd->vdev_top_zap);
885 	} else {
886 		ASSERT0(vd->vdev_top_zap);
887 	}
888 
889 	if (top_level && alloctype != VDEV_ALLOC_ATTACH) {
890 		ASSERT(alloctype == VDEV_ALLOC_LOAD ||
891 		    alloctype == VDEV_ALLOC_ADD ||
892 		    alloctype == VDEV_ALLOC_SPLIT ||
893 		    alloctype == VDEV_ALLOC_ROOTPOOL);
894 		/* Note: metaslab_group_create() is now deferred */
895 	}
896 
897 	if (vd->vdev_ops->vdev_op_leaf &&
898 	    (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
899 		(void) nvlist_lookup_uint64(nv,
900 		    ZPOOL_CONFIG_VDEV_LEAF_ZAP, &vd->vdev_leaf_zap);
901 	} else {
902 		ASSERT0(vd->vdev_leaf_zap);
903 	}
904 
905 	/*
906 	 * If we're a leaf vdev, try to load the DTL object and other state.
907 	 */
908 
909 	if (vd->vdev_ops->vdev_op_leaf &&
910 	    (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_L2CACHE ||
911 	    alloctype == VDEV_ALLOC_ROOTPOOL)) {
912 		if (alloctype == VDEV_ALLOC_LOAD) {
913 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DTL,
914 			    &vd->vdev_dtl_object);
915 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_UNSPARE,
916 			    &vd->vdev_unspare);
917 		}
918 
919 		if (alloctype == VDEV_ALLOC_ROOTPOOL) {
920 			uint64_t spare = 0;
921 
922 			if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
923 			    &spare) == 0 && spare)
924 				spa_spare_add(vd);
925 		}
926 
927 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE,
928 		    &vd->vdev_offline);
929 
930 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_RESILVER_TXG,
931 		    &vd->vdev_resilver_txg);
932 
933 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REBUILD_TXG,
934 		    &vd->vdev_rebuild_txg);
935 
936 		if (nvlist_exists(nv, ZPOOL_CONFIG_RESILVER_DEFER))
937 			vdev_defer_resilver(vd);
938 
939 		/*
940 		 * In general, when importing a pool we want to ignore the
941 		 * persistent fault state, as the diagnosis made on another
942 		 * system may not be valid in the current context.  The only
943 		 * exception is if we forced a vdev to a persistently faulted
944 		 * state with 'zpool offline -f'.  The persistent fault will
945 		 * remain across imports until cleared.
946 		 *
947 		 * Local vdevs will remain in the faulted state.
948 		 */
949 		if (spa_load_state(spa) == SPA_LOAD_OPEN ||
950 		    spa_load_state(spa) == SPA_LOAD_IMPORT) {
951 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED,
952 			    &vd->vdev_faulted);
953 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DEGRADED,
954 			    &vd->vdev_degraded);
955 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED,
956 			    &vd->vdev_removed);
957 
958 			if (vd->vdev_faulted || vd->vdev_degraded) {
959 				char *aux;
960 
961 				vd->vdev_label_aux =
962 				    VDEV_AUX_ERR_EXCEEDED;
963 				if (nvlist_lookup_string(nv,
964 				    ZPOOL_CONFIG_AUX_STATE, &aux) == 0 &&
965 				    strcmp(aux, "external") == 0)
966 					vd->vdev_label_aux = VDEV_AUX_EXTERNAL;
967 				else
968 					vd->vdev_faulted = 0ULL;
969 			}
970 		}
971 	}
972 
973 	/*
974 	 * Add ourselves to the parent's list of children.
975 	 */
976 	vdev_add_child(parent, vd);
977 
978 	*vdp = vd;
979 
980 	return (0);
981 }
982 
983 void
984 vdev_free(vdev_t *vd)
985 {
986 	spa_t *spa = vd->vdev_spa;
987 
988 	ASSERT3P(vd->vdev_initialize_thread, ==, NULL);
989 	ASSERT3P(vd->vdev_trim_thread, ==, NULL);
990 	ASSERT3P(vd->vdev_autotrim_thread, ==, NULL);
991 	ASSERT3P(vd->vdev_rebuild_thread, ==, NULL);
992 
993 	/*
994 	 * Scan queues are normally destroyed at the end of a scan. If the
995 	 * queue exists here, that implies the vdev is being removed while
996 	 * the scan is still running.
997 	 */
998 	if (vd->vdev_scan_io_queue != NULL) {
999 		mutex_enter(&vd->vdev_scan_io_queue_lock);
1000 		dsl_scan_io_queue_destroy(vd->vdev_scan_io_queue);
1001 		vd->vdev_scan_io_queue = NULL;
1002 		mutex_exit(&vd->vdev_scan_io_queue_lock);
1003 	}
1004 
1005 	/*
1006 	 * vdev_free() implies closing the vdev first.  This is simpler than
1007 	 * trying to ensure complicated semantics for all callers.
1008 	 */
1009 	vdev_close(vd);
1010 
1011 	ASSERT(!list_link_active(&vd->vdev_config_dirty_node));
1012 	ASSERT(!list_link_active(&vd->vdev_state_dirty_node));
1013 
1014 	/*
1015 	 * Free all children.
1016 	 */
1017 	for (int c = 0; c < vd->vdev_children; c++)
1018 		vdev_free(vd->vdev_child[c]);
1019 
1020 	ASSERT(vd->vdev_child == NULL);
1021 	ASSERT(vd->vdev_guid_sum == vd->vdev_guid);
1022 
1023 	if (vd->vdev_ops->vdev_op_fini != NULL)
1024 		vd->vdev_ops->vdev_op_fini(vd);
1025 
1026 	/*
1027 	 * Discard allocation state.
1028 	 */
1029 	if (vd->vdev_mg != NULL) {
1030 		vdev_metaslab_fini(vd);
1031 		metaslab_group_destroy(vd->vdev_mg);
1032 		vd->vdev_mg = NULL;
1033 	}
1034 	if (vd->vdev_log_mg != NULL) {
1035 		ASSERT0(vd->vdev_ms_count);
1036 		metaslab_group_destroy(vd->vdev_log_mg);
1037 		vd->vdev_log_mg = NULL;
1038 	}
1039 
1040 	ASSERT0(vd->vdev_stat.vs_space);
1041 	ASSERT0(vd->vdev_stat.vs_dspace);
1042 	ASSERT0(vd->vdev_stat.vs_alloc);
1043 
1044 	/*
1045 	 * Remove this vdev from its parent's child list.
1046 	 */
1047 	vdev_remove_child(vd->vdev_parent, vd);
1048 
1049 	ASSERT(vd->vdev_parent == NULL);
1050 	ASSERT(!list_link_active(&vd->vdev_leaf_node));
1051 
1052 	/*
1053 	 * Clean up vdev structure.
1054 	 */
1055 	vdev_queue_fini(vd);
1056 	vdev_cache_fini(vd);
1057 
1058 	if (vd->vdev_path)
1059 		spa_strfree(vd->vdev_path);
1060 	if (vd->vdev_devid)
1061 		spa_strfree(vd->vdev_devid);
1062 	if (vd->vdev_physpath)
1063 		spa_strfree(vd->vdev_physpath);
1064 
1065 	if (vd->vdev_enc_sysfs_path)
1066 		spa_strfree(vd->vdev_enc_sysfs_path);
1067 
1068 	if (vd->vdev_fru)
1069 		spa_strfree(vd->vdev_fru);
1070 
1071 	if (vd->vdev_isspare)
1072 		spa_spare_remove(vd);
1073 	if (vd->vdev_isl2cache)
1074 		spa_l2cache_remove(vd);
1075 
1076 	txg_list_destroy(&vd->vdev_ms_list);
1077 	txg_list_destroy(&vd->vdev_dtl_list);
1078 
1079 	mutex_enter(&vd->vdev_dtl_lock);
1080 	space_map_close(vd->vdev_dtl_sm);
1081 	for (int t = 0; t < DTL_TYPES; t++) {
1082 		range_tree_vacate(vd->vdev_dtl[t], NULL, NULL);
1083 		range_tree_destroy(vd->vdev_dtl[t]);
1084 	}
1085 	mutex_exit(&vd->vdev_dtl_lock);
1086 
1087 	EQUIV(vd->vdev_indirect_births != NULL,
1088 	    vd->vdev_indirect_mapping != NULL);
1089 	if (vd->vdev_indirect_births != NULL) {
1090 		vdev_indirect_mapping_close(vd->vdev_indirect_mapping);
1091 		vdev_indirect_births_close(vd->vdev_indirect_births);
1092 	}
1093 
1094 	if (vd->vdev_obsolete_sm != NULL) {
1095 		ASSERT(vd->vdev_removing ||
1096 		    vd->vdev_ops == &vdev_indirect_ops);
1097 		space_map_close(vd->vdev_obsolete_sm);
1098 		vd->vdev_obsolete_sm = NULL;
1099 	}
1100 	range_tree_destroy(vd->vdev_obsolete_segments);
1101 	rw_destroy(&vd->vdev_indirect_rwlock);
1102 	mutex_destroy(&vd->vdev_obsolete_lock);
1103 
1104 	mutex_destroy(&vd->vdev_dtl_lock);
1105 	mutex_destroy(&vd->vdev_stat_lock);
1106 	mutex_destroy(&vd->vdev_probe_lock);
1107 	mutex_destroy(&vd->vdev_scan_io_queue_lock);
1108 
1109 	mutex_destroy(&vd->vdev_initialize_lock);
1110 	mutex_destroy(&vd->vdev_initialize_io_lock);
1111 	cv_destroy(&vd->vdev_initialize_io_cv);
1112 	cv_destroy(&vd->vdev_initialize_cv);
1113 
1114 	mutex_destroy(&vd->vdev_trim_lock);
1115 	mutex_destroy(&vd->vdev_autotrim_lock);
1116 	mutex_destroy(&vd->vdev_trim_io_lock);
1117 	cv_destroy(&vd->vdev_trim_cv);
1118 	cv_destroy(&vd->vdev_autotrim_cv);
1119 	cv_destroy(&vd->vdev_trim_io_cv);
1120 
1121 	mutex_destroy(&vd->vdev_rebuild_lock);
1122 	cv_destroy(&vd->vdev_rebuild_cv);
1123 
1124 	zfs_ratelimit_fini(&vd->vdev_delay_rl);
1125 	zfs_ratelimit_fini(&vd->vdev_deadman_rl);
1126 	zfs_ratelimit_fini(&vd->vdev_checksum_rl);
1127 
1128 	if (vd == spa->spa_root_vdev)
1129 		spa->spa_root_vdev = NULL;
1130 
1131 	kmem_free(vd, sizeof (vdev_t));
1132 }
1133 
1134 /*
1135  * Transfer top-level vdev state from svd to tvd.
1136  */
1137 static void
1138 vdev_top_transfer(vdev_t *svd, vdev_t *tvd)
1139 {
1140 	spa_t *spa = svd->vdev_spa;
1141 	metaslab_t *msp;
1142 	vdev_t *vd;
1143 	int t;
1144 
1145 	ASSERT(tvd == tvd->vdev_top);
1146 
1147 	tvd->vdev_pending_fastwrite = svd->vdev_pending_fastwrite;
1148 	tvd->vdev_ms_array = svd->vdev_ms_array;
1149 	tvd->vdev_ms_shift = svd->vdev_ms_shift;
1150 	tvd->vdev_ms_count = svd->vdev_ms_count;
1151 	tvd->vdev_top_zap = svd->vdev_top_zap;
1152 
1153 	svd->vdev_ms_array = 0;
1154 	svd->vdev_ms_shift = 0;
1155 	svd->vdev_ms_count = 0;
1156 	svd->vdev_top_zap = 0;
1157 
1158 	if (tvd->vdev_mg)
1159 		ASSERT3P(tvd->vdev_mg, ==, svd->vdev_mg);
1160 	if (tvd->vdev_log_mg)
1161 		ASSERT3P(tvd->vdev_log_mg, ==, svd->vdev_log_mg);
1162 	tvd->vdev_mg = svd->vdev_mg;
1163 	tvd->vdev_log_mg = svd->vdev_log_mg;
1164 	tvd->vdev_ms = svd->vdev_ms;
1165 
1166 	svd->vdev_mg = NULL;
1167 	svd->vdev_log_mg = NULL;
1168 	svd->vdev_ms = NULL;
1169 
1170 	if (tvd->vdev_mg != NULL)
1171 		tvd->vdev_mg->mg_vd = tvd;
1172 	if (tvd->vdev_log_mg != NULL)
1173 		tvd->vdev_log_mg->mg_vd = tvd;
1174 
1175 	tvd->vdev_checkpoint_sm = svd->vdev_checkpoint_sm;
1176 	svd->vdev_checkpoint_sm = NULL;
1177 
1178 	tvd->vdev_alloc_bias = svd->vdev_alloc_bias;
1179 	svd->vdev_alloc_bias = VDEV_BIAS_NONE;
1180 
1181 	tvd->vdev_stat.vs_alloc = svd->vdev_stat.vs_alloc;
1182 	tvd->vdev_stat.vs_space = svd->vdev_stat.vs_space;
1183 	tvd->vdev_stat.vs_dspace = svd->vdev_stat.vs_dspace;
1184 
1185 	svd->vdev_stat.vs_alloc = 0;
1186 	svd->vdev_stat.vs_space = 0;
1187 	svd->vdev_stat.vs_dspace = 0;
1188 
1189 	/*
1190 	 * State which may be set on a top-level vdev that's in the
1191 	 * process of being removed.
1192 	 */
1193 	ASSERT0(tvd->vdev_indirect_config.vic_births_object);
1194 	ASSERT0(tvd->vdev_indirect_config.vic_mapping_object);
1195 	ASSERT3U(tvd->vdev_indirect_config.vic_prev_indirect_vdev, ==, -1ULL);
1196 	ASSERT3P(tvd->vdev_indirect_mapping, ==, NULL);
1197 	ASSERT3P(tvd->vdev_indirect_births, ==, NULL);
1198 	ASSERT3P(tvd->vdev_obsolete_sm, ==, NULL);
1199 	ASSERT0(tvd->vdev_noalloc);
1200 	ASSERT0(tvd->vdev_removing);
1201 	ASSERT0(tvd->vdev_rebuilding);
1202 	tvd->vdev_noalloc = svd->vdev_noalloc;
1203 	tvd->vdev_removing = svd->vdev_removing;
1204 	tvd->vdev_rebuilding = svd->vdev_rebuilding;
1205 	tvd->vdev_rebuild_config = svd->vdev_rebuild_config;
1206 	tvd->vdev_indirect_config = svd->vdev_indirect_config;
1207 	tvd->vdev_indirect_mapping = svd->vdev_indirect_mapping;
1208 	tvd->vdev_indirect_births = svd->vdev_indirect_births;
1209 	range_tree_swap(&svd->vdev_obsolete_segments,
1210 	    &tvd->vdev_obsolete_segments);
1211 	tvd->vdev_obsolete_sm = svd->vdev_obsolete_sm;
1212 	svd->vdev_indirect_config.vic_mapping_object = 0;
1213 	svd->vdev_indirect_config.vic_births_object = 0;
1214 	svd->vdev_indirect_config.vic_prev_indirect_vdev = -1ULL;
1215 	svd->vdev_indirect_mapping = NULL;
1216 	svd->vdev_indirect_births = NULL;
1217 	svd->vdev_obsolete_sm = NULL;
1218 	svd->vdev_noalloc = 0;
1219 	svd->vdev_removing = 0;
1220 	svd->vdev_rebuilding = 0;
1221 
1222 	for (t = 0; t < TXG_SIZE; t++) {
1223 		while ((msp = txg_list_remove(&svd->vdev_ms_list, t)) != NULL)
1224 			(void) txg_list_add(&tvd->vdev_ms_list, msp, t);
1225 		while ((vd = txg_list_remove(&svd->vdev_dtl_list, t)) != NULL)
1226 			(void) txg_list_add(&tvd->vdev_dtl_list, vd, t);
1227 		if (txg_list_remove_this(&spa->spa_vdev_txg_list, svd, t))
1228 			(void) txg_list_add(&spa->spa_vdev_txg_list, tvd, t);
1229 	}
1230 
1231 	if (list_link_active(&svd->vdev_config_dirty_node)) {
1232 		vdev_config_clean(svd);
1233 		vdev_config_dirty(tvd);
1234 	}
1235 
1236 	if (list_link_active(&svd->vdev_state_dirty_node)) {
1237 		vdev_state_clean(svd);
1238 		vdev_state_dirty(tvd);
1239 	}
1240 
1241 	tvd->vdev_deflate_ratio = svd->vdev_deflate_ratio;
1242 	svd->vdev_deflate_ratio = 0;
1243 
1244 	tvd->vdev_islog = svd->vdev_islog;
1245 	svd->vdev_islog = 0;
1246 
1247 	dsl_scan_io_queue_vdev_xfer(svd, tvd);
1248 }
1249 
1250 static void
1251 vdev_top_update(vdev_t *tvd, vdev_t *vd)
1252 {
1253 	if (vd == NULL)
1254 		return;
1255 
1256 	vd->vdev_top = tvd;
1257 
1258 	for (int c = 0; c < vd->vdev_children; c++)
1259 		vdev_top_update(tvd, vd->vdev_child[c]);
1260 }
1261 
1262 /*
1263  * Add a mirror/replacing vdev above an existing vdev.  There is no need to
1264  * call .vdev_op_init() since mirror/replacing vdevs do not have private state.
1265  */
1266 vdev_t *
1267 vdev_add_parent(vdev_t *cvd, vdev_ops_t *ops)
1268 {
1269 	spa_t *spa = cvd->vdev_spa;
1270 	vdev_t *pvd = cvd->vdev_parent;
1271 	vdev_t *mvd;
1272 
1273 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1274 
1275 	mvd = vdev_alloc_common(spa, cvd->vdev_id, 0, ops);
1276 
1277 	mvd->vdev_asize = cvd->vdev_asize;
1278 	mvd->vdev_min_asize = cvd->vdev_min_asize;
1279 	mvd->vdev_max_asize = cvd->vdev_max_asize;
1280 	mvd->vdev_psize = cvd->vdev_psize;
1281 	mvd->vdev_ashift = cvd->vdev_ashift;
1282 	mvd->vdev_logical_ashift = cvd->vdev_logical_ashift;
1283 	mvd->vdev_physical_ashift = cvd->vdev_physical_ashift;
1284 	mvd->vdev_state = cvd->vdev_state;
1285 	mvd->vdev_crtxg = cvd->vdev_crtxg;
1286 
1287 	vdev_remove_child(pvd, cvd);
1288 	vdev_add_child(pvd, mvd);
1289 	cvd->vdev_id = mvd->vdev_children;
1290 	vdev_add_child(mvd, cvd);
1291 	vdev_top_update(cvd->vdev_top, cvd->vdev_top);
1292 
1293 	if (mvd == mvd->vdev_top)
1294 		vdev_top_transfer(cvd, mvd);
1295 
1296 	return (mvd);
1297 }
1298 
1299 /*
1300  * Remove a 1-way mirror/replacing vdev from the tree.
1301  */
1302 void
1303 vdev_remove_parent(vdev_t *cvd)
1304 {
1305 	vdev_t *mvd = cvd->vdev_parent;
1306 	vdev_t *pvd = mvd->vdev_parent;
1307 
1308 	ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1309 
1310 	ASSERT(mvd->vdev_children == 1);
1311 	ASSERT(mvd->vdev_ops == &vdev_mirror_ops ||
1312 	    mvd->vdev_ops == &vdev_replacing_ops ||
1313 	    mvd->vdev_ops == &vdev_spare_ops);
1314 	cvd->vdev_ashift = mvd->vdev_ashift;
1315 	cvd->vdev_logical_ashift = mvd->vdev_logical_ashift;
1316 	cvd->vdev_physical_ashift = mvd->vdev_physical_ashift;
1317 	vdev_remove_child(mvd, cvd);
1318 	vdev_remove_child(pvd, mvd);
1319 
1320 	/*
1321 	 * If cvd will replace mvd as a top-level vdev, preserve mvd's guid.
1322 	 * Otherwise, we could have detached an offline device, and when we
1323 	 * go to import the pool we'll think we have two top-level vdevs,
1324 	 * instead of a different version of the same top-level vdev.
1325 	 */
1326 	if (mvd->vdev_top == mvd) {
1327 		uint64_t guid_delta = mvd->vdev_guid - cvd->vdev_guid;
1328 		cvd->vdev_orig_guid = cvd->vdev_guid;
1329 		cvd->vdev_guid += guid_delta;
1330 		cvd->vdev_guid_sum += guid_delta;
1331 
1332 		/*
1333 		 * If pool not set for autoexpand, we need to also preserve
1334 		 * mvd's asize to prevent automatic expansion of cvd.
1335 		 * Otherwise if we are adjusting the mirror by attaching and
1336 		 * detaching children of non-uniform sizes, the mirror could
1337 		 * autoexpand, unexpectedly requiring larger devices to
1338 		 * re-establish the mirror.
1339 		 */
1340 		if (!cvd->vdev_spa->spa_autoexpand)
1341 			cvd->vdev_asize = mvd->vdev_asize;
1342 	}
1343 	cvd->vdev_id = mvd->vdev_id;
1344 	vdev_add_child(pvd, cvd);
1345 	vdev_top_update(cvd->vdev_top, cvd->vdev_top);
1346 
1347 	if (cvd == cvd->vdev_top)
1348 		vdev_top_transfer(mvd, cvd);
1349 
1350 	ASSERT(mvd->vdev_children == 0);
1351 	vdev_free(mvd);
1352 }
1353 
1354 void
1355 vdev_metaslab_group_create(vdev_t *vd)
1356 {
1357 	spa_t *spa = vd->vdev_spa;
1358 
1359 	/*
1360 	 * metaslab_group_create was delayed until allocation bias was available
1361 	 */
1362 	if (vd->vdev_mg == NULL) {
1363 		metaslab_class_t *mc;
1364 
1365 		if (vd->vdev_islog && vd->vdev_alloc_bias == VDEV_BIAS_NONE)
1366 			vd->vdev_alloc_bias = VDEV_BIAS_LOG;
1367 
1368 		ASSERT3U(vd->vdev_islog, ==,
1369 		    (vd->vdev_alloc_bias == VDEV_BIAS_LOG));
1370 
1371 		switch (vd->vdev_alloc_bias) {
1372 		case VDEV_BIAS_LOG:
1373 			mc = spa_log_class(spa);
1374 			break;
1375 		case VDEV_BIAS_SPECIAL:
1376 			mc = spa_special_class(spa);
1377 			break;
1378 		case VDEV_BIAS_DEDUP:
1379 			mc = spa_dedup_class(spa);
1380 			break;
1381 		default:
1382 			mc = spa_normal_class(spa);
1383 		}
1384 
1385 		vd->vdev_mg = metaslab_group_create(mc, vd,
1386 		    spa->spa_alloc_count);
1387 
1388 		if (!vd->vdev_islog) {
1389 			vd->vdev_log_mg = metaslab_group_create(
1390 			    spa_embedded_log_class(spa), vd, 1);
1391 		}
1392 
1393 		/*
1394 		 * The spa ashift min/max only apply for the normal metaslab
1395 		 * class. Class destination is late binding so ashift boundary
1396 		 * setting had to wait until now.
1397 		 */
1398 		if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
1399 		    mc == spa_normal_class(spa) && vd->vdev_aux == NULL) {
1400 			if (vd->vdev_ashift > spa->spa_max_ashift)
1401 				spa->spa_max_ashift = vd->vdev_ashift;
1402 			if (vd->vdev_ashift < spa->spa_min_ashift)
1403 				spa->spa_min_ashift = vd->vdev_ashift;
1404 
1405 			uint64_t min_alloc = vdev_get_min_alloc(vd);
1406 			if (min_alloc < spa->spa_min_alloc)
1407 				spa->spa_min_alloc = min_alloc;
1408 		}
1409 	}
1410 }
1411 
1412 int
1413 vdev_metaslab_init(vdev_t *vd, uint64_t txg)
1414 {
1415 	spa_t *spa = vd->vdev_spa;
1416 	uint64_t oldc = vd->vdev_ms_count;
1417 	uint64_t newc = vd->vdev_asize >> vd->vdev_ms_shift;
1418 	metaslab_t **mspp;
1419 	int error;
1420 	boolean_t expanding = (oldc != 0);
1421 
1422 	ASSERT(txg == 0 || spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1423 
1424 	/*
1425 	 * This vdev is not being allocated from yet or is a hole.
1426 	 */
1427 	if (vd->vdev_ms_shift == 0)
1428 		return (0);
1429 
1430 	ASSERT(!vd->vdev_ishole);
1431 
1432 	ASSERT(oldc <= newc);
1433 
1434 	mspp = vmem_zalloc(newc * sizeof (*mspp), KM_SLEEP);
1435 
1436 	if (expanding) {
1437 		memcpy(mspp, vd->vdev_ms, oldc * sizeof (*mspp));
1438 		vmem_free(vd->vdev_ms, oldc * sizeof (*mspp));
1439 	}
1440 
1441 	vd->vdev_ms = mspp;
1442 	vd->vdev_ms_count = newc;
1443 
1444 	for (uint64_t m = oldc; m < newc; m++) {
1445 		uint64_t object = 0;
1446 		/*
1447 		 * vdev_ms_array may be 0 if we are creating the "fake"
1448 		 * metaslabs for an indirect vdev for zdb's leak detection.
1449 		 * See zdb_leak_init().
1450 		 */
1451 		if (txg == 0 && vd->vdev_ms_array != 0) {
1452 			error = dmu_read(spa->spa_meta_objset,
1453 			    vd->vdev_ms_array,
1454 			    m * sizeof (uint64_t), sizeof (uint64_t), &object,
1455 			    DMU_READ_PREFETCH);
1456 			if (error != 0) {
1457 				vdev_dbgmsg(vd, "unable to read the metaslab "
1458 				    "array [error=%d]", error);
1459 				return (error);
1460 			}
1461 		}
1462 
1463 		error = metaslab_init(vd->vdev_mg, m, object, txg,
1464 		    &(vd->vdev_ms[m]));
1465 		if (error != 0) {
1466 			vdev_dbgmsg(vd, "metaslab_init failed [error=%d]",
1467 			    error);
1468 			return (error);
1469 		}
1470 	}
1471 
1472 	/*
1473 	 * Find the emptiest metaslab on the vdev and mark it for use for
1474 	 * embedded slog by moving it from the regular to the log metaslab
1475 	 * group.
1476 	 */
1477 	if (vd->vdev_mg->mg_class == spa_normal_class(spa) &&
1478 	    vd->vdev_ms_count > zfs_embedded_slog_min_ms &&
1479 	    avl_is_empty(&vd->vdev_log_mg->mg_metaslab_tree)) {
1480 		uint64_t slog_msid = 0;
1481 		uint64_t smallest = UINT64_MAX;
1482 
1483 		/*
1484 		 * Note, we only search the new metaslabs, because the old
1485 		 * (pre-existing) ones may be active (e.g. have non-empty
1486 		 * range_tree's), and we don't move them to the new
1487 		 * metaslab_t.
1488 		 */
1489 		for (uint64_t m = oldc; m < newc; m++) {
1490 			uint64_t alloc =
1491 			    space_map_allocated(vd->vdev_ms[m]->ms_sm);
1492 			if (alloc < smallest) {
1493 				slog_msid = m;
1494 				smallest = alloc;
1495 			}
1496 		}
1497 		metaslab_t *slog_ms = vd->vdev_ms[slog_msid];
1498 		/*
1499 		 * The metaslab was marked as dirty at the end of
1500 		 * metaslab_init(). Remove it from the dirty list so that we
1501 		 * can uninitialize and reinitialize it to the new class.
1502 		 */
1503 		if (txg != 0) {
1504 			(void) txg_list_remove_this(&vd->vdev_ms_list,
1505 			    slog_ms, txg);
1506 		}
1507 		uint64_t sm_obj = space_map_object(slog_ms->ms_sm);
1508 		metaslab_fini(slog_ms);
1509 		VERIFY0(metaslab_init(vd->vdev_log_mg, slog_msid, sm_obj, txg,
1510 		    &vd->vdev_ms[slog_msid]));
1511 	}
1512 
1513 	if (txg == 0)
1514 		spa_config_enter(spa, SCL_ALLOC, FTAG, RW_WRITER);
1515 
1516 	/*
1517 	 * If the vdev is marked as non-allocating then don't
1518 	 * activate the metaslabs since we want to ensure that
1519 	 * no allocations are performed on this device.
1520 	 */
1521 	if (vd->vdev_noalloc) {
1522 		/* track non-allocating vdev space */
1523 		spa->spa_nonallocating_dspace += spa_deflate(spa) ?
1524 		    vd->vdev_stat.vs_dspace : vd->vdev_stat.vs_space;
1525 	} else if (!expanding) {
1526 		metaslab_group_activate(vd->vdev_mg);
1527 		if (vd->vdev_log_mg != NULL)
1528 			metaslab_group_activate(vd->vdev_log_mg);
1529 	}
1530 
1531 	if (txg == 0)
1532 		spa_config_exit(spa, SCL_ALLOC, FTAG);
1533 
1534 	return (0);
1535 }
1536 
1537 void
1538 vdev_metaslab_fini(vdev_t *vd)
1539 {
1540 	if (vd->vdev_checkpoint_sm != NULL) {
1541 		ASSERT(spa_feature_is_active(vd->vdev_spa,
1542 		    SPA_FEATURE_POOL_CHECKPOINT));
1543 		space_map_close(vd->vdev_checkpoint_sm);
1544 		/*
1545 		 * Even though we close the space map, we need to set its
1546 		 * pointer to NULL. The reason is that vdev_metaslab_fini()
1547 		 * may be called multiple times for certain operations
1548 		 * (i.e. when destroying a pool) so we need to ensure that
1549 		 * this clause never executes twice. This logic is similar
1550 		 * to the one used for the vdev_ms clause below.
1551 		 */
1552 		vd->vdev_checkpoint_sm = NULL;
1553 	}
1554 
1555 	if (vd->vdev_ms != NULL) {
1556 		metaslab_group_t *mg = vd->vdev_mg;
1557 
1558 		metaslab_group_passivate(mg);
1559 		if (vd->vdev_log_mg != NULL) {
1560 			ASSERT(!vd->vdev_islog);
1561 			metaslab_group_passivate(vd->vdev_log_mg);
1562 		}
1563 
1564 		uint64_t count = vd->vdev_ms_count;
1565 		for (uint64_t m = 0; m < count; m++) {
1566 			metaslab_t *msp = vd->vdev_ms[m];
1567 			if (msp != NULL)
1568 				metaslab_fini(msp);
1569 		}
1570 		vmem_free(vd->vdev_ms, count * sizeof (metaslab_t *));
1571 		vd->vdev_ms = NULL;
1572 		vd->vdev_ms_count = 0;
1573 
1574 		for (int i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++) {
1575 			ASSERT0(mg->mg_histogram[i]);
1576 			if (vd->vdev_log_mg != NULL)
1577 				ASSERT0(vd->vdev_log_mg->mg_histogram[i]);
1578 		}
1579 	}
1580 	ASSERT0(vd->vdev_ms_count);
1581 	ASSERT3U(vd->vdev_pending_fastwrite, ==, 0);
1582 }
1583 
1584 typedef struct vdev_probe_stats {
1585 	boolean_t	vps_readable;
1586 	boolean_t	vps_writeable;
1587 	int		vps_flags;
1588 } vdev_probe_stats_t;
1589 
1590 static void
1591 vdev_probe_done(zio_t *zio)
1592 {
1593 	spa_t *spa = zio->io_spa;
1594 	vdev_t *vd = zio->io_vd;
1595 	vdev_probe_stats_t *vps = zio->io_private;
1596 
1597 	ASSERT(vd->vdev_probe_zio != NULL);
1598 
1599 	if (zio->io_type == ZIO_TYPE_READ) {
1600 		if (zio->io_error == 0)
1601 			vps->vps_readable = 1;
1602 		if (zio->io_error == 0 && spa_writeable(spa)) {
1603 			zio_nowait(zio_write_phys(vd->vdev_probe_zio, vd,
1604 			    zio->io_offset, zio->io_size, zio->io_abd,
1605 			    ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1606 			    ZIO_PRIORITY_SYNC_WRITE, vps->vps_flags, B_TRUE));
1607 		} else {
1608 			abd_free(zio->io_abd);
1609 		}
1610 	} else if (zio->io_type == ZIO_TYPE_WRITE) {
1611 		if (zio->io_error == 0)
1612 			vps->vps_writeable = 1;
1613 		abd_free(zio->io_abd);
1614 	} else if (zio->io_type == ZIO_TYPE_NULL) {
1615 		zio_t *pio;
1616 		zio_link_t *zl;
1617 
1618 		vd->vdev_cant_read |= !vps->vps_readable;
1619 		vd->vdev_cant_write |= !vps->vps_writeable;
1620 
1621 		if (vdev_readable(vd) &&
1622 		    (vdev_writeable(vd) || !spa_writeable(spa))) {
1623 			zio->io_error = 0;
1624 		} else {
1625 			ASSERT(zio->io_error != 0);
1626 			vdev_dbgmsg(vd, "failed probe");
1627 			(void) zfs_ereport_post(FM_EREPORT_ZFS_PROBE_FAILURE,
1628 			    spa, vd, NULL, NULL, 0);
1629 			zio->io_error = SET_ERROR(ENXIO);
1630 		}
1631 
1632 		mutex_enter(&vd->vdev_probe_lock);
1633 		ASSERT(vd->vdev_probe_zio == zio);
1634 		vd->vdev_probe_zio = NULL;
1635 		mutex_exit(&vd->vdev_probe_lock);
1636 
1637 		zl = NULL;
1638 		while ((pio = zio_walk_parents(zio, &zl)) != NULL)
1639 			if (!vdev_accessible(vd, pio))
1640 				pio->io_error = SET_ERROR(ENXIO);
1641 
1642 		kmem_free(vps, sizeof (*vps));
1643 	}
1644 }
1645 
1646 /*
1647  * Determine whether this device is accessible.
1648  *
1649  * Read and write to several known locations: the pad regions of each
1650  * vdev label but the first, which we leave alone in case it contains
1651  * a VTOC.
1652  */
1653 zio_t *
1654 vdev_probe(vdev_t *vd, zio_t *zio)
1655 {
1656 	spa_t *spa = vd->vdev_spa;
1657 	vdev_probe_stats_t *vps = NULL;
1658 	zio_t *pio;
1659 
1660 	ASSERT(vd->vdev_ops->vdev_op_leaf);
1661 
1662 	/*
1663 	 * Don't probe the probe.
1664 	 */
1665 	if (zio && (zio->io_flags & ZIO_FLAG_PROBE))
1666 		return (NULL);
1667 
1668 	/*
1669 	 * To prevent 'probe storms' when a device fails, we create
1670 	 * just one probe i/o at a time.  All zios that want to probe
1671 	 * this vdev will become parents of the probe io.
1672 	 */
1673 	mutex_enter(&vd->vdev_probe_lock);
1674 
1675 	if ((pio = vd->vdev_probe_zio) == NULL) {
1676 		vps = kmem_zalloc(sizeof (*vps), KM_SLEEP);
1677 
1678 		vps->vps_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_PROBE |
1679 		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE |
1680 		    ZIO_FLAG_TRYHARD;
1681 
1682 		if (spa_config_held(spa, SCL_ZIO, RW_WRITER)) {
1683 			/*
1684 			 * vdev_cant_read and vdev_cant_write can only
1685 			 * transition from TRUE to FALSE when we have the
1686 			 * SCL_ZIO lock as writer; otherwise they can only
1687 			 * transition from FALSE to TRUE.  This ensures that
1688 			 * any zio looking at these values can assume that
1689 			 * failures persist for the life of the I/O.  That's
1690 			 * important because when a device has intermittent
1691 			 * connectivity problems, we want to ensure that
1692 			 * they're ascribed to the device (ENXIO) and not
1693 			 * the zio (EIO).
1694 			 *
1695 			 * Since we hold SCL_ZIO as writer here, clear both
1696 			 * values so the probe can reevaluate from first
1697 			 * principles.
1698 			 */
1699 			vps->vps_flags |= ZIO_FLAG_CONFIG_WRITER;
1700 			vd->vdev_cant_read = B_FALSE;
1701 			vd->vdev_cant_write = B_FALSE;
1702 		}
1703 
1704 		vd->vdev_probe_zio = pio = zio_null(NULL, spa, vd,
1705 		    vdev_probe_done, vps,
1706 		    vps->vps_flags | ZIO_FLAG_DONT_PROPAGATE);
1707 
1708 		/*
1709 		 * We can't change the vdev state in this context, so we
1710 		 * kick off an async task to do it on our behalf.
1711 		 */
1712 		if (zio != NULL) {
1713 			vd->vdev_probe_wanted = B_TRUE;
1714 			spa_async_request(spa, SPA_ASYNC_PROBE);
1715 		}
1716 	}
1717 
1718 	if (zio != NULL)
1719 		zio_add_child(zio, pio);
1720 
1721 	mutex_exit(&vd->vdev_probe_lock);
1722 
1723 	if (vps == NULL) {
1724 		ASSERT(zio != NULL);
1725 		return (NULL);
1726 	}
1727 
1728 	for (int l = 1; l < VDEV_LABELS; l++) {
1729 		zio_nowait(zio_read_phys(pio, vd,
1730 		    vdev_label_offset(vd->vdev_psize, l,
1731 		    offsetof(vdev_label_t, vl_be)), VDEV_PAD_SIZE,
1732 		    abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE),
1733 		    ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1734 		    ZIO_PRIORITY_SYNC_READ, vps->vps_flags, B_TRUE));
1735 	}
1736 
1737 	if (zio == NULL)
1738 		return (pio);
1739 
1740 	zio_nowait(pio);
1741 	return (NULL);
1742 }
1743 
1744 static void
1745 vdev_load_child(void *arg)
1746 {
1747 	vdev_t *vd = arg;
1748 
1749 	vd->vdev_load_error = vdev_load(vd);
1750 }
1751 
1752 static void
1753 vdev_open_child(void *arg)
1754 {
1755 	vdev_t *vd = arg;
1756 
1757 	vd->vdev_open_thread = curthread;
1758 	vd->vdev_open_error = vdev_open(vd);
1759 	vd->vdev_open_thread = NULL;
1760 }
1761 
1762 static boolean_t
1763 vdev_uses_zvols(vdev_t *vd)
1764 {
1765 #ifdef _KERNEL
1766 	if (zvol_is_zvol(vd->vdev_path))
1767 		return (B_TRUE);
1768 #endif
1769 
1770 	for (int c = 0; c < vd->vdev_children; c++)
1771 		if (vdev_uses_zvols(vd->vdev_child[c]))
1772 			return (B_TRUE);
1773 
1774 	return (B_FALSE);
1775 }
1776 
1777 /*
1778  * Returns B_TRUE if the passed child should be opened.
1779  */
1780 static boolean_t
1781 vdev_default_open_children_func(vdev_t *vd)
1782 {
1783 	(void) vd;
1784 	return (B_TRUE);
1785 }
1786 
1787 /*
1788  * Open the requested child vdevs.  If any of the leaf vdevs are using
1789  * a ZFS volume then do the opens in a single thread.  This avoids a
1790  * deadlock when the current thread is holding the spa_namespace_lock.
1791  */
1792 static void
1793 vdev_open_children_impl(vdev_t *vd, vdev_open_children_func_t *open_func)
1794 {
1795 	int children = vd->vdev_children;
1796 
1797 	taskq_t *tq = taskq_create("vdev_open", children, minclsyspri,
1798 	    children, children, TASKQ_PREPOPULATE);
1799 	vd->vdev_nonrot = B_TRUE;
1800 
1801 	for (int c = 0; c < children; c++) {
1802 		vdev_t *cvd = vd->vdev_child[c];
1803 
1804 		if (open_func(cvd) == B_FALSE)
1805 			continue;
1806 
1807 		if (tq == NULL || vdev_uses_zvols(vd)) {
1808 			cvd->vdev_open_error = vdev_open(cvd);
1809 		} else {
1810 			VERIFY(taskq_dispatch(tq, vdev_open_child,
1811 			    cvd, TQ_SLEEP) != TASKQID_INVALID);
1812 		}
1813 
1814 		vd->vdev_nonrot &= cvd->vdev_nonrot;
1815 	}
1816 
1817 	if (tq != NULL) {
1818 		taskq_wait(tq);
1819 		taskq_destroy(tq);
1820 	}
1821 }
1822 
1823 /*
1824  * Open all child vdevs.
1825  */
1826 void
1827 vdev_open_children(vdev_t *vd)
1828 {
1829 	vdev_open_children_impl(vd, vdev_default_open_children_func);
1830 }
1831 
1832 /*
1833  * Conditionally open a subset of child vdevs.
1834  */
1835 void
1836 vdev_open_children_subset(vdev_t *vd, vdev_open_children_func_t *open_func)
1837 {
1838 	vdev_open_children_impl(vd, open_func);
1839 }
1840 
1841 /*
1842  * Compute the raidz-deflation ratio.  Note, we hard-code
1843  * in 128k (1 << 17) because it is the "typical" blocksize.
1844  * Even though SPA_MAXBLOCKSIZE changed, this algorithm can not change,
1845  * otherwise it would inconsistently account for existing bp's.
1846  */
1847 static void
1848 vdev_set_deflate_ratio(vdev_t *vd)
1849 {
1850 	if (vd == vd->vdev_top && !vd->vdev_ishole && vd->vdev_ashift != 0) {
1851 		vd->vdev_deflate_ratio = (1 << 17) /
1852 		    (vdev_psize_to_asize(vd, 1 << 17) >> SPA_MINBLOCKSHIFT);
1853 	}
1854 }
1855 
1856 /*
1857  * Choose the best of two ashifts, preferring one between logical ashift
1858  * (absolute minimum) and administrator defined maximum, otherwise take
1859  * the biggest of the two.
1860  */
1861 uint64_t
1862 vdev_best_ashift(uint64_t logical, uint64_t a, uint64_t b)
1863 {
1864 	if (a > logical && a <= zfs_vdev_max_auto_ashift) {
1865 		if (b <= logical || b > zfs_vdev_max_auto_ashift)
1866 			return (a);
1867 		else
1868 			return (MAX(a, b));
1869 	} else if (b <= logical || b > zfs_vdev_max_auto_ashift)
1870 		return (MAX(a, b));
1871 	return (b);
1872 }
1873 
1874 /*
1875  * Maximize performance by inflating the configured ashift for top level
1876  * vdevs to be as close to the physical ashift as possible while maintaining
1877  * administrator defined limits and ensuring it doesn't go below the
1878  * logical ashift.
1879  */
1880 static void
1881 vdev_ashift_optimize(vdev_t *vd)
1882 {
1883 	ASSERT(vd == vd->vdev_top);
1884 
1885 	if (vd->vdev_ashift < vd->vdev_physical_ashift &&
1886 	    vd->vdev_physical_ashift <= zfs_vdev_max_auto_ashift) {
1887 		vd->vdev_ashift = MIN(
1888 		    MAX(zfs_vdev_max_auto_ashift, vd->vdev_ashift),
1889 		    MAX(zfs_vdev_min_auto_ashift,
1890 		    vd->vdev_physical_ashift));
1891 	} else {
1892 		/*
1893 		 * If the logical and physical ashifts are the same, then
1894 		 * we ensure that the top-level vdev's ashift is not smaller
1895 		 * than our minimum ashift value. For the unusual case
1896 		 * where logical ashift > physical ashift, we can't cap
1897 		 * the calculated ashift based on max ashift as that
1898 		 * would cause failures.
1899 		 * We still check if we need to increase it to match
1900 		 * the min ashift.
1901 		 */
1902 		vd->vdev_ashift = MAX(zfs_vdev_min_auto_ashift,
1903 		    vd->vdev_ashift);
1904 	}
1905 }
1906 
1907 /*
1908  * Prepare a virtual device for access.
1909  */
1910 int
1911 vdev_open(vdev_t *vd)
1912 {
1913 	spa_t *spa = vd->vdev_spa;
1914 	int error;
1915 	uint64_t osize = 0;
1916 	uint64_t max_osize = 0;
1917 	uint64_t asize, max_asize, psize;
1918 	uint64_t logical_ashift = 0;
1919 	uint64_t physical_ashift = 0;
1920 
1921 	ASSERT(vd->vdev_open_thread == curthread ||
1922 	    spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1923 	ASSERT(vd->vdev_state == VDEV_STATE_CLOSED ||
1924 	    vd->vdev_state == VDEV_STATE_CANT_OPEN ||
1925 	    vd->vdev_state == VDEV_STATE_OFFLINE);
1926 
1927 	vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
1928 	vd->vdev_cant_read = B_FALSE;
1929 	vd->vdev_cant_write = B_FALSE;
1930 	vd->vdev_min_asize = vdev_get_min_asize(vd);
1931 
1932 	/*
1933 	 * If this vdev is not removed, check its fault status.  If it's
1934 	 * faulted, bail out of the open.
1935 	 */
1936 	if (!vd->vdev_removed && vd->vdev_faulted) {
1937 		ASSERT(vd->vdev_children == 0);
1938 		ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1939 		    vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1940 		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1941 		    vd->vdev_label_aux);
1942 		return (SET_ERROR(ENXIO));
1943 	} else if (vd->vdev_offline) {
1944 		ASSERT(vd->vdev_children == 0);
1945 		vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE, VDEV_AUX_NONE);
1946 		return (SET_ERROR(ENXIO));
1947 	}
1948 
1949 	error = vd->vdev_ops->vdev_op_open(vd, &osize, &max_osize,
1950 	    &logical_ashift, &physical_ashift);
1951 
1952 	/* Keep the device in removed state if unplugged */
1953 	if (error == ENOENT && vd->vdev_removed) {
1954 		vdev_set_state(vd, B_TRUE, VDEV_STATE_REMOVED,
1955 		    VDEV_AUX_NONE);
1956 		return (error);
1957 	}
1958 
1959 	/*
1960 	 * Physical volume size should never be larger than its max size, unless
1961 	 * the disk has shrunk while we were reading it or the device is buggy
1962 	 * or damaged: either way it's not safe for use, bail out of the open.
1963 	 */
1964 	if (osize > max_osize) {
1965 		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1966 		    VDEV_AUX_OPEN_FAILED);
1967 		return (SET_ERROR(ENXIO));
1968 	}
1969 
1970 	/*
1971 	 * Reset the vdev_reopening flag so that we actually close
1972 	 * the vdev on error.
1973 	 */
1974 	vd->vdev_reopening = B_FALSE;
1975 	if (zio_injection_enabled && error == 0)
1976 		error = zio_handle_device_injection(vd, NULL, SET_ERROR(ENXIO));
1977 
1978 	if (error) {
1979 		if (vd->vdev_removed &&
1980 		    vd->vdev_stat.vs_aux != VDEV_AUX_OPEN_FAILED)
1981 			vd->vdev_removed = B_FALSE;
1982 
1983 		if (vd->vdev_stat.vs_aux == VDEV_AUX_CHILDREN_OFFLINE) {
1984 			vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE,
1985 			    vd->vdev_stat.vs_aux);
1986 		} else {
1987 			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1988 			    vd->vdev_stat.vs_aux);
1989 		}
1990 		return (error);
1991 	}
1992 
1993 	vd->vdev_removed = B_FALSE;
1994 
1995 	/*
1996 	 * Recheck the faulted flag now that we have confirmed that
1997 	 * the vdev is accessible.  If we're faulted, bail.
1998 	 */
1999 	if (vd->vdev_faulted) {
2000 		ASSERT(vd->vdev_children == 0);
2001 		ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
2002 		    vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
2003 		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
2004 		    vd->vdev_label_aux);
2005 		return (SET_ERROR(ENXIO));
2006 	}
2007 
2008 	if (vd->vdev_degraded) {
2009 		ASSERT(vd->vdev_children == 0);
2010 		vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
2011 		    VDEV_AUX_ERR_EXCEEDED);
2012 	} else {
2013 		vdev_set_state(vd, B_TRUE, VDEV_STATE_HEALTHY, 0);
2014 	}
2015 
2016 	/*
2017 	 * For hole or missing vdevs we just return success.
2018 	 */
2019 	if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops)
2020 		return (0);
2021 
2022 	for (int c = 0; c < vd->vdev_children; c++) {
2023 		if (vd->vdev_child[c]->vdev_state != VDEV_STATE_HEALTHY) {
2024 			vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
2025 			    VDEV_AUX_NONE);
2026 			break;
2027 		}
2028 	}
2029 
2030 	osize = P2ALIGN(osize, (uint64_t)sizeof (vdev_label_t));
2031 	max_osize = P2ALIGN(max_osize, (uint64_t)sizeof (vdev_label_t));
2032 
2033 	if (vd->vdev_children == 0) {
2034 		if (osize < SPA_MINDEVSIZE) {
2035 			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2036 			    VDEV_AUX_TOO_SMALL);
2037 			return (SET_ERROR(EOVERFLOW));
2038 		}
2039 		psize = osize;
2040 		asize = osize - (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE);
2041 		max_asize = max_osize - (VDEV_LABEL_START_SIZE +
2042 		    VDEV_LABEL_END_SIZE);
2043 	} else {
2044 		if (vd->vdev_parent != NULL && osize < SPA_MINDEVSIZE -
2045 		    (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE)) {
2046 			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2047 			    VDEV_AUX_TOO_SMALL);
2048 			return (SET_ERROR(EOVERFLOW));
2049 		}
2050 		psize = 0;
2051 		asize = osize;
2052 		max_asize = max_osize;
2053 	}
2054 
2055 	/*
2056 	 * If the vdev was expanded, record this so that we can re-create the
2057 	 * uberblock rings in labels {2,3}, during the next sync.
2058 	 */
2059 	if ((psize > vd->vdev_psize) && (vd->vdev_psize != 0))
2060 		vd->vdev_copy_uberblocks = B_TRUE;
2061 
2062 	vd->vdev_psize = psize;
2063 
2064 	/*
2065 	 * Make sure the allocatable size hasn't shrunk too much.
2066 	 */
2067 	if (asize < vd->vdev_min_asize) {
2068 		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2069 		    VDEV_AUX_BAD_LABEL);
2070 		return (SET_ERROR(EINVAL));
2071 	}
2072 
2073 	/*
2074 	 * We can always set the logical/physical ashift members since
2075 	 * their values are only used to calculate the vdev_ashift when
2076 	 * the device is first added to the config. These values should
2077 	 * not be used for anything else since they may change whenever
2078 	 * the device is reopened and we don't store them in the label.
2079 	 */
2080 	vd->vdev_physical_ashift =
2081 	    MAX(physical_ashift, vd->vdev_physical_ashift);
2082 	vd->vdev_logical_ashift = MAX(logical_ashift,
2083 	    vd->vdev_logical_ashift);
2084 
2085 	if (vd->vdev_asize == 0) {
2086 		/*
2087 		 * This is the first-ever open, so use the computed values.
2088 		 * For compatibility, a different ashift can be requested.
2089 		 */
2090 		vd->vdev_asize = asize;
2091 		vd->vdev_max_asize = max_asize;
2092 
2093 		/*
2094 		 * If the vdev_ashift was not overridden at creation time,
2095 		 * then set it the logical ashift and optimize the ashift.
2096 		 */
2097 		if (vd->vdev_ashift == 0) {
2098 			vd->vdev_ashift = vd->vdev_logical_ashift;
2099 
2100 			if (vd->vdev_logical_ashift > ASHIFT_MAX) {
2101 				vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2102 				    VDEV_AUX_ASHIFT_TOO_BIG);
2103 				return (SET_ERROR(EDOM));
2104 			}
2105 
2106 			if (vd->vdev_top == vd) {
2107 				vdev_ashift_optimize(vd);
2108 			}
2109 		}
2110 		if (vd->vdev_ashift != 0 && (vd->vdev_ashift < ASHIFT_MIN ||
2111 		    vd->vdev_ashift > ASHIFT_MAX)) {
2112 			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2113 			    VDEV_AUX_BAD_ASHIFT);
2114 			return (SET_ERROR(EDOM));
2115 		}
2116 	} else {
2117 		/*
2118 		 * Make sure the alignment required hasn't increased.
2119 		 */
2120 		if (vd->vdev_ashift > vd->vdev_top->vdev_ashift &&
2121 		    vd->vdev_ops->vdev_op_leaf) {
2122 			(void) zfs_ereport_post(
2123 			    FM_EREPORT_ZFS_DEVICE_BAD_ASHIFT,
2124 			    spa, vd, NULL, NULL, 0);
2125 			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2126 			    VDEV_AUX_BAD_LABEL);
2127 			return (SET_ERROR(EDOM));
2128 		}
2129 		vd->vdev_max_asize = max_asize;
2130 	}
2131 
2132 	/*
2133 	 * If all children are healthy we update asize if either:
2134 	 * The asize has increased, due to a device expansion caused by dynamic
2135 	 * LUN growth or vdev replacement, and automatic expansion is enabled;
2136 	 * making the additional space available.
2137 	 *
2138 	 * The asize has decreased, due to a device shrink usually caused by a
2139 	 * vdev replace with a smaller device. This ensures that calculations
2140 	 * based of max_asize and asize e.g. esize are always valid. It's safe
2141 	 * to do this as we've already validated that asize is greater than
2142 	 * vdev_min_asize.
2143 	 */
2144 	if (vd->vdev_state == VDEV_STATE_HEALTHY &&
2145 	    ((asize > vd->vdev_asize &&
2146 	    (vd->vdev_expanding || spa->spa_autoexpand)) ||
2147 	    (asize < vd->vdev_asize)))
2148 		vd->vdev_asize = asize;
2149 
2150 	vdev_set_min_asize(vd);
2151 
2152 	/*
2153 	 * Ensure we can issue some IO before declaring the
2154 	 * vdev open for business.
2155 	 */
2156 	if (vd->vdev_ops->vdev_op_leaf &&
2157 	    (error = zio_wait(vdev_probe(vd, NULL))) != 0) {
2158 		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
2159 		    VDEV_AUX_ERR_EXCEEDED);
2160 		return (error);
2161 	}
2162 
2163 	/*
2164 	 * Track the minimum allocation size.
2165 	 */
2166 	if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
2167 	    vd->vdev_islog == 0 && vd->vdev_aux == NULL) {
2168 		uint64_t min_alloc = vdev_get_min_alloc(vd);
2169 		if (min_alloc < spa->spa_min_alloc)
2170 			spa->spa_min_alloc = min_alloc;
2171 	}
2172 
2173 	/*
2174 	 * If this is a leaf vdev, assess whether a resilver is needed.
2175 	 * But don't do this if we are doing a reopen for a scrub, since
2176 	 * this would just restart the scrub we are already doing.
2177 	 */
2178 	if (vd->vdev_ops->vdev_op_leaf && !spa->spa_scrub_reopen)
2179 		dsl_scan_assess_vdev(spa->spa_dsl_pool, vd);
2180 
2181 	return (0);
2182 }
2183 
2184 static void
2185 vdev_validate_child(void *arg)
2186 {
2187 	vdev_t *vd = arg;
2188 
2189 	vd->vdev_validate_thread = curthread;
2190 	vd->vdev_validate_error = vdev_validate(vd);
2191 	vd->vdev_validate_thread = NULL;
2192 }
2193 
2194 /*
2195  * Called once the vdevs are all opened, this routine validates the label
2196  * contents. This needs to be done before vdev_load() so that we don't
2197  * inadvertently do repair I/Os to the wrong device.
2198  *
2199  * This function will only return failure if one of the vdevs indicates that it
2200  * has since been destroyed or exported.  This is only possible if
2201  * /etc/zfs/zpool.cache was readonly at the time.  Otherwise, the vdev state
2202  * will be updated but the function will return 0.
2203  */
2204 int
2205 vdev_validate(vdev_t *vd)
2206 {
2207 	spa_t *spa = vd->vdev_spa;
2208 	taskq_t *tq = NULL;
2209 	nvlist_t *label;
2210 	uint64_t guid = 0, aux_guid = 0, top_guid;
2211 	uint64_t state;
2212 	nvlist_t *nvl;
2213 	uint64_t txg;
2214 	int children = vd->vdev_children;
2215 
2216 	if (vdev_validate_skip)
2217 		return (0);
2218 
2219 	if (children > 0) {
2220 		tq = taskq_create("vdev_validate", children, minclsyspri,
2221 		    children, children, TASKQ_PREPOPULATE);
2222 	}
2223 
2224 	for (uint64_t c = 0; c < children; c++) {
2225 		vdev_t *cvd = vd->vdev_child[c];
2226 
2227 		if (tq == NULL || vdev_uses_zvols(cvd)) {
2228 			vdev_validate_child(cvd);
2229 		} else {
2230 			VERIFY(taskq_dispatch(tq, vdev_validate_child, cvd,
2231 			    TQ_SLEEP) != TASKQID_INVALID);
2232 		}
2233 	}
2234 	if (tq != NULL) {
2235 		taskq_wait(tq);
2236 		taskq_destroy(tq);
2237 	}
2238 	for (int c = 0; c < children; c++) {
2239 		int error = vd->vdev_child[c]->vdev_validate_error;
2240 
2241 		if (error != 0)
2242 			return (SET_ERROR(EBADF));
2243 	}
2244 
2245 
2246 	/*
2247 	 * If the device has already failed, or was marked offline, don't do
2248 	 * any further validation.  Otherwise, label I/O will fail and we will
2249 	 * overwrite the previous state.
2250 	 */
2251 	if (!vd->vdev_ops->vdev_op_leaf || !vdev_readable(vd))
2252 		return (0);
2253 
2254 	/*
2255 	 * If we are performing an extreme rewind, we allow for a label that
2256 	 * was modified at a point after the current txg.
2257 	 * If config lock is not held do not check for the txg. spa_sync could
2258 	 * be updating the vdev's label before updating spa_last_synced_txg.
2259 	 */
2260 	if (spa->spa_extreme_rewind || spa_last_synced_txg(spa) == 0 ||
2261 	    spa_config_held(spa, SCL_CONFIG, RW_WRITER) != SCL_CONFIG)
2262 		txg = UINT64_MAX;
2263 	else
2264 		txg = spa_last_synced_txg(spa);
2265 
2266 	if ((label = vdev_label_read_config(vd, txg)) == NULL) {
2267 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2268 		    VDEV_AUX_BAD_LABEL);
2269 		vdev_dbgmsg(vd, "vdev_validate: failed reading config for "
2270 		    "txg %llu", (u_longlong_t)txg);
2271 		return (0);
2272 	}
2273 
2274 	/*
2275 	 * Determine if this vdev has been split off into another
2276 	 * pool.  If so, then refuse to open it.
2277 	 */
2278 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_SPLIT_GUID,
2279 	    &aux_guid) == 0 && aux_guid == spa_guid(spa)) {
2280 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2281 		    VDEV_AUX_SPLIT_POOL);
2282 		nvlist_free(label);
2283 		vdev_dbgmsg(vd, "vdev_validate: vdev split into other pool");
2284 		return (0);
2285 	}
2286 
2287 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID, &guid) != 0) {
2288 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2289 		    VDEV_AUX_CORRUPT_DATA);
2290 		nvlist_free(label);
2291 		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
2292 		    ZPOOL_CONFIG_POOL_GUID);
2293 		return (0);
2294 	}
2295 
2296 	/*
2297 	 * If config is not trusted then ignore the spa guid check. This is
2298 	 * necessary because if the machine crashed during a re-guid the new
2299 	 * guid might have been written to all of the vdev labels, but not the
2300 	 * cached config. The check will be performed again once we have the
2301 	 * trusted config from the MOS.
2302 	 */
2303 	if (spa->spa_trust_config && guid != spa_guid(spa)) {
2304 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2305 		    VDEV_AUX_CORRUPT_DATA);
2306 		nvlist_free(label);
2307 		vdev_dbgmsg(vd, "vdev_validate: vdev label pool_guid doesn't "
2308 		    "match config (%llu != %llu)", (u_longlong_t)guid,
2309 		    (u_longlong_t)spa_guid(spa));
2310 		return (0);
2311 	}
2312 
2313 	if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvl)
2314 	    != 0 || nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_ORIG_GUID,
2315 	    &aux_guid) != 0)
2316 		aux_guid = 0;
2317 
2318 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0) {
2319 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2320 		    VDEV_AUX_CORRUPT_DATA);
2321 		nvlist_free(label);
2322 		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
2323 		    ZPOOL_CONFIG_GUID);
2324 		return (0);
2325 	}
2326 
2327 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID, &top_guid)
2328 	    != 0) {
2329 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2330 		    VDEV_AUX_CORRUPT_DATA);
2331 		nvlist_free(label);
2332 		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
2333 		    ZPOOL_CONFIG_TOP_GUID);
2334 		return (0);
2335 	}
2336 
2337 	/*
2338 	 * If this vdev just became a top-level vdev because its sibling was
2339 	 * detached, it will have adopted the parent's vdev guid -- but the
2340 	 * label may or may not be on disk yet. Fortunately, either version
2341 	 * of the label will have the same top guid, so if we're a top-level
2342 	 * vdev, we can safely compare to that instead.
2343 	 * However, if the config comes from a cachefile that failed to update
2344 	 * after the detach, a top-level vdev will appear as a non top-level
2345 	 * vdev in the config. Also relax the constraints if we perform an
2346 	 * extreme rewind.
2347 	 *
2348 	 * If we split this vdev off instead, then we also check the
2349 	 * original pool's guid. We don't want to consider the vdev
2350 	 * corrupt if it is partway through a split operation.
2351 	 */
2352 	if (vd->vdev_guid != guid && vd->vdev_guid != aux_guid) {
2353 		boolean_t mismatch = B_FALSE;
2354 		if (spa->spa_trust_config && !spa->spa_extreme_rewind) {
2355 			if (vd != vd->vdev_top || vd->vdev_guid != top_guid)
2356 				mismatch = B_TRUE;
2357 		} else {
2358 			if (vd->vdev_guid != top_guid &&
2359 			    vd->vdev_top->vdev_guid != guid)
2360 				mismatch = B_TRUE;
2361 		}
2362 
2363 		if (mismatch) {
2364 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2365 			    VDEV_AUX_CORRUPT_DATA);
2366 			nvlist_free(label);
2367 			vdev_dbgmsg(vd, "vdev_validate: config guid "
2368 			    "doesn't match label guid");
2369 			vdev_dbgmsg(vd, "CONFIG: guid %llu, top_guid %llu",
2370 			    (u_longlong_t)vd->vdev_guid,
2371 			    (u_longlong_t)vd->vdev_top->vdev_guid);
2372 			vdev_dbgmsg(vd, "LABEL: guid %llu, top_guid %llu, "
2373 			    "aux_guid %llu", (u_longlong_t)guid,
2374 			    (u_longlong_t)top_guid, (u_longlong_t)aux_guid);
2375 			return (0);
2376 		}
2377 	}
2378 
2379 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
2380 	    &state) != 0) {
2381 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2382 		    VDEV_AUX_CORRUPT_DATA);
2383 		nvlist_free(label);
2384 		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
2385 		    ZPOOL_CONFIG_POOL_STATE);
2386 		return (0);
2387 	}
2388 
2389 	nvlist_free(label);
2390 
2391 	/*
2392 	 * If this is a verbatim import, no need to check the
2393 	 * state of the pool.
2394 	 */
2395 	if (!(spa->spa_import_flags & ZFS_IMPORT_VERBATIM) &&
2396 	    spa_load_state(spa) == SPA_LOAD_OPEN &&
2397 	    state != POOL_STATE_ACTIVE) {
2398 		vdev_dbgmsg(vd, "vdev_validate: invalid pool state (%llu) "
2399 		    "for spa %s", (u_longlong_t)state, spa->spa_name);
2400 		return (SET_ERROR(EBADF));
2401 	}
2402 
2403 	/*
2404 	 * If we were able to open and validate a vdev that was
2405 	 * previously marked permanently unavailable, clear that state
2406 	 * now.
2407 	 */
2408 	if (vd->vdev_not_present)
2409 		vd->vdev_not_present = 0;
2410 
2411 	return (0);
2412 }
2413 
2414 static void
2415 vdev_copy_path_impl(vdev_t *svd, vdev_t *dvd)
2416 {
2417 	char *old, *new;
2418 	if (svd->vdev_path != NULL && dvd->vdev_path != NULL) {
2419 		if (strcmp(svd->vdev_path, dvd->vdev_path) != 0) {
2420 			zfs_dbgmsg("vdev_copy_path: vdev %llu: path changed "
2421 			    "from '%s' to '%s'", (u_longlong_t)dvd->vdev_guid,
2422 			    dvd->vdev_path, svd->vdev_path);
2423 			spa_strfree(dvd->vdev_path);
2424 			dvd->vdev_path = spa_strdup(svd->vdev_path);
2425 		}
2426 	} else if (svd->vdev_path != NULL) {
2427 		dvd->vdev_path = spa_strdup(svd->vdev_path);
2428 		zfs_dbgmsg("vdev_copy_path: vdev %llu: path set to '%s'",
2429 		    (u_longlong_t)dvd->vdev_guid, dvd->vdev_path);
2430 	}
2431 
2432 	/*
2433 	 * Our enclosure sysfs path may have changed between imports
2434 	 */
2435 	old = dvd->vdev_enc_sysfs_path;
2436 	new = svd->vdev_enc_sysfs_path;
2437 	if ((old != NULL && new == NULL) ||
2438 	    (old == NULL && new != NULL) ||
2439 	    ((old != NULL && new != NULL) && strcmp(new, old) != 0)) {
2440 		zfs_dbgmsg("vdev_copy_path: vdev %llu: vdev_enc_sysfs_path "
2441 		    "changed from '%s' to '%s'", (u_longlong_t)dvd->vdev_guid,
2442 		    old, new);
2443 
2444 		if (dvd->vdev_enc_sysfs_path)
2445 			spa_strfree(dvd->vdev_enc_sysfs_path);
2446 
2447 		if (svd->vdev_enc_sysfs_path) {
2448 			dvd->vdev_enc_sysfs_path = spa_strdup(
2449 			    svd->vdev_enc_sysfs_path);
2450 		} else {
2451 			dvd->vdev_enc_sysfs_path = NULL;
2452 		}
2453 	}
2454 }
2455 
2456 /*
2457  * Recursively copy vdev paths from one vdev to another. Source and destination
2458  * vdev trees must have same geometry otherwise return error. Intended to copy
2459  * paths from userland config into MOS config.
2460  */
2461 int
2462 vdev_copy_path_strict(vdev_t *svd, vdev_t *dvd)
2463 {
2464 	if ((svd->vdev_ops == &vdev_missing_ops) ||
2465 	    (svd->vdev_ishole && dvd->vdev_ishole) ||
2466 	    (dvd->vdev_ops == &vdev_indirect_ops))
2467 		return (0);
2468 
2469 	if (svd->vdev_ops != dvd->vdev_ops) {
2470 		vdev_dbgmsg(svd, "vdev_copy_path: vdev type mismatch: %s != %s",
2471 		    svd->vdev_ops->vdev_op_type, dvd->vdev_ops->vdev_op_type);
2472 		return (SET_ERROR(EINVAL));
2473 	}
2474 
2475 	if (svd->vdev_guid != dvd->vdev_guid) {
2476 		vdev_dbgmsg(svd, "vdev_copy_path: guids mismatch (%llu != "
2477 		    "%llu)", (u_longlong_t)svd->vdev_guid,
2478 		    (u_longlong_t)dvd->vdev_guid);
2479 		return (SET_ERROR(EINVAL));
2480 	}
2481 
2482 	if (svd->vdev_children != dvd->vdev_children) {
2483 		vdev_dbgmsg(svd, "vdev_copy_path: children count mismatch: "
2484 		    "%llu != %llu", (u_longlong_t)svd->vdev_children,
2485 		    (u_longlong_t)dvd->vdev_children);
2486 		return (SET_ERROR(EINVAL));
2487 	}
2488 
2489 	for (uint64_t i = 0; i < svd->vdev_children; i++) {
2490 		int error = vdev_copy_path_strict(svd->vdev_child[i],
2491 		    dvd->vdev_child[i]);
2492 		if (error != 0)
2493 			return (error);
2494 	}
2495 
2496 	if (svd->vdev_ops->vdev_op_leaf)
2497 		vdev_copy_path_impl(svd, dvd);
2498 
2499 	return (0);
2500 }
2501 
2502 static void
2503 vdev_copy_path_search(vdev_t *stvd, vdev_t *dvd)
2504 {
2505 	ASSERT(stvd->vdev_top == stvd);
2506 	ASSERT3U(stvd->vdev_id, ==, dvd->vdev_top->vdev_id);
2507 
2508 	for (uint64_t i = 0; i < dvd->vdev_children; i++) {
2509 		vdev_copy_path_search(stvd, dvd->vdev_child[i]);
2510 	}
2511 
2512 	if (!dvd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(dvd))
2513 		return;
2514 
2515 	/*
2516 	 * The idea here is that while a vdev can shift positions within
2517 	 * a top vdev (when replacing, attaching mirror, etc.) it cannot
2518 	 * step outside of it.
2519 	 */
2520 	vdev_t *vd = vdev_lookup_by_guid(stvd, dvd->vdev_guid);
2521 
2522 	if (vd == NULL || vd->vdev_ops != dvd->vdev_ops)
2523 		return;
2524 
2525 	ASSERT(vd->vdev_ops->vdev_op_leaf);
2526 
2527 	vdev_copy_path_impl(vd, dvd);
2528 }
2529 
2530 /*
2531  * Recursively copy vdev paths from one root vdev to another. Source and
2532  * destination vdev trees may differ in geometry. For each destination leaf
2533  * vdev, search a vdev with the same guid and top vdev id in the source.
2534  * Intended to copy paths from userland config into MOS config.
2535  */
2536 void
2537 vdev_copy_path_relaxed(vdev_t *srvd, vdev_t *drvd)
2538 {
2539 	uint64_t children = MIN(srvd->vdev_children, drvd->vdev_children);
2540 	ASSERT(srvd->vdev_ops == &vdev_root_ops);
2541 	ASSERT(drvd->vdev_ops == &vdev_root_ops);
2542 
2543 	for (uint64_t i = 0; i < children; i++) {
2544 		vdev_copy_path_search(srvd->vdev_child[i],
2545 		    drvd->vdev_child[i]);
2546 	}
2547 }
2548 
2549 /*
2550  * Close a virtual device.
2551  */
2552 void
2553 vdev_close(vdev_t *vd)
2554 {
2555 	vdev_t *pvd = vd->vdev_parent;
2556 	spa_t *spa __maybe_unused = vd->vdev_spa;
2557 
2558 	ASSERT(vd != NULL);
2559 	ASSERT(vd->vdev_open_thread == curthread ||
2560 	    spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2561 
2562 	/*
2563 	 * If our parent is reopening, then we are as well, unless we are
2564 	 * going offline.
2565 	 */
2566 	if (pvd != NULL && pvd->vdev_reopening)
2567 		vd->vdev_reopening = (pvd->vdev_reopening && !vd->vdev_offline);
2568 
2569 	vd->vdev_ops->vdev_op_close(vd);
2570 
2571 	vdev_cache_purge(vd);
2572 
2573 	/*
2574 	 * We record the previous state before we close it, so that if we are
2575 	 * doing a reopen(), we don't generate FMA ereports if we notice that
2576 	 * it's still faulted.
2577 	 */
2578 	vd->vdev_prevstate = vd->vdev_state;
2579 
2580 	if (vd->vdev_offline)
2581 		vd->vdev_state = VDEV_STATE_OFFLINE;
2582 	else
2583 		vd->vdev_state = VDEV_STATE_CLOSED;
2584 	vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
2585 }
2586 
2587 void
2588 vdev_hold(vdev_t *vd)
2589 {
2590 	spa_t *spa = vd->vdev_spa;
2591 
2592 	ASSERT(spa_is_root(spa));
2593 	if (spa->spa_state == POOL_STATE_UNINITIALIZED)
2594 		return;
2595 
2596 	for (int c = 0; c < vd->vdev_children; c++)
2597 		vdev_hold(vd->vdev_child[c]);
2598 
2599 	if (vd->vdev_ops->vdev_op_leaf && vd->vdev_ops->vdev_op_hold != NULL)
2600 		vd->vdev_ops->vdev_op_hold(vd);
2601 }
2602 
2603 void
2604 vdev_rele(vdev_t *vd)
2605 {
2606 	ASSERT(spa_is_root(vd->vdev_spa));
2607 	for (int c = 0; c < vd->vdev_children; c++)
2608 		vdev_rele(vd->vdev_child[c]);
2609 
2610 	if (vd->vdev_ops->vdev_op_leaf && vd->vdev_ops->vdev_op_rele != NULL)
2611 		vd->vdev_ops->vdev_op_rele(vd);
2612 }
2613 
2614 /*
2615  * Reopen all interior vdevs and any unopened leaves.  We don't actually
2616  * reopen leaf vdevs which had previously been opened as they might deadlock
2617  * on the spa_config_lock.  Instead we only obtain the leaf's physical size.
2618  * If the leaf has never been opened then open it, as usual.
2619  */
2620 void
2621 vdev_reopen(vdev_t *vd)
2622 {
2623 	spa_t *spa = vd->vdev_spa;
2624 
2625 	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2626 
2627 	/* set the reopening flag unless we're taking the vdev offline */
2628 	vd->vdev_reopening = !vd->vdev_offline;
2629 	vdev_close(vd);
2630 	(void) vdev_open(vd);
2631 
2632 	/*
2633 	 * Call vdev_validate() here to make sure we have the same device.
2634 	 * Otherwise, a device with an invalid label could be successfully
2635 	 * opened in response to vdev_reopen().
2636 	 */
2637 	if (vd->vdev_aux) {
2638 		(void) vdev_validate_aux(vd);
2639 		if (vdev_readable(vd) && vdev_writeable(vd) &&
2640 		    vd->vdev_aux == &spa->spa_l2cache) {
2641 			/*
2642 			 * In case the vdev is present we should evict all ARC
2643 			 * buffers and pointers to log blocks and reclaim their
2644 			 * space before restoring its contents to L2ARC.
2645 			 */
2646 			if (l2arc_vdev_present(vd)) {
2647 				l2arc_rebuild_vdev(vd, B_TRUE);
2648 			} else {
2649 				l2arc_add_vdev(spa, vd);
2650 			}
2651 			spa_async_request(spa, SPA_ASYNC_L2CACHE_REBUILD);
2652 			spa_async_request(spa, SPA_ASYNC_L2CACHE_TRIM);
2653 		}
2654 	} else {
2655 		(void) vdev_validate(vd);
2656 	}
2657 
2658 	/*
2659 	 * Reassess parent vdev's health.
2660 	 */
2661 	vdev_propagate_state(vd);
2662 }
2663 
2664 int
2665 vdev_create(vdev_t *vd, uint64_t txg, boolean_t isreplacing)
2666 {
2667 	int error;
2668 
2669 	/*
2670 	 * Normally, partial opens (e.g. of a mirror) are allowed.
2671 	 * For a create, however, we want to fail the request if
2672 	 * there are any components we can't open.
2673 	 */
2674 	error = vdev_open(vd);
2675 
2676 	if (error || vd->vdev_state != VDEV_STATE_HEALTHY) {
2677 		vdev_close(vd);
2678 		return (error ? error : SET_ERROR(ENXIO));
2679 	}
2680 
2681 	/*
2682 	 * Recursively load DTLs and initialize all labels.
2683 	 */
2684 	if ((error = vdev_dtl_load(vd)) != 0 ||
2685 	    (error = vdev_label_init(vd, txg, isreplacing ?
2686 	    VDEV_LABEL_REPLACE : VDEV_LABEL_CREATE)) != 0) {
2687 		vdev_close(vd);
2688 		return (error);
2689 	}
2690 
2691 	return (0);
2692 }
2693 
2694 void
2695 vdev_metaslab_set_size(vdev_t *vd)
2696 {
2697 	uint64_t asize = vd->vdev_asize;
2698 	uint64_t ms_count = asize >> zfs_vdev_default_ms_shift;
2699 	uint64_t ms_shift;
2700 
2701 	/*
2702 	 * There are two dimensions to the metaslab sizing calculation:
2703 	 * the size of the metaslab and the count of metaslabs per vdev.
2704 	 *
2705 	 * The default values used below are a good balance between memory
2706 	 * usage (larger metaslab size means more memory needed for loaded
2707 	 * metaslabs; more metaslabs means more memory needed for the
2708 	 * metaslab_t structs), metaslab load time (larger metaslabs take
2709 	 * longer to load), and metaslab sync time (more metaslabs means
2710 	 * more time spent syncing all of them).
2711 	 *
2712 	 * In general, we aim for zfs_vdev_default_ms_count (200) metaslabs.
2713 	 * The range of the dimensions are as follows:
2714 	 *
2715 	 *	2^29 <= ms_size  <= 2^34
2716 	 *	  16 <= ms_count <= 131,072
2717 	 *
2718 	 * On the lower end of vdev sizes, we aim for metaslabs sizes of
2719 	 * at least 512MB (2^29) to minimize fragmentation effects when
2720 	 * testing with smaller devices.  However, the count constraint
2721 	 * of at least 16 metaslabs will override this minimum size goal.
2722 	 *
2723 	 * On the upper end of vdev sizes, we aim for a maximum metaslab
2724 	 * size of 16GB.  However, we will cap the total count to 2^17
2725 	 * metaslabs to keep our memory footprint in check and let the
2726 	 * metaslab size grow from there if that limit is hit.
2727 	 *
2728 	 * The net effect of applying above constrains is summarized below.
2729 	 *
2730 	 *   vdev size       metaslab count
2731 	 *  --------------|-----------------
2732 	 *      < 8GB        ~16
2733 	 *  8GB   - 100GB   one per 512MB
2734 	 *  100GB - 3TB     ~200
2735 	 *  3TB   - 2PB     one per 16GB
2736 	 *      > 2PB       ~131,072
2737 	 *  --------------------------------
2738 	 *
2739 	 *  Finally, note that all of the above calculate the initial
2740 	 *  number of metaslabs. Expanding a top-level vdev will result
2741 	 *  in additional metaslabs being allocated making it possible
2742 	 *  to exceed the zfs_vdev_ms_count_limit.
2743 	 */
2744 
2745 	if (ms_count < zfs_vdev_min_ms_count)
2746 		ms_shift = highbit64(asize / zfs_vdev_min_ms_count);
2747 	else if (ms_count > zfs_vdev_default_ms_count)
2748 		ms_shift = highbit64(asize / zfs_vdev_default_ms_count);
2749 	else
2750 		ms_shift = zfs_vdev_default_ms_shift;
2751 
2752 	if (ms_shift < SPA_MAXBLOCKSHIFT) {
2753 		ms_shift = SPA_MAXBLOCKSHIFT;
2754 	} else if (ms_shift > zfs_vdev_max_ms_shift) {
2755 		ms_shift = zfs_vdev_max_ms_shift;
2756 		/* cap the total count to constrain memory footprint */
2757 		if ((asize >> ms_shift) > zfs_vdev_ms_count_limit)
2758 			ms_shift = highbit64(asize / zfs_vdev_ms_count_limit);
2759 	}
2760 
2761 	vd->vdev_ms_shift = ms_shift;
2762 	ASSERT3U(vd->vdev_ms_shift, >=, SPA_MAXBLOCKSHIFT);
2763 }
2764 
2765 void
2766 vdev_dirty(vdev_t *vd, int flags, void *arg, uint64_t txg)
2767 {
2768 	ASSERT(vd == vd->vdev_top);
2769 	/* indirect vdevs don't have metaslabs or dtls */
2770 	ASSERT(vdev_is_concrete(vd) || flags == 0);
2771 	ASSERT(ISP2(flags));
2772 	ASSERT(spa_writeable(vd->vdev_spa));
2773 
2774 	if (flags & VDD_METASLAB)
2775 		(void) txg_list_add(&vd->vdev_ms_list, arg, txg);
2776 
2777 	if (flags & VDD_DTL)
2778 		(void) txg_list_add(&vd->vdev_dtl_list, arg, txg);
2779 
2780 	(void) txg_list_add(&vd->vdev_spa->spa_vdev_txg_list, vd, txg);
2781 }
2782 
2783 void
2784 vdev_dirty_leaves(vdev_t *vd, int flags, uint64_t txg)
2785 {
2786 	for (int c = 0; c < vd->vdev_children; c++)
2787 		vdev_dirty_leaves(vd->vdev_child[c], flags, txg);
2788 
2789 	if (vd->vdev_ops->vdev_op_leaf)
2790 		vdev_dirty(vd->vdev_top, flags, vd, txg);
2791 }
2792 
2793 /*
2794  * DTLs.
2795  *
2796  * A vdev's DTL (dirty time log) is the set of transaction groups for which
2797  * the vdev has less than perfect replication.  There are four kinds of DTL:
2798  *
2799  * DTL_MISSING: txgs for which the vdev has no valid copies of the data
2800  *
2801  * DTL_PARTIAL: txgs for which data is available, but not fully replicated
2802  *
2803  * DTL_SCRUB: the txgs that could not be repaired by the last scrub; upon
2804  *	scrub completion, DTL_SCRUB replaces DTL_MISSING in the range of
2805  *	txgs that was scrubbed.
2806  *
2807  * DTL_OUTAGE: txgs which cannot currently be read, whether due to
2808  *	persistent errors or just some device being offline.
2809  *	Unlike the other three, the DTL_OUTAGE map is not generally
2810  *	maintained; it's only computed when needed, typically to
2811  *	determine whether a device can be detached.
2812  *
2813  * For leaf vdevs, DTL_MISSING and DTL_PARTIAL are identical: the device
2814  * either has the data or it doesn't.
2815  *
2816  * For interior vdevs such as mirror and RAID-Z the picture is more complex.
2817  * A vdev's DTL_PARTIAL is the union of its children's DTL_PARTIALs, because
2818  * if any child is less than fully replicated, then so is its parent.
2819  * A vdev's DTL_MISSING is a modified union of its children's DTL_MISSINGs,
2820  * comprising only those txgs which appear in 'maxfaults' or more children;
2821  * those are the txgs we don't have enough replication to read.  For example,
2822  * double-parity RAID-Z can tolerate up to two missing devices (maxfaults == 2);
2823  * thus, its DTL_MISSING consists of the set of txgs that appear in more than
2824  * two child DTL_MISSING maps.
2825  *
2826  * It should be clear from the above that to compute the DTLs and outage maps
2827  * for all vdevs, it suffices to know just the leaf vdevs' DTL_MISSING maps.
2828  * Therefore, that is all we keep on disk.  When loading the pool, or after
2829  * a configuration change, we generate all other DTLs from first principles.
2830  */
2831 void
2832 vdev_dtl_dirty(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
2833 {
2834 	range_tree_t *rt = vd->vdev_dtl[t];
2835 
2836 	ASSERT(t < DTL_TYPES);
2837 	ASSERT(vd != vd->vdev_spa->spa_root_vdev);
2838 	ASSERT(spa_writeable(vd->vdev_spa));
2839 
2840 	mutex_enter(&vd->vdev_dtl_lock);
2841 	if (!range_tree_contains(rt, txg, size))
2842 		range_tree_add(rt, txg, size);
2843 	mutex_exit(&vd->vdev_dtl_lock);
2844 }
2845 
2846 boolean_t
2847 vdev_dtl_contains(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
2848 {
2849 	range_tree_t *rt = vd->vdev_dtl[t];
2850 	boolean_t dirty = B_FALSE;
2851 
2852 	ASSERT(t < DTL_TYPES);
2853 	ASSERT(vd != vd->vdev_spa->spa_root_vdev);
2854 
2855 	/*
2856 	 * While we are loading the pool, the DTLs have not been loaded yet.
2857 	 * This isn't a problem but it can result in devices being tried
2858 	 * which are known to not have the data.  In which case, the import
2859 	 * is relying on the checksum to ensure that we get the right data.
2860 	 * Note that while importing we are only reading the MOS, which is
2861 	 * always checksummed.
2862 	 */
2863 	mutex_enter(&vd->vdev_dtl_lock);
2864 	if (!range_tree_is_empty(rt))
2865 		dirty = range_tree_contains(rt, txg, size);
2866 	mutex_exit(&vd->vdev_dtl_lock);
2867 
2868 	return (dirty);
2869 }
2870 
2871 boolean_t
2872 vdev_dtl_empty(vdev_t *vd, vdev_dtl_type_t t)
2873 {
2874 	range_tree_t *rt = vd->vdev_dtl[t];
2875 	boolean_t empty;
2876 
2877 	mutex_enter(&vd->vdev_dtl_lock);
2878 	empty = range_tree_is_empty(rt);
2879 	mutex_exit(&vd->vdev_dtl_lock);
2880 
2881 	return (empty);
2882 }
2883 
2884 /*
2885  * Check if the txg falls within the range which must be
2886  * resilvered.  DVAs outside this range can always be skipped.
2887  */
2888 boolean_t
2889 vdev_default_need_resilver(vdev_t *vd, const dva_t *dva, size_t psize,
2890     uint64_t phys_birth)
2891 {
2892 	(void) dva, (void) psize;
2893 
2894 	/* Set by sequential resilver. */
2895 	if (phys_birth == TXG_UNKNOWN)
2896 		return (B_TRUE);
2897 
2898 	return (vdev_dtl_contains(vd, DTL_PARTIAL, phys_birth, 1));
2899 }
2900 
2901 /*
2902  * Returns B_TRUE if the vdev determines the DVA needs to be resilvered.
2903  */
2904 boolean_t
2905 vdev_dtl_need_resilver(vdev_t *vd, const dva_t *dva, size_t psize,
2906     uint64_t phys_birth)
2907 {
2908 	ASSERT(vd != vd->vdev_spa->spa_root_vdev);
2909 
2910 	if (vd->vdev_ops->vdev_op_need_resilver == NULL ||
2911 	    vd->vdev_ops->vdev_op_leaf)
2912 		return (B_TRUE);
2913 
2914 	return (vd->vdev_ops->vdev_op_need_resilver(vd, dva, psize,
2915 	    phys_birth));
2916 }
2917 
2918 /*
2919  * Returns the lowest txg in the DTL range.
2920  */
2921 static uint64_t
2922 vdev_dtl_min(vdev_t *vd)
2923 {
2924 	ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
2925 	ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
2926 	ASSERT0(vd->vdev_children);
2927 
2928 	return (range_tree_min(vd->vdev_dtl[DTL_MISSING]) - 1);
2929 }
2930 
2931 /*
2932  * Returns the highest txg in the DTL.
2933  */
2934 static uint64_t
2935 vdev_dtl_max(vdev_t *vd)
2936 {
2937 	ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
2938 	ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
2939 	ASSERT0(vd->vdev_children);
2940 
2941 	return (range_tree_max(vd->vdev_dtl[DTL_MISSING]));
2942 }
2943 
2944 /*
2945  * Determine if a resilvering vdev should remove any DTL entries from
2946  * its range. If the vdev was resilvering for the entire duration of the
2947  * scan then it should excise that range from its DTLs. Otherwise, this
2948  * vdev is considered partially resilvered and should leave its DTL
2949  * entries intact. The comment in vdev_dtl_reassess() describes how we
2950  * excise the DTLs.
2951  */
2952 static boolean_t
2953 vdev_dtl_should_excise(vdev_t *vd, boolean_t rebuild_done)
2954 {
2955 	ASSERT0(vd->vdev_children);
2956 
2957 	if (vd->vdev_state < VDEV_STATE_DEGRADED)
2958 		return (B_FALSE);
2959 
2960 	if (vd->vdev_resilver_deferred)
2961 		return (B_FALSE);
2962 
2963 	if (range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]))
2964 		return (B_TRUE);
2965 
2966 	if (rebuild_done) {
2967 		vdev_rebuild_t *vr = &vd->vdev_top->vdev_rebuild_config;
2968 		vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
2969 
2970 		/* Rebuild not initiated by attach */
2971 		if (vd->vdev_rebuild_txg == 0)
2972 			return (B_TRUE);
2973 
2974 		/*
2975 		 * When a rebuild completes without error then all missing data
2976 		 * up to the rebuild max txg has been reconstructed and the DTL
2977 		 * is eligible for excision.
2978 		 */
2979 		if (vrp->vrp_rebuild_state == VDEV_REBUILD_COMPLETE &&
2980 		    vdev_dtl_max(vd) <= vrp->vrp_max_txg) {
2981 			ASSERT3U(vrp->vrp_min_txg, <=, vdev_dtl_min(vd));
2982 			ASSERT3U(vrp->vrp_min_txg, <, vd->vdev_rebuild_txg);
2983 			ASSERT3U(vd->vdev_rebuild_txg, <=, vrp->vrp_max_txg);
2984 			return (B_TRUE);
2985 		}
2986 	} else {
2987 		dsl_scan_t *scn = vd->vdev_spa->spa_dsl_pool->dp_scan;
2988 		dsl_scan_phys_t *scnp __maybe_unused = &scn->scn_phys;
2989 
2990 		/* Resilver not initiated by attach */
2991 		if (vd->vdev_resilver_txg == 0)
2992 			return (B_TRUE);
2993 
2994 		/*
2995 		 * When a resilver is initiated the scan will assign the
2996 		 * scn_max_txg value to the highest txg value that exists
2997 		 * in all DTLs. If this device's max DTL is not part of this
2998 		 * scan (i.e. it is not in the range (scn_min_txg, scn_max_txg]
2999 		 * then it is not eligible for excision.
3000 		 */
3001 		if (vdev_dtl_max(vd) <= scn->scn_phys.scn_max_txg) {
3002 			ASSERT3U(scnp->scn_min_txg, <=, vdev_dtl_min(vd));
3003 			ASSERT3U(scnp->scn_min_txg, <, vd->vdev_resilver_txg);
3004 			ASSERT3U(vd->vdev_resilver_txg, <=, scnp->scn_max_txg);
3005 			return (B_TRUE);
3006 		}
3007 	}
3008 
3009 	return (B_FALSE);
3010 }
3011 
3012 /*
3013  * Reassess DTLs after a config change or scrub completion. If txg == 0 no
3014  * write operations will be issued to the pool.
3015  */
3016 void
3017 vdev_dtl_reassess(vdev_t *vd, uint64_t txg, uint64_t scrub_txg,
3018     boolean_t scrub_done, boolean_t rebuild_done)
3019 {
3020 	spa_t *spa = vd->vdev_spa;
3021 	avl_tree_t reftree;
3022 	int minref;
3023 
3024 	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
3025 
3026 	for (int c = 0; c < vd->vdev_children; c++)
3027 		vdev_dtl_reassess(vd->vdev_child[c], txg,
3028 		    scrub_txg, scrub_done, rebuild_done);
3029 
3030 	if (vd == spa->spa_root_vdev || !vdev_is_concrete(vd) || vd->vdev_aux)
3031 		return;
3032 
3033 	if (vd->vdev_ops->vdev_op_leaf) {
3034 		dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
3035 		vdev_rebuild_t *vr = &vd->vdev_top->vdev_rebuild_config;
3036 		boolean_t check_excise = B_FALSE;
3037 		boolean_t wasempty = B_TRUE;
3038 
3039 		mutex_enter(&vd->vdev_dtl_lock);
3040 
3041 		/*
3042 		 * If requested, pretend the scan or rebuild completed cleanly.
3043 		 */
3044 		if (zfs_scan_ignore_errors) {
3045 			if (scn != NULL)
3046 				scn->scn_phys.scn_errors = 0;
3047 			if (vr != NULL)
3048 				vr->vr_rebuild_phys.vrp_errors = 0;
3049 		}
3050 
3051 		if (scrub_txg != 0 &&
3052 		    !range_tree_is_empty(vd->vdev_dtl[DTL_MISSING])) {
3053 			wasempty = B_FALSE;
3054 			zfs_dbgmsg("guid:%llu txg:%llu scrub:%llu started:%d "
3055 			    "dtl:%llu/%llu errors:%llu",
3056 			    (u_longlong_t)vd->vdev_guid, (u_longlong_t)txg,
3057 			    (u_longlong_t)scrub_txg, spa->spa_scrub_started,
3058 			    (u_longlong_t)vdev_dtl_min(vd),
3059 			    (u_longlong_t)vdev_dtl_max(vd),
3060 			    (u_longlong_t)(scn ? scn->scn_phys.scn_errors : 0));
3061 		}
3062 
3063 		/*
3064 		 * If we've completed a scrub/resilver or a rebuild cleanly
3065 		 * then determine if this vdev should remove any DTLs. We
3066 		 * only want to excise regions on vdevs that were available
3067 		 * during the entire duration of this scan.
3068 		 */
3069 		if (rebuild_done &&
3070 		    vr != NULL && vr->vr_rebuild_phys.vrp_errors == 0) {
3071 			check_excise = B_TRUE;
3072 		} else {
3073 			if (spa->spa_scrub_started ||
3074 			    (scn != NULL && scn->scn_phys.scn_errors == 0)) {
3075 				check_excise = B_TRUE;
3076 			}
3077 		}
3078 
3079 		if (scrub_txg && check_excise &&
3080 		    vdev_dtl_should_excise(vd, rebuild_done)) {
3081 			/*
3082 			 * We completed a scrub, resilver or rebuild up to
3083 			 * scrub_txg.  If we did it without rebooting, then
3084 			 * the scrub dtl will be valid, so excise the old
3085 			 * region and fold in the scrub dtl.  Otherwise,
3086 			 * leave the dtl as-is if there was an error.
3087 			 *
3088 			 * There's little trick here: to excise the beginning
3089 			 * of the DTL_MISSING map, we put it into a reference
3090 			 * tree and then add a segment with refcnt -1 that
3091 			 * covers the range [0, scrub_txg).  This means
3092 			 * that each txg in that range has refcnt -1 or 0.
3093 			 * We then add DTL_SCRUB with a refcnt of 2, so that
3094 			 * entries in the range [0, scrub_txg) will have a
3095 			 * positive refcnt -- either 1 or 2.  We then convert
3096 			 * the reference tree into the new DTL_MISSING map.
3097 			 */
3098 			space_reftree_create(&reftree);
3099 			space_reftree_add_map(&reftree,
3100 			    vd->vdev_dtl[DTL_MISSING], 1);
3101 			space_reftree_add_seg(&reftree, 0, scrub_txg, -1);
3102 			space_reftree_add_map(&reftree,
3103 			    vd->vdev_dtl[DTL_SCRUB], 2);
3104 			space_reftree_generate_map(&reftree,
3105 			    vd->vdev_dtl[DTL_MISSING], 1);
3106 			space_reftree_destroy(&reftree);
3107 
3108 			if (!range_tree_is_empty(vd->vdev_dtl[DTL_MISSING])) {
3109 				zfs_dbgmsg("update DTL_MISSING:%llu/%llu",
3110 				    (u_longlong_t)vdev_dtl_min(vd),
3111 				    (u_longlong_t)vdev_dtl_max(vd));
3112 			} else if (!wasempty) {
3113 				zfs_dbgmsg("DTL_MISSING is now empty");
3114 			}
3115 		}
3116 		range_tree_vacate(vd->vdev_dtl[DTL_PARTIAL], NULL, NULL);
3117 		range_tree_walk(vd->vdev_dtl[DTL_MISSING],
3118 		    range_tree_add, vd->vdev_dtl[DTL_PARTIAL]);
3119 		if (scrub_done)
3120 			range_tree_vacate(vd->vdev_dtl[DTL_SCRUB], NULL, NULL);
3121 		range_tree_vacate(vd->vdev_dtl[DTL_OUTAGE], NULL, NULL);
3122 		if (!vdev_readable(vd))
3123 			range_tree_add(vd->vdev_dtl[DTL_OUTAGE], 0, -1ULL);
3124 		else
3125 			range_tree_walk(vd->vdev_dtl[DTL_MISSING],
3126 			    range_tree_add, vd->vdev_dtl[DTL_OUTAGE]);
3127 
3128 		/*
3129 		 * If the vdev was resilvering or rebuilding and no longer
3130 		 * has any DTLs then reset the appropriate flag and dirty
3131 		 * the top level so that we persist the change.
3132 		 */
3133 		if (txg != 0 &&
3134 		    range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
3135 		    range_tree_is_empty(vd->vdev_dtl[DTL_OUTAGE])) {
3136 			if (vd->vdev_rebuild_txg != 0) {
3137 				vd->vdev_rebuild_txg = 0;
3138 				vdev_config_dirty(vd->vdev_top);
3139 			} else if (vd->vdev_resilver_txg != 0) {
3140 				vd->vdev_resilver_txg = 0;
3141 				vdev_config_dirty(vd->vdev_top);
3142 			}
3143 		}
3144 
3145 		mutex_exit(&vd->vdev_dtl_lock);
3146 
3147 		if (txg != 0)
3148 			vdev_dirty(vd->vdev_top, VDD_DTL, vd, txg);
3149 		return;
3150 	}
3151 
3152 	mutex_enter(&vd->vdev_dtl_lock);
3153 	for (int t = 0; t < DTL_TYPES; t++) {
3154 		/* account for child's outage in parent's missing map */
3155 		int s = (t == DTL_MISSING) ? DTL_OUTAGE: t;
3156 		if (t == DTL_SCRUB)
3157 			continue;			/* leaf vdevs only */
3158 		if (t == DTL_PARTIAL)
3159 			minref = 1;			/* i.e. non-zero */
3160 		else if (vdev_get_nparity(vd) != 0)
3161 			minref = vdev_get_nparity(vd) + 1; /* RAID-Z, dRAID */
3162 		else
3163 			minref = vd->vdev_children;	/* any kind of mirror */
3164 		space_reftree_create(&reftree);
3165 		for (int c = 0; c < vd->vdev_children; c++) {
3166 			vdev_t *cvd = vd->vdev_child[c];
3167 			mutex_enter(&cvd->vdev_dtl_lock);
3168 			space_reftree_add_map(&reftree, cvd->vdev_dtl[s], 1);
3169 			mutex_exit(&cvd->vdev_dtl_lock);
3170 		}
3171 		space_reftree_generate_map(&reftree, vd->vdev_dtl[t], minref);
3172 		space_reftree_destroy(&reftree);
3173 	}
3174 	mutex_exit(&vd->vdev_dtl_lock);
3175 }
3176 
3177 /*
3178  * Iterate over all the vdevs except spare, and post kobj events
3179  */
3180 void
3181 vdev_post_kobj_evt(vdev_t *vd)
3182 {
3183 	if (vd->vdev_ops->vdev_op_kobj_evt_post &&
3184 	    vd->vdev_kobj_flag == B_FALSE) {
3185 		vd->vdev_kobj_flag = B_TRUE;
3186 		vd->vdev_ops->vdev_op_kobj_evt_post(vd);
3187 	}
3188 
3189 	for (int c = 0; c < vd->vdev_children; c++)
3190 		vdev_post_kobj_evt(vd->vdev_child[c]);
3191 }
3192 
3193 /*
3194  * Iterate over all the vdevs except spare, and clear kobj events
3195  */
3196 void
3197 vdev_clear_kobj_evt(vdev_t *vd)
3198 {
3199 	vd->vdev_kobj_flag = B_FALSE;
3200 
3201 	for (int c = 0; c < vd->vdev_children; c++)
3202 		vdev_clear_kobj_evt(vd->vdev_child[c]);
3203 }
3204 
3205 int
3206 vdev_dtl_load(vdev_t *vd)
3207 {
3208 	spa_t *spa = vd->vdev_spa;
3209 	objset_t *mos = spa->spa_meta_objset;
3210 	range_tree_t *rt;
3211 	int error = 0;
3212 
3213 	if (vd->vdev_ops->vdev_op_leaf && vd->vdev_dtl_object != 0) {
3214 		ASSERT(vdev_is_concrete(vd));
3215 
3216 		/*
3217 		 * If the dtl cannot be sync'd there is no need to open it.
3218 		 */
3219 		if (spa->spa_mode == SPA_MODE_READ && !spa->spa_read_spacemaps)
3220 			return (0);
3221 
3222 		error = space_map_open(&vd->vdev_dtl_sm, mos,
3223 		    vd->vdev_dtl_object, 0, -1ULL, 0);
3224 		if (error)
3225 			return (error);
3226 		ASSERT(vd->vdev_dtl_sm != NULL);
3227 
3228 		rt = range_tree_create(NULL, RANGE_SEG64, NULL, 0, 0);
3229 		error = space_map_load(vd->vdev_dtl_sm, rt, SM_ALLOC);
3230 		if (error == 0) {
3231 			mutex_enter(&vd->vdev_dtl_lock);
3232 			range_tree_walk(rt, range_tree_add,
3233 			    vd->vdev_dtl[DTL_MISSING]);
3234 			mutex_exit(&vd->vdev_dtl_lock);
3235 		}
3236 
3237 		range_tree_vacate(rt, NULL, NULL);
3238 		range_tree_destroy(rt);
3239 
3240 		return (error);
3241 	}
3242 
3243 	for (int c = 0; c < vd->vdev_children; c++) {
3244 		error = vdev_dtl_load(vd->vdev_child[c]);
3245 		if (error != 0)
3246 			break;
3247 	}
3248 
3249 	return (error);
3250 }
3251 
3252 static void
3253 vdev_zap_allocation_data(vdev_t *vd, dmu_tx_t *tx)
3254 {
3255 	spa_t *spa = vd->vdev_spa;
3256 	objset_t *mos = spa->spa_meta_objset;
3257 	vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
3258 	const char *string;
3259 
3260 	ASSERT(alloc_bias != VDEV_BIAS_NONE);
3261 
3262 	string =
3263 	    (alloc_bias == VDEV_BIAS_LOG) ? VDEV_ALLOC_BIAS_LOG :
3264 	    (alloc_bias == VDEV_BIAS_SPECIAL) ? VDEV_ALLOC_BIAS_SPECIAL :
3265 	    (alloc_bias == VDEV_BIAS_DEDUP) ? VDEV_ALLOC_BIAS_DEDUP : NULL;
3266 
3267 	ASSERT(string != NULL);
3268 	VERIFY0(zap_add(mos, vd->vdev_top_zap, VDEV_TOP_ZAP_ALLOCATION_BIAS,
3269 	    1, strlen(string) + 1, string, tx));
3270 
3271 	if (alloc_bias == VDEV_BIAS_SPECIAL || alloc_bias == VDEV_BIAS_DEDUP) {
3272 		spa_activate_allocation_classes(spa, tx);
3273 	}
3274 }
3275 
3276 void
3277 vdev_destroy_unlink_zap(vdev_t *vd, uint64_t zapobj, dmu_tx_t *tx)
3278 {
3279 	spa_t *spa = vd->vdev_spa;
3280 
3281 	VERIFY0(zap_destroy(spa->spa_meta_objset, zapobj, tx));
3282 	VERIFY0(zap_remove_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
3283 	    zapobj, tx));
3284 }
3285 
3286 uint64_t
3287 vdev_create_link_zap(vdev_t *vd, dmu_tx_t *tx)
3288 {
3289 	spa_t *spa = vd->vdev_spa;
3290 	uint64_t zap = zap_create(spa->spa_meta_objset, DMU_OTN_ZAP_METADATA,
3291 	    DMU_OT_NONE, 0, tx);
3292 
3293 	ASSERT(zap != 0);
3294 	VERIFY0(zap_add_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
3295 	    zap, tx));
3296 
3297 	return (zap);
3298 }
3299 
3300 void
3301 vdev_construct_zaps(vdev_t *vd, dmu_tx_t *tx)
3302 {
3303 	if (vd->vdev_ops != &vdev_hole_ops &&
3304 	    vd->vdev_ops != &vdev_missing_ops &&
3305 	    vd->vdev_ops != &vdev_root_ops &&
3306 	    !vd->vdev_top->vdev_removing) {
3307 		if (vd->vdev_ops->vdev_op_leaf && vd->vdev_leaf_zap == 0) {
3308 			vd->vdev_leaf_zap = vdev_create_link_zap(vd, tx);
3309 		}
3310 		if (vd == vd->vdev_top && vd->vdev_top_zap == 0) {
3311 			vd->vdev_top_zap = vdev_create_link_zap(vd, tx);
3312 			if (vd->vdev_alloc_bias != VDEV_BIAS_NONE)
3313 				vdev_zap_allocation_data(vd, tx);
3314 		}
3315 	}
3316 
3317 	for (uint64_t i = 0; i < vd->vdev_children; i++) {
3318 		vdev_construct_zaps(vd->vdev_child[i], tx);
3319 	}
3320 }
3321 
3322 static void
3323 vdev_dtl_sync(vdev_t *vd, uint64_t txg)
3324 {
3325 	spa_t *spa = vd->vdev_spa;
3326 	range_tree_t *rt = vd->vdev_dtl[DTL_MISSING];
3327 	objset_t *mos = spa->spa_meta_objset;
3328 	range_tree_t *rtsync;
3329 	dmu_tx_t *tx;
3330 	uint64_t object = space_map_object(vd->vdev_dtl_sm);
3331 
3332 	ASSERT(vdev_is_concrete(vd));
3333 	ASSERT(vd->vdev_ops->vdev_op_leaf);
3334 
3335 	tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
3336 
3337 	if (vd->vdev_detached || vd->vdev_top->vdev_removing) {
3338 		mutex_enter(&vd->vdev_dtl_lock);
3339 		space_map_free(vd->vdev_dtl_sm, tx);
3340 		space_map_close(vd->vdev_dtl_sm);
3341 		vd->vdev_dtl_sm = NULL;
3342 		mutex_exit(&vd->vdev_dtl_lock);
3343 
3344 		/*
3345 		 * We only destroy the leaf ZAP for detached leaves or for
3346 		 * removed log devices. Removed data devices handle leaf ZAP
3347 		 * cleanup later, once cancellation is no longer possible.
3348 		 */
3349 		if (vd->vdev_leaf_zap != 0 && (vd->vdev_detached ||
3350 		    vd->vdev_top->vdev_islog)) {
3351 			vdev_destroy_unlink_zap(vd, vd->vdev_leaf_zap, tx);
3352 			vd->vdev_leaf_zap = 0;
3353 		}
3354 
3355 		dmu_tx_commit(tx);
3356 		return;
3357 	}
3358 
3359 	if (vd->vdev_dtl_sm == NULL) {
3360 		uint64_t new_object;
3361 
3362 		new_object = space_map_alloc(mos, zfs_vdev_dtl_sm_blksz, tx);
3363 		VERIFY3U(new_object, !=, 0);
3364 
3365 		VERIFY0(space_map_open(&vd->vdev_dtl_sm, mos, new_object,
3366 		    0, -1ULL, 0));
3367 		ASSERT(vd->vdev_dtl_sm != NULL);
3368 	}
3369 
3370 	rtsync = range_tree_create(NULL, RANGE_SEG64, NULL, 0, 0);
3371 
3372 	mutex_enter(&vd->vdev_dtl_lock);
3373 	range_tree_walk(rt, range_tree_add, rtsync);
3374 	mutex_exit(&vd->vdev_dtl_lock);
3375 
3376 	space_map_truncate(vd->vdev_dtl_sm, zfs_vdev_dtl_sm_blksz, tx);
3377 	space_map_write(vd->vdev_dtl_sm, rtsync, SM_ALLOC, SM_NO_VDEVID, tx);
3378 	range_tree_vacate(rtsync, NULL, NULL);
3379 
3380 	range_tree_destroy(rtsync);
3381 
3382 	/*
3383 	 * If the object for the space map has changed then dirty
3384 	 * the top level so that we update the config.
3385 	 */
3386 	if (object != space_map_object(vd->vdev_dtl_sm)) {
3387 		vdev_dbgmsg(vd, "txg %llu, spa %s, DTL old object %llu, "
3388 		    "new object %llu", (u_longlong_t)txg, spa_name(spa),
3389 		    (u_longlong_t)object,
3390 		    (u_longlong_t)space_map_object(vd->vdev_dtl_sm));
3391 		vdev_config_dirty(vd->vdev_top);
3392 	}
3393 
3394 	dmu_tx_commit(tx);
3395 }
3396 
3397 /*
3398  * Determine whether the specified vdev can be offlined/detached/removed
3399  * without losing data.
3400  */
3401 boolean_t
3402 vdev_dtl_required(vdev_t *vd)
3403 {
3404 	spa_t *spa = vd->vdev_spa;
3405 	vdev_t *tvd = vd->vdev_top;
3406 	uint8_t cant_read = vd->vdev_cant_read;
3407 	boolean_t required;
3408 
3409 	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
3410 
3411 	if (vd == spa->spa_root_vdev || vd == tvd)
3412 		return (B_TRUE);
3413 
3414 	/*
3415 	 * Temporarily mark the device as unreadable, and then determine
3416 	 * whether this results in any DTL outages in the top-level vdev.
3417 	 * If not, we can safely offline/detach/remove the device.
3418 	 */
3419 	vd->vdev_cant_read = B_TRUE;
3420 	vdev_dtl_reassess(tvd, 0, 0, B_FALSE, B_FALSE);
3421 	required = !vdev_dtl_empty(tvd, DTL_OUTAGE);
3422 	vd->vdev_cant_read = cant_read;
3423 	vdev_dtl_reassess(tvd, 0, 0, B_FALSE, B_FALSE);
3424 
3425 	if (!required && zio_injection_enabled) {
3426 		required = !!zio_handle_device_injection(vd, NULL,
3427 		    SET_ERROR(ECHILD));
3428 	}
3429 
3430 	return (required);
3431 }
3432 
3433 /*
3434  * Determine if resilver is needed, and if so the txg range.
3435  */
3436 boolean_t
3437 vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
3438 {
3439 	boolean_t needed = B_FALSE;
3440 	uint64_t thismin = UINT64_MAX;
3441 	uint64_t thismax = 0;
3442 
3443 	if (vd->vdev_children == 0) {
3444 		mutex_enter(&vd->vdev_dtl_lock);
3445 		if (!range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
3446 		    vdev_writeable(vd)) {
3447 
3448 			thismin = vdev_dtl_min(vd);
3449 			thismax = vdev_dtl_max(vd);
3450 			needed = B_TRUE;
3451 		}
3452 		mutex_exit(&vd->vdev_dtl_lock);
3453 	} else {
3454 		for (int c = 0; c < vd->vdev_children; c++) {
3455 			vdev_t *cvd = vd->vdev_child[c];
3456 			uint64_t cmin, cmax;
3457 
3458 			if (vdev_resilver_needed(cvd, &cmin, &cmax)) {
3459 				thismin = MIN(thismin, cmin);
3460 				thismax = MAX(thismax, cmax);
3461 				needed = B_TRUE;
3462 			}
3463 		}
3464 	}
3465 
3466 	if (needed && minp) {
3467 		*minp = thismin;
3468 		*maxp = thismax;
3469 	}
3470 	return (needed);
3471 }
3472 
3473 /*
3474  * Gets the checkpoint space map object from the vdev's ZAP.  On success sm_obj
3475  * will contain either the checkpoint spacemap object or zero if none exists.
3476  * All other errors are returned to the caller.
3477  */
3478 int
3479 vdev_checkpoint_sm_object(vdev_t *vd, uint64_t *sm_obj)
3480 {
3481 	ASSERT0(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER));
3482 
3483 	if (vd->vdev_top_zap == 0) {
3484 		*sm_obj = 0;
3485 		return (0);
3486 	}
3487 
3488 	int error = zap_lookup(spa_meta_objset(vd->vdev_spa), vd->vdev_top_zap,
3489 	    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1, sm_obj);
3490 	if (error == ENOENT) {
3491 		*sm_obj = 0;
3492 		error = 0;
3493 	}
3494 
3495 	return (error);
3496 }
3497 
3498 int
3499 vdev_load(vdev_t *vd)
3500 {
3501 	int children = vd->vdev_children;
3502 	int error = 0;
3503 	taskq_t *tq = NULL;
3504 
3505 	/*
3506 	 * It's only worthwhile to use the taskq for the root vdev, because the
3507 	 * slow part is metaslab_init, and that only happens for top-level
3508 	 * vdevs.
3509 	 */
3510 	if (vd->vdev_ops == &vdev_root_ops && vd->vdev_children > 0) {
3511 		tq = taskq_create("vdev_load", children, minclsyspri,
3512 		    children, children, TASKQ_PREPOPULATE);
3513 	}
3514 
3515 	/*
3516 	 * Recursively load all children.
3517 	 */
3518 	for (int c = 0; c < vd->vdev_children; c++) {
3519 		vdev_t *cvd = vd->vdev_child[c];
3520 
3521 		if (tq == NULL || vdev_uses_zvols(cvd)) {
3522 			cvd->vdev_load_error = vdev_load(cvd);
3523 		} else {
3524 			VERIFY(taskq_dispatch(tq, vdev_load_child,
3525 			    cvd, TQ_SLEEP) != TASKQID_INVALID);
3526 		}
3527 	}
3528 
3529 	if (tq != NULL) {
3530 		taskq_wait(tq);
3531 		taskq_destroy(tq);
3532 	}
3533 
3534 	for (int c = 0; c < vd->vdev_children; c++) {
3535 		int error = vd->vdev_child[c]->vdev_load_error;
3536 
3537 		if (error != 0)
3538 			return (error);
3539 	}
3540 
3541 	vdev_set_deflate_ratio(vd);
3542 
3543 	/*
3544 	 * On spa_load path, grab the allocation bias from our zap
3545 	 */
3546 	if (vd == vd->vdev_top && vd->vdev_top_zap != 0) {
3547 		spa_t *spa = vd->vdev_spa;
3548 		char bias_str[64];
3549 
3550 		error = zap_lookup(spa->spa_meta_objset, vd->vdev_top_zap,
3551 		    VDEV_TOP_ZAP_ALLOCATION_BIAS, 1, sizeof (bias_str),
3552 		    bias_str);
3553 		if (error == 0) {
3554 			ASSERT(vd->vdev_alloc_bias == VDEV_BIAS_NONE);
3555 			vd->vdev_alloc_bias = vdev_derive_alloc_bias(bias_str);
3556 		} else if (error != ENOENT) {
3557 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3558 			    VDEV_AUX_CORRUPT_DATA);
3559 			vdev_dbgmsg(vd, "vdev_load: zap_lookup(top_zap=%llu) "
3560 			    "failed [error=%d]",
3561 			    (u_longlong_t)vd->vdev_top_zap, error);
3562 			return (error);
3563 		}
3564 	}
3565 
3566 	/*
3567 	 * Load any rebuild state from the top-level vdev zap.
3568 	 */
3569 	if (vd == vd->vdev_top && vd->vdev_top_zap != 0) {
3570 		error = vdev_rebuild_load(vd);
3571 		if (error && error != ENOTSUP) {
3572 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3573 			    VDEV_AUX_CORRUPT_DATA);
3574 			vdev_dbgmsg(vd, "vdev_load: vdev_rebuild_load "
3575 			    "failed [error=%d]", error);
3576 			return (error);
3577 		}
3578 	}
3579 
3580 	/*
3581 	 * If this is a top-level vdev, initialize its metaslabs.
3582 	 */
3583 	if (vd == vd->vdev_top && vdev_is_concrete(vd)) {
3584 		vdev_metaslab_group_create(vd);
3585 
3586 		if (vd->vdev_ashift == 0 || vd->vdev_asize == 0) {
3587 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3588 			    VDEV_AUX_CORRUPT_DATA);
3589 			vdev_dbgmsg(vd, "vdev_load: invalid size. ashift=%llu, "
3590 			    "asize=%llu", (u_longlong_t)vd->vdev_ashift,
3591 			    (u_longlong_t)vd->vdev_asize);
3592 			return (SET_ERROR(ENXIO));
3593 		}
3594 
3595 		error = vdev_metaslab_init(vd, 0);
3596 		if (error != 0) {
3597 			vdev_dbgmsg(vd, "vdev_load: metaslab_init failed "
3598 			    "[error=%d]", error);
3599 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3600 			    VDEV_AUX_CORRUPT_DATA);
3601 			return (error);
3602 		}
3603 
3604 		uint64_t checkpoint_sm_obj;
3605 		error = vdev_checkpoint_sm_object(vd, &checkpoint_sm_obj);
3606 		if (error == 0 && checkpoint_sm_obj != 0) {
3607 			objset_t *mos = spa_meta_objset(vd->vdev_spa);
3608 			ASSERT(vd->vdev_asize != 0);
3609 			ASSERT3P(vd->vdev_checkpoint_sm, ==, NULL);
3610 
3611 			error = space_map_open(&vd->vdev_checkpoint_sm,
3612 			    mos, checkpoint_sm_obj, 0, vd->vdev_asize,
3613 			    vd->vdev_ashift);
3614 			if (error != 0) {
3615 				vdev_dbgmsg(vd, "vdev_load: space_map_open "
3616 				    "failed for checkpoint spacemap (obj %llu) "
3617 				    "[error=%d]",
3618 				    (u_longlong_t)checkpoint_sm_obj, error);
3619 				return (error);
3620 			}
3621 			ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
3622 
3623 			/*
3624 			 * Since the checkpoint_sm contains free entries
3625 			 * exclusively we can use space_map_allocated() to
3626 			 * indicate the cumulative checkpointed space that
3627 			 * has been freed.
3628 			 */
3629 			vd->vdev_stat.vs_checkpoint_space =
3630 			    -space_map_allocated(vd->vdev_checkpoint_sm);
3631 			vd->vdev_spa->spa_checkpoint_info.sci_dspace +=
3632 			    vd->vdev_stat.vs_checkpoint_space;
3633 		} else if (error != 0) {
3634 			vdev_dbgmsg(vd, "vdev_load: failed to retrieve "
3635 			    "checkpoint space map object from vdev ZAP "
3636 			    "[error=%d]", error);
3637 			return (error);
3638 		}
3639 	}
3640 
3641 	/*
3642 	 * If this is a leaf vdev, load its DTL.
3643 	 */
3644 	if (vd->vdev_ops->vdev_op_leaf && (error = vdev_dtl_load(vd)) != 0) {
3645 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3646 		    VDEV_AUX_CORRUPT_DATA);
3647 		vdev_dbgmsg(vd, "vdev_load: vdev_dtl_load failed "
3648 		    "[error=%d]", error);
3649 		return (error);
3650 	}
3651 
3652 	uint64_t obsolete_sm_object;
3653 	error = vdev_obsolete_sm_object(vd, &obsolete_sm_object);
3654 	if (error == 0 && obsolete_sm_object != 0) {
3655 		objset_t *mos = vd->vdev_spa->spa_meta_objset;
3656 		ASSERT(vd->vdev_asize != 0);
3657 		ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
3658 
3659 		if ((error = space_map_open(&vd->vdev_obsolete_sm, mos,
3660 		    obsolete_sm_object, 0, vd->vdev_asize, 0))) {
3661 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3662 			    VDEV_AUX_CORRUPT_DATA);
3663 			vdev_dbgmsg(vd, "vdev_load: space_map_open failed for "
3664 			    "obsolete spacemap (obj %llu) [error=%d]",
3665 			    (u_longlong_t)obsolete_sm_object, error);
3666 			return (error);
3667 		}
3668 	} else if (error != 0) {
3669 		vdev_dbgmsg(vd, "vdev_load: failed to retrieve obsolete "
3670 		    "space map object from vdev ZAP [error=%d]", error);
3671 		return (error);
3672 	}
3673 
3674 	return (0);
3675 }
3676 
3677 /*
3678  * The special vdev case is used for hot spares and l2cache devices.  Its
3679  * sole purpose it to set the vdev state for the associated vdev.  To do this,
3680  * we make sure that we can open the underlying device, then try to read the
3681  * label, and make sure that the label is sane and that it hasn't been
3682  * repurposed to another pool.
3683  */
3684 int
3685 vdev_validate_aux(vdev_t *vd)
3686 {
3687 	nvlist_t *label;
3688 	uint64_t guid, version;
3689 	uint64_t state;
3690 
3691 	if (!vdev_readable(vd))
3692 		return (0);
3693 
3694 	if ((label = vdev_label_read_config(vd, -1ULL)) == NULL) {
3695 		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
3696 		    VDEV_AUX_CORRUPT_DATA);
3697 		return (-1);
3698 	}
3699 
3700 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_VERSION, &version) != 0 ||
3701 	    !SPA_VERSION_IS_SUPPORTED(version) ||
3702 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0 ||
3703 	    guid != vd->vdev_guid ||
3704 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE, &state) != 0) {
3705 		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
3706 		    VDEV_AUX_CORRUPT_DATA);
3707 		nvlist_free(label);
3708 		return (-1);
3709 	}
3710 
3711 	/*
3712 	 * We don't actually check the pool state here.  If it's in fact in
3713 	 * use by another pool, we update this fact on the fly when requested.
3714 	 */
3715 	nvlist_free(label);
3716 	return (0);
3717 }
3718 
3719 static void
3720 vdev_destroy_ms_flush_data(vdev_t *vd, dmu_tx_t *tx)
3721 {
3722 	objset_t *mos = spa_meta_objset(vd->vdev_spa);
3723 
3724 	if (vd->vdev_top_zap == 0)
3725 		return;
3726 
3727 	uint64_t object = 0;
3728 	int err = zap_lookup(mos, vd->vdev_top_zap,
3729 	    VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, sizeof (uint64_t), 1, &object);
3730 	if (err == ENOENT)
3731 		return;
3732 	VERIFY0(err);
3733 
3734 	VERIFY0(dmu_object_free(mos, object, tx));
3735 	VERIFY0(zap_remove(mos, vd->vdev_top_zap,
3736 	    VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, tx));
3737 }
3738 
3739 /*
3740  * Free the objects used to store this vdev's spacemaps, and the array
3741  * that points to them.
3742  */
3743 void
3744 vdev_destroy_spacemaps(vdev_t *vd, dmu_tx_t *tx)
3745 {
3746 	if (vd->vdev_ms_array == 0)
3747 		return;
3748 
3749 	objset_t *mos = vd->vdev_spa->spa_meta_objset;
3750 	uint64_t array_count = vd->vdev_asize >> vd->vdev_ms_shift;
3751 	size_t array_bytes = array_count * sizeof (uint64_t);
3752 	uint64_t *smobj_array = kmem_alloc(array_bytes, KM_SLEEP);
3753 	VERIFY0(dmu_read(mos, vd->vdev_ms_array, 0,
3754 	    array_bytes, smobj_array, 0));
3755 
3756 	for (uint64_t i = 0; i < array_count; i++) {
3757 		uint64_t smobj = smobj_array[i];
3758 		if (smobj == 0)
3759 			continue;
3760 
3761 		space_map_free_obj(mos, smobj, tx);
3762 	}
3763 
3764 	kmem_free(smobj_array, array_bytes);
3765 	VERIFY0(dmu_object_free(mos, vd->vdev_ms_array, tx));
3766 	vdev_destroy_ms_flush_data(vd, tx);
3767 	vd->vdev_ms_array = 0;
3768 }
3769 
3770 static void
3771 vdev_remove_empty_log(vdev_t *vd, uint64_t txg)
3772 {
3773 	spa_t *spa = vd->vdev_spa;
3774 
3775 	ASSERT(vd->vdev_islog);
3776 	ASSERT(vd == vd->vdev_top);
3777 	ASSERT3U(txg, ==, spa_syncing_txg(spa));
3778 
3779 	dmu_tx_t *tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
3780 
3781 	vdev_destroy_spacemaps(vd, tx);
3782 	if (vd->vdev_top_zap != 0) {
3783 		vdev_destroy_unlink_zap(vd, vd->vdev_top_zap, tx);
3784 		vd->vdev_top_zap = 0;
3785 	}
3786 
3787 	dmu_tx_commit(tx);
3788 }
3789 
3790 void
3791 vdev_sync_done(vdev_t *vd, uint64_t txg)
3792 {
3793 	metaslab_t *msp;
3794 	boolean_t reassess = !txg_list_empty(&vd->vdev_ms_list, TXG_CLEAN(txg));
3795 
3796 	ASSERT(vdev_is_concrete(vd));
3797 
3798 	while ((msp = txg_list_remove(&vd->vdev_ms_list, TXG_CLEAN(txg)))
3799 	    != NULL)
3800 		metaslab_sync_done(msp, txg);
3801 
3802 	if (reassess) {
3803 		metaslab_sync_reassess(vd->vdev_mg);
3804 		if (vd->vdev_log_mg != NULL)
3805 			metaslab_sync_reassess(vd->vdev_log_mg);
3806 	}
3807 }
3808 
3809 void
3810 vdev_sync(vdev_t *vd, uint64_t txg)
3811 {
3812 	spa_t *spa = vd->vdev_spa;
3813 	vdev_t *lvd;
3814 	metaslab_t *msp;
3815 
3816 	ASSERT3U(txg, ==, spa->spa_syncing_txg);
3817 	dmu_tx_t *tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
3818 	if (range_tree_space(vd->vdev_obsolete_segments) > 0) {
3819 		ASSERT(vd->vdev_removing ||
3820 		    vd->vdev_ops == &vdev_indirect_ops);
3821 
3822 		vdev_indirect_sync_obsolete(vd, tx);
3823 
3824 		/*
3825 		 * If the vdev is indirect, it can't have dirty
3826 		 * metaslabs or DTLs.
3827 		 */
3828 		if (vd->vdev_ops == &vdev_indirect_ops) {
3829 			ASSERT(txg_list_empty(&vd->vdev_ms_list, txg));
3830 			ASSERT(txg_list_empty(&vd->vdev_dtl_list, txg));
3831 			dmu_tx_commit(tx);
3832 			return;
3833 		}
3834 	}
3835 
3836 	ASSERT(vdev_is_concrete(vd));
3837 
3838 	if (vd->vdev_ms_array == 0 && vd->vdev_ms_shift != 0 &&
3839 	    !vd->vdev_removing) {
3840 		ASSERT(vd == vd->vdev_top);
3841 		ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
3842 		vd->vdev_ms_array = dmu_object_alloc(spa->spa_meta_objset,
3843 		    DMU_OT_OBJECT_ARRAY, 0, DMU_OT_NONE, 0, tx);
3844 		ASSERT(vd->vdev_ms_array != 0);
3845 		vdev_config_dirty(vd);
3846 	}
3847 
3848 	while ((msp = txg_list_remove(&vd->vdev_ms_list, txg)) != NULL) {
3849 		metaslab_sync(msp, txg);
3850 		(void) txg_list_add(&vd->vdev_ms_list, msp, TXG_CLEAN(txg));
3851 	}
3852 
3853 	while ((lvd = txg_list_remove(&vd->vdev_dtl_list, txg)) != NULL)
3854 		vdev_dtl_sync(lvd, txg);
3855 
3856 	/*
3857 	 * If this is an empty log device being removed, destroy the
3858 	 * metadata associated with it.
3859 	 */
3860 	if (vd->vdev_islog && vd->vdev_stat.vs_alloc == 0 && vd->vdev_removing)
3861 		vdev_remove_empty_log(vd, txg);
3862 
3863 	(void) txg_list_add(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg));
3864 	dmu_tx_commit(tx);
3865 }
3866 
3867 uint64_t
3868 vdev_psize_to_asize(vdev_t *vd, uint64_t psize)
3869 {
3870 	return (vd->vdev_ops->vdev_op_asize(vd, psize));
3871 }
3872 
3873 /*
3874  * Mark the given vdev faulted.  A faulted vdev behaves as if the device could
3875  * not be opened, and no I/O is attempted.
3876  */
3877 int
3878 vdev_fault(spa_t *spa, uint64_t guid, vdev_aux_t aux)
3879 {
3880 	vdev_t *vd, *tvd;
3881 
3882 	spa_vdev_state_enter(spa, SCL_NONE);
3883 
3884 	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3885 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENODEV)));
3886 
3887 	if (!vd->vdev_ops->vdev_op_leaf)
3888 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENOTSUP)));
3889 
3890 	tvd = vd->vdev_top;
3891 
3892 	/*
3893 	 * If user did a 'zpool offline -f' then make the fault persist across
3894 	 * reboots.
3895 	 */
3896 	if (aux == VDEV_AUX_EXTERNAL_PERSIST) {
3897 		/*
3898 		 * There are two kinds of forced faults: temporary and
3899 		 * persistent.  Temporary faults go away at pool import, while
3900 		 * persistent faults stay set.  Both types of faults can be
3901 		 * cleared with a zpool clear.
3902 		 *
3903 		 * We tell if a vdev is persistently faulted by looking at the
3904 		 * ZPOOL_CONFIG_AUX_STATE nvpair.  If it's set to "external" at
3905 		 * import then it's a persistent fault.  Otherwise, it's
3906 		 * temporary.  We get ZPOOL_CONFIG_AUX_STATE set to "external"
3907 		 * by setting vd.vdev_stat.vs_aux to VDEV_AUX_EXTERNAL.  This
3908 		 * tells vdev_config_generate() (which gets run later) to set
3909 		 * ZPOOL_CONFIG_AUX_STATE to "external" in the nvlist.
3910 		 */
3911 		vd->vdev_stat.vs_aux = VDEV_AUX_EXTERNAL;
3912 		vd->vdev_tmpoffline = B_FALSE;
3913 		aux = VDEV_AUX_EXTERNAL;
3914 	} else {
3915 		vd->vdev_tmpoffline = B_TRUE;
3916 	}
3917 
3918 	/*
3919 	 * We don't directly use the aux state here, but if we do a
3920 	 * vdev_reopen(), we need this value to be present to remember why we
3921 	 * were faulted.
3922 	 */
3923 	vd->vdev_label_aux = aux;
3924 
3925 	/*
3926 	 * Faulted state takes precedence over degraded.
3927 	 */
3928 	vd->vdev_delayed_close = B_FALSE;
3929 	vd->vdev_faulted = 1ULL;
3930 	vd->vdev_degraded = 0ULL;
3931 	vdev_set_state(vd, B_FALSE, VDEV_STATE_FAULTED, aux);
3932 
3933 	/*
3934 	 * If this device has the only valid copy of the data, then
3935 	 * back off and simply mark the vdev as degraded instead.
3936 	 */
3937 	if (!tvd->vdev_islog && vd->vdev_aux == NULL && vdev_dtl_required(vd)) {
3938 		vd->vdev_degraded = 1ULL;
3939 		vd->vdev_faulted = 0ULL;
3940 
3941 		/*
3942 		 * If we reopen the device and it's not dead, only then do we
3943 		 * mark it degraded.
3944 		 */
3945 		vdev_reopen(tvd);
3946 
3947 		if (vdev_readable(vd))
3948 			vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED, aux);
3949 	}
3950 
3951 	return (spa_vdev_state_exit(spa, vd, 0));
3952 }
3953 
3954 /*
3955  * Mark the given vdev degraded.  A degraded vdev is purely an indication to the
3956  * user that something is wrong.  The vdev continues to operate as normal as far
3957  * as I/O is concerned.
3958  */
3959 int
3960 vdev_degrade(spa_t *spa, uint64_t guid, vdev_aux_t aux)
3961 {
3962 	vdev_t *vd;
3963 
3964 	spa_vdev_state_enter(spa, SCL_NONE);
3965 
3966 	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3967 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENODEV)));
3968 
3969 	if (!vd->vdev_ops->vdev_op_leaf)
3970 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENOTSUP)));
3971 
3972 	/*
3973 	 * If the vdev is already faulted, then don't do anything.
3974 	 */
3975 	if (vd->vdev_faulted || vd->vdev_degraded)
3976 		return (spa_vdev_state_exit(spa, NULL, 0));
3977 
3978 	vd->vdev_degraded = 1ULL;
3979 	if (!vdev_is_dead(vd))
3980 		vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED,
3981 		    aux);
3982 
3983 	return (spa_vdev_state_exit(spa, vd, 0));
3984 }
3985 
3986 int
3987 vdev_remove_wanted(spa_t *spa, uint64_t guid)
3988 {
3989 	vdev_t *vd;
3990 
3991 	spa_vdev_state_enter(spa, SCL_NONE);
3992 
3993 	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3994 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENODEV)));
3995 
3996 	/*
3997 	 * If the vdev is already removed, then don't do anything.
3998 	 */
3999 	if (vd->vdev_removed)
4000 		return (spa_vdev_state_exit(spa, NULL, 0));
4001 
4002 	vd->vdev_remove_wanted = B_TRUE;
4003 	spa_async_request(spa, SPA_ASYNC_REMOVE);
4004 
4005 	return (spa_vdev_state_exit(spa, vd, 0));
4006 }
4007 
4008 
4009 /*
4010  * Online the given vdev.
4011  *
4012  * If 'ZFS_ONLINE_UNSPARE' is set, it implies two things.  First, any attached
4013  * spare device should be detached when the device finishes resilvering.
4014  * Second, the online should be treated like a 'test' online case, so no FMA
4015  * events are generated if the device fails to open.
4016  */
4017 int
4018 vdev_online(spa_t *spa, uint64_t guid, uint64_t flags, vdev_state_t *newstate)
4019 {
4020 	vdev_t *vd, *tvd, *pvd, *rvd = spa->spa_root_vdev;
4021 	boolean_t wasoffline;
4022 	vdev_state_t oldstate;
4023 
4024 	spa_vdev_state_enter(spa, SCL_NONE);
4025 
4026 	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
4027 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENODEV)));
4028 
4029 	if (!vd->vdev_ops->vdev_op_leaf)
4030 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENOTSUP)));
4031 
4032 	wasoffline = (vd->vdev_offline || vd->vdev_tmpoffline);
4033 	oldstate = vd->vdev_state;
4034 
4035 	tvd = vd->vdev_top;
4036 	vd->vdev_offline = B_FALSE;
4037 	vd->vdev_tmpoffline = B_FALSE;
4038 	vd->vdev_checkremove = !!(flags & ZFS_ONLINE_CHECKREMOVE);
4039 	vd->vdev_forcefault = !!(flags & ZFS_ONLINE_FORCEFAULT);
4040 
4041 	/* XXX - L2ARC 1.0 does not support expansion */
4042 	if (!vd->vdev_aux) {
4043 		for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
4044 			pvd->vdev_expanding = !!((flags & ZFS_ONLINE_EXPAND) ||
4045 			    spa->spa_autoexpand);
4046 		vd->vdev_expansion_time = gethrestime_sec();
4047 	}
4048 
4049 	vdev_reopen(tvd);
4050 	vd->vdev_checkremove = vd->vdev_forcefault = B_FALSE;
4051 
4052 	if (!vd->vdev_aux) {
4053 		for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
4054 			pvd->vdev_expanding = B_FALSE;
4055 	}
4056 
4057 	if (newstate)
4058 		*newstate = vd->vdev_state;
4059 	if ((flags & ZFS_ONLINE_UNSPARE) &&
4060 	    !vdev_is_dead(vd) && vd->vdev_parent &&
4061 	    vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
4062 	    vd->vdev_parent->vdev_child[0] == vd)
4063 		vd->vdev_unspare = B_TRUE;
4064 
4065 	if ((flags & ZFS_ONLINE_EXPAND) || spa->spa_autoexpand) {
4066 
4067 		/* XXX - L2ARC 1.0 does not support expansion */
4068 		if (vd->vdev_aux)
4069 			return (spa_vdev_state_exit(spa, vd, ENOTSUP));
4070 		spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
4071 	}
4072 
4073 	/* Restart initializing if necessary */
4074 	mutex_enter(&vd->vdev_initialize_lock);
4075 	if (vdev_writeable(vd) &&
4076 	    vd->vdev_initialize_thread == NULL &&
4077 	    vd->vdev_initialize_state == VDEV_INITIALIZE_ACTIVE) {
4078 		(void) vdev_initialize(vd);
4079 	}
4080 	mutex_exit(&vd->vdev_initialize_lock);
4081 
4082 	/*
4083 	 * Restart trimming if necessary. We do not restart trimming for cache
4084 	 * devices here. This is triggered by l2arc_rebuild_vdev()
4085 	 * asynchronously for the whole device or in l2arc_evict() as it evicts
4086 	 * space for upcoming writes.
4087 	 */
4088 	mutex_enter(&vd->vdev_trim_lock);
4089 	if (vdev_writeable(vd) && !vd->vdev_isl2cache &&
4090 	    vd->vdev_trim_thread == NULL &&
4091 	    vd->vdev_trim_state == VDEV_TRIM_ACTIVE) {
4092 		(void) vdev_trim(vd, vd->vdev_trim_rate, vd->vdev_trim_partial,
4093 		    vd->vdev_trim_secure);
4094 	}
4095 	mutex_exit(&vd->vdev_trim_lock);
4096 
4097 	if (wasoffline ||
4098 	    (oldstate < VDEV_STATE_DEGRADED &&
4099 	    vd->vdev_state >= VDEV_STATE_DEGRADED))
4100 		spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_ONLINE);
4101 
4102 	return (spa_vdev_state_exit(spa, vd, 0));
4103 }
4104 
4105 static int
4106 vdev_offline_locked(spa_t *spa, uint64_t guid, uint64_t flags)
4107 {
4108 	vdev_t *vd, *tvd;
4109 	int error = 0;
4110 	uint64_t generation;
4111 	metaslab_group_t *mg;
4112 
4113 top:
4114 	spa_vdev_state_enter(spa, SCL_ALLOC);
4115 
4116 	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
4117 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENODEV)));
4118 
4119 	if (!vd->vdev_ops->vdev_op_leaf)
4120 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENOTSUP)));
4121 
4122 	if (vd->vdev_ops == &vdev_draid_spare_ops)
4123 		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
4124 
4125 	tvd = vd->vdev_top;
4126 	mg = tvd->vdev_mg;
4127 	generation = spa->spa_config_generation + 1;
4128 
4129 	/*
4130 	 * If the device isn't already offline, try to offline it.
4131 	 */
4132 	if (!vd->vdev_offline) {
4133 		/*
4134 		 * If this device has the only valid copy of some data,
4135 		 * don't allow it to be offlined. Log devices are always
4136 		 * expendable.
4137 		 */
4138 		if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
4139 		    vdev_dtl_required(vd))
4140 			return (spa_vdev_state_exit(spa, NULL,
4141 			    SET_ERROR(EBUSY)));
4142 
4143 		/*
4144 		 * If the top-level is a slog and it has had allocations
4145 		 * then proceed.  We check that the vdev's metaslab group
4146 		 * is not NULL since it's possible that we may have just
4147 		 * added this vdev but not yet initialized its metaslabs.
4148 		 */
4149 		if (tvd->vdev_islog && mg != NULL) {
4150 			/*
4151 			 * Prevent any future allocations.
4152 			 */
4153 			ASSERT3P(tvd->vdev_log_mg, ==, NULL);
4154 			metaslab_group_passivate(mg);
4155 			(void) spa_vdev_state_exit(spa, vd, 0);
4156 
4157 			error = spa_reset_logs(spa);
4158 
4159 			/*
4160 			 * If the log device was successfully reset but has
4161 			 * checkpointed data, do not offline it.
4162 			 */
4163 			if (error == 0 &&
4164 			    tvd->vdev_checkpoint_sm != NULL) {
4165 				ASSERT3U(space_map_allocated(
4166 				    tvd->vdev_checkpoint_sm), !=, 0);
4167 				error = ZFS_ERR_CHECKPOINT_EXISTS;
4168 			}
4169 
4170 			spa_vdev_state_enter(spa, SCL_ALLOC);
4171 
4172 			/*
4173 			 * Check to see if the config has changed.
4174 			 */
4175 			if (error || generation != spa->spa_config_generation) {
4176 				metaslab_group_activate(mg);
4177 				if (error)
4178 					return (spa_vdev_state_exit(spa,
4179 					    vd, error));
4180 				(void) spa_vdev_state_exit(spa, vd, 0);
4181 				goto top;
4182 			}
4183 			ASSERT0(tvd->vdev_stat.vs_alloc);
4184 		}
4185 
4186 		/*
4187 		 * Offline this device and reopen its top-level vdev.
4188 		 * If the top-level vdev is a log device then just offline
4189 		 * it. Otherwise, if this action results in the top-level
4190 		 * vdev becoming unusable, undo it and fail the request.
4191 		 */
4192 		vd->vdev_offline = B_TRUE;
4193 		vdev_reopen(tvd);
4194 
4195 		if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
4196 		    vdev_is_dead(tvd)) {
4197 			vd->vdev_offline = B_FALSE;
4198 			vdev_reopen(tvd);
4199 			return (spa_vdev_state_exit(spa, NULL,
4200 			    SET_ERROR(EBUSY)));
4201 		}
4202 
4203 		/*
4204 		 * Add the device back into the metaslab rotor so that
4205 		 * once we online the device it's open for business.
4206 		 */
4207 		if (tvd->vdev_islog && mg != NULL)
4208 			metaslab_group_activate(mg);
4209 	}
4210 
4211 	vd->vdev_tmpoffline = !!(flags & ZFS_OFFLINE_TEMPORARY);
4212 
4213 	return (spa_vdev_state_exit(spa, vd, 0));
4214 }
4215 
4216 int
4217 vdev_offline(spa_t *spa, uint64_t guid, uint64_t flags)
4218 {
4219 	int error;
4220 
4221 	mutex_enter(&spa->spa_vdev_top_lock);
4222 	error = vdev_offline_locked(spa, guid, flags);
4223 	mutex_exit(&spa->spa_vdev_top_lock);
4224 
4225 	return (error);
4226 }
4227 
4228 /*
4229  * Clear the error counts associated with this vdev.  Unlike vdev_online() and
4230  * vdev_offline(), we assume the spa config is locked.  We also clear all
4231  * children.  If 'vd' is NULL, then the user wants to clear all vdevs.
4232  */
4233 void
4234 vdev_clear(spa_t *spa, vdev_t *vd)
4235 {
4236 	vdev_t *rvd = spa->spa_root_vdev;
4237 
4238 	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
4239 
4240 	if (vd == NULL)
4241 		vd = rvd;
4242 
4243 	vd->vdev_stat.vs_read_errors = 0;
4244 	vd->vdev_stat.vs_write_errors = 0;
4245 	vd->vdev_stat.vs_checksum_errors = 0;
4246 	vd->vdev_stat.vs_slow_ios = 0;
4247 
4248 	for (int c = 0; c < vd->vdev_children; c++)
4249 		vdev_clear(spa, vd->vdev_child[c]);
4250 
4251 	/*
4252 	 * It makes no sense to "clear" an indirect vdev.
4253 	 */
4254 	if (!vdev_is_concrete(vd))
4255 		return;
4256 
4257 	/*
4258 	 * If we're in the FAULTED state or have experienced failed I/O, then
4259 	 * clear the persistent state and attempt to reopen the device.  We
4260 	 * also mark the vdev config dirty, so that the new faulted state is
4261 	 * written out to disk.
4262 	 */
4263 	if (vd->vdev_faulted || vd->vdev_degraded ||
4264 	    !vdev_readable(vd) || !vdev_writeable(vd)) {
4265 		/*
4266 		 * When reopening in response to a clear event, it may be due to
4267 		 * a fmadm repair request.  In this case, if the device is
4268 		 * still broken, we want to still post the ereport again.
4269 		 */
4270 		vd->vdev_forcefault = B_TRUE;
4271 
4272 		vd->vdev_faulted = vd->vdev_degraded = 0ULL;
4273 		vd->vdev_cant_read = B_FALSE;
4274 		vd->vdev_cant_write = B_FALSE;
4275 		vd->vdev_stat.vs_aux = 0;
4276 
4277 		vdev_reopen(vd == rvd ? rvd : vd->vdev_top);
4278 
4279 		vd->vdev_forcefault = B_FALSE;
4280 
4281 		if (vd != rvd && vdev_writeable(vd->vdev_top))
4282 			vdev_state_dirty(vd->vdev_top);
4283 
4284 		/* If a resilver isn't required, check if vdevs can be culled */
4285 		if (vd->vdev_aux == NULL && !vdev_is_dead(vd) &&
4286 		    !dsl_scan_resilvering(spa->spa_dsl_pool) &&
4287 		    !dsl_scan_resilver_scheduled(spa->spa_dsl_pool))
4288 			spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
4289 
4290 		spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_CLEAR);
4291 	}
4292 
4293 	/*
4294 	 * When clearing a FMA-diagnosed fault, we always want to
4295 	 * unspare the device, as we assume that the original spare was
4296 	 * done in response to the FMA fault.
4297 	 */
4298 	if (!vdev_is_dead(vd) && vd->vdev_parent != NULL &&
4299 	    vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
4300 	    vd->vdev_parent->vdev_child[0] == vd)
4301 		vd->vdev_unspare = B_TRUE;
4302 
4303 	/* Clear recent error events cache (i.e. duplicate events tracking) */
4304 	zfs_ereport_clear(spa, vd);
4305 }
4306 
4307 boolean_t
4308 vdev_is_dead(vdev_t *vd)
4309 {
4310 	/*
4311 	 * Holes and missing devices are always considered "dead".
4312 	 * This simplifies the code since we don't have to check for
4313 	 * these types of devices in the various code paths.
4314 	 * Instead we rely on the fact that we skip over dead devices
4315 	 * before issuing I/O to them.
4316 	 */
4317 	return (vd->vdev_state < VDEV_STATE_DEGRADED ||
4318 	    vd->vdev_ops == &vdev_hole_ops ||
4319 	    vd->vdev_ops == &vdev_missing_ops);
4320 }
4321 
4322 boolean_t
4323 vdev_readable(vdev_t *vd)
4324 {
4325 	return (!vdev_is_dead(vd) && !vd->vdev_cant_read);
4326 }
4327 
4328 boolean_t
4329 vdev_writeable(vdev_t *vd)
4330 {
4331 	return (!vdev_is_dead(vd) && !vd->vdev_cant_write &&
4332 	    vdev_is_concrete(vd));
4333 }
4334 
4335 boolean_t
4336 vdev_allocatable(vdev_t *vd)
4337 {
4338 	uint64_t state = vd->vdev_state;
4339 
4340 	/*
4341 	 * We currently allow allocations from vdevs which may be in the
4342 	 * process of reopening (i.e. VDEV_STATE_CLOSED). If the device
4343 	 * fails to reopen then we'll catch it later when we're holding
4344 	 * the proper locks.  Note that we have to get the vdev state
4345 	 * in a local variable because although it changes atomically,
4346 	 * we're asking two separate questions about it.
4347 	 */
4348 	return (!(state < VDEV_STATE_DEGRADED && state != VDEV_STATE_CLOSED) &&
4349 	    !vd->vdev_cant_write && vdev_is_concrete(vd) &&
4350 	    vd->vdev_mg->mg_initialized);
4351 }
4352 
4353 boolean_t
4354 vdev_accessible(vdev_t *vd, zio_t *zio)
4355 {
4356 	ASSERT(zio->io_vd == vd);
4357 
4358 	if (vdev_is_dead(vd) || vd->vdev_remove_wanted)
4359 		return (B_FALSE);
4360 
4361 	if (zio->io_type == ZIO_TYPE_READ)
4362 		return (!vd->vdev_cant_read);
4363 
4364 	if (zio->io_type == ZIO_TYPE_WRITE)
4365 		return (!vd->vdev_cant_write);
4366 
4367 	return (B_TRUE);
4368 }
4369 
4370 static void
4371 vdev_get_child_stat(vdev_t *cvd, vdev_stat_t *vs, vdev_stat_t *cvs)
4372 {
4373 	/*
4374 	 * Exclude the dRAID spare when aggregating to avoid double counting
4375 	 * the ops and bytes.  These IOs are counted by the physical leaves.
4376 	 */
4377 	if (cvd->vdev_ops == &vdev_draid_spare_ops)
4378 		return;
4379 
4380 	for (int t = 0; t < VS_ZIO_TYPES; t++) {
4381 		vs->vs_ops[t] += cvs->vs_ops[t];
4382 		vs->vs_bytes[t] += cvs->vs_bytes[t];
4383 	}
4384 
4385 	cvs->vs_scan_removing = cvd->vdev_removing;
4386 }
4387 
4388 /*
4389  * Get extended stats
4390  */
4391 static void
4392 vdev_get_child_stat_ex(vdev_t *cvd, vdev_stat_ex_t *vsx, vdev_stat_ex_t *cvsx)
4393 {
4394 	(void) cvd;
4395 
4396 	int t, b;
4397 	for (t = 0; t < ZIO_TYPES; t++) {
4398 		for (b = 0; b < ARRAY_SIZE(vsx->vsx_disk_histo[0]); b++)
4399 			vsx->vsx_disk_histo[t][b] += cvsx->vsx_disk_histo[t][b];
4400 
4401 		for (b = 0; b < ARRAY_SIZE(vsx->vsx_total_histo[0]); b++) {
4402 			vsx->vsx_total_histo[t][b] +=
4403 			    cvsx->vsx_total_histo[t][b];
4404 		}
4405 	}
4406 
4407 	for (t = 0; t < ZIO_PRIORITY_NUM_QUEUEABLE; t++) {
4408 		for (b = 0; b < ARRAY_SIZE(vsx->vsx_queue_histo[0]); b++) {
4409 			vsx->vsx_queue_histo[t][b] +=
4410 			    cvsx->vsx_queue_histo[t][b];
4411 		}
4412 		vsx->vsx_active_queue[t] += cvsx->vsx_active_queue[t];
4413 		vsx->vsx_pend_queue[t] += cvsx->vsx_pend_queue[t];
4414 
4415 		for (b = 0; b < ARRAY_SIZE(vsx->vsx_ind_histo[0]); b++)
4416 			vsx->vsx_ind_histo[t][b] += cvsx->vsx_ind_histo[t][b];
4417 
4418 		for (b = 0; b < ARRAY_SIZE(vsx->vsx_agg_histo[0]); b++)
4419 			vsx->vsx_agg_histo[t][b] += cvsx->vsx_agg_histo[t][b];
4420 	}
4421 
4422 }
4423 
4424 boolean_t
4425 vdev_is_spacemap_addressable(vdev_t *vd)
4426 {
4427 	if (spa_feature_is_active(vd->vdev_spa, SPA_FEATURE_SPACEMAP_V2))
4428 		return (B_TRUE);
4429 
4430 	/*
4431 	 * If double-word space map entries are not enabled we assume
4432 	 * 47 bits of the space map entry are dedicated to the entry's
4433 	 * offset (see SM_OFFSET_BITS in space_map.h). We then use that
4434 	 * to calculate the maximum address that can be described by a
4435 	 * space map entry for the given device.
4436 	 */
4437 	uint64_t shift = vd->vdev_ashift + SM_OFFSET_BITS;
4438 
4439 	if (shift >= 63) /* detect potential overflow */
4440 		return (B_TRUE);
4441 
4442 	return (vd->vdev_asize < (1ULL << shift));
4443 }
4444 
4445 /*
4446  * Get statistics for the given vdev.
4447  */
4448 static void
4449 vdev_get_stats_ex_impl(vdev_t *vd, vdev_stat_t *vs, vdev_stat_ex_t *vsx)
4450 {
4451 	int t;
4452 	/*
4453 	 * If we're getting stats on the root vdev, aggregate the I/O counts
4454 	 * over all top-level vdevs (i.e. the direct children of the root).
4455 	 */
4456 	if (!vd->vdev_ops->vdev_op_leaf) {
4457 		if (vs) {
4458 			memset(vs->vs_ops, 0, sizeof (vs->vs_ops));
4459 			memset(vs->vs_bytes, 0, sizeof (vs->vs_bytes));
4460 		}
4461 		if (vsx)
4462 			memset(vsx, 0, sizeof (*vsx));
4463 
4464 		for (int c = 0; c < vd->vdev_children; c++) {
4465 			vdev_t *cvd = vd->vdev_child[c];
4466 			vdev_stat_t *cvs = &cvd->vdev_stat;
4467 			vdev_stat_ex_t *cvsx = &cvd->vdev_stat_ex;
4468 
4469 			vdev_get_stats_ex_impl(cvd, cvs, cvsx);
4470 			if (vs)
4471 				vdev_get_child_stat(cvd, vs, cvs);
4472 			if (vsx)
4473 				vdev_get_child_stat_ex(cvd, vsx, cvsx);
4474 		}
4475 	} else {
4476 		/*
4477 		 * We're a leaf.  Just copy our ZIO active queue stats in.  The
4478 		 * other leaf stats are updated in vdev_stat_update().
4479 		 */
4480 		if (!vsx)
4481 			return;
4482 
4483 		memcpy(vsx, &vd->vdev_stat_ex, sizeof (vd->vdev_stat_ex));
4484 
4485 		for (t = 0; t < ARRAY_SIZE(vd->vdev_queue.vq_class); t++) {
4486 			vsx->vsx_active_queue[t] =
4487 			    vd->vdev_queue.vq_class[t].vqc_active;
4488 			vsx->vsx_pend_queue[t] = avl_numnodes(
4489 			    &vd->vdev_queue.vq_class[t].vqc_queued_tree);
4490 		}
4491 	}
4492 }
4493 
4494 void
4495 vdev_get_stats_ex(vdev_t *vd, vdev_stat_t *vs, vdev_stat_ex_t *vsx)
4496 {
4497 	vdev_t *tvd = vd->vdev_top;
4498 	mutex_enter(&vd->vdev_stat_lock);
4499 	if (vs) {
4500 		memcpy(vs, &vd->vdev_stat, sizeof (*vs));
4501 		vs->vs_timestamp = gethrtime() - vs->vs_timestamp;
4502 		vs->vs_state = vd->vdev_state;
4503 		vs->vs_rsize = vdev_get_min_asize(vd);
4504 
4505 		if (vd->vdev_ops->vdev_op_leaf) {
4506 			vs->vs_pspace = vd->vdev_psize;
4507 			vs->vs_rsize += VDEV_LABEL_START_SIZE +
4508 			    VDEV_LABEL_END_SIZE;
4509 			/*
4510 			 * Report initializing progress. Since we don't
4511 			 * have the initializing locks held, this is only
4512 			 * an estimate (although a fairly accurate one).
4513 			 */
4514 			vs->vs_initialize_bytes_done =
4515 			    vd->vdev_initialize_bytes_done;
4516 			vs->vs_initialize_bytes_est =
4517 			    vd->vdev_initialize_bytes_est;
4518 			vs->vs_initialize_state = vd->vdev_initialize_state;
4519 			vs->vs_initialize_action_time =
4520 			    vd->vdev_initialize_action_time;
4521 
4522 			/*
4523 			 * Report manual TRIM progress. Since we don't have
4524 			 * the manual TRIM locks held, this is only an
4525 			 * estimate (although fairly accurate one).
4526 			 */
4527 			vs->vs_trim_notsup = !vd->vdev_has_trim;
4528 			vs->vs_trim_bytes_done = vd->vdev_trim_bytes_done;
4529 			vs->vs_trim_bytes_est = vd->vdev_trim_bytes_est;
4530 			vs->vs_trim_state = vd->vdev_trim_state;
4531 			vs->vs_trim_action_time = vd->vdev_trim_action_time;
4532 
4533 			/* Set when there is a deferred resilver. */
4534 			vs->vs_resilver_deferred = vd->vdev_resilver_deferred;
4535 		}
4536 
4537 		/*
4538 		 * Report expandable space on top-level, non-auxiliary devices
4539 		 * only. The expandable space is reported in terms of metaslab
4540 		 * sized units since that determines how much space the pool
4541 		 * can expand.
4542 		 */
4543 		if (vd->vdev_aux == NULL && tvd != NULL) {
4544 			vs->vs_esize = P2ALIGN(
4545 			    vd->vdev_max_asize - vd->vdev_asize,
4546 			    1ULL << tvd->vdev_ms_shift);
4547 		}
4548 
4549 		vs->vs_configured_ashift = vd->vdev_top != NULL
4550 		    ? vd->vdev_top->vdev_ashift : vd->vdev_ashift;
4551 		vs->vs_logical_ashift = vd->vdev_logical_ashift;
4552 		if (vd->vdev_physical_ashift <= ASHIFT_MAX)
4553 			vs->vs_physical_ashift = vd->vdev_physical_ashift;
4554 		else
4555 			vs->vs_physical_ashift = 0;
4556 
4557 		/*
4558 		 * Report fragmentation and rebuild progress for top-level,
4559 		 * non-auxiliary, concrete devices.
4560 		 */
4561 		if (vd->vdev_aux == NULL && vd == vd->vdev_top &&
4562 		    vdev_is_concrete(vd)) {
4563 			/*
4564 			 * The vdev fragmentation rating doesn't take into
4565 			 * account the embedded slog metaslab (vdev_log_mg).
4566 			 * Since it's only one metaslab, it would have a tiny
4567 			 * impact on the overall fragmentation.
4568 			 */
4569 			vs->vs_fragmentation = (vd->vdev_mg != NULL) ?
4570 			    vd->vdev_mg->mg_fragmentation : 0;
4571 		}
4572 		vs->vs_noalloc = MAX(vd->vdev_noalloc,
4573 		    tvd ? tvd->vdev_noalloc : 0);
4574 	}
4575 
4576 	vdev_get_stats_ex_impl(vd, vs, vsx);
4577 	mutex_exit(&vd->vdev_stat_lock);
4578 }
4579 
4580 void
4581 vdev_get_stats(vdev_t *vd, vdev_stat_t *vs)
4582 {
4583 	return (vdev_get_stats_ex(vd, vs, NULL));
4584 }
4585 
4586 void
4587 vdev_clear_stats(vdev_t *vd)
4588 {
4589 	mutex_enter(&vd->vdev_stat_lock);
4590 	vd->vdev_stat.vs_space = 0;
4591 	vd->vdev_stat.vs_dspace = 0;
4592 	vd->vdev_stat.vs_alloc = 0;
4593 	mutex_exit(&vd->vdev_stat_lock);
4594 }
4595 
4596 void
4597 vdev_scan_stat_init(vdev_t *vd)
4598 {
4599 	vdev_stat_t *vs = &vd->vdev_stat;
4600 
4601 	for (int c = 0; c < vd->vdev_children; c++)
4602 		vdev_scan_stat_init(vd->vdev_child[c]);
4603 
4604 	mutex_enter(&vd->vdev_stat_lock);
4605 	vs->vs_scan_processed = 0;
4606 	mutex_exit(&vd->vdev_stat_lock);
4607 }
4608 
4609 void
4610 vdev_stat_update(zio_t *zio, uint64_t psize)
4611 {
4612 	spa_t *spa = zio->io_spa;
4613 	vdev_t *rvd = spa->spa_root_vdev;
4614 	vdev_t *vd = zio->io_vd ? zio->io_vd : rvd;
4615 	vdev_t *pvd;
4616 	uint64_t txg = zio->io_txg;
4617 	vdev_stat_t *vs = vd ? &vd->vdev_stat : NULL;
4618 	vdev_stat_ex_t *vsx = vd ? &vd->vdev_stat_ex : NULL;
4619 	zio_type_t type = zio->io_type;
4620 	int flags = zio->io_flags;
4621 
4622 	/*
4623 	 * If this i/o is a gang leader, it didn't do any actual work.
4624 	 */
4625 	if (zio->io_gang_tree)
4626 		return;
4627 
4628 	if (zio->io_error == 0) {
4629 		/*
4630 		 * If this is a root i/o, don't count it -- we've already
4631 		 * counted the top-level vdevs, and vdev_get_stats() will
4632 		 * aggregate them when asked.  This reduces contention on
4633 		 * the root vdev_stat_lock and implicitly handles blocks
4634 		 * that compress away to holes, for which there is no i/o.
4635 		 * (Holes never create vdev children, so all the counters
4636 		 * remain zero, which is what we want.)
4637 		 *
4638 		 * Note: this only applies to successful i/o (io_error == 0)
4639 		 * because unlike i/o counts, errors are not additive.
4640 		 * When reading a ditto block, for example, failure of
4641 		 * one top-level vdev does not imply a root-level error.
4642 		 */
4643 		if (vd == rvd)
4644 			return;
4645 
4646 		ASSERT(vd == zio->io_vd);
4647 
4648 		if (flags & ZIO_FLAG_IO_BYPASS)
4649 			return;
4650 
4651 		mutex_enter(&vd->vdev_stat_lock);
4652 
4653 		if (flags & ZIO_FLAG_IO_REPAIR) {
4654 			/*
4655 			 * Repair is the result of a resilver issued by the
4656 			 * scan thread (spa_sync).
4657 			 */
4658 			if (flags & ZIO_FLAG_SCAN_THREAD) {
4659 				dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
4660 				dsl_scan_phys_t *scn_phys = &scn->scn_phys;
4661 				uint64_t *processed = &scn_phys->scn_processed;
4662 
4663 				if (vd->vdev_ops->vdev_op_leaf)
4664 					atomic_add_64(processed, psize);
4665 				vs->vs_scan_processed += psize;
4666 			}
4667 
4668 			/*
4669 			 * Repair is the result of a rebuild issued by the
4670 			 * rebuild thread (vdev_rebuild_thread).  To avoid
4671 			 * double counting repaired bytes the virtual dRAID
4672 			 * spare vdev is excluded from the processed bytes.
4673 			 */
4674 			if (zio->io_priority == ZIO_PRIORITY_REBUILD) {
4675 				vdev_t *tvd = vd->vdev_top;
4676 				vdev_rebuild_t *vr = &tvd->vdev_rebuild_config;
4677 				vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
4678 				uint64_t *rebuilt = &vrp->vrp_bytes_rebuilt;
4679 
4680 				if (vd->vdev_ops->vdev_op_leaf &&
4681 				    vd->vdev_ops != &vdev_draid_spare_ops) {
4682 					atomic_add_64(rebuilt, psize);
4683 				}
4684 				vs->vs_rebuild_processed += psize;
4685 			}
4686 
4687 			if (flags & ZIO_FLAG_SELF_HEAL)
4688 				vs->vs_self_healed += psize;
4689 		}
4690 
4691 		/*
4692 		 * The bytes/ops/histograms are recorded at the leaf level and
4693 		 * aggregated into the higher level vdevs in vdev_get_stats().
4694 		 */
4695 		if (vd->vdev_ops->vdev_op_leaf &&
4696 		    (zio->io_priority < ZIO_PRIORITY_NUM_QUEUEABLE)) {
4697 			zio_type_t vs_type = type;
4698 			zio_priority_t priority = zio->io_priority;
4699 
4700 			/*
4701 			 * TRIM ops and bytes are reported to user space as
4702 			 * ZIO_TYPE_IOCTL.  This is done to preserve the
4703 			 * vdev_stat_t structure layout for user space.
4704 			 */
4705 			if (type == ZIO_TYPE_TRIM)
4706 				vs_type = ZIO_TYPE_IOCTL;
4707 
4708 			/*
4709 			 * Solely for the purposes of 'zpool iostat -lqrw'
4710 			 * reporting use the priority to categorize the IO.
4711 			 * Only the following are reported to user space:
4712 			 *
4713 			 *   ZIO_PRIORITY_SYNC_READ,
4714 			 *   ZIO_PRIORITY_SYNC_WRITE,
4715 			 *   ZIO_PRIORITY_ASYNC_READ,
4716 			 *   ZIO_PRIORITY_ASYNC_WRITE,
4717 			 *   ZIO_PRIORITY_SCRUB,
4718 			 *   ZIO_PRIORITY_TRIM,
4719 			 *   ZIO_PRIORITY_REBUILD.
4720 			 */
4721 			if (priority == ZIO_PRIORITY_INITIALIZING) {
4722 				ASSERT3U(type, ==, ZIO_TYPE_WRITE);
4723 				priority = ZIO_PRIORITY_ASYNC_WRITE;
4724 			} else if (priority == ZIO_PRIORITY_REMOVAL) {
4725 				priority = ((type == ZIO_TYPE_WRITE) ?
4726 				    ZIO_PRIORITY_ASYNC_WRITE :
4727 				    ZIO_PRIORITY_ASYNC_READ);
4728 			}
4729 
4730 			vs->vs_ops[vs_type]++;
4731 			vs->vs_bytes[vs_type] += psize;
4732 
4733 			if (flags & ZIO_FLAG_DELEGATED) {
4734 				vsx->vsx_agg_histo[priority]
4735 				    [RQ_HISTO(zio->io_size)]++;
4736 			} else {
4737 				vsx->vsx_ind_histo[priority]
4738 				    [RQ_HISTO(zio->io_size)]++;
4739 			}
4740 
4741 			if (zio->io_delta && zio->io_delay) {
4742 				vsx->vsx_queue_histo[priority]
4743 				    [L_HISTO(zio->io_delta - zio->io_delay)]++;
4744 				vsx->vsx_disk_histo[type]
4745 				    [L_HISTO(zio->io_delay)]++;
4746 				vsx->vsx_total_histo[type]
4747 				    [L_HISTO(zio->io_delta)]++;
4748 			}
4749 		}
4750 
4751 		mutex_exit(&vd->vdev_stat_lock);
4752 		return;
4753 	}
4754 
4755 	if (flags & ZIO_FLAG_SPECULATIVE)
4756 		return;
4757 
4758 	/*
4759 	 * If this is an I/O error that is going to be retried, then ignore the
4760 	 * error.  Otherwise, the user may interpret B_FAILFAST I/O errors as
4761 	 * hard errors, when in reality they can happen for any number of
4762 	 * innocuous reasons (bus resets, MPxIO link failure, etc).
4763 	 */
4764 	if (zio->io_error == EIO &&
4765 	    !(zio->io_flags & ZIO_FLAG_IO_RETRY))
4766 		return;
4767 
4768 	/*
4769 	 * Intent logs writes won't propagate their error to the root
4770 	 * I/O so don't mark these types of failures as pool-level
4771 	 * errors.
4772 	 */
4773 	if (zio->io_vd == NULL && (zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
4774 		return;
4775 
4776 	if (type == ZIO_TYPE_WRITE && txg != 0 &&
4777 	    (!(flags & ZIO_FLAG_IO_REPAIR) ||
4778 	    (flags & ZIO_FLAG_SCAN_THREAD) ||
4779 	    spa->spa_claiming)) {
4780 		/*
4781 		 * This is either a normal write (not a repair), or it's
4782 		 * a repair induced by the scrub thread, or it's a repair
4783 		 * made by zil_claim() during spa_load() in the first txg.
4784 		 * In the normal case, we commit the DTL change in the same
4785 		 * txg as the block was born.  In the scrub-induced repair
4786 		 * case, we know that scrubs run in first-pass syncing context,
4787 		 * so we commit the DTL change in spa_syncing_txg(spa).
4788 		 * In the zil_claim() case, we commit in spa_first_txg(spa).
4789 		 *
4790 		 * We currently do not make DTL entries for failed spontaneous
4791 		 * self-healing writes triggered by normal (non-scrubbing)
4792 		 * reads, because we have no transactional context in which to
4793 		 * do so -- and it's not clear that it'd be desirable anyway.
4794 		 */
4795 		if (vd->vdev_ops->vdev_op_leaf) {
4796 			uint64_t commit_txg = txg;
4797 			if (flags & ZIO_FLAG_SCAN_THREAD) {
4798 				ASSERT(flags & ZIO_FLAG_IO_REPAIR);
4799 				ASSERT(spa_sync_pass(spa) == 1);
4800 				vdev_dtl_dirty(vd, DTL_SCRUB, txg, 1);
4801 				commit_txg = spa_syncing_txg(spa);
4802 			} else if (spa->spa_claiming) {
4803 				ASSERT(flags & ZIO_FLAG_IO_REPAIR);
4804 				commit_txg = spa_first_txg(spa);
4805 			}
4806 			ASSERT(commit_txg >= spa_syncing_txg(spa));
4807 			if (vdev_dtl_contains(vd, DTL_MISSING, txg, 1))
4808 				return;
4809 			for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
4810 				vdev_dtl_dirty(pvd, DTL_PARTIAL, txg, 1);
4811 			vdev_dirty(vd->vdev_top, VDD_DTL, vd, commit_txg);
4812 		}
4813 		if (vd != rvd)
4814 			vdev_dtl_dirty(vd, DTL_MISSING, txg, 1);
4815 	}
4816 }
4817 
4818 int64_t
4819 vdev_deflated_space(vdev_t *vd, int64_t space)
4820 {
4821 	ASSERT((space & (SPA_MINBLOCKSIZE-1)) == 0);
4822 	ASSERT(vd->vdev_deflate_ratio != 0 || vd->vdev_isl2cache);
4823 
4824 	return ((space >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio);
4825 }
4826 
4827 /*
4828  * Update the in-core space usage stats for this vdev, its metaslab class,
4829  * and the root vdev.
4830  */
4831 void
4832 vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
4833     int64_t space_delta)
4834 {
4835 	(void) defer_delta;
4836 	int64_t dspace_delta;
4837 	spa_t *spa = vd->vdev_spa;
4838 	vdev_t *rvd = spa->spa_root_vdev;
4839 
4840 	ASSERT(vd == vd->vdev_top);
4841 
4842 	/*
4843 	 * Apply the inverse of the psize-to-asize (ie. RAID-Z) space-expansion
4844 	 * factor.  We must calculate this here and not at the root vdev
4845 	 * because the root vdev's psize-to-asize is simply the max of its
4846 	 * children's, thus not accurate enough for us.
4847 	 */
4848 	dspace_delta = vdev_deflated_space(vd, space_delta);
4849 
4850 	mutex_enter(&vd->vdev_stat_lock);
4851 	/* ensure we won't underflow */
4852 	if (alloc_delta < 0) {
4853 		ASSERT3U(vd->vdev_stat.vs_alloc, >=, -alloc_delta);
4854 	}
4855 
4856 	vd->vdev_stat.vs_alloc += alloc_delta;
4857 	vd->vdev_stat.vs_space += space_delta;
4858 	vd->vdev_stat.vs_dspace += dspace_delta;
4859 	mutex_exit(&vd->vdev_stat_lock);
4860 
4861 	/* every class but log contributes to root space stats */
4862 	if (vd->vdev_mg != NULL && !vd->vdev_islog) {
4863 		ASSERT(!vd->vdev_isl2cache);
4864 		mutex_enter(&rvd->vdev_stat_lock);
4865 		rvd->vdev_stat.vs_alloc += alloc_delta;
4866 		rvd->vdev_stat.vs_space += space_delta;
4867 		rvd->vdev_stat.vs_dspace += dspace_delta;
4868 		mutex_exit(&rvd->vdev_stat_lock);
4869 	}
4870 	/* Note: metaslab_class_space_update moved to metaslab_space_update */
4871 }
4872 
4873 /*
4874  * Mark a top-level vdev's config as dirty, placing it on the dirty list
4875  * so that it will be written out next time the vdev configuration is synced.
4876  * If the root vdev is specified (vdev_top == NULL), dirty all top-level vdevs.
4877  */
4878 void
4879 vdev_config_dirty(vdev_t *vd)
4880 {
4881 	spa_t *spa = vd->vdev_spa;
4882 	vdev_t *rvd = spa->spa_root_vdev;
4883 	int c;
4884 
4885 	ASSERT(spa_writeable(spa));
4886 
4887 	/*
4888 	 * If this is an aux vdev (as with l2cache and spare devices), then we
4889 	 * update the vdev config manually and set the sync flag.
4890 	 */
4891 	if (vd->vdev_aux != NULL) {
4892 		spa_aux_vdev_t *sav = vd->vdev_aux;
4893 		nvlist_t **aux;
4894 		uint_t naux;
4895 
4896 		for (c = 0; c < sav->sav_count; c++) {
4897 			if (sav->sav_vdevs[c] == vd)
4898 				break;
4899 		}
4900 
4901 		if (c == sav->sav_count) {
4902 			/*
4903 			 * We're being removed.  There's nothing more to do.
4904 			 */
4905 			ASSERT(sav->sav_sync == B_TRUE);
4906 			return;
4907 		}
4908 
4909 		sav->sav_sync = B_TRUE;
4910 
4911 		if (nvlist_lookup_nvlist_array(sav->sav_config,
4912 		    ZPOOL_CONFIG_L2CACHE, &aux, &naux) != 0) {
4913 			VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
4914 			    ZPOOL_CONFIG_SPARES, &aux, &naux) == 0);
4915 		}
4916 
4917 		ASSERT(c < naux);
4918 
4919 		/*
4920 		 * Setting the nvlist in the middle if the array is a little
4921 		 * sketchy, but it will work.
4922 		 */
4923 		nvlist_free(aux[c]);
4924 		aux[c] = vdev_config_generate(spa, vd, B_TRUE, 0);
4925 
4926 		return;
4927 	}
4928 
4929 	/*
4930 	 * The dirty list is protected by the SCL_CONFIG lock.  The caller
4931 	 * must either hold SCL_CONFIG as writer, or must be the sync thread
4932 	 * (which holds SCL_CONFIG as reader).  There's only one sync thread,
4933 	 * so this is sufficient to ensure mutual exclusion.
4934 	 */
4935 	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
4936 	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
4937 	    spa_config_held(spa, SCL_CONFIG, RW_READER)));
4938 
4939 	if (vd == rvd) {
4940 		for (c = 0; c < rvd->vdev_children; c++)
4941 			vdev_config_dirty(rvd->vdev_child[c]);
4942 	} else {
4943 		ASSERT(vd == vd->vdev_top);
4944 
4945 		if (!list_link_active(&vd->vdev_config_dirty_node) &&
4946 		    vdev_is_concrete(vd)) {
4947 			list_insert_head(&spa->spa_config_dirty_list, vd);
4948 		}
4949 	}
4950 }
4951 
4952 void
4953 vdev_config_clean(vdev_t *vd)
4954 {
4955 	spa_t *spa = vd->vdev_spa;
4956 
4957 	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
4958 	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
4959 	    spa_config_held(spa, SCL_CONFIG, RW_READER)));
4960 
4961 	ASSERT(list_link_active(&vd->vdev_config_dirty_node));
4962 	list_remove(&spa->spa_config_dirty_list, vd);
4963 }
4964 
4965 /*
4966  * Mark a top-level vdev's state as dirty, so that the next pass of
4967  * spa_sync() can convert this into vdev_config_dirty().  We distinguish
4968  * the state changes from larger config changes because they require
4969  * much less locking, and are often needed for administrative actions.
4970  */
4971 void
4972 vdev_state_dirty(vdev_t *vd)
4973 {
4974 	spa_t *spa = vd->vdev_spa;
4975 
4976 	ASSERT(spa_writeable(spa));
4977 	ASSERT(vd == vd->vdev_top);
4978 
4979 	/*
4980 	 * The state list is protected by the SCL_STATE lock.  The caller
4981 	 * must either hold SCL_STATE as writer, or must be the sync thread
4982 	 * (which holds SCL_STATE as reader).  There's only one sync thread,
4983 	 * so this is sufficient to ensure mutual exclusion.
4984 	 */
4985 	ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
4986 	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
4987 	    spa_config_held(spa, SCL_STATE, RW_READER)));
4988 
4989 	if (!list_link_active(&vd->vdev_state_dirty_node) &&
4990 	    vdev_is_concrete(vd))
4991 		list_insert_head(&spa->spa_state_dirty_list, vd);
4992 }
4993 
4994 void
4995 vdev_state_clean(vdev_t *vd)
4996 {
4997 	spa_t *spa = vd->vdev_spa;
4998 
4999 	ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
5000 	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
5001 	    spa_config_held(spa, SCL_STATE, RW_READER)));
5002 
5003 	ASSERT(list_link_active(&vd->vdev_state_dirty_node));
5004 	list_remove(&spa->spa_state_dirty_list, vd);
5005 }
5006 
5007 /*
5008  * Propagate vdev state up from children to parent.
5009  */
5010 void
5011 vdev_propagate_state(vdev_t *vd)
5012 {
5013 	spa_t *spa = vd->vdev_spa;
5014 	vdev_t *rvd = spa->spa_root_vdev;
5015 	int degraded = 0, faulted = 0;
5016 	int corrupted = 0;
5017 	vdev_t *child;
5018 
5019 	if (vd->vdev_children > 0) {
5020 		for (int c = 0; c < vd->vdev_children; c++) {
5021 			child = vd->vdev_child[c];
5022 
5023 			/*
5024 			 * Don't factor holes or indirect vdevs into the
5025 			 * decision.
5026 			 */
5027 			if (!vdev_is_concrete(child))
5028 				continue;
5029 
5030 			if (!vdev_readable(child) ||
5031 			    (!vdev_writeable(child) && spa_writeable(spa))) {
5032 				/*
5033 				 * Root special: if there is a top-level log
5034 				 * device, treat the root vdev as if it were
5035 				 * degraded.
5036 				 */
5037 				if (child->vdev_islog && vd == rvd)
5038 					degraded++;
5039 				else
5040 					faulted++;
5041 			} else if (child->vdev_state <= VDEV_STATE_DEGRADED) {
5042 				degraded++;
5043 			}
5044 
5045 			if (child->vdev_stat.vs_aux == VDEV_AUX_CORRUPT_DATA)
5046 				corrupted++;
5047 		}
5048 
5049 		vd->vdev_ops->vdev_op_state_change(vd, faulted, degraded);
5050 
5051 		/*
5052 		 * Root special: if there is a top-level vdev that cannot be
5053 		 * opened due to corrupted metadata, then propagate the root
5054 		 * vdev's aux state as 'corrupt' rather than 'insufficient
5055 		 * replicas'.
5056 		 */
5057 		if (corrupted && vd == rvd &&
5058 		    rvd->vdev_state == VDEV_STATE_CANT_OPEN)
5059 			vdev_set_state(rvd, B_FALSE, VDEV_STATE_CANT_OPEN,
5060 			    VDEV_AUX_CORRUPT_DATA);
5061 	}
5062 
5063 	if (vd->vdev_parent)
5064 		vdev_propagate_state(vd->vdev_parent);
5065 }
5066 
5067 /*
5068  * Set a vdev's state.  If this is during an open, we don't update the parent
5069  * state, because we're in the process of opening children depth-first.
5070  * Otherwise, we propagate the change to the parent.
5071  *
5072  * If this routine places a device in a faulted state, an appropriate ereport is
5073  * generated.
5074  */
5075 void
5076 vdev_set_state(vdev_t *vd, boolean_t isopen, vdev_state_t state, vdev_aux_t aux)
5077 {
5078 	uint64_t save_state;
5079 	spa_t *spa = vd->vdev_spa;
5080 
5081 	if (state == vd->vdev_state) {
5082 		/*
5083 		 * Since vdev_offline() code path is already in an offline
5084 		 * state we can miss a statechange event to OFFLINE. Check
5085 		 * the previous state to catch this condition.
5086 		 */
5087 		if (vd->vdev_ops->vdev_op_leaf &&
5088 		    (state == VDEV_STATE_OFFLINE) &&
5089 		    (vd->vdev_prevstate >= VDEV_STATE_FAULTED)) {
5090 			/* post an offline state change */
5091 			zfs_post_state_change(spa, vd, vd->vdev_prevstate);
5092 		}
5093 		vd->vdev_stat.vs_aux = aux;
5094 		return;
5095 	}
5096 
5097 	save_state = vd->vdev_state;
5098 
5099 	vd->vdev_state = state;
5100 	vd->vdev_stat.vs_aux = aux;
5101 
5102 	/*
5103 	 * If we are setting the vdev state to anything but an open state, then
5104 	 * always close the underlying device unless the device has requested
5105 	 * a delayed close (i.e. we're about to remove or fault the device).
5106 	 * Otherwise, we keep accessible but invalid devices open forever.
5107 	 * We don't call vdev_close() itself, because that implies some extra
5108 	 * checks (offline, etc) that we don't want here.  This is limited to
5109 	 * leaf devices, because otherwise closing the device will affect other
5110 	 * children.
5111 	 */
5112 	if (!vd->vdev_delayed_close && vdev_is_dead(vd) &&
5113 	    vd->vdev_ops->vdev_op_leaf)
5114 		vd->vdev_ops->vdev_op_close(vd);
5115 
5116 	if (vd->vdev_removed &&
5117 	    state == VDEV_STATE_CANT_OPEN &&
5118 	    (aux == VDEV_AUX_OPEN_FAILED || vd->vdev_checkremove)) {
5119 		/*
5120 		 * If the previous state is set to VDEV_STATE_REMOVED, then this
5121 		 * device was previously marked removed and someone attempted to
5122 		 * reopen it.  If this failed due to a nonexistent device, then
5123 		 * keep the device in the REMOVED state.  We also let this be if
5124 		 * it is one of our special test online cases, which is only
5125 		 * attempting to online the device and shouldn't generate an FMA
5126 		 * fault.
5127 		 */
5128 		vd->vdev_state = VDEV_STATE_REMOVED;
5129 		vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
5130 	} else if (state == VDEV_STATE_REMOVED) {
5131 		vd->vdev_removed = B_TRUE;
5132 	} else if (state == VDEV_STATE_CANT_OPEN) {
5133 		/*
5134 		 * If we fail to open a vdev during an import or recovery, we
5135 		 * mark it as "not available", which signifies that it was
5136 		 * never there to begin with.  Failure to open such a device
5137 		 * is not considered an error.
5138 		 */
5139 		if ((spa_load_state(spa) == SPA_LOAD_IMPORT ||
5140 		    spa_load_state(spa) == SPA_LOAD_RECOVER) &&
5141 		    vd->vdev_ops->vdev_op_leaf)
5142 			vd->vdev_not_present = 1;
5143 
5144 		/*
5145 		 * Post the appropriate ereport.  If the 'prevstate' field is
5146 		 * set to something other than VDEV_STATE_UNKNOWN, it indicates
5147 		 * that this is part of a vdev_reopen().  In this case, we don't
5148 		 * want to post the ereport if the device was already in the
5149 		 * CANT_OPEN state beforehand.
5150 		 *
5151 		 * If the 'checkremove' flag is set, then this is an attempt to
5152 		 * online the device in response to an insertion event.  If we
5153 		 * hit this case, then we have detected an insertion event for a
5154 		 * faulted or offline device that wasn't in the removed state.
5155 		 * In this scenario, we don't post an ereport because we are
5156 		 * about to replace the device, or attempt an online with
5157 		 * vdev_forcefault, which will generate the fault for us.
5158 		 */
5159 		if ((vd->vdev_prevstate != state || vd->vdev_forcefault) &&
5160 		    !vd->vdev_not_present && !vd->vdev_checkremove &&
5161 		    vd != spa->spa_root_vdev) {
5162 			const char *class;
5163 
5164 			switch (aux) {
5165 			case VDEV_AUX_OPEN_FAILED:
5166 				class = FM_EREPORT_ZFS_DEVICE_OPEN_FAILED;
5167 				break;
5168 			case VDEV_AUX_CORRUPT_DATA:
5169 				class = FM_EREPORT_ZFS_DEVICE_CORRUPT_DATA;
5170 				break;
5171 			case VDEV_AUX_NO_REPLICAS:
5172 				class = FM_EREPORT_ZFS_DEVICE_NO_REPLICAS;
5173 				break;
5174 			case VDEV_AUX_BAD_GUID_SUM:
5175 				class = FM_EREPORT_ZFS_DEVICE_BAD_GUID_SUM;
5176 				break;
5177 			case VDEV_AUX_TOO_SMALL:
5178 				class = FM_EREPORT_ZFS_DEVICE_TOO_SMALL;
5179 				break;
5180 			case VDEV_AUX_BAD_LABEL:
5181 				class = FM_EREPORT_ZFS_DEVICE_BAD_LABEL;
5182 				break;
5183 			case VDEV_AUX_BAD_ASHIFT:
5184 				class = FM_EREPORT_ZFS_DEVICE_BAD_ASHIFT;
5185 				break;
5186 			default:
5187 				class = FM_EREPORT_ZFS_DEVICE_UNKNOWN;
5188 			}
5189 
5190 			(void) zfs_ereport_post(class, spa, vd, NULL, NULL,
5191 			    save_state);
5192 		}
5193 
5194 		/* Erase any notion of persistent removed state */
5195 		vd->vdev_removed = B_FALSE;
5196 	} else {
5197 		vd->vdev_removed = B_FALSE;
5198 	}
5199 
5200 	/*
5201 	 * Notify ZED of any significant state-change on a leaf vdev.
5202 	 *
5203 	 */
5204 	if (vd->vdev_ops->vdev_op_leaf) {
5205 		/* preserve original state from a vdev_reopen() */
5206 		if ((vd->vdev_prevstate != VDEV_STATE_UNKNOWN) &&
5207 		    (vd->vdev_prevstate != vd->vdev_state) &&
5208 		    (save_state <= VDEV_STATE_CLOSED))
5209 			save_state = vd->vdev_prevstate;
5210 
5211 		/* filter out state change due to initial vdev_open */
5212 		if (save_state > VDEV_STATE_CLOSED)
5213 			zfs_post_state_change(spa, vd, save_state);
5214 	}
5215 
5216 	if (!isopen && vd->vdev_parent)
5217 		vdev_propagate_state(vd->vdev_parent);
5218 }
5219 
5220 boolean_t
5221 vdev_children_are_offline(vdev_t *vd)
5222 {
5223 	ASSERT(!vd->vdev_ops->vdev_op_leaf);
5224 
5225 	for (uint64_t i = 0; i < vd->vdev_children; i++) {
5226 		if (vd->vdev_child[i]->vdev_state != VDEV_STATE_OFFLINE)
5227 			return (B_FALSE);
5228 	}
5229 
5230 	return (B_TRUE);
5231 }
5232 
5233 /*
5234  * Check the vdev configuration to ensure that it's capable of supporting
5235  * a root pool. We do not support partial configuration.
5236  */
5237 boolean_t
5238 vdev_is_bootable(vdev_t *vd)
5239 {
5240 	if (!vd->vdev_ops->vdev_op_leaf) {
5241 		const char *vdev_type = vd->vdev_ops->vdev_op_type;
5242 
5243 		if (strcmp(vdev_type, VDEV_TYPE_MISSING) == 0)
5244 			return (B_FALSE);
5245 	}
5246 
5247 	for (int c = 0; c < vd->vdev_children; c++) {
5248 		if (!vdev_is_bootable(vd->vdev_child[c]))
5249 			return (B_FALSE);
5250 	}
5251 	return (B_TRUE);
5252 }
5253 
5254 boolean_t
5255 vdev_is_concrete(vdev_t *vd)
5256 {
5257 	vdev_ops_t *ops = vd->vdev_ops;
5258 	if (ops == &vdev_indirect_ops || ops == &vdev_hole_ops ||
5259 	    ops == &vdev_missing_ops || ops == &vdev_root_ops) {
5260 		return (B_FALSE);
5261 	} else {
5262 		return (B_TRUE);
5263 	}
5264 }
5265 
5266 /*
5267  * Determine if a log device has valid content.  If the vdev was
5268  * removed or faulted in the MOS config then we know that
5269  * the content on the log device has already been written to the pool.
5270  */
5271 boolean_t
5272 vdev_log_state_valid(vdev_t *vd)
5273 {
5274 	if (vd->vdev_ops->vdev_op_leaf && !vd->vdev_faulted &&
5275 	    !vd->vdev_removed)
5276 		return (B_TRUE);
5277 
5278 	for (int c = 0; c < vd->vdev_children; c++)
5279 		if (vdev_log_state_valid(vd->vdev_child[c]))
5280 			return (B_TRUE);
5281 
5282 	return (B_FALSE);
5283 }
5284 
5285 /*
5286  * Expand a vdev if possible.
5287  */
5288 void
5289 vdev_expand(vdev_t *vd, uint64_t txg)
5290 {
5291 	ASSERT(vd->vdev_top == vd);
5292 	ASSERT(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5293 	ASSERT(vdev_is_concrete(vd));
5294 
5295 	vdev_set_deflate_ratio(vd);
5296 
5297 	if ((vd->vdev_asize >> vd->vdev_ms_shift) > vd->vdev_ms_count &&
5298 	    vdev_is_concrete(vd)) {
5299 		vdev_metaslab_group_create(vd);
5300 		VERIFY(vdev_metaslab_init(vd, txg) == 0);
5301 		vdev_config_dirty(vd);
5302 	}
5303 }
5304 
5305 /*
5306  * Split a vdev.
5307  */
5308 void
5309 vdev_split(vdev_t *vd)
5310 {
5311 	vdev_t *cvd, *pvd = vd->vdev_parent;
5312 
5313 	vdev_remove_child(pvd, vd);
5314 	vdev_compact_children(pvd);
5315 
5316 	cvd = pvd->vdev_child[0];
5317 	if (pvd->vdev_children == 1) {
5318 		vdev_remove_parent(cvd);
5319 		cvd->vdev_splitting = B_TRUE;
5320 	}
5321 	vdev_propagate_state(cvd);
5322 }
5323 
5324 void
5325 vdev_deadman(vdev_t *vd, const char *tag)
5326 {
5327 	for (int c = 0; c < vd->vdev_children; c++) {
5328 		vdev_t *cvd = vd->vdev_child[c];
5329 
5330 		vdev_deadman(cvd, tag);
5331 	}
5332 
5333 	if (vd->vdev_ops->vdev_op_leaf) {
5334 		vdev_queue_t *vq = &vd->vdev_queue;
5335 
5336 		mutex_enter(&vq->vq_lock);
5337 		if (avl_numnodes(&vq->vq_active_tree) > 0) {
5338 			spa_t *spa = vd->vdev_spa;
5339 			zio_t *fio;
5340 			uint64_t delta;
5341 
5342 			zfs_dbgmsg("slow vdev: %s has %lu active IOs",
5343 			    vd->vdev_path, avl_numnodes(&vq->vq_active_tree));
5344 
5345 			/*
5346 			 * Look at the head of all the pending queues,
5347 			 * if any I/O has been outstanding for longer than
5348 			 * the spa_deadman_synctime invoke the deadman logic.
5349 			 */
5350 			fio = avl_first(&vq->vq_active_tree);
5351 			delta = gethrtime() - fio->io_timestamp;
5352 			if (delta > spa_deadman_synctime(spa))
5353 				zio_deadman(fio, tag);
5354 		}
5355 		mutex_exit(&vq->vq_lock);
5356 	}
5357 }
5358 
5359 void
5360 vdev_defer_resilver(vdev_t *vd)
5361 {
5362 	ASSERT(vd->vdev_ops->vdev_op_leaf);
5363 
5364 	vd->vdev_resilver_deferred = B_TRUE;
5365 	vd->vdev_spa->spa_resilver_deferred = B_TRUE;
5366 }
5367 
5368 /*
5369  * Clears the resilver deferred flag on all leaf devs under vd. Returns
5370  * B_TRUE if we have devices that need to be resilvered and are available to
5371  * accept resilver I/Os.
5372  */
5373 boolean_t
5374 vdev_clear_resilver_deferred(vdev_t *vd, dmu_tx_t *tx)
5375 {
5376 	boolean_t resilver_needed = B_FALSE;
5377 	spa_t *spa = vd->vdev_spa;
5378 
5379 	for (int c = 0; c < vd->vdev_children; c++) {
5380 		vdev_t *cvd = vd->vdev_child[c];
5381 		resilver_needed |= vdev_clear_resilver_deferred(cvd, tx);
5382 	}
5383 
5384 	if (vd == spa->spa_root_vdev &&
5385 	    spa_feature_is_active(spa, SPA_FEATURE_RESILVER_DEFER)) {
5386 		spa_feature_decr(spa, SPA_FEATURE_RESILVER_DEFER, tx);
5387 		vdev_config_dirty(vd);
5388 		spa->spa_resilver_deferred = B_FALSE;
5389 		return (resilver_needed);
5390 	}
5391 
5392 	if (!vdev_is_concrete(vd) || vd->vdev_aux ||
5393 	    !vd->vdev_ops->vdev_op_leaf)
5394 		return (resilver_needed);
5395 
5396 	vd->vdev_resilver_deferred = B_FALSE;
5397 
5398 	return (!vdev_is_dead(vd) && !vd->vdev_offline &&
5399 	    vdev_resilver_needed(vd, NULL, NULL));
5400 }
5401 
5402 boolean_t
5403 vdev_xlate_is_empty(range_seg64_t *rs)
5404 {
5405 	return (rs->rs_start == rs->rs_end);
5406 }
5407 
5408 /*
5409  * Translate a logical range to the first contiguous physical range for the
5410  * specified vdev_t.  This function is initially called with a leaf vdev and
5411  * will walk each parent vdev until it reaches a top-level vdev. Once the
5412  * top-level is reached the physical range is initialized and the recursive
5413  * function begins to unwind. As it unwinds it calls the parent's vdev
5414  * specific translation function to do the real conversion.
5415  */
5416 void
5417 vdev_xlate(vdev_t *vd, const range_seg64_t *logical_rs,
5418     range_seg64_t *physical_rs, range_seg64_t *remain_rs)
5419 {
5420 	/*
5421 	 * Walk up the vdev tree
5422 	 */
5423 	if (vd != vd->vdev_top) {
5424 		vdev_xlate(vd->vdev_parent, logical_rs, physical_rs,
5425 		    remain_rs);
5426 	} else {
5427 		/*
5428 		 * We've reached the top-level vdev, initialize the physical
5429 		 * range to the logical range and set an empty remaining
5430 		 * range then start to unwind.
5431 		 */
5432 		physical_rs->rs_start = logical_rs->rs_start;
5433 		physical_rs->rs_end = logical_rs->rs_end;
5434 
5435 		remain_rs->rs_start = logical_rs->rs_start;
5436 		remain_rs->rs_end = logical_rs->rs_start;
5437 
5438 		return;
5439 	}
5440 
5441 	vdev_t *pvd = vd->vdev_parent;
5442 	ASSERT3P(pvd, !=, NULL);
5443 	ASSERT3P(pvd->vdev_ops->vdev_op_xlate, !=, NULL);
5444 
5445 	/*
5446 	 * As this recursive function unwinds, translate the logical
5447 	 * range into its physical and any remaining components by calling
5448 	 * the vdev specific translate function.
5449 	 */
5450 	range_seg64_t intermediate = { 0 };
5451 	pvd->vdev_ops->vdev_op_xlate(vd, physical_rs, &intermediate, remain_rs);
5452 
5453 	physical_rs->rs_start = intermediate.rs_start;
5454 	physical_rs->rs_end = intermediate.rs_end;
5455 }
5456 
5457 void
5458 vdev_xlate_walk(vdev_t *vd, const range_seg64_t *logical_rs,
5459     vdev_xlate_func_t *func, void *arg)
5460 {
5461 	range_seg64_t iter_rs = *logical_rs;
5462 	range_seg64_t physical_rs;
5463 	range_seg64_t remain_rs;
5464 
5465 	while (!vdev_xlate_is_empty(&iter_rs)) {
5466 
5467 		vdev_xlate(vd, &iter_rs, &physical_rs, &remain_rs);
5468 
5469 		/*
5470 		 * With raidz and dRAID, it's possible that the logical range
5471 		 * does not live on this leaf vdev. Only when there is a non-
5472 		 * zero physical size call the provided function.
5473 		 */
5474 		if (!vdev_xlate_is_empty(&physical_rs))
5475 			func(arg, &physical_rs);
5476 
5477 		iter_rs = remain_rs;
5478 	}
5479 }
5480 
5481 static char *
5482 vdev_name(vdev_t *vd, char *buf, int buflen)
5483 {
5484 	if (vd->vdev_path == NULL) {
5485 		if (strcmp(vd->vdev_ops->vdev_op_type, "root") == 0) {
5486 			strlcpy(buf, vd->vdev_spa->spa_name, buflen);
5487 		} else if (!vd->vdev_ops->vdev_op_leaf) {
5488 			snprintf(buf, buflen, "%s-%llu",
5489 			    vd->vdev_ops->vdev_op_type,
5490 			    (u_longlong_t)vd->vdev_id);
5491 		}
5492 	} else {
5493 		strlcpy(buf, vd->vdev_path, buflen);
5494 	}
5495 	return (buf);
5496 }
5497 
5498 /*
5499  * Look at the vdev tree and determine whether any devices are currently being
5500  * replaced.
5501  */
5502 boolean_t
5503 vdev_replace_in_progress(vdev_t *vdev)
5504 {
5505 	ASSERT(spa_config_held(vdev->vdev_spa, SCL_ALL, RW_READER) != 0);
5506 
5507 	if (vdev->vdev_ops == &vdev_replacing_ops)
5508 		return (B_TRUE);
5509 
5510 	/*
5511 	 * A 'spare' vdev indicates that we have a replace in progress, unless
5512 	 * it has exactly two children, and the second, the hot spare, has
5513 	 * finished being resilvered.
5514 	 */
5515 	if (vdev->vdev_ops == &vdev_spare_ops && (vdev->vdev_children > 2 ||
5516 	    !vdev_dtl_empty(vdev->vdev_child[1], DTL_MISSING)))
5517 		return (B_TRUE);
5518 
5519 	for (int i = 0; i < vdev->vdev_children; i++) {
5520 		if (vdev_replace_in_progress(vdev->vdev_child[i]))
5521 			return (B_TRUE);
5522 	}
5523 
5524 	return (B_FALSE);
5525 }
5526 
5527 /*
5528  * Add a (source=src, propname=propval) list to an nvlist.
5529  */
5530 static void
5531 vdev_prop_add_list(nvlist_t *nvl, const char *propname, char *strval,
5532     uint64_t intval, zprop_source_t src)
5533 {
5534 	nvlist_t *propval;
5535 
5536 	propval = fnvlist_alloc();
5537 	fnvlist_add_uint64(propval, ZPROP_SOURCE, src);
5538 
5539 	if (strval != NULL)
5540 		fnvlist_add_string(propval, ZPROP_VALUE, strval);
5541 	else
5542 		fnvlist_add_uint64(propval, ZPROP_VALUE, intval);
5543 
5544 	fnvlist_add_nvlist(nvl, propname, propval);
5545 	nvlist_free(propval);
5546 }
5547 
5548 static void
5549 vdev_props_set_sync(void *arg, dmu_tx_t *tx)
5550 {
5551 	vdev_t *vd;
5552 	nvlist_t *nvp = arg;
5553 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
5554 	objset_t *mos = spa->spa_meta_objset;
5555 	nvpair_t *elem = NULL;
5556 	uint64_t vdev_guid;
5557 	nvlist_t *nvprops;
5558 
5559 	vdev_guid = fnvlist_lookup_uint64(nvp, ZPOOL_VDEV_PROPS_SET_VDEV);
5560 	nvprops = fnvlist_lookup_nvlist(nvp, ZPOOL_VDEV_PROPS_SET_PROPS);
5561 	vd = spa_lookup_by_guid(spa, vdev_guid, B_TRUE);
5562 
5563 	/* this vdev could get removed while waiting for this sync task */
5564 	if (vd == NULL)
5565 		return;
5566 
5567 	mutex_enter(&spa->spa_props_lock);
5568 
5569 	while ((elem = nvlist_next_nvpair(nvprops, elem)) != NULL) {
5570 		uint64_t intval, objid = 0;
5571 		char *strval;
5572 		vdev_prop_t prop;
5573 		const char *propname = nvpair_name(elem);
5574 		zprop_type_t proptype;
5575 
5576 		/*
5577 		 * Set vdev property values in the vdev props mos object.
5578 		 */
5579 		if (vd->vdev_top_zap != 0) {
5580 			objid = vd->vdev_top_zap;
5581 		} else if (vd->vdev_leaf_zap != 0) {
5582 			objid = vd->vdev_leaf_zap;
5583 		} else {
5584 			panic("vdev not top or leaf");
5585 		}
5586 
5587 		switch (prop = vdev_name_to_prop(propname)) {
5588 		case VDEV_PROP_USERPROP:
5589 			if (vdev_prop_user(propname)) {
5590 				strval = fnvpair_value_string(elem);
5591 				if (strlen(strval) == 0) {
5592 					/* remove the property if value == "" */
5593 					(void) zap_remove(mos, objid, propname,
5594 					    tx);
5595 				} else {
5596 					VERIFY0(zap_update(mos, objid, propname,
5597 					    1, strlen(strval) + 1, strval, tx));
5598 				}
5599 				spa_history_log_internal(spa, "vdev set", tx,
5600 				    "vdev_guid=%llu: %s=%s",
5601 				    (u_longlong_t)vdev_guid, nvpair_name(elem),
5602 				    strval);
5603 			}
5604 			break;
5605 		default:
5606 			/* normalize the property name */
5607 			propname = vdev_prop_to_name(prop);
5608 			proptype = vdev_prop_get_type(prop);
5609 
5610 			if (nvpair_type(elem) == DATA_TYPE_STRING) {
5611 				ASSERT(proptype == PROP_TYPE_STRING);
5612 				strval = fnvpair_value_string(elem);
5613 				VERIFY0(zap_update(mos, objid, propname,
5614 				    1, strlen(strval) + 1, strval, tx));
5615 				spa_history_log_internal(spa, "vdev set", tx,
5616 				    "vdev_guid=%llu: %s=%s",
5617 				    (u_longlong_t)vdev_guid, nvpair_name(elem),
5618 				    strval);
5619 			} else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
5620 				intval = fnvpair_value_uint64(elem);
5621 
5622 				if (proptype == PROP_TYPE_INDEX) {
5623 					const char *unused;
5624 					VERIFY0(vdev_prop_index_to_string(
5625 					    prop, intval, &unused));
5626 				}
5627 				VERIFY0(zap_update(mos, objid, propname,
5628 				    sizeof (uint64_t), 1, &intval, tx));
5629 				spa_history_log_internal(spa, "vdev set", tx,
5630 				    "vdev_guid=%llu: %s=%lld",
5631 				    (u_longlong_t)vdev_guid,
5632 				    nvpair_name(elem), (longlong_t)intval);
5633 			} else {
5634 				panic("invalid vdev property type %u",
5635 				    nvpair_type(elem));
5636 			}
5637 		}
5638 
5639 	}
5640 
5641 	mutex_exit(&spa->spa_props_lock);
5642 }
5643 
5644 int
5645 vdev_prop_set(vdev_t *vd, nvlist_t *innvl, nvlist_t *outnvl)
5646 {
5647 	spa_t *spa = vd->vdev_spa;
5648 	nvpair_t *elem = NULL;
5649 	uint64_t vdev_guid;
5650 	nvlist_t *nvprops;
5651 	int error;
5652 
5653 	ASSERT(vd != NULL);
5654 
5655 	if (nvlist_lookup_uint64(innvl, ZPOOL_VDEV_PROPS_SET_VDEV,
5656 	    &vdev_guid) != 0)
5657 		return (SET_ERROR(EINVAL));
5658 
5659 	if (nvlist_lookup_nvlist(innvl, ZPOOL_VDEV_PROPS_SET_PROPS,
5660 	    &nvprops) != 0)
5661 		return (SET_ERROR(EINVAL));
5662 
5663 	if ((vd = spa_lookup_by_guid(spa, vdev_guid, B_TRUE)) == NULL)
5664 		return (SET_ERROR(EINVAL));
5665 
5666 	while ((elem = nvlist_next_nvpair(nvprops, elem)) != NULL) {
5667 		char *propname = nvpair_name(elem);
5668 		vdev_prop_t prop = vdev_name_to_prop(propname);
5669 		uint64_t intval = 0;
5670 		char *strval = NULL;
5671 
5672 		if (prop == VDEV_PROP_USERPROP && !vdev_prop_user(propname)) {
5673 			error = EINVAL;
5674 			goto end;
5675 		}
5676 
5677 		if (vdev_prop_readonly(prop)) {
5678 			error = EROFS;
5679 			goto end;
5680 		}
5681 
5682 		/* Special Processing */
5683 		switch (prop) {
5684 		case VDEV_PROP_PATH:
5685 			if (vd->vdev_path == NULL) {
5686 				error = EROFS;
5687 				break;
5688 			}
5689 			if (nvpair_value_string(elem, &strval) != 0) {
5690 				error = EINVAL;
5691 				break;
5692 			}
5693 			/* New path must start with /dev/ */
5694 			if (strncmp(strval, "/dev/", 5)) {
5695 				error = EINVAL;
5696 				break;
5697 			}
5698 			error = spa_vdev_setpath(spa, vdev_guid, strval);
5699 			break;
5700 		case VDEV_PROP_ALLOCATING:
5701 			if (nvpair_value_uint64(elem, &intval) != 0) {
5702 				error = EINVAL;
5703 				break;
5704 			}
5705 			if (intval != vd->vdev_noalloc)
5706 				break;
5707 			if (intval == 0)
5708 				error = spa_vdev_noalloc(spa, vdev_guid);
5709 			else
5710 				error = spa_vdev_alloc(spa, vdev_guid);
5711 			break;
5712 		default:
5713 			/* Most processing is done in vdev_props_set_sync */
5714 			break;
5715 		}
5716 end:
5717 		if (error != 0) {
5718 			intval = error;
5719 			vdev_prop_add_list(outnvl, propname, strval, intval, 0);
5720 			return (error);
5721 		}
5722 	}
5723 
5724 	return (dsl_sync_task(spa->spa_name, NULL, vdev_props_set_sync,
5725 	    innvl, 6, ZFS_SPACE_CHECK_EXTRA_RESERVED));
5726 }
5727 
5728 int
5729 vdev_prop_get(vdev_t *vd, nvlist_t *innvl, nvlist_t *outnvl)
5730 {
5731 	spa_t *spa = vd->vdev_spa;
5732 	objset_t *mos = spa->spa_meta_objset;
5733 	int err = 0;
5734 	uint64_t objid;
5735 	uint64_t vdev_guid;
5736 	nvpair_t *elem = NULL;
5737 	nvlist_t *nvprops = NULL;
5738 	uint64_t intval = 0;
5739 	char *strval = NULL;
5740 	const char *propname = NULL;
5741 	vdev_prop_t prop;
5742 
5743 	ASSERT(vd != NULL);
5744 	ASSERT(mos != NULL);
5745 
5746 	if (nvlist_lookup_uint64(innvl, ZPOOL_VDEV_PROPS_GET_VDEV,
5747 	    &vdev_guid) != 0)
5748 		return (SET_ERROR(EINVAL));
5749 
5750 	nvlist_lookup_nvlist(innvl, ZPOOL_VDEV_PROPS_GET_PROPS, &nvprops);
5751 
5752 	if (vd->vdev_top_zap != 0) {
5753 		objid = vd->vdev_top_zap;
5754 	} else if (vd->vdev_leaf_zap != 0) {
5755 		objid = vd->vdev_leaf_zap;
5756 	} else {
5757 		return (SET_ERROR(EINVAL));
5758 	}
5759 	ASSERT(objid != 0);
5760 
5761 	mutex_enter(&spa->spa_props_lock);
5762 
5763 	if (nvprops != NULL) {
5764 		char namebuf[64] = { 0 };
5765 
5766 		while ((elem = nvlist_next_nvpair(nvprops, elem)) != NULL) {
5767 			intval = 0;
5768 			strval = NULL;
5769 			propname = nvpair_name(elem);
5770 			prop = vdev_name_to_prop(propname);
5771 			zprop_source_t src = ZPROP_SRC_DEFAULT;
5772 			uint64_t integer_size, num_integers;
5773 
5774 			switch (prop) {
5775 			/* Special Read-only Properties */
5776 			case VDEV_PROP_NAME:
5777 				strval = vdev_name(vd, namebuf,
5778 				    sizeof (namebuf));
5779 				if (strval == NULL)
5780 					continue;
5781 				vdev_prop_add_list(outnvl, propname, strval, 0,
5782 				    ZPROP_SRC_NONE);
5783 				continue;
5784 			case VDEV_PROP_CAPACITY:
5785 				/* percent used */
5786 				intval = (vd->vdev_stat.vs_dspace == 0) ? 0 :
5787 				    (vd->vdev_stat.vs_alloc * 100 /
5788 				    vd->vdev_stat.vs_dspace);
5789 				vdev_prop_add_list(outnvl, propname, NULL,
5790 				    intval, ZPROP_SRC_NONE);
5791 				continue;
5792 			case VDEV_PROP_STATE:
5793 				vdev_prop_add_list(outnvl, propname, NULL,
5794 				    vd->vdev_state, ZPROP_SRC_NONE);
5795 				continue;
5796 			case VDEV_PROP_GUID:
5797 				vdev_prop_add_list(outnvl, propname, NULL,
5798 				    vd->vdev_guid, ZPROP_SRC_NONE);
5799 				continue;
5800 			case VDEV_PROP_ASIZE:
5801 				vdev_prop_add_list(outnvl, propname, NULL,
5802 				    vd->vdev_asize, ZPROP_SRC_NONE);
5803 				continue;
5804 			case VDEV_PROP_PSIZE:
5805 				vdev_prop_add_list(outnvl, propname, NULL,
5806 				    vd->vdev_psize, ZPROP_SRC_NONE);
5807 				continue;
5808 			case VDEV_PROP_ASHIFT:
5809 				vdev_prop_add_list(outnvl, propname, NULL,
5810 				    vd->vdev_ashift, ZPROP_SRC_NONE);
5811 				continue;
5812 			case VDEV_PROP_SIZE:
5813 				vdev_prop_add_list(outnvl, propname, NULL,
5814 				    vd->vdev_stat.vs_dspace, ZPROP_SRC_NONE);
5815 				continue;
5816 			case VDEV_PROP_FREE:
5817 				vdev_prop_add_list(outnvl, propname, NULL,
5818 				    vd->vdev_stat.vs_dspace -
5819 				    vd->vdev_stat.vs_alloc, ZPROP_SRC_NONE);
5820 				continue;
5821 			case VDEV_PROP_ALLOCATED:
5822 				vdev_prop_add_list(outnvl, propname, NULL,
5823 				    vd->vdev_stat.vs_alloc, ZPROP_SRC_NONE);
5824 				continue;
5825 			case VDEV_PROP_EXPANDSZ:
5826 				vdev_prop_add_list(outnvl, propname, NULL,
5827 				    vd->vdev_stat.vs_esize, ZPROP_SRC_NONE);
5828 				continue;
5829 			case VDEV_PROP_FRAGMENTATION:
5830 				vdev_prop_add_list(outnvl, propname, NULL,
5831 				    vd->vdev_stat.vs_fragmentation,
5832 				    ZPROP_SRC_NONE);
5833 				continue;
5834 			case VDEV_PROP_PARITY:
5835 				vdev_prop_add_list(outnvl, propname, NULL,
5836 				    vdev_get_nparity(vd), ZPROP_SRC_NONE);
5837 				continue;
5838 			case VDEV_PROP_PATH:
5839 				if (vd->vdev_path == NULL)
5840 					continue;
5841 				vdev_prop_add_list(outnvl, propname,
5842 				    vd->vdev_path, 0, ZPROP_SRC_NONE);
5843 				continue;
5844 			case VDEV_PROP_DEVID:
5845 				if (vd->vdev_devid == NULL)
5846 					continue;
5847 				vdev_prop_add_list(outnvl, propname,
5848 				    vd->vdev_devid, 0, ZPROP_SRC_NONE);
5849 				continue;
5850 			case VDEV_PROP_PHYS_PATH:
5851 				if (vd->vdev_physpath == NULL)
5852 					continue;
5853 				vdev_prop_add_list(outnvl, propname,
5854 				    vd->vdev_physpath, 0, ZPROP_SRC_NONE);
5855 				continue;
5856 			case VDEV_PROP_ENC_PATH:
5857 				if (vd->vdev_enc_sysfs_path == NULL)
5858 					continue;
5859 				vdev_prop_add_list(outnvl, propname,
5860 				    vd->vdev_enc_sysfs_path, 0, ZPROP_SRC_NONE);
5861 				continue;
5862 			case VDEV_PROP_FRU:
5863 				if (vd->vdev_fru == NULL)
5864 					continue;
5865 				vdev_prop_add_list(outnvl, propname,
5866 				    vd->vdev_fru, 0, ZPROP_SRC_NONE);
5867 				continue;
5868 			case VDEV_PROP_PARENT:
5869 				if (vd->vdev_parent != NULL) {
5870 					strval = vdev_name(vd->vdev_parent,
5871 					    namebuf, sizeof (namebuf));
5872 					vdev_prop_add_list(outnvl, propname,
5873 					    strval, 0, ZPROP_SRC_NONE);
5874 				}
5875 				continue;
5876 			case VDEV_PROP_CHILDREN:
5877 				if (vd->vdev_children > 0)
5878 					strval = kmem_zalloc(ZAP_MAXVALUELEN,
5879 					    KM_SLEEP);
5880 				for (uint64_t i = 0; i < vd->vdev_children;
5881 				    i++) {
5882 					const char *vname;
5883 
5884 					vname = vdev_name(vd->vdev_child[i],
5885 					    namebuf, sizeof (namebuf));
5886 					if (vname == NULL)
5887 						vname = "(unknown)";
5888 					if (strlen(strval) > 0)
5889 						strlcat(strval, ",",
5890 						    ZAP_MAXVALUELEN);
5891 					strlcat(strval, vname, ZAP_MAXVALUELEN);
5892 				}
5893 				if (strval != NULL) {
5894 					vdev_prop_add_list(outnvl, propname,
5895 					    strval, 0, ZPROP_SRC_NONE);
5896 					kmem_free(strval, ZAP_MAXVALUELEN);
5897 				}
5898 				continue;
5899 			case VDEV_PROP_NUMCHILDREN:
5900 				vdev_prop_add_list(outnvl, propname, NULL,
5901 				    vd->vdev_children, ZPROP_SRC_NONE);
5902 				continue;
5903 			case VDEV_PROP_READ_ERRORS:
5904 				vdev_prop_add_list(outnvl, propname, NULL,
5905 				    vd->vdev_stat.vs_read_errors,
5906 				    ZPROP_SRC_NONE);
5907 				continue;
5908 			case VDEV_PROP_WRITE_ERRORS:
5909 				vdev_prop_add_list(outnvl, propname, NULL,
5910 				    vd->vdev_stat.vs_write_errors,
5911 				    ZPROP_SRC_NONE);
5912 				continue;
5913 			case VDEV_PROP_CHECKSUM_ERRORS:
5914 				vdev_prop_add_list(outnvl, propname, NULL,
5915 				    vd->vdev_stat.vs_checksum_errors,
5916 				    ZPROP_SRC_NONE);
5917 				continue;
5918 			case VDEV_PROP_INITIALIZE_ERRORS:
5919 				vdev_prop_add_list(outnvl, propname, NULL,
5920 				    vd->vdev_stat.vs_initialize_errors,
5921 				    ZPROP_SRC_NONE);
5922 				continue;
5923 			case VDEV_PROP_OPS_NULL:
5924 				vdev_prop_add_list(outnvl, propname, NULL,
5925 				    vd->vdev_stat.vs_ops[ZIO_TYPE_NULL],
5926 				    ZPROP_SRC_NONE);
5927 				continue;
5928 			case VDEV_PROP_OPS_READ:
5929 				vdev_prop_add_list(outnvl, propname, NULL,
5930 				    vd->vdev_stat.vs_ops[ZIO_TYPE_READ],
5931 				    ZPROP_SRC_NONE);
5932 				continue;
5933 			case VDEV_PROP_OPS_WRITE:
5934 				vdev_prop_add_list(outnvl, propname, NULL,
5935 				    vd->vdev_stat.vs_ops[ZIO_TYPE_WRITE],
5936 				    ZPROP_SRC_NONE);
5937 				continue;
5938 			case VDEV_PROP_OPS_FREE:
5939 				vdev_prop_add_list(outnvl, propname, NULL,
5940 				    vd->vdev_stat.vs_ops[ZIO_TYPE_FREE],
5941 				    ZPROP_SRC_NONE);
5942 				continue;
5943 			case VDEV_PROP_OPS_CLAIM:
5944 				vdev_prop_add_list(outnvl, propname, NULL,
5945 				    vd->vdev_stat.vs_ops[ZIO_TYPE_CLAIM],
5946 				    ZPROP_SRC_NONE);
5947 				continue;
5948 			case VDEV_PROP_OPS_TRIM:
5949 				/*
5950 				 * TRIM ops and bytes are reported to user
5951 				 * space as ZIO_TYPE_IOCTL.  This is done to
5952 				 * preserve the vdev_stat_t structure layout
5953 				 * for user space.
5954 				 */
5955 				vdev_prop_add_list(outnvl, propname, NULL,
5956 				    vd->vdev_stat.vs_ops[ZIO_TYPE_IOCTL],
5957 				    ZPROP_SRC_NONE);
5958 				continue;
5959 			case VDEV_PROP_BYTES_NULL:
5960 				vdev_prop_add_list(outnvl, propname, NULL,
5961 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_NULL],
5962 				    ZPROP_SRC_NONE);
5963 				continue;
5964 			case VDEV_PROP_BYTES_READ:
5965 				vdev_prop_add_list(outnvl, propname, NULL,
5966 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_READ],
5967 				    ZPROP_SRC_NONE);
5968 				continue;
5969 			case VDEV_PROP_BYTES_WRITE:
5970 				vdev_prop_add_list(outnvl, propname, NULL,
5971 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_WRITE],
5972 				    ZPROP_SRC_NONE);
5973 				continue;
5974 			case VDEV_PROP_BYTES_FREE:
5975 				vdev_prop_add_list(outnvl, propname, NULL,
5976 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_FREE],
5977 				    ZPROP_SRC_NONE);
5978 				continue;
5979 			case VDEV_PROP_BYTES_CLAIM:
5980 				vdev_prop_add_list(outnvl, propname, NULL,
5981 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_CLAIM],
5982 				    ZPROP_SRC_NONE);
5983 				continue;
5984 			case VDEV_PROP_BYTES_TRIM:
5985 				/*
5986 				 * TRIM ops and bytes are reported to user
5987 				 * space as ZIO_TYPE_IOCTL.  This is done to
5988 				 * preserve the vdev_stat_t structure layout
5989 				 * for user space.
5990 				 */
5991 				vdev_prop_add_list(outnvl, propname, NULL,
5992 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_IOCTL],
5993 				    ZPROP_SRC_NONE);
5994 				continue;
5995 			case VDEV_PROP_REMOVING:
5996 				vdev_prop_add_list(outnvl, propname, NULL,
5997 				    vd->vdev_removing, ZPROP_SRC_NONE);
5998 				continue;
5999 			/* Numeric Properites */
6000 			case VDEV_PROP_ALLOCATING:
6001 				src = ZPROP_SRC_LOCAL;
6002 				strval = NULL;
6003 
6004 				err = zap_lookup(mos, objid, nvpair_name(elem),
6005 				    sizeof (uint64_t), 1, &intval);
6006 				if (err == ENOENT) {
6007 					intval =
6008 					    vdev_prop_default_numeric(prop);
6009 					err = 0;
6010 				} else if (err)
6011 					break;
6012 				if (intval == vdev_prop_default_numeric(prop))
6013 					src = ZPROP_SRC_DEFAULT;
6014 
6015 				/* Leaf vdevs cannot have this property */
6016 				if (vd->vdev_mg == NULL &&
6017 				    vd->vdev_top != NULL) {
6018 					src = ZPROP_SRC_NONE;
6019 					intval = ZPROP_BOOLEAN_NA;
6020 				}
6021 
6022 				vdev_prop_add_list(outnvl, propname, strval,
6023 				    intval, src);
6024 				break;
6025 			/* Text Properties */
6026 			case VDEV_PROP_COMMENT:
6027 				/* Exists in the ZAP below */
6028 				/* FALLTHRU */
6029 			case VDEV_PROP_USERPROP:
6030 				/* User Properites */
6031 				src = ZPROP_SRC_LOCAL;
6032 
6033 				err = zap_length(mos, objid, nvpair_name(elem),
6034 				    &integer_size, &num_integers);
6035 				if (err)
6036 					break;
6037 
6038 				switch (integer_size) {
6039 				case 8:
6040 					/* User properties cannot be integers */
6041 					err = EINVAL;
6042 					break;
6043 				case 1:
6044 					/* string property */
6045 					strval = kmem_alloc(num_integers,
6046 					    KM_SLEEP);
6047 					err = zap_lookup(mos, objid,
6048 					    nvpair_name(elem), 1,
6049 					    num_integers, strval);
6050 					if (err) {
6051 						kmem_free(strval,
6052 						    num_integers);
6053 						break;
6054 					}
6055 					vdev_prop_add_list(outnvl, propname,
6056 					    strval, 0, src);
6057 					kmem_free(strval, num_integers);
6058 					break;
6059 				}
6060 				break;
6061 			default:
6062 				err = ENOENT;
6063 				break;
6064 			}
6065 			if (err)
6066 				break;
6067 		}
6068 	} else {
6069 		/*
6070 		 * Get all properties from the MOS vdev property object.
6071 		 */
6072 		zap_cursor_t zc;
6073 		zap_attribute_t za;
6074 		for (zap_cursor_init(&zc, mos, objid);
6075 		    (err = zap_cursor_retrieve(&zc, &za)) == 0;
6076 		    zap_cursor_advance(&zc)) {
6077 			intval = 0;
6078 			strval = NULL;
6079 			zprop_source_t src = ZPROP_SRC_DEFAULT;
6080 			propname = za.za_name;
6081 			prop = vdev_name_to_prop(propname);
6082 
6083 			switch (za.za_integer_length) {
6084 			case 8:
6085 				/* We do not allow integer user properties */
6086 				/* This is likely an internal value */
6087 				break;
6088 			case 1:
6089 				/* string property */
6090 				strval = kmem_alloc(za.za_num_integers,
6091 				    KM_SLEEP);
6092 				err = zap_lookup(mos, objid, za.za_name, 1,
6093 				    za.za_num_integers, strval);
6094 				if (err) {
6095 					kmem_free(strval, za.za_num_integers);
6096 					break;
6097 				}
6098 				vdev_prop_add_list(outnvl, propname, strval, 0,
6099 				    src);
6100 				kmem_free(strval, za.za_num_integers);
6101 				break;
6102 
6103 			default:
6104 				break;
6105 			}
6106 		}
6107 		zap_cursor_fini(&zc);
6108 	}
6109 
6110 	mutex_exit(&spa->spa_props_lock);
6111 	if (err && err != ENOENT) {
6112 		return (err);
6113 	}
6114 
6115 	return (0);
6116 }
6117 
6118 EXPORT_SYMBOL(vdev_fault);
6119 EXPORT_SYMBOL(vdev_degrade);
6120 EXPORT_SYMBOL(vdev_online);
6121 EXPORT_SYMBOL(vdev_offline);
6122 EXPORT_SYMBOL(vdev_clear);
6123 
6124 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, default_ms_count, UINT, ZMOD_RW,
6125 	"Target number of metaslabs per top-level vdev");
6126 
6127 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, default_ms_shift, UINT, ZMOD_RW,
6128 	"Default limit for metaslab size");
6129 
6130 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, min_ms_count, UINT, ZMOD_RW,
6131 	"Minimum number of metaslabs per top-level vdev");
6132 
6133 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, ms_count_limit, UINT, ZMOD_RW,
6134 	"Practical upper limit of total metaslabs per top-level vdev");
6135 
6136 ZFS_MODULE_PARAM(zfs, zfs_, slow_io_events_per_second, UINT, ZMOD_RW,
6137 	"Rate limit slow IO (delay) events to this many per second");
6138 
6139 /* BEGIN CSTYLED */
6140 ZFS_MODULE_PARAM(zfs, zfs_, checksum_events_per_second, UINT, ZMOD_RW,
6141 	"Rate limit checksum events to this many checksum errors per second "
6142 	"(do not set below ZED threshold).");
6143 /* END CSTYLED */
6144 
6145 ZFS_MODULE_PARAM(zfs, zfs_, scan_ignore_errors, INT, ZMOD_RW,
6146 	"Ignore errors during resilver/scrub");
6147 
6148 ZFS_MODULE_PARAM(zfs_vdev, vdev_, validate_skip, INT, ZMOD_RW,
6149 	"Bypass vdev_validate()");
6150 
6151 ZFS_MODULE_PARAM(zfs, zfs_, nocacheflush, INT, ZMOD_RW,
6152 	"Disable cache flushes");
6153 
6154 ZFS_MODULE_PARAM(zfs, zfs_, embedded_slog_min_ms, UINT, ZMOD_RW,
6155 	"Minimum number of metaslabs required to dedicate one for log blocks");
6156 
6157 /* BEGIN CSTYLED */
6158 ZFS_MODULE_PARAM_CALL(zfs_vdev, zfs_vdev_, min_auto_ashift,
6159 	param_set_min_auto_ashift, param_get_ulong, ZMOD_RW,
6160 	"Minimum ashift used when creating new top-level vdevs");
6161 
6162 ZFS_MODULE_PARAM_CALL(zfs_vdev, zfs_vdev_, max_auto_ashift,
6163 	param_set_max_auto_ashift, param_get_ulong, ZMOD_RW,
6164 	"Maximum ashift used when optimizing for logical -> physical sector "
6165 	"size on new top-level vdevs");
6166 /* END CSTYLED */
6167