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