xref: /freebsd/sys/contrib/openzfs/module/zfs/vdev.c (revision 80aae8a3f8aa70712930664572be9e6885dc0be7)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2011, 2021 by Delphix. All rights reserved.
26  * Copyright 2017 Nexenta Systems, Inc.
27  * Copyright (c) 2014 Integros [integros.com]
28  * Copyright 2016 Toomas Soome <tsoome@me.com>
29  * Copyright 2017 Joyent, Inc.
30  * Copyright (c) 2017, Intel Corporation.
31  * Copyright (c) 2019, Datto Inc. All rights reserved.
32  * Copyright (c) 2021, 2025, Klara, Inc.
33  * Copyright (c) 2021, 2023 Hewlett Packard Enterprise Development LP.
34  * Copyright (c) 2026, Seagate Technology, LLC.
35  */
36 
37 #include <sys/zfs_context.h>
38 #include <sys/fm/fs/zfs.h>
39 #include <sys/spa.h>
40 #include <sys/spa_impl.h>
41 #include <sys/bpobj.h>
42 #include <sys/dmu.h>
43 #include <sys/dmu_tx.h>
44 #include <sys/dsl_dir.h>
45 #include <sys/vdev_impl.h>
46 #include <sys/vdev_rebuild.h>
47 #include <sys/vdev_draid.h>
48 #include <sys/uberblock_impl.h>
49 #include <sys/metaslab.h>
50 #include <sys/metaslab_impl.h>
51 #include <sys/space_map.h>
52 #include <sys/space_reftree.h>
53 #include <sys/zio.h>
54 #include <sys/zap.h>
55 #include <sys/fs/zfs.h>
56 #include <sys/arc.h>
57 #include <sys/zil.h>
58 #include <sys/dsl_scan.h>
59 #include <sys/vdev_raidz.h>
60 #include <sys/abd.h>
61 #include <sys/vdev_initialize.h>
62 #include <sys/vdev_trim.h>
63 #include <sys/vdev_raidz.h>
64 #include <sys/zvol.h>
65 #include <sys/zfs_ratelimit.h>
66 #include "zfs_prop.h"
67 
68 /*
69  * One metaslab from each (normal-class) vdev is used by the ZIL.  These are
70  * called "embedded slog metaslabs", are referenced by vdev_log_mg, and are
71  * part of the spa_embedded_log_class.  The metaslab with the most free space
72  * in each vdev is selected for this purpose when the pool is opened (or a
73  * vdev is added).  See vdev_metaslab_init().
74  *
75  * Log blocks can be allocated from the following locations.  Each one is tried
76  * in order until the allocation succeeds:
77  * 1. dedicated log vdevs, aka "slog" (spa_log_class)
78  * 2. embedded slog metaslabs (spa_embedded_log_class)
79  * 3. other metaslabs in normal vdevs (spa_normal_class)
80  *
81  * zfs_embedded_slog_min_ms disables the embedded slog if there are fewer
82  * than this number of metaslabs in the vdev.  This ensures that we don't set
83  * aside an unreasonable amount of space for the ZIL.  If set to less than
84  * 1 << (spa_slop_shift + 1), on small pools the usable space may be reduced
85  * (by more than 1<<spa_slop_shift) due to the embedded slog metaslab.
86  */
87 static uint_t zfs_embedded_slog_min_ms = 64;
88 
89 /* default target for number of metaslabs per top-level vdev */
90 static uint_t zfs_vdev_default_ms_count = 200;
91 
92 /* minimum number of metaslabs per top-level vdev */
93 static uint_t zfs_vdev_min_ms_count = 16;
94 
95 /* practical upper limit of total metaslabs per top-level vdev */
96 static uint_t zfs_vdev_ms_count_limit = 1ULL << 17;
97 
98 /* lower limit for metaslab size (512M) */
99 static uint_t zfs_vdev_default_ms_shift = 29;
100 
101 /* upper limit for metaslab size (16G) */
102 static uint_t zfs_vdev_max_ms_shift = 34;
103 
104 int vdev_validate_skip = B_FALSE;
105 
106 /*
107  * Since the DTL space map of a vdev is not expected to have a lot of
108  * entries, we default its block size to 4K.
109  */
110 int zfs_vdev_dtl_sm_blksz = (1 << 12);
111 
112 /*
113  * Rate limit slow IO (delay) events to this many per second.
114  */
115 static unsigned int zfs_slow_io_events_per_second = 20;
116 
117 /*
118  * Rate limit deadman "hung IO" events to this many per second.
119  */
120 static unsigned int zfs_deadman_events_per_second = 1;
121 
122 /*
123  * Rate limit direct write IO verify failures to this many per scond.
124  */
125 static unsigned int zfs_dio_write_verify_events_per_second = 20;
126 
127 /*
128  * Rate limit checksum events after this many checksum errors per second.
129  */
130 static unsigned int zfs_checksum_events_per_second = 20;
131 
132 /*
133  * Ignore errors during scrub/resilver.  Allows to work around resilver
134  * upon import when there are pool errors.
135  */
136 static int zfs_scan_ignore_errors = 0;
137 
138 /*
139  * vdev-wide space maps that have lots of entries written to them at
140  * the end of each transaction can benefit from a higher I/O bandwidth
141  * (e.g. vdev_obsolete_sm), thus we default their block size to 128K.
142  */
143 int zfs_vdev_standard_sm_blksz = (1 << 17);
144 
145 /*
146  * Tunable parameter for debugging or performance analysis. Setting this
147  * will cause pool corruption on power loss if a volatile out-of-order
148  * write cache is enabled.
149  */
150 int zfs_nocacheflush = 0;
151 
152 /*
153  * Maximum and minimum ashift values that can be automatically set based on
154  * vdev's physical ashift (disk's physical sector size).  While ASHIFT_MAX
155  * is higher than the maximum value, it is intentionally limited here to not
156  * excessively impact pool space efficiency.  Higher ashift values may still
157  * be forced by vdev logical ashift or by user via ashift property, but won't
158  * be set automatically as a performance optimization.
159  */
160 uint_t zfs_vdev_max_auto_ashift = 14;
161 uint_t zfs_vdev_min_auto_ashift = ASHIFT_MIN;
162 
163 /*
164  * VDEV checksum verification for Direct I/O writes. This is neccessary for
165  * Linux, because anonymous pages can not be placed under write protection
166  * during Direct I/O writes.
167  */
168 #if !defined(__FreeBSD__)
169 uint_t zfs_vdev_direct_write_verify = 1;
170 #else
171 uint_t zfs_vdev_direct_write_verify = 0;
172 #endif
173 
174 void
vdev_dbgmsg(vdev_t * vd,const char * fmt,...)175 vdev_dbgmsg(vdev_t *vd, const char *fmt, ...)
176 {
177 	va_list adx;
178 	char buf[256];
179 
180 	va_start(adx, fmt);
181 	(void) vsnprintf(buf, sizeof (buf), fmt, adx);
182 	va_end(adx);
183 
184 	if (vd->vdev_path != NULL) {
185 		zfs_dbgmsg("%s vdev '%s': %s", vd->vdev_ops->vdev_op_type,
186 		    vd->vdev_path, buf);
187 	} else {
188 		zfs_dbgmsg("%s-%llu vdev (guid %llu): %s",
189 		    vd->vdev_ops->vdev_op_type,
190 		    (u_longlong_t)vd->vdev_id,
191 		    (u_longlong_t)vd->vdev_guid, buf);
192 	}
193 }
194 
195 void
vdev_dbgmsg_print_tree(vdev_t * vd,int indent)196 vdev_dbgmsg_print_tree(vdev_t *vd, int indent)
197 {
198 	char state[20];
199 
200 	if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops) {
201 		zfs_dbgmsg("%*svdev %llu: %s", indent, "",
202 		    (u_longlong_t)vd->vdev_id,
203 		    vd->vdev_ops->vdev_op_type);
204 		return;
205 	}
206 
207 	switch (vd->vdev_state) {
208 	case VDEV_STATE_UNKNOWN:
209 		(void) snprintf(state, sizeof (state), "unknown");
210 		break;
211 	case VDEV_STATE_CLOSED:
212 		(void) snprintf(state, sizeof (state), "closed");
213 		break;
214 	case VDEV_STATE_OFFLINE:
215 		(void) snprintf(state, sizeof (state), "offline");
216 		break;
217 	case VDEV_STATE_REMOVED:
218 		(void) snprintf(state, sizeof (state), "removed");
219 		break;
220 	case VDEV_STATE_CANT_OPEN:
221 		(void) snprintf(state, sizeof (state), "can't open");
222 		break;
223 	case VDEV_STATE_FAULTED:
224 		(void) snprintf(state, sizeof (state), "faulted");
225 		break;
226 	case VDEV_STATE_DEGRADED:
227 		(void) snprintf(state, sizeof (state), "degraded");
228 		break;
229 	case VDEV_STATE_HEALTHY:
230 		(void) snprintf(state, sizeof (state), "healthy");
231 		break;
232 	default:
233 		(void) snprintf(state, sizeof (state), "<state %u>",
234 		    (uint_t)vd->vdev_state);
235 	}
236 
237 	zfs_dbgmsg("%*svdev %u: %s%s, guid: %llu, path: %s, %s", indent,
238 	    "", (int)vd->vdev_id, vd->vdev_ops->vdev_op_type,
239 	    vd->vdev_islog ? " (log)" : "",
240 	    (u_longlong_t)vd->vdev_guid,
241 	    vd->vdev_path ? vd->vdev_path : "N/A", state);
242 
243 	for (uint64_t i = 0; i < vd->vdev_children; i++)
244 		vdev_dbgmsg_print_tree(vd->vdev_child[i], indent + 2);
245 }
246 
247 char *
vdev_rt_name(vdev_t * vd,const char * name)248 vdev_rt_name(vdev_t *vd, const char *name)
249 {
250 	return (kmem_asprintf("{spa=%s vdev_guid=%llu %s}",
251 	    spa_name(vd->vdev_spa),
252 	    (u_longlong_t)vd->vdev_guid,
253 	    name));
254 }
255 
256 static char *
vdev_rt_name_dtl(vdev_t * vd,const char * name,vdev_dtl_type_t dtl_type)257 vdev_rt_name_dtl(vdev_t *vd, const char *name, vdev_dtl_type_t dtl_type)
258 {
259 	return (kmem_asprintf("{spa=%s vdev_guid=%llu %s[%d]}",
260 	    spa_name(vd->vdev_spa),
261 	    (u_longlong_t)vd->vdev_guid,
262 	    name,
263 	    dtl_type));
264 }
265 
266 /*
267  * Virtual device management.
268  */
269 
270 static vdev_ops_t *const vdev_ops_table[] = {
271 	&vdev_root_ops,
272 	&vdev_raidz_ops,
273 	&vdev_draid_ops,
274 	&vdev_draid_spare_ops,
275 	&vdev_mirror_ops,
276 	&vdev_replacing_ops,
277 	&vdev_spare_ops,
278 	&vdev_disk_ops,
279 	&vdev_file_ops,
280 	&vdev_missing_ops,
281 	&vdev_hole_ops,
282 	&vdev_indirect_ops,
283 	NULL
284 };
285 
286 /*
287  * Given a vdev type, return the appropriate ops vector.
288  */
289 static vdev_ops_t *
vdev_getops(const char * type)290 vdev_getops(const char *type)
291 {
292 	vdev_ops_t *ops, *const *opspp;
293 
294 	for (opspp = vdev_ops_table; (ops = *opspp) != NULL; opspp++)
295 		if (strcmp(ops->vdev_op_type, type) == 0)
296 			break;
297 
298 	return (ops);
299 }
300 
301 /*
302  * Given a vdev and a metaslab class, find which metaslab group we're
303  * interested in. All vdevs may belong to two different metaslab classes.
304  * Dedicated slog devices use only the primary metaslab group, rather than a
305  * separate log group.  For embedded slogs, vdev_log_mg will be non-NULL and
306  * will point to a metaslab group of either embedded_log_class (for normal
307  * vdevs) or special_embedded_log_class (for special vdevs).
308  */
309 metaslab_group_t *
vdev_get_mg(vdev_t * vd,metaslab_class_t * mc)310 vdev_get_mg(vdev_t *vd, metaslab_class_t *mc)
311 {
312 	if ((mc == spa_embedded_log_class(vd->vdev_spa) ||
313 	    mc == spa_special_embedded_log_class(vd->vdev_spa)) &&
314 	    vd->vdev_log_mg != NULL)
315 		return (vd->vdev_log_mg);
316 	else
317 		return (vd->vdev_mg);
318 }
319 
320 void
vdev_default_xlate(vdev_t * vd,const zfs_range_seg64_t * logical_rs,zfs_range_seg64_t * physical_rs,zfs_range_seg64_t * remain_rs)321 vdev_default_xlate(vdev_t *vd, const zfs_range_seg64_t *logical_rs,
322     zfs_range_seg64_t *physical_rs, zfs_range_seg64_t *remain_rs)
323 {
324 	(void) vd, (void) remain_rs;
325 
326 	physical_rs->rs_start = logical_rs->rs_start;
327 	physical_rs->rs_end = logical_rs->rs_end;
328 }
329 
330 /*
331  * Derive the enumerated allocation bias from string input.
332  * String origin is either the per-vdev zap or zpool(8).
333  */
334 static vdev_alloc_bias_t
vdev_derive_alloc_bias(const char * bias)335 vdev_derive_alloc_bias(const char *bias)
336 {
337 	vdev_alloc_bias_t alloc_bias = VDEV_BIAS_NONE;
338 
339 	if (strcmp(bias, VDEV_ALLOC_BIAS_LOG) == 0)
340 		alloc_bias = VDEV_BIAS_LOG;
341 	else if (strcmp(bias, VDEV_ALLOC_BIAS_SPECIAL) == 0)
342 		alloc_bias = VDEV_BIAS_SPECIAL;
343 	else if (strcmp(bias, VDEV_ALLOC_BIAS_DEDUP) == 0)
344 		alloc_bias = VDEV_BIAS_DEDUP;
345 
346 	return (alloc_bias);
347 }
348 
349 uint64_t
vdev_default_psize(vdev_t * vd,uint64_t asize,uint64_t txg)350 vdev_default_psize(vdev_t *vd, uint64_t asize, uint64_t txg)
351 {
352 	ASSERT0(asize % (1ULL << vd->vdev_top->vdev_ashift));
353 	uint64_t csize, psize = asize;
354 	for (int c = 0; c < vd->vdev_children; c++) {
355 		csize = vdev_asize_to_psize_txg(vd->vdev_child[c], asize, txg);
356 		psize = MIN(psize, csize);
357 	}
358 
359 	return (psize);
360 }
361 
362 /*
363  * Default asize function: return the MAX of psize with the asize of
364  * all children.  This is what's used by anything other than RAID-Z.
365  */
366 uint64_t
vdev_default_asize(vdev_t * vd,uint64_t psize,uint64_t txg)367 vdev_default_asize(vdev_t *vd, uint64_t psize, uint64_t txg)
368 {
369 	uint64_t asize = P2ROUNDUP(psize, 1ULL << vd->vdev_top->vdev_ashift);
370 	uint64_t csize;
371 
372 	for (int c = 0; c < vd->vdev_children; c++) {
373 		csize = vdev_psize_to_asize_txg(vd->vdev_child[c], psize, txg);
374 		asize = MAX(asize, csize);
375 	}
376 
377 	return (asize);
378 }
379 
380 uint64_t
vdev_default_min_asize(vdev_t * vd)381 vdev_default_min_asize(vdev_t *vd)
382 {
383 	return (vd->vdev_min_asize);
384 }
385 
386 /*
387  * Get the minimum allocatable size. We define the allocatable size as
388  * the vdev's asize rounded to the nearest metaslab. This allows us to
389  * replace or attach devices which don't have the same physical size but
390  * can still satisfy the same number of allocations.
391  */
392 uint64_t
vdev_get_min_asize(vdev_t * vd)393 vdev_get_min_asize(vdev_t *vd)
394 {
395 	vdev_t *pvd = vd->vdev_parent;
396 
397 	/*
398 	 * If our parent is NULL (inactive spare or cache) or is the root,
399 	 * just return our own asize.
400 	 */
401 	if (pvd == NULL)
402 		return (vd->vdev_asize);
403 
404 	/*
405 	 * The top-level vdev just returns the allocatable size rounded
406 	 * to the nearest metaslab.
407 	 */
408 	if (vd == vd->vdev_top)
409 		return (P2ALIGN_TYPED(vd->vdev_asize, 1ULL << vd->vdev_ms_shift,
410 		    uint64_t));
411 
412 	return (pvd->vdev_ops->vdev_op_min_asize(pvd));
413 }
414 
415 void
vdev_set_min_asize(vdev_t * vd)416 vdev_set_min_asize(vdev_t *vd)
417 {
418 	vd->vdev_min_asize = vdev_get_min_asize(vd);
419 
420 	for (int c = 0; c < vd->vdev_children; c++)
421 		vdev_set_min_asize(vd->vdev_child[c]);
422 }
423 
424 /*
425  * Get the minimal allocation size for the top-level vdev.
426  */
427 uint64_t
vdev_get_min_alloc(vdev_t * vd)428 vdev_get_min_alloc(vdev_t *vd)
429 {
430 	uint64_t min_alloc = 1ULL << vd->vdev_ashift;
431 
432 	if (vd->vdev_ops->vdev_op_min_alloc != NULL)
433 		min_alloc = vd->vdev_ops->vdev_op_min_alloc(vd);
434 
435 	return (min_alloc);
436 }
437 
438 /*
439  * Get the parity level for a top-level vdev.
440  */
441 uint64_t
vdev_get_nparity(vdev_t * vd)442 vdev_get_nparity(vdev_t *vd)
443 {
444 	uint64_t nparity = 0;
445 
446 	if (vd->vdev_ops->vdev_op_nparity != NULL)
447 		nparity = vd->vdev_ops->vdev_op_nparity(vd);
448 
449 	return (nparity);
450 }
451 
452 static int
vdev_prop_get_objid(vdev_t * vd,uint64_t * objid)453 vdev_prop_get_objid(vdev_t *vd, uint64_t *objid)
454 {
455 
456 	if (vd->vdev_root_zap != 0) {
457 		*objid = vd->vdev_root_zap;
458 	} else if (vd->vdev_top_zap != 0) {
459 		*objid = vd->vdev_top_zap;
460 	} else if (vd->vdev_leaf_zap != 0) {
461 		*objid = vd->vdev_leaf_zap;
462 	} else {
463 		return (EINVAL);
464 	}
465 
466 	return (0);
467 }
468 
469 static int
vdev_prop_get_int(vdev_t * vd,vdev_prop_t prop,uint64_t * value)470 vdev_prop_get_int(vdev_t *vd, vdev_prop_t prop, uint64_t *value)
471 {
472 	spa_t *spa = vd->vdev_spa;
473 	objset_t *mos = spa->spa_meta_objset;
474 	uint64_t objid;
475 	int err;
476 
477 	if (vdev_prop_get_objid(vd, &objid) != 0)
478 		return (EINVAL);
479 
480 	err = zap_lookup(mos, objid, vdev_prop_to_name(prop),
481 	    sizeof (uint64_t), 1, value);
482 	if (err == ENOENT)
483 		*value = vdev_prop_default_numeric(prop);
484 
485 	return (err);
486 }
487 
488 static int
vdev_prop_get_bool(vdev_t * vd,vdev_prop_t prop,boolean_t * bvalue)489 vdev_prop_get_bool(vdev_t *vd, vdev_prop_t prop, boolean_t *bvalue)
490 {
491 	int err;
492 	uint64_t ivalue;
493 
494 	err = vdev_prop_get_int(vd, prop, &ivalue);
495 	*bvalue = ivalue != 0;
496 
497 	return (err);
498 }
499 
500 /*
501  * Get the number of data disks for a top-level vdev.
502  */
503 uint64_t
vdev_get_ndisks(vdev_t * vd)504 vdev_get_ndisks(vdev_t *vd)
505 {
506 	uint64_t ndisks = 1;
507 
508 	if (vd->vdev_ops->vdev_op_ndisks != NULL)
509 		ndisks = vd->vdev_ops->vdev_op_ndisks(vd);
510 
511 	return (ndisks);
512 }
513 
514 vdev_t *
vdev_lookup_top(spa_t * spa,uint64_t vdev)515 vdev_lookup_top(spa_t *spa, uint64_t vdev)
516 {
517 	vdev_t *rvd = spa->spa_root_vdev;
518 
519 	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
520 
521 	if (vdev < rvd->vdev_children) {
522 		ASSERT(rvd->vdev_child[vdev] != NULL);
523 		return (rvd->vdev_child[vdev]);
524 	}
525 
526 	return (NULL);
527 }
528 
529 vdev_t *
vdev_lookup_by_guid(vdev_t * vd,uint64_t guid)530 vdev_lookup_by_guid(vdev_t *vd, uint64_t guid)
531 {
532 	vdev_t *mvd;
533 
534 	if (vd->vdev_guid == guid)
535 		return (vd);
536 
537 	for (int c = 0; c < vd->vdev_children; c++)
538 		if ((mvd = vdev_lookup_by_guid(vd->vdev_child[c], guid)) !=
539 		    NULL)
540 			return (mvd);
541 
542 	return (NULL);
543 }
544 
545 static int
vdev_count_leaves_impl(vdev_t * vd)546 vdev_count_leaves_impl(vdev_t *vd)
547 {
548 	int n = 0;
549 
550 	if (vd->vdev_ops->vdev_op_leaf)
551 		return (1);
552 
553 	for (int c = 0; c < vd->vdev_children; c++)
554 		n += vdev_count_leaves_impl(vd->vdev_child[c]);
555 
556 	return (n);
557 }
558 
559 int
vdev_count_leaves(spa_t * spa)560 vdev_count_leaves(spa_t *spa)
561 {
562 	int rc;
563 
564 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
565 	rc = vdev_count_leaves_impl(spa->spa_root_vdev);
566 	spa_config_exit(spa, SCL_VDEV, FTAG);
567 
568 	return (rc);
569 }
570 
571 void
vdev_add_child(vdev_t * pvd,vdev_t * cvd)572 vdev_add_child(vdev_t *pvd, vdev_t *cvd)
573 {
574 	size_t oldsize, newsize;
575 	uint64_t id = cvd->vdev_id;
576 	vdev_t **newchild;
577 
578 	ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
579 	ASSERT0P(cvd->vdev_parent);
580 
581 	cvd->vdev_parent = pvd;
582 
583 	if (pvd == NULL)
584 		return;
585 
586 	ASSERT(id >= pvd->vdev_children || pvd->vdev_child[id] == NULL);
587 
588 	oldsize = pvd->vdev_children * sizeof (vdev_t *);
589 	pvd->vdev_children = MAX(pvd->vdev_children, id + 1);
590 	newsize = pvd->vdev_children * sizeof (vdev_t *);
591 
592 	newchild = kmem_alloc(newsize, KM_SLEEP);
593 	if (pvd->vdev_child != NULL) {
594 		memcpy(newchild, pvd->vdev_child, oldsize);
595 		kmem_free(pvd->vdev_child, oldsize);
596 	}
597 
598 	pvd->vdev_child = newchild;
599 	pvd->vdev_child[id] = cvd;
600 	pvd->vdev_nonrot &= cvd->vdev_nonrot;
601 
602 	cvd->vdev_top = (pvd->vdev_top ? pvd->vdev_top: cvd);
603 	ASSERT0P(cvd->vdev_top->vdev_parent->vdev_parent);
604 
605 	/*
606 	 * Walk up all ancestors to update guid sum.
607 	 */
608 	for (; pvd != NULL; pvd = pvd->vdev_parent)
609 		pvd->vdev_guid_sum += cvd->vdev_guid_sum;
610 
611 	if (cvd->vdev_ops->vdev_op_leaf) {
612 		list_insert_head(&cvd->vdev_spa->spa_leaf_list, cvd);
613 		cvd->vdev_spa->spa_leaf_list_gen++;
614 	}
615 }
616 
617 void
vdev_remove_child(vdev_t * pvd,vdev_t * cvd)618 vdev_remove_child(vdev_t *pvd, vdev_t *cvd)
619 {
620 	int c;
621 	uint_t id = cvd->vdev_id;
622 
623 	ASSERT(cvd->vdev_parent == pvd);
624 
625 	if (pvd == NULL)
626 		return;
627 
628 	ASSERT(id < pvd->vdev_children);
629 	ASSERT(pvd->vdev_child[id] == cvd);
630 
631 	pvd->vdev_child[id] = NULL;
632 	cvd->vdev_parent = NULL;
633 
634 	for (c = 0; c < pvd->vdev_children; c++)
635 		if (pvd->vdev_child[c])
636 			break;
637 
638 	if (c == pvd->vdev_children) {
639 		kmem_free(pvd->vdev_child, c * sizeof (vdev_t *));
640 		pvd->vdev_child = NULL;
641 		pvd->vdev_children = 0;
642 	}
643 
644 	if (cvd->vdev_ops->vdev_op_leaf) {
645 		spa_t *spa = cvd->vdev_spa;
646 		list_remove(&spa->spa_leaf_list, cvd);
647 		spa->spa_leaf_list_gen++;
648 	}
649 
650 	/*
651 	 * Walk up all ancestors to update guid sum.
652 	 */
653 	for (; pvd != NULL; pvd = pvd->vdev_parent)
654 		pvd->vdev_guid_sum -= cvd->vdev_guid_sum;
655 }
656 
657 /*
658  * Remove any holes in the child array.
659  */
660 void
vdev_compact_children(vdev_t * pvd)661 vdev_compact_children(vdev_t *pvd)
662 {
663 	vdev_t **newchild, *cvd;
664 	int oldc = pvd->vdev_children;
665 	int newc;
666 
667 	ASSERT(spa_config_held(pvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
668 
669 	if (oldc == 0)
670 		return;
671 
672 	for (int c = newc = 0; c < oldc; c++)
673 		if (pvd->vdev_child[c])
674 			newc++;
675 
676 	if (newc > 0) {
677 		newchild = kmem_zalloc(newc * sizeof (vdev_t *), KM_SLEEP);
678 
679 		for (int c = newc = 0; c < oldc; c++) {
680 			if ((cvd = pvd->vdev_child[c]) != NULL) {
681 				newchild[newc] = cvd;
682 				cvd->vdev_id = newc++;
683 			}
684 		}
685 	} else {
686 		newchild = NULL;
687 	}
688 
689 	kmem_free(pvd->vdev_child, oldc * sizeof (vdev_t *));
690 	pvd->vdev_child = newchild;
691 	pvd->vdev_children = newc;
692 }
693 
694 /*
695  * Allocate and minimally initialize a vdev_t.
696  */
697 vdev_t *
vdev_alloc_common(spa_t * spa,uint_t id,uint64_t guid,vdev_ops_t * ops)698 vdev_alloc_common(spa_t *spa, uint_t id, uint64_t guid, vdev_ops_t *ops)
699 {
700 	vdev_t *vd;
701 	vdev_indirect_config_t *vic;
702 
703 	vd = kmem_zalloc(sizeof (vdev_t), KM_SLEEP);
704 	vic = &vd->vdev_indirect_config;
705 
706 	if (spa->spa_root_vdev == NULL) {
707 		ASSERT(ops == &vdev_root_ops);
708 		spa->spa_root_vdev = vd;
709 		spa->spa_load_guid = spa_generate_load_guid();
710 	}
711 
712 	if (guid == 0 && ops != &vdev_hole_ops) {
713 		if (spa->spa_root_vdev == vd) {
714 			/*
715 			 * The root vdev's guid will also be the pool guid,
716 			 * which must be unique among all pools.
717 			 */
718 			guid = spa_generate_guid(NULL);
719 		} else {
720 			/*
721 			 * Any other vdev's guid must be unique within the pool.
722 			 */
723 			guid = spa_generate_guid(spa);
724 		}
725 		ASSERT(!spa_guid_exists(spa_guid(spa), guid));
726 	}
727 
728 	vd->vdev_spa = spa;
729 	vd->vdev_id = id;
730 	vd->vdev_guid = guid;
731 	vd->vdev_guid_sum = guid;
732 	vd->vdev_ops = ops;
733 	vd->vdev_state = VDEV_STATE_CLOSED;
734 	vd->vdev_ishole = (ops == &vdev_hole_ops);
735 	vic->vic_prev_indirect_vdev = UINT64_MAX;
736 
737 	rw_init(&vd->vdev_indirect_rwlock, NULL, RW_DEFAULT, NULL);
738 	mutex_init(&vd->vdev_obsolete_lock, NULL, MUTEX_DEFAULT, NULL);
739 	vd->vdev_obsolete_segments = zfs_range_tree_create_flags(
740 	    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
741 	    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "vdev_obsolete_segments"));
742 
743 	/*
744 	 * Initialize rate limit structs for events.  We rate limit ZIO delay
745 	 * and checksum events so that we don't overwhelm ZED with thousands
746 	 * of events when a disk is acting up.
747 	 */
748 	zfs_ratelimit_init(&vd->vdev_delay_rl, &zfs_slow_io_events_per_second,
749 	    1);
750 	zfs_ratelimit_init(&vd->vdev_deadman_rl, &zfs_deadman_events_per_second,
751 	    1);
752 	zfs_ratelimit_init(&vd->vdev_dio_verify_rl,
753 	    &zfs_dio_write_verify_events_per_second, 1);
754 	zfs_ratelimit_init(&vd->vdev_checksum_rl,
755 	    &zfs_checksum_events_per_second, 1);
756 
757 	/*
758 	 * Default Thresholds for tuning ZED
759 	 */
760 	vd->vdev_checksum_n = vdev_prop_default_numeric(VDEV_PROP_CHECKSUM_N);
761 	vd->vdev_checksum_t = vdev_prop_default_numeric(VDEV_PROP_CHECKSUM_T);
762 
763 	vd->vdev_io_n = vdev_prop_default_numeric(VDEV_PROP_IO_N);
764 	vd->vdev_io_t = vdev_prop_default_numeric(VDEV_PROP_IO_T);
765 
766 	vd->vdev_slow_io_events = vdev_prop_default_numeric(
767 	    VDEV_PROP_SLOW_IO_EVENTS);
768 	vd->vdev_slow_io_n = vdev_prop_default_numeric(VDEV_PROP_SLOW_IO_N);
769 	vd->vdev_slow_io_t = vdev_prop_default_numeric(VDEV_PROP_SLOW_IO_T);
770 
771 	vd->vdev_scheduler = vdev_prop_default_numeric(VDEV_PROP_SCHEDULER);
772 
773 	list_link_init(&vd->vdev_config_dirty_node);
774 	list_link_init(&vd->vdev_state_dirty_node);
775 	list_link_init(&vd->vdev_initialize_node);
776 	list_link_init(&vd->vdev_leaf_node);
777 	list_link_init(&vd->vdev_trim_node);
778 
779 	mutex_init(&vd->vdev_dtl_lock, NULL, MUTEX_NOLOCKDEP, NULL);
780 	mutex_init(&vd->vdev_stat_lock, NULL, MUTEX_DEFAULT, NULL);
781 	mutex_init(&vd->vdev_probe_lock, NULL, MUTEX_DEFAULT, NULL);
782 	mutex_init(&vd->vdev_scan_io_queue_lock, NULL, MUTEX_DEFAULT, NULL);
783 
784 	mutex_init(&vd->vdev_initialize_lock, NULL, MUTEX_DEFAULT, NULL);
785 	mutex_init(&vd->vdev_initialize_io_lock, NULL, MUTEX_DEFAULT, NULL);
786 	cv_init(&vd->vdev_initialize_cv, NULL, CV_DEFAULT, NULL);
787 	cv_init(&vd->vdev_initialize_io_cv, NULL, CV_DEFAULT, NULL);
788 
789 	mutex_init(&vd->vdev_trim_lock, NULL, MUTEX_DEFAULT, NULL);
790 	mutex_init(&vd->vdev_autotrim_lock, NULL, MUTEX_DEFAULT, NULL);
791 	mutex_init(&vd->vdev_trim_io_lock, NULL, MUTEX_DEFAULT, NULL);
792 	cv_init(&vd->vdev_trim_cv, NULL, CV_DEFAULT, NULL);
793 	cv_init(&vd->vdev_autotrim_cv, NULL, CV_DEFAULT, NULL);
794 	cv_init(&vd->vdev_autotrim_kick_cv, NULL, CV_DEFAULT, NULL);
795 	cv_init(&vd->vdev_trim_io_cv, NULL, CV_DEFAULT, NULL);
796 
797 	mutex_init(&vd->vdev_rebuild_lock, NULL, MUTEX_DEFAULT, NULL);
798 	cv_init(&vd->vdev_rebuild_cv, NULL, CV_DEFAULT, NULL);
799 
800 	for (int t = 0; t < DTL_TYPES; t++) {
801 		vd->vdev_dtl[t] = zfs_range_tree_create_flags(
802 		    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
803 		    ZFS_RT_F_DYN_NAME, vdev_rt_name_dtl(vd, "vdev_dtl", t));
804 	}
805 
806 	txg_list_create(&vd->vdev_ms_list, spa,
807 	    offsetof(struct metaslab, ms_txg_node));
808 	txg_list_create(&vd->vdev_dtl_list, spa,
809 	    offsetof(struct vdev, vdev_dtl_node));
810 	vd->vdev_stat.vs_timestamp = gethrtime();
811 	vdev_queue_init(vd);
812 
813 	return (vd);
814 }
815 
816 /*
817  * Allocate a new vdev.  The 'alloctype' is used to control whether we are
818  * creating a new vdev or loading an existing one - the behavior is slightly
819  * different for each case.
820  */
821 int
vdev_alloc(spa_t * spa,vdev_t ** vdp,nvlist_t * nv,vdev_t * parent,uint_t id,int alloctype)822 vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
823     int alloctype)
824 {
825 	vdev_ops_t *ops;
826 	const char *type;
827 	uint64_t guid = 0, islog;
828 	vdev_t *vd;
829 	vdev_indirect_config_t *vic;
830 	const char *tmp = NULL;
831 	int rc;
832 	vdev_alloc_bias_t alloc_bias = VDEV_BIAS_NONE;
833 	boolean_t top_level = (parent && !parent->vdev_parent);
834 
835 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
836 
837 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
838 		return (SET_ERROR(EINVAL));
839 
840 	if ((ops = vdev_getops(type)) == NULL)
841 		return (SET_ERROR(EINVAL));
842 
843 	/*
844 	 * If this is a load, get the vdev guid from the nvlist.
845 	 * Otherwise, vdev_alloc_common() will generate one for us.
846 	 */
847 	if (alloctype == VDEV_ALLOC_LOAD) {
848 		uint64_t label_id;
849 
850 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID, &label_id) ||
851 		    label_id != id)
852 			return (SET_ERROR(EINVAL));
853 
854 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
855 			return (SET_ERROR(EINVAL));
856 	} else if (alloctype == VDEV_ALLOC_SPARE) {
857 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
858 			return (SET_ERROR(EINVAL));
859 	} else if (alloctype == VDEV_ALLOC_L2CACHE) {
860 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
861 			return (SET_ERROR(EINVAL));
862 	} else if (alloctype == VDEV_ALLOC_ROOTPOOL) {
863 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
864 			return (SET_ERROR(EINVAL));
865 	}
866 
867 	/*
868 	 * The first allocated vdev must be of type 'root'.
869 	 */
870 	if (ops != &vdev_root_ops && spa->spa_root_vdev == NULL)
871 		return (SET_ERROR(EINVAL));
872 
873 	/*
874 	 * Determine whether we're a log vdev.
875 	 */
876 	islog = 0;
877 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &islog);
878 	if (islog && spa_version(spa) < SPA_VERSION_SLOGS)
879 		return (SET_ERROR(ENOTSUP));
880 
881 	if (ops == &vdev_hole_ops && spa_version(spa) < SPA_VERSION_HOLES)
882 		return (SET_ERROR(ENOTSUP));
883 
884 	if (top_level && alloctype == VDEV_ALLOC_ADD) {
885 		const char *bias;
886 
887 		/*
888 		 * If creating a top-level vdev, check for allocation
889 		 * classes input.
890 		 */
891 		if (nvlist_lookup_string(nv, ZPOOL_CONFIG_ALLOCATION_BIAS,
892 		    &bias) == 0) {
893 			alloc_bias = vdev_derive_alloc_bias(bias);
894 
895 			/* spa_vdev_add() expects feature to be enabled */
896 			if (spa->spa_load_state != SPA_LOAD_CREATE &&
897 			    !spa_feature_is_enabled(spa,
898 			    SPA_FEATURE_ALLOCATION_CLASSES)) {
899 				return (SET_ERROR(ENOTSUP));
900 			}
901 		}
902 
903 		/* spa_vdev_add() expects feature to be enabled */
904 		if (ops == &vdev_draid_ops &&
905 		    spa->spa_load_state != SPA_LOAD_CREATE &&
906 		    !spa_feature_is_enabled(spa, SPA_FEATURE_DRAID)) {
907 			return (SET_ERROR(ENOTSUP));
908 		}
909 	}
910 
911 	/*
912 	 * Initialize the vdev specific data.  This is done before calling
913 	 * vdev_alloc_common() since it may fail and this simplifies the
914 	 * error reporting and cleanup code paths.
915 	 */
916 	void *tsd = NULL;
917 	if (ops->vdev_op_init != NULL) {
918 		rc = ops->vdev_op_init(spa, nv, &tsd);
919 		if (rc != 0) {
920 			return (rc);
921 		}
922 	}
923 
924 	vd = vdev_alloc_common(spa, id, guid, ops);
925 	vd->vdev_tsd = tsd;
926 	vd->vdev_islog = islog;
927 
928 	if (top_level && alloc_bias != VDEV_BIAS_NONE)
929 		vd->vdev_alloc_bias = alloc_bias;
930 
931 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &tmp) == 0)
932 		vd->vdev_path = spa_strdup(tmp);
933 
934 	/*
935 	 * ZPOOL_CONFIG_AUX_STATE = "external" means we previously forced a
936 	 * fault on a vdev and want it to persist across imports (like with
937 	 * zpool offline -f).
938 	 */
939 	rc = nvlist_lookup_string(nv, ZPOOL_CONFIG_AUX_STATE, &tmp);
940 	if (rc == 0 && tmp != NULL && strcmp(tmp, "external") == 0) {
941 		vd->vdev_stat.vs_aux = VDEV_AUX_EXTERNAL;
942 		vd->vdev_faulted = 1;
943 		vd->vdev_label_aux = VDEV_AUX_EXTERNAL;
944 	}
945 
946 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &tmp) == 0)
947 		vd->vdev_devid = spa_strdup(tmp);
948 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PHYS_PATH, &tmp) == 0)
949 		vd->vdev_physpath = spa_strdup(tmp);
950 
951 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_VDEV_ENC_SYSFS_PATH,
952 	    &tmp) == 0)
953 		vd->vdev_enc_sysfs_path = spa_strdup(tmp);
954 
955 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_FRU, &tmp) == 0)
956 		vd->vdev_fru = spa_strdup(tmp);
957 
958 	/*
959 	 * Set the whole_disk property.  If it's not specified, leave the value
960 	 * as -1.
961 	 */
962 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
963 	    &vd->vdev_wholedisk) != 0)
964 		vd->vdev_wholedisk = -1ULL;
965 
966 	vic = &vd->vdev_indirect_config;
967 
968 	ASSERT0(vic->vic_mapping_object);
969 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_INDIRECT_OBJECT,
970 	    &vic->vic_mapping_object);
971 	ASSERT0(vic->vic_births_object);
972 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_INDIRECT_BIRTHS,
973 	    &vic->vic_births_object);
974 	ASSERT3U(vic->vic_prev_indirect_vdev, ==, UINT64_MAX);
975 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_PREV_INDIRECT_VDEV,
976 	    &vic->vic_prev_indirect_vdev);
977 
978 	/*
979 	 * Look for the 'not present' flag.  This will only be set if the device
980 	 * was not present at the time of import.
981 	 */
982 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
983 	    &vd->vdev_not_present);
984 
985 	/*
986 	 * Get the alignment requirement. Ignore pool ashift for vdev
987 	 * attach case.
988 	 */
989 	if (alloctype != VDEV_ALLOC_ATTACH) {
990 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT,
991 		    &vd->vdev_ashift);
992 	} else {
993 		vd->vdev_attaching = B_TRUE;
994 	}
995 
996 	/*
997 	 * Retrieve the vdev creation time.
998 	 */
999 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_CREATE_TXG,
1000 	    &vd->vdev_crtxg);
1001 
1002 	if (vd->vdev_ops == &vdev_root_ops &&
1003 	    (alloctype == VDEV_ALLOC_LOAD ||
1004 	    alloctype == VDEV_ALLOC_SPLIT ||
1005 	    alloctype == VDEV_ALLOC_ROOTPOOL)) {
1006 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_VDEV_ROOT_ZAP,
1007 		    &vd->vdev_root_zap);
1008 	}
1009 
1010 	/*
1011 	 * If we're a top-level vdev, try to load the allocation parameters.
1012 	 */
1013 	if (top_level &&
1014 	    (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
1015 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
1016 		    &vd->vdev_ms_array);
1017 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
1018 		    &vd->vdev_ms_shift);
1019 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASIZE,
1020 		    &vd->vdev_asize);
1021 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NONALLOCATING,
1022 		    &vd->vdev_noalloc);
1023 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVING,
1024 		    &vd->vdev_removing);
1025 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_VDEV_TOP_ZAP,
1026 		    &vd->vdev_top_zap);
1027 		vd->vdev_rz_expanding = nvlist_exists(nv,
1028 		    ZPOOL_CONFIG_RAIDZ_EXPANDING);
1029 	} else {
1030 		ASSERT0(vd->vdev_top_zap);
1031 	}
1032 
1033 	if (top_level && alloctype != VDEV_ALLOC_ATTACH) {
1034 		ASSERT(alloctype == VDEV_ALLOC_LOAD ||
1035 		    alloctype == VDEV_ALLOC_ADD ||
1036 		    alloctype == VDEV_ALLOC_SPLIT ||
1037 		    alloctype == VDEV_ALLOC_ROOTPOOL);
1038 		/* Note: metaslab_group_create() is now deferred */
1039 	}
1040 
1041 	if (vd->vdev_ops->vdev_op_leaf &&
1042 	    (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
1043 		(void) nvlist_lookup_uint64(nv,
1044 		    ZPOOL_CONFIG_VDEV_LEAF_ZAP, &vd->vdev_leaf_zap);
1045 	} else {
1046 		ASSERT0(vd->vdev_leaf_zap);
1047 	}
1048 
1049 	/*
1050 	 * If we're a leaf vdev, try to load the DTL object and other state.
1051 	 */
1052 
1053 	if (vd->vdev_ops->vdev_op_leaf &&
1054 	    (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_L2CACHE ||
1055 	    alloctype == VDEV_ALLOC_ROOTPOOL)) {
1056 		if (alloctype == VDEV_ALLOC_LOAD) {
1057 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DTL,
1058 			    &vd->vdev_dtl_object);
1059 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_UNSPARE,
1060 			    &vd->vdev_unspare);
1061 		}
1062 
1063 		if (alloctype == VDEV_ALLOC_ROOTPOOL) {
1064 			uint64_t spare = 0;
1065 
1066 			if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
1067 			    &spare) == 0 && spare)
1068 				spa_spare_add(vd);
1069 		}
1070 
1071 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE,
1072 		    &vd->vdev_offline);
1073 
1074 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_RESILVER_TXG,
1075 		    &vd->vdev_resilver_txg);
1076 
1077 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REBUILD_TXG,
1078 		    &vd->vdev_rebuild_txg);
1079 
1080 		if (nvlist_exists(nv, ZPOOL_CONFIG_RESILVER_DEFER))
1081 			vdev_defer_resilver(vd);
1082 
1083 		/*
1084 		 * In general, when importing a pool we want to ignore the
1085 		 * persistent fault state, as the diagnosis made on another
1086 		 * system may not be valid in the current context.  The only
1087 		 * exception is if we forced a vdev to a persistently faulted
1088 		 * state with 'zpool offline -f'.  The persistent fault will
1089 		 * remain across imports until cleared.
1090 		 *
1091 		 * Local vdevs will remain in the faulted state.
1092 		 */
1093 		if (spa_load_state(spa) == SPA_LOAD_OPEN ||
1094 		    spa_load_state(spa) == SPA_LOAD_IMPORT) {
1095 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED,
1096 			    &vd->vdev_faulted);
1097 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DEGRADED,
1098 			    &vd->vdev_degraded);
1099 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED,
1100 			    &vd->vdev_removed);
1101 
1102 			if (vd->vdev_faulted || vd->vdev_degraded) {
1103 				const char *aux;
1104 
1105 				vd->vdev_label_aux =
1106 				    VDEV_AUX_ERR_EXCEEDED;
1107 				if (nvlist_lookup_string(nv,
1108 				    ZPOOL_CONFIG_AUX_STATE, &aux) == 0 &&
1109 				    strcmp(aux, "external") == 0)
1110 					vd->vdev_label_aux = VDEV_AUX_EXTERNAL;
1111 				else
1112 					vd->vdev_faulted = 0ULL;
1113 			}
1114 		}
1115 	}
1116 
1117 	if (top_level && (ops == &vdev_raidz_ops || ops == &vdev_draid_ops))
1118 		vd->vdev_autosit =
1119 		    vdev_prop_default_numeric(VDEV_PROP_AUTOSIT);
1120 
1121 	/*
1122 	 * Add ourselves to the parent's list of children.
1123 	 */
1124 	vdev_add_child(parent, vd);
1125 
1126 	*vdp = vd;
1127 
1128 	return (0);
1129 }
1130 
1131 void
vdev_free(vdev_t * vd)1132 vdev_free(vdev_t *vd)
1133 {
1134 	spa_t *spa = vd->vdev_spa;
1135 
1136 	ASSERT0P(vd->vdev_initialize_thread);
1137 	ASSERT0P(vd->vdev_trim_thread);
1138 	ASSERT0P(vd->vdev_autotrim_thread);
1139 	ASSERT0P(vd->vdev_rebuild_thread);
1140 
1141 	/*
1142 	 * Scan queues are normally destroyed at the end of a scan. If the
1143 	 * queue exists here, that implies the vdev is being removed while
1144 	 * the scan is still running.
1145 	 */
1146 	if (vd->vdev_scan_io_queue != NULL) {
1147 		mutex_enter(&vd->vdev_scan_io_queue_lock);
1148 		dsl_scan_io_queue_destroy(vd->vdev_scan_io_queue);
1149 		vd->vdev_scan_io_queue = NULL;
1150 		mutex_exit(&vd->vdev_scan_io_queue_lock);
1151 	}
1152 
1153 	/*
1154 	 * vdev_free() implies closing the vdev first.  This is simpler than
1155 	 * trying to ensure complicated semantics for all callers.
1156 	 */
1157 	vdev_close(vd);
1158 
1159 	ASSERT(!list_link_active(&vd->vdev_config_dirty_node));
1160 	ASSERT(!list_link_active(&vd->vdev_state_dirty_node));
1161 
1162 	/*
1163 	 * Free all children.
1164 	 */
1165 	for (int c = 0; c < vd->vdev_children; c++)
1166 		vdev_free(vd->vdev_child[c]);
1167 
1168 	ASSERT0P(vd->vdev_child);
1169 	ASSERT(vd->vdev_guid_sum == vd->vdev_guid);
1170 
1171 	if (vd->vdev_ops->vdev_op_fini != NULL)
1172 		vd->vdev_ops->vdev_op_fini(vd);
1173 
1174 	/*
1175 	 * Discard allocation state.
1176 	 */
1177 	if (vd->vdev_mg != NULL) {
1178 		vdev_metaslab_fini(vd);
1179 		metaslab_group_destroy(vd->vdev_mg);
1180 		vd->vdev_mg = NULL;
1181 	}
1182 	if (vd->vdev_log_mg != NULL) {
1183 		ASSERT0(vd->vdev_ms_count);
1184 		metaslab_group_destroy(vd->vdev_log_mg);
1185 		vd->vdev_log_mg = NULL;
1186 	}
1187 
1188 	ASSERT0(vd->vdev_stat.vs_space);
1189 	ASSERT0(vd->vdev_stat.vs_dspace);
1190 	ASSERT0(vd->vdev_stat.vs_alloc);
1191 
1192 	/*
1193 	 * Remove this vdev from its parent's child list.
1194 	 */
1195 	vdev_remove_child(vd->vdev_parent, vd);
1196 
1197 	ASSERT0P(vd->vdev_parent);
1198 	ASSERT(!list_link_active(&vd->vdev_leaf_node));
1199 
1200 	/*
1201 	 * Clean up vdev structure.
1202 	 */
1203 	vdev_queue_fini(vd);
1204 
1205 	if (vd->vdev_path)
1206 		spa_strfree(vd->vdev_path);
1207 	if (vd->vdev_devid)
1208 		spa_strfree(vd->vdev_devid);
1209 	if (vd->vdev_physpath)
1210 		spa_strfree(vd->vdev_physpath);
1211 
1212 	if (vd->vdev_enc_sysfs_path)
1213 		spa_strfree(vd->vdev_enc_sysfs_path);
1214 
1215 	if (vd->vdev_fru)
1216 		spa_strfree(vd->vdev_fru);
1217 
1218 	if (vd->vdev_isspare)
1219 		spa_spare_remove(vd);
1220 	if (vd->vdev_isl2cache)
1221 		spa_l2cache_remove(vd);
1222 	if (vd->vdev_prev_histo)
1223 		kmem_free(vd->vdev_prev_histo,
1224 		    sizeof (uint64_t) * VDEV_L_HISTO_BUCKETS);
1225 
1226 	txg_list_destroy(&vd->vdev_ms_list);
1227 	txg_list_destroy(&vd->vdev_dtl_list);
1228 
1229 	mutex_enter(&vd->vdev_dtl_lock);
1230 	space_map_close(vd->vdev_dtl_sm);
1231 	for (int t = 0; t < DTL_TYPES; t++) {
1232 		zfs_range_tree_vacate(vd->vdev_dtl[t], NULL, NULL);
1233 		zfs_range_tree_destroy(vd->vdev_dtl[t]);
1234 	}
1235 	mutex_exit(&vd->vdev_dtl_lock);
1236 
1237 	EQUIV(vd->vdev_indirect_births != NULL,
1238 	    vd->vdev_indirect_mapping != NULL);
1239 	if (vd->vdev_indirect_births != NULL) {
1240 		vdev_indirect_mapping_close(vd->vdev_indirect_mapping);
1241 		vdev_indirect_births_close(vd->vdev_indirect_births);
1242 	}
1243 
1244 	if (vd->vdev_obsolete_sm != NULL) {
1245 		ASSERT(vd->vdev_removing ||
1246 		    vd->vdev_ops == &vdev_indirect_ops);
1247 		space_map_close(vd->vdev_obsolete_sm);
1248 		vd->vdev_obsolete_sm = NULL;
1249 	}
1250 	zfs_range_tree_destroy(vd->vdev_obsolete_segments);
1251 	rw_destroy(&vd->vdev_indirect_rwlock);
1252 	mutex_destroy(&vd->vdev_obsolete_lock);
1253 
1254 	mutex_destroy(&vd->vdev_dtl_lock);
1255 	mutex_destroy(&vd->vdev_stat_lock);
1256 	mutex_destroy(&vd->vdev_probe_lock);
1257 	mutex_destroy(&vd->vdev_scan_io_queue_lock);
1258 
1259 	mutex_destroy(&vd->vdev_initialize_lock);
1260 	mutex_destroy(&vd->vdev_initialize_io_lock);
1261 	cv_destroy(&vd->vdev_initialize_io_cv);
1262 	cv_destroy(&vd->vdev_initialize_cv);
1263 
1264 	mutex_destroy(&vd->vdev_trim_lock);
1265 	mutex_destroy(&vd->vdev_autotrim_lock);
1266 	mutex_destroy(&vd->vdev_trim_io_lock);
1267 	cv_destroy(&vd->vdev_trim_cv);
1268 	cv_destroy(&vd->vdev_autotrim_cv);
1269 	cv_destroy(&vd->vdev_autotrim_kick_cv);
1270 	cv_destroy(&vd->vdev_trim_io_cv);
1271 
1272 	mutex_destroy(&vd->vdev_rebuild_lock);
1273 	cv_destroy(&vd->vdev_rebuild_cv);
1274 
1275 	zfs_ratelimit_fini(&vd->vdev_delay_rl);
1276 	zfs_ratelimit_fini(&vd->vdev_deadman_rl);
1277 	zfs_ratelimit_fini(&vd->vdev_dio_verify_rl);
1278 	zfs_ratelimit_fini(&vd->vdev_checksum_rl);
1279 
1280 	if (vd == spa->spa_root_vdev)
1281 		spa->spa_root_vdev = NULL;
1282 
1283 	kmem_free(vd, sizeof (vdev_t));
1284 }
1285 
1286 /*
1287  * Transfer top-level vdev state from svd to tvd.
1288  */
1289 static void
vdev_top_transfer(vdev_t * svd,vdev_t * tvd)1290 vdev_top_transfer(vdev_t *svd, vdev_t *tvd)
1291 {
1292 	spa_t *spa = svd->vdev_spa;
1293 	metaslab_t *msp;
1294 	vdev_t *vd;
1295 	int t;
1296 
1297 	ASSERT(tvd == tvd->vdev_top);
1298 
1299 	tvd->vdev_ms_array = svd->vdev_ms_array;
1300 	tvd->vdev_ms_shift = svd->vdev_ms_shift;
1301 	tvd->vdev_ms_count = svd->vdev_ms_count;
1302 	tvd->vdev_top_zap = svd->vdev_top_zap;
1303 
1304 	svd->vdev_ms_array = 0;
1305 	svd->vdev_ms_shift = 0;
1306 	svd->vdev_ms_count = 0;
1307 	svd->vdev_top_zap = 0;
1308 
1309 	if (tvd->vdev_mg)
1310 		ASSERT3P(tvd->vdev_mg, ==, svd->vdev_mg);
1311 	if (tvd->vdev_log_mg)
1312 		ASSERT3P(tvd->vdev_log_mg, ==, svd->vdev_log_mg);
1313 	tvd->vdev_mg = svd->vdev_mg;
1314 	tvd->vdev_log_mg = svd->vdev_log_mg;
1315 	tvd->vdev_ms = svd->vdev_ms;
1316 
1317 	svd->vdev_mg = NULL;
1318 	svd->vdev_log_mg = NULL;
1319 	svd->vdev_ms = NULL;
1320 
1321 	if (tvd->vdev_mg != NULL)
1322 		tvd->vdev_mg->mg_vd = tvd;
1323 	if (tvd->vdev_log_mg != NULL)
1324 		tvd->vdev_log_mg->mg_vd = tvd;
1325 
1326 	tvd->vdev_checkpoint_sm = svd->vdev_checkpoint_sm;
1327 	svd->vdev_checkpoint_sm = NULL;
1328 
1329 	tvd->vdev_alloc_bias = svd->vdev_alloc_bias;
1330 	svd->vdev_alloc_bias = VDEV_BIAS_NONE;
1331 
1332 	tvd->vdev_stat.vs_alloc = svd->vdev_stat.vs_alloc;
1333 	tvd->vdev_stat.vs_space = svd->vdev_stat.vs_space;
1334 	tvd->vdev_stat.vs_dspace = svd->vdev_stat.vs_dspace;
1335 
1336 	svd->vdev_stat.vs_alloc = 0;
1337 	svd->vdev_stat.vs_space = 0;
1338 	svd->vdev_stat.vs_dspace = 0;
1339 
1340 	/*
1341 	 * State which may be set on a top-level vdev that's in the
1342 	 * process of being removed.
1343 	 */
1344 	ASSERT0(tvd->vdev_indirect_config.vic_births_object);
1345 	ASSERT0(tvd->vdev_indirect_config.vic_mapping_object);
1346 	ASSERT3U(tvd->vdev_indirect_config.vic_prev_indirect_vdev, ==, -1ULL);
1347 	ASSERT0P(tvd->vdev_indirect_mapping);
1348 	ASSERT0P(tvd->vdev_indirect_births);
1349 	ASSERT0P(tvd->vdev_obsolete_sm);
1350 	ASSERT0(tvd->vdev_noalloc);
1351 	ASSERT0(tvd->vdev_removing);
1352 	ASSERT0(tvd->vdev_rebuilding);
1353 	tvd->vdev_noalloc = svd->vdev_noalloc;
1354 	tvd->vdev_removing = svd->vdev_removing;
1355 	tvd->vdev_rebuilding = svd->vdev_rebuilding;
1356 	tvd->vdev_rebuild_config = svd->vdev_rebuild_config;
1357 	tvd->vdev_indirect_config = svd->vdev_indirect_config;
1358 	tvd->vdev_indirect_mapping = svd->vdev_indirect_mapping;
1359 	tvd->vdev_indirect_births = svd->vdev_indirect_births;
1360 	zfs_range_tree_swap(&svd->vdev_obsolete_segments,
1361 	    &tvd->vdev_obsolete_segments);
1362 	tvd->vdev_obsolete_sm = svd->vdev_obsolete_sm;
1363 	svd->vdev_indirect_config.vic_mapping_object = 0;
1364 	svd->vdev_indirect_config.vic_births_object = 0;
1365 	svd->vdev_indirect_config.vic_prev_indirect_vdev = -1ULL;
1366 	svd->vdev_indirect_mapping = NULL;
1367 	svd->vdev_indirect_births = NULL;
1368 	svd->vdev_obsolete_sm = NULL;
1369 	svd->vdev_noalloc = 0;
1370 	svd->vdev_removing = 0;
1371 	svd->vdev_rebuilding = 0;
1372 
1373 	for (t = 0; t < TXG_SIZE; t++) {
1374 		while ((msp = txg_list_remove(&svd->vdev_ms_list, t)) != NULL)
1375 			(void) txg_list_add(&tvd->vdev_ms_list, msp, t);
1376 		while ((vd = txg_list_remove(&svd->vdev_dtl_list, t)) != NULL)
1377 			(void) txg_list_add(&tvd->vdev_dtl_list, vd, t);
1378 		if (txg_list_remove_this(&spa->spa_vdev_txg_list, svd, t))
1379 			(void) txg_list_add(&spa->spa_vdev_txg_list, tvd, t);
1380 	}
1381 
1382 	if (list_link_active(&svd->vdev_config_dirty_node)) {
1383 		vdev_config_clean(svd);
1384 		vdev_config_dirty(tvd);
1385 	}
1386 
1387 	if (list_link_active(&svd->vdev_state_dirty_node)) {
1388 		vdev_state_clean(svd);
1389 		vdev_state_dirty(tvd);
1390 	}
1391 
1392 	tvd->vdev_deflate_ratio = svd->vdev_deflate_ratio;
1393 	svd->vdev_deflate_ratio = 0;
1394 
1395 	tvd->vdev_islog = svd->vdev_islog;
1396 	svd->vdev_islog = 0;
1397 
1398 	dsl_scan_io_queue_vdev_xfer(svd, tvd);
1399 }
1400 
1401 static void
vdev_top_update(vdev_t * tvd,vdev_t * vd)1402 vdev_top_update(vdev_t *tvd, vdev_t *vd)
1403 {
1404 	if (vd == NULL)
1405 		return;
1406 
1407 	vd->vdev_top = tvd;
1408 
1409 	for (int c = 0; c < vd->vdev_children; c++)
1410 		vdev_top_update(tvd, vd->vdev_child[c]);
1411 }
1412 
1413 /*
1414  * Add a mirror/replacing vdev above an existing vdev.  There is no need to
1415  * call .vdev_op_init() since mirror/replacing vdevs do not have private state.
1416  */
1417 vdev_t *
vdev_add_parent(vdev_t * cvd,vdev_ops_t * ops)1418 vdev_add_parent(vdev_t *cvd, vdev_ops_t *ops)
1419 {
1420 	spa_t *spa = cvd->vdev_spa;
1421 	vdev_t *pvd = cvd->vdev_parent;
1422 	vdev_t *mvd;
1423 
1424 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1425 
1426 	mvd = vdev_alloc_common(spa, cvd->vdev_id, 0, ops);
1427 
1428 	mvd->vdev_asize = cvd->vdev_asize;
1429 	mvd->vdev_min_asize = cvd->vdev_min_asize;
1430 	mvd->vdev_max_asize = cvd->vdev_max_asize;
1431 	mvd->vdev_psize = cvd->vdev_psize;
1432 	mvd->vdev_ashift = cvd->vdev_ashift;
1433 	mvd->vdev_logical_ashift = cvd->vdev_logical_ashift;
1434 	mvd->vdev_physical_ashift = cvd->vdev_physical_ashift;
1435 	mvd->vdev_state = cvd->vdev_state;
1436 	mvd->vdev_crtxg = cvd->vdev_crtxg;
1437 	mvd->vdev_nonrot = cvd->vdev_nonrot;
1438 
1439 	vdev_remove_child(pvd, cvd);
1440 	vdev_add_child(pvd, mvd);
1441 	cvd->vdev_id = mvd->vdev_children;
1442 	vdev_add_child(mvd, cvd);
1443 	vdev_top_update(cvd->vdev_top, cvd->vdev_top);
1444 
1445 	if (mvd == mvd->vdev_top)
1446 		vdev_top_transfer(cvd, mvd);
1447 
1448 	return (mvd);
1449 }
1450 
1451 /*
1452  * Remove a 1-way mirror/replacing vdev from the tree.
1453  */
1454 void
vdev_remove_parent(vdev_t * cvd)1455 vdev_remove_parent(vdev_t *cvd)
1456 {
1457 	vdev_t *mvd = cvd->vdev_parent;
1458 	vdev_t *pvd = mvd->vdev_parent;
1459 
1460 	ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1461 
1462 	ASSERT(mvd->vdev_children == 1);
1463 	ASSERT(mvd->vdev_ops == &vdev_mirror_ops ||
1464 	    mvd->vdev_ops == &vdev_replacing_ops ||
1465 	    mvd->vdev_ops == &vdev_spare_ops);
1466 	cvd->vdev_ashift = mvd->vdev_ashift;
1467 	cvd->vdev_logical_ashift = mvd->vdev_logical_ashift;
1468 	cvd->vdev_physical_ashift = mvd->vdev_physical_ashift;
1469 	vdev_remove_child(mvd, cvd);
1470 	vdev_remove_child(pvd, mvd);
1471 
1472 	/*
1473 	 * If cvd will replace mvd as a top-level vdev, preserve mvd's guid.
1474 	 * Otherwise, we could have detached an offline device, and when we
1475 	 * go to import the pool we'll think we have two top-level vdevs,
1476 	 * instead of a different version of the same top-level vdev.
1477 	 */
1478 	if (mvd->vdev_top == mvd) {
1479 		uint64_t guid_delta = mvd->vdev_guid - cvd->vdev_guid;
1480 		cvd->vdev_orig_guid = cvd->vdev_guid;
1481 		cvd->vdev_guid += guid_delta;
1482 		cvd->vdev_guid_sum += guid_delta;
1483 
1484 		/*
1485 		 * If pool not set for autoexpand, we need to also preserve
1486 		 * mvd's asize to prevent automatic expansion of cvd.
1487 		 * Otherwise if we are adjusting the mirror by attaching and
1488 		 * detaching children of non-uniform sizes, the mirror could
1489 		 * autoexpand, unexpectedly requiring larger devices to
1490 		 * re-establish the mirror.
1491 		 */
1492 		if (!cvd->vdev_spa->spa_autoexpand)
1493 			cvd->vdev_asize = mvd->vdev_asize;
1494 	}
1495 	cvd->vdev_id = mvd->vdev_id;
1496 	vdev_add_child(pvd, cvd);
1497 	vdev_top_update(cvd->vdev_top, cvd->vdev_top);
1498 
1499 	if (cvd == cvd->vdev_top)
1500 		vdev_top_transfer(mvd, cvd);
1501 
1502 	ASSERT0(mvd->vdev_children);
1503 	vdev_free(mvd);
1504 }
1505 
1506 /*
1507  * Choose GCD for spa_gcd_alloc.
1508  */
1509 static uint64_t
vdev_gcd(uint64_t a,uint64_t b)1510 vdev_gcd(uint64_t a, uint64_t b)
1511 {
1512 	while (b != 0) {
1513 		uint64_t t = b;
1514 		b = a % b;
1515 		a = t;
1516 	}
1517 	return (a);
1518 }
1519 
1520 /*
1521  * Set spa_min_alloc and spa_gcd_alloc.
1522  */
1523 static void
vdev_spa_set_alloc(spa_t * spa,uint64_t min_alloc)1524 vdev_spa_set_alloc(spa_t *spa, uint64_t min_alloc)
1525 {
1526 	if (min_alloc < spa->spa_min_alloc)
1527 		spa->spa_min_alloc = min_alloc;
1528 
1529 	if (min_alloc > spa->spa_max_alloc)
1530 		spa->spa_max_alloc = min_alloc;
1531 
1532 	if (spa->spa_gcd_alloc == INT_MAX)
1533 		spa->spa_gcd_alloc = min_alloc;
1534 	else
1535 		spa->spa_gcd_alloc = vdev_gcd(min_alloc, spa->spa_gcd_alloc);
1536 }
1537 
1538 void
vdev_metaslab_group_create(vdev_t * vd)1539 vdev_metaslab_group_create(vdev_t *vd)
1540 {
1541 	spa_t *spa = vd->vdev_spa;
1542 
1543 	/*
1544 	 * metaslab_group_create was delayed until allocation bias was available
1545 	 */
1546 	if (vd->vdev_mg == NULL) {
1547 		metaslab_class_t *mc;
1548 
1549 		if (vd->vdev_islog && vd->vdev_alloc_bias == VDEV_BIAS_NONE)
1550 			vd->vdev_alloc_bias = VDEV_BIAS_LOG;
1551 
1552 		ASSERT3U(vd->vdev_islog, ==,
1553 		    (vd->vdev_alloc_bias == VDEV_BIAS_LOG));
1554 
1555 		switch (vd->vdev_alloc_bias) {
1556 		case VDEV_BIAS_LOG:
1557 			mc = spa_log_class(spa);
1558 			break;
1559 		case VDEV_BIAS_SPECIAL:
1560 			mc = spa_special_class(spa);
1561 			break;
1562 		case VDEV_BIAS_DEDUP:
1563 			mc = spa_dedup_class(spa);
1564 			break;
1565 		default:
1566 			mc = spa_normal_class(spa);
1567 		}
1568 
1569 		vd->vdev_mg = metaslab_group_create(mc, vd);
1570 
1571 		if (!vd->vdev_islog) {
1572 			if (mc == spa_special_class(spa)) {
1573 				vd->vdev_log_mg = metaslab_group_create(
1574 				    spa_special_embedded_log_class(spa), vd);
1575 			} else {
1576 				vd->vdev_log_mg = metaslab_group_create(
1577 				    spa_embedded_log_class(spa), vd);
1578 			}
1579 		}
1580 
1581 		/*
1582 		 * The spa ashift min/max only apply for the normal metaslab
1583 		 * class. Class destination is late binding so ashift boundary
1584 		 * setting had to wait until now.
1585 		 */
1586 		if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
1587 		    mc == spa_normal_class(spa) && vd->vdev_aux == NULL) {
1588 			if (vd->vdev_ashift > spa->spa_max_ashift)
1589 				spa->spa_max_ashift = vd->vdev_ashift;
1590 			if (vd->vdev_ashift < spa->spa_min_ashift)
1591 				spa->spa_min_ashift = vd->vdev_ashift;
1592 
1593 			vdev_spa_set_alloc(spa, vdev_get_min_alloc(vd));
1594 		}
1595 	}
1596 }
1597 
1598 void
vdev_update_nonallocating_space(vdev_t * vd,boolean_t add)1599 vdev_update_nonallocating_space(vdev_t *vd, boolean_t add)
1600 {
1601 	spa_t *spa = vd->vdev_spa;
1602 
1603 	if (vd->vdev_mg->mg_class != spa_normal_class(spa))
1604 		return;
1605 
1606 	uint64_t raw_space = metaslab_group_get_space(vd->vdev_mg);
1607 	uint64_t dspace = spa_deflate(spa) ?
1608 	    vdev_deflated_space(vd, raw_space) : raw_space;
1609 	if (add) {
1610 		spa->spa_nonallocating_dspace += dspace;
1611 	} else {
1612 		ASSERT3U(spa->spa_nonallocating_dspace, >=, dspace);
1613 		spa->spa_nonallocating_dspace -= dspace;
1614 	}
1615 }
1616 
1617 int
vdev_metaslab_init(vdev_t * vd,uint64_t txg)1618 vdev_metaslab_init(vdev_t *vd, uint64_t txg)
1619 {
1620 	spa_t *spa = vd->vdev_spa;
1621 	uint64_t oldc = vd->vdev_ms_count;
1622 	uint64_t newc = vd->vdev_asize >> vd->vdev_ms_shift;
1623 	metaslab_t **mspp;
1624 	int error;
1625 	boolean_t expanding = (oldc != 0);
1626 
1627 	ASSERT(txg == 0 || spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1628 
1629 	/*
1630 	 * This vdev is not being allocated from yet or is a hole.
1631 	 */
1632 	if (vd->vdev_ms_shift == 0)
1633 		return (0);
1634 
1635 	ASSERT(!vd->vdev_ishole);
1636 
1637 	ASSERT(oldc <= newc);
1638 
1639 	mspp = vmem_zalloc(newc * sizeof (*mspp), KM_SLEEP);
1640 
1641 	if (expanding) {
1642 		memcpy(mspp, vd->vdev_ms, oldc * sizeof (*mspp));
1643 		vmem_free(vd->vdev_ms, oldc * sizeof (*mspp));
1644 	}
1645 
1646 	vd->vdev_ms = mspp;
1647 	vd->vdev_ms_count = newc;
1648 
1649 	/*
1650 	 * Weighting algorithms can depend on the number of metaslabs in the
1651 	 * vdev. In order to ensure that all weights are correct at all times,
1652 	 * we need to recalculate here.
1653 	 */
1654 	for (uint64_t m = 0; m < oldc; m++) {
1655 		metaslab_t *msp = vd->vdev_ms[m];
1656 		mutex_enter(&msp->ms_lock);
1657 		metaslab_recalculate_weight_and_sort(msp);
1658 		mutex_exit(&msp->ms_lock);
1659 	}
1660 
1661 	for (uint64_t m = oldc; m < newc; m++) {
1662 		uint64_t object = 0;
1663 		/*
1664 		 * vdev_ms_array may be 0 if we are creating the "fake"
1665 		 * metaslabs for an indirect vdev for zdb's leak detection.
1666 		 * See zdb_leak_init().
1667 		 */
1668 		if (txg == 0 && vd->vdev_ms_array != 0) {
1669 			error = dmu_read(spa->spa_meta_objset,
1670 			    vd->vdev_ms_array,
1671 			    m * sizeof (uint64_t), sizeof (uint64_t), &object,
1672 			    DMU_READ_PREFETCH);
1673 			if (error != 0) {
1674 				vdev_dbgmsg(vd, "unable to read the metaslab "
1675 				    "array [error=%d]", error);
1676 				return (error);
1677 			}
1678 		}
1679 
1680 		error = metaslab_init(vd->vdev_mg, m, object, txg,
1681 		    &(vd->vdev_ms[m]));
1682 		if (error != 0) {
1683 			vdev_dbgmsg(vd, "metaslab_init failed [error=%d]",
1684 			    error);
1685 			return (error);
1686 		}
1687 	}
1688 
1689 	/*
1690 	 * Find the emptiest metaslab on the vdev and mark it for use for
1691 	 * embedded slog by moving it from the regular to the log metaslab
1692 	 * group.  This works for normal and special vdevs.
1693 	 */
1694 	if ((vd->vdev_mg->mg_class == spa_normal_class(spa) ||
1695 	    vd->vdev_mg->mg_class == spa_special_class(spa)) &&
1696 	    vd->vdev_ms_count > zfs_embedded_slog_min_ms &&
1697 	    avl_is_empty(&vd->vdev_log_mg->mg_metaslab_tree)) {
1698 		uint64_t slog_msid = 0;
1699 		uint64_t smallest = UINT64_MAX;
1700 
1701 		/*
1702 		 * Note, we only search the new metaslabs, because the old
1703 		 * (pre-existing) ones may be active (e.g. have non-empty
1704 		 * range_tree's), and we don't move them to the new
1705 		 * metaslab_t.
1706 		 */
1707 		for (uint64_t m = oldc; m < newc; m++) {
1708 			uint64_t alloc =
1709 			    space_map_allocated(vd->vdev_ms[m]->ms_sm);
1710 			if (alloc < smallest) {
1711 				slog_msid = m;
1712 				smallest = alloc;
1713 			}
1714 		}
1715 		metaslab_t *slog_ms = vd->vdev_ms[slog_msid];
1716 		/*
1717 		 * The metaslab was marked as dirty at the end of
1718 		 * metaslab_init(). Remove it from the dirty list so that we
1719 		 * can uninitialize and reinitialize it to the new class.
1720 		 */
1721 		if (txg != 0) {
1722 			(void) txg_list_remove_this(&vd->vdev_ms_list,
1723 			    slog_ms, txg);
1724 		}
1725 		uint64_t sm_obj = space_map_object(slog_ms->ms_sm);
1726 		metaslab_fini(slog_ms);
1727 		VERIFY0(metaslab_init(vd->vdev_log_mg, slog_msid, sm_obj, txg,
1728 		    &vd->vdev_ms[slog_msid]));
1729 	}
1730 
1731 	if (txg == 0)
1732 		spa_config_enter(spa, SCL_ALLOC, FTAG, RW_WRITER);
1733 
1734 	/*
1735 	 * If the vdev is marked as non-allocating then don't
1736 	 * activate the metaslabs since we want to ensure that
1737 	 * no allocations are performed on this device.
1738 	 */
1739 	if (vd->vdev_noalloc) {
1740 		/* track non-allocating vdev space */
1741 		vdev_update_nonallocating_space(vd, B_TRUE);
1742 	} else if (!expanding) {
1743 		metaslab_group_activate(vd->vdev_mg);
1744 		if (vd->vdev_log_mg != NULL)
1745 			metaslab_group_activate(vd->vdev_log_mg);
1746 	}
1747 
1748 	if (txg == 0)
1749 		spa_config_exit(spa, SCL_ALLOC, FTAG);
1750 
1751 	return (0);
1752 }
1753 
1754 void
vdev_metaslab_fini(vdev_t * vd)1755 vdev_metaslab_fini(vdev_t *vd)
1756 {
1757 	if (vd->vdev_checkpoint_sm != NULL) {
1758 		ASSERT(spa_feature_is_active(vd->vdev_spa,
1759 		    SPA_FEATURE_POOL_CHECKPOINT));
1760 		space_map_close(vd->vdev_checkpoint_sm);
1761 		/*
1762 		 * Even though we close the space map, we need to set its
1763 		 * pointer to NULL. The reason is that vdev_metaslab_fini()
1764 		 * may be called multiple times for certain operations
1765 		 * (i.e. when destroying a pool) so we need to ensure that
1766 		 * this clause never executes twice. This logic is similar
1767 		 * to the one used for the vdev_ms clause below.
1768 		 */
1769 		vd->vdev_checkpoint_sm = NULL;
1770 	}
1771 
1772 	if (vd->vdev_ms != NULL) {
1773 		metaslab_group_t *mg = vd->vdev_mg;
1774 
1775 		metaslab_group_passivate(mg);
1776 		if (vd->vdev_log_mg != NULL) {
1777 			ASSERT(!vd->vdev_islog);
1778 			metaslab_group_passivate(vd->vdev_log_mg);
1779 		}
1780 
1781 		uint64_t count = vd->vdev_ms_count;
1782 		for (uint64_t m = 0; m < count; m++) {
1783 			metaslab_t *msp = vd->vdev_ms[m];
1784 			if (msp != NULL)
1785 				metaslab_fini(msp);
1786 		}
1787 		vmem_free(vd->vdev_ms, count * sizeof (metaslab_t *));
1788 		vd->vdev_ms = NULL;
1789 		vd->vdev_ms_count = 0;
1790 
1791 		for (int i = 0; i < ZFS_RANGE_TREE_HISTOGRAM_SIZE; i++) {
1792 			ASSERT0(mg->mg_histogram[i]);
1793 			if (vd->vdev_log_mg != NULL)
1794 				ASSERT0(vd->vdev_log_mg->mg_histogram[i]);
1795 		}
1796 	}
1797 	ASSERT0(vd->vdev_ms_count);
1798 }
1799 
1800 typedef struct vdev_probe_stats {
1801 	boolean_t	vps_readable;
1802 	boolean_t	vps_writeable;
1803 	boolean_t	vps_zio_done_probe;
1804 	int		vps_flags;
1805 } vdev_probe_stats_t;
1806 
1807 static void
vdev_probe_done(zio_t * zio)1808 vdev_probe_done(zio_t *zio)
1809 {
1810 	spa_t *spa = zio->io_spa;
1811 	vdev_t *vd = zio->io_vd;
1812 	vdev_probe_stats_t *vps = zio->io_private;
1813 
1814 	ASSERT(vd->vdev_probe_zio != NULL);
1815 
1816 	if (zio->io_type == ZIO_TYPE_READ) {
1817 		if (zio->io_error == 0)
1818 			vps->vps_readable = 1;
1819 		if (zio->io_error == 0 && spa_writeable(spa)) {
1820 			zio_nowait(zio_write_phys(vd->vdev_probe_zio, vd,
1821 			    zio->io_offset, zio->io_size, zio->io_abd,
1822 			    ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1823 			    ZIO_PRIORITY_SYNC_WRITE, vps->vps_flags, B_TRUE));
1824 		} else {
1825 			abd_free(zio->io_abd);
1826 		}
1827 	} else if (zio->io_type == ZIO_TYPE_WRITE) {
1828 		if (zio->io_error == 0)
1829 			vps->vps_writeable = 1;
1830 		abd_free(zio->io_abd);
1831 	} else if (zio->io_type == ZIO_TYPE_NULL) {
1832 		zio_t *pio;
1833 		zio_link_t *zl;
1834 
1835 		vd->vdev_cant_read |= !vps->vps_readable;
1836 		vd->vdev_cant_write |= !vps->vps_writeable;
1837 		vdev_dbgmsg(vd, "probe done, cant_read=%u cant_write=%u",
1838 		    vd->vdev_cant_read, vd->vdev_cant_write);
1839 
1840 		if (vdev_readable(vd) &&
1841 		    (vdev_writeable(vd) || !spa_writeable(spa))) {
1842 			zio->io_error = 0;
1843 		} else {
1844 			ASSERT(zio->io_error != 0);
1845 			vdev_dbgmsg(vd, "failed probe");
1846 			(void) zfs_ereport_post(FM_EREPORT_ZFS_PROBE_FAILURE,
1847 			    spa, vd, NULL, NULL, 0);
1848 			zio->io_error = SET_ERROR(ENXIO);
1849 
1850 			/*
1851 			 * If this probe was initiated from zio pipeline, then
1852 			 * change the state in a spa_async_request. Probes that
1853 			 * were initiated from a vdev_open can change the state
1854 			 * as part of the open call.
1855 			 * Skip fault injection if this vdev is already removed
1856 			 * or a removal is pending.
1857 			 */
1858 			if (vps->vps_zio_done_probe &&
1859 			    !vd->vdev_remove_wanted && !vd->vdev_removed) {
1860 				vd->vdev_fault_wanted = B_TRUE;
1861 				spa_async_request(spa, SPA_ASYNC_FAULT_VDEV);
1862 			}
1863 		}
1864 
1865 		mutex_enter(&vd->vdev_probe_lock);
1866 		ASSERT(vd->vdev_probe_zio == zio);
1867 		vd->vdev_probe_zio = NULL;
1868 		mutex_exit(&vd->vdev_probe_lock);
1869 
1870 		zl = NULL;
1871 		while ((pio = zio_walk_parents(zio, &zl)) != NULL)
1872 			if (!vdev_accessible(vd, pio))
1873 				pio->io_error = SET_ERROR(ENXIO);
1874 
1875 		kmem_free(vps, sizeof (*vps));
1876 	}
1877 }
1878 
1879 /*
1880  * Determine whether this device is accessible.
1881  *
1882  * Read and write to several known locations: the pad regions of each
1883  * vdev label but the first, which we leave alone in case it contains
1884  * a VTOC.
1885  */
1886 zio_t *
vdev_probe(vdev_t * vd,zio_t * zio)1887 vdev_probe(vdev_t *vd, zio_t *zio)
1888 {
1889 	spa_t *spa = vd->vdev_spa;
1890 	vdev_probe_stats_t *vps = NULL;
1891 	zio_t *pio;
1892 
1893 	ASSERT(vd->vdev_ops->vdev_op_leaf);
1894 
1895 	/*
1896 	 * Don't probe the probe.
1897 	 */
1898 	if (zio && (zio->io_flags & ZIO_FLAG_PROBE))
1899 		return (NULL);
1900 
1901 	/*
1902 	 * To prevent 'probe storms' when a device fails, we create
1903 	 * just one probe i/o at a time.  All zios that want to probe
1904 	 * this vdev will become parents of the probe io.
1905 	 */
1906 	mutex_enter(&vd->vdev_probe_lock);
1907 
1908 	if ((pio = vd->vdev_probe_zio) == NULL) {
1909 		vps = kmem_zalloc(sizeof (*vps), KM_SLEEP);
1910 
1911 		vps->vps_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_PROBE |
1912 		    ZIO_FLAG_DONT_AGGREGATE | ZIO_FLAG_TRYHARD;
1913 		vps->vps_zio_done_probe = (zio != NULL);
1914 
1915 		if (spa_config_held(spa, SCL_ZIO, RW_WRITER)) {
1916 			/*
1917 			 * vdev_cant_read and vdev_cant_write can only
1918 			 * transition from TRUE to FALSE when we have the
1919 			 * SCL_ZIO lock as writer; otherwise they can only
1920 			 * transition from FALSE to TRUE.  This ensures that
1921 			 * any zio looking at these values can assume that
1922 			 * failures persist for the life of the I/O.  That's
1923 			 * important because when a device has intermittent
1924 			 * connectivity problems, we want to ensure that
1925 			 * they're ascribed to the device (ENXIO) and not
1926 			 * the zio (EIO).
1927 			 *
1928 			 * Since we hold SCL_ZIO as writer here, clear both
1929 			 * values so the probe can reevaluate from first
1930 			 * principles.
1931 			 */
1932 			vps->vps_flags |= ZIO_FLAG_CONFIG_WRITER;
1933 			vd->vdev_cant_read = B_FALSE;
1934 			vd->vdev_cant_write = B_FALSE;
1935 		}
1936 
1937 		vd->vdev_probe_zio = pio = zio_null(NULL, spa, vd,
1938 		    vdev_probe_done, vps,
1939 		    vps->vps_flags | ZIO_FLAG_DONT_PROPAGATE);
1940 	}
1941 
1942 	if (zio != NULL)
1943 		zio_add_child(zio, pio);
1944 
1945 	mutex_exit(&vd->vdev_probe_lock);
1946 
1947 	if (vps == NULL) {
1948 		ASSERT(zio != NULL);
1949 		return (NULL);
1950 	}
1951 
1952 	for (int l = 1; l < VDEV_LABELS; l++) {
1953 		zio_nowait(zio_read_phys(pio, vd,
1954 		    vdev_label_offset(vd->vdev_psize, l,
1955 		    offsetof(vdev_label_t, vl_be)), VDEV_PAD_SIZE,
1956 		    abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE),
1957 		    ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1958 		    ZIO_PRIORITY_SYNC_READ, vps->vps_flags, B_TRUE));
1959 	}
1960 
1961 	if (zio == NULL)
1962 		return (pio);
1963 
1964 	zio_nowait(pio);
1965 	return (NULL);
1966 }
1967 
1968 static void
vdev_load_child(void * arg)1969 vdev_load_child(void *arg)
1970 {
1971 	vdev_t *vd = arg;
1972 
1973 	vd->vdev_load_error = vdev_load(vd);
1974 }
1975 
1976 static void
vdev_open_child(void * arg)1977 vdev_open_child(void *arg)
1978 {
1979 	vdev_t *vd = arg;
1980 
1981 	vd->vdev_open_thread = curthread;
1982 	vd->vdev_open_error = vdev_open(vd);
1983 	vd->vdev_open_thread = NULL;
1984 }
1985 
1986 static boolean_t
vdev_uses_zvols(vdev_t * vd)1987 vdev_uses_zvols(vdev_t *vd)
1988 {
1989 #ifdef _KERNEL
1990 	if (zvol_is_zvol(vd->vdev_path))
1991 		return (B_TRUE);
1992 #endif
1993 
1994 	for (int c = 0; c < vd->vdev_children; c++)
1995 		if (vdev_uses_zvols(vd->vdev_child[c]))
1996 			return (B_TRUE);
1997 
1998 	return (B_FALSE);
1999 }
2000 
2001 /*
2002  * Returns B_TRUE if the passed child should be opened.
2003  */
2004 static boolean_t
vdev_default_open_children_func(vdev_t * vd)2005 vdev_default_open_children_func(vdev_t *vd)
2006 {
2007 	(void) vd;
2008 	return (B_TRUE);
2009 }
2010 
2011 /*
2012  * Open the requested child vdevs.  If any of the leaf vdevs are using
2013  * a ZFS volume then do the opens in a single thread.  This avoids a
2014  * deadlock when the current thread is holding the spa_namespace_lock.
2015  */
2016 static void
vdev_open_children_impl(vdev_t * vd,vdev_open_children_func_t * open_func)2017 vdev_open_children_impl(vdev_t *vd, vdev_open_children_func_t *open_func)
2018 {
2019 	int children = vd->vdev_children;
2020 
2021 	taskq_t *tq = taskq_create("vdev_open", children, minclsyspri,
2022 	    children, children, TASKQ_PREPOPULATE);
2023 	vd->vdev_nonrot = B_TRUE;
2024 
2025 	for (int c = 0; c < children; c++) {
2026 		vdev_t *cvd = vd->vdev_child[c];
2027 
2028 		if (open_func(cvd) == B_FALSE)
2029 			continue;
2030 
2031 		if (tq == NULL || vdev_uses_zvols(vd)) {
2032 			cvd->vdev_open_error = vdev_open(cvd);
2033 		} else {
2034 			VERIFY(taskq_dispatch(tq, vdev_open_child,
2035 			    cvd, TQ_SLEEP) != TASKQID_INVALID);
2036 		}
2037 	}
2038 
2039 	if (tq != NULL)
2040 		taskq_wait(tq);
2041 	for (int c = 0; c < children; c++) {
2042 		vdev_t *cvd = vd->vdev_child[c];
2043 
2044 		if (open_func(cvd) == B_FALSE ||
2045 		    cvd->vdev_state <= VDEV_STATE_FAULTED)
2046 			continue;
2047 		vd->vdev_nonrot &= cvd->vdev_nonrot;
2048 	}
2049 
2050 	if (tq != NULL)
2051 		taskq_destroy(tq);
2052 }
2053 
2054 /*
2055  * Open all child vdevs.
2056  */
2057 void
vdev_open_children(vdev_t * vd)2058 vdev_open_children(vdev_t *vd)
2059 {
2060 	vdev_open_children_impl(vd, vdev_default_open_children_func);
2061 }
2062 
2063 /*
2064  * Conditionally open a subset of child vdevs.
2065  */
2066 void
vdev_open_children_subset(vdev_t * vd,vdev_open_children_func_t * open_func)2067 vdev_open_children_subset(vdev_t *vd, vdev_open_children_func_t *open_func)
2068 {
2069 	vdev_open_children_impl(vd, open_func);
2070 }
2071 
2072 /*
2073  * Compute the raidz-deflation ratio.  Note, we hard-code 128k (1 << 17)
2074  * because it is the "typical" blocksize.  Even though SPA_MAXBLOCKSIZE
2075  * changed, this algorithm can not change, otherwise it would inconsistently
2076  * account for existing bp's.  We also hard-code txg 0 for the same reason
2077  * since expanded RAIDZ vdevs can use a different asize for different birth
2078  * txg's.
2079  */
2080 static void
vdev_set_deflate_ratio(vdev_t * vd)2081 vdev_set_deflate_ratio(vdev_t *vd)
2082 {
2083 	if (vd == vd->vdev_top && !vd->vdev_ishole && vd->vdev_ashift != 0) {
2084 		vd->vdev_deflate_ratio = (1 << 17) /
2085 		    (vdev_psize_to_asize_txg(vd, 1 << 17, 0) >>
2086 		    SPA_MINBLOCKSHIFT);
2087 	}
2088 }
2089 
2090 /*
2091  * Choose the best of two ashifts, preferring one between logical ashift
2092  * (absolute minimum) and administrator defined maximum, otherwise take
2093  * the biggest of the two.
2094  */
2095 uint64_t
vdev_best_ashift(uint64_t logical,uint64_t a,uint64_t b)2096 vdev_best_ashift(uint64_t logical, uint64_t a, uint64_t b)
2097 {
2098 	if (a > logical && a <= zfs_vdev_max_auto_ashift) {
2099 		if (b <= logical || b > zfs_vdev_max_auto_ashift)
2100 			return (a);
2101 		else
2102 			return (MAX(a, b));
2103 	} else if (b <= logical || b > zfs_vdev_max_auto_ashift)
2104 		return (MAX(a, b));
2105 	return (b);
2106 }
2107 
2108 /*
2109  * Maximize performance by inflating the configured ashift for top level
2110  * vdevs to be as close to the physical ashift as possible while maintaining
2111  * administrator defined limits and ensuring it doesn't go below the
2112  * logical ashift.
2113  */
2114 static void
vdev_ashift_optimize(vdev_t * vd)2115 vdev_ashift_optimize(vdev_t *vd)
2116 {
2117 	ASSERT(vd == vd->vdev_top);
2118 
2119 	if (vd->vdev_ashift < vd->vdev_physical_ashift &&
2120 	    vd->vdev_physical_ashift <= zfs_vdev_max_auto_ashift) {
2121 		vd->vdev_ashift = MIN(
2122 		    MAX(zfs_vdev_max_auto_ashift, vd->vdev_ashift),
2123 		    MAX(zfs_vdev_min_auto_ashift,
2124 		    vd->vdev_physical_ashift));
2125 	} else {
2126 		/*
2127 		 * If the logical and physical ashifts are the same, then
2128 		 * we ensure that the top-level vdev's ashift is not smaller
2129 		 * than our minimum ashift value. For the unusual case
2130 		 * where logical ashift > physical ashift, we can't cap
2131 		 * the calculated ashift based on max ashift as that
2132 		 * would cause failures.
2133 		 * We still check if we need to increase it to match
2134 		 * the min ashift.
2135 		 */
2136 		vd->vdev_ashift = MAX(zfs_vdev_min_auto_ashift,
2137 		    vd->vdev_ashift);
2138 	}
2139 }
2140 
2141 /*
2142  * Prepare a virtual device for access.
2143  */
2144 int
vdev_open(vdev_t * vd)2145 vdev_open(vdev_t *vd)
2146 {
2147 	spa_t *spa = vd->vdev_spa;
2148 	int error;
2149 	uint64_t osize = 0;
2150 	uint64_t max_osize = 0;
2151 	uint64_t asize, max_asize, psize;
2152 	uint64_t logical_ashift = 0;
2153 	uint64_t physical_ashift = 0;
2154 
2155 	ASSERT(vd->vdev_open_thread == curthread ||
2156 	    spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2157 	ASSERT(vd->vdev_state == VDEV_STATE_CLOSED ||
2158 	    vd->vdev_state == VDEV_STATE_CANT_OPEN ||
2159 	    vd->vdev_state == VDEV_STATE_OFFLINE);
2160 
2161 	vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
2162 	vd->vdev_cant_read = B_FALSE;
2163 	vd->vdev_cant_write = B_FALSE;
2164 	vd->vdev_fault_wanted = B_FALSE;
2165 	vd->vdev_remove_wanted = B_FALSE;
2166 	vd->vdev_min_asize = vdev_get_min_asize(vd);
2167 
2168 	/*
2169 	 * If this vdev is not removed, check its fault status.  If it's
2170 	 * faulted, bail out of the open.
2171 	 */
2172 	if (!vd->vdev_removed && vd->vdev_faulted) {
2173 		ASSERT0(vd->vdev_children);
2174 		ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
2175 		    vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
2176 		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
2177 		    vd->vdev_label_aux);
2178 		return (SET_ERROR(ENXIO));
2179 	} else if (vd->vdev_offline) {
2180 		ASSERT0(vd->vdev_children);
2181 		vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE, VDEV_AUX_NONE);
2182 		return (SET_ERROR(ENXIO));
2183 	}
2184 
2185 	error = vd->vdev_ops->vdev_op_open(vd, &osize, &max_osize,
2186 	    &logical_ashift, &physical_ashift);
2187 
2188 	/* Keep the device in removed state if unplugged */
2189 	if (error == ENOENT && vd->vdev_removed) {
2190 		vdev_set_state(vd, B_TRUE, VDEV_STATE_REMOVED,
2191 		    VDEV_AUX_NONE);
2192 		return (error);
2193 	}
2194 
2195 	/*
2196 	 * Physical volume size should never be larger than its max size, unless
2197 	 * the disk has shrunk while we were reading it or the device is buggy
2198 	 * or damaged: either way it's not safe for use, bail out of the open.
2199 	 */
2200 	if (osize > max_osize) {
2201 		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2202 		    VDEV_AUX_OPEN_FAILED);
2203 		return (SET_ERROR(ENXIO));
2204 	}
2205 
2206 	/*
2207 	 * Reset the vdev_reopening flag so that we actually close
2208 	 * the vdev on error.
2209 	 */
2210 	vd->vdev_reopening = B_FALSE;
2211 	if (zio_injection_enabled && error == 0)
2212 		error = zio_handle_device_injection(vd, NULL, SET_ERROR(ENXIO));
2213 
2214 	if (error) {
2215 		if (vd->vdev_removed &&
2216 		    vd->vdev_stat.vs_aux != VDEV_AUX_OPEN_FAILED)
2217 			vd->vdev_removed = B_FALSE;
2218 
2219 		if (vd->vdev_stat.vs_aux == VDEV_AUX_CHILDREN_OFFLINE) {
2220 			vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE,
2221 			    vd->vdev_stat.vs_aux);
2222 		} else {
2223 			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2224 			    vd->vdev_stat.vs_aux);
2225 		}
2226 		return (error);
2227 	}
2228 
2229 	vd->vdev_removed = B_FALSE;
2230 
2231 	/*
2232 	 * Recheck the faulted flag now that we have confirmed that
2233 	 * the vdev is accessible.  If we're faulted, bail.
2234 	 */
2235 	if (vd->vdev_faulted) {
2236 		ASSERT0(vd->vdev_children);
2237 		ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
2238 		    vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
2239 		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
2240 		    vd->vdev_label_aux);
2241 		return (SET_ERROR(ENXIO));
2242 	}
2243 
2244 	if (vd->vdev_degraded) {
2245 		ASSERT0(vd->vdev_children);
2246 		vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
2247 		    VDEV_AUX_ERR_EXCEEDED);
2248 	} else {
2249 		vdev_set_state(vd, B_TRUE, VDEV_STATE_HEALTHY, 0);
2250 	}
2251 
2252 	/*
2253 	 * For hole or missing vdevs we just return success.
2254 	 */
2255 	if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops)
2256 		return (0);
2257 
2258 	for (int c = 0; c < vd->vdev_children; c++) {
2259 		if (vd->vdev_child[c]->vdev_state != VDEV_STATE_HEALTHY) {
2260 			vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
2261 			    VDEV_AUX_NONE);
2262 			break;
2263 		}
2264 	}
2265 
2266 	osize = P2ALIGN_TYPED(osize, sizeof (vdev_label_t), uint64_t);
2267 	max_osize = P2ALIGN_TYPED(max_osize, sizeof (vdev_label_t), uint64_t);
2268 
2269 	if (vd->vdev_children == 0) {
2270 		if (osize < SPA_MINDEVSIZE) {
2271 			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2272 			    VDEV_AUX_TOO_SMALL);
2273 			return (SET_ERROR(EOVERFLOW));
2274 		}
2275 		psize = osize;
2276 		asize = osize - (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE);
2277 		max_asize = max_osize - (VDEV_LABEL_START_SIZE +
2278 		    VDEV_LABEL_END_SIZE);
2279 	} else {
2280 		if (vd->vdev_parent != NULL && osize < SPA_MINDEVSIZE -
2281 		    (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE)) {
2282 			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2283 			    VDEV_AUX_TOO_SMALL);
2284 			return (SET_ERROR(EOVERFLOW));
2285 		}
2286 		psize = 0;
2287 		asize = osize;
2288 		max_asize = max_osize;
2289 	}
2290 
2291 	/*
2292 	 * If the vdev was expanded, record this so that we can re-create the
2293 	 * uberblock rings in labels {2,3}, during the next sync.
2294 	 */
2295 	if ((psize > vd->vdev_psize) && (vd->vdev_psize != 0))
2296 		vd->vdev_copy_uberblocks = B_TRUE;
2297 
2298 	vd->vdev_psize = psize;
2299 
2300 	/*
2301 	 * Make sure the allocatable size hasn't shrunk too much.
2302 	 */
2303 	if (asize < vd->vdev_min_asize) {
2304 		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2305 		    VDEV_AUX_BAD_LABEL);
2306 		return (SET_ERROR(EINVAL));
2307 	}
2308 
2309 	/*
2310 	 * We can always set the logical/physical ashift members since
2311 	 * their values are only used to calculate the vdev_ashift when
2312 	 * the device is first added to the config. These values should
2313 	 * not be used for anything else since they may change whenever
2314 	 * the device is reopened and we don't store them in the label.
2315 	 */
2316 	vd->vdev_physical_ashift =
2317 	    MAX(physical_ashift, vd->vdev_physical_ashift);
2318 	vd->vdev_logical_ashift = MAX(logical_ashift,
2319 	    vd->vdev_logical_ashift);
2320 
2321 	if (vd->vdev_asize == 0) {
2322 		/*
2323 		 * This is the first-ever open, so use the computed values.
2324 		 * For compatibility, a different ashift can be requested.
2325 		 */
2326 		vd->vdev_asize = asize;
2327 		vd->vdev_max_asize = max_asize;
2328 
2329 		/*
2330 		 * If the vdev_ashift was not overridden at creation time
2331 		 * (0) or the override value is impossible for the device,
2332 		 * then set it the logical ashift and optimize the ashift.
2333 		 */
2334 		if (vd->vdev_ashift < vd->vdev_logical_ashift) {
2335 			vd->vdev_ashift = vd->vdev_logical_ashift;
2336 
2337 			if (vd->vdev_logical_ashift > ASHIFT_MAX) {
2338 				vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2339 				    VDEV_AUX_ASHIFT_TOO_BIG);
2340 				return (SET_ERROR(EDOM));
2341 			}
2342 
2343 			if (vd->vdev_top == vd && vd->vdev_attaching == B_FALSE)
2344 				vdev_ashift_optimize(vd);
2345 			vd->vdev_attaching = B_FALSE;
2346 		}
2347 		if (vd->vdev_ashift != 0 && (vd->vdev_ashift < ASHIFT_MIN ||
2348 		    vd->vdev_ashift > ASHIFT_MAX)) {
2349 			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2350 			    VDEV_AUX_BAD_ASHIFT);
2351 			return (SET_ERROR(EDOM));
2352 		}
2353 	} else {
2354 		/*
2355 		 * Make sure the alignment required hasn't increased.
2356 		 */
2357 		if (vd->vdev_ashift > vd->vdev_top->vdev_ashift &&
2358 		    vd->vdev_ops->vdev_op_leaf) {
2359 			(void) zfs_ereport_post(
2360 			    FM_EREPORT_ZFS_DEVICE_BAD_ASHIFT,
2361 			    spa, vd, NULL, NULL, 0);
2362 			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2363 			    VDEV_AUX_BAD_LABEL);
2364 			return (SET_ERROR(EDOM));
2365 		}
2366 		vd->vdev_max_asize = max_asize;
2367 	}
2368 
2369 	/*
2370 	 * If all children are healthy we update asize if either:
2371 	 * The asize has increased, due to a device expansion caused by dynamic
2372 	 * LUN growth or vdev replacement, and automatic expansion is enabled;
2373 	 * making the additional space available.
2374 	 *
2375 	 * The asize has decreased, due to a device shrink usually caused by a
2376 	 * vdev replace with a smaller device. This ensures that calculations
2377 	 * based of max_asize and asize e.g. esize are always valid. It's safe
2378 	 * to do this as we've already validated that asize is greater than
2379 	 * vdev_min_asize.
2380 	 */
2381 	if (vd->vdev_state == VDEV_STATE_HEALTHY &&
2382 	    ((asize > vd->vdev_asize &&
2383 	    (vd->vdev_expanding || spa->spa_autoexpand)) ||
2384 	    (asize < vd->vdev_asize)))
2385 		vd->vdev_asize = asize;
2386 
2387 	vdev_set_min_asize(vd);
2388 
2389 	/*
2390 	 * Ensure we can issue some IO before declaring the
2391 	 * vdev open for business.
2392 	 */
2393 	if (vd->vdev_ops->vdev_op_leaf &&
2394 	    (error = zio_wait(vdev_probe(vd, NULL))) != 0) {
2395 		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
2396 		    VDEV_AUX_ERR_EXCEEDED);
2397 		return (error);
2398 	}
2399 
2400 	/*
2401 	 * Track the minimum allocation size.
2402 	 */
2403 	if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
2404 	    vd->vdev_islog == 0 && vd->vdev_aux == NULL) {
2405 		uint64_t min_alloc = vdev_get_min_alloc(vd);
2406 		vdev_spa_set_alloc(spa, min_alloc);
2407 	}
2408 
2409 	/*
2410 	 * If this is a leaf vdev, assess whether a resilver is needed.
2411 	 * But don't do this if we are doing a reopen for a scrub, since
2412 	 * this would just restart the scrub we are already doing.
2413 	 */
2414 	if (vd->vdev_ops->vdev_op_leaf && !spa->spa_scrub_reopen)
2415 		dsl_scan_assess_vdev(spa->spa_dsl_pool, vd);
2416 
2417 	return (0);
2418 }
2419 
2420 static void
vdev_validate_child(void * arg)2421 vdev_validate_child(void *arg)
2422 {
2423 	vdev_t *vd = arg;
2424 
2425 	vd->vdev_validate_thread = curthread;
2426 	vd->vdev_validate_error = vdev_validate(vd);
2427 	vd->vdev_validate_thread = NULL;
2428 }
2429 
2430 /*
2431  * Called once the vdevs are all opened, this routine validates the label
2432  * contents. This needs to be done before vdev_load() so that we don't
2433  * inadvertently do repair I/Os to the wrong device.
2434  *
2435  * This function will only return failure if one of the vdevs indicates that it
2436  * has since been destroyed or exported.  This is only possible if
2437  * /etc/zfs/zpool.cache was readonly at the time.  Otherwise, the vdev state
2438  * will be updated but the function will return 0.
2439  */
2440 int
vdev_validate(vdev_t * vd)2441 vdev_validate(vdev_t *vd)
2442 {
2443 	spa_t *spa = vd->vdev_spa;
2444 	taskq_t *tq = NULL;
2445 	nvlist_t *label;
2446 	uint64_t guid = 0, aux_guid = 0, top_guid;
2447 	uint64_t state;
2448 	nvlist_t *nvl;
2449 	uint64_t txg;
2450 	int children = vd->vdev_children;
2451 
2452 	if (vdev_validate_skip)
2453 		return (0);
2454 
2455 	if (children > 0) {
2456 		tq = taskq_create("vdev_validate", children, minclsyspri,
2457 		    children, children, TASKQ_PREPOPULATE);
2458 	}
2459 
2460 	for (uint64_t c = 0; c < children; c++) {
2461 		vdev_t *cvd = vd->vdev_child[c];
2462 
2463 		if (tq == NULL || vdev_uses_zvols(cvd)) {
2464 			vdev_validate_child(cvd);
2465 		} else {
2466 			VERIFY(taskq_dispatch(tq, vdev_validate_child, cvd,
2467 			    TQ_SLEEP) != TASKQID_INVALID);
2468 		}
2469 	}
2470 	if (tq != NULL) {
2471 		taskq_wait(tq);
2472 		taskq_destroy(tq);
2473 	}
2474 	for (int c = 0; c < children; c++) {
2475 		int error = vd->vdev_child[c]->vdev_validate_error;
2476 
2477 		if (error != 0)
2478 			return (SET_ERROR(EBADF));
2479 	}
2480 
2481 
2482 	/*
2483 	 * If the device has already failed, or was marked offline, don't do
2484 	 * any further validation.  Otherwise, label I/O will fail and we will
2485 	 * overwrite the previous state.
2486 	 */
2487 	if (!vd->vdev_ops->vdev_op_leaf || !vdev_readable(vd))
2488 		return (0);
2489 
2490 	/*
2491 	 * If we are performing an extreme rewind, we allow for a label that
2492 	 * was modified at a point after the current txg.
2493 	 * If config lock is not held do not check for the txg. spa_sync could
2494 	 * be updating the vdev's label before updating spa_last_synced_txg.
2495 	 */
2496 	if (spa->spa_extreme_rewind || spa_last_synced_txg(spa) == 0 ||
2497 	    spa_config_held(spa, SCL_CONFIG, RW_WRITER) != SCL_CONFIG)
2498 		txg = UINT64_MAX;
2499 	else
2500 		txg = spa_last_synced_txg(spa);
2501 
2502 	if ((label = vdev_label_read_config(vd, txg)) == NULL) {
2503 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2504 		    VDEV_AUX_BAD_LABEL);
2505 		vdev_dbgmsg(vd, "vdev_validate: failed reading config for "
2506 		    "txg %llu", (u_longlong_t)txg);
2507 		return (0);
2508 	}
2509 
2510 	/*
2511 	 * Determine if this vdev has been split off into another
2512 	 * pool.  If so, then refuse to open it.
2513 	 */
2514 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_SPLIT_GUID,
2515 	    &aux_guid) == 0 && aux_guid == spa_guid(spa)) {
2516 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2517 		    VDEV_AUX_SPLIT_POOL);
2518 		nvlist_free(label);
2519 		vdev_dbgmsg(vd, "vdev_validate: vdev split into other pool");
2520 		return (0);
2521 	}
2522 
2523 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID, &guid) != 0) {
2524 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2525 		    VDEV_AUX_CORRUPT_DATA);
2526 		nvlist_free(label);
2527 		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
2528 		    ZPOOL_CONFIG_POOL_GUID);
2529 		return (0);
2530 	}
2531 
2532 	/*
2533 	 * If config is not trusted then ignore the spa guid check. This is
2534 	 * necessary because if the machine crashed during a re-guid the new
2535 	 * guid might have been written to all of the vdev labels, but not the
2536 	 * cached config. The check will be performed again once we have the
2537 	 * trusted config from the MOS.
2538 	 */
2539 	if (spa->spa_trust_config && guid != spa_guid(spa)) {
2540 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2541 		    VDEV_AUX_CORRUPT_DATA);
2542 		nvlist_free(label);
2543 		vdev_dbgmsg(vd, "vdev_validate: vdev label pool_guid doesn't "
2544 		    "match config (%llu != %llu)", (u_longlong_t)guid,
2545 		    (u_longlong_t)spa_guid(spa));
2546 		return (0);
2547 	}
2548 
2549 	if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvl)
2550 	    != 0 || nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_ORIG_GUID,
2551 	    &aux_guid) != 0)
2552 		aux_guid = 0;
2553 
2554 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0) {
2555 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2556 		    VDEV_AUX_CORRUPT_DATA);
2557 		nvlist_free(label);
2558 		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
2559 		    ZPOOL_CONFIG_GUID);
2560 		return (0);
2561 	}
2562 
2563 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID, &top_guid)
2564 	    != 0) {
2565 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2566 		    VDEV_AUX_CORRUPT_DATA);
2567 		nvlist_free(label);
2568 		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
2569 		    ZPOOL_CONFIG_TOP_GUID);
2570 		return (0);
2571 	}
2572 
2573 	/*
2574 	 * If this vdev just became a top-level vdev because its sibling was
2575 	 * detached, it will have adopted the parent's vdev guid -- but the
2576 	 * label may or may not be on disk yet. Fortunately, either version
2577 	 * of the label will have the same top guid, so if we're a top-level
2578 	 * vdev, we can safely compare to that instead.
2579 	 * However, if the config comes from a cachefile that failed to update
2580 	 * after the detach, a top-level vdev will appear as a non top-level
2581 	 * vdev in the config. Also relax the constraints if we perform an
2582 	 * extreme rewind.
2583 	 *
2584 	 * If we split this vdev off instead, then we also check the
2585 	 * original pool's guid. We don't want to consider the vdev
2586 	 * corrupt if it is partway through a split operation.
2587 	 */
2588 	if (vd->vdev_guid != guid && vd->vdev_guid != aux_guid) {
2589 		boolean_t mismatch = B_FALSE;
2590 		if (spa->spa_trust_config && !spa->spa_extreme_rewind) {
2591 			if (vd != vd->vdev_top || vd->vdev_guid != top_guid)
2592 				mismatch = B_TRUE;
2593 		} else {
2594 			if (vd->vdev_guid != top_guid &&
2595 			    vd->vdev_top->vdev_guid != guid)
2596 				mismatch = B_TRUE;
2597 		}
2598 
2599 		if (mismatch) {
2600 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2601 			    VDEV_AUX_CORRUPT_DATA);
2602 			nvlist_free(label);
2603 			vdev_dbgmsg(vd, "vdev_validate: config guid "
2604 			    "doesn't match label guid");
2605 			vdev_dbgmsg(vd, "CONFIG: guid %llu, top_guid %llu",
2606 			    (u_longlong_t)vd->vdev_guid,
2607 			    (u_longlong_t)vd->vdev_top->vdev_guid);
2608 			vdev_dbgmsg(vd, "LABEL: guid %llu, top_guid %llu, "
2609 			    "aux_guid %llu", (u_longlong_t)guid,
2610 			    (u_longlong_t)top_guid, (u_longlong_t)aux_guid);
2611 			return (0);
2612 		}
2613 	}
2614 
2615 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
2616 	    &state) != 0) {
2617 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2618 		    VDEV_AUX_CORRUPT_DATA);
2619 		nvlist_free(label);
2620 		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
2621 		    ZPOOL_CONFIG_POOL_STATE);
2622 		return (0);
2623 	}
2624 
2625 	nvlist_free(label);
2626 
2627 	/*
2628 	 * If this is a verbatim import, no need to check the
2629 	 * state of the pool.
2630 	 */
2631 	if (!(spa->spa_import_flags & ZFS_IMPORT_VERBATIM) &&
2632 	    spa_load_state(spa) == SPA_LOAD_OPEN &&
2633 	    state != POOL_STATE_ACTIVE) {
2634 		vdev_dbgmsg(vd, "vdev_validate: invalid pool state (%llu) "
2635 		    "for spa %s", (u_longlong_t)state, spa->spa_name);
2636 		return (SET_ERROR(EBADF));
2637 	}
2638 
2639 	/*
2640 	 * If we were able to open and validate a vdev that was
2641 	 * previously marked permanently unavailable, clear that state
2642 	 * now.
2643 	 */
2644 	if (vd->vdev_not_present)
2645 		vd->vdev_not_present = 0;
2646 
2647 	return (0);
2648 }
2649 
2650 static void
vdev_update_path(const char * prefix,char * svd,char ** dvd,uint64_t guid)2651 vdev_update_path(const char *prefix, char *svd, char **dvd, uint64_t guid)
2652 {
2653 	if (svd != NULL && *dvd != NULL) {
2654 		if (strcmp(svd, *dvd) != 0) {
2655 			zfs_dbgmsg("vdev_copy_path: vdev %llu: %s changed "
2656 			    "from '%s' to '%s'", (u_longlong_t)guid, prefix,
2657 			    *dvd, svd);
2658 			spa_strfree(*dvd);
2659 			*dvd = spa_strdup(svd);
2660 		}
2661 	} else if (svd != NULL) {
2662 		*dvd = spa_strdup(svd);
2663 		zfs_dbgmsg("vdev_copy_path: vdev %llu: path set to '%s'",
2664 		    (u_longlong_t)guid, *dvd);
2665 	}
2666 }
2667 
2668 static void
vdev_copy_path_impl(vdev_t * svd,vdev_t * dvd)2669 vdev_copy_path_impl(vdev_t *svd, vdev_t *dvd)
2670 {
2671 	char *old, *new;
2672 
2673 	vdev_update_path("vdev_path", svd->vdev_path, &dvd->vdev_path,
2674 	    dvd->vdev_guid);
2675 
2676 	vdev_update_path("vdev_devid", svd->vdev_devid, &dvd->vdev_devid,
2677 	    dvd->vdev_guid);
2678 
2679 	vdev_update_path("vdev_physpath", svd->vdev_physpath,
2680 	    &dvd->vdev_physpath, dvd->vdev_guid);
2681 
2682 	/*
2683 	 * Our enclosure sysfs path may have changed between imports
2684 	 */
2685 	old = dvd->vdev_enc_sysfs_path;
2686 	new = svd->vdev_enc_sysfs_path;
2687 	if ((old != NULL && new == NULL) ||
2688 	    (old == NULL && new != NULL) ||
2689 	    ((old != NULL && new != NULL) && strcmp(new, old) != 0)) {
2690 		zfs_dbgmsg("vdev_copy_path: vdev %llu: vdev_enc_sysfs_path "
2691 		    "changed from '%s' to '%s'", (u_longlong_t)dvd->vdev_guid,
2692 		    old, new);
2693 
2694 		if (dvd->vdev_enc_sysfs_path)
2695 			spa_strfree(dvd->vdev_enc_sysfs_path);
2696 
2697 		if (svd->vdev_enc_sysfs_path) {
2698 			dvd->vdev_enc_sysfs_path = spa_strdup(
2699 			    svd->vdev_enc_sysfs_path);
2700 		} else {
2701 			dvd->vdev_enc_sysfs_path = NULL;
2702 		}
2703 	}
2704 }
2705 
2706 /*
2707  * Recursively copy vdev paths from one vdev to another. Source and destination
2708  * vdev trees must have same geometry otherwise return error. Intended to copy
2709  * paths from userland config into MOS config.
2710  */
2711 int
vdev_copy_path_strict(vdev_t * svd,vdev_t * dvd)2712 vdev_copy_path_strict(vdev_t *svd, vdev_t *dvd)
2713 {
2714 	if ((svd->vdev_ops == &vdev_missing_ops) ||
2715 	    (svd->vdev_ishole && dvd->vdev_ishole) ||
2716 	    (dvd->vdev_ops == &vdev_indirect_ops))
2717 		return (0);
2718 
2719 	if (svd->vdev_ops != dvd->vdev_ops) {
2720 		vdev_dbgmsg(svd, "vdev_copy_path: vdev type mismatch: %s != %s",
2721 		    svd->vdev_ops->vdev_op_type, dvd->vdev_ops->vdev_op_type);
2722 		return (SET_ERROR(EINVAL));
2723 	}
2724 
2725 	if (svd->vdev_guid != dvd->vdev_guid) {
2726 		vdev_dbgmsg(svd, "vdev_copy_path: guids mismatch (%llu != "
2727 		    "%llu)", (u_longlong_t)svd->vdev_guid,
2728 		    (u_longlong_t)dvd->vdev_guid);
2729 		return (SET_ERROR(EINVAL));
2730 	}
2731 
2732 	if (svd->vdev_children != dvd->vdev_children) {
2733 		vdev_dbgmsg(svd, "vdev_copy_path: children count mismatch: "
2734 		    "%llu != %llu", (u_longlong_t)svd->vdev_children,
2735 		    (u_longlong_t)dvd->vdev_children);
2736 		return (SET_ERROR(EINVAL));
2737 	}
2738 
2739 	for (uint64_t i = 0; i < svd->vdev_children; i++) {
2740 		int error = vdev_copy_path_strict(svd->vdev_child[i],
2741 		    dvd->vdev_child[i]);
2742 		if (error != 0)
2743 			return (error);
2744 	}
2745 
2746 	if (svd->vdev_ops->vdev_op_leaf)
2747 		vdev_copy_path_impl(svd, dvd);
2748 
2749 	return (0);
2750 }
2751 
2752 static void
vdev_copy_path_search(vdev_t * stvd,vdev_t * dvd)2753 vdev_copy_path_search(vdev_t *stvd, vdev_t *dvd)
2754 {
2755 	ASSERT(stvd->vdev_top == stvd);
2756 	ASSERT3U(stvd->vdev_id, ==, dvd->vdev_top->vdev_id);
2757 
2758 	for (uint64_t i = 0; i < dvd->vdev_children; i++) {
2759 		vdev_copy_path_search(stvd, dvd->vdev_child[i]);
2760 	}
2761 
2762 	if (!dvd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(dvd))
2763 		return;
2764 
2765 	/*
2766 	 * The idea here is that while a vdev can shift positions within
2767 	 * a top vdev (when replacing, attaching mirror, etc.) it cannot
2768 	 * step outside of it.
2769 	 */
2770 	vdev_t *vd = vdev_lookup_by_guid(stvd, dvd->vdev_guid);
2771 
2772 	if (vd == NULL || vd->vdev_ops != dvd->vdev_ops)
2773 		return;
2774 
2775 	ASSERT(vd->vdev_ops->vdev_op_leaf);
2776 
2777 	vdev_copy_path_impl(vd, dvd);
2778 }
2779 
2780 /*
2781  * Recursively copy vdev paths from one root vdev to another. Source and
2782  * destination vdev trees may differ in geometry. For each destination leaf
2783  * vdev, search a vdev with the same guid and top vdev id in the source.
2784  * Intended to copy paths from userland config into MOS config.
2785  */
2786 void
vdev_copy_path_relaxed(vdev_t * srvd,vdev_t * drvd)2787 vdev_copy_path_relaxed(vdev_t *srvd, vdev_t *drvd)
2788 {
2789 	uint64_t children = MIN(srvd->vdev_children, drvd->vdev_children);
2790 	ASSERT(srvd->vdev_ops == &vdev_root_ops);
2791 	ASSERT(drvd->vdev_ops == &vdev_root_ops);
2792 
2793 	for (uint64_t i = 0; i < children; i++) {
2794 		vdev_copy_path_search(srvd->vdev_child[i],
2795 		    drvd->vdev_child[i]);
2796 	}
2797 }
2798 
2799 /*
2800  * Close a virtual device.
2801  */
2802 void
vdev_close(vdev_t * vd)2803 vdev_close(vdev_t *vd)
2804 {
2805 	vdev_t *pvd = vd->vdev_parent;
2806 	spa_t *spa __maybe_unused = vd->vdev_spa;
2807 
2808 	ASSERT(vd != NULL);
2809 	ASSERT(vd->vdev_open_thread == curthread ||
2810 	    spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2811 
2812 	/*
2813 	 * If our parent is reopening, then we are as well, unless we are
2814 	 * going offline.
2815 	 */
2816 	if (pvd != NULL && pvd->vdev_reopening)
2817 		vd->vdev_reopening = (pvd->vdev_reopening && !vd->vdev_offline);
2818 
2819 	vd->vdev_ops->vdev_op_close(vd);
2820 
2821 	/*
2822 	 * We record the previous state before we close it, so that if we are
2823 	 * doing a reopen(), we don't generate FMA ereports if we notice that
2824 	 * it's still faulted.
2825 	 */
2826 	vd->vdev_prevstate = vd->vdev_state;
2827 
2828 	if (vd->vdev_offline)
2829 		vd->vdev_state = VDEV_STATE_OFFLINE;
2830 	else
2831 		vd->vdev_state = VDEV_STATE_CLOSED;
2832 	vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
2833 }
2834 
2835 void
vdev_hold(vdev_t * vd)2836 vdev_hold(vdev_t *vd)
2837 {
2838 	spa_t *spa = vd->vdev_spa;
2839 
2840 	ASSERT(spa_is_root(spa));
2841 	if (spa->spa_state == POOL_STATE_UNINITIALIZED)
2842 		return;
2843 
2844 	for (int c = 0; c < vd->vdev_children; c++)
2845 		vdev_hold(vd->vdev_child[c]);
2846 
2847 	if (vd->vdev_ops->vdev_op_leaf && vd->vdev_ops->vdev_op_hold != NULL)
2848 		vd->vdev_ops->vdev_op_hold(vd);
2849 }
2850 
2851 void
vdev_rele(vdev_t * vd)2852 vdev_rele(vdev_t *vd)
2853 {
2854 	ASSERT(spa_is_root(vd->vdev_spa));
2855 	for (int c = 0; c < vd->vdev_children; c++)
2856 		vdev_rele(vd->vdev_child[c]);
2857 
2858 	if (vd->vdev_ops->vdev_op_leaf && vd->vdev_ops->vdev_op_rele != NULL)
2859 		vd->vdev_ops->vdev_op_rele(vd);
2860 }
2861 
2862 /*
2863  * Reopen all interior vdevs and any unopened leaves.  We don't actually
2864  * reopen leaf vdevs which had previously been opened as they might deadlock
2865  * on the spa_config_lock.  Instead we only obtain the leaf's physical size.
2866  * If the leaf has never been opened then open it, as usual.
2867  */
2868 void
vdev_reopen(vdev_t * vd)2869 vdev_reopen(vdev_t *vd)
2870 {
2871 	spa_t *spa = vd->vdev_spa;
2872 
2873 	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2874 
2875 	/* set the reopening flag unless we're taking the vdev offline */
2876 	vd->vdev_reopening = !vd->vdev_offline;
2877 	vdev_close(vd);
2878 	(void) vdev_open(vd);
2879 
2880 	/*
2881 	 * Call vdev_validate() here to make sure we have the same device.
2882 	 * Otherwise, a device with an invalid label could be successfully
2883 	 * opened in response to vdev_reopen().
2884 	 */
2885 	if (vd->vdev_aux) {
2886 		(void) vdev_validate_aux(vd);
2887 		if (vdev_readable(vd) && vdev_writeable(vd) &&
2888 		    vd->vdev_aux == &spa->spa_l2cache) {
2889 			/*
2890 			 * In case the vdev is present we should evict all ARC
2891 			 * buffers and pointers to log blocks and reclaim their
2892 			 * space before restoring its contents to L2ARC.
2893 			 */
2894 			if (l2arc_vdev_present(vd)) {
2895 				l2arc_rebuild_vdev(vd, B_TRUE);
2896 			} else {
2897 				l2arc_add_vdev(spa, vd);
2898 			}
2899 			spa_async_request(spa, SPA_ASYNC_L2CACHE_REBUILD);
2900 			spa_async_request(spa, SPA_ASYNC_L2CACHE_TRIM);
2901 		}
2902 	} else {
2903 		(void) vdev_validate(vd);
2904 	}
2905 
2906 	/*
2907 	 * Recheck if resilver is still needed and cancel any
2908 	 * scheduled resilver if resilver is unneeded.
2909 	 */
2910 	if (!vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL) &&
2911 	    spa->spa_async_tasks & SPA_ASYNC_RESILVER) {
2912 		mutex_enter(&spa->spa_async_lock);
2913 		spa->spa_async_tasks &= ~SPA_ASYNC_RESILVER;
2914 		mutex_exit(&spa->spa_async_lock);
2915 	}
2916 
2917 	/*
2918 	 * Reassess parent vdev's health.
2919 	 */
2920 	vdev_propagate_state(vd);
2921 }
2922 
2923 int
vdev_create(vdev_t * vd,uint64_t txg,boolean_t isreplacing)2924 vdev_create(vdev_t *vd, uint64_t txg, boolean_t isreplacing)
2925 {
2926 	int error;
2927 
2928 	/*
2929 	 * Normally, partial opens (e.g. of a mirror) are allowed.
2930 	 * For a create, however, we want to fail the request if
2931 	 * there are any components we can't open.
2932 	 */
2933 	error = vdev_open(vd);
2934 
2935 	if (error || vd->vdev_state != VDEV_STATE_HEALTHY) {
2936 		vdev_close(vd);
2937 		return (error ? error : SET_ERROR(ENXIO));
2938 	}
2939 
2940 	/*
2941 	 * Recursively load DTLs and initialize all labels.
2942 	 */
2943 	if ((error = vdev_dtl_load(vd)) != 0 ||
2944 	    (error = vdev_label_init(vd, txg, isreplacing ?
2945 	    VDEV_LABEL_REPLACE : VDEV_LABEL_CREATE)) != 0) {
2946 		vdev_close(vd);
2947 		return (error);
2948 	}
2949 
2950 	return (0);
2951 }
2952 
2953 void
vdev_metaslab_set_size(vdev_t * vd)2954 vdev_metaslab_set_size(vdev_t *vd)
2955 {
2956 	uint64_t asize = vd->vdev_asize;
2957 	uint64_t ms_count = asize >> zfs_vdev_default_ms_shift;
2958 	uint64_t ms_shift;
2959 
2960 	/*
2961 	 * There are two dimensions to the metaslab sizing calculation:
2962 	 * the size of the metaslab and the count of metaslabs per vdev.
2963 	 *
2964 	 * The default values used below are a good balance between memory
2965 	 * usage (larger metaslab size means more memory needed for loaded
2966 	 * metaslabs; more metaslabs means more memory needed for the
2967 	 * metaslab_t structs), metaslab load time (larger metaslabs take
2968 	 * longer to load), and metaslab sync time (more metaslabs means
2969 	 * more time spent syncing all of them).
2970 	 *
2971 	 * In general, we aim for zfs_vdev_default_ms_count (200) metaslabs.
2972 	 * The range of the dimensions are as follows:
2973 	 *
2974 	 *	2^29 <= ms_size  <= 2^34
2975 	 *	  16 <= ms_count <= 131,072
2976 	 *
2977 	 * On the lower end of vdev sizes, we aim for metaslabs sizes of
2978 	 * at least 512MB (2^29) to minimize fragmentation effects when
2979 	 * testing with smaller devices.  However, the count constraint
2980 	 * of at least 16 metaslabs will override this minimum size goal.
2981 	 *
2982 	 * On the upper end of vdev sizes, we aim for a maximum metaslab
2983 	 * size of 16GB.  However, we will cap the total count to 2^17
2984 	 * metaslabs to keep our memory footprint in check and let the
2985 	 * metaslab size grow from there if that limit is hit.
2986 	 *
2987 	 * The net effect of applying above constrains is summarized below.
2988 	 *
2989 	 *   vdev size       metaslab count
2990 	 *  --------------|-----------------
2991 	 *      < 8GB        ~16
2992 	 *  8GB   - 100GB   one per 512MB
2993 	 *  100GB - 3TB     ~200
2994 	 *  3TB   - 2PB     one per 16GB
2995 	 *      > 2PB       ~131,072
2996 	 *  --------------------------------
2997 	 *
2998 	 *  Finally, note that all of the above calculate the initial
2999 	 *  number of metaslabs. Expanding a top-level vdev will result
3000 	 *  in additional metaslabs being allocated making it possible
3001 	 *  to exceed the zfs_vdev_ms_count_limit.
3002 	 */
3003 
3004 	if (ms_count < zfs_vdev_min_ms_count)
3005 		ms_shift = highbit64(asize / zfs_vdev_min_ms_count);
3006 	else if (ms_count > zfs_vdev_default_ms_count)
3007 		ms_shift = highbit64(asize / zfs_vdev_default_ms_count);
3008 	else
3009 		ms_shift = zfs_vdev_default_ms_shift;
3010 
3011 	if (ms_shift < SPA_MAXBLOCKSHIFT) {
3012 		ms_shift = SPA_MAXBLOCKSHIFT;
3013 	} else if (ms_shift > zfs_vdev_max_ms_shift) {
3014 		ms_shift = zfs_vdev_max_ms_shift;
3015 		/* cap the total count to constrain memory footprint */
3016 		if ((asize >> ms_shift) > zfs_vdev_ms_count_limit)
3017 			ms_shift = highbit64(asize / zfs_vdev_ms_count_limit);
3018 	}
3019 
3020 	vd->vdev_ms_shift = ms_shift;
3021 	ASSERT3U(vd->vdev_ms_shift, >=, SPA_MAXBLOCKSHIFT);
3022 }
3023 
3024 void
vdev_dirty(vdev_t * vd,int flags,void * arg,uint64_t txg)3025 vdev_dirty(vdev_t *vd, int flags, void *arg, uint64_t txg)
3026 {
3027 	ASSERT(vd == vd->vdev_top);
3028 	/* indirect vdevs don't have metaslabs or dtls */
3029 	ASSERT(vdev_is_concrete(vd) || flags == 0);
3030 	ASSERT(ISP2(flags));
3031 	ASSERT(spa_writeable(vd->vdev_spa));
3032 
3033 	if (flags & VDD_METASLAB)
3034 		(void) txg_list_add(&vd->vdev_ms_list, arg, txg);
3035 
3036 	if (flags & VDD_DTL)
3037 		(void) txg_list_add(&vd->vdev_dtl_list, arg, txg);
3038 
3039 	(void) txg_list_add(&vd->vdev_spa->spa_vdev_txg_list, vd, txg);
3040 }
3041 
3042 void
vdev_dirty_leaves(vdev_t * vd,int flags,uint64_t txg)3043 vdev_dirty_leaves(vdev_t *vd, int flags, uint64_t txg)
3044 {
3045 	for (int c = 0; c < vd->vdev_children; c++)
3046 		vdev_dirty_leaves(vd->vdev_child[c], flags, txg);
3047 
3048 	if (vd->vdev_ops->vdev_op_leaf)
3049 		vdev_dirty(vd->vdev_top, flags, vd, txg);
3050 }
3051 
3052 /*
3053  * DTLs.
3054  *
3055  * A vdev's DTL (dirty time log) is the set of transaction groups for which
3056  * the vdev has less than perfect replication.  There are four kinds of DTL:
3057  *
3058  * DTL_MISSING: txgs for which the vdev has no valid copies of the data
3059  *
3060  * DTL_PARTIAL: txgs for which data is available, but not fully replicated
3061  *
3062  * DTL_SCRUB: the txgs that could not be repaired by the last scrub; upon
3063  *	scrub completion, DTL_SCRUB replaces DTL_MISSING in the range of
3064  *	txgs that was scrubbed.
3065  *
3066  * DTL_OUTAGE: txgs which cannot currently be read, whether due to
3067  *	persistent errors or just some device being offline.
3068  *	Unlike the other three, the DTL_OUTAGE map is not generally
3069  *	maintained; it's only computed when needed, typically to
3070  *	determine whether a device can be detached.
3071  *
3072  * For leaf vdevs, DTL_MISSING and DTL_PARTIAL are identical: the device
3073  * either has the data or it doesn't.
3074  *
3075  * For interior vdevs such as mirror and RAID-Z the picture is more complex.
3076  * A vdev's DTL_PARTIAL is the union of its children's DTL_PARTIALs, because
3077  * if any child is less than fully replicated, then so is its parent.
3078  * A vdev's DTL_MISSING is a modified union of its children's DTL_MISSINGs,
3079  * comprising only those txgs which appear in 'maxfaults' or more children;
3080  * those are the txgs we don't have enough replication to read.  For example,
3081  * double-parity RAID-Z can tolerate up to two missing devices (maxfaults == 2);
3082  * thus, its DTL_MISSING consists of the set of txgs that appear in more than
3083  * two child DTL_MISSING maps.
3084  *
3085  * It should be clear from the above that to compute the DTLs and outage maps
3086  * for all vdevs, it suffices to know just the leaf vdevs' DTL_MISSING maps.
3087  * Therefore, that is all we keep on disk.  When loading the pool, or after
3088  * a configuration change, we generate all other DTLs from first principles.
3089  */
3090 void
vdev_dtl_dirty(vdev_t * vd,vdev_dtl_type_t t,uint64_t txg,uint64_t size)3091 vdev_dtl_dirty(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
3092 {
3093 	zfs_range_tree_t *rt = vd->vdev_dtl[t];
3094 
3095 	ASSERT(t < DTL_TYPES);
3096 	ASSERT(vd != vd->vdev_spa->spa_root_vdev);
3097 	ASSERT(spa_writeable(vd->vdev_spa));
3098 
3099 	mutex_enter(&vd->vdev_dtl_lock);
3100 	if (!zfs_range_tree_contains(rt, txg, size)) {
3101 		/* Clear whatever is there already. */
3102 		zfs_range_tree_clear(rt, txg, size);
3103 		zfs_range_tree_add(rt, txg, size);
3104 	}
3105 	mutex_exit(&vd->vdev_dtl_lock);
3106 }
3107 
3108 boolean_t
vdev_dtl_contains(vdev_t * vd,vdev_dtl_type_t t,uint64_t txg,uint64_t size)3109 vdev_dtl_contains(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
3110 {
3111 	zfs_range_tree_t *rt = vd->vdev_dtl[t];
3112 	boolean_t dirty = B_FALSE;
3113 
3114 	ASSERT(t < DTL_TYPES);
3115 	ASSERT(vd != vd->vdev_spa->spa_root_vdev);
3116 
3117 	/*
3118 	 * While we are loading the pool, the DTLs have not been loaded yet.
3119 	 * This isn't a problem but it can result in devices being tried
3120 	 * which are known to not have the data.  In which case, the import
3121 	 * is relying on the checksum to ensure that we get the right data.
3122 	 * Note that while importing we are only reading the MOS, which is
3123 	 * always checksummed.
3124 	 */
3125 	mutex_enter(&vd->vdev_dtl_lock);
3126 	if (!zfs_range_tree_is_empty(rt))
3127 		dirty = zfs_range_tree_contains(rt, txg, size);
3128 	mutex_exit(&vd->vdev_dtl_lock);
3129 
3130 	return (dirty);
3131 }
3132 
3133 boolean_t
vdev_dtl_empty(vdev_t * vd,vdev_dtl_type_t t)3134 vdev_dtl_empty(vdev_t *vd, vdev_dtl_type_t t)
3135 {
3136 	zfs_range_tree_t *rt = vd->vdev_dtl[t];
3137 	boolean_t empty;
3138 
3139 	mutex_enter(&vd->vdev_dtl_lock);
3140 	empty = zfs_range_tree_is_empty(rt);
3141 	mutex_exit(&vd->vdev_dtl_lock);
3142 
3143 	return (empty);
3144 }
3145 
3146 /*
3147  * Check if the txg falls within the range which must be
3148  * resilvered.  DVAs outside this range can always be skipped.
3149  */
3150 boolean_t
vdev_default_need_resilver(vdev_t * vd,const dva_t * dva,size_t psize,uint64_t phys_birth)3151 vdev_default_need_resilver(vdev_t *vd, const dva_t *dva, size_t psize,
3152     uint64_t phys_birth)
3153 {
3154 	(void) dva, (void) psize;
3155 
3156 	/* Set by sequential resilver. */
3157 	if (phys_birth == TXG_UNKNOWN)
3158 		return (B_TRUE);
3159 
3160 	return (vdev_dtl_contains(vd, DTL_PARTIAL, phys_birth, 1));
3161 }
3162 
3163 /*
3164  * Returns B_TRUE if the vdev determines the DVA needs to be resilvered.
3165  */
3166 boolean_t
vdev_dtl_need_resilver(vdev_t * vd,const dva_t * dva,size_t psize,uint64_t phys_birth)3167 vdev_dtl_need_resilver(vdev_t *vd, const dva_t *dva, size_t psize,
3168     uint64_t phys_birth)
3169 {
3170 	ASSERT(vd != vd->vdev_spa->spa_root_vdev);
3171 
3172 	if (vd->vdev_ops->vdev_op_need_resilver == NULL ||
3173 	    vd->vdev_ops->vdev_op_leaf)
3174 		return (B_TRUE);
3175 
3176 	return (vd->vdev_ops->vdev_op_need_resilver(vd, dva, psize,
3177 	    phys_birth));
3178 }
3179 
3180 /*
3181  * Returns the lowest txg in the DTL range.
3182  */
3183 static uint64_t
vdev_dtl_min(vdev_t * vd)3184 vdev_dtl_min(vdev_t *vd)
3185 {
3186 	ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
3187 	ASSERT3U(zfs_range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
3188 	ASSERT0(vd->vdev_children);
3189 
3190 	return (zfs_range_tree_min(vd->vdev_dtl[DTL_MISSING]) - 1);
3191 }
3192 
3193 /*
3194  * Returns the highest txg in the DTL.
3195  */
3196 static uint64_t
vdev_dtl_max(vdev_t * vd)3197 vdev_dtl_max(vdev_t *vd)
3198 {
3199 	ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
3200 	ASSERT3U(zfs_range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
3201 	ASSERT0(vd->vdev_children);
3202 
3203 	return (zfs_range_tree_max(vd->vdev_dtl[DTL_MISSING]));
3204 }
3205 
3206 /*
3207  * Determine if a resilvering vdev should remove any DTL entries from
3208  * its range. If the vdev was resilvering for the entire duration of the
3209  * scan then it should excise that range from its DTLs. Otherwise, this
3210  * vdev is considered partially resilvered and should leave its DTL
3211  * entries intact. The comment in vdev_dtl_reassess() describes how we
3212  * excise the DTLs.
3213  */
3214 static boolean_t
vdev_dtl_should_excise(vdev_t * vd,boolean_t rebuild_done)3215 vdev_dtl_should_excise(vdev_t *vd, boolean_t rebuild_done)
3216 {
3217 	ASSERT0(vd->vdev_children);
3218 
3219 	if (vd->vdev_state < VDEV_STATE_DEGRADED)
3220 		return (B_FALSE);
3221 
3222 	if (vd->vdev_resilver_deferred)
3223 		return (B_FALSE);
3224 
3225 	if (zfs_range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]))
3226 		return (B_TRUE);
3227 
3228 	if (rebuild_done) {
3229 		vdev_rebuild_t *vr = &vd->vdev_top->vdev_rebuild_config;
3230 		vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
3231 
3232 		/* Rebuild not initiated by attach */
3233 		if (vd->vdev_rebuild_txg == 0)
3234 			return (B_TRUE);
3235 
3236 		/*
3237 		 * When a rebuild completes without error then all missing data
3238 		 * up to the rebuild max txg has been reconstructed and the DTL
3239 		 * is eligible for excision.
3240 		 */
3241 		if (vrp->vrp_rebuild_state == VDEV_REBUILD_COMPLETE &&
3242 		    vdev_dtl_max(vd) <= vrp->vrp_max_txg) {
3243 			ASSERT3U(vrp->vrp_min_txg, <=, vdev_dtl_min(vd));
3244 			ASSERT3U(vrp->vrp_min_txg, <, vd->vdev_rebuild_txg);
3245 			ASSERT3U(vd->vdev_rebuild_txg, <=, vrp->vrp_max_txg);
3246 			return (B_TRUE);
3247 		}
3248 	} else {
3249 		dsl_scan_t *scn = vd->vdev_spa->spa_dsl_pool->dp_scan;
3250 		dsl_scan_phys_t *scnp __maybe_unused = &scn->scn_phys;
3251 
3252 		/* Resilver not initiated by attach */
3253 		if (vd->vdev_resilver_txg == 0)
3254 			return (B_TRUE);
3255 
3256 		/*
3257 		 * When a resilver is initiated the scan will assign the
3258 		 * scn_max_txg value to the highest txg value that exists
3259 		 * in all DTLs. If this device's max DTL is not part of this
3260 		 * scan (i.e. it is not in the range (scn_min_txg, scn_max_txg]
3261 		 * then it is not eligible for excision.
3262 		 */
3263 		if (vdev_dtl_max(vd) <= scn->scn_phys.scn_max_txg) {
3264 			ASSERT3U(scnp->scn_min_txg, <=, vdev_dtl_min(vd));
3265 			ASSERT3U(scnp->scn_min_txg, <, vd->vdev_resilver_txg);
3266 			ASSERT3U(vd->vdev_resilver_txg, <=, scnp->scn_max_txg);
3267 			return (B_TRUE);
3268 		}
3269 	}
3270 
3271 	return (B_FALSE);
3272 }
3273 
3274 /*
3275  * Reassess DTLs after a config change or scrub completion. If txg == 0 no
3276  * write operations will be issued to the pool.
3277  */
3278 static void
vdev_dtl_reassess_impl(vdev_t * vd,uint64_t txg,uint64_t scrub_txg,boolean_t scrub_done,boolean_t rebuild_done,boolean_t faulting)3279 vdev_dtl_reassess_impl(vdev_t *vd, uint64_t txg, uint64_t scrub_txg,
3280     boolean_t scrub_done, boolean_t rebuild_done, boolean_t faulting)
3281 {
3282 	spa_t *spa = vd->vdev_spa;
3283 	avl_tree_t reftree;
3284 	int minref;
3285 
3286 	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
3287 
3288 	for (int c = 0; c < vd->vdev_children; c++)
3289 		vdev_dtl_reassess_impl(vd->vdev_child[c], txg,
3290 		    scrub_txg, scrub_done, rebuild_done, faulting);
3291 
3292 	if (vd == spa->spa_root_vdev || !vdev_is_concrete(vd) || vd->vdev_aux)
3293 		return;
3294 
3295 	if (vd->vdev_ops->vdev_op_leaf) {
3296 		dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
3297 		vdev_rebuild_t *vr = &vd->vdev_top->vdev_rebuild_config;
3298 		boolean_t check_excise = B_FALSE;
3299 		boolean_t wasempty = B_TRUE;
3300 
3301 		mutex_enter(&vd->vdev_dtl_lock);
3302 
3303 		/*
3304 		 * If requested, pretend the scan or rebuild completed cleanly.
3305 		 */
3306 		if (zfs_scan_ignore_errors) {
3307 			if (scn != NULL)
3308 				scn->scn_phys.scn_errors = 0;
3309 			if (vr != NULL)
3310 				vr->vr_rebuild_phys.vrp_errors = 0;
3311 		}
3312 
3313 		if (scrub_txg != 0 &&
3314 		    !zfs_range_tree_is_empty(vd->vdev_dtl[DTL_MISSING])) {
3315 			wasempty = B_FALSE;
3316 			zfs_dbgmsg("guid:%llu txg:%llu scrub:%llu started:%d "
3317 			    "dtl:%llu/%llu errors:%llu",
3318 			    (u_longlong_t)vd->vdev_guid, (u_longlong_t)txg,
3319 			    (u_longlong_t)scrub_txg, spa->spa_scrub_started,
3320 			    (u_longlong_t)vdev_dtl_min(vd),
3321 			    (u_longlong_t)vdev_dtl_max(vd),
3322 			    (u_longlong_t)(scn ? scn->scn_phys.scn_errors : 0));
3323 		}
3324 
3325 		/*
3326 		 * If we've completed a scrub/resilver or a rebuild cleanly
3327 		 * then determine if this vdev should remove any DTLs. We
3328 		 * only want to excise regions on vdevs that were available
3329 		 * during the entire duration of this scan.
3330 		 */
3331 		if (rebuild_done &&
3332 		    vr != NULL && vr->vr_rebuild_phys.vrp_errors == 0) {
3333 			check_excise = B_TRUE;
3334 		} else {
3335 			if (spa->spa_scrub_started ||
3336 			    (scn != NULL && scn->scn_phys.scn_errors == 0)) {
3337 				check_excise = B_TRUE;
3338 			}
3339 		}
3340 
3341 		if (scrub_txg && check_excise &&
3342 		    vdev_dtl_should_excise(vd, rebuild_done)) {
3343 			/*
3344 			 * We completed a scrub, resilver or rebuild up to
3345 			 * scrub_txg.  If we did it without rebooting, then
3346 			 * the scrub dtl will be valid, so excise the old
3347 			 * region and fold in the scrub dtl.  Otherwise,
3348 			 * leave the dtl as-is if there was an error.
3349 			 *
3350 			 * There's little trick here: to excise the beginning
3351 			 * of the DTL_MISSING map, we put it into a reference
3352 			 * tree and then add a segment with refcnt -1 that
3353 			 * covers the range [0, scrub_txg).  This means
3354 			 * that each txg in that range has refcnt -1 or 0.
3355 			 * We then add DTL_SCRUB with a refcnt of 2, so that
3356 			 * entries in the range [0, scrub_txg) will have a
3357 			 * positive refcnt -- either 1 or 2.  We then convert
3358 			 * the reference tree into the new DTL_MISSING map.
3359 			 */
3360 			space_reftree_create(&reftree);
3361 			space_reftree_add_map(&reftree,
3362 			    vd->vdev_dtl[DTL_MISSING], 1);
3363 			space_reftree_add_seg(&reftree, 0, scrub_txg, -1);
3364 			space_reftree_add_map(&reftree,
3365 			    vd->vdev_dtl[DTL_SCRUB], 2);
3366 			space_reftree_generate_map(&reftree,
3367 			    vd->vdev_dtl[DTL_MISSING], 1);
3368 			space_reftree_destroy(&reftree);
3369 
3370 			if (!zfs_range_tree_is_empty(
3371 			    vd->vdev_dtl[DTL_MISSING])) {
3372 				zfs_dbgmsg("update DTL_MISSING:%llu/%llu",
3373 				    (u_longlong_t)vdev_dtl_min(vd),
3374 				    (u_longlong_t)vdev_dtl_max(vd));
3375 			} else if (!wasempty) {
3376 				zfs_dbgmsg("DTL_MISSING is now empty");
3377 			}
3378 		}
3379 		zfs_range_tree_vacate(vd->vdev_dtl[DTL_PARTIAL], NULL, NULL);
3380 		zfs_range_tree_walk(vd->vdev_dtl[DTL_MISSING],
3381 		    zfs_range_tree_add, vd->vdev_dtl[DTL_PARTIAL]);
3382 		if (scrub_done)
3383 			zfs_range_tree_vacate(vd->vdev_dtl[DTL_SCRUB], NULL,
3384 			    NULL);
3385 		zfs_range_tree_vacate(vd->vdev_dtl[DTL_OUTAGE], NULL, NULL);
3386 
3387 		/*
3388 		 * For the faulting case, treat members of a replacing vdev
3389 		 * as if they are not available. It's more likely than not that
3390 		 * a vdev in a replacing vdev could encounter read errors so
3391 		 * treat it as not being able to contribute.
3392 		 */
3393 		if (!vdev_readable(vd) ||
3394 		    (faulting && vd->vdev_parent != NULL &&
3395 		    vd->vdev_parent->vdev_ops == &vdev_replacing_ops)) {
3396 			zfs_range_tree_add(vd->vdev_dtl[DTL_OUTAGE], 0, -1ULL);
3397 		} else {
3398 			zfs_range_tree_walk(vd->vdev_dtl[DTL_MISSING],
3399 			    zfs_range_tree_add, vd->vdev_dtl[DTL_OUTAGE]);
3400 		}
3401 
3402 		/*
3403 		 * If the vdev was resilvering or rebuilding and no longer
3404 		 * has any DTLs then reset the appropriate flag and dirty
3405 		 * the top level so that we persist the change.
3406 		 */
3407 		if (txg != 0 &&
3408 		    zfs_range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
3409 		    zfs_range_tree_is_empty(vd->vdev_dtl[DTL_OUTAGE])) {
3410 			if (vd->vdev_rebuild_txg != 0) {
3411 				vd->vdev_rebuild_txg = 0;
3412 				vdev_config_dirty(vd->vdev_top);
3413 			} else if (vd->vdev_resilver_txg != 0) {
3414 				vd->vdev_resilver_txg = 0;
3415 				vdev_config_dirty(vd->vdev_top);
3416 			}
3417 		}
3418 
3419 		mutex_exit(&vd->vdev_dtl_lock);
3420 
3421 		if (txg != 0)
3422 			vdev_dirty(vd->vdev_top, VDD_DTL, vd, txg);
3423 	} else {
3424 		mutex_enter(&vd->vdev_dtl_lock);
3425 		for (int t = 0; t < DTL_TYPES; t++) {
3426 			/* account for child's outage in parent's missing map */
3427 			int s = (t == DTL_MISSING) ? DTL_OUTAGE: t;
3428 			if (t == DTL_SCRUB) {
3429 				/* leaf vdevs only */
3430 				continue;
3431 			}
3432 			if (t == DTL_PARTIAL) {
3433 				/* i.e. non-zero */
3434 				minref = 1;
3435 			} else if (vdev_get_nparity(vd) != 0) {
3436 				/* RAIDZ, DRAID */
3437 				minref = vdev_get_nparity(vd) + 1;
3438 			} else {
3439 				/* any kind of mirror */
3440 				minref = vd->vdev_children;
3441 			}
3442 			space_reftree_create(&reftree);
3443 			for (int c = 0; c < vd->vdev_children; c++) {
3444 				vdev_t *cvd = vd->vdev_child[c];
3445 				mutex_enter(&cvd->vdev_dtl_lock);
3446 				space_reftree_add_map(&reftree,
3447 				    cvd->vdev_dtl[s], 1);
3448 				mutex_exit(&cvd->vdev_dtl_lock);
3449 			}
3450 			space_reftree_generate_map(&reftree,
3451 			    vd->vdev_dtl[t], minref);
3452 			space_reftree_destroy(&reftree);
3453 		}
3454 		mutex_exit(&vd->vdev_dtl_lock);
3455 	}
3456 
3457 	if (vd->vdev_top->vdev_ops == &vdev_raidz_ops) {
3458 		raidz_dtl_reassessed(vd);
3459 	}
3460 }
3461 
3462 void
vdev_dtl_reassess(vdev_t * vd,uint64_t txg,uint64_t scrub_txg,boolean_t scrub_done,boolean_t rebuild_done)3463 vdev_dtl_reassess(vdev_t *vd, uint64_t txg, uint64_t scrub_txg,
3464     boolean_t scrub_done, boolean_t rebuild_done)
3465 {
3466 	return (vdev_dtl_reassess_impl(vd, txg, scrub_txg, scrub_done,
3467 	    rebuild_done, B_FALSE));
3468 }
3469 
3470 /*
3471  * Iterate over all the vdevs except spare, and post kobj events
3472  */
3473 void
vdev_post_kobj_evt(vdev_t * vd)3474 vdev_post_kobj_evt(vdev_t *vd)
3475 {
3476 	if (vd->vdev_ops->vdev_op_kobj_evt_post &&
3477 	    vd->vdev_kobj_flag == B_FALSE) {
3478 		vd->vdev_kobj_flag = B_TRUE;
3479 		vd->vdev_ops->vdev_op_kobj_evt_post(vd);
3480 	}
3481 
3482 	for (int c = 0; c < vd->vdev_children; c++)
3483 		vdev_post_kobj_evt(vd->vdev_child[c]);
3484 }
3485 
3486 /*
3487  * Iterate over all the vdevs except spare, and clear kobj events
3488  */
3489 void
vdev_clear_kobj_evt(vdev_t * vd)3490 vdev_clear_kobj_evt(vdev_t *vd)
3491 {
3492 	vd->vdev_kobj_flag = B_FALSE;
3493 
3494 	for (int c = 0; c < vd->vdev_children; c++)
3495 		vdev_clear_kobj_evt(vd->vdev_child[c]);
3496 }
3497 
3498 int
vdev_dtl_load(vdev_t * vd)3499 vdev_dtl_load(vdev_t *vd)
3500 {
3501 	spa_t *spa = vd->vdev_spa;
3502 	objset_t *mos = spa->spa_meta_objset;
3503 	zfs_range_tree_t *rt;
3504 	int error = 0;
3505 
3506 	if (vd->vdev_ops->vdev_op_leaf && vd->vdev_dtl_object != 0) {
3507 		ASSERT(vdev_is_concrete(vd));
3508 
3509 		/*
3510 		 * If the dtl cannot be sync'd there is no need to open it.
3511 		 */
3512 		if (spa->spa_mode == SPA_MODE_READ && !spa->spa_read_spacemaps)
3513 			return (0);
3514 
3515 		error = space_map_open(&vd->vdev_dtl_sm, mos,
3516 		    vd->vdev_dtl_object, 0, -1ULL, 0);
3517 		if (error)
3518 			return (error);
3519 		ASSERT(vd->vdev_dtl_sm != NULL);
3520 
3521 		rt = zfs_range_tree_create_flags(
3522 		    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
3523 		    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "vdev_dtl_load:rt"));
3524 		error = space_map_load(vd->vdev_dtl_sm, rt, SM_ALLOC);
3525 		if (error == 0) {
3526 			mutex_enter(&vd->vdev_dtl_lock);
3527 			zfs_range_tree_walk(rt, zfs_range_tree_add,
3528 			    vd->vdev_dtl[DTL_MISSING]);
3529 			mutex_exit(&vd->vdev_dtl_lock);
3530 		}
3531 
3532 		zfs_range_tree_vacate(rt, NULL, NULL);
3533 		zfs_range_tree_destroy(rt);
3534 
3535 		return (error);
3536 	}
3537 
3538 	for (int c = 0; c < vd->vdev_children; c++) {
3539 		error = vdev_dtl_load(vd->vdev_child[c]);
3540 		if (error != 0)
3541 			break;
3542 	}
3543 
3544 	return (error);
3545 }
3546 
3547 static void
vdev_zap_allocation_data(vdev_t * vd,dmu_tx_t * tx)3548 vdev_zap_allocation_data(vdev_t *vd, dmu_tx_t *tx)
3549 {
3550 	spa_t *spa = vd->vdev_spa;
3551 	objset_t *mos = spa->spa_meta_objset;
3552 	vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
3553 	const char *string;
3554 
3555 	ASSERT(alloc_bias != VDEV_BIAS_NONE);
3556 
3557 	string =
3558 	    (alloc_bias == VDEV_BIAS_LOG) ? VDEV_ALLOC_BIAS_LOG :
3559 	    (alloc_bias == VDEV_BIAS_SPECIAL) ? VDEV_ALLOC_BIAS_SPECIAL :
3560 	    (alloc_bias == VDEV_BIAS_DEDUP) ? VDEV_ALLOC_BIAS_DEDUP : NULL;
3561 
3562 	ASSERT(string != NULL);
3563 	VERIFY0(zap_add(mos, vd->vdev_top_zap, VDEV_TOP_ZAP_ALLOCATION_BIAS,
3564 	    1, strlen(string) + 1, string, tx));
3565 
3566 	if (alloc_bias == VDEV_BIAS_SPECIAL || alloc_bias == VDEV_BIAS_DEDUP) {
3567 		spa_activate_allocation_classes(spa, tx);
3568 	}
3569 }
3570 
3571 void
vdev_destroy_unlink_zap(vdev_t * vd,uint64_t zapobj,dmu_tx_t * tx)3572 vdev_destroy_unlink_zap(vdev_t *vd, uint64_t zapobj, dmu_tx_t *tx)
3573 {
3574 	spa_t *spa = vd->vdev_spa;
3575 
3576 	VERIFY0(zap_destroy(spa->spa_meta_objset, zapobj, tx));
3577 	VERIFY0(zap_remove_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
3578 	    zapobj, tx));
3579 }
3580 
3581 uint64_t
vdev_create_link_zap(vdev_t * vd,dmu_tx_t * tx)3582 vdev_create_link_zap(vdev_t *vd, dmu_tx_t *tx)
3583 {
3584 	spa_t *spa = vd->vdev_spa;
3585 	uint64_t zap = zap_create(spa->spa_meta_objset, DMU_OTN_ZAP_METADATA,
3586 	    DMU_OT_NONE, 0, tx);
3587 
3588 	ASSERT(zap != 0);
3589 	VERIFY0(zap_add_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
3590 	    zap, tx));
3591 
3592 	return (zap);
3593 }
3594 
3595 void
vdev_construct_zaps(vdev_t * vd,dmu_tx_t * tx)3596 vdev_construct_zaps(vdev_t *vd, dmu_tx_t *tx)
3597 {
3598 	if (vd->vdev_ops != &vdev_hole_ops &&
3599 	    vd->vdev_ops != &vdev_missing_ops &&
3600 	    vd->vdev_ops != &vdev_root_ops &&
3601 	    !vd->vdev_top->vdev_removing) {
3602 		if (vd->vdev_ops->vdev_op_leaf && vd->vdev_leaf_zap == 0) {
3603 			vd->vdev_leaf_zap = vdev_create_link_zap(vd, tx);
3604 		}
3605 		if (vd == vd->vdev_top && vd->vdev_top_zap == 0) {
3606 			vd->vdev_top_zap = vdev_create_link_zap(vd, tx);
3607 			if (vd->vdev_alloc_bias != VDEV_BIAS_NONE)
3608 				vdev_zap_allocation_data(vd, tx);
3609 		}
3610 	}
3611 	if (vd->vdev_ops == &vdev_root_ops && vd->vdev_root_zap == 0 &&
3612 	    spa_feature_is_enabled(vd->vdev_spa, SPA_FEATURE_AVZ_V2)) {
3613 		if (!spa_feature_is_active(vd->vdev_spa, SPA_FEATURE_AVZ_V2))
3614 			spa_feature_incr(vd->vdev_spa, SPA_FEATURE_AVZ_V2, tx);
3615 		vd->vdev_root_zap = vdev_create_link_zap(vd, tx);
3616 	}
3617 
3618 	for (uint64_t i = 0; i < vd->vdev_children; i++) {
3619 		vdev_construct_zaps(vd->vdev_child[i], tx);
3620 	}
3621 }
3622 
3623 static void
vdev_dtl_sync(vdev_t * vd,uint64_t txg)3624 vdev_dtl_sync(vdev_t *vd, uint64_t txg)
3625 {
3626 	spa_t *spa = vd->vdev_spa;
3627 	zfs_range_tree_t *rt = vd->vdev_dtl[DTL_MISSING];
3628 	objset_t *mos = spa->spa_meta_objset;
3629 	zfs_range_tree_t *rtsync;
3630 	dmu_tx_t *tx;
3631 	uint64_t object = space_map_object(vd->vdev_dtl_sm);
3632 
3633 	ASSERT(vdev_is_concrete(vd));
3634 	ASSERT(vd->vdev_ops->vdev_op_leaf);
3635 
3636 	tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
3637 
3638 	if (vd->vdev_detached || vd->vdev_top->vdev_removing) {
3639 		mutex_enter(&vd->vdev_dtl_lock);
3640 		space_map_free(vd->vdev_dtl_sm, tx);
3641 		space_map_close(vd->vdev_dtl_sm);
3642 		vd->vdev_dtl_sm = NULL;
3643 		mutex_exit(&vd->vdev_dtl_lock);
3644 
3645 		/*
3646 		 * We only destroy the leaf ZAP for detached leaves or for
3647 		 * removed log devices. Removed data devices handle leaf ZAP
3648 		 * cleanup later, once cancellation is no longer possible.
3649 		 */
3650 		if (vd->vdev_leaf_zap != 0 && (vd->vdev_detached ||
3651 		    vd->vdev_top->vdev_islog)) {
3652 			vdev_destroy_unlink_zap(vd, vd->vdev_leaf_zap, tx);
3653 			vd->vdev_leaf_zap = 0;
3654 		}
3655 
3656 		dmu_tx_commit(tx);
3657 		return;
3658 	}
3659 
3660 	if (vd->vdev_dtl_sm == NULL) {
3661 		uint64_t new_object;
3662 
3663 		new_object = space_map_alloc(mos, zfs_vdev_dtl_sm_blksz, tx);
3664 		VERIFY3U(new_object, !=, 0);
3665 
3666 		VERIFY0(space_map_open(&vd->vdev_dtl_sm, mos, new_object,
3667 		    0, -1ULL, 0));
3668 		ASSERT(vd->vdev_dtl_sm != NULL);
3669 	}
3670 
3671 	rtsync = zfs_range_tree_create_flags(NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
3672 	    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "rtsync"));
3673 
3674 	mutex_enter(&vd->vdev_dtl_lock);
3675 	zfs_range_tree_walk(rt, zfs_range_tree_add, rtsync);
3676 	mutex_exit(&vd->vdev_dtl_lock);
3677 
3678 	space_map_truncate(vd->vdev_dtl_sm, zfs_vdev_dtl_sm_blksz, tx);
3679 	space_map_write(vd->vdev_dtl_sm, rtsync, SM_ALLOC, SM_NO_VDEVID, tx);
3680 	zfs_range_tree_vacate(rtsync, NULL, NULL);
3681 
3682 	zfs_range_tree_destroy(rtsync);
3683 
3684 	/*
3685 	 * If the object for the space map has changed then dirty
3686 	 * the top level so that we update the config.
3687 	 */
3688 	if (object != space_map_object(vd->vdev_dtl_sm)) {
3689 		vdev_dbgmsg(vd, "txg %llu, spa %s, DTL old object %llu, "
3690 		    "new object %llu", (u_longlong_t)txg, spa_name(spa),
3691 		    (u_longlong_t)object,
3692 		    (u_longlong_t)space_map_object(vd->vdev_dtl_sm));
3693 		vdev_config_dirty(vd->vdev_top);
3694 	}
3695 
3696 	dmu_tx_commit(tx);
3697 }
3698 
3699 /*
3700  * Determine whether the specified vdev can be
3701  * - offlined
3702  * - detached
3703  * - removed
3704  * - faulted
3705  * without losing data.
3706  */
3707 boolean_t
vdev_dtl_required(vdev_t * vd)3708 vdev_dtl_required(vdev_t *vd)
3709 {
3710 	spa_t *spa = vd->vdev_spa;
3711 	vdev_t *tvd = vd->vdev_top;
3712 	uint8_t cant_read = vd->vdev_cant_read;
3713 	boolean_t required;
3714 	boolean_t faulting = vd->vdev_state == VDEV_STATE_FAULTED;
3715 
3716 	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
3717 
3718 	if (vd == spa->spa_root_vdev || vd == tvd)
3719 		return (B_TRUE);
3720 
3721 	/*
3722 	 * Temporarily mark the device as unreadable, and then determine
3723 	 * whether this results in any DTL outages in the top-level vdev.
3724 	 * If not, we can safely offline/detach/remove the device.
3725 	 */
3726 	vd->vdev_cant_read = B_TRUE;
3727 	vdev_dtl_reassess_impl(tvd, 0, 0, B_FALSE, B_FALSE, faulting);
3728 	required = !vdev_dtl_empty(tvd, DTL_OUTAGE);
3729 	vd->vdev_cant_read = cant_read;
3730 	vdev_dtl_reassess_impl(tvd, 0, 0, B_FALSE, B_FALSE, faulting);
3731 
3732 	if (!required && zio_injection_enabled) {
3733 		required = !!zio_handle_device_injection(vd, NULL,
3734 		    SET_ERROR(ECHILD));
3735 	}
3736 
3737 	return (required);
3738 }
3739 
3740 /*
3741  * Determine if resilver is needed, and if so the txg range.
3742  */
3743 boolean_t
vdev_resilver_needed(vdev_t * vd,uint64_t * minp,uint64_t * maxp)3744 vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
3745 {
3746 	boolean_t needed = B_FALSE;
3747 	uint64_t thismin = UINT64_MAX;
3748 	uint64_t thismax = 0;
3749 
3750 	if (vd->vdev_children == 0) {
3751 		mutex_enter(&vd->vdev_dtl_lock);
3752 		if (!zfs_range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
3753 		    vdev_writeable(vd)) {
3754 
3755 			thismin = vdev_dtl_min(vd);
3756 			thismax = vdev_dtl_max(vd);
3757 			needed = B_TRUE;
3758 		}
3759 		mutex_exit(&vd->vdev_dtl_lock);
3760 	} else {
3761 		for (int c = 0; c < vd->vdev_children; c++) {
3762 			vdev_t *cvd = vd->vdev_child[c];
3763 			uint64_t cmin, cmax;
3764 
3765 			if (vdev_resilver_needed(cvd, &cmin, &cmax)) {
3766 				thismin = MIN(thismin, cmin);
3767 				thismax = MAX(thismax, cmax);
3768 				needed = B_TRUE;
3769 			}
3770 		}
3771 	}
3772 
3773 	if (needed && minp) {
3774 		*minp = thismin;
3775 		*maxp = thismax;
3776 	}
3777 	return (needed);
3778 }
3779 
3780 /*
3781  * Gets the checkpoint space map object from the vdev's ZAP.  On success sm_obj
3782  * will contain either the checkpoint spacemap object or zero if none exists.
3783  * All other errors are returned to the caller.
3784  */
3785 int
vdev_checkpoint_sm_object(vdev_t * vd,uint64_t * sm_obj)3786 vdev_checkpoint_sm_object(vdev_t *vd, uint64_t *sm_obj)
3787 {
3788 	ASSERT0(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER));
3789 
3790 	if (vd->vdev_top_zap == 0) {
3791 		*sm_obj = 0;
3792 		return (0);
3793 	}
3794 
3795 	int error = zap_lookup(spa_meta_objset(vd->vdev_spa), vd->vdev_top_zap,
3796 	    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1, sm_obj);
3797 	if (error == ENOENT) {
3798 		*sm_obj = 0;
3799 		error = 0;
3800 	}
3801 
3802 	return (error);
3803 }
3804 
3805 int
vdev_load(vdev_t * vd)3806 vdev_load(vdev_t *vd)
3807 {
3808 	int children = vd->vdev_children;
3809 	int error = 0;
3810 	taskq_t *tq = NULL;
3811 
3812 	/*
3813 	 * It's only worthwhile to use the taskq for the root vdev, because the
3814 	 * slow part is metaslab_init, and that only happens for top-level
3815 	 * vdevs.
3816 	 */
3817 	if (vd->vdev_ops == &vdev_root_ops && vd->vdev_children > 0) {
3818 		tq = taskq_create("vdev_load", children, minclsyspri,
3819 		    children, children, TASKQ_PREPOPULATE);
3820 	}
3821 
3822 	/*
3823 	 * Recursively load all children.
3824 	 */
3825 	for (int c = 0; c < vd->vdev_children; c++) {
3826 		vdev_t *cvd = vd->vdev_child[c];
3827 
3828 		if (tq == NULL || vdev_uses_zvols(cvd)) {
3829 			cvd->vdev_load_error = vdev_load(cvd);
3830 		} else {
3831 			VERIFY(taskq_dispatch(tq, vdev_load_child,
3832 			    cvd, TQ_SLEEP) != TASKQID_INVALID);
3833 		}
3834 	}
3835 
3836 	if (tq != NULL) {
3837 		taskq_wait(tq);
3838 		taskq_destroy(tq);
3839 	}
3840 
3841 	for (int c = 0; c < vd->vdev_children; c++) {
3842 		int error = vd->vdev_child[c]->vdev_load_error;
3843 
3844 		if (error != 0)
3845 			return (error);
3846 	}
3847 
3848 	vdev_set_deflate_ratio(vd);
3849 
3850 	if (vd->vdev_ops == &vdev_raidz_ops) {
3851 		error = vdev_raidz_load(vd);
3852 		if (error != 0)
3853 			return (error);
3854 	}
3855 
3856 	/*
3857 	 * On spa_load path, grab the allocation bias from our zap
3858 	 */
3859 	if (vd == vd->vdev_top && vd->vdev_top_zap != 0) {
3860 		spa_t *spa = vd->vdev_spa;
3861 		char bias_str[64];
3862 
3863 		error = zap_lookup(spa->spa_meta_objset, vd->vdev_top_zap,
3864 		    VDEV_TOP_ZAP_ALLOCATION_BIAS, 1, sizeof (bias_str),
3865 		    bias_str);
3866 		if (error == 0) {
3867 			ASSERT(vd->vdev_alloc_bias == VDEV_BIAS_NONE);
3868 			vd->vdev_alloc_bias = vdev_derive_alloc_bias(bias_str);
3869 		} else if (error != ENOENT) {
3870 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3871 			    VDEV_AUX_CORRUPT_DATA);
3872 			vdev_dbgmsg(vd, "vdev_load: zap_lookup(top_zap=%llu) "
3873 			    "failed [error=%d]",
3874 			    (u_longlong_t)vd->vdev_top_zap, error);
3875 			return (error);
3876 		}
3877 	}
3878 
3879 	if (vd == vd->vdev_top && vd->vdev_top_zap != 0) {
3880 		spa_t *spa = vd->vdev_spa;
3881 		uint64_t failfast;
3882 
3883 		error = zap_lookup(spa->spa_meta_objset, vd->vdev_top_zap,
3884 		    vdev_prop_to_name(VDEV_PROP_FAILFAST), sizeof (failfast),
3885 		    1, &failfast);
3886 		if (error == 0) {
3887 			vd->vdev_failfast = failfast & 1;
3888 		} else if (error == ENOENT) {
3889 			vd->vdev_failfast = vdev_prop_default_numeric(
3890 			    VDEV_PROP_FAILFAST);
3891 		} else {
3892 			vdev_dbgmsg(vd,
3893 			    "vdev_load: zap_lookup(top_zap=%llu) "
3894 			    "failed [error=%d]",
3895 			    (u_longlong_t)vd->vdev_top_zap, error);
3896 		}
3897 	}
3898 
3899 	if (vd == vd->vdev_top && vd->vdev_top_zap != 0) {
3900 		spa_t *spa = vd->vdev_spa;
3901 		uint64_t autosit;
3902 
3903 		error = zap_lookup(spa->spa_meta_objset, vd->vdev_top_zap,
3904 		    vdev_prop_to_name(VDEV_PROP_AUTOSIT), sizeof (autosit),
3905 		    1, &autosit);
3906 		if (error == 0) {
3907 			vd->vdev_autosit = autosit == 1;
3908 		} else if (error == ENOENT) {
3909 			vd->vdev_autosit = vdev_prop_default_numeric(
3910 			    VDEV_PROP_AUTOSIT);
3911 		} else {
3912 			vdev_dbgmsg(vd,
3913 			    "vdev_load: zap_lookup(top_zap=%llu) "
3914 			    "failed [error=%d]",
3915 			    (u_longlong_t)vd->vdev_top_zap, error);
3916 		}
3917 	}
3918 
3919 	/*
3920 	 * Load any rebuild state from the top-level vdev zap.
3921 	 */
3922 	if (vd == vd->vdev_top && vd->vdev_top_zap != 0) {
3923 		error = vdev_rebuild_load(vd);
3924 		if (error && error != ENOTSUP) {
3925 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3926 			    VDEV_AUX_CORRUPT_DATA);
3927 			vdev_dbgmsg(vd, "vdev_load: vdev_rebuild_load "
3928 			    "failed [error=%d]", error);
3929 			return (error);
3930 		}
3931 	}
3932 
3933 	if (vd->vdev_top_zap != 0 || vd->vdev_leaf_zap != 0) {
3934 		uint64_t zapobj;
3935 
3936 		if (vd->vdev_top_zap != 0)
3937 			zapobj = vd->vdev_top_zap;
3938 		else
3939 			zapobj = vd->vdev_leaf_zap;
3940 
3941 		error = vdev_prop_get_int(vd, VDEV_PROP_CHECKSUM_N,
3942 		    &vd->vdev_checksum_n);
3943 		if (error && error != ENOENT)
3944 			vdev_dbgmsg(vd, "vdev_load: zap_lookup(zap=%llu) "
3945 			    "failed [error=%d]", (u_longlong_t)zapobj, error);
3946 
3947 		error = vdev_prop_get_int(vd, VDEV_PROP_CHECKSUM_T,
3948 		    &vd->vdev_checksum_t);
3949 		if (error && error != ENOENT)
3950 			vdev_dbgmsg(vd, "vdev_load: zap_lookup(zap=%llu) "
3951 			    "failed [error=%d]", (u_longlong_t)zapobj, error);
3952 
3953 		error = vdev_prop_get_int(vd, VDEV_PROP_IO_N,
3954 		    &vd->vdev_io_n);
3955 		if (error && error != ENOENT)
3956 			vdev_dbgmsg(vd, "vdev_load: zap_lookup(zap=%llu) "
3957 			    "failed [error=%d]", (u_longlong_t)zapobj, error);
3958 
3959 		error = vdev_prop_get_int(vd, VDEV_PROP_IO_T,
3960 		    &vd->vdev_io_t);
3961 		if (error && error != ENOENT)
3962 			vdev_dbgmsg(vd, "vdev_load: zap_lookup(zap=%llu) "
3963 			    "failed [error=%d]", (u_longlong_t)zapobj, error);
3964 
3965 		error = vdev_prop_get_bool(vd, VDEV_PROP_SLOW_IO_EVENTS,
3966 		    &vd->vdev_slow_io_events);
3967 		if (error && error != ENOENT)
3968 			vdev_dbgmsg(vd, "vdev_load: zap_lookup(zap=%llu) "
3969 			    "failed [error=%d]", (u_longlong_t)zapobj, error);
3970 		error = vdev_prop_get_int(vd, VDEV_PROP_SLOW_IO_N,
3971 		    &vd->vdev_slow_io_n);
3972 		if (error && error != ENOENT)
3973 			vdev_dbgmsg(vd, "vdev_load: zap_lookup(zap=%llu) "
3974 			    "failed [error=%d]", (u_longlong_t)zapobj, error);
3975 
3976 		error = vdev_prop_get_int(vd, VDEV_PROP_SLOW_IO_T,
3977 		    &vd->vdev_slow_io_t);
3978 		if (error && error != ENOENT)
3979 			vdev_dbgmsg(vd, "vdev_load: zap_lookup(zap=%llu) "
3980 			    "failed [error=%d]", (u_longlong_t)zapobj, error);
3981 
3982 		error = vdev_prop_get_int(vd, VDEV_PROP_SCHEDULER,
3983 		    &vd->vdev_scheduler);
3984 		if (error && error != ENOENT)
3985 			vdev_dbgmsg(vd, "vdev_load: zap_lookup(zap=%llu) "
3986 			    "failed [error=%d]", (u_longlong_t)zapobj, error);
3987 	}
3988 
3989 	/*
3990 	 * If this is a top-level vdev, initialize its metaslabs.
3991 	 */
3992 	if (vd == vd->vdev_top && vdev_is_concrete(vd)) {
3993 		vdev_metaslab_group_create(vd);
3994 
3995 		if (vd->vdev_ashift == 0 || vd->vdev_asize == 0) {
3996 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3997 			    VDEV_AUX_CORRUPT_DATA);
3998 			vdev_dbgmsg(vd, "vdev_load: invalid size. ashift=%llu, "
3999 			    "asize=%llu", (u_longlong_t)vd->vdev_ashift,
4000 			    (u_longlong_t)vd->vdev_asize);
4001 			return (SET_ERROR(ENXIO));
4002 		}
4003 
4004 		error = vdev_metaslab_init(vd, 0);
4005 		if (error != 0) {
4006 			vdev_dbgmsg(vd, "vdev_load: metaslab_init failed "
4007 			    "[error=%d]", error);
4008 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
4009 			    VDEV_AUX_CORRUPT_DATA);
4010 			return (error);
4011 		}
4012 
4013 		uint64_t checkpoint_sm_obj;
4014 		error = vdev_checkpoint_sm_object(vd, &checkpoint_sm_obj);
4015 		if (error == 0 && checkpoint_sm_obj != 0) {
4016 			objset_t *mos = spa_meta_objset(vd->vdev_spa);
4017 			ASSERT(vd->vdev_asize != 0);
4018 			ASSERT0P(vd->vdev_checkpoint_sm);
4019 
4020 			error = space_map_open(&vd->vdev_checkpoint_sm,
4021 			    mos, checkpoint_sm_obj, 0, vd->vdev_asize,
4022 			    vd->vdev_ashift);
4023 			if (error != 0) {
4024 				vdev_dbgmsg(vd, "vdev_load: space_map_open "
4025 				    "failed for checkpoint spacemap (obj %llu) "
4026 				    "[error=%d]",
4027 				    (u_longlong_t)checkpoint_sm_obj, error);
4028 				return (error);
4029 			}
4030 			ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
4031 
4032 			/*
4033 			 * Since the checkpoint_sm contains free entries
4034 			 * exclusively we can use space_map_allocated() to
4035 			 * indicate the cumulative checkpointed space that
4036 			 * has been freed.
4037 			 */
4038 			vd->vdev_stat.vs_checkpoint_space =
4039 			    -space_map_allocated(vd->vdev_checkpoint_sm);
4040 			vd->vdev_spa->spa_checkpoint_info.sci_dspace +=
4041 			    vd->vdev_stat.vs_checkpoint_space;
4042 		} else if (error != 0) {
4043 			vdev_dbgmsg(vd, "vdev_load: failed to retrieve "
4044 			    "checkpoint space map object from vdev ZAP "
4045 			    "[error=%d]", error);
4046 			return (error);
4047 		}
4048 	}
4049 
4050 	/*
4051 	 * If this is a leaf vdev, load its DTL.
4052 	 */
4053 	if (vd->vdev_ops->vdev_op_leaf && (error = vdev_dtl_load(vd)) != 0) {
4054 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
4055 		    VDEV_AUX_CORRUPT_DATA);
4056 		vdev_dbgmsg(vd, "vdev_load: vdev_dtl_load failed "
4057 		    "[error=%d]", error);
4058 		return (error);
4059 	}
4060 
4061 	uint64_t obsolete_sm_object;
4062 	error = vdev_obsolete_sm_object(vd, &obsolete_sm_object);
4063 	if (error == 0 && obsolete_sm_object != 0) {
4064 		objset_t *mos = vd->vdev_spa->spa_meta_objset;
4065 		ASSERT(vd->vdev_asize != 0);
4066 		ASSERT0P(vd->vdev_obsolete_sm);
4067 
4068 		if ((error = space_map_open(&vd->vdev_obsolete_sm, mos,
4069 		    obsolete_sm_object, 0, vd->vdev_asize, 0))) {
4070 			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
4071 			    VDEV_AUX_CORRUPT_DATA);
4072 			vdev_dbgmsg(vd, "vdev_load: space_map_open failed for "
4073 			    "obsolete spacemap (obj %llu) [error=%d]",
4074 			    (u_longlong_t)obsolete_sm_object, error);
4075 			return (error);
4076 		}
4077 	} else if (error != 0) {
4078 		vdev_dbgmsg(vd, "vdev_load: failed to retrieve obsolete "
4079 		    "space map object from vdev ZAP [error=%d]", error);
4080 		return (error);
4081 	}
4082 
4083 	return (0);
4084 }
4085 
4086 /*
4087  * The special vdev case is used for hot spares and l2cache devices.  Its
4088  * sole purpose it to set the vdev state for the associated vdev.  To do this,
4089  * we make sure that we can open the underlying device, then try to read the
4090  * label, and make sure that the label is sane and that it hasn't been
4091  * repurposed to another pool.
4092  */
4093 int
vdev_validate_aux(vdev_t * vd)4094 vdev_validate_aux(vdev_t *vd)
4095 {
4096 	nvlist_t *label;
4097 	uint64_t guid, version;
4098 	uint64_t state;
4099 
4100 	if (!vdev_readable(vd))
4101 		return (0);
4102 
4103 	if ((label = vdev_label_read_config(vd, -1ULL)) == NULL) {
4104 		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
4105 		    VDEV_AUX_CORRUPT_DATA);
4106 		return (-1);
4107 	}
4108 
4109 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_VERSION, &version) != 0 ||
4110 	    !SPA_VERSION_IS_SUPPORTED(version) ||
4111 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0 ||
4112 	    guid != vd->vdev_guid ||
4113 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE, &state) != 0) {
4114 		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
4115 		    VDEV_AUX_CORRUPT_DATA);
4116 		nvlist_free(label);
4117 		return (-1);
4118 	}
4119 
4120 	/*
4121 	 * We don't actually check the pool state here.  If it's in fact in
4122 	 * use by another pool, we update this fact on the fly when requested.
4123 	 */
4124 	nvlist_free(label);
4125 	return (0);
4126 }
4127 
4128 static void
vdev_destroy_ms_flush_data(vdev_t * vd,dmu_tx_t * tx)4129 vdev_destroy_ms_flush_data(vdev_t *vd, dmu_tx_t *tx)
4130 {
4131 	objset_t *mos = spa_meta_objset(vd->vdev_spa);
4132 
4133 	if (vd->vdev_top_zap == 0)
4134 		return;
4135 
4136 	uint64_t object = 0;
4137 	int err = zap_lookup(mos, vd->vdev_top_zap,
4138 	    VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, sizeof (uint64_t), 1, &object);
4139 	if (err == ENOENT)
4140 		return;
4141 	VERIFY0(err);
4142 
4143 	VERIFY0(dmu_object_free(mos, object, tx));
4144 	VERIFY0(zap_remove(mos, vd->vdev_top_zap,
4145 	    VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, tx));
4146 }
4147 
4148 /*
4149  * Free the objects used to store this vdev's spacemaps, and the array
4150  * that points to them.
4151  */
4152 void
vdev_destroy_spacemaps(vdev_t * vd,dmu_tx_t * tx)4153 vdev_destroy_spacemaps(vdev_t *vd, dmu_tx_t *tx)
4154 {
4155 	if (vd->vdev_ms_array == 0)
4156 		return;
4157 
4158 	objset_t *mos = vd->vdev_spa->spa_meta_objset;
4159 	uint64_t array_count = vd->vdev_asize >> vd->vdev_ms_shift;
4160 	size_t array_bytes = array_count * sizeof (uint64_t);
4161 	uint64_t *smobj_array = kmem_alloc(array_bytes, KM_SLEEP);
4162 	VERIFY0(dmu_read(mos, vd->vdev_ms_array, 0,
4163 	    array_bytes, smobj_array, 0));
4164 
4165 	for (uint64_t i = 0; i < array_count; i++) {
4166 		uint64_t smobj = smobj_array[i];
4167 		if (smobj == 0)
4168 			continue;
4169 
4170 		space_map_free_obj(mos, smobj, tx);
4171 	}
4172 
4173 	kmem_free(smobj_array, array_bytes);
4174 	VERIFY0(dmu_object_free(mos, vd->vdev_ms_array, tx));
4175 	vdev_destroy_ms_flush_data(vd, tx);
4176 	vd->vdev_ms_array = 0;
4177 }
4178 
4179 static void
vdev_remove_empty_log(vdev_t * vd,uint64_t txg)4180 vdev_remove_empty_log(vdev_t *vd, uint64_t txg)
4181 {
4182 	spa_t *spa = vd->vdev_spa;
4183 
4184 	ASSERT(vd->vdev_islog);
4185 	ASSERT(vd == vd->vdev_top);
4186 	ASSERT3U(txg, ==, spa_syncing_txg(spa));
4187 
4188 	dmu_tx_t *tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
4189 
4190 	vdev_destroy_spacemaps(vd, tx);
4191 	if (vd->vdev_top_zap != 0) {
4192 		vdev_destroy_unlink_zap(vd, vd->vdev_top_zap, tx);
4193 		vd->vdev_top_zap = 0;
4194 	}
4195 
4196 	dmu_tx_commit(tx);
4197 }
4198 
4199 void
vdev_sync_done(vdev_t * vd,uint64_t txg)4200 vdev_sync_done(vdev_t *vd, uint64_t txg)
4201 {
4202 	metaslab_t *msp;
4203 	boolean_t reassess = !txg_list_empty(&vd->vdev_ms_list, TXG_CLEAN(txg));
4204 
4205 	ASSERT(vdev_is_concrete(vd));
4206 
4207 	while ((msp = txg_list_remove(&vd->vdev_ms_list, TXG_CLEAN(txg)))
4208 	    != NULL)
4209 		metaslab_sync_done(msp, txg);
4210 
4211 	if (reassess) {
4212 		metaslab_sync_reassess(vd->vdev_mg);
4213 		if (vd->vdev_log_mg != NULL)
4214 			metaslab_sync_reassess(vd->vdev_log_mg);
4215 	}
4216 }
4217 
4218 void
vdev_sync(vdev_t * vd,uint64_t txg)4219 vdev_sync(vdev_t *vd, uint64_t txg)
4220 {
4221 	spa_t *spa = vd->vdev_spa;
4222 	vdev_t *lvd;
4223 	metaslab_t *msp;
4224 
4225 	ASSERT3U(txg, ==, spa->spa_syncing_txg);
4226 	dmu_tx_t *tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
4227 	if (zfs_range_tree_space(vd->vdev_obsolete_segments) > 0) {
4228 		ASSERT(vd->vdev_removing ||
4229 		    vd->vdev_ops == &vdev_indirect_ops);
4230 
4231 		vdev_indirect_sync_obsolete(vd, tx);
4232 
4233 		/*
4234 		 * If the vdev is indirect, it can't have dirty
4235 		 * metaslabs or DTLs.
4236 		 */
4237 		if (vd->vdev_ops == &vdev_indirect_ops) {
4238 			ASSERT(txg_list_empty(&vd->vdev_ms_list, txg));
4239 			ASSERT(txg_list_empty(&vd->vdev_dtl_list, txg));
4240 			dmu_tx_commit(tx);
4241 			return;
4242 		}
4243 	}
4244 
4245 	ASSERT(vdev_is_concrete(vd));
4246 
4247 	if (vd->vdev_ms_array == 0 && vd->vdev_ms_shift != 0 &&
4248 	    !vd->vdev_removing) {
4249 		ASSERT(vd == vd->vdev_top);
4250 		ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
4251 		vd->vdev_ms_array = dmu_object_alloc(spa->spa_meta_objset,
4252 		    DMU_OT_OBJECT_ARRAY, 0, DMU_OT_NONE, 0, tx);
4253 		ASSERT(vd->vdev_ms_array != 0);
4254 		vdev_config_dirty(vd);
4255 	}
4256 
4257 	while ((msp = txg_list_remove(&vd->vdev_ms_list, txg)) != NULL) {
4258 		metaslab_sync(msp, txg);
4259 		(void) txg_list_add(&vd->vdev_ms_list, msp, TXG_CLEAN(txg));
4260 	}
4261 
4262 	while ((lvd = txg_list_remove(&vd->vdev_dtl_list, txg)) != NULL)
4263 		vdev_dtl_sync(lvd, txg);
4264 
4265 	/*
4266 	 * If this is an empty log device being removed, destroy the
4267 	 * metadata associated with it.
4268 	 */
4269 	if (vd->vdev_islog && vd->vdev_stat.vs_alloc == 0 && vd->vdev_removing)
4270 		vdev_remove_empty_log(vd, txg);
4271 
4272 	(void) txg_list_add(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg));
4273 	dmu_tx_commit(tx);
4274 }
4275 uint64_t
vdev_asize_to_psize_txg(vdev_t * vd,uint64_t asize,uint64_t txg)4276 vdev_asize_to_psize_txg(vdev_t *vd, uint64_t asize, uint64_t txg)
4277 {
4278 	return (vd->vdev_ops->vdev_op_asize_to_psize(vd, asize, txg));
4279 }
4280 
4281 /*
4282  * Return the amount of space that should be (or was) allocated for the given
4283  * psize (compressed block size) in the given TXG. Note that for expanded
4284  * RAIDZ vdevs, the size allocated for older BP's may be larger. See
4285  * vdev_raidz_psize_to_asize().
4286  */
4287 uint64_t
vdev_psize_to_asize_txg(vdev_t * vd,uint64_t psize,uint64_t txg)4288 vdev_psize_to_asize_txg(vdev_t *vd, uint64_t psize, uint64_t txg)
4289 {
4290 	return (vd->vdev_ops->vdev_op_psize_to_asize(vd, psize, txg));
4291 }
4292 
4293 uint64_t
vdev_psize_to_asize(vdev_t * vd,uint64_t psize)4294 vdev_psize_to_asize(vdev_t *vd, uint64_t psize)
4295 {
4296 	return (vdev_psize_to_asize_txg(vd, psize, 0));
4297 }
4298 
4299 /*
4300  * Mark the given vdev faulted.  A faulted vdev behaves as if the device could
4301  * not be opened, and no I/O is attempted.
4302  */
4303 int
vdev_fault(spa_t * spa,uint64_t guid,vdev_aux_t aux)4304 vdev_fault(spa_t *spa, uint64_t guid, vdev_aux_t aux)
4305 {
4306 	vdev_t *vd, *tvd;
4307 
4308 	spa_vdev_state_enter(spa, SCL_NONE);
4309 
4310 	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
4311 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENODEV)));
4312 
4313 	if (!vd->vdev_ops->vdev_op_leaf)
4314 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENOTSUP)));
4315 
4316 	tvd = vd->vdev_top;
4317 
4318 	/*
4319 	 * If user did a 'zpool offline -f' then make the fault persist across
4320 	 * reboots.
4321 	 */
4322 	if (aux == VDEV_AUX_EXTERNAL_PERSIST) {
4323 		/*
4324 		 * There are two kinds of forced faults: temporary and
4325 		 * persistent.  Temporary faults go away at pool import, while
4326 		 * persistent faults stay set.  Both types of faults can be
4327 		 * cleared with a zpool clear.
4328 		 *
4329 		 * We tell if a vdev is persistently faulted by looking at the
4330 		 * ZPOOL_CONFIG_AUX_STATE nvpair.  If it's set to "external" at
4331 		 * import then it's a persistent fault.  Otherwise, it's
4332 		 * temporary.  We get ZPOOL_CONFIG_AUX_STATE set to "external"
4333 		 * by setting vd.vdev_stat.vs_aux to VDEV_AUX_EXTERNAL.  This
4334 		 * tells vdev_config_generate() (which gets run later) to set
4335 		 * ZPOOL_CONFIG_AUX_STATE to "external" in the nvlist.
4336 		 */
4337 		vd->vdev_stat.vs_aux = VDEV_AUX_EXTERNAL;
4338 		vd->vdev_tmpoffline = B_FALSE;
4339 		aux = VDEV_AUX_EXTERNAL;
4340 	} else {
4341 		vd->vdev_tmpoffline = B_TRUE;
4342 	}
4343 
4344 	/*
4345 	 * We don't directly use the aux state here, but if we do a
4346 	 * vdev_reopen(), we need this value to be present to remember why we
4347 	 * were faulted.
4348 	 */
4349 	vd->vdev_label_aux = aux;
4350 
4351 	/*
4352 	 * Faulted state takes precedence over degraded.
4353 	 */
4354 	vd->vdev_delayed_close = B_FALSE;
4355 	vd->vdev_faulted = 1ULL;
4356 	vd->vdev_degraded = 0ULL;
4357 	vdev_set_state(vd, B_FALSE, VDEV_STATE_FAULTED, aux);
4358 
4359 	/*
4360 	 * If this device has the only valid copy of the data, then
4361 	 * back off and simply mark the vdev as degraded instead.
4362 	 */
4363 	if (!tvd->vdev_islog && vd->vdev_aux == NULL && vdev_dtl_required(vd)) {
4364 		vd->vdev_degraded = 1ULL;
4365 		vd->vdev_faulted = 0ULL;
4366 
4367 		/*
4368 		 * If we reopen the device and it's not dead, only then do we
4369 		 * mark it degraded.
4370 		 */
4371 		vdev_reopen(tvd);
4372 
4373 		if (vdev_readable(vd))
4374 			vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED, aux);
4375 	}
4376 
4377 	return (spa_vdev_state_exit(spa, vd, 0));
4378 }
4379 
4380 /*
4381  * Mark the given vdev degraded.  A degraded vdev is purely an indication to the
4382  * user that something is wrong.  The vdev continues to operate as normal as far
4383  * as I/O is concerned.
4384  */
4385 int
vdev_degrade(spa_t * spa,uint64_t guid,vdev_aux_t aux)4386 vdev_degrade(spa_t *spa, uint64_t guid, vdev_aux_t aux)
4387 {
4388 	vdev_t *vd;
4389 
4390 	spa_vdev_state_enter(spa, SCL_NONE);
4391 
4392 	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
4393 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENODEV)));
4394 
4395 	if (!vd->vdev_ops->vdev_op_leaf)
4396 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENOTSUP)));
4397 
4398 	/*
4399 	 * If the vdev is already faulted, then don't do anything.
4400 	 */
4401 	if (vd->vdev_faulted || vd->vdev_degraded)
4402 		return (spa_vdev_state_exit(spa, NULL, 0));
4403 
4404 	vd->vdev_degraded = 1ULL;
4405 	if (!vdev_is_dead(vd))
4406 		vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED,
4407 		    aux);
4408 
4409 	return (spa_vdev_state_exit(spa, vd, 0));
4410 }
4411 
4412 int
vdev_remove_wanted(spa_t * spa,uint64_t guid)4413 vdev_remove_wanted(spa_t *spa, uint64_t guid)
4414 {
4415 	vdev_t *vd;
4416 
4417 	spa_vdev_state_enter(spa, SCL_NONE);
4418 
4419 	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
4420 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENODEV)));
4421 
4422 	/*
4423 	 * If the vdev is already removed, or expanding which can trigger
4424 	 * repartition add/remove events, then don't do anything.
4425 	 */
4426 	if (vd->vdev_removed || vd->vdev_expanding)
4427 		return (spa_vdev_state_exit(spa, NULL, 0));
4428 
4429 	/*
4430 	 * Confirm the vdev has been removed, otherwise don't do anything.
4431 	 */
4432 	if (vd->vdev_ops->vdev_op_leaf && !zio_wait(vdev_probe(vd, NULL)))
4433 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(EEXIST)));
4434 
4435 	vd->vdev_remove_wanted = B_TRUE;
4436 	spa_async_request(spa, SPA_ASYNC_REMOVE_BY_USER);
4437 
4438 	return (spa_vdev_state_exit(spa, vd, 0));
4439 }
4440 
4441 
4442 /*
4443  * Online the given vdev.
4444  *
4445  * If 'ZFS_ONLINE_UNSPARE' is set, it implies two things.  First, any attached
4446  * spare device should be detached when the device finishes resilvering.
4447  * Second, the online should be treated like a 'test' online case, so no FMA
4448  * events are generated if the device fails to open.
4449  */
4450 int
vdev_online(spa_t * spa,uint64_t guid,uint64_t flags,vdev_state_t * newstate)4451 vdev_online(spa_t *spa, uint64_t guid, uint64_t flags, vdev_state_t *newstate)
4452 {
4453 	vdev_t *vd, *tvd, *pvd, *rvd = spa->spa_root_vdev;
4454 	boolean_t wasoffline;
4455 	vdev_state_t oldstate;
4456 
4457 	spa_vdev_state_enter(spa, SCL_NONE);
4458 
4459 	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
4460 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENODEV)));
4461 
4462 	wasoffline = (vd->vdev_offline || vd->vdev_tmpoffline);
4463 	oldstate = vd->vdev_state;
4464 
4465 	tvd = vd->vdev_top;
4466 	vd->vdev_offline = B_FALSE;
4467 	vd->vdev_tmpoffline = B_FALSE;
4468 	vd->vdev_checkremove = !!(flags & ZFS_ONLINE_CHECKREMOVE);
4469 	vd->vdev_forcefault = !!(flags & ZFS_ONLINE_FORCEFAULT);
4470 
4471 	/* XXX - L2ARC 1.0 does not support expansion */
4472 	if (!vd->vdev_aux) {
4473 		for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
4474 			pvd->vdev_expanding = !!((flags & ZFS_ONLINE_EXPAND) ||
4475 			    spa->spa_autoexpand);
4476 		vd->vdev_expansion_time = gethrestime_sec();
4477 	}
4478 
4479 	vdev_reopen(tvd);
4480 	vd->vdev_checkremove = vd->vdev_forcefault = B_FALSE;
4481 
4482 	if (!vd->vdev_aux) {
4483 		for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
4484 			pvd->vdev_expanding = B_FALSE;
4485 	}
4486 
4487 	if (newstate)
4488 		*newstate = vd->vdev_state;
4489 	if ((flags & ZFS_ONLINE_UNSPARE) &&
4490 	    !vdev_is_dead(vd) && vd->vdev_parent &&
4491 	    vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
4492 	    vd->vdev_parent->vdev_child[0] == vd)
4493 		vd->vdev_unspare = B_TRUE;
4494 
4495 	if ((flags & ZFS_ONLINE_EXPAND) || spa->spa_autoexpand) {
4496 
4497 		/* XXX - L2ARC 1.0 does not support expansion */
4498 		if (vd->vdev_aux)
4499 			return (spa_vdev_state_exit(spa, vd, ENOTSUP));
4500 		spa->spa_ccw_fail_time = 0;
4501 		spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
4502 	}
4503 
4504 	/* Restart initializing if necessary */
4505 	mutex_enter(&vd->vdev_initialize_lock);
4506 	if (vdev_writeable(vd) &&
4507 	    vd->vdev_initialize_thread == NULL &&
4508 	    vd->vdev_initialize_state == VDEV_INITIALIZE_ACTIVE) {
4509 		(void) vdev_initialize(vd);
4510 	}
4511 	mutex_exit(&vd->vdev_initialize_lock);
4512 
4513 	/*
4514 	 * Restart trimming if necessary. We do not restart trimming for cache
4515 	 * devices here. This is triggered by l2arc_rebuild_vdev()
4516 	 * asynchronously for the whole device or in l2arc_evict() as it evicts
4517 	 * space for upcoming writes.
4518 	 */
4519 	mutex_enter(&vd->vdev_trim_lock);
4520 	if (vdev_writeable(vd) && !vd->vdev_isl2cache &&
4521 	    vd->vdev_trim_thread == NULL &&
4522 	    vd->vdev_trim_state == VDEV_TRIM_ACTIVE) {
4523 		(void) vdev_trim(vd, vd->vdev_trim_rate, vd->vdev_trim_partial,
4524 		    vd->vdev_trim_secure);
4525 	}
4526 	mutex_exit(&vd->vdev_trim_lock);
4527 
4528 	if (wasoffline ||
4529 	    (oldstate < VDEV_STATE_DEGRADED &&
4530 	    vd->vdev_state >= VDEV_STATE_DEGRADED)) {
4531 		spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_ONLINE);
4532 
4533 		/*
4534 		 * Asynchronously detach spare vdev if resilver or
4535 		 * rebuild is not required
4536 		 */
4537 		if (vd->vdev_unspare &&
4538 		    !dsl_scan_resilvering(spa->spa_dsl_pool) &&
4539 		    !dsl_scan_resilver_scheduled(spa->spa_dsl_pool) &&
4540 		    !vdev_rebuild_active(tvd))
4541 			spa_async_request(spa, SPA_ASYNC_DETACH_SPARE);
4542 	}
4543 	return (spa_vdev_state_exit(spa, vd, 0));
4544 }
4545 
4546 static int
vdev_offline_locked(spa_t * spa,uint64_t guid,uint64_t flags)4547 vdev_offline_locked(spa_t *spa, uint64_t guid, uint64_t flags)
4548 {
4549 	vdev_t *vd, *tvd;
4550 	int error = 0;
4551 	uint64_t generation;
4552 	metaslab_group_t *mg;
4553 
4554 top:
4555 	spa_vdev_state_enter(spa, SCL_ALLOC);
4556 
4557 	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
4558 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENODEV)));
4559 
4560 	if (!vd->vdev_ops->vdev_op_leaf)
4561 		return (spa_vdev_state_exit(spa, NULL, SET_ERROR(ENOTSUP)));
4562 
4563 	if (vd->vdev_ops == &vdev_draid_spare_ops)
4564 		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
4565 
4566 	tvd = vd->vdev_top;
4567 	mg = tvd->vdev_mg;
4568 	generation = spa->spa_config_generation + 1;
4569 
4570 	/*
4571 	 * If the device isn't already offline, try to offline it.
4572 	 */
4573 	if (!vd->vdev_offline) {
4574 		/*
4575 		 * If this device has the only valid copy of some data,
4576 		 * don't allow it to be offlined. Log devices are always
4577 		 * expendable.
4578 		 */
4579 		if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
4580 		    vdev_dtl_required(vd))
4581 			return (spa_vdev_state_exit(spa, NULL,
4582 			    SET_ERROR(EBUSY)));
4583 
4584 		/*
4585 		 * If the top-level is a slog and it has had allocations
4586 		 * then proceed.  We check that the vdev's metaslab group
4587 		 * is not NULL since it's possible that we may have just
4588 		 * added this vdev but not yet initialized its metaslabs.
4589 		 */
4590 		if (tvd->vdev_islog && mg != NULL) {
4591 			/*
4592 			 * Prevent any future allocations.
4593 			 */
4594 			ASSERT0P(tvd->vdev_log_mg);
4595 			metaslab_group_passivate(mg);
4596 			(void) spa_vdev_state_exit(spa, vd, 0);
4597 
4598 			error = spa_reset_logs(spa);
4599 
4600 			/*
4601 			 * If the log device was successfully reset but has
4602 			 * checkpointed data, do not offline it.
4603 			 */
4604 			if (error == 0 &&
4605 			    tvd->vdev_checkpoint_sm != NULL) {
4606 				ASSERT3U(space_map_allocated(
4607 				    tvd->vdev_checkpoint_sm), !=, 0);
4608 				error = ZFS_ERR_CHECKPOINT_EXISTS;
4609 			}
4610 
4611 			spa_vdev_state_enter(spa, SCL_ALLOC);
4612 
4613 			/*
4614 			 * Check to see if the config has changed.
4615 			 */
4616 			if (error || generation != spa->spa_config_generation) {
4617 				metaslab_group_activate(mg);
4618 				if (error)
4619 					return (spa_vdev_state_exit(spa,
4620 					    vd, error));
4621 				(void) spa_vdev_state_exit(spa, vd, 0);
4622 				goto top;
4623 			}
4624 			ASSERT0(tvd->vdev_stat.vs_alloc);
4625 		}
4626 
4627 		/*
4628 		 * Offline this device and reopen its top-level vdev.
4629 		 * If the top-level vdev is a log device then just offline
4630 		 * it. Otherwise, if this action results in the top-level
4631 		 * vdev becoming unusable, undo it and fail the request.
4632 		 */
4633 		vd->vdev_offline = B_TRUE;
4634 		vdev_reopen(tvd);
4635 
4636 		if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
4637 		    vdev_is_dead(tvd)) {
4638 			vd->vdev_offline = B_FALSE;
4639 			vdev_reopen(tvd);
4640 			return (spa_vdev_state_exit(spa, NULL,
4641 			    SET_ERROR(EBUSY)));
4642 		}
4643 
4644 		/*
4645 		 * Add the device back into the metaslab rotor so that
4646 		 * once we online the device it's open for business.
4647 		 */
4648 		if (tvd->vdev_islog && mg != NULL)
4649 			metaslab_group_activate(mg);
4650 	}
4651 
4652 	vd->vdev_tmpoffline = !!(flags & ZFS_OFFLINE_TEMPORARY);
4653 
4654 	return (spa_vdev_state_exit(spa, vd, 0));
4655 }
4656 
4657 int
vdev_offline(spa_t * spa,uint64_t guid,uint64_t flags)4658 vdev_offline(spa_t *spa, uint64_t guid, uint64_t flags)
4659 {
4660 	int error;
4661 
4662 	mutex_enter(&spa->spa_vdev_top_lock);
4663 	error = vdev_offline_locked(spa, guid, flags);
4664 	mutex_exit(&spa->spa_vdev_top_lock);
4665 
4666 	return (error);
4667 }
4668 
4669 /*
4670  * Clear the error counts associated with this vdev.  Unlike vdev_online() and
4671  * vdev_offline(), we assume the spa config is locked.  We also clear all
4672  * children.  If 'vd' is NULL, then the user wants to clear all vdevs.
4673  */
4674 void
vdev_clear(spa_t * spa,vdev_t * vd)4675 vdev_clear(spa_t *spa, vdev_t *vd)
4676 {
4677 	vdev_t *rvd = spa->spa_root_vdev;
4678 
4679 	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
4680 
4681 	if (vd == NULL)
4682 		vd = rvd;
4683 
4684 	vd->vdev_stat.vs_read_errors = 0;
4685 	vd->vdev_stat.vs_write_errors = 0;
4686 	vd->vdev_stat.vs_checksum_errors = 0;
4687 	vd->vdev_stat.vs_dio_verify_errors = 0;
4688 	vd->vdev_stat.vs_slow_ios = 0;
4689 	atomic_store_64((volatile uint64_t *)&vd->vdev_outlier_count, 0);
4690 	vd->vdev_read_sit_out_expire = 0;
4691 
4692 	for (int c = 0; c < vd->vdev_children; c++)
4693 		vdev_clear(spa, vd->vdev_child[c]);
4694 
4695 	/*
4696 	 * It makes no sense to "clear" an indirect  or removed vdev.
4697 	 */
4698 	if (!vdev_is_concrete(vd) || vd->vdev_removed)
4699 		return;
4700 
4701 	/*
4702 	 * If we're in the FAULTED state or have experienced failed I/O, then
4703 	 * clear the persistent state and attempt to reopen the device.  We
4704 	 * also mark the vdev config dirty, so that the new faulted state is
4705 	 * written out to disk.
4706 	 */
4707 	if (vd->vdev_faulted || vd->vdev_degraded ||
4708 	    !vdev_readable(vd) || !vdev_writeable(vd)) {
4709 		/*
4710 		 * When reopening in response to a clear event, it may be due to
4711 		 * a fmadm repair request.  In this case, if the device is
4712 		 * still broken, we want to still post the ereport again.
4713 		 */
4714 		vd->vdev_forcefault = B_TRUE;
4715 
4716 		vd->vdev_faulted = vd->vdev_degraded = 0ULL;
4717 		vd->vdev_cant_read = B_FALSE;
4718 		vd->vdev_cant_write = B_FALSE;
4719 		vd->vdev_stat.vs_aux = 0;
4720 
4721 		vdev_reopen(vd == rvd ? rvd : vd->vdev_top);
4722 
4723 		vd->vdev_forcefault = B_FALSE;
4724 
4725 		if (vd != rvd && vdev_writeable(vd->vdev_top))
4726 			vdev_state_dirty(vd->vdev_top);
4727 
4728 		/* If a resilver isn't required, check if vdevs can be culled */
4729 		if (vd->vdev_aux == NULL && !vdev_is_dead(vd) &&
4730 		    !dsl_scan_resilvering(spa->spa_dsl_pool) &&
4731 		    !dsl_scan_resilver_scheduled(spa->spa_dsl_pool))
4732 			spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
4733 
4734 		spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_CLEAR);
4735 	}
4736 
4737 	/*
4738 	 * When clearing a FMA-diagnosed fault, we always want to
4739 	 * unspare the device, as we assume that the original spare was
4740 	 * done in response to the FMA fault.
4741 	 */
4742 	if (!vdev_is_dead(vd) && vd->vdev_parent != NULL &&
4743 	    vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
4744 	    vd->vdev_parent->vdev_child[0] == vd)
4745 		vd->vdev_unspare = B_TRUE;
4746 
4747 	/* Clear recent error events cache (i.e. duplicate events tracking) */
4748 	zfs_ereport_clear(spa, vd);
4749 }
4750 
4751 boolean_t
vdev_is_dead(vdev_t * vd)4752 vdev_is_dead(vdev_t *vd)
4753 {
4754 	/*
4755 	 * Holes and missing devices are always considered "dead".
4756 	 * This simplifies the code since we don't have to check for
4757 	 * these types of devices in the various code paths.
4758 	 * Instead we rely on the fact that we skip over dead devices
4759 	 * before issuing I/O to them.
4760 	 */
4761 	return (vd->vdev_state < VDEV_STATE_DEGRADED ||
4762 	    vd->vdev_ops == &vdev_hole_ops ||
4763 	    vd->vdev_ops == &vdev_missing_ops);
4764 }
4765 
4766 boolean_t
vdev_readable(vdev_t * vd)4767 vdev_readable(vdev_t *vd)
4768 {
4769 	return (!vdev_is_dead(vd) && !vd->vdev_cant_read);
4770 }
4771 
4772 boolean_t
vdev_writeable(vdev_t * vd)4773 vdev_writeable(vdev_t *vd)
4774 {
4775 	return (!vdev_is_dead(vd) && !vd->vdev_cant_write &&
4776 	    vdev_is_concrete(vd));
4777 }
4778 
4779 boolean_t
vdev_allocatable(vdev_t * vd)4780 vdev_allocatable(vdev_t *vd)
4781 {
4782 	uint64_t state = vd->vdev_state;
4783 
4784 	/*
4785 	 * We currently allow allocations from vdevs which may be in the
4786 	 * process of reopening (i.e. VDEV_STATE_CLOSED). If the device
4787 	 * fails to reopen then we'll catch it later when we're holding
4788 	 * the proper locks.  Note that we have to get the vdev state
4789 	 * in a local variable because although it changes atomically,
4790 	 * we're asking two separate questions about it.
4791 	 */
4792 	return (!(state < VDEV_STATE_DEGRADED && state != VDEV_STATE_CLOSED) &&
4793 	    !vd->vdev_cant_write && vdev_is_concrete(vd) &&
4794 	    vd->vdev_mg->mg_initialized);
4795 }
4796 
4797 boolean_t
vdev_accessible(vdev_t * vd,zio_t * zio)4798 vdev_accessible(vdev_t *vd, zio_t *zio)
4799 {
4800 	ASSERT(zio->io_vd == vd);
4801 
4802 	if (vdev_is_dead(vd) || vd->vdev_remove_wanted)
4803 		return (B_FALSE);
4804 
4805 	if (zio->io_type == ZIO_TYPE_READ)
4806 		return (!vd->vdev_cant_read);
4807 
4808 	if (zio->io_type == ZIO_TYPE_WRITE)
4809 		return (!vd->vdev_cant_write);
4810 
4811 	return (B_TRUE);
4812 }
4813 
4814 static void
vdev_get_child_stat(vdev_t * cvd,vdev_stat_t * vs,vdev_stat_t * cvs)4815 vdev_get_child_stat(vdev_t *cvd, vdev_stat_t *vs, vdev_stat_t *cvs)
4816 {
4817 	/*
4818 	 * Exclude the dRAID spare when aggregating to avoid double counting
4819 	 * the ops and bytes.  These IOs are counted by the physical leaves.
4820 	 */
4821 	if (cvd->vdev_ops == &vdev_draid_spare_ops)
4822 		return;
4823 
4824 	for (int t = 0; t < VS_ZIO_TYPES; t++) {
4825 		vs->vs_ops[t] += cvs->vs_ops[t];
4826 		vs->vs_bytes[t] += cvs->vs_bytes[t];
4827 	}
4828 
4829 	cvs->vs_scan_removing = cvd->vdev_removing;
4830 }
4831 
4832 /*
4833  * Get extended stats
4834  */
4835 static void
vdev_get_child_stat_ex(vdev_t * cvd,vdev_stat_ex_t * vsx,vdev_stat_ex_t * cvsx)4836 vdev_get_child_stat_ex(vdev_t *cvd, vdev_stat_ex_t *vsx, vdev_stat_ex_t *cvsx)
4837 {
4838 	(void) cvd;
4839 
4840 	int t, b;
4841 	for (t = 0; t < ZIO_TYPES; t++) {
4842 		for (b = 0; b < ARRAY_SIZE(vsx->vsx_disk_histo[0]); b++)
4843 			vsx->vsx_disk_histo[t][b] += cvsx->vsx_disk_histo[t][b];
4844 
4845 		for (b = 0; b < ARRAY_SIZE(vsx->vsx_total_histo[0]); b++) {
4846 			vsx->vsx_total_histo[t][b] +=
4847 			    cvsx->vsx_total_histo[t][b];
4848 		}
4849 	}
4850 
4851 	for (t = 0; t < ZIO_PRIORITY_NUM_QUEUEABLE; t++) {
4852 		for (b = 0; b < ARRAY_SIZE(vsx->vsx_queue_histo[0]); b++) {
4853 			vsx->vsx_queue_histo[t][b] +=
4854 			    cvsx->vsx_queue_histo[t][b];
4855 		}
4856 		vsx->vsx_active_queue[t] += cvsx->vsx_active_queue[t];
4857 		vsx->vsx_pend_queue[t] += cvsx->vsx_pend_queue[t];
4858 
4859 		for (b = 0; b < ARRAY_SIZE(vsx->vsx_ind_histo[0]); b++)
4860 			vsx->vsx_ind_histo[t][b] += cvsx->vsx_ind_histo[t][b];
4861 
4862 		for (b = 0; b < ARRAY_SIZE(vsx->vsx_agg_histo[0]); b++)
4863 			vsx->vsx_agg_histo[t][b] += cvsx->vsx_agg_histo[t][b];
4864 	}
4865 
4866 }
4867 
4868 boolean_t
vdev_is_spacemap_addressable(vdev_t * vd)4869 vdev_is_spacemap_addressable(vdev_t *vd)
4870 {
4871 	if (spa_feature_is_active(vd->vdev_spa, SPA_FEATURE_SPACEMAP_V2))
4872 		return (B_TRUE);
4873 
4874 	/*
4875 	 * If double-word space map entries are not enabled we assume
4876 	 * 47 bits of the space map entry are dedicated to the entry's
4877 	 * offset (see SM_OFFSET_BITS in space_map.h). We then use that
4878 	 * to calculate the maximum address that can be described by a
4879 	 * space map entry for the given device.
4880 	 */
4881 	uint64_t shift = vd->vdev_ashift + SM_OFFSET_BITS;
4882 
4883 	if (shift >= 63) /* detect potential overflow */
4884 		return (B_TRUE);
4885 
4886 	return (vd->vdev_asize < (1ULL << shift));
4887 }
4888 
4889 /*
4890  * Get statistics for the given vdev.
4891  */
4892 static void
vdev_get_stats_ex_impl(vdev_t * vd,vdev_stat_t * vs,vdev_stat_ex_t * vsx)4893 vdev_get_stats_ex_impl(vdev_t *vd, vdev_stat_t *vs, vdev_stat_ex_t *vsx)
4894 {
4895 	int t;
4896 	/*
4897 	 * If we're getting stats on the root vdev, aggregate the I/O counts
4898 	 * over all top-level vdevs (i.e. the direct children of the root).
4899 	 */
4900 	if (!vd->vdev_ops->vdev_op_leaf) {
4901 		if (vs) {
4902 			memset(vs->vs_ops, 0, sizeof (vs->vs_ops));
4903 			memset(vs->vs_bytes, 0, sizeof (vs->vs_bytes));
4904 		}
4905 		if (vsx)
4906 			memset(vsx, 0, sizeof (*vsx));
4907 
4908 		for (int c = 0; c < vd->vdev_children; c++) {
4909 			vdev_t *cvd = vd->vdev_child[c];
4910 			vdev_stat_t *cvs = &cvd->vdev_stat;
4911 			vdev_stat_ex_t *cvsx = &cvd->vdev_stat_ex;
4912 
4913 			vdev_get_stats_ex_impl(cvd, cvs, cvsx);
4914 			if (vs)
4915 				vdev_get_child_stat(cvd, vs, cvs);
4916 			if (vsx)
4917 				vdev_get_child_stat_ex(cvd, vsx, cvsx);
4918 		}
4919 	} else {
4920 		/*
4921 		 * We're a leaf.  Just copy our ZIO active queue stats in.  The
4922 		 * other leaf stats are updated in vdev_stat_update().
4923 		 */
4924 		if (!vsx)
4925 			return;
4926 
4927 		memcpy(vsx, &vd->vdev_stat_ex, sizeof (vd->vdev_stat_ex));
4928 
4929 		for (t = 0; t < ZIO_PRIORITY_NUM_QUEUEABLE; t++) {
4930 			vsx->vsx_active_queue[t] = vd->vdev_queue.vq_cactive[t];
4931 			vsx->vsx_pend_queue[t] = vdev_queue_class_length(vd, t);
4932 		}
4933 	}
4934 }
4935 
4936 void
vdev_get_stats_ex(vdev_t * vd,vdev_stat_t * vs,vdev_stat_ex_t * vsx)4937 vdev_get_stats_ex(vdev_t *vd, vdev_stat_t *vs, vdev_stat_ex_t *vsx)
4938 {
4939 	vdev_t *tvd = vd->vdev_top;
4940 	mutex_enter(&vd->vdev_stat_lock);
4941 	if (vs) {
4942 		memcpy(vs, &vd->vdev_stat, sizeof (*vs));
4943 		vs->vs_timestamp = gethrtime() - vs->vs_timestamp;
4944 		vs->vs_state = vd->vdev_state;
4945 		vs->vs_rsize = vdev_get_min_asize(vd);
4946 
4947 		if (vd->vdev_ops->vdev_op_leaf) {
4948 			vs->vs_pspace = vd->vdev_psize;
4949 			vs->vs_rsize += VDEV_LABEL_START_SIZE +
4950 			    VDEV_LABEL_END_SIZE;
4951 			/*
4952 			 * Report initializing progress. Since we don't
4953 			 * have the initializing locks held, this is only
4954 			 * an estimate (although a fairly accurate one).
4955 			 */
4956 			vs->vs_initialize_bytes_done =
4957 			    vd->vdev_initialize_bytes_done;
4958 			vs->vs_initialize_bytes_est =
4959 			    vd->vdev_initialize_bytes_est;
4960 			vs->vs_initialize_state = vd->vdev_initialize_state;
4961 			vs->vs_initialize_action_time =
4962 			    vd->vdev_initialize_action_time;
4963 
4964 			/*
4965 			 * Report manual TRIM progress. Since we don't have
4966 			 * the manual TRIM locks held, this is only an
4967 			 * estimate (although fairly accurate one).
4968 			 */
4969 			vs->vs_trim_notsup = !vd->vdev_has_trim;
4970 			vs->vs_trim_bytes_done = vd->vdev_trim_bytes_done;
4971 			vs->vs_trim_bytes_est = vd->vdev_trim_bytes_est;
4972 			vs->vs_trim_state = vd->vdev_trim_state;
4973 			vs->vs_trim_action_time = vd->vdev_trim_action_time;
4974 
4975 			/* Set when there is a deferred resilver. */
4976 			vs->vs_resilver_deferred = vd->vdev_resilver_deferred;
4977 		}
4978 
4979 		/*
4980 		 * Report expandable space on top-level, non-auxiliary devices
4981 		 * only. The expandable space is reported in terms of metaslab
4982 		 * sized units since that determines how much space the pool
4983 		 * can expand.
4984 		 */
4985 		if (vd->vdev_aux == NULL && tvd != NULL) {
4986 			vs->vs_esize = P2ALIGN_TYPED(
4987 			    vd->vdev_max_asize - vd->vdev_asize,
4988 			    1ULL << tvd->vdev_ms_shift, uint64_t);
4989 		}
4990 
4991 		vs->vs_configured_ashift = vd->vdev_top != NULL
4992 		    ? vd->vdev_top->vdev_ashift : vd->vdev_ashift;
4993 		vs->vs_logical_ashift = vd->vdev_logical_ashift;
4994 		if (vd->vdev_physical_ashift <= ASHIFT_MAX)
4995 			vs->vs_physical_ashift = vd->vdev_physical_ashift;
4996 		else
4997 			vs->vs_physical_ashift = 0;
4998 
4999 		/*
5000 		 * Report fragmentation and rebuild progress for top-level,
5001 		 * non-auxiliary, concrete devices.
5002 		 */
5003 		if (vd->vdev_aux == NULL && vd == vd->vdev_top &&
5004 		    vdev_is_concrete(vd)) {
5005 			/*
5006 			 * The vdev fragmentation rating doesn't take into
5007 			 * account the embedded slog metaslab (vdev_log_mg).
5008 			 * Since it's only one metaslab, it would have a tiny
5009 			 * impact on the overall fragmentation.
5010 			 */
5011 			vs->vs_fragmentation = (vd->vdev_mg != NULL) ?
5012 			    vd->vdev_mg->mg_fragmentation : 0;
5013 		}
5014 		vs->vs_noalloc = MAX(vd->vdev_noalloc,
5015 		    tvd ? tvd->vdev_noalloc : 0);
5016 	}
5017 
5018 	vdev_get_stats_ex_impl(vd, vs, vsx);
5019 	mutex_exit(&vd->vdev_stat_lock);
5020 }
5021 
5022 void
vdev_get_stats(vdev_t * vd,vdev_stat_t * vs)5023 vdev_get_stats(vdev_t *vd, vdev_stat_t *vs)
5024 {
5025 	return (vdev_get_stats_ex(vd, vs, NULL));
5026 }
5027 
5028 void
vdev_clear_stats(vdev_t * vd)5029 vdev_clear_stats(vdev_t *vd)
5030 {
5031 	mutex_enter(&vd->vdev_stat_lock);
5032 	vd->vdev_stat.vs_space = 0;
5033 	vd->vdev_stat.vs_dspace = 0;
5034 	vd->vdev_stat.vs_alloc = 0;
5035 	mutex_exit(&vd->vdev_stat_lock);
5036 }
5037 
5038 void
vdev_scan_stat_init(vdev_t * vd)5039 vdev_scan_stat_init(vdev_t *vd)
5040 {
5041 	vdev_stat_t *vs = &vd->vdev_stat;
5042 
5043 	for (int c = 0; c < vd->vdev_children; c++)
5044 		vdev_scan_stat_init(vd->vdev_child[c]);
5045 
5046 	mutex_enter(&vd->vdev_stat_lock);
5047 	vs->vs_scan_processed = 0;
5048 	mutex_exit(&vd->vdev_stat_lock);
5049 }
5050 
5051 void
vdev_stat_update(zio_t * zio,uint64_t psize)5052 vdev_stat_update(zio_t *zio, uint64_t psize)
5053 {
5054 	spa_t *spa = zio->io_spa;
5055 	vdev_t *rvd = spa->spa_root_vdev;
5056 	vdev_t *vd = zio->io_vd ? zio->io_vd : rvd;
5057 	vdev_t *pvd;
5058 	uint64_t txg = zio->io_txg;
5059 /* Suppress ASAN false positive */
5060 #ifdef __SANITIZE_ADDRESS__
5061 	vdev_stat_t *vs = vd ? &vd->vdev_stat : NULL;
5062 	vdev_stat_ex_t *vsx = vd ? &vd->vdev_stat_ex : NULL;
5063 #else
5064 	vdev_stat_t *vs = &vd->vdev_stat;
5065 	vdev_stat_ex_t *vsx = &vd->vdev_stat_ex;
5066 #endif
5067 	zio_type_t type = zio->io_type;
5068 	int flags = zio->io_flags;
5069 
5070 	/*
5071 	 * If this i/o is a gang leader, it didn't do any actual work.
5072 	 */
5073 	if (zio->io_gang_tree)
5074 		return;
5075 
5076 	if (zio->io_error == 0) {
5077 		/*
5078 		 * If this is a root i/o, don't count it -- we've already
5079 		 * counted the top-level vdevs, and vdev_get_stats() will
5080 		 * aggregate them when asked.  This reduces contention on
5081 		 * the root vdev_stat_lock and implicitly handles blocks
5082 		 * that compress away to holes, for which there is no i/o.
5083 		 * (Holes never create vdev children, so all the counters
5084 		 * remain zero, which is what we want.)
5085 		 *
5086 		 * Note: this only applies to successful i/o (io_error == 0)
5087 		 * because unlike i/o counts, errors are not additive.
5088 		 * When reading a ditto block, for example, failure of
5089 		 * one top-level vdev does not imply a root-level error.
5090 		 */
5091 		if (vd == rvd)
5092 			return;
5093 
5094 		ASSERT(vd == zio->io_vd);
5095 
5096 		if (flags & ZIO_FLAG_IO_BYPASS)
5097 			return;
5098 
5099 		mutex_enter(&vd->vdev_stat_lock);
5100 
5101 		if (flags & ZIO_FLAG_IO_REPAIR) {
5102 			/*
5103 			 * Repair is the result of a resilver issued by the
5104 			 * scan thread (spa_sync).
5105 			 */
5106 			if (flags & ZIO_FLAG_SCAN_THREAD) {
5107 				dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
5108 				dsl_scan_phys_t *scn_phys = &scn->scn_phys;
5109 				uint64_t *processed = &scn_phys->scn_processed;
5110 
5111 				if (vd->vdev_ops->vdev_op_leaf)
5112 					atomic_add_64(processed, psize);
5113 				vs->vs_scan_processed += psize;
5114 			}
5115 
5116 			/*
5117 			 * Repair is the result of a rebuild issued by the
5118 			 * rebuild thread (vdev_rebuild_thread).  To avoid
5119 			 * double counting repaired bytes the virtual dRAID
5120 			 * spare vdev is excluded from the processed bytes.
5121 			 */
5122 			if (zio->io_priority == ZIO_PRIORITY_REBUILD) {
5123 				vdev_t *tvd = vd->vdev_top;
5124 				vdev_rebuild_t *vr = &tvd->vdev_rebuild_config;
5125 				vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
5126 				uint64_t *rebuilt = &vrp->vrp_bytes_rebuilt;
5127 
5128 				if (vd->vdev_ops->vdev_op_leaf &&
5129 				    vd->vdev_ops != &vdev_draid_spare_ops) {
5130 					atomic_add_64(rebuilt, psize);
5131 				}
5132 				vs->vs_rebuild_processed += psize;
5133 			}
5134 
5135 			if (flags & ZIO_FLAG_SELF_HEAL)
5136 				vs->vs_self_healed += psize;
5137 		}
5138 
5139 		/*
5140 		 * The bytes/ops/histograms are recorded at the leaf level and
5141 		 * aggregated into the higher level vdevs in vdev_get_stats().
5142 		 */
5143 		if (vd->vdev_ops->vdev_op_leaf &&
5144 		    (zio->io_priority < ZIO_PRIORITY_NUM_QUEUEABLE)) {
5145 			zio_type_t vs_type = type;
5146 			zio_priority_t priority = zio->io_priority;
5147 
5148 			/*
5149 			 * TRIM ops and bytes are reported to user space as
5150 			 * ZIO_TYPE_FLUSH.  This is done to preserve the
5151 			 * vdev_stat_t structure layout for user space.
5152 			 */
5153 			if (type == ZIO_TYPE_TRIM)
5154 				vs_type = ZIO_TYPE_FLUSH;
5155 
5156 			/*
5157 			 * Solely for the purposes of 'zpool iostat -lqrw'
5158 			 * reporting use the priority to categorize the IO.
5159 			 * Only the following are reported to user space:
5160 			 *
5161 			 *   ZIO_PRIORITY_SYNC_READ,
5162 			 *   ZIO_PRIORITY_SYNC_WRITE,
5163 			 *   ZIO_PRIORITY_ASYNC_READ,
5164 			 *   ZIO_PRIORITY_ASYNC_WRITE,
5165 			 *   ZIO_PRIORITY_SCRUB,
5166 			 *   ZIO_PRIORITY_TRIM,
5167 			 *   ZIO_PRIORITY_REBUILD.
5168 			 */
5169 			if (priority == ZIO_PRIORITY_INITIALIZING) {
5170 				ASSERT3U(type, ==, ZIO_TYPE_WRITE);
5171 				priority = ZIO_PRIORITY_ASYNC_WRITE;
5172 			} else if (priority == ZIO_PRIORITY_REMOVAL) {
5173 				priority = ((type == ZIO_TYPE_WRITE) ?
5174 				    ZIO_PRIORITY_ASYNC_WRITE :
5175 				    ZIO_PRIORITY_ASYNC_READ);
5176 			}
5177 
5178 			vs->vs_ops[vs_type]++;
5179 			vs->vs_bytes[vs_type] += psize;
5180 
5181 			if (flags & ZIO_FLAG_DELEGATED) {
5182 				vsx->vsx_agg_histo[priority]
5183 				    [RQ_HISTO(zio->io_size)]++;
5184 			} else {
5185 				vsx->vsx_ind_histo[priority]
5186 				    [RQ_HISTO(zio->io_size)]++;
5187 			}
5188 
5189 			if (zio->io_delta && zio->io_delay) {
5190 				vsx->vsx_queue_histo[priority]
5191 				    [L_HISTO(zio->io_delta - zio->io_delay)]++;
5192 				vsx->vsx_disk_histo[type]
5193 				    [L_HISTO(zio->io_delay)]++;
5194 				vsx->vsx_total_histo[type]
5195 				    [L_HISTO(zio->io_delta)]++;
5196 			}
5197 		}
5198 
5199 		mutex_exit(&vd->vdev_stat_lock);
5200 		return;
5201 	}
5202 
5203 	if (flags & ZIO_FLAG_SPECULATIVE)
5204 		return;
5205 
5206 	/*
5207 	 * If this is an I/O error that is going to be retried, then ignore the
5208 	 * error.  Otherwise, the user may interpret B_FAILFAST I/O errors as
5209 	 * hard errors, when in reality they can happen for any number of
5210 	 * innocuous reasons (bus resets, MPxIO link failure, etc).
5211 	 */
5212 	if (zio->io_error == EIO &&
5213 	    !(zio->io_flags & ZIO_FLAG_IO_RETRY))
5214 		return;
5215 
5216 	/*
5217 	 * Intent logs writes won't propagate their error to the root
5218 	 * I/O so don't mark these types of failures as pool-level
5219 	 * errors.
5220 	 */
5221 	if (zio->io_vd == NULL && (zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
5222 		return;
5223 
5224 	if (type == ZIO_TYPE_WRITE && txg != 0 &&
5225 	    (!(flags & ZIO_FLAG_IO_REPAIR) ||
5226 	    (flags & ZIO_FLAG_SCAN_THREAD) ||
5227 	    zio->io_priority == ZIO_PRIORITY_REBUILD ||
5228 	    spa->spa_claiming)) {
5229 		/*
5230 		 * This is either a normal write (not a repair), or it's
5231 		 * a repair induced by the scrub thread, or it's a repair
5232 		 * made by zil_claim() during spa_load() in the first txg,
5233 		 * or its repair induced by rebuild (sequential resilver).
5234 		 * In the normal case, we commit the DTL change in the same
5235 		 * txg as the block was born.  In the scrub-induced repair
5236 		 * case, we know that scrubs run in first-pass syncing context,
5237 		 * so we commit the DTL change in spa_syncing_txg(spa).
5238 		 * In the zil_claim() case, we commit in spa_first_txg(spa).
5239 		 *
5240 		 * We currently do not make DTL entries for failed spontaneous
5241 		 * self-healing writes triggered by normal (non-scrubbing)
5242 		 * reads, because we have no transactional context in which to
5243 		 * do so -- and it's not clear that it'd be desirable anyway.
5244 		 *
5245 		 * For rebuild, since we don't have any information about BPs
5246 		 * and txgs that are being rebuilt, we need to add all known
5247 		 * txgs (starting from TXG_INITIAL) to DTL so that during
5248 		 * healing resilver we would be able to check all txgs at
5249 		 * vdev_draid_need_resilver().
5250 		 */
5251 		uint64_t size = 1;
5252 		if (vd->vdev_ops->vdev_op_leaf) {
5253 			uint64_t commit_txg = txg;
5254 			if (flags & ZIO_FLAG_SCAN_THREAD) {
5255 				ASSERT(flags & ZIO_FLAG_IO_REPAIR);
5256 				ASSERT(spa_sync_pass(spa) == 1);
5257 				vdev_dtl_dirty(vd, DTL_SCRUB, txg, size);
5258 				commit_txg = spa_syncing_txg(spa);
5259 			} else if (spa->spa_claiming) {
5260 				ASSERT(flags & ZIO_FLAG_IO_REPAIR);
5261 				commit_txg = spa_first_txg(spa);
5262 			} else if (zio->io_priority == ZIO_PRIORITY_REBUILD) {
5263 				ASSERT(flags & ZIO_FLAG_IO_REPAIR);
5264 				vdev_rebuild_txgs(vd->vdev_top, &txg, &size);
5265 				commit_txg = spa_open_txg(spa);
5266 			}
5267 			ASSERT(commit_txg >= spa_syncing_txg(spa));
5268 			if (vdev_dtl_contains(vd, DTL_MISSING, txg, size))
5269 				return;
5270 			for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
5271 				vdev_dtl_dirty(pvd, DTL_PARTIAL, txg, size);
5272 			vdev_dirty(vd->vdev_top, VDD_DTL, vd, commit_txg);
5273 		}
5274 		if (vd != rvd)
5275 			vdev_dtl_dirty(vd, DTL_MISSING, txg, size);
5276 	}
5277 }
5278 
5279 int64_t
vdev_deflated_space(vdev_t * vd,int64_t space)5280 vdev_deflated_space(vdev_t *vd, int64_t space)
5281 {
5282 	ASSERT0((space & (SPA_MINBLOCKSIZE-1)));
5283 	ASSERT(vd->vdev_deflate_ratio != 0 || vd->vdev_isl2cache);
5284 
5285 	return ((space >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio);
5286 }
5287 
5288 /*
5289  * Update the in-core space usage stats for this vdev, its metaslab class,
5290  * and the root vdev.
5291  */
5292 void
vdev_space_update(vdev_t * vd,int64_t alloc_delta,int64_t defer_delta,int64_t space_delta)5293 vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
5294     int64_t space_delta)
5295 {
5296 	(void) defer_delta;
5297 	int64_t dspace_delta;
5298 	spa_t *spa = vd->vdev_spa;
5299 	vdev_t *rvd = spa->spa_root_vdev;
5300 
5301 	ASSERT(vd == vd->vdev_top);
5302 
5303 	/*
5304 	 * Apply the inverse of the psize-to-asize (ie. RAID-Z) space-expansion
5305 	 * factor.  We must calculate this here and not at the root vdev
5306 	 * because the root vdev's psize-to-asize is simply the max of its
5307 	 * children's, thus not accurate enough for us.
5308 	 */
5309 	dspace_delta = vdev_deflated_space(vd, space_delta);
5310 
5311 	mutex_enter(&vd->vdev_stat_lock);
5312 	/* ensure we won't underflow */
5313 	if (alloc_delta < 0) {
5314 		ASSERT3U(vd->vdev_stat.vs_alloc, >=, -alloc_delta);
5315 	}
5316 
5317 	vd->vdev_stat.vs_alloc += alloc_delta;
5318 	vd->vdev_stat.vs_space += space_delta;
5319 	vd->vdev_stat.vs_dspace += dspace_delta;
5320 	mutex_exit(&vd->vdev_stat_lock);
5321 
5322 	/* every class but log contributes to root space stats */
5323 	if (vd->vdev_mg != NULL && !vd->vdev_islog) {
5324 		ASSERT(!vd->vdev_isl2cache);
5325 		mutex_enter(&rvd->vdev_stat_lock);
5326 		rvd->vdev_stat.vs_alloc += alloc_delta;
5327 		rvd->vdev_stat.vs_space += space_delta;
5328 		rvd->vdev_stat.vs_dspace += dspace_delta;
5329 		mutex_exit(&rvd->vdev_stat_lock);
5330 	}
5331 	/* Note: metaslab_class_space_update moved to metaslab_space_update */
5332 }
5333 
5334 /*
5335  * Mark a top-level vdev's config as dirty, placing it on the dirty list
5336  * so that it will be written out next time the vdev configuration is synced.
5337  * If the root vdev is specified (vdev_top == NULL), dirty all top-level vdevs.
5338  */
5339 void
vdev_config_dirty(vdev_t * vd)5340 vdev_config_dirty(vdev_t *vd)
5341 {
5342 	spa_t *spa = vd->vdev_spa;
5343 	vdev_t *rvd = spa->spa_root_vdev;
5344 	int c;
5345 
5346 	ASSERT(spa_writeable(spa));
5347 
5348 	/*
5349 	 * If this is an aux vdev (as with l2cache and spare devices), then we
5350 	 * update the vdev config manually and set the sync flag.
5351 	 */
5352 	if (vd->vdev_aux != NULL) {
5353 		spa_aux_vdev_t *sav = vd->vdev_aux;
5354 		nvlist_t **aux;
5355 		uint_t naux;
5356 
5357 		for (c = 0; c < sav->sav_count; c++) {
5358 			if (sav->sav_vdevs[c] == vd)
5359 				break;
5360 		}
5361 
5362 		if (c == sav->sav_count) {
5363 			/*
5364 			 * We're being removed.  There's nothing more to do.
5365 			 */
5366 			ASSERT(sav->sav_sync == B_TRUE);
5367 			return;
5368 		}
5369 
5370 		sav->sav_sync = B_TRUE;
5371 
5372 		if (nvlist_lookup_nvlist_array(sav->sav_config,
5373 		    ZPOOL_CONFIG_L2CACHE, &aux, &naux) != 0) {
5374 			VERIFY0(nvlist_lookup_nvlist_array(sav->sav_config,
5375 			    ZPOOL_CONFIG_SPARES, &aux, &naux));
5376 		}
5377 
5378 		ASSERT(c < naux);
5379 
5380 		/*
5381 		 * Setting the nvlist in the middle if the array is a little
5382 		 * sketchy, but it will work.
5383 		 */
5384 		nvlist_free(aux[c]);
5385 		aux[c] = vdev_config_generate(spa, vd, B_TRUE, 0);
5386 
5387 		return;
5388 	}
5389 
5390 	/*
5391 	 * The dirty list is protected by the SCL_CONFIG lock.  The caller
5392 	 * must either hold SCL_CONFIG as writer, or must be the sync thread
5393 	 * (which holds SCL_CONFIG as reader).  There's only one sync thread,
5394 	 * so this is sufficient to ensure mutual exclusion.
5395 	 */
5396 	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
5397 	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
5398 	    spa_config_held(spa, SCL_CONFIG, RW_READER)));
5399 
5400 	if (vd == rvd) {
5401 		for (c = 0; c < rvd->vdev_children; c++)
5402 			vdev_config_dirty(rvd->vdev_child[c]);
5403 	} else {
5404 		ASSERT(vd == vd->vdev_top);
5405 
5406 		if (!list_link_active(&vd->vdev_config_dirty_node) &&
5407 		    vdev_is_concrete(vd)) {
5408 			list_insert_head(&spa->spa_config_dirty_list, vd);
5409 		}
5410 	}
5411 }
5412 
5413 void
vdev_config_clean(vdev_t * vd)5414 vdev_config_clean(vdev_t *vd)
5415 {
5416 	spa_t *spa = vd->vdev_spa;
5417 
5418 	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
5419 	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
5420 	    spa_config_held(spa, SCL_CONFIG, RW_READER)));
5421 
5422 	ASSERT(list_link_active(&vd->vdev_config_dirty_node));
5423 	list_remove(&spa->spa_config_dirty_list, vd);
5424 }
5425 
5426 /*
5427  * Mark a top-level vdev's state as dirty, so that the next pass of
5428  * spa_sync() can convert this into vdev_config_dirty().  We distinguish
5429  * the state changes from larger config changes because they require
5430  * much less locking, and are often needed for administrative actions.
5431  */
5432 void
vdev_state_dirty(vdev_t * vd)5433 vdev_state_dirty(vdev_t *vd)
5434 {
5435 	spa_t *spa = vd->vdev_spa;
5436 
5437 	ASSERT(spa_writeable(spa));
5438 	ASSERT(vd == vd->vdev_top);
5439 
5440 	/*
5441 	 * The state list is protected by the SCL_STATE lock.  The caller
5442 	 * must either hold SCL_STATE as writer, or must be the sync thread
5443 	 * (which holds SCL_STATE as reader).  There's only one sync thread,
5444 	 * so this is sufficient to ensure mutual exclusion.
5445 	 */
5446 	ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
5447 	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
5448 	    spa_config_held(spa, SCL_STATE, RW_READER)));
5449 
5450 	if (!list_link_active(&vd->vdev_state_dirty_node) &&
5451 	    vdev_is_concrete(vd))
5452 		list_insert_head(&spa->spa_state_dirty_list, vd);
5453 }
5454 
5455 void
vdev_state_clean(vdev_t * vd)5456 vdev_state_clean(vdev_t *vd)
5457 {
5458 	spa_t *spa = vd->vdev_spa;
5459 
5460 	ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
5461 	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
5462 	    spa_config_held(spa, SCL_STATE, RW_READER)));
5463 
5464 	ASSERT(list_link_active(&vd->vdev_state_dirty_node));
5465 	list_remove(&spa->spa_state_dirty_list, vd);
5466 }
5467 
5468 /*
5469  * Propagate vdev state up from children to parent.
5470  */
5471 void
vdev_propagate_state(vdev_t * vd)5472 vdev_propagate_state(vdev_t *vd)
5473 {
5474 	spa_t *spa = vd->vdev_spa;
5475 	vdev_t *rvd = spa->spa_root_vdev;
5476 	int degraded = 0, faulted = 0;
5477 	int corrupted = 0;
5478 	vdev_t *child;
5479 
5480 	if (vd->vdev_children > 0) {
5481 		for (int c = 0; c < vd->vdev_children; c++) {
5482 			child = vd->vdev_child[c];
5483 
5484 			/*
5485 			 * Don't factor holes or indirect vdevs into the
5486 			 * decision.
5487 			 */
5488 			if (!vdev_is_concrete(child))
5489 				continue;
5490 
5491 			if (!vdev_readable(child) ||
5492 			    (!vdev_writeable(child) && spa_writeable(spa))) {
5493 				/*
5494 				 * Root special: if there is a top-level log
5495 				 * device, treat the root vdev as if it were
5496 				 * degraded.
5497 				 */
5498 				if (child->vdev_islog && vd == rvd)
5499 					degraded++;
5500 				else
5501 					faulted++;
5502 			} else if (child->vdev_state <= VDEV_STATE_DEGRADED) {
5503 				degraded++;
5504 			}
5505 
5506 			if (child->vdev_stat.vs_aux == VDEV_AUX_CORRUPT_DATA)
5507 				corrupted++;
5508 		}
5509 
5510 		vd->vdev_ops->vdev_op_state_change(vd, faulted, degraded);
5511 
5512 		/*
5513 		 * Root special: if there is a top-level vdev that cannot be
5514 		 * opened due to corrupted metadata, then propagate the root
5515 		 * vdev's aux state as 'corrupt' rather than 'insufficient
5516 		 * replicas'.
5517 		 */
5518 		if (corrupted && vd == rvd &&
5519 		    rvd->vdev_state == VDEV_STATE_CANT_OPEN)
5520 			vdev_set_state(rvd, B_FALSE, VDEV_STATE_CANT_OPEN,
5521 			    VDEV_AUX_CORRUPT_DATA);
5522 	}
5523 
5524 	if (vd->vdev_parent)
5525 		vdev_propagate_state(vd->vdev_parent);
5526 }
5527 
5528 /*
5529  * Set a vdev's state.  If this is during an open, we don't update the parent
5530  * state, because we're in the process of opening children depth-first.
5531  * Otherwise, we propagate the change to the parent.
5532  *
5533  * If this routine places a device in a faulted state, an appropriate ereport is
5534  * generated.
5535  */
5536 void
vdev_set_state(vdev_t * vd,boolean_t isopen,vdev_state_t state,vdev_aux_t aux)5537 vdev_set_state(vdev_t *vd, boolean_t isopen, vdev_state_t state, vdev_aux_t aux)
5538 {
5539 	uint64_t save_state;
5540 	spa_t *spa = vd->vdev_spa;
5541 
5542 	if (state == vd->vdev_state) {
5543 		/*
5544 		 * Since vdev_offline() code path is already in an offline
5545 		 * state we can miss a statechange event to OFFLINE. Check
5546 		 * the previous state to catch this condition.
5547 		 */
5548 		if (vd->vdev_ops->vdev_op_leaf &&
5549 		    (state == VDEV_STATE_OFFLINE) &&
5550 		    (vd->vdev_prevstate >= VDEV_STATE_FAULTED)) {
5551 			/* post an offline state change */
5552 			zfs_post_state_change(spa, vd, vd->vdev_prevstate);
5553 		}
5554 		vd->vdev_stat.vs_aux = aux;
5555 		return;
5556 	}
5557 
5558 	save_state = vd->vdev_state;
5559 
5560 	vd->vdev_state = state;
5561 	vd->vdev_stat.vs_aux = aux;
5562 
5563 	/*
5564 	 * If we are setting the vdev state to anything but an open state, then
5565 	 * always close the underlying device unless the device has requested
5566 	 * a delayed close (i.e. we're about to remove or fault the device).
5567 	 * Otherwise, we keep accessible but invalid devices open forever.
5568 	 * We don't call vdev_close() itself, because that implies some extra
5569 	 * checks (offline, etc) that we don't want here.  This is limited to
5570 	 * leaf devices, because otherwise closing the device will affect other
5571 	 * children.
5572 	 */
5573 	if (!vd->vdev_delayed_close && vdev_is_dead(vd) &&
5574 	    vd->vdev_ops->vdev_op_leaf)
5575 		vd->vdev_ops->vdev_op_close(vd);
5576 
5577 	if (vd->vdev_removed &&
5578 	    state == VDEV_STATE_CANT_OPEN &&
5579 	    (aux == VDEV_AUX_OPEN_FAILED || vd->vdev_checkremove)) {
5580 		/*
5581 		 * If the previous state is set to VDEV_STATE_REMOVED, then this
5582 		 * device was previously marked removed and someone attempted to
5583 		 * reopen it.  If this failed due to a nonexistent device, then
5584 		 * keep the device in the REMOVED state.  We also let this be if
5585 		 * it is one of our special test online cases, which is only
5586 		 * attempting to online the device and shouldn't generate an FMA
5587 		 * fault.
5588 		 */
5589 		vd->vdev_state = VDEV_STATE_REMOVED;
5590 		vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
5591 	} else if (state == VDEV_STATE_REMOVED) {
5592 		vd->vdev_removed = B_TRUE;
5593 	} else if (state == VDEV_STATE_CANT_OPEN) {
5594 		/*
5595 		 * If we fail to open a vdev during an import or recovery, we
5596 		 * mark it as "not available", which signifies that it was
5597 		 * never there to begin with.  Failure to open such a device
5598 		 * is not considered an error.
5599 		 */
5600 		if ((spa_load_state(spa) == SPA_LOAD_IMPORT ||
5601 		    spa_load_state(spa) == SPA_LOAD_RECOVER) &&
5602 		    vd->vdev_ops->vdev_op_leaf)
5603 			vd->vdev_not_present = 1;
5604 
5605 		/*
5606 		 * Post the appropriate ereport.  If the 'prevstate' field is
5607 		 * set to something other than VDEV_STATE_UNKNOWN, it indicates
5608 		 * that this is part of a vdev_reopen().  In this case, we don't
5609 		 * want to post the ereport if the device was already in the
5610 		 * CANT_OPEN state beforehand.
5611 		 *
5612 		 * If the 'checkremove' flag is set, then this is an attempt to
5613 		 * online the device in response to an insertion event.  If we
5614 		 * hit this case, then we have detected an insertion event for a
5615 		 * faulted or offline device that wasn't in the removed state.
5616 		 * In this scenario, we don't post an ereport because we are
5617 		 * about to replace the device, or attempt an online with
5618 		 * vdev_forcefault, which will generate the fault for us.
5619 		 */
5620 		if ((vd->vdev_prevstate != state || vd->vdev_forcefault) &&
5621 		    !vd->vdev_not_present && !vd->vdev_checkremove &&
5622 		    vd != spa->spa_root_vdev) {
5623 			const char *class;
5624 
5625 			switch (aux) {
5626 			case VDEV_AUX_OPEN_FAILED:
5627 				class = FM_EREPORT_ZFS_DEVICE_OPEN_FAILED;
5628 				break;
5629 			case VDEV_AUX_CORRUPT_DATA:
5630 				class = FM_EREPORT_ZFS_DEVICE_CORRUPT_DATA;
5631 				break;
5632 			case VDEV_AUX_NO_REPLICAS:
5633 				class = FM_EREPORT_ZFS_DEVICE_NO_REPLICAS;
5634 				break;
5635 			case VDEV_AUX_BAD_GUID_SUM:
5636 				class = FM_EREPORT_ZFS_DEVICE_BAD_GUID_SUM;
5637 				break;
5638 			case VDEV_AUX_TOO_SMALL:
5639 				class = FM_EREPORT_ZFS_DEVICE_TOO_SMALL;
5640 				break;
5641 			case VDEV_AUX_BAD_LABEL:
5642 				class = FM_EREPORT_ZFS_DEVICE_BAD_LABEL;
5643 				break;
5644 			case VDEV_AUX_BAD_ASHIFT:
5645 				class = FM_EREPORT_ZFS_DEVICE_BAD_ASHIFT;
5646 				break;
5647 			default:
5648 				class = FM_EREPORT_ZFS_DEVICE_UNKNOWN;
5649 			}
5650 
5651 			(void) zfs_ereport_post(class, spa, vd, NULL, NULL,
5652 			    save_state);
5653 		}
5654 
5655 		/* Erase any notion of persistent removed state */
5656 		vd->vdev_removed = B_FALSE;
5657 	} else {
5658 		vd->vdev_removed = B_FALSE;
5659 	}
5660 
5661 	/*
5662 	 * Notify ZED of any significant state-change on a leaf vdev.
5663 	 *
5664 	 */
5665 	if (vd->vdev_ops->vdev_op_leaf) {
5666 		/* preserve original state from a vdev_reopen() */
5667 		if ((vd->vdev_prevstate != VDEV_STATE_UNKNOWN) &&
5668 		    (vd->vdev_prevstate != vd->vdev_state) &&
5669 		    (save_state <= VDEV_STATE_CLOSED))
5670 			save_state = vd->vdev_prevstate;
5671 
5672 		/* filter out state change due to initial vdev_open */
5673 		if (save_state > VDEV_STATE_CLOSED)
5674 			zfs_post_state_change(spa, vd, save_state);
5675 	}
5676 
5677 	if (!isopen && vd->vdev_parent)
5678 		vdev_propagate_state(vd->vdev_parent);
5679 }
5680 
5681 boolean_t
vdev_children_are_offline(vdev_t * vd)5682 vdev_children_are_offline(vdev_t *vd)
5683 {
5684 	ASSERT(!vd->vdev_ops->vdev_op_leaf);
5685 
5686 	for (uint64_t i = 0; i < vd->vdev_children; i++) {
5687 		if (vd->vdev_child[i]->vdev_state != VDEV_STATE_OFFLINE)
5688 			return (B_FALSE);
5689 	}
5690 
5691 	return (B_TRUE);
5692 }
5693 
5694 /*
5695  * Check the vdev configuration to ensure that it's capable of supporting
5696  * a root pool. We do not support partial configuration.
5697  */
5698 boolean_t
vdev_is_bootable(vdev_t * vd)5699 vdev_is_bootable(vdev_t *vd)
5700 {
5701 	if (!vd->vdev_ops->vdev_op_leaf) {
5702 		const char *vdev_type = vd->vdev_ops->vdev_op_type;
5703 
5704 		if (strcmp(vdev_type, VDEV_TYPE_MISSING) == 0)
5705 			return (B_FALSE);
5706 	}
5707 
5708 	for (int c = 0; c < vd->vdev_children; c++) {
5709 		if (!vdev_is_bootable(vd->vdev_child[c]))
5710 			return (B_FALSE);
5711 	}
5712 	return (B_TRUE);
5713 }
5714 
5715 boolean_t
vdev_is_concrete(vdev_t * vd)5716 vdev_is_concrete(vdev_t *vd)
5717 {
5718 	vdev_ops_t *ops = vd->vdev_ops;
5719 	if (ops == &vdev_indirect_ops || ops == &vdev_hole_ops ||
5720 	    ops == &vdev_missing_ops || ops == &vdev_root_ops) {
5721 		return (B_FALSE);
5722 	} else {
5723 		return (B_TRUE);
5724 	}
5725 }
5726 
5727 /*
5728  * Determine if a log device has valid content.  If the vdev was
5729  * removed or faulted in the MOS config then we know that
5730  * the content on the log device has already been written to the pool.
5731  */
5732 boolean_t
vdev_log_state_valid(vdev_t * vd)5733 vdev_log_state_valid(vdev_t *vd)
5734 {
5735 	if (vd->vdev_ops->vdev_op_leaf && !vd->vdev_faulted &&
5736 	    !vd->vdev_removed)
5737 		return (B_TRUE);
5738 
5739 	for (int c = 0; c < vd->vdev_children; c++)
5740 		if (vdev_log_state_valid(vd->vdev_child[c]))
5741 			return (B_TRUE);
5742 
5743 	return (B_FALSE);
5744 }
5745 
5746 /*
5747  * Expand a vdev if possible.
5748  */
5749 void
vdev_expand(vdev_t * vd,uint64_t txg)5750 vdev_expand(vdev_t *vd, uint64_t txg)
5751 {
5752 	ASSERT(vd->vdev_top == vd);
5753 	ASSERT(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5754 	ASSERT(vdev_is_concrete(vd));
5755 
5756 	vdev_set_deflate_ratio(vd);
5757 
5758 	if ((vd->vdev_spa->spa_raidz_expand == NULL ||
5759 	    vd->vdev_spa->spa_raidz_expand->vre_vdev_id != vd->vdev_id) &&
5760 	    (vd->vdev_asize >> vd->vdev_ms_shift) > vd->vdev_ms_count &&
5761 	    vdev_is_concrete(vd)) {
5762 		vdev_metaslab_group_create(vd);
5763 		VERIFY0(vdev_metaslab_init(vd, txg));
5764 		vdev_config_dirty(vd);
5765 	}
5766 }
5767 
5768 /*
5769  * Split a vdev.
5770  */
5771 void
vdev_split(vdev_t * vd)5772 vdev_split(vdev_t *vd)
5773 {
5774 	vdev_t *cvd, *pvd = vd->vdev_parent;
5775 
5776 	VERIFY3U(pvd->vdev_children, >, 1);
5777 
5778 	vdev_remove_child(pvd, vd);
5779 	vdev_compact_children(pvd);
5780 
5781 	ASSERT3P(pvd->vdev_child, !=, NULL);
5782 
5783 	cvd = pvd->vdev_child[0];
5784 	if (pvd->vdev_children == 1) {
5785 		vdev_remove_parent(cvd);
5786 		cvd->vdev_splitting = B_TRUE;
5787 	}
5788 	vdev_propagate_state(cvd);
5789 }
5790 
5791 void
vdev_deadman(vdev_t * vd,const char * tag)5792 vdev_deadman(vdev_t *vd, const char *tag)
5793 {
5794 	for (int c = 0; c < vd->vdev_children; c++) {
5795 		vdev_t *cvd = vd->vdev_child[c];
5796 
5797 		vdev_deadman(cvd, tag);
5798 	}
5799 
5800 	if (vd->vdev_ops->vdev_op_leaf) {
5801 		vdev_queue_t *vq = &vd->vdev_queue;
5802 
5803 		mutex_enter(&vq->vq_lock);
5804 		if (vq->vq_active > 0) {
5805 			spa_t *spa = vd->vdev_spa;
5806 			zio_t *fio;
5807 			uint64_t delta;
5808 
5809 			zfs_dbgmsg("slow vdev: %s has %u active IOs",
5810 			    vd->vdev_path, vq->vq_active);
5811 
5812 			/*
5813 			 * Look at the head of all the pending queues,
5814 			 * if any I/O has been outstanding for longer than
5815 			 * the spa_deadman_synctime invoke the deadman logic.
5816 			 */
5817 			fio = list_head(&vq->vq_active_list);
5818 			delta = gethrtime() - fio->io_timestamp;
5819 			if (delta > spa_deadman_synctime(spa))
5820 				zio_deadman(fio, tag);
5821 		}
5822 		mutex_exit(&vq->vq_lock);
5823 	}
5824 }
5825 
5826 void
vdev_defer_resilver(vdev_t * vd)5827 vdev_defer_resilver(vdev_t *vd)
5828 {
5829 	ASSERT(vd->vdev_ops->vdev_op_leaf);
5830 
5831 	vd->vdev_resilver_deferred = B_TRUE;
5832 	vd->vdev_spa->spa_resilver_deferred = B_TRUE;
5833 }
5834 
5835 /*
5836  * Clears the resilver deferred flag on all leaf devs under vd. Returns
5837  * B_TRUE if we have devices that need to be resilvered and are available to
5838  * accept resilver I/Os.
5839  */
5840 boolean_t
vdev_clear_resilver_deferred(vdev_t * vd,dmu_tx_t * tx)5841 vdev_clear_resilver_deferred(vdev_t *vd, dmu_tx_t *tx)
5842 {
5843 	boolean_t resilver_needed = B_FALSE;
5844 	spa_t *spa = vd->vdev_spa;
5845 
5846 	for (int c = 0; c < vd->vdev_children; c++) {
5847 		vdev_t *cvd = vd->vdev_child[c];
5848 		resilver_needed |= vdev_clear_resilver_deferred(cvd, tx);
5849 	}
5850 
5851 	if (vd == spa->spa_root_vdev &&
5852 	    spa_feature_is_active(spa, SPA_FEATURE_RESILVER_DEFER)) {
5853 		spa_feature_decr(spa, SPA_FEATURE_RESILVER_DEFER, tx);
5854 		vdev_config_dirty(vd);
5855 		spa->spa_resilver_deferred = B_FALSE;
5856 		return (resilver_needed);
5857 	}
5858 
5859 	if (!vdev_is_concrete(vd) || vd->vdev_aux ||
5860 	    !vd->vdev_ops->vdev_op_leaf)
5861 		return (resilver_needed);
5862 
5863 	vd->vdev_resilver_deferred = B_FALSE;
5864 
5865 	return (!vdev_is_dead(vd) && !vd->vdev_offline &&
5866 	    vdev_resilver_needed(vd, NULL, NULL));
5867 }
5868 
5869 boolean_t
vdev_xlate_is_empty(zfs_range_seg64_t * rs)5870 vdev_xlate_is_empty(zfs_range_seg64_t *rs)
5871 {
5872 	return (rs->rs_start == rs->rs_end);
5873 }
5874 
5875 /*
5876  * Translate a logical range to the first contiguous physical range for the
5877  * specified vdev_t.  This function is initially called with a leaf vdev and
5878  * will walk each parent vdev until it reaches a top-level vdev. Once the
5879  * top-level is reached the physical range is initialized and the recursive
5880  * function begins to unwind. As it unwinds it calls the parent's vdev
5881  * specific translation function to do the real conversion.
5882  */
5883 void
vdev_xlate(vdev_t * vd,const zfs_range_seg64_t * logical_rs,zfs_range_seg64_t * physical_rs,zfs_range_seg64_t * remain_rs)5884 vdev_xlate(vdev_t *vd, const zfs_range_seg64_t *logical_rs,
5885     zfs_range_seg64_t *physical_rs, zfs_range_seg64_t *remain_rs)
5886 {
5887 	/*
5888 	 * Walk up the vdev tree
5889 	 */
5890 	if (vd != vd->vdev_top) {
5891 		vdev_xlate(vd->vdev_parent, logical_rs, physical_rs,
5892 		    remain_rs);
5893 	} else {
5894 		/*
5895 		 * We've reached the top-level vdev, initialize the physical
5896 		 * range to the logical range and set an empty remaining
5897 		 * range then start to unwind.
5898 		 */
5899 		physical_rs->rs_start = logical_rs->rs_start;
5900 		physical_rs->rs_end = logical_rs->rs_end;
5901 
5902 		remain_rs->rs_start = logical_rs->rs_start;
5903 		remain_rs->rs_end = logical_rs->rs_start;
5904 
5905 		return;
5906 	}
5907 
5908 	vdev_t *pvd = vd->vdev_parent;
5909 	ASSERT3P(pvd, !=, NULL);
5910 	ASSERT3P(pvd->vdev_ops->vdev_op_xlate, !=, NULL);
5911 
5912 	/*
5913 	 * As this recursive function unwinds, translate the logical
5914 	 * range into its physical and any remaining components by calling
5915 	 * the vdev specific translate function.
5916 	 */
5917 	zfs_range_seg64_t intermediate = { 0 };
5918 	pvd->vdev_ops->vdev_op_xlate(vd, physical_rs, &intermediate, remain_rs);
5919 
5920 	physical_rs->rs_start = intermediate.rs_start;
5921 	physical_rs->rs_end = intermediate.rs_end;
5922 }
5923 
5924 void
vdev_xlate_walk(vdev_t * vd,const zfs_range_seg64_t * logical_rs,vdev_xlate_func_t * func,void * arg)5925 vdev_xlate_walk(vdev_t *vd, const zfs_range_seg64_t *logical_rs,
5926     vdev_xlate_func_t *func, void *arg)
5927 {
5928 	zfs_range_seg64_t iter_rs = *logical_rs;
5929 	zfs_range_seg64_t physical_rs;
5930 	zfs_range_seg64_t remain_rs;
5931 
5932 	while (!vdev_xlate_is_empty(&iter_rs)) {
5933 
5934 		vdev_xlate(vd, &iter_rs, &physical_rs, &remain_rs);
5935 
5936 		/*
5937 		 * With raidz and dRAID, it's possible that the logical range
5938 		 * does not live on this leaf vdev. Only when there is a non-
5939 		 * zero physical size call the provided function.
5940 		 */
5941 		if (!vdev_xlate_is_empty(&physical_rs))
5942 			func(arg, &physical_rs);
5943 
5944 		iter_rs = remain_rs;
5945 	}
5946 }
5947 
5948 static char *
vdev_name(vdev_t * vd,char * buf,int buflen)5949 vdev_name(vdev_t *vd, char *buf, int buflen)
5950 {
5951 	if (vd->vdev_path == NULL) {
5952 		if (strcmp(vd->vdev_ops->vdev_op_type, "root") == 0) {
5953 			strlcpy(buf, vd->vdev_spa->spa_name, buflen);
5954 		} else if (!vd->vdev_ops->vdev_op_leaf) {
5955 			snprintf(buf, buflen, "%s-%llu",
5956 			    vd->vdev_ops->vdev_op_type,
5957 			    (u_longlong_t)vd->vdev_id);
5958 		}
5959 	} else {
5960 		strlcpy(buf, vd->vdev_path, buflen);
5961 	}
5962 	return (buf);
5963 }
5964 
5965 /*
5966  * Look at the vdev tree and determine whether any devices are currently being
5967  * replaced.
5968  */
5969 boolean_t
vdev_replace_in_progress(vdev_t * vdev)5970 vdev_replace_in_progress(vdev_t *vdev)
5971 {
5972 	ASSERT(spa_config_held(vdev->vdev_spa, SCL_ALL, RW_READER) != 0);
5973 
5974 	if (vdev->vdev_ops == &vdev_replacing_ops)
5975 		return (B_TRUE);
5976 
5977 	/*
5978 	 * A 'spare' vdev indicates that we have a replace in progress, unless
5979 	 * it has exactly two children, and the second, the hot spare, has
5980 	 * finished being resilvered.
5981 	 */
5982 	if (vdev->vdev_ops == &vdev_spare_ops && (vdev->vdev_children > 2 ||
5983 	    !vdev_dtl_empty(vdev->vdev_child[1], DTL_MISSING)))
5984 		return (B_TRUE);
5985 
5986 	for (int i = 0; i < vdev->vdev_children; i++) {
5987 		if (vdev_replace_in_progress(vdev->vdev_child[i]))
5988 			return (B_TRUE);
5989 	}
5990 
5991 	return (B_FALSE);
5992 }
5993 
5994 /*
5995  * Add a (source=src, propname=propval) list to an nvlist.
5996  */
5997 static void
vdev_prop_add_list(nvlist_t * nvl,const char * propname,const char * strval,uint64_t intval,zprop_source_t src)5998 vdev_prop_add_list(nvlist_t *nvl, const char *propname, const char *strval,
5999     uint64_t intval, zprop_source_t src)
6000 {
6001 	nvlist_t *propval;
6002 
6003 	propval = fnvlist_alloc();
6004 	fnvlist_add_uint64(propval, ZPROP_SOURCE, src);
6005 
6006 	if (strval != NULL)
6007 		fnvlist_add_string(propval, ZPROP_VALUE, strval);
6008 	else
6009 		fnvlist_add_uint64(propval, ZPROP_VALUE, intval);
6010 
6011 	fnvlist_add_nvlist(nvl, propname, propval);
6012 	nvlist_free(propval);
6013 }
6014 
6015 static void
vdev_props_set_sync(void * arg,dmu_tx_t * tx)6016 vdev_props_set_sync(void *arg, dmu_tx_t *tx)
6017 {
6018 	vdev_t *vd;
6019 	nvlist_t *nvp = arg;
6020 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
6021 	objset_t *mos = spa->spa_meta_objset;
6022 	nvpair_t *elem = NULL;
6023 	uint64_t vdev_guid;
6024 	uint64_t objid;
6025 	nvlist_t *nvprops;
6026 
6027 	vdev_guid = fnvlist_lookup_uint64(nvp, ZPOOL_VDEV_PROPS_SET_VDEV);
6028 	nvprops = fnvlist_lookup_nvlist(nvp, ZPOOL_VDEV_PROPS_SET_PROPS);
6029 	vd = spa_lookup_by_guid(spa, vdev_guid, B_TRUE);
6030 
6031 	/* this vdev could get removed while waiting for this sync task */
6032 	if (vd == NULL)
6033 		return;
6034 
6035 	/*
6036 	 * Set vdev property values in the vdev props mos object.
6037 	 */
6038 	if (vdev_prop_get_objid(vd, &objid) != 0)
6039 		panic("unexpected vdev type");
6040 
6041 	mutex_enter(&spa->spa_props_lock);
6042 
6043 	while ((elem = nvlist_next_nvpair(nvprops, elem)) != NULL) {
6044 		uint64_t intval;
6045 		const char *strval;
6046 		vdev_prop_t prop;
6047 		const char *propname = nvpair_name(elem);
6048 		zprop_type_t proptype;
6049 
6050 		switch (prop = vdev_name_to_prop(propname)) {
6051 		case VDEV_PROP_USERPROP:
6052 			if (vdev_prop_user(propname)) {
6053 				strval = fnvpair_value_string(elem);
6054 				if (strlen(strval) == 0) {
6055 					/* remove the property if value == "" */
6056 					(void) zap_remove(mos, objid, propname,
6057 					    tx);
6058 				} else {
6059 					VERIFY0(zap_update(mos, objid, propname,
6060 					    1, strlen(strval) + 1, strval, tx));
6061 				}
6062 				spa_history_log_internal(spa, "vdev set", tx,
6063 				    "vdev_guid=%llu: %s=%s",
6064 				    (u_longlong_t)vdev_guid, nvpair_name(elem),
6065 				    strval);
6066 			}
6067 			break;
6068 		default:
6069 			/* normalize the property name */
6070 			propname = vdev_prop_to_name(prop);
6071 			proptype = vdev_prop_get_type(prop);
6072 
6073 			if (nvpair_type(elem) == DATA_TYPE_STRING) {
6074 				ASSERT(proptype == PROP_TYPE_STRING);
6075 				strval = fnvpair_value_string(elem);
6076 				VERIFY0(zap_update(mos, objid, propname,
6077 				    1, strlen(strval) + 1, strval, tx));
6078 				spa_history_log_internal(spa, "vdev set", tx,
6079 				    "vdev_guid=%llu: %s=%s",
6080 				    (u_longlong_t)vdev_guid, nvpair_name(elem),
6081 				    strval);
6082 			} else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
6083 				intval = fnvpair_value_uint64(elem);
6084 
6085 				if (proptype == PROP_TYPE_INDEX) {
6086 					const char *unused;
6087 					VERIFY0(vdev_prop_index_to_string(
6088 					    prop, intval, &unused));
6089 				}
6090 				VERIFY0(zap_update(mos, objid, propname,
6091 				    sizeof (uint64_t), 1, &intval, tx));
6092 				spa_history_log_internal(spa, "vdev set", tx,
6093 				    "vdev_guid=%llu: %s=%lld",
6094 				    (u_longlong_t)vdev_guid,
6095 				    nvpair_name(elem), (longlong_t)intval);
6096 			} else {
6097 				panic("invalid vdev property type %u",
6098 				    nvpair_type(elem));
6099 			}
6100 		}
6101 
6102 	}
6103 
6104 	mutex_exit(&spa->spa_props_lock);
6105 }
6106 
6107 int
vdev_prop_set(vdev_t * vd,nvlist_t * innvl,nvlist_t * outnvl)6108 vdev_prop_set(vdev_t *vd, nvlist_t *innvl, nvlist_t *outnvl)
6109 {
6110 	spa_t *spa = vd->vdev_spa;
6111 	nvpair_t *elem = NULL;
6112 	uint64_t vdev_guid;
6113 	nvlist_t *nvprops;
6114 	int error = 0;
6115 
6116 	ASSERT(vd != NULL);
6117 
6118 	/* Check that vdev has a zap we can use */
6119 	if (vd->vdev_root_zap == 0 &&
6120 	    vd->vdev_top_zap == 0 &&
6121 	    vd->vdev_leaf_zap == 0)
6122 		return (SET_ERROR(EINVAL));
6123 
6124 	if (nvlist_lookup_uint64(innvl, ZPOOL_VDEV_PROPS_SET_VDEV,
6125 	    &vdev_guid) != 0)
6126 		return (SET_ERROR(EINVAL));
6127 
6128 	if (nvlist_lookup_nvlist(innvl, ZPOOL_VDEV_PROPS_SET_PROPS,
6129 	    &nvprops) != 0)
6130 		return (SET_ERROR(EINVAL));
6131 
6132 	if ((vd = spa_lookup_by_guid(spa, vdev_guid, B_TRUE)) == NULL)
6133 		return (SET_ERROR(EINVAL));
6134 
6135 	while ((elem = nvlist_next_nvpair(nvprops, elem)) != NULL) {
6136 		const char *propname = nvpair_name(elem);
6137 		vdev_prop_t prop = vdev_name_to_prop(propname);
6138 		uint64_t intval = 0;
6139 		const char *strval = NULL;
6140 
6141 		if (prop == VDEV_PROP_USERPROP && !vdev_prop_user(propname)) {
6142 			error = EINVAL;
6143 			goto end;
6144 		}
6145 
6146 		if (prop != VDEV_PROP_USERPROP && vdev_prop_readonly(prop)) {
6147 			error = EROFS;
6148 			goto end;
6149 		}
6150 
6151 		/* Special Processing */
6152 		switch (prop) {
6153 		case VDEV_PROP_PATH:
6154 			if (vd->vdev_path == NULL) {
6155 				error = EROFS;
6156 				break;
6157 			}
6158 			if (nvpair_value_string(elem, &strval) != 0) {
6159 				error = EINVAL;
6160 				break;
6161 			}
6162 			/* New path must start with /dev/ */
6163 			if (strncmp(strval, "/dev/", 5)) {
6164 				error = EINVAL;
6165 				break;
6166 			}
6167 			error = spa_vdev_setpath(spa, vdev_guid, strval);
6168 			break;
6169 		case VDEV_PROP_ALLOCATING:
6170 			if (nvpair_value_uint64(elem, &intval) != 0) {
6171 				error = EINVAL;
6172 				break;
6173 			}
6174 			if (intval != vd->vdev_noalloc)
6175 				break;
6176 			if (intval == 0)
6177 				error = spa_vdev_noalloc(spa, vdev_guid);
6178 			else
6179 				error = spa_vdev_alloc(spa, vdev_guid);
6180 			break;
6181 		case VDEV_PROP_FAILFAST:
6182 			if (nvpair_value_uint64(elem, &intval) != 0) {
6183 				error = EINVAL;
6184 				break;
6185 			}
6186 			vd->vdev_failfast = intval & 1;
6187 			break;
6188 		case VDEV_PROP_SIT_OUT:
6189 			/* Only expose this for a draid or raidz leaf */
6190 			if (!vd->vdev_ops->vdev_op_leaf ||
6191 			    vd->vdev_top == NULL ||
6192 			    (vd->vdev_top->vdev_ops != &vdev_raidz_ops &&
6193 			    vd->vdev_top->vdev_ops != &vdev_draid_ops)) {
6194 				error = ENOTSUP;
6195 				break;
6196 			}
6197 			if (nvpair_value_uint64(elem, &intval) != 0) {
6198 				error = EINVAL;
6199 				break;
6200 			}
6201 			if (intval == 1) {
6202 				vdev_t *ancestor = vd;
6203 				while (ancestor->vdev_parent != vd->vdev_top)
6204 					ancestor = ancestor->vdev_parent;
6205 				vdev_t *pvd = vd->vdev_top;
6206 				uint_t sitouts = 0;
6207 				for (int i = 0; i < pvd->vdev_children; i++) {
6208 					if (pvd->vdev_child[i] == ancestor)
6209 						continue;
6210 					if (vdev_sit_out_reads(
6211 					    pvd->vdev_child[i], 0)) {
6212 						sitouts++;
6213 					}
6214 				}
6215 				if (sitouts >= vdev_get_nparity(pvd)) {
6216 					error = ZFS_ERR_TOO_MANY_SITOUTS;
6217 					break;
6218 				}
6219 				if (error == 0)
6220 					vdev_raidz_sit_child(vd,
6221 					    INT64_MAX - gethrestime_sec());
6222 			} else {
6223 				vdev_raidz_unsit_child(vd);
6224 			}
6225 			break;
6226 		case VDEV_PROP_AUTOSIT:
6227 			if (vd->vdev_ops != &vdev_raidz_ops &&
6228 			    vd->vdev_ops != &vdev_draid_ops) {
6229 				error = ENOTSUP;
6230 				break;
6231 			}
6232 			if (nvpair_value_uint64(elem, &intval) != 0) {
6233 				error = EINVAL;
6234 				break;
6235 			}
6236 			vd->vdev_autosit = intval == 1;
6237 			break;
6238 		case VDEV_PROP_CHECKSUM_N:
6239 			if (nvpair_value_uint64(elem, &intval) != 0) {
6240 				error = EINVAL;
6241 				break;
6242 			}
6243 			vd->vdev_checksum_n = intval;
6244 			break;
6245 		case VDEV_PROP_CHECKSUM_T:
6246 			if (nvpair_value_uint64(elem, &intval) != 0) {
6247 				error = EINVAL;
6248 				break;
6249 			}
6250 			vd->vdev_checksum_t = intval;
6251 			break;
6252 		case VDEV_PROP_IO_N:
6253 			if (nvpair_value_uint64(elem, &intval) != 0) {
6254 				error = EINVAL;
6255 				break;
6256 			}
6257 			vd->vdev_io_n = intval;
6258 			break;
6259 		case VDEV_PROP_IO_T:
6260 			if (nvpair_value_uint64(elem, &intval) != 0) {
6261 				error = EINVAL;
6262 				break;
6263 			}
6264 			vd->vdev_io_t = intval;
6265 			break;
6266 		case VDEV_PROP_SLOW_IO_EVENTS:
6267 			if (nvpair_value_uint64(elem, &intval) != 0) {
6268 				error = EINVAL;
6269 				break;
6270 			}
6271 			vd->vdev_slow_io_events = intval != 0;
6272 			break;
6273 		case VDEV_PROP_SLOW_IO_N:
6274 			if (nvpair_value_uint64(elem, &intval) != 0) {
6275 				error = EINVAL;
6276 				break;
6277 			}
6278 			vd->vdev_slow_io_n = intval;
6279 			break;
6280 		case VDEV_PROP_SLOW_IO_T:
6281 			if (nvpair_value_uint64(elem, &intval) != 0) {
6282 				error = EINVAL;
6283 				break;
6284 			}
6285 			vd->vdev_slow_io_t = intval;
6286 			break;
6287 		case VDEV_PROP_SCHEDULER:
6288 			if (nvpair_value_uint64(elem, &intval) != 0) {
6289 				error = EINVAL;
6290 				break;
6291 			}
6292 			vd->vdev_scheduler = intval;
6293 			break;
6294 		default:
6295 			/* Most processing is done in vdev_props_set_sync */
6296 			break;
6297 		}
6298 end:
6299 		if (error != 0) {
6300 			intval = error;
6301 			vdev_prop_add_list(outnvl, propname, strval, intval, 0);
6302 			return (error);
6303 		}
6304 	}
6305 
6306 	return (dsl_sync_task(spa->spa_name, NULL, vdev_props_set_sync,
6307 	    innvl, 6, ZFS_SPACE_CHECK_EXTRA_RESERVED));
6308 }
6309 
6310 int
vdev_prop_get(vdev_t * vd,nvlist_t * innvl,nvlist_t * outnvl)6311 vdev_prop_get(vdev_t *vd, nvlist_t *innvl, nvlist_t *outnvl)
6312 {
6313 	spa_t *spa = vd->vdev_spa;
6314 	objset_t *mos = spa->spa_meta_objset;
6315 	int err = 0;
6316 	uint64_t objid;
6317 	uint64_t vdev_guid;
6318 	nvpair_t *elem = NULL;
6319 	nvlist_t *nvprops = NULL;
6320 	uint64_t intval = 0;
6321 	boolean_t boolval = 0;
6322 	char *strval = NULL;
6323 	const char *propname = NULL;
6324 	vdev_prop_t prop;
6325 
6326 	ASSERT(vd != NULL);
6327 	ASSERT(mos != NULL);
6328 
6329 	if (nvlist_lookup_uint64(innvl, ZPOOL_VDEV_PROPS_GET_VDEV,
6330 	    &vdev_guid) != 0)
6331 		return (SET_ERROR(EINVAL));
6332 
6333 	nvlist_lookup_nvlist(innvl, ZPOOL_VDEV_PROPS_GET_PROPS, &nvprops);
6334 
6335 	if (vdev_prop_get_objid(vd, &objid) != 0)
6336 		return (SET_ERROR(EINVAL));
6337 	ASSERT(objid != 0);
6338 
6339 	mutex_enter(&spa->spa_props_lock);
6340 
6341 	if (nvprops != NULL) {
6342 		char namebuf[64] = { 0 };
6343 
6344 		while ((elem = nvlist_next_nvpair(nvprops, elem)) != NULL) {
6345 			intval = 0;
6346 			strval = NULL;
6347 			propname = nvpair_name(elem);
6348 			prop = vdev_name_to_prop(propname);
6349 			zprop_source_t src = ZPROP_SRC_DEFAULT;
6350 			uint64_t integer_size, num_integers;
6351 
6352 			switch (prop) {
6353 			/* Special Read-only Properties */
6354 			case VDEV_PROP_NAME:
6355 				strval = vdev_name(vd, namebuf,
6356 				    sizeof (namebuf));
6357 				if (strval == NULL)
6358 					continue;
6359 				vdev_prop_add_list(outnvl, propname, strval, 0,
6360 				    ZPROP_SRC_NONE);
6361 				continue;
6362 			case VDEV_PROP_CAPACITY:
6363 				/* percent used */
6364 				intval = (vd->vdev_stat.vs_dspace == 0) ? 0 :
6365 				    (vd->vdev_stat.vs_alloc * 100 /
6366 				    vd->vdev_stat.vs_dspace);
6367 				vdev_prop_add_list(outnvl, propname, NULL,
6368 				    intval, ZPROP_SRC_NONE);
6369 				continue;
6370 			case VDEV_PROP_STATE:
6371 				vdev_prop_add_list(outnvl, propname, NULL,
6372 				    vd->vdev_state, ZPROP_SRC_NONE);
6373 				continue;
6374 			case VDEV_PROP_GUID:
6375 				vdev_prop_add_list(outnvl, propname, NULL,
6376 				    vd->vdev_guid, ZPROP_SRC_NONE);
6377 				continue;
6378 			case VDEV_PROP_ASIZE:
6379 				vdev_prop_add_list(outnvl, propname, NULL,
6380 				    vd->vdev_asize, ZPROP_SRC_NONE);
6381 				continue;
6382 			case VDEV_PROP_PSIZE:
6383 				vdev_prop_add_list(outnvl, propname, NULL,
6384 				    vd->vdev_psize, ZPROP_SRC_NONE);
6385 				continue;
6386 			case VDEV_PROP_ASHIFT:
6387 				vdev_prop_add_list(outnvl, propname, NULL,
6388 				    vd->vdev_ashift, ZPROP_SRC_NONE);
6389 				continue;
6390 			case VDEV_PROP_SIZE:
6391 				vdev_prop_add_list(outnvl, propname, NULL,
6392 				    vd->vdev_stat.vs_dspace, ZPROP_SRC_NONE);
6393 				continue;
6394 			case VDEV_PROP_FREE:
6395 				vdev_prop_add_list(outnvl, propname, NULL,
6396 				    vd->vdev_stat.vs_dspace -
6397 				    vd->vdev_stat.vs_alloc, ZPROP_SRC_NONE);
6398 				continue;
6399 			case VDEV_PROP_ALLOCATED:
6400 				vdev_prop_add_list(outnvl, propname, NULL,
6401 				    vd->vdev_stat.vs_alloc, ZPROP_SRC_NONE);
6402 				continue;
6403 			case VDEV_PROP_EXPANDSZ:
6404 				vdev_prop_add_list(outnvl, propname, NULL,
6405 				    vd->vdev_stat.vs_esize, ZPROP_SRC_NONE);
6406 				continue;
6407 			case VDEV_PROP_FRAGMENTATION:
6408 				vdev_prop_add_list(outnvl, propname, NULL,
6409 				    vd->vdev_stat.vs_fragmentation,
6410 				    ZPROP_SRC_NONE);
6411 				continue;
6412 			case VDEV_PROP_PARITY:
6413 				vdev_prop_add_list(outnvl, propname, NULL,
6414 				    vdev_get_nparity(vd), ZPROP_SRC_NONE);
6415 				continue;
6416 			case VDEV_PROP_PATH:
6417 				if (vd->vdev_path == NULL)
6418 					continue;
6419 				vdev_prop_add_list(outnvl, propname,
6420 				    vd->vdev_path, 0, ZPROP_SRC_NONE);
6421 				continue;
6422 			case VDEV_PROP_DEVID:
6423 				if (vd->vdev_devid == NULL)
6424 					continue;
6425 				vdev_prop_add_list(outnvl, propname,
6426 				    vd->vdev_devid, 0, ZPROP_SRC_NONE);
6427 				continue;
6428 			case VDEV_PROP_PHYS_PATH:
6429 				if (vd->vdev_physpath == NULL)
6430 					continue;
6431 				vdev_prop_add_list(outnvl, propname,
6432 				    vd->vdev_physpath, 0, ZPROP_SRC_NONE);
6433 				continue;
6434 			case VDEV_PROP_ENC_PATH:
6435 				if (vd->vdev_enc_sysfs_path == NULL)
6436 					continue;
6437 				vdev_prop_add_list(outnvl, propname,
6438 				    vd->vdev_enc_sysfs_path, 0, ZPROP_SRC_NONE);
6439 				continue;
6440 			case VDEV_PROP_FRU:
6441 				if (vd->vdev_fru == NULL)
6442 					continue;
6443 				vdev_prop_add_list(outnvl, propname,
6444 				    vd->vdev_fru, 0, ZPROP_SRC_NONE);
6445 				continue;
6446 			case VDEV_PROP_PARENT:
6447 				if (vd->vdev_parent != NULL) {
6448 					strval = vdev_name(vd->vdev_parent,
6449 					    namebuf, sizeof (namebuf));
6450 					vdev_prop_add_list(outnvl, propname,
6451 					    strval, 0, ZPROP_SRC_NONE);
6452 				}
6453 				continue;
6454 			case VDEV_PROP_CHILDREN:
6455 				if (vd->vdev_children > 0)
6456 					strval = kmem_zalloc(ZAP_MAXVALUELEN,
6457 					    KM_SLEEP);
6458 				for (uint64_t i = 0; i < vd->vdev_children;
6459 				    i++) {
6460 					const char *vname;
6461 
6462 					vname = vdev_name(vd->vdev_child[i],
6463 					    namebuf, sizeof (namebuf));
6464 					if (vname == NULL)
6465 						vname = "(unknown)";
6466 					if (strlen(strval) > 0)
6467 						strlcat(strval, ",",
6468 						    ZAP_MAXVALUELEN);
6469 					strlcat(strval, vname, ZAP_MAXVALUELEN);
6470 				}
6471 				if (strval != NULL) {
6472 					vdev_prop_add_list(outnvl, propname,
6473 					    strval, 0, ZPROP_SRC_NONE);
6474 					kmem_free(strval, ZAP_MAXVALUELEN);
6475 				}
6476 				continue;
6477 			case VDEV_PROP_NUMCHILDREN:
6478 				vdev_prop_add_list(outnvl, propname, NULL,
6479 				    vd->vdev_children, ZPROP_SRC_NONE);
6480 				continue;
6481 			case VDEV_PROP_READ_ERRORS:
6482 				vdev_prop_add_list(outnvl, propname, NULL,
6483 				    vd->vdev_stat.vs_read_errors,
6484 				    ZPROP_SRC_NONE);
6485 				continue;
6486 			case VDEV_PROP_WRITE_ERRORS:
6487 				vdev_prop_add_list(outnvl, propname, NULL,
6488 				    vd->vdev_stat.vs_write_errors,
6489 				    ZPROP_SRC_NONE);
6490 				continue;
6491 			case VDEV_PROP_CHECKSUM_ERRORS:
6492 				vdev_prop_add_list(outnvl, propname, NULL,
6493 				    vd->vdev_stat.vs_checksum_errors,
6494 				    ZPROP_SRC_NONE);
6495 				continue;
6496 			case VDEV_PROP_INITIALIZE_ERRORS:
6497 				vdev_prop_add_list(outnvl, propname, NULL,
6498 				    vd->vdev_stat.vs_initialize_errors,
6499 				    ZPROP_SRC_NONE);
6500 				continue;
6501 			case VDEV_PROP_TRIM_ERRORS:
6502 				vdev_prop_add_list(outnvl, propname, NULL,
6503 				    vd->vdev_stat.vs_trim_errors,
6504 				    ZPROP_SRC_NONE);
6505 				continue;
6506 			case VDEV_PROP_SLOW_IOS:
6507 				vdev_prop_add_list(outnvl, propname, NULL,
6508 				    vd->vdev_stat.vs_slow_ios,
6509 				    ZPROP_SRC_NONE);
6510 				continue;
6511 			case VDEV_PROP_OPS_NULL:
6512 				vdev_prop_add_list(outnvl, propname, NULL,
6513 				    vd->vdev_stat.vs_ops[ZIO_TYPE_NULL],
6514 				    ZPROP_SRC_NONE);
6515 				continue;
6516 			case VDEV_PROP_OPS_READ:
6517 				vdev_prop_add_list(outnvl, propname, NULL,
6518 				    vd->vdev_stat.vs_ops[ZIO_TYPE_READ],
6519 				    ZPROP_SRC_NONE);
6520 				continue;
6521 			case VDEV_PROP_OPS_WRITE:
6522 				vdev_prop_add_list(outnvl, propname, NULL,
6523 				    vd->vdev_stat.vs_ops[ZIO_TYPE_WRITE],
6524 				    ZPROP_SRC_NONE);
6525 				continue;
6526 			case VDEV_PROP_OPS_FREE:
6527 				vdev_prop_add_list(outnvl, propname, NULL,
6528 				    vd->vdev_stat.vs_ops[ZIO_TYPE_FREE],
6529 				    ZPROP_SRC_NONE);
6530 				continue;
6531 			case VDEV_PROP_OPS_CLAIM:
6532 				vdev_prop_add_list(outnvl, propname, NULL,
6533 				    vd->vdev_stat.vs_ops[ZIO_TYPE_CLAIM],
6534 				    ZPROP_SRC_NONE);
6535 				continue;
6536 			case VDEV_PROP_OPS_TRIM:
6537 				/*
6538 				 * TRIM ops and bytes are reported to user
6539 				 * space as ZIO_TYPE_FLUSH.  This is done to
6540 				 * preserve the vdev_stat_t structure layout
6541 				 * for user space.
6542 				 */
6543 				vdev_prop_add_list(outnvl, propname, NULL,
6544 				    vd->vdev_stat.vs_ops[ZIO_TYPE_FLUSH],
6545 				    ZPROP_SRC_NONE);
6546 				continue;
6547 			case VDEV_PROP_BYTES_NULL:
6548 				vdev_prop_add_list(outnvl, propname, NULL,
6549 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_NULL],
6550 				    ZPROP_SRC_NONE);
6551 				continue;
6552 			case VDEV_PROP_BYTES_READ:
6553 				vdev_prop_add_list(outnvl, propname, NULL,
6554 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_READ],
6555 				    ZPROP_SRC_NONE);
6556 				continue;
6557 			case VDEV_PROP_BYTES_WRITE:
6558 				vdev_prop_add_list(outnvl, propname, NULL,
6559 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_WRITE],
6560 				    ZPROP_SRC_NONE);
6561 				continue;
6562 			case VDEV_PROP_BYTES_FREE:
6563 				vdev_prop_add_list(outnvl, propname, NULL,
6564 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_FREE],
6565 				    ZPROP_SRC_NONE);
6566 				continue;
6567 			case VDEV_PROP_BYTES_CLAIM:
6568 				vdev_prop_add_list(outnvl, propname, NULL,
6569 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_CLAIM],
6570 				    ZPROP_SRC_NONE);
6571 				continue;
6572 			case VDEV_PROP_BYTES_TRIM:
6573 				/*
6574 				 * TRIM ops and bytes are reported to user
6575 				 * space as ZIO_TYPE_FLUSH.  This is done to
6576 				 * preserve the vdev_stat_t structure layout
6577 				 * for user space.
6578 				 */
6579 				vdev_prop_add_list(outnvl, propname, NULL,
6580 				    vd->vdev_stat.vs_bytes[ZIO_TYPE_FLUSH],
6581 				    ZPROP_SRC_NONE);
6582 				continue;
6583 			case VDEV_PROP_REMOVING:
6584 				vdev_prop_add_list(outnvl, propname, NULL,
6585 				    vd->vdev_removing, ZPROP_SRC_NONE);
6586 				continue;
6587 			case VDEV_PROP_RAIDZ_EXPANDING:
6588 				/* Only expose this for raidz */
6589 				if (vd->vdev_ops == &vdev_raidz_ops) {
6590 					vdev_prop_add_list(outnvl, propname,
6591 					    NULL, vd->vdev_rz_expanding,
6592 					    ZPROP_SRC_NONE);
6593 				}
6594 				continue;
6595 			case VDEV_PROP_SIT_OUT:
6596 				/* Only expose this for a draid or raidz leaf */
6597 				if (vd->vdev_ops->vdev_op_leaf &&
6598 				    vd->vdev_top != NULL &&
6599 				    (vd->vdev_top->vdev_ops ==
6600 				    &vdev_raidz_ops ||
6601 				    vd->vdev_top->vdev_ops ==
6602 				    &vdev_draid_ops)) {
6603 					vdev_prop_add_list(outnvl, propname,
6604 					    NULL, vdev_sit_out_reads(vd, 0),
6605 					    ZPROP_SRC_NONE);
6606 				}
6607 				continue;
6608 			case VDEV_PROP_TRIM_SUPPORT:
6609 				/* only valid for leaf vdevs */
6610 				if (vd->vdev_ops->vdev_op_leaf) {
6611 					vdev_prop_add_list(outnvl, propname,
6612 					    NULL, vd->vdev_has_trim,
6613 					    ZPROP_SRC_NONE);
6614 				}
6615 				continue;
6616 			/* Numeric Properites */
6617 			case VDEV_PROP_ALLOCATING:
6618 				/* Leaf vdevs cannot have this property */
6619 				if (vd->vdev_mg == NULL &&
6620 				    vd->vdev_top != NULL) {
6621 					src = ZPROP_SRC_NONE;
6622 					intval = ZPROP_BOOLEAN_NA;
6623 				} else {
6624 					err = vdev_prop_get_int(vd, prop,
6625 					    &intval);
6626 					if (err && err != ENOENT)
6627 						break;
6628 
6629 					if (intval ==
6630 					    vdev_prop_default_numeric(prop))
6631 						src = ZPROP_SRC_DEFAULT;
6632 					else
6633 						src = ZPROP_SRC_LOCAL;
6634 				}
6635 
6636 				vdev_prop_add_list(outnvl, propname, NULL,
6637 				    intval, src);
6638 				break;
6639 			case VDEV_PROP_FAILFAST:
6640 				src = ZPROP_SRC_LOCAL;
6641 				strval = NULL;
6642 
6643 				err = zap_lookup(mos, objid, nvpair_name(elem),
6644 				    sizeof (uint64_t), 1, &intval);
6645 				if (err == ENOENT) {
6646 					intval = vdev_prop_default_numeric(
6647 					    prop);
6648 					err = 0;
6649 				} else if (err) {
6650 					break;
6651 				}
6652 				if (intval == vdev_prop_default_numeric(prop))
6653 					src = ZPROP_SRC_DEFAULT;
6654 
6655 				vdev_prop_add_list(outnvl, propname, strval,
6656 				    intval, src);
6657 				break;
6658 			case VDEV_PROP_AUTOSIT:
6659 				/* Only raidz vdevs cannot have this property */
6660 				if (vd->vdev_ops != &vdev_raidz_ops &&
6661 				    vd->vdev_ops != &vdev_draid_ops) {
6662 					src = ZPROP_SRC_NONE;
6663 					intval = ZPROP_BOOLEAN_NA;
6664 				} else {
6665 					err = vdev_prop_get_int(vd, prop,
6666 					    &intval);
6667 					if (err && err != ENOENT)
6668 						break;
6669 
6670 					if (intval ==
6671 					    vdev_prop_default_numeric(prop))
6672 						src = ZPROP_SRC_DEFAULT;
6673 					else
6674 						src = ZPROP_SRC_LOCAL;
6675 				}
6676 
6677 				vdev_prop_add_list(outnvl, propname, NULL,
6678 				    intval, src);
6679 				break;
6680 
6681 			case VDEV_PROP_SLOW_IO_EVENTS:
6682 				err = vdev_prop_get_bool(vd, prop, &boolval);
6683 				if (err && err != ENOENT)
6684 					break;
6685 
6686 				src = ZPROP_SRC_LOCAL;
6687 				if (boolval == vdev_prop_default_numeric(prop))
6688 					src = ZPROP_SRC_DEFAULT;
6689 
6690 				vdev_prop_add_list(outnvl, propname, NULL,
6691 				    boolval, src);
6692 				break;
6693 			case VDEV_PROP_CHECKSUM_N:
6694 			case VDEV_PROP_CHECKSUM_T:
6695 			case VDEV_PROP_IO_N:
6696 			case VDEV_PROP_IO_T:
6697 			case VDEV_PROP_SLOW_IO_N:
6698 			case VDEV_PROP_SLOW_IO_T:
6699 			case VDEV_PROP_SCHEDULER:
6700 				err = vdev_prop_get_int(vd, prop, &intval);
6701 				if (err && err != ENOENT)
6702 					break;
6703 
6704 				if (intval == vdev_prop_default_numeric(prop))
6705 					src = ZPROP_SRC_DEFAULT;
6706 				else
6707 					src = ZPROP_SRC_LOCAL;
6708 
6709 				vdev_prop_add_list(outnvl, propname, NULL,
6710 				    intval, src);
6711 				break;
6712 			/* Text Properties */
6713 			case VDEV_PROP_COMMENT:
6714 				/* Exists in the ZAP below */
6715 				/* FALLTHRU */
6716 			case VDEV_PROP_USERPROP:
6717 				/* User Properites */
6718 				src = ZPROP_SRC_LOCAL;
6719 
6720 				err = zap_length(mos, objid, nvpair_name(elem),
6721 				    &integer_size, &num_integers);
6722 				if (err)
6723 					break;
6724 
6725 				switch (integer_size) {
6726 				case 8:
6727 					/* User properties cannot be integers */
6728 					err = EINVAL;
6729 					break;
6730 				case 1:
6731 					/* string property */
6732 					strval = kmem_alloc(num_integers,
6733 					    KM_SLEEP);
6734 					err = zap_lookup(mos, objid,
6735 					    nvpair_name(elem), 1,
6736 					    num_integers, strval);
6737 					if (err) {
6738 						kmem_free(strval,
6739 						    num_integers);
6740 						break;
6741 					}
6742 					vdev_prop_add_list(outnvl, propname,
6743 					    strval, 0, src);
6744 					kmem_free(strval, num_integers);
6745 					break;
6746 				}
6747 				break;
6748 			default:
6749 				err = ENOENT;
6750 				break;
6751 			}
6752 			if (err)
6753 				break;
6754 		}
6755 	} else {
6756 		/*
6757 		 * Get all properties from the MOS vdev property object.
6758 		 */
6759 		zap_cursor_t zc;
6760 		zap_attribute_t *za = zap_attribute_alloc();
6761 		for (zap_cursor_init(&zc, mos, objid);
6762 		    (err = zap_cursor_retrieve(&zc, za)) == 0;
6763 		    zap_cursor_advance(&zc)) {
6764 			intval = 0;
6765 			strval = NULL;
6766 			zprop_source_t src = ZPROP_SRC_DEFAULT;
6767 			propname = za->za_name;
6768 
6769 			switch (za->za_integer_length) {
6770 			case 8:
6771 				/* We do not allow integer user properties */
6772 				/* This is likely an internal value */
6773 				break;
6774 			case 1:
6775 				/* string property */
6776 				strval = kmem_alloc(za->za_num_integers,
6777 				    KM_SLEEP);
6778 				err = zap_lookup(mos, objid, za->za_name, 1,
6779 				    za->za_num_integers, strval);
6780 				if (err) {
6781 					kmem_free(strval, za->za_num_integers);
6782 					break;
6783 				}
6784 				vdev_prop_add_list(outnvl, propname, strval, 0,
6785 				    src);
6786 				kmem_free(strval, za->za_num_integers);
6787 				break;
6788 
6789 			default:
6790 				break;
6791 			}
6792 		}
6793 		zap_cursor_fini(&zc);
6794 		zap_attribute_free(za);
6795 	}
6796 
6797 	mutex_exit(&spa->spa_props_lock);
6798 	if (err && err != ENOENT) {
6799 		return (err);
6800 	}
6801 
6802 	return (0);
6803 }
6804 
6805 EXPORT_SYMBOL(vdev_fault);
6806 EXPORT_SYMBOL(vdev_degrade);
6807 EXPORT_SYMBOL(vdev_online);
6808 EXPORT_SYMBOL(vdev_offline);
6809 EXPORT_SYMBOL(vdev_clear);
6810 
6811 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, default_ms_count, UINT, ZMOD_RW,
6812 	"Target number of metaslabs per top-level vdev");
6813 
6814 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, default_ms_shift, UINT, ZMOD_RW,
6815 	"Default lower limit for metaslab size");
6816 
6817 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, max_ms_shift, UINT, ZMOD_RW,
6818 	"Default upper limit for metaslab size");
6819 
6820 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, min_ms_count, UINT, ZMOD_RW,
6821 	"Minimum number of metaslabs per top-level vdev");
6822 
6823 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, ms_count_limit, UINT, ZMOD_RW,
6824 	"Practical upper limit of total metaslabs per top-level vdev");
6825 
6826 ZFS_MODULE_PARAM(zfs, zfs_, slow_io_events_per_second, UINT, ZMOD_RW,
6827 	"Rate limit slow IO (delay) events to this many per second");
6828 
6829 ZFS_MODULE_PARAM(zfs, zfs_, deadman_events_per_second, UINT, ZMOD_RW,
6830 	"Rate limit hung IO (deadman) events to this many per second");
6831 
6832 ZFS_MODULE_PARAM(zfs, zfs_, dio_write_verify_events_per_second, UINT, ZMOD_RW,
6833 	"Rate Direct I/O write verify events to this many per second");
6834 
6835 ZFS_MODULE_PARAM(zfs_vdev, zfs_vdev_, direct_write_verify, UINT, ZMOD_RW,
6836 	"Direct I/O writes will perform for checksum verification before "
6837 	"commiting write");
6838 
6839 ZFS_MODULE_PARAM(zfs, zfs_, checksum_events_per_second, UINT, ZMOD_RW,
6840 	"Rate limit checksum events to this many checksum errors per second "
6841 	"(do not set below ZED threshold).");
6842 
6843 ZFS_MODULE_PARAM(zfs, zfs_, scan_ignore_errors, INT, ZMOD_RW,
6844 	"Ignore errors during resilver/scrub");
6845 
6846 ZFS_MODULE_PARAM(zfs_vdev, vdev_, validate_skip, INT, ZMOD_RW,
6847 	"Bypass vdev_validate()");
6848 
6849 ZFS_MODULE_PARAM(zfs, zfs_, nocacheflush, INT, ZMOD_RW,
6850 	"Disable cache flushes");
6851 
6852 ZFS_MODULE_PARAM(zfs, zfs_, embedded_slog_min_ms, UINT, ZMOD_RW,
6853 	"Minimum number of metaslabs required to dedicate one for log blocks");
6854 
6855 ZFS_MODULE_PARAM_CALL(zfs_vdev, zfs_vdev_, min_auto_ashift,
6856 	param_set_min_auto_ashift, param_get_uint, ZMOD_RW,
6857 	"Minimum ashift used when creating new top-level vdevs");
6858 
6859 ZFS_MODULE_PARAM_CALL(zfs_vdev, zfs_vdev_, max_auto_ashift,
6860 	param_set_max_auto_ashift, param_get_uint, ZMOD_RW,
6861 	"Maximum ashift used when optimizing for logical -> physical sector "
6862 	"size on new top-level vdevs");
6863 
6864 ZFS_MODULE_PARAM_CALL(zfs_vdev, zfs_vdev_, raidz_impl,
6865 		param_set_raidz_impl, param_get_raidz_impl, ZMOD_RW,
6866 		"RAIDZ implementation");
6867