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