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