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