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