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