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