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