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