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