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