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