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