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