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