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