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