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