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