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