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