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