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