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