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 http://www.opensolaris.org/os/licensing.
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, 2018 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 2019 Joyent, Inc.
29 * Copyright (c) 2017, Intel Corporation.
30 */
31
32#include <sys/zfs_context.h>
33#include <sys/fm/fs/zfs.h>
34#include <sys/spa.h>
35#include <sys/spa_impl.h>
36#include <sys/bpobj.h>
37#include <sys/dmu.h>
38#include <sys/dmu_tx.h>
39#include <sys/dsl_dir.h>
40#include <sys/vdev_impl.h>
41#include <sys/uberblock_impl.h>
42#include <sys/metaslab.h>
43#include <sys/metaslab_impl.h>
44#include <sys/space_map.h>
45#include <sys/space_reftree.h>
46#include <sys/zio.h>
47#include <sys/zap.h>
48#include <sys/fs/zfs.h>
49#include <sys/arc.h>
50#include <sys/zil.h>
51#include <sys/dsl_scan.h>
52#include <sys/abd.h>
53#include <sys/vdev_initialize.h>
54#include <sys/vdev_trim.h>
55
56/*
57 * Virtual device management.
58 */
59
60static vdev_ops_t *vdev_ops_table[] = {
61	&vdev_root_ops,
62	&vdev_raidz_ops,
63	&vdev_mirror_ops,
64	&vdev_replacing_ops,
65	&vdev_spare_ops,
66	&vdev_disk_ops,
67	&vdev_file_ops,
68	&vdev_missing_ops,
69	&vdev_hole_ops,
70	&vdev_indirect_ops,
71	NULL
72};
73
74/* maximum scrub/resilver I/O queue per leaf vdev */
75int zfs_scrub_limit = 10;
76
77/* default target for number of metaslabs per top-level vdev */
78int zfs_vdev_default_ms_count = 200;
79
80/* minimum number of metaslabs per top-level vdev */
81int zfs_vdev_min_ms_count = 16;
82
83/* practical upper limit of total metaslabs per top-level vdev */
84int zfs_vdev_ms_count_limit = 1ULL << 17;
85
86/* lower limit for metaslab size (512M) */
87int zfs_vdev_default_ms_shift = 29;
88
89/* upper limit for metaslab size (16G) */
90int zfs_vdev_max_ms_shift = 34;
91
92boolean_t vdev_validate_skip = B_FALSE;
93
94/*
95 * Since the DTL space map of a vdev is not expected to have a lot of
96 * entries, we default its block size to 4K.
97 */
98int zfs_vdev_dtl_sm_blksz = (1 << 12);
99
100/*
101 * vdev-wide space maps that have lots of entries written to them at
102 * the end of each transaction can benefit from a higher I/O bandwidth
103 * (e.g. vdev_obsolete_sm), thus we default their block size to 128K.
104 */
105int zfs_vdev_standard_sm_blksz = (1 << 17);
106
107int zfs_ashift_min;
108
109/*PRINTFLIKE2*/
110void
111vdev_dbgmsg(vdev_t *vd, const char *fmt, ...)
112{
113	va_list adx;
114	char buf[256];
115
116	va_start(adx, fmt);
117	(void) vsnprintf(buf, sizeof (buf), fmt, adx);
118	va_end(adx);
119
120	if (vd->vdev_path != NULL) {
121		zfs_dbgmsg("%s vdev '%s': %s", vd->vdev_ops->vdev_op_type,
122		    vd->vdev_path, buf);
123	} else {
124		zfs_dbgmsg("%s-%llu vdev (guid %llu): %s",
125		    vd->vdev_ops->vdev_op_type,
126		    (u_longlong_t)vd->vdev_id,
127		    (u_longlong_t)vd->vdev_guid, buf);
128	}
129}
130
131void
132vdev_dbgmsg_print_tree(vdev_t *vd, int indent)
133{
134	char state[20];
135
136	if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops) {
137		zfs_dbgmsg("%*svdev %u: %s", indent, "", vd->vdev_id,
138		    vd->vdev_ops->vdev_op_type);
139		return;
140	}
141
142	switch (vd->vdev_state) {
143	case VDEV_STATE_UNKNOWN:
144		(void) snprintf(state, sizeof (state), "unknown");
145		break;
146	case VDEV_STATE_CLOSED:
147		(void) snprintf(state, sizeof (state), "closed");
148		break;
149	case VDEV_STATE_OFFLINE:
150		(void) snprintf(state, sizeof (state), "offline");
151		break;
152	case VDEV_STATE_REMOVED:
153		(void) snprintf(state, sizeof (state), "removed");
154		break;
155	case VDEV_STATE_CANT_OPEN:
156		(void) snprintf(state, sizeof (state), "can't open");
157		break;
158	case VDEV_STATE_FAULTED:
159		(void) snprintf(state, sizeof (state), "faulted");
160		break;
161	case VDEV_STATE_DEGRADED:
162		(void) snprintf(state, sizeof (state), "degraded");
163		break;
164	case VDEV_STATE_HEALTHY:
165		(void) snprintf(state, sizeof (state), "healthy");
166		break;
167	default:
168		(void) snprintf(state, sizeof (state), "<state %u>",
169		    (uint_t)vd->vdev_state);
170	}
171
172	zfs_dbgmsg("%*svdev %u: %s%s, guid: %llu, path: %s, %s", indent,
173	    "", (int)vd->vdev_id, vd->vdev_ops->vdev_op_type,
174	    vd->vdev_islog ? " (log)" : "",
175	    (u_longlong_t)vd->vdev_guid,
176	    vd->vdev_path ? vd->vdev_path : "N/A", state);
177
178	for (uint64_t i = 0; i < vd->vdev_children; i++)
179		vdev_dbgmsg_print_tree(vd->vdev_child[i], indent + 2);
180}
181
182/*
183 * Given a vdev type, return the appropriate ops vector.
184 */
185static vdev_ops_t *
186vdev_getops(const char *type)
187{
188	vdev_ops_t *ops, **opspp;
189
190	for (opspp = vdev_ops_table; (ops = *opspp) != NULL; opspp++)
191		if (strcmp(ops->vdev_op_type, type) == 0)
192			break;
193
194	return (ops);
195}
196
197/*
198 * Derive the enumerated alloction bias from string input.
199 * String origin is either the per-vdev zap or zpool(1M).
200 */
201static vdev_alloc_bias_t
202vdev_derive_alloc_bias(const char *bias)
203{
204	vdev_alloc_bias_t alloc_bias = VDEV_BIAS_NONE;
205
206	if (strcmp(bias, VDEV_ALLOC_BIAS_LOG) == 0)
207		alloc_bias = VDEV_BIAS_LOG;
208	else if (strcmp(bias, VDEV_ALLOC_BIAS_SPECIAL) == 0)
209		alloc_bias = VDEV_BIAS_SPECIAL;
210	else if (strcmp(bias, VDEV_ALLOC_BIAS_DEDUP) == 0)
211		alloc_bias = VDEV_BIAS_DEDUP;
212
213	return (alloc_bias);
214}
215
216/* ARGSUSED */
217void
218vdev_default_xlate(vdev_t *vd, const range_seg_t *in, range_seg_t *res)
219{
220	res->rs_start = in->rs_start;
221	res->rs_end = in->rs_end;
222}
223
224/*
225 * Default asize function: return the MAX of psize with the asize of
226 * all children.  This is what's used by anything other than RAID-Z.
227 */
228uint64_t
229vdev_default_asize(vdev_t *vd, uint64_t psize)
230{
231	uint64_t asize = P2ROUNDUP(psize, 1ULL << vd->vdev_top->vdev_ashift);
232	uint64_t csize;
233
234	for (int c = 0; c < vd->vdev_children; c++) {
235		csize = vdev_psize_to_asize(vd->vdev_child[c], psize);
236		asize = MAX(asize, csize);
237	}
238
239	return (asize);
240}
241
242/*
243 * Get the minimum allocatable size. We define the allocatable size as
244 * the vdev's asize rounded to the nearest metaslab. This allows us to
245 * replace or attach devices which don't have the same physical size but
246 * can still satisfy the same number of allocations.
247 */
248uint64_t
249vdev_get_min_asize(vdev_t *vd)
250{
251	vdev_t *pvd = vd->vdev_parent;
252
253	/*
254	 * If our parent is NULL (inactive spare or cache) or is the root,
255	 * just return our own asize.
256	 */
257	if (pvd == NULL)
258		return (vd->vdev_asize);
259
260	/*
261	 * The top-level vdev just returns the allocatable size rounded
262	 * to the nearest metaslab.
263	 */
264	if (vd == vd->vdev_top)
265		return (P2ALIGN(vd->vdev_asize, 1ULL << vd->vdev_ms_shift));
266
267	/*
268	 * The allocatable space for a raidz vdev is N * sizeof(smallest child),
269	 * so each child must provide at least 1/Nth of its asize.
270	 */
271	if (pvd->vdev_ops == &vdev_raidz_ops)
272		return ((pvd->vdev_min_asize + pvd->vdev_children - 1) /
273		    pvd->vdev_children);
274
275	return (pvd->vdev_min_asize);
276}
277
278void
279vdev_set_min_asize(vdev_t *vd)
280{
281	vd->vdev_min_asize = vdev_get_min_asize(vd);
282
283	for (int c = 0; c < vd->vdev_children; c++)
284		vdev_set_min_asize(vd->vdev_child[c]);
285}
286
287vdev_t *
288vdev_lookup_top(spa_t *spa, uint64_t vdev)
289{
290	vdev_t *rvd = spa->spa_root_vdev;
291
292	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
293
294	if (vdev < rvd->vdev_children) {
295		ASSERT(rvd->vdev_child[vdev] != NULL);
296		return (rvd->vdev_child[vdev]);
297	}
298
299	return (NULL);
300}
301
302vdev_t *
303vdev_lookup_by_guid(vdev_t *vd, uint64_t guid)
304{
305	vdev_t *mvd;
306
307	if (vd->vdev_guid == guid)
308		return (vd);
309
310	for (int c = 0; c < vd->vdev_children; c++)
311		if ((mvd = vdev_lookup_by_guid(vd->vdev_child[c], guid)) !=
312		    NULL)
313			return (mvd);
314
315	return (NULL);
316}
317
318static int
319vdev_count_leaves_impl(vdev_t *vd)
320{
321	int n = 0;
322
323	if (vd->vdev_ops->vdev_op_leaf)
324		return (1);
325
326	for (int c = 0; c < vd->vdev_children; c++)
327		n += vdev_count_leaves_impl(vd->vdev_child[c]);
328
329	return (n);
330}
331
332int
333vdev_count_leaves(spa_t *spa)
334{
335	return (vdev_count_leaves_impl(spa->spa_root_vdev));
336}
337
338void
339vdev_add_child(vdev_t *pvd, vdev_t *cvd)
340{
341	size_t oldsize, newsize;
342	uint64_t id = cvd->vdev_id;
343	vdev_t **newchild;
344	spa_t *spa = cvd->vdev_spa;
345
346	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
347	ASSERT(cvd->vdev_parent == NULL);
348
349	cvd->vdev_parent = pvd;
350
351	if (pvd == NULL)
352		return;
353
354	ASSERT(id >= pvd->vdev_children || pvd->vdev_child[id] == NULL);
355
356	oldsize = pvd->vdev_children * sizeof (vdev_t *);
357	pvd->vdev_children = MAX(pvd->vdev_children, id + 1);
358	newsize = pvd->vdev_children * sizeof (vdev_t *);
359
360	newchild = kmem_zalloc(newsize, KM_SLEEP);
361	if (pvd->vdev_child != NULL) {
362		bcopy(pvd->vdev_child, newchild, oldsize);
363		kmem_free(pvd->vdev_child, oldsize);
364	}
365
366	pvd->vdev_child = newchild;
367	pvd->vdev_child[id] = cvd;
368
369	cvd->vdev_top = (pvd->vdev_top ? pvd->vdev_top: cvd);
370	ASSERT(cvd->vdev_top->vdev_parent->vdev_parent == NULL);
371
372	/*
373	 * Walk up all ancestors to update guid sum.
374	 */
375	for (; pvd != NULL; pvd = pvd->vdev_parent)
376		pvd->vdev_guid_sum += cvd->vdev_guid_sum;
377
378	if (cvd->vdev_ops->vdev_op_leaf) {
379		list_insert_head(&cvd->vdev_spa->spa_leaf_list, cvd);
380		cvd->vdev_spa->spa_leaf_list_gen++;
381	}
382}
383
384void
385vdev_remove_child(vdev_t *pvd, vdev_t *cvd)
386{
387	int c;
388	uint_t id = cvd->vdev_id;
389
390	ASSERT(cvd->vdev_parent == pvd);
391
392	if (pvd == NULL)
393		return;
394
395	ASSERT(id < pvd->vdev_children);
396	ASSERT(pvd->vdev_child[id] == cvd);
397
398	pvd->vdev_child[id] = NULL;
399	cvd->vdev_parent = NULL;
400
401	for (c = 0; c < pvd->vdev_children; c++)
402		if (pvd->vdev_child[c])
403			break;
404
405	if (c == pvd->vdev_children) {
406		kmem_free(pvd->vdev_child, c * sizeof (vdev_t *));
407		pvd->vdev_child = NULL;
408		pvd->vdev_children = 0;
409	}
410
411	if (cvd->vdev_ops->vdev_op_leaf) {
412		spa_t *spa = cvd->vdev_spa;
413		list_remove(&spa->spa_leaf_list, cvd);
414		spa->spa_leaf_list_gen++;
415	}
416
417	/*
418	 * Walk up all ancestors to update guid sum.
419	 */
420	for (; pvd != NULL; pvd = pvd->vdev_parent)
421		pvd->vdev_guid_sum -= cvd->vdev_guid_sum;
422}
423
424/*
425 * Remove any holes in the child array.
426 */
427void
428vdev_compact_children(vdev_t *pvd)
429{
430	vdev_t **newchild, *cvd;
431	int oldc = pvd->vdev_children;
432	int newc;
433
434	ASSERT(spa_config_held(pvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
435
436	for (int c = newc = 0; c < oldc; c++)
437		if (pvd->vdev_child[c])
438			newc++;
439
440	newchild = kmem_alloc(newc * sizeof (vdev_t *), KM_SLEEP);
441
442	for (int c = newc = 0; c < oldc; c++) {
443		if ((cvd = pvd->vdev_child[c]) != NULL) {
444			newchild[newc] = cvd;
445			cvd->vdev_id = newc++;
446		}
447	}
448
449	kmem_free(pvd->vdev_child, oldc * sizeof (vdev_t *));
450	pvd->vdev_child = newchild;
451	pvd->vdev_children = newc;
452}
453
454/*
455 * Allocate and minimally initialize a vdev_t.
456 */
457vdev_t *
458vdev_alloc_common(spa_t *spa, uint_t id, uint64_t guid, vdev_ops_t *ops)
459{
460	vdev_t *vd;
461	vdev_indirect_config_t *vic;
462
463	vd = kmem_zalloc(sizeof (vdev_t), KM_SLEEP);
464	vic = &vd->vdev_indirect_config;
465
466	if (spa->spa_root_vdev == NULL) {
467		ASSERT(ops == &vdev_root_ops);
468		spa->spa_root_vdev = vd;
469		spa->spa_load_guid = spa_generate_guid(NULL);
470	}
471
472	if (guid == 0 && ops != &vdev_hole_ops) {
473		if (spa->spa_root_vdev == vd) {
474			/*
475			 * The root vdev's guid will also be the pool guid,
476			 * which must be unique among all pools.
477			 */
478			guid = spa_generate_guid(NULL);
479		} else {
480			/*
481			 * Any other vdev's guid must be unique within the pool.
482			 */
483			guid = spa_generate_guid(spa);
484		}
485		ASSERT(!spa_guid_exists(spa_guid(spa), guid));
486	}
487
488	vd->vdev_spa = spa;
489	vd->vdev_id = id;
490	vd->vdev_guid = guid;
491	vd->vdev_guid_sum = guid;
492	vd->vdev_ops = ops;
493	vd->vdev_state = VDEV_STATE_CLOSED;
494	vd->vdev_ishole = (ops == &vdev_hole_ops);
495	vic->vic_prev_indirect_vdev = UINT64_MAX;
496
497	rw_init(&vd->vdev_indirect_rwlock, NULL, RW_DEFAULT, NULL);
498	mutex_init(&vd->vdev_obsolete_lock, NULL, MUTEX_DEFAULT, NULL);
499	vd->vdev_obsolete_segments = range_tree_create(NULL, NULL);
500
501	list_link_init(&vd->vdev_initialize_node);
502	list_link_init(&vd->vdev_leaf_node);
503	list_link_init(&vd->vdev_trim_node);
504	mutex_init(&vd->vdev_dtl_lock, NULL, MUTEX_DEFAULT, NULL);
505	mutex_init(&vd->vdev_stat_lock, NULL, MUTEX_DEFAULT, NULL);
506	mutex_init(&vd->vdev_probe_lock, NULL, MUTEX_DEFAULT, NULL);
507	mutex_init(&vd->vdev_scan_io_queue_lock, NULL, MUTEX_DEFAULT, NULL);
508	mutex_init(&vd->vdev_initialize_lock, NULL, MUTEX_DEFAULT, NULL);
509	mutex_init(&vd->vdev_initialize_io_lock, NULL, MUTEX_DEFAULT, NULL);
510	cv_init(&vd->vdev_initialize_cv, NULL, CV_DEFAULT, NULL);
511	cv_init(&vd->vdev_initialize_io_cv, NULL, CV_DEFAULT, NULL);
512	mutex_init(&vd->vdev_trim_lock, NULL, MUTEX_DEFAULT, NULL);
513	mutex_init(&vd->vdev_autotrim_lock, NULL, MUTEX_DEFAULT, NULL);
514	mutex_init(&vd->vdev_trim_io_lock, NULL, MUTEX_DEFAULT, NULL);
515	cv_init(&vd->vdev_trim_cv, NULL, CV_DEFAULT, NULL);
516	cv_init(&vd->vdev_autotrim_cv, NULL, CV_DEFAULT, NULL);
517	cv_init(&vd->vdev_trim_io_cv, NULL, CV_DEFAULT, NULL);
518
519	for (int t = 0; t < DTL_TYPES; t++) {
520		vd->vdev_dtl[t] = range_tree_create(NULL, NULL);
521	}
522	txg_list_create(&vd->vdev_ms_list, spa,
523	    offsetof(struct metaslab, ms_txg_node));
524	txg_list_create(&vd->vdev_dtl_list, spa,
525	    offsetof(struct vdev, vdev_dtl_node));
526	vd->vdev_stat.vs_timestamp = gethrtime();
527	vdev_queue_init(vd);
528	vdev_cache_init(vd);
529
530	return (vd);
531}
532
533/*
534 * Allocate a new vdev.  The 'alloctype' is used to control whether we are
535 * creating a new vdev or loading an existing one - the behavior is slightly
536 * different for each case.
537 */
538int
539vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
540    int alloctype)
541{
542	vdev_ops_t *ops;
543	char *type;
544	uint64_t guid = 0, islog, nparity;
545	vdev_t *vd;
546	vdev_indirect_config_t *vic;
547	vdev_alloc_bias_t alloc_bias = VDEV_BIAS_NONE;
548	boolean_t top_level = (parent && !parent->vdev_parent);
549
550	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
551
552	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
553		return (SET_ERROR(EINVAL));
554
555	if ((ops = vdev_getops(type)) == NULL)
556		return (SET_ERROR(EINVAL));
557
558	/*
559	 * If this is a load, get the vdev guid from the nvlist.
560	 * Otherwise, vdev_alloc_common() will generate one for us.
561	 */
562	if (alloctype == VDEV_ALLOC_LOAD) {
563		uint64_t label_id;
564
565		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID, &label_id) ||
566		    label_id != id)
567			return (SET_ERROR(EINVAL));
568
569		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
570			return (SET_ERROR(EINVAL));
571	} else if (alloctype == VDEV_ALLOC_SPARE) {
572		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
573			return (SET_ERROR(EINVAL));
574	} else if (alloctype == VDEV_ALLOC_L2CACHE) {
575		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
576			return (SET_ERROR(EINVAL));
577	} else if (alloctype == VDEV_ALLOC_ROOTPOOL) {
578		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
579			return (SET_ERROR(EINVAL));
580	}
581
582	/*
583	 * The first allocated vdev must be of type 'root'.
584	 */
585	if (ops != &vdev_root_ops && spa->spa_root_vdev == NULL)
586		return (SET_ERROR(EINVAL));
587
588	/*
589	 * Determine whether we're a log vdev.
590	 */
591	islog = 0;
592	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &islog);
593	if (islog && spa_version(spa) < SPA_VERSION_SLOGS)
594		return (SET_ERROR(ENOTSUP));
595
596	if (ops == &vdev_hole_ops && spa_version(spa) < SPA_VERSION_HOLES)
597		return (SET_ERROR(ENOTSUP));
598
599	/*
600	 * Set the nparity property for RAID-Z vdevs.
601	 */
602	nparity = -1ULL;
603	if (ops == &vdev_raidz_ops) {
604		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
605		    &nparity) == 0) {
606			if (nparity == 0 || nparity > VDEV_RAIDZ_MAXPARITY)
607				return (SET_ERROR(EINVAL));
608			/*
609			 * Previous versions could only support 1 or 2 parity
610			 * device.
611			 */
612			if (nparity > 1 &&
613			    spa_version(spa) < SPA_VERSION_RAIDZ2)
614				return (SET_ERROR(ENOTSUP));
615			if (nparity > 2 &&
616			    spa_version(spa) < SPA_VERSION_RAIDZ3)
617				return (SET_ERROR(ENOTSUP));
618		} else {
619			/*
620			 * We require the parity to be specified for SPAs that
621			 * support multiple parity levels.
622			 */
623			if (spa_version(spa) >= SPA_VERSION_RAIDZ2)
624				return (SET_ERROR(EINVAL));
625			/*
626			 * Otherwise, we default to 1 parity device for RAID-Z.
627			 */
628			nparity = 1;
629		}
630	} else {
631		nparity = 0;
632	}
633	ASSERT(nparity != -1ULL);
634
635	/*
636	 * If creating a top-level vdev, check for allocation classes input
637	 */
638	if (top_level && alloctype == VDEV_ALLOC_ADD) {
639		char *bias;
640
641		if (nvlist_lookup_string(nv, ZPOOL_CONFIG_ALLOCATION_BIAS,
642		    &bias) == 0) {
643			alloc_bias = vdev_derive_alloc_bias(bias);
644
645			/* spa_vdev_add() expects feature to be enabled */
646			if (alloc_bias != VDEV_BIAS_LOG &&
647			    spa->spa_load_state != SPA_LOAD_CREATE &&
648			    !spa_feature_is_enabled(spa,
649			    SPA_FEATURE_ALLOCATION_CLASSES)) {
650				return (SET_ERROR(ENOTSUP));
651			}
652		}
653	}
654
655	vd = vdev_alloc_common(spa, id, guid, ops);
656	vic = &vd->vdev_indirect_config;
657
658	vd->vdev_islog = islog;
659	vd->vdev_nparity = nparity;
660	if (top_level && alloc_bias != VDEV_BIAS_NONE)
661		vd->vdev_alloc_bias = alloc_bias;
662
663	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &vd->vdev_path) == 0)
664		vd->vdev_path = spa_strdup(vd->vdev_path);
665	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &vd->vdev_devid) == 0)
666		vd->vdev_devid = spa_strdup(vd->vdev_devid);
667	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PHYS_PATH,
668	    &vd->vdev_physpath) == 0)
669		vd->vdev_physpath = spa_strdup(vd->vdev_physpath);
670	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_FRU, &vd->vdev_fru) == 0)
671		vd->vdev_fru = spa_strdup(vd->vdev_fru);
672
673	/*
674	 * Set the whole_disk property.  If it's not specified, leave the value
675	 * as -1.
676	 */
677	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
678	    &vd->vdev_wholedisk) != 0)
679		vd->vdev_wholedisk = -1ULL;
680
681	ASSERT0(vic->vic_mapping_object);
682	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_INDIRECT_OBJECT,
683	    &vic->vic_mapping_object);
684	ASSERT0(vic->vic_births_object);
685	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_INDIRECT_BIRTHS,
686	    &vic->vic_births_object);
687	ASSERT3U(vic->vic_prev_indirect_vdev, ==, UINT64_MAX);
688	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_PREV_INDIRECT_VDEV,
689	    &vic->vic_prev_indirect_vdev);
690
691	/*
692	 * Look for the 'not present' flag.  This will only be set if the device
693	 * was not present at the time of import.
694	 */
695	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
696	    &vd->vdev_not_present);
697
698	/*
699	 * Get the alignment requirement.
700	 */
701	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT, &vd->vdev_ashift);
702
703	/*
704	 * Retrieve the vdev creation time.
705	 */
706	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_CREATE_TXG,
707	    &vd->vdev_crtxg);
708
709	/*
710	 * If we're a top-level vdev, try to load the allocation parameters.
711	 */
712	if (top_level &&
713	    (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
714		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
715		    &vd->vdev_ms_array);
716		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
717		    &vd->vdev_ms_shift);
718		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASIZE,
719		    &vd->vdev_asize);
720		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVING,
721		    &vd->vdev_removing);
722		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_VDEV_TOP_ZAP,
723		    &vd->vdev_top_zap);
724	} else {
725		ASSERT0(vd->vdev_top_zap);
726	}
727
728	if (top_level && alloctype != VDEV_ALLOC_ATTACH) {
729		ASSERT(alloctype == VDEV_ALLOC_LOAD ||
730		    alloctype == VDEV_ALLOC_ADD ||
731		    alloctype == VDEV_ALLOC_SPLIT ||
732		    alloctype == VDEV_ALLOC_ROOTPOOL);
733		/* Note: metaslab_group_create() is now deferred */
734	}
735
736	if (vd->vdev_ops->vdev_op_leaf &&
737	    (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
738		(void) nvlist_lookup_uint64(nv,
739		    ZPOOL_CONFIG_VDEV_LEAF_ZAP, &vd->vdev_leaf_zap);
740	} else {
741		ASSERT0(vd->vdev_leaf_zap);
742	}
743
744	/*
745	 * If we're a leaf vdev, try to load the DTL object and other state.
746	 */
747
748	if (vd->vdev_ops->vdev_op_leaf &&
749	    (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_L2CACHE ||
750	    alloctype == VDEV_ALLOC_ROOTPOOL)) {
751		if (alloctype == VDEV_ALLOC_LOAD) {
752			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DTL,
753			    &vd->vdev_dtl_object);
754			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_UNSPARE,
755			    &vd->vdev_unspare);
756		}
757
758		if (alloctype == VDEV_ALLOC_ROOTPOOL) {
759			uint64_t spare = 0;
760
761			if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
762			    &spare) == 0 && spare)
763				spa_spare_add(vd);
764		}
765
766		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE,
767		    &vd->vdev_offline);
768
769		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_RESILVER_TXG,
770		    &vd->vdev_resilver_txg);
771
772		if (nvlist_exists(nv, ZPOOL_CONFIG_RESILVER_DEFER))
773			vdev_set_deferred_resilver(spa, vd);
774
775		/*
776		 * When importing a pool, we want to ignore the persistent fault
777		 * state, as the diagnosis made on another system may not be
778		 * valid in the current context.  Local vdevs will
779		 * remain in the faulted state.
780		 */
781		if (spa_load_state(spa) == SPA_LOAD_OPEN) {
782			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED,
783			    &vd->vdev_faulted);
784			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DEGRADED,
785			    &vd->vdev_degraded);
786			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED,
787			    &vd->vdev_removed);
788
789			if (vd->vdev_faulted || vd->vdev_degraded) {
790				char *aux;
791
792				vd->vdev_label_aux =
793				    VDEV_AUX_ERR_EXCEEDED;
794				if (nvlist_lookup_string(nv,
795				    ZPOOL_CONFIG_AUX_STATE, &aux) == 0 &&
796				    strcmp(aux, "external") == 0)
797					vd->vdev_label_aux = VDEV_AUX_EXTERNAL;
798			}
799		}
800	}
801
802	/*
803	 * Add ourselves to the parent's list of children.
804	 */
805	vdev_add_child(parent, vd);
806
807	*vdp = vd;
808
809	return (0);
810}
811
812void
813vdev_free(vdev_t *vd)
814{
815	spa_t *spa = vd->vdev_spa;
816
817	ASSERT3P(vd->vdev_initialize_thread, ==, NULL);
818	ASSERT3P(vd->vdev_trim_thread, ==, NULL);
819	ASSERT3P(vd->vdev_autotrim_thread, ==, NULL);
820
821	/*
822	 * Scan queues are normally destroyed at the end of a scan. If the
823	 * queue exists here, that implies the vdev is being removed while
824	 * the scan is still running.
825	 */
826	if (vd->vdev_scan_io_queue != NULL) {
827		mutex_enter(&vd->vdev_scan_io_queue_lock);
828		dsl_scan_io_queue_destroy(vd->vdev_scan_io_queue);
829		vd->vdev_scan_io_queue = NULL;
830		mutex_exit(&vd->vdev_scan_io_queue_lock);
831	}
832
833	/*
834	 * vdev_free() implies closing the vdev first.  This is simpler than
835	 * trying to ensure complicated semantics for all callers.
836	 */
837	vdev_close(vd);
838
839	ASSERT(!list_link_active(&vd->vdev_config_dirty_node));
840	ASSERT(!list_link_active(&vd->vdev_state_dirty_node));
841
842	/*
843	 * Free all children.
844	 */
845	for (int c = 0; c < vd->vdev_children; c++)
846		vdev_free(vd->vdev_child[c]);
847
848	ASSERT(vd->vdev_child == NULL);
849	ASSERT(vd->vdev_guid_sum == vd->vdev_guid);
850
851	/*
852	 * Discard allocation state.
853	 */
854	if (vd->vdev_mg != NULL) {
855		vdev_metaslab_fini(vd);
856		metaslab_group_destroy(vd->vdev_mg);
857		vd->vdev_mg = NULL;
858	}
859
860	ASSERT0(vd->vdev_stat.vs_space);
861	ASSERT0(vd->vdev_stat.vs_dspace);
862	ASSERT0(vd->vdev_stat.vs_alloc);
863
864	/*
865	 * Remove this vdev from its parent's child list.
866	 */
867	vdev_remove_child(vd->vdev_parent, vd);
868
869	ASSERT(vd->vdev_parent == NULL);
870	ASSERT(!list_link_active(&vd->vdev_leaf_node));
871
872	/*
873	 * Clean up vdev structure.
874	 */
875	vdev_queue_fini(vd);
876	vdev_cache_fini(vd);
877
878	if (vd->vdev_path)
879		spa_strfree(vd->vdev_path);
880	if (vd->vdev_devid)
881		spa_strfree(vd->vdev_devid);
882	if (vd->vdev_physpath)
883		spa_strfree(vd->vdev_physpath);
884	if (vd->vdev_fru)
885		spa_strfree(vd->vdev_fru);
886
887	if (vd->vdev_isspare)
888		spa_spare_remove(vd);
889	if (vd->vdev_isl2cache)
890		spa_l2cache_remove(vd);
891
892	txg_list_destroy(&vd->vdev_ms_list);
893	txg_list_destroy(&vd->vdev_dtl_list);
894
895	mutex_enter(&vd->vdev_dtl_lock);
896	space_map_close(vd->vdev_dtl_sm);
897	for (int t = 0; t < DTL_TYPES; t++) {
898		range_tree_vacate(vd->vdev_dtl[t], NULL, NULL);
899		range_tree_destroy(vd->vdev_dtl[t]);
900	}
901	mutex_exit(&vd->vdev_dtl_lock);
902
903	EQUIV(vd->vdev_indirect_births != NULL,
904	    vd->vdev_indirect_mapping != NULL);
905	if (vd->vdev_indirect_births != NULL) {
906		vdev_indirect_mapping_close(vd->vdev_indirect_mapping);
907		vdev_indirect_births_close(vd->vdev_indirect_births);
908	}
909
910	if (vd->vdev_obsolete_sm != NULL) {
911		ASSERT(vd->vdev_removing ||
912		    vd->vdev_ops == &vdev_indirect_ops);
913		space_map_close(vd->vdev_obsolete_sm);
914		vd->vdev_obsolete_sm = NULL;
915	}
916	range_tree_destroy(vd->vdev_obsolete_segments);
917	rw_destroy(&vd->vdev_indirect_rwlock);
918	mutex_destroy(&vd->vdev_obsolete_lock);
919
920	mutex_destroy(&vd->vdev_dtl_lock);
921	mutex_destroy(&vd->vdev_stat_lock);
922	mutex_destroy(&vd->vdev_probe_lock);
923	mutex_destroy(&vd->vdev_scan_io_queue_lock);
924	mutex_destroy(&vd->vdev_initialize_lock);
925	mutex_destroy(&vd->vdev_initialize_io_lock);
926	cv_destroy(&vd->vdev_initialize_io_cv);
927	cv_destroy(&vd->vdev_initialize_cv);
928	mutex_destroy(&vd->vdev_trim_lock);
929	mutex_destroy(&vd->vdev_autotrim_lock);
930	mutex_destroy(&vd->vdev_trim_io_lock);
931	cv_destroy(&vd->vdev_trim_cv);
932	cv_destroy(&vd->vdev_autotrim_cv);
933	cv_destroy(&vd->vdev_trim_io_cv);
934
935	if (vd == spa->spa_root_vdev)
936		spa->spa_root_vdev = NULL;
937
938	kmem_free(vd, sizeof (vdev_t));
939}
940
941/*
942 * Transfer top-level vdev state from svd to tvd.
943 */
944static void
945vdev_top_transfer(vdev_t *svd, vdev_t *tvd)
946{
947	spa_t *spa = svd->vdev_spa;
948	metaslab_t *msp;
949	vdev_t *vd;
950	int t;
951
952	ASSERT(tvd == tvd->vdev_top);
953
954	tvd->vdev_ms_array = svd->vdev_ms_array;
955	tvd->vdev_ms_shift = svd->vdev_ms_shift;
956	tvd->vdev_ms_count = svd->vdev_ms_count;
957	tvd->vdev_top_zap = svd->vdev_top_zap;
958
959	svd->vdev_ms_array = 0;
960	svd->vdev_ms_shift = 0;
961	svd->vdev_ms_count = 0;
962	svd->vdev_top_zap = 0;
963
964	if (tvd->vdev_mg)
965		ASSERT3P(tvd->vdev_mg, ==, svd->vdev_mg);
966	tvd->vdev_mg = svd->vdev_mg;
967	tvd->vdev_ms = svd->vdev_ms;
968
969	svd->vdev_mg = NULL;
970	svd->vdev_ms = NULL;
971
972	if (tvd->vdev_mg != NULL)
973		tvd->vdev_mg->mg_vd = tvd;
974
975	tvd->vdev_checkpoint_sm = svd->vdev_checkpoint_sm;
976	svd->vdev_checkpoint_sm = NULL;
977
978	tvd->vdev_alloc_bias = svd->vdev_alloc_bias;
979	svd->vdev_alloc_bias = VDEV_BIAS_NONE;
980
981	tvd->vdev_stat.vs_alloc = svd->vdev_stat.vs_alloc;
982	tvd->vdev_stat.vs_space = svd->vdev_stat.vs_space;
983	tvd->vdev_stat.vs_dspace = svd->vdev_stat.vs_dspace;
984
985	svd->vdev_stat.vs_alloc = 0;
986	svd->vdev_stat.vs_space = 0;
987	svd->vdev_stat.vs_dspace = 0;
988
989	/*
990	 * State which may be set on a top-level vdev that's in the
991	 * process of being removed.
992	 */
993	ASSERT0(tvd->vdev_indirect_config.vic_births_object);
994	ASSERT0(tvd->vdev_indirect_config.vic_mapping_object);
995	ASSERT3U(tvd->vdev_indirect_config.vic_prev_indirect_vdev, ==, -1ULL);
996	ASSERT3P(tvd->vdev_indirect_mapping, ==, NULL);
997	ASSERT3P(tvd->vdev_indirect_births, ==, NULL);
998	ASSERT3P(tvd->vdev_obsolete_sm, ==, NULL);
999	ASSERT0(tvd->vdev_removing);
1000	tvd->vdev_removing = svd->vdev_removing;
1001	tvd->vdev_indirect_config = svd->vdev_indirect_config;
1002	tvd->vdev_indirect_mapping = svd->vdev_indirect_mapping;
1003	tvd->vdev_indirect_births = svd->vdev_indirect_births;
1004	range_tree_swap(&svd->vdev_obsolete_segments,
1005	    &tvd->vdev_obsolete_segments);
1006	tvd->vdev_obsolete_sm = svd->vdev_obsolete_sm;
1007	svd->vdev_indirect_config.vic_mapping_object = 0;
1008	svd->vdev_indirect_config.vic_births_object = 0;
1009	svd->vdev_indirect_config.vic_prev_indirect_vdev = -1ULL;
1010	svd->vdev_indirect_mapping = NULL;
1011	svd->vdev_indirect_births = NULL;
1012	svd->vdev_obsolete_sm = NULL;
1013	svd->vdev_removing = 0;
1014
1015	for (t = 0; t < TXG_SIZE; t++) {
1016		while ((msp = txg_list_remove(&svd->vdev_ms_list, t)) != NULL)
1017			(void) txg_list_add(&tvd->vdev_ms_list, msp, t);
1018		while ((vd = txg_list_remove(&svd->vdev_dtl_list, t)) != NULL)
1019			(void) txg_list_add(&tvd->vdev_dtl_list, vd, t);
1020		if (txg_list_remove_this(&spa->spa_vdev_txg_list, svd, t))
1021			(void) txg_list_add(&spa->spa_vdev_txg_list, tvd, t);
1022	}
1023
1024	if (list_link_active(&svd->vdev_config_dirty_node)) {
1025		vdev_config_clean(svd);
1026		vdev_config_dirty(tvd);
1027	}
1028
1029	if (list_link_active(&svd->vdev_state_dirty_node)) {
1030		vdev_state_clean(svd);
1031		vdev_state_dirty(tvd);
1032	}
1033
1034	tvd->vdev_deflate_ratio = svd->vdev_deflate_ratio;
1035	svd->vdev_deflate_ratio = 0;
1036
1037	tvd->vdev_islog = svd->vdev_islog;
1038	svd->vdev_islog = 0;
1039
1040	dsl_scan_io_queue_vdev_xfer(svd, tvd);
1041}
1042
1043static void
1044vdev_top_update(vdev_t *tvd, vdev_t *vd)
1045{
1046	if (vd == NULL)
1047		return;
1048
1049	vd->vdev_top = tvd;
1050
1051	for (int c = 0; c < vd->vdev_children; c++)
1052		vdev_top_update(tvd, vd->vdev_child[c]);
1053}
1054
1055/*
1056 * Add a mirror/replacing vdev above an existing vdev.
1057 */
1058vdev_t *
1059vdev_add_parent(vdev_t *cvd, vdev_ops_t *ops)
1060{
1061	spa_t *spa = cvd->vdev_spa;
1062	vdev_t *pvd = cvd->vdev_parent;
1063	vdev_t *mvd;
1064
1065	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1066
1067	mvd = vdev_alloc_common(spa, cvd->vdev_id, 0, ops);
1068
1069	mvd->vdev_asize = cvd->vdev_asize;
1070	mvd->vdev_min_asize = cvd->vdev_min_asize;
1071	mvd->vdev_max_asize = cvd->vdev_max_asize;
1072	mvd->vdev_psize = cvd->vdev_psize;
1073	mvd->vdev_ashift = cvd->vdev_ashift;
1074	mvd->vdev_state = cvd->vdev_state;
1075	mvd->vdev_crtxg = cvd->vdev_crtxg;
1076
1077	vdev_remove_child(pvd, cvd);
1078	vdev_add_child(pvd, mvd);
1079	cvd->vdev_id = mvd->vdev_children;
1080	vdev_add_child(mvd, cvd);
1081	vdev_top_update(cvd->vdev_top, cvd->vdev_top);
1082
1083	if (mvd == mvd->vdev_top)
1084		vdev_top_transfer(cvd, mvd);
1085
1086	return (mvd);
1087}
1088
1089/*
1090 * Remove a 1-way mirror/replacing vdev from the tree.
1091 */
1092void
1093vdev_remove_parent(vdev_t *cvd)
1094{
1095	vdev_t *mvd = cvd->vdev_parent;
1096	vdev_t *pvd = mvd->vdev_parent;
1097
1098	ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1099
1100	ASSERT(mvd->vdev_children == 1);
1101	ASSERT(mvd->vdev_ops == &vdev_mirror_ops ||
1102	    mvd->vdev_ops == &vdev_replacing_ops ||
1103	    mvd->vdev_ops == &vdev_spare_ops);
1104	cvd->vdev_ashift = mvd->vdev_ashift;
1105
1106	vdev_remove_child(mvd, cvd);
1107	vdev_remove_child(pvd, mvd);
1108
1109	/*
1110	 * If cvd will replace mvd as a top-level vdev, preserve mvd's guid.
1111	 * Otherwise, we could have detached an offline device, and when we
1112	 * go to import the pool we'll think we have two top-level vdevs,
1113	 * instead of a different version of the same top-level vdev.
1114	 */
1115	if (mvd->vdev_top == mvd) {
1116		uint64_t guid_delta = mvd->vdev_guid - cvd->vdev_guid;
1117		cvd->vdev_orig_guid = cvd->vdev_guid;
1118		cvd->vdev_guid += guid_delta;
1119		cvd->vdev_guid_sum += guid_delta;
1120	}
1121	cvd->vdev_id = mvd->vdev_id;
1122	vdev_add_child(pvd, cvd);
1123	vdev_top_update(cvd->vdev_top, cvd->vdev_top);
1124
1125	if (cvd == cvd->vdev_top)
1126		vdev_top_transfer(mvd, cvd);
1127
1128	ASSERT(mvd->vdev_children == 0);
1129	vdev_free(mvd);
1130}
1131
1132static void
1133vdev_metaslab_group_create(vdev_t *vd)
1134{
1135	spa_t *spa = vd->vdev_spa;
1136
1137	/*
1138	 * metaslab_group_create was delayed until allocation bias was available
1139	 */
1140	if (vd->vdev_mg == NULL) {
1141		metaslab_class_t *mc;
1142
1143		if (vd->vdev_islog && vd->vdev_alloc_bias == VDEV_BIAS_NONE)
1144			vd->vdev_alloc_bias = VDEV_BIAS_LOG;
1145
1146		ASSERT3U(vd->vdev_islog, ==,
1147		    (vd->vdev_alloc_bias == VDEV_BIAS_LOG));
1148
1149		switch (vd->vdev_alloc_bias) {
1150		case VDEV_BIAS_LOG:
1151			mc = spa_log_class(spa);
1152			break;
1153		case VDEV_BIAS_SPECIAL:
1154			mc = spa_special_class(spa);
1155			break;
1156		case VDEV_BIAS_DEDUP:
1157			mc = spa_dedup_class(spa);
1158			break;
1159		default:
1160			mc = spa_normal_class(spa);
1161		}
1162
1163		vd->vdev_mg = metaslab_group_create(mc, vd,
1164		    spa->spa_alloc_count);
1165
1166		/*
1167		 * The spa ashift values currently only reflect the
1168		 * general vdev classes. Class destination is late
1169		 * binding so ashift checking had to wait until now
1170		 */
1171		if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
1172		    mc == spa_normal_class(spa) && vd->vdev_aux == NULL) {
1173			if (vd->vdev_ashift > spa->spa_max_ashift)
1174				spa->spa_max_ashift = vd->vdev_ashift;
1175			if (vd->vdev_ashift < spa->spa_min_ashift)
1176				spa->spa_min_ashift = vd->vdev_ashift;
1177		}
1178	}
1179}
1180
1181int
1182vdev_metaslab_init(vdev_t *vd, uint64_t txg)
1183{
1184	spa_t *spa = vd->vdev_spa;
1185	objset_t *mos = spa->spa_meta_objset;
1186	uint64_t m;
1187	uint64_t oldc = vd->vdev_ms_count;
1188	uint64_t newc = vd->vdev_asize >> vd->vdev_ms_shift;
1189	metaslab_t **mspp;
1190	int error;
1191	boolean_t expanding = (oldc != 0);
1192
1193	ASSERT(txg == 0 || spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1194
1195	/*
1196	 * This vdev is not being allocated from yet or is a hole.
1197	 */
1198	if (vd->vdev_ms_shift == 0)
1199		return (0);
1200
1201	ASSERT(!vd->vdev_ishole);
1202
1203	ASSERT(oldc <= newc);
1204
1205	mspp = kmem_zalloc(newc * sizeof (*mspp), KM_SLEEP);
1206
1207	if (expanding) {
1208		bcopy(vd->vdev_ms, mspp, oldc * sizeof (*mspp));
1209		kmem_free(vd->vdev_ms, oldc * sizeof (*mspp));
1210	}
1211
1212	vd->vdev_ms = mspp;
1213	vd->vdev_ms_count = newc;
1214	for (m = oldc; m < newc; m++) {
1215		uint64_t object = 0;
1216
1217		/*
1218		 * vdev_ms_array may be 0 if we are creating the "fake"
1219		 * metaslabs for an indirect vdev for zdb's leak detection.
1220		 * See zdb_leak_init().
1221		 */
1222		if (txg == 0 && vd->vdev_ms_array != 0) {
1223			error = dmu_read(mos, vd->vdev_ms_array,
1224			    m * sizeof (uint64_t), sizeof (uint64_t), &object,
1225			    DMU_READ_PREFETCH);
1226			if (error != 0) {
1227				vdev_dbgmsg(vd, "unable to read the metaslab "
1228				    "array [error=%d]", error);
1229				return (error);
1230			}
1231		}
1232
1233#ifndef _KERNEL
1234		/*
1235		 * To accomodate zdb_leak_init() fake indirect
1236		 * metaslabs, we allocate a metaslab group for
1237		 * indirect vdevs which normally don't have one.
1238		 */
1239		if (vd->vdev_mg == NULL) {
1240			ASSERT0(vdev_is_concrete(vd));
1241			vdev_metaslab_group_create(vd);
1242		}
1243#endif
1244		error = metaslab_init(vd->vdev_mg, m, object, txg,
1245		    &(vd->vdev_ms[m]));
1246		if (error != 0) {
1247			vdev_dbgmsg(vd, "metaslab_init failed [error=%d]",
1248			    error);
1249			return (error);
1250		}
1251	}
1252
1253	if (txg == 0)
1254		spa_config_enter(spa, SCL_ALLOC, FTAG, RW_WRITER);
1255
1256	/*
1257	 * If the vdev is being removed we don't activate
1258	 * the metaslabs since we want to ensure that no new
1259	 * allocations are performed on this device.
1260	 */
1261	if (!expanding && !vd->vdev_removing) {
1262		metaslab_group_activate(vd->vdev_mg);
1263	}
1264
1265	if (txg == 0)
1266		spa_config_exit(spa, SCL_ALLOC, FTAG);
1267
1268	/*
1269	 * Regardless whether this vdev was just added or it is being
1270	 * expanded, the metaslab count has changed. Recalculate the
1271	 * block limit.
1272	 */
1273	spa_log_sm_set_blocklimit(spa);
1274
1275	return (0);
1276}
1277
1278void
1279vdev_metaslab_fini(vdev_t *vd)
1280{
1281	if (vd->vdev_checkpoint_sm != NULL) {
1282		ASSERT(spa_feature_is_active(vd->vdev_spa,
1283		    SPA_FEATURE_POOL_CHECKPOINT));
1284		space_map_close(vd->vdev_checkpoint_sm);
1285		/*
1286		 * Even though we close the space map, we need to set its
1287		 * pointer to NULL. The reason is that vdev_metaslab_fini()
1288		 * may be called multiple times for certain operations
1289		 * (i.e. when destroying a pool) so we need to ensure that
1290		 * this clause never executes twice. This logic is similar
1291		 * to the one used for the vdev_ms clause below.
1292		 */
1293		vd->vdev_checkpoint_sm = NULL;
1294	}
1295
1296	if (vd->vdev_ms != NULL) {
1297		metaslab_group_t *mg = vd->vdev_mg;
1298		metaslab_group_passivate(mg);
1299
1300		uint64_t count = vd->vdev_ms_count;
1301		for (uint64_t m = 0; m < count; m++) {
1302			metaslab_t *msp = vd->vdev_ms[m];
1303			if (msp != NULL)
1304				metaslab_fini(msp);
1305		}
1306		kmem_free(vd->vdev_ms, count * sizeof (metaslab_t *));
1307		vd->vdev_ms = NULL;
1308
1309		vd->vdev_ms_count = 0;
1310
1311		for (int i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
1312			ASSERT0(mg->mg_histogram[i]);
1313	}
1314	ASSERT0(vd->vdev_ms_count);
1315}
1316
1317typedef struct vdev_probe_stats {
1318	boolean_t	vps_readable;
1319	boolean_t	vps_writeable;
1320	int		vps_flags;
1321} vdev_probe_stats_t;
1322
1323static void
1324vdev_probe_done(zio_t *zio)
1325{
1326	spa_t *spa = zio->io_spa;
1327	vdev_t *vd = zio->io_vd;
1328	vdev_probe_stats_t *vps = zio->io_private;
1329
1330	ASSERT(vd->vdev_probe_zio != NULL);
1331
1332	if (zio->io_type == ZIO_TYPE_READ) {
1333		if (zio->io_error == 0)
1334			vps->vps_readable = 1;
1335		if (zio->io_error == 0 && spa_writeable(spa)) {
1336			zio_nowait(zio_write_phys(vd->vdev_probe_zio, vd,
1337			    zio->io_offset, zio->io_size, zio->io_abd,
1338			    ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1339			    ZIO_PRIORITY_SYNC_WRITE, vps->vps_flags, B_TRUE));
1340		} else {
1341			abd_free(zio->io_abd);
1342		}
1343	} else if (zio->io_type == ZIO_TYPE_WRITE) {
1344		if (zio->io_error == 0)
1345			vps->vps_writeable = 1;
1346		abd_free(zio->io_abd);
1347	} else if (zio->io_type == ZIO_TYPE_NULL) {
1348		zio_t *pio;
1349
1350		vd->vdev_cant_read |= !vps->vps_readable;
1351		vd->vdev_cant_write |= !vps->vps_writeable;
1352
1353		if (vdev_readable(vd) &&
1354		    (vdev_writeable(vd) || !spa_writeable(spa))) {
1355			zio->io_error = 0;
1356		} else {
1357			ASSERT(zio->io_error != 0);
1358			vdev_dbgmsg(vd, "failed probe");
1359			zfs_ereport_post(FM_EREPORT_ZFS_PROBE_FAILURE,
1360			    spa, vd, NULL, NULL, 0, 0);
1361			zio->io_error = SET_ERROR(ENXIO);
1362		}
1363
1364		mutex_enter(&vd->vdev_probe_lock);
1365		ASSERT(vd->vdev_probe_zio == zio);
1366		vd->vdev_probe_zio = NULL;
1367		mutex_exit(&vd->vdev_probe_lock);
1368
1369		zio_link_t *zl = NULL;
1370		while ((pio = zio_walk_parents(zio, &zl)) != NULL)
1371			if (!vdev_accessible(vd, pio))
1372				pio->io_error = SET_ERROR(ENXIO);
1373
1374		kmem_free(vps, sizeof (*vps));
1375	}
1376}
1377
1378/*
1379 * Determine whether this device is accessible.
1380 *
1381 * Read and write to several known locations: the pad regions of each
1382 * vdev label but the first, which we leave alone in case it contains
1383 * a VTOC.
1384 */
1385zio_t *
1386vdev_probe(vdev_t *vd, zio_t *zio)
1387{
1388	spa_t *spa = vd->vdev_spa;
1389	vdev_probe_stats_t *vps = NULL;
1390	zio_t *pio;
1391
1392	ASSERT(vd->vdev_ops->vdev_op_leaf);
1393
1394	/*
1395	 * Don't probe the probe.
1396	 */
1397	if (zio && (zio->io_flags & ZIO_FLAG_PROBE))
1398		return (NULL);
1399
1400	/*
1401	 * To prevent 'probe storms' when a device fails, we create
1402	 * just one probe i/o at a time.  All zios that want to probe
1403	 * this vdev will become parents of the probe io.
1404	 */
1405	mutex_enter(&vd->vdev_probe_lock);
1406
1407	if ((pio = vd->vdev_probe_zio) == NULL) {
1408		vps = kmem_zalloc(sizeof (*vps), KM_SLEEP);
1409
1410		vps->vps_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_PROBE |
1411		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE |
1412		    ZIO_FLAG_TRYHARD;
1413
1414		if (spa_config_held(spa, SCL_ZIO, RW_WRITER)) {
1415			/*
1416			 * vdev_cant_read and vdev_cant_write can only
1417			 * transition from TRUE to FALSE when we have the
1418			 * SCL_ZIO lock as writer; otherwise they can only
1419			 * transition from FALSE to TRUE.  This ensures that
1420			 * any zio looking at these values can assume that
1421			 * failures persist for the life of the I/O.  That's
1422			 * important because when a device has intermittent
1423			 * connectivity problems, we want to ensure that
1424			 * they're ascribed to the device (ENXIO) and not
1425			 * the zio (EIO).
1426			 *
1427			 * Since we hold SCL_ZIO as writer here, clear both
1428			 * values so the probe can reevaluate from first
1429			 * principles.
1430			 */
1431			vps->vps_flags |= ZIO_FLAG_CONFIG_WRITER;
1432			vd->vdev_cant_read = B_FALSE;
1433			vd->vdev_cant_write = B_FALSE;
1434		}
1435
1436		vd->vdev_probe_zio = pio = zio_null(NULL, spa, vd,
1437		    vdev_probe_done, vps,
1438		    vps->vps_flags | ZIO_FLAG_DONT_PROPAGATE);
1439
1440		/*
1441		 * We can't change the vdev state in this context, so we
1442		 * kick off an async task to do it on our behalf.
1443		 */
1444		if (zio != NULL) {
1445			vd->vdev_probe_wanted = B_TRUE;
1446			spa_async_request(spa, SPA_ASYNC_PROBE);
1447		}
1448	}
1449
1450	if (zio != NULL)
1451		zio_add_child(zio, pio);
1452
1453	mutex_exit(&vd->vdev_probe_lock);
1454
1455	if (vps == NULL) {
1456		ASSERT(zio != NULL);
1457		return (NULL);
1458	}
1459
1460	for (int l = 1; l < VDEV_LABELS; l++) {
1461		zio_nowait(zio_read_phys(pio, vd,
1462		    vdev_label_offset(vd->vdev_psize, l,
1463		    offsetof(vdev_label_t, vl_pad2)), VDEV_PAD_SIZE,
1464		    abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE),
1465		    ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1466		    ZIO_PRIORITY_SYNC_READ, vps->vps_flags, B_TRUE));
1467	}
1468
1469	if (zio == NULL)
1470		return (pio);
1471
1472	zio_nowait(pio);
1473	return (NULL);
1474}
1475
1476static void
1477vdev_open_child(void *arg)
1478{
1479	vdev_t *vd = arg;
1480
1481	vd->vdev_open_thread = curthread;
1482	vd->vdev_open_error = vdev_open(vd);
1483	vd->vdev_open_thread = NULL;
1484}
1485
1486boolean_t
1487vdev_uses_zvols(vdev_t *vd)
1488{
1489	if (vd->vdev_path && strncmp(vd->vdev_path, ZVOL_DIR,
1490	    strlen(ZVOL_DIR)) == 0)
1491		return (B_TRUE);
1492	for (int c = 0; c < vd->vdev_children; c++)
1493		if (vdev_uses_zvols(vd->vdev_child[c]))
1494			return (B_TRUE);
1495	return (B_FALSE);
1496}
1497
1498void
1499vdev_open_children(vdev_t *vd)
1500{
1501	taskq_t *tq;
1502	int children = vd->vdev_children;
1503
1504	/*
1505	 * in order to handle pools on top of zvols, do the opens
1506	 * in a single thread so that the same thread holds the
1507	 * spa_namespace_lock
1508	 */
1509	if (vdev_uses_zvols(vd)) {
1510retry_sync:
1511		for (int c = 0; c < children; c++)
1512			vd->vdev_child[c]->vdev_open_error =
1513			    vdev_open(vd->vdev_child[c]);
1514	} else {
1515		tq = taskq_create("vdev_open", children, minclsyspri,
1516		    children, children, TASKQ_PREPOPULATE);
1517		if (tq == NULL)
1518			goto retry_sync;
1519
1520		for (int c = 0; c < children; c++)
1521			VERIFY(taskq_dispatch(tq, vdev_open_child,
1522			    vd->vdev_child[c], TQ_SLEEP) != TASKQID_INVALID);
1523
1524		taskq_destroy(tq);
1525	}
1526
1527	vd->vdev_nonrot = B_TRUE;
1528
1529	for (int c = 0; c < children; c++)
1530		vd->vdev_nonrot &= vd->vdev_child[c]->vdev_nonrot;
1531}
1532
1533/*
1534 * Compute the raidz-deflation ratio.  Note, we hard-code
1535 * in 128k (1 << 17) because it is the "typical" blocksize.
1536 * Even though SPA_MAXBLOCKSIZE changed, this algorithm can not change,
1537 * otherwise it would inconsistently account for existing bp's.
1538 */
1539static void
1540vdev_set_deflate_ratio(vdev_t *vd)
1541{
1542	if (vd == vd->vdev_top && !vd->vdev_ishole && vd->vdev_ashift != 0) {
1543		vd->vdev_deflate_ratio = (1 << 17) /
1544		    (vdev_psize_to_asize(vd, 1 << 17) >> SPA_MINBLOCKSHIFT);
1545	}
1546}
1547
1548/*
1549 * Prepare a virtual device for access.
1550 */
1551int
1552vdev_open(vdev_t *vd)
1553{
1554	spa_t *spa = vd->vdev_spa;
1555	int error;
1556	uint64_t osize = 0;
1557	uint64_t max_osize = 0;
1558	uint64_t asize, max_asize, psize;
1559	uint64_t ashift = 0;
1560
1561	ASSERT(vd->vdev_open_thread == curthread ||
1562	    spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1563	ASSERT(vd->vdev_state == VDEV_STATE_CLOSED ||
1564	    vd->vdev_state == VDEV_STATE_CANT_OPEN ||
1565	    vd->vdev_state == VDEV_STATE_OFFLINE);
1566
1567	vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
1568	vd->vdev_cant_read = B_FALSE;
1569	vd->vdev_cant_write = B_FALSE;
1570	vd->vdev_min_asize = vdev_get_min_asize(vd);
1571
1572	/*
1573	 * If this vdev is not removed, check its fault status.  If it's
1574	 * faulted, bail out of the open.
1575	 */
1576	if (!vd->vdev_removed && vd->vdev_faulted) {
1577		ASSERT(vd->vdev_children == 0);
1578		ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1579		    vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1580		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1581		    vd->vdev_label_aux);
1582		return (SET_ERROR(ENXIO));
1583	} else if (vd->vdev_offline) {
1584		ASSERT(vd->vdev_children == 0);
1585		vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE, VDEV_AUX_NONE);
1586		return (SET_ERROR(ENXIO));
1587	}
1588
1589	error = vd->vdev_ops->vdev_op_open(vd, &osize, &max_osize, &ashift);
1590
1591	/*
1592	 * Reset the vdev_reopening flag so that we actually close
1593	 * the vdev on error.
1594	 */
1595	vd->vdev_reopening = B_FALSE;
1596	if (zio_injection_enabled && error == 0)
1597		error = zio_handle_device_injection(vd, NULL, ENXIO);
1598
1599	if (error) {
1600		if (vd->vdev_removed &&
1601		    vd->vdev_stat.vs_aux != VDEV_AUX_OPEN_FAILED)
1602			vd->vdev_removed = B_FALSE;
1603
1604		if (vd->vdev_stat.vs_aux == VDEV_AUX_CHILDREN_OFFLINE) {
1605			vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE,
1606			    vd->vdev_stat.vs_aux);
1607		} else {
1608			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1609			    vd->vdev_stat.vs_aux);
1610		}
1611		return (error);
1612	}
1613
1614	vd->vdev_removed = B_FALSE;
1615
1616	/*
1617	 * Recheck the faulted flag now that we have confirmed that
1618	 * the vdev is accessible.  If we're faulted, bail.
1619	 */
1620	if (vd->vdev_faulted) {
1621		ASSERT(vd->vdev_children == 0);
1622		ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1623		    vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1624		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1625		    vd->vdev_label_aux);
1626		return (SET_ERROR(ENXIO));
1627	}
1628
1629	if (vd->vdev_degraded) {
1630		ASSERT(vd->vdev_children == 0);
1631		vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1632		    VDEV_AUX_ERR_EXCEEDED);
1633	} else {
1634		vdev_set_state(vd, B_TRUE, VDEV_STATE_HEALTHY, 0);
1635	}
1636
1637	/*
1638	 * For hole or missing vdevs we just return success.
1639	 */
1640	if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops)
1641		return (0);
1642
1643	for (int c = 0; c < vd->vdev_children; c++) {
1644		if (vd->vdev_child[c]->vdev_state != VDEV_STATE_HEALTHY) {
1645			vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1646			    VDEV_AUX_NONE);
1647			break;
1648		}
1649	}
1650
1651	osize = P2ALIGN(osize, (uint64_t)sizeof (vdev_label_t));
1652	max_osize = P2ALIGN(max_osize, (uint64_t)sizeof (vdev_label_t));
1653
1654	if (vd->vdev_children == 0) {
1655		if (osize < SPA_MINDEVSIZE) {
1656			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1657			    VDEV_AUX_TOO_SMALL);
1658			return (SET_ERROR(EOVERFLOW));
1659		}
1660		psize = osize;
1661		asize = osize - (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE);
1662		max_asize = max_osize - (VDEV_LABEL_START_SIZE +
1663		    VDEV_LABEL_END_SIZE);
1664	} else {
1665		if (vd->vdev_parent != NULL && osize < SPA_MINDEVSIZE -
1666		    (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE)) {
1667			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1668			    VDEV_AUX_TOO_SMALL);
1669			return (SET_ERROR(EOVERFLOW));
1670		}
1671		psize = 0;
1672		asize = osize;
1673		max_asize = max_osize;
1674	}
1675
1676	vd->vdev_psize = psize;
1677
1678	/*
1679	 * Make sure the allocatable size hasn't shrunk too much.
1680	 */
1681	if (asize < vd->vdev_min_asize) {
1682		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1683		    VDEV_AUX_BAD_LABEL);
1684		return (SET_ERROR(EINVAL));
1685	}
1686
1687	if (vd->vdev_asize == 0) {
1688		/*
1689		 * This is the first-ever open, so use the computed values.
1690		 * For compatibility, a different ashift can be requested.
1691		 */
1692		vd->vdev_asize = asize;
1693		vd->vdev_max_asize = max_asize;
1694		if (vd->vdev_ashift == 0) {
1695			vd->vdev_ashift = ashift; /* use detected value */
1696		}
1697		if (vd->vdev_ashift != 0 && (vd->vdev_ashift < ASHIFT_MIN ||
1698		    vd->vdev_ashift > ASHIFT_MAX)) {
1699			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1700			    VDEV_AUX_BAD_ASHIFT);
1701			return (SET_ERROR(EDOM));
1702		}
1703	} else {
1704		/*
1705		 * Detect if the alignment requirement has increased.
1706		 * We don't want to make the pool unavailable, just
1707		 * post an event instead.
1708		 */
1709		if (ashift > vd->vdev_top->vdev_ashift &&
1710		    vd->vdev_ops->vdev_op_leaf) {
1711			zfs_ereport_post(FM_EREPORT_ZFS_DEVICE_BAD_ASHIFT,
1712			    spa, vd, NULL, NULL, 0, 0);
1713		}
1714
1715		vd->vdev_max_asize = max_asize;
1716	}
1717
1718	/*
1719	 * If all children are healthy we update asize if either:
1720	 * The asize has increased, due to a device expansion caused by dynamic
1721	 * LUN growth or vdev replacement, and automatic expansion is enabled;
1722	 * making the additional space available.
1723	 *
1724	 * The asize has decreased, due to a device shrink usually caused by a
1725	 * vdev replace with a smaller device. This ensures that calculations
1726	 * based of max_asize and asize e.g. esize are always valid. It's safe
1727	 * to do this as we've already validated that asize is greater than
1728	 * vdev_min_asize.
1729	 */
1730	if (vd->vdev_state == VDEV_STATE_HEALTHY &&
1731	    ((asize > vd->vdev_asize &&
1732	    (vd->vdev_expanding || spa->spa_autoexpand)) ||
1733	    (asize < vd->vdev_asize)))
1734		vd->vdev_asize = asize;
1735
1736	vdev_set_min_asize(vd);
1737
1738	/*
1739	 * Ensure we can issue some IO before declaring the
1740	 * vdev open for business.
1741	 */
1742	if (vd->vdev_ops->vdev_op_leaf &&
1743	    (error = zio_wait(vdev_probe(vd, NULL))) != 0) {
1744		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1745		    VDEV_AUX_ERR_EXCEEDED);
1746		return (error);
1747	}
1748
1749	/*
1750	 * Track the min and max ashift values for normal data devices.
1751	 *
1752	 * DJB - TBD these should perhaps be tracked per allocation class
1753	 * (e.g. spa_min_ashift is used to round up post compression buffers)
1754	 */
1755	if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
1756	    vd->vdev_alloc_bias == VDEV_BIAS_NONE &&
1757	    vd->vdev_aux == NULL) {
1758		if (vd->vdev_ashift > spa->spa_max_ashift)
1759			spa->spa_max_ashift = vd->vdev_ashift;
1760		if (vd->vdev_ashift < spa->spa_min_ashift)
1761			spa->spa_min_ashift = vd->vdev_ashift;
1762	}
1763
1764	/*
1765	 * If a leaf vdev has a DTL, and seems healthy, then kick off a
1766	 * resilver.  But don't do this if we are doing a reopen for a scrub,
1767	 * since this would just restart the scrub we are already doing.
1768	 */
1769	if (vd->vdev_ops->vdev_op_leaf && !spa->spa_scrub_reopen &&
1770	    vdev_resilver_needed(vd, NULL, NULL)) {
1771		if (dsl_scan_resilvering(spa->spa_dsl_pool) &&
1772		    spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER))
1773			vdev_set_deferred_resilver(spa, vd);
1774		else
1775			spa_async_request(spa, SPA_ASYNC_RESILVER);
1776	}
1777
1778	return (0);
1779}
1780
1781/*
1782 * Called once the vdevs are all opened, this routine validates the label
1783 * contents. This needs to be done before vdev_load() so that we don't
1784 * inadvertently do repair I/Os to the wrong device.
1785 *
1786 * This function will only return failure if one of the vdevs indicates that it
1787 * has since been destroyed or exported.  This is only possible if
1788 * /etc/zfs/zpool.cache was readonly at the time.  Otherwise, the vdev state
1789 * will be updated but the function will return 0.
1790 */
1791int
1792vdev_validate(vdev_t *vd)
1793{
1794	spa_t *spa = vd->vdev_spa;
1795	nvlist_t *label;
1796	uint64_t guid = 0, aux_guid = 0, top_guid;
1797	uint64_t state;
1798	nvlist_t *nvl;
1799	uint64_t txg;
1800
1801	if (vdev_validate_skip)
1802		return (0);
1803
1804	for (uint64_t c = 0; c < vd->vdev_children; c++)
1805		if (vdev_validate(vd->vdev_child[c]) != 0)
1806			return (SET_ERROR(EBADF));
1807
1808	/*
1809	 * If the device has already failed, or was marked offline, don't do
1810	 * any further validation.  Otherwise, label I/O will fail and we will
1811	 * overwrite the previous state.
1812	 */
1813	if (!vd->vdev_ops->vdev_op_leaf || !vdev_readable(vd))
1814		return (0);
1815
1816	/*
1817	 * If we are performing an extreme rewind, we allow for a label that
1818	 * was modified at a point after the current txg.
1819	 * If config lock is not held do not check for the txg. spa_sync could
1820	 * be updating the vdev's label before updating spa_last_synced_txg.
1821	 */
1822	if (spa->spa_extreme_rewind || spa_last_synced_txg(spa) == 0 ||
1823	    spa_config_held(spa, SCL_CONFIG, RW_WRITER) != SCL_CONFIG)
1824		txg = UINT64_MAX;
1825	else
1826		txg = spa_last_synced_txg(spa);
1827
1828	if ((label = vdev_label_read_config(vd, txg)) == NULL) {
1829		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1830		    VDEV_AUX_BAD_LABEL);
1831		vdev_dbgmsg(vd, "vdev_validate: failed reading config for "
1832		    "txg %llu", (u_longlong_t)txg);
1833		return (0);
1834	}
1835
1836	/*
1837	 * Determine if this vdev has been split off into another
1838	 * pool.  If so, then refuse to open it.
1839	 */
1840	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_SPLIT_GUID,
1841	    &aux_guid) == 0 && aux_guid == spa_guid(spa)) {
1842		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1843		    VDEV_AUX_SPLIT_POOL);
1844		nvlist_free(label);
1845		vdev_dbgmsg(vd, "vdev_validate: vdev split into other pool");
1846		return (0);
1847	}
1848
1849	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID, &guid) != 0) {
1850		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1851		    VDEV_AUX_CORRUPT_DATA);
1852		nvlist_free(label);
1853		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
1854		    ZPOOL_CONFIG_POOL_GUID);
1855		return (0);
1856	}
1857
1858	/*
1859	 * If config is not trusted then ignore the spa guid check. This is
1860	 * necessary because if the machine crashed during a re-guid the new
1861	 * guid might have been written to all of the vdev labels, but not the
1862	 * cached config. The check will be performed again once we have the
1863	 * trusted config from the MOS.
1864	 */
1865	if (spa->spa_trust_config && guid != spa_guid(spa)) {
1866		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1867		    VDEV_AUX_CORRUPT_DATA);
1868		nvlist_free(label);
1869		vdev_dbgmsg(vd, "vdev_validate: vdev label pool_guid doesn't "
1870		    "match config (%llu != %llu)", (u_longlong_t)guid,
1871		    (u_longlong_t)spa_guid(spa));
1872		return (0);
1873	}
1874
1875	if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvl)
1876	    != 0 || nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_ORIG_GUID,
1877	    &aux_guid) != 0)
1878		aux_guid = 0;
1879
1880	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0) {
1881		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1882		    VDEV_AUX_CORRUPT_DATA);
1883		nvlist_free(label);
1884		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
1885		    ZPOOL_CONFIG_GUID);
1886		return (0);
1887	}
1888
1889	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID, &top_guid)
1890	    != 0) {
1891		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1892		    VDEV_AUX_CORRUPT_DATA);
1893		nvlist_free(label);
1894		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
1895		    ZPOOL_CONFIG_TOP_GUID);
1896		return (0);
1897	}
1898
1899	/*
1900	 * If this vdev just became a top-level vdev because its sibling was
1901	 * detached, it will have adopted the parent's vdev guid -- but the
1902	 * label may or may not be on disk yet. Fortunately, either version
1903	 * of the label will have the same top guid, so if we're a top-level
1904	 * vdev, we can safely compare to that instead.
1905	 * However, if the config comes from a cachefile that failed to update
1906	 * after the detach, a top-level vdev will appear as a non top-level
1907	 * vdev in the config. Also relax the constraints if we perform an
1908	 * extreme rewind.
1909	 *
1910	 * If we split this vdev off instead, then we also check the
1911	 * original pool's guid. We don't want to consider the vdev
1912	 * corrupt if it is partway through a split operation.
1913	 */
1914	if (vd->vdev_guid != guid && vd->vdev_guid != aux_guid) {
1915		boolean_t mismatch = B_FALSE;
1916		if (spa->spa_trust_config && !spa->spa_extreme_rewind) {
1917			if (vd != vd->vdev_top || vd->vdev_guid != top_guid)
1918				mismatch = B_TRUE;
1919		} else {
1920			if (vd->vdev_guid != top_guid &&
1921			    vd->vdev_top->vdev_guid != guid)
1922				mismatch = B_TRUE;
1923		}
1924
1925		if (mismatch) {
1926			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1927			    VDEV_AUX_CORRUPT_DATA);
1928			nvlist_free(label);
1929			vdev_dbgmsg(vd, "vdev_validate: config guid "
1930			    "doesn't match label guid");
1931			vdev_dbgmsg(vd, "CONFIG: guid %llu, top_guid %llu",
1932			    (u_longlong_t)vd->vdev_guid,
1933			    (u_longlong_t)vd->vdev_top->vdev_guid);
1934			vdev_dbgmsg(vd, "LABEL: guid %llu, top_guid %llu, "
1935			    "aux_guid %llu", (u_longlong_t)guid,
1936			    (u_longlong_t)top_guid, (u_longlong_t)aux_guid);
1937			return (0);
1938		}
1939	}
1940
1941	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
1942	    &state) != 0) {
1943		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1944		    VDEV_AUX_CORRUPT_DATA);
1945		nvlist_free(label);
1946		vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
1947		    ZPOOL_CONFIG_POOL_STATE);
1948		return (0);
1949	}
1950
1951	nvlist_free(label);
1952
1953	/*
1954	 * If this is a verbatim import, no need to check the
1955	 * state of the pool.
1956	 */
1957	if (!(spa->spa_import_flags & ZFS_IMPORT_VERBATIM) &&
1958	    spa_load_state(spa) == SPA_LOAD_OPEN &&
1959	    state != POOL_STATE_ACTIVE) {
1960		vdev_dbgmsg(vd, "vdev_validate: invalid pool state (%llu) "
1961		    "for spa %s", (u_longlong_t)state, spa->spa_name);
1962		return (SET_ERROR(EBADF));
1963	}
1964
1965	/*
1966	 * If we were able to open and validate a vdev that was
1967	 * previously marked permanently unavailable, clear that state
1968	 * now.
1969	 */
1970	if (vd->vdev_not_present)
1971		vd->vdev_not_present = 0;
1972
1973	return (0);
1974}
1975
1976static void
1977vdev_copy_path_impl(vdev_t *svd, vdev_t *dvd)
1978{
1979	if (svd->vdev_path != NULL && dvd->vdev_path != NULL) {
1980		if (strcmp(svd->vdev_path, dvd->vdev_path) != 0) {
1981			zfs_dbgmsg("vdev_copy_path: vdev %llu: path changed "
1982			    "from '%s' to '%s'", (u_longlong_t)dvd->vdev_guid,
1983			    dvd->vdev_path, svd->vdev_path);
1984			spa_strfree(dvd->vdev_path);
1985			dvd->vdev_path = spa_strdup(svd->vdev_path);
1986		}
1987	} else if (svd->vdev_path != NULL) {
1988		dvd->vdev_path = spa_strdup(svd->vdev_path);
1989		zfs_dbgmsg("vdev_copy_path: vdev %llu: path set to '%s'",
1990		    (u_longlong_t)dvd->vdev_guid, dvd->vdev_path);
1991	}
1992}
1993
1994/*
1995 * Recursively copy vdev paths from one vdev to another. Source and destination
1996 * vdev trees must have same geometry otherwise return error. Intended to copy
1997 * paths from userland config into MOS config.
1998 */
1999int
2000vdev_copy_path_strict(vdev_t *svd, vdev_t *dvd)
2001{
2002	if ((svd->vdev_ops == &vdev_missing_ops) ||
2003	    (svd->vdev_ishole && dvd->vdev_ishole) ||
2004	    (dvd->vdev_ops == &vdev_indirect_ops))
2005		return (0);
2006
2007	if (svd->vdev_ops != dvd->vdev_ops) {
2008		vdev_dbgmsg(svd, "vdev_copy_path: vdev type mismatch: %s != %s",
2009		    svd->vdev_ops->vdev_op_type, dvd->vdev_ops->vdev_op_type);
2010		return (SET_ERROR(EINVAL));
2011	}
2012
2013	if (svd->vdev_guid != dvd->vdev_guid) {
2014		vdev_dbgmsg(svd, "vdev_copy_path: guids mismatch (%llu != "
2015		    "%llu)", (u_longlong_t)svd->vdev_guid,
2016		    (u_longlong_t)dvd->vdev_guid);
2017		return (SET_ERROR(EINVAL));
2018	}
2019
2020	if (svd->vdev_children != dvd->vdev_children) {
2021		vdev_dbgmsg(svd, "vdev_copy_path: children count mismatch: "
2022		    "%llu != %llu", (u_longlong_t)svd->vdev_children,
2023		    (u_longlong_t)dvd->vdev_children);
2024		return (SET_ERROR(EINVAL));
2025	}
2026
2027	for (uint64_t i = 0; i < svd->vdev_children; i++) {
2028		int error = vdev_copy_path_strict(svd->vdev_child[i],
2029		    dvd->vdev_child[i]);
2030		if (error != 0)
2031			return (error);
2032	}
2033
2034	if (svd->vdev_ops->vdev_op_leaf)
2035		vdev_copy_path_impl(svd, dvd);
2036
2037	return (0);
2038}
2039
2040static void
2041vdev_copy_path_search(vdev_t *stvd, vdev_t *dvd)
2042{
2043	ASSERT(stvd->vdev_top == stvd);
2044	ASSERT3U(stvd->vdev_id, ==, dvd->vdev_top->vdev_id);
2045
2046	for (uint64_t i = 0; i < dvd->vdev_children; i++) {
2047		vdev_copy_path_search(stvd, dvd->vdev_child[i]);
2048	}
2049
2050	if (!dvd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(dvd))
2051		return;
2052
2053	/*
2054	 * The idea here is that while a vdev can shift positions within
2055	 * a top vdev (when replacing, attaching mirror, etc.) it cannot
2056	 * step outside of it.
2057	 */
2058	vdev_t *vd = vdev_lookup_by_guid(stvd, dvd->vdev_guid);
2059
2060	if (vd == NULL || vd->vdev_ops != dvd->vdev_ops)
2061		return;
2062
2063	ASSERT(vd->vdev_ops->vdev_op_leaf);
2064
2065	vdev_copy_path_impl(vd, dvd);
2066}
2067
2068/*
2069 * Recursively copy vdev paths from one root vdev to another. Source and
2070 * destination vdev trees may differ in geometry. For each destination leaf
2071 * vdev, search a vdev with the same guid and top vdev id in the source.
2072 * Intended to copy paths from userland config into MOS config.
2073 */
2074void
2075vdev_copy_path_relaxed(vdev_t *srvd, vdev_t *drvd)
2076{
2077	uint64_t children = MIN(srvd->vdev_children, drvd->vdev_children);
2078	ASSERT(srvd->vdev_ops == &vdev_root_ops);
2079	ASSERT(drvd->vdev_ops == &vdev_root_ops);
2080
2081	for (uint64_t i = 0; i < children; i++) {
2082		vdev_copy_path_search(srvd->vdev_child[i],
2083		    drvd->vdev_child[i]);
2084	}
2085}
2086
2087/*
2088 * Close a virtual device.
2089 */
2090void
2091vdev_close(vdev_t *vd)
2092{
2093	spa_t *spa = vd->vdev_spa;
2094	vdev_t *pvd = vd->vdev_parent;
2095
2096	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2097
2098	/*
2099	 * If our parent is reopening, then we are as well, unless we are
2100	 * going offline.
2101	 */
2102	if (pvd != NULL && pvd->vdev_reopening)
2103		vd->vdev_reopening = (pvd->vdev_reopening && !vd->vdev_offline);
2104
2105	vd->vdev_ops->vdev_op_close(vd);
2106
2107	vdev_cache_purge(vd);
2108
2109	/*
2110	 * We record the previous state before we close it, so that if we are
2111	 * doing a reopen(), we don't generate FMA ereports if we notice that
2112	 * it's still faulted.
2113	 */
2114	vd->vdev_prevstate = vd->vdev_state;
2115
2116	if (vd->vdev_offline)
2117		vd->vdev_state = VDEV_STATE_OFFLINE;
2118	else
2119		vd->vdev_state = VDEV_STATE_CLOSED;
2120	vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
2121}
2122
2123void
2124vdev_hold(vdev_t *vd)
2125{
2126	spa_t *spa = vd->vdev_spa;
2127
2128	ASSERT(spa_is_root(spa));
2129	if (spa->spa_state == POOL_STATE_UNINITIALIZED)
2130		return;
2131
2132	for (int c = 0; c < vd->vdev_children; c++)
2133		vdev_hold(vd->vdev_child[c]);
2134
2135	if (vd->vdev_ops->vdev_op_leaf)
2136		vd->vdev_ops->vdev_op_hold(vd);
2137}
2138
2139void
2140vdev_rele(vdev_t *vd)
2141{
2142	spa_t *spa = vd->vdev_spa;
2143
2144	ASSERT(spa_is_root(spa));
2145	for (int c = 0; c < vd->vdev_children; c++)
2146		vdev_rele(vd->vdev_child[c]);
2147
2148	if (vd->vdev_ops->vdev_op_leaf)
2149		vd->vdev_ops->vdev_op_rele(vd);
2150}
2151
2152/*
2153 * Reopen all interior vdevs and any unopened leaves.  We don't actually
2154 * reopen leaf vdevs which had previously been opened as they might deadlock
2155 * on the spa_config_lock.  Instead we only obtain the leaf's physical size.
2156 * If the leaf has never been opened then open it, as usual.
2157 */
2158void
2159vdev_reopen(vdev_t *vd)
2160{
2161	spa_t *spa = vd->vdev_spa;
2162
2163	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2164
2165	/* set the reopening flag unless we're taking the vdev offline */
2166	vd->vdev_reopening = !vd->vdev_offline;
2167	vdev_close(vd);
2168	(void) vdev_open(vd);
2169
2170	/*
2171	 * Call vdev_validate() here to make sure we have the same device.
2172	 * Otherwise, a device with an invalid label could be successfully
2173	 * opened in response to vdev_reopen().
2174	 */
2175	if (vd->vdev_aux) {
2176		(void) vdev_validate_aux(vd);
2177		if (vdev_readable(vd) && vdev_writeable(vd) &&
2178		    vd->vdev_aux == &spa->spa_l2cache &&
2179		    !l2arc_vdev_present(vd))
2180			l2arc_add_vdev(spa, vd);
2181	} else {
2182		(void) vdev_validate(vd);
2183	}
2184
2185	/*
2186	 * Reassess parent vdev's health.
2187	 */
2188	vdev_propagate_state(vd);
2189}
2190
2191int
2192vdev_create(vdev_t *vd, uint64_t txg, boolean_t isreplacing)
2193{
2194	int error;
2195
2196	/*
2197	 * Normally, partial opens (e.g. of a mirror) are allowed.
2198	 * For a create, however, we want to fail the request if
2199	 * there are any components we can't open.
2200	 */
2201	error = vdev_open(vd);
2202
2203	if (error || vd->vdev_state != VDEV_STATE_HEALTHY) {
2204		vdev_close(vd);
2205		return (error ? error : ENXIO);
2206	}
2207
2208	/*
2209	 * Recursively load DTLs and initialize all labels.
2210	 */
2211	if ((error = vdev_dtl_load(vd)) != 0 ||
2212	    (error = vdev_label_init(vd, txg, isreplacing ?
2213	    VDEV_LABEL_REPLACE : VDEV_LABEL_CREATE)) != 0) {
2214		vdev_close(vd);
2215		return (error);
2216	}
2217
2218	return (0);
2219}
2220
2221void
2222vdev_metaslab_set_size(vdev_t *vd)
2223{
2224	uint64_t asize = vd->vdev_asize;
2225	uint64_t ms_count = asize >> zfs_vdev_default_ms_shift;
2226	uint64_t ms_shift;
2227
2228	/* BEGIN CSTYLED */
2229	/*
2230	 * There are two dimensions to the metaslab sizing calculation:
2231	 * the size of the metaslab and the count of metaslabs per vdev.
2232	 *
2233	 * The default values used below are a good balance between memory
2234	 * usage (larger metaslab size means more memory needed for loaded
2235	 * metaslabs; more metaslabs means more memory needed for the
2236	 * metaslab_t structs), metaslab load time (larger metaslabs take
2237	 * longer to load), and metaslab sync time (more metaslabs means
2238	 * more time spent syncing all of them).
2239	 *
2240	 * In general, we aim for zfs_vdev_default_ms_count (200) metaslabs.
2241	 * The range of the dimensions are as follows:
2242	 *
2243	 *	2^29 <= ms_size  <= 2^34
2244	 *	  16 <= ms_count <= 131,072
2245	 *
2246	 * On the lower end of vdev sizes, we aim for metaslabs sizes of
2247	 * at least 512MB (2^29) to minimize fragmentation effects when
2248	 * testing with smaller devices.  However, the count constraint
2249	 * of at least 16 metaslabs will override this minimum size goal.
2250	 *
2251	 * On the upper end of vdev sizes, we aim for a maximum metaslab
2252	 * size of 16GB.  However, we will cap the total count to 2^17
2253	 * metaslabs to keep our memory footprint in check and let the
2254	 * metaslab size grow from there if that limit is hit.
2255	 *
2256	 * The net effect of applying above constrains is summarized below.
2257	 *
2258	 *   vdev size	    metaslab count
2259	 *  --------------|-----------------
2260	 *	< 8GB		~16
2261	 *  8GB   - 100GB	one per 512MB
2262	 *  100GB - 3TB		~200
2263	 *  3TB   - 2PB		one per 16GB
2264	 *	> 2PB		~131,072
2265	 *  --------------------------------
2266	 *
2267	 *  Finally, note that all of the above calculate the initial
2268	 *  number of metaslabs. Expanding a top-level vdev will result
2269	 *  in additional metaslabs being allocated making it possible
2270	 *  to exceed the zfs_vdev_ms_count_limit.
2271	 */
2272	/* END CSTYLED */
2273
2274	if (ms_count < zfs_vdev_min_ms_count)
2275		ms_shift = highbit64(asize / zfs_vdev_min_ms_count);
2276	else if (ms_count > zfs_vdev_default_ms_count)
2277		ms_shift = highbit64(asize / zfs_vdev_default_ms_count);
2278	else
2279		ms_shift = zfs_vdev_default_ms_shift;
2280
2281	if (ms_shift < SPA_MAXBLOCKSHIFT) {
2282		ms_shift = SPA_MAXBLOCKSHIFT;
2283	} else if (ms_shift > zfs_vdev_max_ms_shift) {
2284		ms_shift = zfs_vdev_max_ms_shift;
2285		/* cap the total count to constrain memory footprint */
2286		if ((asize >> ms_shift) > zfs_vdev_ms_count_limit)
2287			ms_shift = highbit64(asize / zfs_vdev_ms_count_limit);
2288	}
2289
2290	vd->vdev_ms_shift = ms_shift;
2291	ASSERT3U(vd->vdev_ms_shift, >=, SPA_MAXBLOCKSHIFT);
2292}
2293
2294void
2295vdev_dirty(vdev_t *vd, int flags, void *arg, uint64_t txg)
2296{
2297	ASSERT(vd == vd->vdev_top);
2298	/* indirect vdevs don't have metaslabs or dtls */
2299	ASSERT(vdev_is_concrete(vd) || flags == 0);
2300	ASSERT(ISP2(flags));
2301	ASSERT(spa_writeable(vd->vdev_spa));
2302
2303	if (flags & VDD_METASLAB)
2304		(void) txg_list_add(&vd->vdev_ms_list, arg, txg);
2305
2306	if (flags & VDD_DTL)
2307		(void) txg_list_add(&vd->vdev_dtl_list, arg, txg);
2308
2309	(void) txg_list_add(&vd->vdev_spa->spa_vdev_txg_list, vd, txg);
2310}
2311
2312void
2313vdev_dirty_leaves(vdev_t *vd, int flags, uint64_t txg)
2314{
2315	for (int c = 0; c < vd->vdev_children; c++)
2316		vdev_dirty_leaves(vd->vdev_child[c], flags, txg);
2317
2318	if (vd->vdev_ops->vdev_op_leaf)
2319		vdev_dirty(vd->vdev_top, flags, vd, txg);
2320}
2321
2322/*
2323 * DTLs.
2324 *
2325 * A vdev's DTL (dirty time log) is the set of transaction groups for which
2326 * the vdev has less than perfect replication.  There are four kinds of DTL:
2327 *
2328 * DTL_MISSING: txgs for which the vdev has no valid copies of the data
2329 *
2330 * DTL_PARTIAL: txgs for which data is available, but not fully replicated
2331 *
2332 * DTL_SCRUB: the txgs that could not be repaired by the last scrub; upon
2333 *	scrub completion, DTL_SCRUB replaces DTL_MISSING in the range of
2334 *	txgs that was scrubbed.
2335 *
2336 * DTL_OUTAGE: txgs which cannot currently be read, whether due to
2337 *	persistent errors or just some device being offline.
2338 *	Unlike the other three, the DTL_OUTAGE map is not generally
2339 *	maintained; it's only computed when needed, typically to
2340 *	determine whether a device can be detached.
2341 *
2342 * For leaf vdevs, DTL_MISSING and DTL_PARTIAL are identical: the device
2343 * either has the data or it doesn't.
2344 *
2345 * For interior vdevs such as mirror and RAID-Z the picture is more complex.
2346 * A vdev's DTL_PARTIAL is the union of its children's DTL_PARTIALs, because
2347 * if any child is less than fully replicated, then so is its parent.
2348 * A vdev's DTL_MISSING is a modified union of its children's DTL_MISSINGs,
2349 * comprising only those txgs which appear in 'maxfaults' or more children;
2350 * those are the txgs we don't have enough replication to read.  For example,
2351 * double-parity RAID-Z can tolerate up to two missing devices (maxfaults == 2);
2352 * thus, its DTL_MISSING consists of the set of txgs that appear in more than
2353 * two child DTL_MISSING maps.
2354 *
2355 * It should be clear from the above that to compute the DTLs and outage maps
2356 * for all vdevs, it suffices to know just the leaf vdevs' DTL_MISSING maps.
2357 * Therefore, that is all we keep on disk.  When loading the pool, or after
2358 * a configuration change, we generate all other DTLs from first principles.
2359 */
2360void
2361vdev_dtl_dirty(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
2362{
2363	range_tree_t *rt = vd->vdev_dtl[t];
2364
2365	ASSERT(t < DTL_TYPES);
2366	ASSERT(vd != vd->vdev_spa->spa_root_vdev);
2367	ASSERT(spa_writeable(vd->vdev_spa));
2368
2369	mutex_enter(&vd->vdev_dtl_lock);
2370	if (!range_tree_contains(rt, txg, size))
2371		range_tree_add(rt, txg, size);
2372	mutex_exit(&vd->vdev_dtl_lock);
2373}
2374
2375boolean_t
2376vdev_dtl_contains(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
2377{
2378	range_tree_t *rt = vd->vdev_dtl[t];
2379	boolean_t dirty = B_FALSE;
2380
2381	ASSERT(t < DTL_TYPES);
2382	ASSERT(vd != vd->vdev_spa->spa_root_vdev);
2383
2384	/*
2385	 * While we are loading the pool, the DTLs have not been loaded yet.
2386	 * Ignore the DTLs and try all devices.  This avoids a recursive
2387	 * mutex enter on the vdev_dtl_lock, and also makes us try hard
2388	 * when loading the pool (relying on the checksum to ensure that
2389	 * we get the right data -- note that we while loading, we are
2390	 * only reading the MOS, which is always checksummed).
2391	 */
2392	if (vd->vdev_spa->spa_load_state != SPA_LOAD_NONE)
2393		return (B_FALSE);
2394
2395	mutex_enter(&vd->vdev_dtl_lock);
2396	if (!range_tree_is_empty(rt))
2397		dirty = range_tree_contains(rt, txg, size);
2398	mutex_exit(&vd->vdev_dtl_lock);
2399
2400	return (dirty);
2401}
2402
2403boolean_t
2404vdev_dtl_empty(vdev_t *vd, vdev_dtl_type_t t)
2405{
2406	range_tree_t *rt = vd->vdev_dtl[t];
2407	boolean_t empty;
2408
2409	mutex_enter(&vd->vdev_dtl_lock);
2410	empty = range_tree_is_empty(rt);
2411	mutex_exit(&vd->vdev_dtl_lock);
2412
2413	return (empty);
2414}
2415
2416/*
2417 * Returns B_TRUE if vdev determines offset needs to be resilvered.
2418 */
2419boolean_t
2420vdev_dtl_need_resilver(vdev_t *vd, uint64_t offset, size_t psize)
2421{
2422	ASSERT(vd != vd->vdev_spa->spa_root_vdev);
2423
2424	if (vd->vdev_ops->vdev_op_need_resilver == NULL ||
2425	    vd->vdev_ops->vdev_op_leaf)
2426		return (B_TRUE);
2427
2428	return (vd->vdev_ops->vdev_op_need_resilver(vd, offset, psize));
2429}
2430
2431/*
2432 * Returns the lowest txg in the DTL range.
2433 */
2434static uint64_t
2435vdev_dtl_min(vdev_t *vd)
2436{
2437	range_seg_t *rs;
2438
2439	ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
2440	ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
2441	ASSERT0(vd->vdev_children);
2442
2443	rs = avl_first(&vd->vdev_dtl[DTL_MISSING]->rt_root);
2444	return (rs->rs_start - 1);
2445}
2446
2447/*
2448 * Returns the highest txg in the DTL.
2449 */
2450static uint64_t
2451vdev_dtl_max(vdev_t *vd)
2452{
2453	range_seg_t *rs;
2454
2455	ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
2456	ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
2457	ASSERT0(vd->vdev_children);
2458
2459	rs = avl_last(&vd->vdev_dtl[DTL_MISSING]->rt_root);
2460	return (rs->rs_end);
2461}
2462
2463/*
2464 * Determine if a resilvering vdev should remove any DTL entries from
2465 * its range. If the vdev was resilvering for the entire duration of the
2466 * scan then it should excise that range from its DTLs. Otherwise, this
2467 * vdev is considered partially resilvered and should leave its DTL
2468 * entries intact. The comment in vdev_dtl_reassess() describes how we
2469 * excise the DTLs.
2470 */
2471static boolean_t
2472vdev_dtl_should_excise(vdev_t *vd)
2473{
2474	spa_t *spa = vd->vdev_spa;
2475	dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
2476
2477	ASSERT0(scn->scn_phys.scn_errors);
2478	ASSERT0(vd->vdev_children);
2479
2480	if (vd->vdev_state < VDEV_STATE_DEGRADED)
2481		return (B_FALSE);
2482
2483	if (vd->vdev_resilver_deferred)
2484		return (B_FALSE);
2485
2486	if (vd->vdev_resilver_txg == 0 ||
2487	    range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]))
2488		return (B_TRUE);
2489
2490	/*
2491	 * When a resilver is initiated the scan will assign the scn_max_txg
2492	 * value to the highest txg value that exists in all DTLs. If this
2493	 * device's max DTL is not part of this scan (i.e. it is not in
2494	 * the range (scn_min_txg, scn_max_txg] then it is not eligible
2495	 * for excision.
2496	 */
2497	if (vdev_dtl_max(vd) <= scn->scn_phys.scn_max_txg) {
2498		ASSERT3U(scn->scn_phys.scn_min_txg, <=, vdev_dtl_min(vd));
2499		ASSERT3U(scn->scn_phys.scn_min_txg, <, vd->vdev_resilver_txg);
2500		ASSERT3U(vd->vdev_resilver_txg, <=, scn->scn_phys.scn_max_txg);
2501		return (B_TRUE);
2502	}
2503	return (B_FALSE);
2504}
2505
2506/*
2507 * Reassess DTLs after a config change or scrub completion.
2508 */
2509void
2510vdev_dtl_reassess(vdev_t *vd, uint64_t txg, uint64_t scrub_txg, int scrub_done)
2511{
2512	spa_t *spa = vd->vdev_spa;
2513	avl_tree_t reftree;
2514	int minref;
2515
2516	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
2517
2518	for (int c = 0; c < vd->vdev_children; c++)
2519		vdev_dtl_reassess(vd->vdev_child[c], txg,
2520		    scrub_txg, scrub_done);
2521
2522	if (vd == spa->spa_root_vdev || !vdev_is_concrete(vd) || vd->vdev_aux)
2523		return;
2524
2525	if (vd->vdev_ops->vdev_op_leaf) {
2526		dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
2527
2528		mutex_enter(&vd->vdev_dtl_lock);
2529
2530		/*
2531		 * If we've completed a scan cleanly then determine
2532		 * if this vdev should remove any DTLs. We only want to
2533		 * excise regions on vdevs that were available during
2534		 * the entire duration of this scan.
2535		 */
2536		if (scrub_txg != 0 &&
2537		    (spa->spa_scrub_started ||
2538		    (scn != NULL && scn->scn_phys.scn_errors == 0)) &&
2539		    vdev_dtl_should_excise(vd)) {
2540			/*
2541			 * We completed a scrub up to scrub_txg.  If we
2542			 * did it without rebooting, then the scrub dtl
2543			 * will be valid, so excise the old region and
2544			 * fold in the scrub dtl.  Otherwise, leave the
2545			 * dtl as-is if there was an error.
2546			 *
2547			 * There's little trick here: to excise the beginning
2548			 * of the DTL_MISSING map, we put it into a reference
2549			 * tree and then add a segment with refcnt -1 that
2550			 * covers the range [0, scrub_txg).  This means
2551			 * that each txg in that range has refcnt -1 or 0.
2552			 * We then add DTL_SCRUB with a refcnt of 2, so that
2553			 * entries in the range [0, scrub_txg) will have a
2554			 * positive refcnt -- either 1 or 2.  We then convert
2555			 * the reference tree into the new DTL_MISSING map.
2556			 */
2557			space_reftree_create(&reftree);
2558			space_reftree_add_map(&reftree,
2559			    vd->vdev_dtl[DTL_MISSING], 1);
2560			space_reftree_add_seg(&reftree, 0, scrub_txg, -1);
2561			space_reftree_add_map(&reftree,
2562			    vd->vdev_dtl[DTL_SCRUB], 2);
2563			space_reftree_generate_map(&reftree,
2564			    vd->vdev_dtl[DTL_MISSING], 1);
2565			space_reftree_destroy(&reftree);
2566		}
2567		range_tree_vacate(vd->vdev_dtl[DTL_PARTIAL], NULL, NULL);
2568		range_tree_walk(vd->vdev_dtl[DTL_MISSING],
2569		    range_tree_add, vd->vdev_dtl[DTL_PARTIAL]);
2570		if (scrub_done)
2571			range_tree_vacate(vd->vdev_dtl[DTL_SCRUB], NULL, NULL);
2572		range_tree_vacate(vd->vdev_dtl[DTL_OUTAGE], NULL, NULL);
2573		if (!vdev_readable(vd))
2574			range_tree_add(vd->vdev_dtl[DTL_OUTAGE], 0, -1ULL);
2575		else
2576			range_tree_walk(vd->vdev_dtl[DTL_MISSING],
2577			    range_tree_add, vd->vdev_dtl[DTL_OUTAGE]);
2578
2579		/*
2580		 * If the vdev was resilvering and no longer has any
2581		 * DTLs then reset its resilvering flag.
2582		 */
2583		if (vd->vdev_resilver_txg != 0 &&
2584		    range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
2585		    range_tree_is_empty(vd->vdev_dtl[DTL_OUTAGE]))
2586			vd->vdev_resilver_txg = 0;
2587
2588		mutex_exit(&vd->vdev_dtl_lock);
2589
2590		if (txg != 0)
2591			vdev_dirty(vd->vdev_top, VDD_DTL, vd, txg);
2592		return;
2593	}
2594
2595	mutex_enter(&vd->vdev_dtl_lock);
2596	for (int t = 0; t < DTL_TYPES; t++) {
2597		/* account for child's outage in parent's missing map */
2598		int s = (t == DTL_MISSING) ? DTL_OUTAGE: t;
2599		if (t == DTL_SCRUB)
2600			continue;			/* leaf vdevs only */
2601		if (t == DTL_PARTIAL)
2602			minref = 1;			/* i.e. non-zero */
2603		else if (vd->vdev_nparity != 0)
2604			minref = vd->vdev_nparity + 1;	/* RAID-Z */
2605		else
2606			minref = vd->vdev_children;	/* any kind of mirror */
2607		space_reftree_create(&reftree);
2608		for (int c = 0; c < vd->vdev_children; c++) {
2609			vdev_t *cvd = vd->vdev_child[c];
2610			mutex_enter(&cvd->vdev_dtl_lock);
2611			space_reftree_add_map(&reftree, cvd->vdev_dtl[s], 1);
2612			mutex_exit(&cvd->vdev_dtl_lock);
2613		}
2614		space_reftree_generate_map(&reftree, vd->vdev_dtl[t], minref);
2615		space_reftree_destroy(&reftree);
2616	}
2617	mutex_exit(&vd->vdev_dtl_lock);
2618}
2619
2620int
2621vdev_dtl_load(vdev_t *vd)
2622{
2623	spa_t *spa = vd->vdev_spa;
2624	objset_t *mos = spa->spa_meta_objset;
2625	int error = 0;
2626
2627	if (vd->vdev_ops->vdev_op_leaf && vd->vdev_dtl_object != 0) {
2628		ASSERT(vdev_is_concrete(vd));
2629
2630		error = space_map_open(&vd->vdev_dtl_sm, mos,
2631		    vd->vdev_dtl_object, 0, -1ULL, 0);
2632		if (error)
2633			return (error);
2634		ASSERT(vd->vdev_dtl_sm != NULL);
2635
2636		mutex_enter(&vd->vdev_dtl_lock);
2637		error = space_map_load(vd->vdev_dtl_sm,
2638		    vd->vdev_dtl[DTL_MISSING], SM_ALLOC);
2639		mutex_exit(&vd->vdev_dtl_lock);
2640
2641		return (error);
2642	}
2643
2644	for (int c = 0; c < vd->vdev_children; c++) {
2645		error = vdev_dtl_load(vd->vdev_child[c]);
2646		if (error != 0)
2647			break;
2648	}
2649
2650	return (error);
2651}
2652
2653static void
2654vdev_zap_allocation_data(vdev_t *vd, dmu_tx_t *tx)
2655{
2656	spa_t *spa = vd->vdev_spa;
2657	objset_t *mos = spa->spa_meta_objset;
2658	vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
2659	const char *string;
2660
2661	ASSERT(alloc_bias != VDEV_BIAS_NONE);
2662
2663	string =
2664	    (alloc_bias == VDEV_BIAS_LOG) ? VDEV_ALLOC_BIAS_LOG :
2665	    (alloc_bias == VDEV_BIAS_SPECIAL) ? VDEV_ALLOC_BIAS_SPECIAL :
2666	    (alloc_bias == VDEV_BIAS_DEDUP) ? VDEV_ALLOC_BIAS_DEDUP : NULL;
2667
2668	ASSERT(string != NULL);
2669	VERIFY0(zap_add(mos, vd->vdev_top_zap, VDEV_TOP_ZAP_ALLOCATION_BIAS,
2670	    1, strlen(string) + 1, string, tx));
2671
2672	if (alloc_bias == VDEV_BIAS_SPECIAL || alloc_bias == VDEV_BIAS_DEDUP) {
2673		spa_activate_allocation_classes(spa, tx);
2674	}
2675}
2676
2677void
2678vdev_destroy_unlink_zap(vdev_t *vd, uint64_t zapobj, dmu_tx_t *tx)
2679{
2680	spa_t *spa = vd->vdev_spa;
2681
2682	VERIFY0(zap_destroy(spa->spa_meta_objset, zapobj, tx));
2683	VERIFY0(zap_remove_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
2684	    zapobj, tx));
2685}
2686
2687uint64_t
2688vdev_create_link_zap(vdev_t *vd, dmu_tx_t *tx)
2689{
2690	spa_t *spa = vd->vdev_spa;
2691	uint64_t zap = zap_create(spa->spa_meta_objset, DMU_OTN_ZAP_METADATA,
2692	    DMU_OT_NONE, 0, tx);
2693
2694	ASSERT(zap != 0);
2695	VERIFY0(zap_add_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
2696	    zap, tx));
2697
2698	return (zap);
2699}
2700
2701void
2702vdev_construct_zaps(vdev_t *vd, dmu_tx_t *tx)
2703{
2704	if (vd->vdev_ops != &vdev_hole_ops &&
2705	    vd->vdev_ops != &vdev_missing_ops &&
2706	    vd->vdev_ops != &vdev_root_ops &&
2707	    !vd->vdev_top->vdev_removing) {
2708		if (vd->vdev_ops->vdev_op_leaf && vd->vdev_leaf_zap == 0) {
2709			vd->vdev_leaf_zap = vdev_create_link_zap(vd, tx);
2710		}
2711		if (vd == vd->vdev_top && vd->vdev_top_zap == 0) {
2712			vd->vdev_top_zap = vdev_create_link_zap(vd, tx);
2713			if (vd->vdev_alloc_bias != VDEV_BIAS_NONE)
2714				vdev_zap_allocation_data(vd, tx);
2715		}
2716	}
2717
2718	for (uint64_t i = 0; i < vd->vdev_children; i++) {
2719		vdev_construct_zaps(vd->vdev_child[i], tx);
2720	}
2721}
2722
2723void
2724vdev_dtl_sync(vdev_t *vd, uint64_t txg)
2725{
2726	spa_t *spa = vd->vdev_spa;
2727	range_tree_t *rt = vd->vdev_dtl[DTL_MISSING];
2728	objset_t *mos = spa->spa_meta_objset;
2729	range_tree_t *rtsync;
2730	dmu_tx_t *tx;
2731	uint64_t object = space_map_object(vd->vdev_dtl_sm);
2732
2733	ASSERT(vdev_is_concrete(vd));
2734	ASSERT(vd->vdev_ops->vdev_op_leaf);
2735
2736	tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
2737
2738	if (vd->vdev_detached || vd->vdev_top->vdev_removing) {
2739		mutex_enter(&vd->vdev_dtl_lock);
2740		space_map_free(vd->vdev_dtl_sm, tx);
2741		space_map_close(vd->vdev_dtl_sm);
2742		vd->vdev_dtl_sm = NULL;
2743		mutex_exit(&vd->vdev_dtl_lock);
2744
2745		/*
2746		 * We only destroy the leaf ZAP for detached leaves or for
2747		 * removed log devices. Removed data devices handle leaf ZAP
2748		 * cleanup later, once cancellation is no longer possible.
2749		 */
2750		if (vd->vdev_leaf_zap != 0 && (vd->vdev_detached ||
2751		    vd->vdev_top->vdev_islog)) {
2752			vdev_destroy_unlink_zap(vd, vd->vdev_leaf_zap, tx);
2753			vd->vdev_leaf_zap = 0;
2754		}
2755
2756		dmu_tx_commit(tx);
2757		return;
2758	}
2759
2760	if (vd->vdev_dtl_sm == NULL) {
2761		uint64_t new_object;
2762
2763		new_object = space_map_alloc(mos, zfs_vdev_dtl_sm_blksz, tx);
2764		VERIFY3U(new_object, !=, 0);
2765
2766		VERIFY0(space_map_open(&vd->vdev_dtl_sm, mos, new_object,
2767		    0, -1ULL, 0));
2768		ASSERT(vd->vdev_dtl_sm != NULL);
2769	}
2770
2771	rtsync = range_tree_create(NULL, NULL);
2772
2773	mutex_enter(&vd->vdev_dtl_lock);
2774	range_tree_walk(rt, range_tree_add, rtsync);
2775	mutex_exit(&vd->vdev_dtl_lock);
2776
2777	space_map_truncate(vd->vdev_dtl_sm, zfs_vdev_dtl_sm_blksz, tx);
2778	space_map_write(vd->vdev_dtl_sm, rtsync, SM_ALLOC, SM_NO_VDEVID, tx);
2779	range_tree_vacate(rtsync, NULL, NULL);
2780
2781	range_tree_destroy(rtsync);
2782
2783	/*
2784	 * If the object for the space map has changed then dirty
2785	 * the top level so that we update the config.
2786	 */
2787	if (object != space_map_object(vd->vdev_dtl_sm)) {
2788		vdev_dbgmsg(vd, "txg %llu, spa %s, DTL old object %llu, "
2789		    "new object %llu", (u_longlong_t)txg, spa_name(spa),
2790		    (u_longlong_t)object,
2791		    (u_longlong_t)space_map_object(vd->vdev_dtl_sm));
2792		vdev_config_dirty(vd->vdev_top);
2793	}
2794
2795	dmu_tx_commit(tx);
2796}
2797
2798/*
2799 * Determine whether the specified vdev can be offlined/detached/removed
2800 * without losing data.
2801 */
2802boolean_t
2803vdev_dtl_required(vdev_t *vd)
2804{
2805	spa_t *spa = vd->vdev_spa;
2806	vdev_t *tvd = vd->vdev_top;
2807	uint8_t cant_read = vd->vdev_cant_read;
2808	boolean_t required;
2809
2810	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2811
2812	if (vd == spa->spa_root_vdev || vd == tvd)
2813		return (B_TRUE);
2814
2815	/*
2816	 * Temporarily mark the device as unreadable, and then determine
2817	 * whether this results in any DTL outages in the top-level vdev.
2818	 * If not, we can safely offline/detach/remove the device.
2819	 */
2820	vd->vdev_cant_read = B_TRUE;
2821	vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2822	required = !vdev_dtl_empty(tvd, DTL_OUTAGE);
2823	vd->vdev_cant_read = cant_read;
2824	vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2825
2826	if (!required && zio_injection_enabled)
2827		required = !!zio_handle_device_injection(vd, NULL, ECHILD);
2828
2829	return (required);
2830}
2831
2832/*
2833 * Determine if resilver is needed, and if so the txg range.
2834 */
2835boolean_t
2836vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
2837{
2838	boolean_t needed = B_FALSE;
2839	uint64_t thismin = UINT64_MAX;
2840	uint64_t thismax = 0;
2841
2842	if (vd->vdev_children == 0) {
2843		mutex_enter(&vd->vdev_dtl_lock);
2844		if (!range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
2845		    vdev_writeable(vd)) {
2846
2847			thismin = vdev_dtl_min(vd);
2848			thismax = vdev_dtl_max(vd);
2849			needed = B_TRUE;
2850		}
2851		mutex_exit(&vd->vdev_dtl_lock);
2852	} else {
2853		for (int c = 0; c < vd->vdev_children; c++) {
2854			vdev_t *cvd = vd->vdev_child[c];
2855			uint64_t cmin, cmax;
2856
2857			if (vdev_resilver_needed(cvd, &cmin, &cmax)) {
2858				thismin = MIN(thismin, cmin);
2859				thismax = MAX(thismax, cmax);
2860				needed = B_TRUE;
2861			}
2862		}
2863	}
2864
2865	if (needed && minp) {
2866		*minp = thismin;
2867		*maxp = thismax;
2868	}
2869	return (needed);
2870}
2871
2872/*
2873 * Gets the checkpoint space map object from the vdev's ZAP.
2874 * Returns the spacemap object, or 0 if it wasn't in the ZAP
2875 * or the ZAP doesn't exist yet.
2876 */
2877int
2878vdev_checkpoint_sm_object(vdev_t *vd)
2879{
2880	ASSERT0(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER));
2881	if (vd->vdev_top_zap == 0) {
2882		return (0);
2883	}
2884
2885	uint64_t sm_obj = 0;
2886	int err = zap_lookup(spa_meta_objset(vd->vdev_spa), vd->vdev_top_zap,
2887	    VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1, &sm_obj);
2888
2889	ASSERT(err == 0 || err == ENOENT);
2890
2891	return (sm_obj);
2892}
2893
2894int
2895vdev_load(vdev_t *vd)
2896{
2897	int error = 0;
2898	/*
2899	 * Recursively load all children.
2900	 */
2901	for (int c = 0; c < vd->vdev_children; c++) {
2902		error = vdev_load(vd->vdev_child[c]);
2903		if (error != 0) {
2904			return (error);
2905		}
2906	}
2907
2908	vdev_set_deflate_ratio(vd);
2909
2910	/*
2911	 * On spa_load path, grab the allocation bias from our zap
2912	 */
2913	if (vd == vd->vdev_top && vd->vdev_top_zap != 0) {
2914		spa_t *spa = vd->vdev_spa;
2915		char bias_str[64];
2916
2917		if (zap_lookup(spa->spa_meta_objset, vd->vdev_top_zap,
2918		    VDEV_TOP_ZAP_ALLOCATION_BIAS, 1, sizeof (bias_str),
2919		    bias_str) == 0) {
2920			ASSERT(vd->vdev_alloc_bias == VDEV_BIAS_NONE);
2921			vd->vdev_alloc_bias = vdev_derive_alloc_bias(bias_str);
2922		}
2923	}
2924
2925	/*
2926	 * If this is a top-level vdev, initialize its metaslabs.
2927	 */
2928	if (vd == vd->vdev_top && vdev_is_concrete(vd)) {
2929		vdev_metaslab_group_create(vd);
2930
2931		if (vd->vdev_ashift == 0 || vd->vdev_asize == 0) {
2932			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2933			    VDEV_AUX_CORRUPT_DATA);
2934			vdev_dbgmsg(vd, "vdev_load: invalid size. ashift=%llu, "
2935			    "asize=%llu", (u_longlong_t)vd->vdev_ashift,
2936			    (u_longlong_t)vd->vdev_asize);
2937			return (SET_ERROR(ENXIO));
2938		}
2939
2940		error = vdev_metaslab_init(vd, 0);
2941		if (error != 0) {
2942			vdev_dbgmsg(vd, "vdev_load: metaslab_init failed "
2943			    "[error=%d]", error);
2944			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2945			    VDEV_AUX_CORRUPT_DATA);
2946			return (error);
2947		}
2948
2949		uint64_t checkpoint_sm_obj = vdev_checkpoint_sm_object(vd);
2950		if (checkpoint_sm_obj != 0) {
2951			objset_t *mos = spa_meta_objset(vd->vdev_spa);
2952			ASSERT(vd->vdev_asize != 0);
2953			ASSERT3P(vd->vdev_checkpoint_sm, ==, NULL);
2954
2955			error = space_map_open(&vd->vdev_checkpoint_sm,
2956			    mos, checkpoint_sm_obj, 0, vd->vdev_asize,
2957			    vd->vdev_ashift);
2958			if (error != 0) {
2959				vdev_dbgmsg(vd, "vdev_load: space_map_open "
2960				    "failed for checkpoint spacemap (obj %llu) "
2961				    "[error=%d]",
2962				    (u_longlong_t)checkpoint_sm_obj, error);
2963				return (error);
2964			}
2965			ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
2966
2967			/*
2968			 * Since the checkpoint_sm contains free entries
2969			 * exclusively we can use space_map_allocated() to
2970			 * indicate the cumulative checkpointed space that
2971			 * has been freed.
2972			 */
2973			vd->vdev_stat.vs_checkpoint_space =
2974			    -space_map_allocated(vd->vdev_checkpoint_sm);
2975			vd->vdev_spa->spa_checkpoint_info.sci_dspace +=
2976			    vd->vdev_stat.vs_checkpoint_space;
2977		}
2978	}
2979
2980	/*
2981	 * If this is a leaf vdev, load its DTL.
2982	 */
2983	if (vd->vdev_ops->vdev_op_leaf && (error = vdev_dtl_load(vd)) != 0) {
2984		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2985		    VDEV_AUX_CORRUPT_DATA);
2986		vdev_dbgmsg(vd, "vdev_load: vdev_dtl_load failed "
2987		    "[error=%d]", error);
2988		return (error);
2989	}
2990
2991	uint64_t obsolete_sm_object = vdev_obsolete_sm_object(vd);
2992	if (obsolete_sm_object != 0) {
2993		objset_t *mos = vd->vdev_spa->spa_meta_objset;
2994		ASSERT(vd->vdev_asize != 0);
2995		ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
2996
2997		if ((error = space_map_open(&vd->vdev_obsolete_sm, mos,
2998		    obsolete_sm_object, 0, vd->vdev_asize, 0))) {
2999			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3000			    VDEV_AUX_CORRUPT_DATA);
3001			vdev_dbgmsg(vd, "vdev_load: space_map_open failed for "
3002			    "obsolete spacemap (obj %llu) [error=%d]",
3003			    (u_longlong_t)obsolete_sm_object, error);
3004			return (error);
3005		}
3006	}
3007
3008	return (0);
3009}
3010
3011/*
3012 * The special vdev case is used for hot spares and l2cache devices.  Its
3013 * sole purpose it to set the vdev state for the associated vdev.  To do this,
3014 * we make sure that we can open the underlying device, then try to read the
3015 * label, and make sure that the label is sane and that it hasn't been
3016 * repurposed to another pool.
3017 */
3018int
3019vdev_validate_aux(vdev_t *vd)
3020{
3021	nvlist_t *label;
3022	uint64_t guid, version;
3023	uint64_t state;
3024
3025	if (!vdev_readable(vd))
3026		return (0);
3027
3028	if ((label = vdev_label_read_config(vd, -1ULL)) == NULL) {
3029		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
3030		    VDEV_AUX_CORRUPT_DATA);
3031		return (-1);
3032	}
3033
3034	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_VERSION, &version) != 0 ||
3035	    !SPA_VERSION_IS_SUPPORTED(version) ||
3036	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0 ||
3037	    guid != vd->vdev_guid ||
3038	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE, &state) != 0) {
3039		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
3040		    VDEV_AUX_CORRUPT_DATA);
3041		nvlist_free(label);
3042		return (-1);
3043	}
3044
3045	/*
3046	 * We don't actually check the pool state here.  If it's in fact in
3047	 * use by another pool, we update this fact on the fly when requested.
3048	 */
3049	nvlist_free(label);
3050	return (0);
3051}
3052
3053static void
3054vdev_destroy_ms_flush_data(vdev_t *vd, dmu_tx_t *tx)
3055{
3056	objset_t *mos = spa_meta_objset(vd->vdev_spa);
3057
3058	if (vd->vdev_top_zap == 0)
3059		return;
3060
3061	uint64_t object = 0;
3062	int err = zap_lookup(mos, vd->vdev_top_zap,
3063	    VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, sizeof (uint64_t), 1, &object);
3064	if (err == ENOENT)
3065		return;
3066
3067	VERIFY0(dmu_object_free(mos, object, tx));
3068	VERIFY0(zap_remove(mos, vd->vdev_top_zap,
3069	    VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, tx));
3070}
3071
3072/*
3073 * Free the objects used to store this vdev's spacemaps, and the array
3074 * that points to them.
3075 */
3076void
3077vdev_destroy_spacemaps(vdev_t *vd, dmu_tx_t *tx)
3078{
3079	if (vd->vdev_ms_array == 0)
3080		return;
3081
3082	objset_t *mos = vd->vdev_spa->spa_meta_objset;
3083	uint64_t array_count = vd->vdev_asize >> vd->vdev_ms_shift;
3084	size_t array_bytes = array_count * sizeof (uint64_t);
3085	uint64_t *smobj_array = kmem_alloc(array_bytes, KM_SLEEP);
3086	VERIFY0(dmu_read(mos, vd->vdev_ms_array, 0,
3087	    array_bytes, smobj_array, 0));
3088
3089	for (uint64_t i = 0; i < array_count; i++) {
3090		uint64_t smobj = smobj_array[i];
3091		if (smobj == 0)
3092			continue;
3093
3094		space_map_free_obj(mos, smobj, tx);
3095	}
3096
3097	kmem_free(smobj_array, array_bytes);
3098	VERIFY0(dmu_object_free(mos, vd->vdev_ms_array, tx));
3099	vdev_destroy_ms_flush_data(vd, tx);
3100	vd->vdev_ms_array = 0;
3101}
3102
3103static void
3104vdev_remove_empty_log(vdev_t *vd, uint64_t txg)
3105{
3106	spa_t *spa = vd->vdev_spa;
3107
3108	ASSERT(vd->vdev_islog);
3109	ASSERT(vd == vd->vdev_top);
3110	ASSERT3U(txg, ==, spa_syncing_txg(spa));
3111
3112	dmu_tx_t *tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
3113
3114	vdev_destroy_spacemaps(vd, tx);
3115	if (vd->vdev_top_zap != 0) {
3116		vdev_destroy_unlink_zap(vd, vd->vdev_top_zap, tx);
3117		vd->vdev_top_zap = 0;
3118	}
3119
3120	dmu_tx_commit(tx);
3121}
3122
3123void
3124vdev_sync_done(vdev_t *vd, uint64_t txg)
3125{
3126	metaslab_t *msp;
3127	boolean_t reassess = !txg_list_empty(&vd->vdev_ms_list, TXG_CLEAN(txg));
3128
3129	ASSERT(vdev_is_concrete(vd));
3130
3131	while ((msp = txg_list_remove(&vd->vdev_ms_list, TXG_CLEAN(txg)))
3132	    != NULL)
3133		metaslab_sync_done(msp, txg);
3134
3135	if (reassess)
3136		metaslab_sync_reassess(vd->vdev_mg);
3137}
3138
3139void
3140vdev_sync(vdev_t *vd, uint64_t txg)
3141{
3142	spa_t *spa = vd->vdev_spa;
3143	vdev_t *lvd;
3144	metaslab_t *msp;
3145
3146	ASSERT3U(txg, ==, spa->spa_syncing_txg);
3147	dmu_tx_t *tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
3148	if (range_tree_space(vd->vdev_obsolete_segments) > 0) {
3149		ASSERT(vd->vdev_removing ||
3150		    vd->vdev_ops == &vdev_indirect_ops);
3151
3152		vdev_indirect_sync_obsolete(vd, tx);
3153
3154		/*
3155		 * If the vdev is indirect, it can't have dirty
3156		 * metaslabs or DTLs.
3157		 */
3158		if (vd->vdev_ops == &vdev_indirect_ops) {
3159			ASSERT(txg_list_empty(&vd->vdev_ms_list, txg));
3160			ASSERT(txg_list_empty(&vd->vdev_dtl_list, txg));
3161			dmu_tx_commit(tx);
3162			return;
3163		}
3164	}
3165
3166	ASSERT(vdev_is_concrete(vd));
3167
3168	if (vd->vdev_ms_array == 0 && vd->vdev_ms_shift != 0 &&
3169	    !vd->vdev_removing) {
3170		ASSERT(vd == vd->vdev_top);
3171		ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
3172		vd->vdev_ms_array = dmu_object_alloc(spa->spa_meta_objset,
3173		    DMU_OT_OBJECT_ARRAY, 0, DMU_OT_NONE, 0, tx);
3174		ASSERT(vd->vdev_ms_array != 0);
3175		vdev_config_dirty(vd);
3176	}
3177
3178	while ((msp = txg_list_remove(&vd->vdev_ms_list, txg)) != NULL) {
3179		metaslab_sync(msp, txg);
3180		(void) txg_list_add(&vd->vdev_ms_list, msp, TXG_CLEAN(txg));
3181	}
3182
3183	while ((lvd = txg_list_remove(&vd->vdev_dtl_list, txg)) != NULL)
3184		vdev_dtl_sync(lvd, txg);
3185
3186	/*
3187	 * If this is an empty log device being removed, destroy the
3188	 * metadata associated with it.
3189	 */
3190	if (vd->vdev_islog && vd->vdev_stat.vs_alloc == 0 && vd->vdev_removing)
3191		vdev_remove_empty_log(vd, txg);
3192
3193	(void) txg_list_add(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg));
3194	dmu_tx_commit(tx);
3195}
3196
3197uint64_t
3198vdev_psize_to_asize(vdev_t *vd, uint64_t psize)
3199{
3200	return (vd->vdev_ops->vdev_op_asize(vd, psize));
3201}
3202
3203/*
3204 * Mark the given vdev faulted.  A faulted vdev behaves as if the device could
3205 * not be opened, and no I/O is attempted.
3206 */
3207int
3208vdev_fault(spa_t *spa, uint64_t guid, vdev_aux_t aux)
3209{
3210	vdev_t *vd, *tvd;
3211
3212	spa_vdev_state_enter(spa, SCL_NONE);
3213
3214	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3215		return (spa_vdev_state_exit(spa, NULL, ENODEV));
3216
3217	if (!vd->vdev_ops->vdev_op_leaf)
3218		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3219
3220	tvd = vd->vdev_top;
3221
3222	/*
3223	 * We don't directly use the aux state here, but if we do a
3224	 * vdev_reopen(), we need this value to be present to remember why we
3225	 * were faulted.
3226	 */
3227	vd->vdev_label_aux = aux;
3228
3229	/*
3230	 * Faulted state takes precedence over degraded.
3231	 */
3232	vd->vdev_delayed_close = B_FALSE;
3233	vd->vdev_faulted = 1ULL;
3234	vd->vdev_degraded = 0ULL;
3235	vdev_set_state(vd, B_FALSE, VDEV_STATE_FAULTED, aux);
3236
3237	/*
3238	 * If this device has the only valid copy of the data, then
3239	 * back off and simply mark the vdev as degraded instead.
3240	 */
3241	if (!tvd->vdev_islog && vd->vdev_aux == NULL && vdev_dtl_required(vd)) {
3242		vd->vdev_degraded = 1ULL;
3243		vd->vdev_faulted = 0ULL;
3244
3245		/*
3246		 * If we reopen the device and it's not dead, only then do we
3247		 * mark it degraded.
3248		 */
3249		vdev_reopen(tvd);
3250
3251		if (vdev_readable(vd))
3252			vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED, aux);
3253	}
3254
3255	return (spa_vdev_state_exit(spa, vd, 0));
3256}
3257
3258/*
3259 * Mark the given vdev degraded.  A degraded vdev is purely an indication to the
3260 * user that something is wrong.  The vdev continues to operate as normal as far
3261 * as I/O is concerned.
3262 */
3263int
3264vdev_degrade(spa_t *spa, uint64_t guid, vdev_aux_t aux)
3265{
3266	vdev_t *vd;
3267
3268	spa_vdev_state_enter(spa, SCL_NONE);
3269
3270	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3271		return (spa_vdev_state_exit(spa, NULL, ENODEV));
3272
3273	if (!vd->vdev_ops->vdev_op_leaf)
3274		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3275
3276	/*
3277	 * If the vdev is already faulted, then don't do anything.
3278	 */
3279	if (vd->vdev_faulted || vd->vdev_degraded)
3280		return (spa_vdev_state_exit(spa, NULL, 0));
3281
3282	vd->vdev_degraded = 1ULL;
3283	if (!vdev_is_dead(vd))
3284		vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED,
3285		    aux);
3286
3287	return (spa_vdev_state_exit(spa, vd, 0));
3288}
3289
3290/*
3291 * Online the given vdev.
3292 *
3293 * If 'ZFS_ONLINE_UNSPARE' is set, it implies two things.  First, any attached
3294 * spare device should be detached when the device finishes resilvering.
3295 * Second, the online should be treated like a 'test' online case, so no FMA
3296 * events are generated if the device fails to open.
3297 */
3298int
3299vdev_online(spa_t *spa, uint64_t guid, uint64_t flags, vdev_state_t *newstate)
3300{
3301	vdev_t *vd, *tvd, *pvd, *rvd = spa->spa_root_vdev;
3302	boolean_t wasoffline;
3303	vdev_state_t oldstate;
3304
3305	spa_vdev_state_enter(spa, SCL_NONE);
3306
3307	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3308		return (spa_vdev_state_exit(spa, NULL, ENODEV));
3309
3310	if (!vd->vdev_ops->vdev_op_leaf)
3311		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3312
3313	wasoffline = (vd->vdev_offline || vd->vdev_tmpoffline);
3314	oldstate = vd->vdev_state;
3315
3316	tvd = vd->vdev_top;
3317	vd->vdev_offline = B_FALSE;
3318	vd->vdev_tmpoffline = B_FALSE;
3319	vd->vdev_checkremove = !!(flags & ZFS_ONLINE_CHECKREMOVE);
3320	vd->vdev_forcefault = !!(flags & ZFS_ONLINE_FORCEFAULT);
3321
3322	/* XXX - L2ARC 1.0 does not support expansion */
3323	if (!vd->vdev_aux) {
3324		for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
3325			pvd->vdev_expanding = !!(flags & ZFS_ONLINE_EXPAND);
3326	}
3327
3328	vdev_reopen(tvd);
3329	vd->vdev_checkremove = vd->vdev_forcefault = B_FALSE;
3330
3331	if (!vd->vdev_aux) {
3332		for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
3333			pvd->vdev_expanding = B_FALSE;
3334	}
3335
3336	if (newstate)
3337		*newstate = vd->vdev_state;
3338	if ((flags & ZFS_ONLINE_UNSPARE) &&
3339	    !vdev_is_dead(vd) && vd->vdev_parent &&
3340	    vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
3341	    vd->vdev_parent->vdev_child[0] == vd)
3342		vd->vdev_unspare = B_TRUE;
3343
3344	if ((flags & ZFS_ONLINE_EXPAND) || spa->spa_autoexpand) {
3345
3346		/* XXX - L2ARC 1.0 does not support expansion */
3347		if (vd->vdev_aux)
3348			return (spa_vdev_state_exit(spa, vd, ENOTSUP));
3349		spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3350	}
3351
3352	/* Restart initializing if necessary */
3353	mutex_enter(&vd->vdev_initialize_lock);
3354	if (vdev_writeable(vd) &&
3355	    vd->vdev_initialize_thread == NULL &&
3356	    vd->vdev_initialize_state == VDEV_INITIALIZE_ACTIVE) {
3357		(void) vdev_initialize(vd);
3358	}
3359	mutex_exit(&vd->vdev_initialize_lock);
3360
3361	/* Restart trimming if necessary */
3362	mutex_enter(&vd->vdev_trim_lock);
3363	if (vdev_writeable(vd) &&
3364	    vd->vdev_trim_thread == NULL &&
3365	    vd->vdev_trim_state == VDEV_TRIM_ACTIVE) {
3366		(void) vdev_trim(vd, vd->vdev_trim_rate, vd->vdev_trim_partial,
3367		    vd->vdev_trim_secure);
3368	}
3369	mutex_exit(&vd->vdev_trim_lock);
3370
3371	if (wasoffline ||
3372	    (oldstate < VDEV_STATE_DEGRADED &&
3373	    vd->vdev_state >= VDEV_STATE_DEGRADED))
3374		spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_ONLINE);
3375
3376	return (spa_vdev_state_exit(spa, vd, 0));
3377}
3378
3379static int
3380vdev_offline_locked(spa_t *spa, uint64_t guid, uint64_t flags)
3381{
3382	vdev_t *vd, *tvd;
3383	int error = 0;
3384	uint64_t generation;
3385	metaslab_group_t *mg;
3386
3387top:
3388	spa_vdev_state_enter(spa, SCL_ALLOC);
3389
3390	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3391		return (spa_vdev_state_exit(spa, NULL, ENODEV));
3392
3393	if (!vd->vdev_ops->vdev_op_leaf)
3394		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3395
3396	tvd = vd->vdev_top;
3397	mg = tvd->vdev_mg;
3398	generation = spa->spa_config_generation + 1;
3399
3400	/*
3401	 * If the device isn't already offline, try to offline it.
3402	 */
3403	if (!vd->vdev_offline) {
3404		/*
3405		 * If this device has the only valid copy of some data,
3406		 * don't allow it to be offlined. Log devices are always
3407		 * expendable.
3408		 */
3409		if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
3410		    vdev_dtl_required(vd))
3411			return (spa_vdev_state_exit(spa, NULL, EBUSY));
3412
3413		/*
3414		 * If the top-level is a slog and it has had allocations
3415		 * then proceed.  We check that the vdev's metaslab group
3416		 * is not NULL since it's possible that we may have just
3417		 * added this vdev but not yet initialized its metaslabs.
3418		 */
3419		if (tvd->vdev_islog && mg != NULL) {
3420			/*
3421			 * Prevent any future allocations.
3422			 */
3423			metaslab_group_passivate(mg);
3424			(void) spa_vdev_state_exit(spa, vd, 0);
3425
3426			error = spa_reset_logs(spa);
3427
3428			/*
3429			 * If the log device was successfully reset but has
3430			 * checkpointed data, do not offline it.
3431			 */
3432			if (error == 0 &&
3433			    tvd->vdev_checkpoint_sm != NULL) {
3434				error = ZFS_ERR_CHECKPOINT_EXISTS;
3435			}
3436
3437			spa_vdev_state_enter(spa, SCL_ALLOC);
3438
3439			/*
3440			 * Check to see if the config has changed.
3441			 */
3442			if (error || generation != spa->spa_config_generation) {
3443				metaslab_group_activate(mg);
3444				if (error)
3445					return (spa_vdev_state_exit(spa,
3446					    vd, error));
3447				(void) spa_vdev_state_exit(spa, vd, 0);
3448				goto top;
3449			}
3450			ASSERT0(tvd->vdev_stat.vs_alloc);
3451		}
3452
3453		/*
3454		 * Offline this device and reopen its top-level vdev.
3455		 * If the top-level vdev is a log device then just offline
3456		 * it. Otherwise, if this action results in the top-level
3457		 * vdev becoming unusable, undo it and fail the request.
3458		 */
3459		vd->vdev_offline = B_TRUE;
3460		vdev_reopen(tvd);
3461
3462		if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
3463		    vdev_is_dead(tvd)) {
3464			vd->vdev_offline = B_FALSE;
3465			vdev_reopen(tvd);
3466			return (spa_vdev_state_exit(spa, NULL, EBUSY));
3467		}
3468
3469		/*
3470		 * Add the device back into the metaslab rotor so that
3471		 * once we online the device it's open for business.
3472		 */
3473		if (tvd->vdev_islog && mg != NULL)
3474			metaslab_group_activate(mg);
3475	}
3476
3477	vd->vdev_tmpoffline = !!(flags & ZFS_OFFLINE_TEMPORARY);
3478
3479	return (spa_vdev_state_exit(spa, vd, 0));
3480}
3481
3482int
3483vdev_offline(spa_t *spa, uint64_t guid, uint64_t flags)
3484{
3485	int error;
3486
3487	mutex_enter(&spa->spa_vdev_top_lock);
3488	error = vdev_offline_locked(spa, guid, flags);
3489	mutex_exit(&spa->spa_vdev_top_lock);
3490
3491	return (error);
3492}
3493
3494/*
3495 * Clear the error counts associated with this vdev.  Unlike vdev_online() and
3496 * vdev_offline(), we assume the spa config is locked.  We also clear all
3497 * children.  If 'vd' is NULL, then the user wants to clear all vdevs.
3498 */
3499void
3500vdev_clear(spa_t *spa, vdev_t *vd)
3501{
3502	vdev_t *rvd = spa->spa_root_vdev;
3503
3504	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
3505
3506	if (vd == NULL)
3507		vd = rvd;
3508
3509	vd->vdev_stat.vs_read_errors = 0;
3510	vd->vdev_stat.vs_write_errors = 0;
3511	vd->vdev_stat.vs_checksum_errors = 0;
3512
3513	for (int c = 0; c < vd->vdev_children; c++)
3514		vdev_clear(spa, vd->vdev_child[c]);
3515
3516	/*
3517	 * It makes no sense to "clear" an indirect vdev.
3518	 */
3519	if (!vdev_is_concrete(vd))
3520		return;
3521
3522	/*
3523	 * If we're in the FAULTED state or have experienced failed I/O, then
3524	 * clear the persistent state and attempt to reopen the device.  We
3525	 * also mark the vdev config dirty, so that the new faulted state is
3526	 * written out to disk.
3527	 */
3528	if (vd->vdev_faulted || vd->vdev_degraded ||
3529	    !vdev_readable(vd) || !vdev_writeable(vd)) {
3530
3531		/*
3532		 * When reopening in reponse to a clear event, it may be due to
3533		 * a fmadm repair request.  In this case, if the device is
3534		 * still broken, we want to still post the ereport again.
3535		 */
3536		vd->vdev_forcefault = B_TRUE;
3537
3538		vd->vdev_faulted = vd->vdev_degraded = 0ULL;
3539		vd->vdev_cant_read = B_FALSE;
3540		vd->vdev_cant_write = B_FALSE;
3541
3542		vdev_reopen(vd == rvd ? rvd : vd->vdev_top);
3543
3544		vd->vdev_forcefault = B_FALSE;
3545
3546		if (vd != rvd && vdev_writeable(vd->vdev_top))
3547			vdev_state_dirty(vd->vdev_top);
3548
3549		if (vd->vdev_aux == NULL && !vdev_is_dead(vd)) {
3550			if (dsl_scan_resilvering(spa->spa_dsl_pool) &&
3551			    spa_feature_is_enabled(spa,
3552			    SPA_FEATURE_RESILVER_DEFER))
3553				vdev_set_deferred_resilver(spa, vd);
3554			else
3555				spa_async_request(spa, SPA_ASYNC_RESILVER);
3556		}
3557
3558		spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_CLEAR);
3559	}
3560
3561	/*
3562	 * When clearing a FMA-diagnosed fault, we always want to
3563	 * unspare the device, as we assume that the original spare was
3564	 * done in response to the FMA fault.
3565	 */
3566	if (!vdev_is_dead(vd) && vd->vdev_parent != NULL &&
3567	    vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
3568	    vd->vdev_parent->vdev_child[0] == vd)
3569		vd->vdev_unspare = B_TRUE;
3570}
3571
3572boolean_t
3573vdev_is_dead(vdev_t *vd)
3574{
3575	/*
3576	 * Holes and missing devices are always considered "dead".
3577	 * This simplifies the code since we don't have to check for
3578	 * these types of devices in the various code paths.
3579	 * Instead we rely on the fact that we skip over dead devices
3580	 * before issuing I/O to them.
3581	 */
3582	return (vd->vdev_state < VDEV_STATE_DEGRADED ||
3583	    vd->vdev_ops == &vdev_hole_ops ||
3584	    vd->vdev_ops == &vdev_missing_ops);
3585}
3586
3587boolean_t
3588vdev_readable(vdev_t *vd)
3589{
3590	return (!vdev_is_dead(vd) && !vd->vdev_cant_read);
3591}
3592
3593boolean_t
3594vdev_writeable(vdev_t *vd)
3595{
3596	return (!vdev_is_dead(vd) && !vd->vdev_cant_write &&
3597	    vdev_is_concrete(vd));
3598}
3599
3600boolean_t
3601vdev_allocatable(vdev_t *vd)
3602{
3603	uint64_t state = vd->vdev_state;
3604
3605	/*
3606	 * We currently allow allocations from vdevs which may be in the
3607	 * process of reopening (i.e. VDEV_STATE_CLOSED). If the device
3608	 * fails to reopen then we'll catch it later when we're holding
3609	 * the proper locks.  Note that we have to get the vdev state
3610	 * in a local variable because although it changes atomically,
3611	 * we're asking two separate questions about it.
3612	 */
3613	return (!(state < VDEV_STATE_DEGRADED && state != VDEV_STATE_CLOSED) &&
3614	    !vd->vdev_cant_write && vdev_is_concrete(vd) &&
3615	    vd->vdev_mg->mg_initialized);
3616}
3617
3618boolean_t
3619vdev_accessible(vdev_t *vd, zio_t *zio)
3620{
3621	ASSERT(zio->io_vd == vd);
3622
3623	if (vdev_is_dead(vd) || vd->vdev_remove_wanted)
3624		return (B_FALSE);
3625
3626	if (zio->io_type == ZIO_TYPE_READ)
3627		return (!vd->vdev_cant_read);
3628
3629	if (zio->io_type == ZIO_TYPE_WRITE)
3630		return (!vd->vdev_cant_write);
3631
3632	return (B_TRUE);
3633}
3634
3635boolean_t
3636vdev_is_spacemap_addressable(vdev_t *vd)
3637{
3638	if (spa_feature_is_active(vd->vdev_spa, SPA_FEATURE_SPACEMAP_V2))
3639		return (B_TRUE);
3640
3641	/*
3642	 * If double-word space map entries are not enabled we assume
3643	 * 47 bits of the space map entry are dedicated to the entry's
3644	 * offset (see SM_OFFSET_BITS in space_map.h). We then use that
3645	 * to calculate the maximum address that can be described by a
3646	 * space map entry for the given device.
3647	 */
3648	uint64_t shift = vd->vdev_ashift + SM_OFFSET_BITS;
3649
3650	if (shift >= 63) /* detect potential overflow */
3651		return (B_TRUE);
3652
3653	return (vd->vdev_asize < (1ULL << shift));
3654}
3655
3656/*
3657 * Get statistics for the given vdev.
3658 */
3659void
3660vdev_get_stats(vdev_t *vd, vdev_stat_t *vs)
3661{
3662	spa_t *spa = vd->vdev_spa;
3663	vdev_t *rvd = spa->spa_root_vdev;
3664	vdev_t *tvd = vd->vdev_top;
3665
3666	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
3667
3668	mutex_enter(&vd->vdev_stat_lock);
3669	bcopy(&vd->vdev_stat, vs, sizeof (*vs));
3670	vs->vs_timestamp = gethrtime() - vs->vs_timestamp;
3671	vs->vs_state = vd->vdev_state;
3672	vs->vs_rsize = vdev_get_min_asize(vd);
3673	if (vd->vdev_ops->vdev_op_leaf) {
3674		vs->vs_rsize += VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE;
3675		/*
3676		 * Report intializing progress. Since we don't have the
3677		 * initializing locks held, this is only an estimate (although a
3678		 * fairly accurate one).
3679		 */
3680		vs->vs_initialize_bytes_done = vd->vdev_initialize_bytes_done;
3681		vs->vs_initialize_bytes_est = vd->vdev_initialize_bytes_est;
3682		vs->vs_initialize_state = vd->vdev_initialize_state;
3683		vs->vs_initialize_action_time = vd->vdev_initialize_action_time;
3684	}
3685
3686	/*
3687	 * Report manual TRIM progress. Since we don't have
3688	 * the manual TRIM locks held, this is only an
3689	 * estimate (although fairly accurate one).
3690	 */
3691	vs->vs_trim_notsup = !vd->vdev_has_trim;
3692	vs->vs_trim_bytes_done = vd->vdev_trim_bytes_done;
3693	vs->vs_trim_bytes_est = vd->vdev_trim_bytes_est;
3694	vs->vs_trim_state = vd->vdev_trim_state;
3695	vs->vs_trim_action_time = vd->vdev_trim_action_time;
3696
3697	/*
3698	 * Report expandable space on top-level, non-auxillary devices only.
3699	 * The expandable space is reported in terms of metaslab sized units
3700	 * since that determines how much space the pool can expand.
3701	 */
3702	if (vd->vdev_aux == NULL && tvd != NULL) {
3703		vs->vs_esize = P2ALIGN(vd->vdev_max_asize - vd->vdev_asize -
3704		    spa->spa_bootsize, 1ULL << tvd->vdev_ms_shift);
3705	}
3706	if (vd->vdev_aux == NULL && vd == vd->vdev_top &&
3707	    vdev_is_concrete(vd)) {
3708		vs->vs_fragmentation = (vd->vdev_mg != NULL) ?
3709		    vd->vdev_mg->mg_fragmentation : 0;
3710	}
3711	if (vd->vdev_ops->vdev_op_leaf)
3712		vs->vs_resilver_deferred = vd->vdev_resilver_deferred;
3713
3714	/*
3715	 * If we're getting stats on the root vdev, aggregate the I/O counts
3716	 * over all top-level vdevs (i.e. the direct children of the root).
3717	 */
3718	if (vd == rvd) {
3719		for (int c = 0; c < rvd->vdev_children; c++) {
3720			vdev_t *cvd = rvd->vdev_child[c];
3721			vdev_stat_t *cvs = &cvd->vdev_stat;
3722
3723			for (int t = 0; t < VS_ZIO_TYPES; t++) {
3724				vs->vs_ops[t] += cvs->vs_ops[t];
3725				vs->vs_bytes[t] += cvs->vs_bytes[t];
3726			}
3727			cvs->vs_scan_removing = cvd->vdev_removing;
3728		}
3729	}
3730	mutex_exit(&vd->vdev_stat_lock);
3731}
3732
3733void
3734vdev_clear_stats(vdev_t *vd)
3735{
3736	mutex_enter(&vd->vdev_stat_lock);
3737	vd->vdev_stat.vs_space = 0;
3738	vd->vdev_stat.vs_dspace = 0;
3739	vd->vdev_stat.vs_alloc = 0;
3740	mutex_exit(&vd->vdev_stat_lock);
3741}
3742
3743void
3744vdev_scan_stat_init(vdev_t *vd)
3745{
3746	vdev_stat_t *vs = &vd->vdev_stat;
3747
3748	for (int c = 0; c < vd->vdev_children; c++)
3749		vdev_scan_stat_init(vd->vdev_child[c]);
3750
3751	mutex_enter(&vd->vdev_stat_lock);
3752	vs->vs_scan_processed = 0;
3753	mutex_exit(&vd->vdev_stat_lock);
3754}
3755
3756void
3757vdev_stat_update(zio_t *zio, uint64_t psize)
3758{
3759	spa_t *spa = zio->io_spa;
3760	vdev_t *rvd = spa->spa_root_vdev;
3761	vdev_t *vd = zio->io_vd ? zio->io_vd : rvd;
3762	vdev_t *pvd;
3763	uint64_t txg = zio->io_txg;
3764	vdev_stat_t *vs = &vd->vdev_stat;
3765	zio_type_t type = zio->io_type;
3766	int flags = zio->io_flags;
3767
3768	/*
3769	 * If this i/o is a gang leader, it didn't do any actual work.
3770	 */
3771	if (zio->io_gang_tree)
3772		return;
3773
3774	if (zio->io_error == 0) {
3775		/*
3776		 * If this is a root i/o, don't count it -- we've already
3777		 * counted the top-level vdevs, and vdev_get_stats() will
3778		 * aggregate them when asked.  This reduces contention on
3779		 * the root vdev_stat_lock and implicitly handles blocks
3780		 * that compress away to holes, for which there is no i/o.
3781		 * (Holes never create vdev children, so all the counters
3782		 * remain zero, which is what we want.)
3783		 *
3784		 * Note: this only applies to successful i/o (io_error == 0)
3785		 * because unlike i/o counts, errors are not additive.
3786		 * When reading a ditto block, for example, failure of
3787		 * one top-level vdev does not imply a root-level error.
3788		 */
3789		if (vd == rvd)
3790			return;
3791
3792		ASSERT(vd == zio->io_vd);
3793
3794		if (flags & ZIO_FLAG_IO_BYPASS)
3795			return;
3796
3797		mutex_enter(&vd->vdev_stat_lock);
3798
3799		if (flags & ZIO_FLAG_IO_REPAIR) {
3800			if (flags & ZIO_FLAG_SCAN_THREAD) {
3801				dsl_scan_phys_t *scn_phys =
3802				    &spa->spa_dsl_pool->dp_scan->scn_phys;
3803				uint64_t *processed = &scn_phys->scn_processed;
3804
3805				/* XXX cleanup? */
3806				if (vd->vdev_ops->vdev_op_leaf)
3807					atomic_add_64(processed, psize);
3808				vs->vs_scan_processed += psize;
3809			}
3810
3811			if (flags & ZIO_FLAG_SELF_HEAL)
3812				vs->vs_self_healed += psize;
3813		}
3814
3815		zio_type_t vs_type = type;
3816
3817		/*
3818		 * TRIM ops and bytes are reported to user space as
3819		 * ZIO_TYPE_IOCTL.  This is done to preserve the
3820		 * vdev_stat_t structure layout for user space.
3821		 */
3822		if (type == ZIO_TYPE_TRIM)
3823			vs_type = ZIO_TYPE_IOCTL;
3824
3825		vs->vs_ops[vs_type]++;
3826		vs->vs_bytes[vs_type] += psize;
3827
3828		mutex_exit(&vd->vdev_stat_lock);
3829		return;
3830	}
3831
3832	if (flags & ZIO_FLAG_SPECULATIVE)
3833		return;
3834
3835	/*
3836	 * If this is an I/O error that is going to be retried, then ignore the
3837	 * error.  Otherwise, the user may interpret B_FAILFAST I/O errors as
3838	 * hard errors, when in reality they can happen for any number of
3839	 * innocuous reasons (bus resets, MPxIO link failure, etc).
3840	 */
3841	if (zio->io_error == EIO &&
3842	    !(zio->io_flags & ZIO_FLAG_IO_RETRY))
3843		return;
3844
3845	/*
3846	 * Intent logs writes won't propagate their error to the root
3847	 * I/O so don't mark these types of failures as pool-level
3848	 * errors.
3849	 */
3850	if (zio->io_vd == NULL && (zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
3851		return;
3852
3853	mutex_enter(&vd->vdev_stat_lock);
3854	if (type == ZIO_TYPE_READ && !vdev_is_dead(vd)) {
3855		if (zio->io_error == ECKSUM)
3856			vs->vs_checksum_errors++;
3857		else
3858			vs->vs_read_errors++;
3859	}
3860	if (type == ZIO_TYPE_WRITE && !vdev_is_dead(vd))
3861		vs->vs_write_errors++;
3862	mutex_exit(&vd->vdev_stat_lock);
3863
3864	if (spa->spa_load_state == SPA_LOAD_NONE &&
3865	    type == ZIO_TYPE_WRITE && txg != 0 &&
3866	    (!(flags & ZIO_FLAG_IO_REPAIR) ||
3867	    (flags & ZIO_FLAG_SCAN_THREAD) ||
3868	    spa->spa_claiming)) {
3869		/*
3870		 * This is either a normal write (not a repair), or it's
3871		 * a repair induced by the scrub thread, or it's a repair
3872		 * made by zil_claim() during spa_load() in the first txg.
3873		 * In the normal case, we commit the DTL change in the same
3874		 * txg as the block was born.  In the scrub-induced repair
3875		 * case, we know that scrubs run in first-pass syncing context,
3876		 * so we commit the DTL change in spa_syncing_txg(spa).
3877		 * In the zil_claim() case, we commit in spa_first_txg(spa).
3878		 *
3879		 * We currently do not make DTL entries for failed spontaneous
3880		 * self-healing writes triggered by normal (non-scrubbing)
3881		 * reads, because we have no transactional context in which to
3882		 * do so -- and it's not clear that it'd be desirable anyway.
3883		 */
3884		if (vd->vdev_ops->vdev_op_leaf) {
3885			uint64_t commit_txg = txg;
3886			if (flags & ZIO_FLAG_SCAN_THREAD) {
3887				ASSERT(flags & ZIO_FLAG_IO_REPAIR);
3888				ASSERT(spa_sync_pass(spa) == 1);
3889				vdev_dtl_dirty(vd, DTL_SCRUB, txg, 1);
3890				commit_txg = spa_syncing_txg(spa);
3891			} else if (spa->spa_claiming) {
3892				ASSERT(flags & ZIO_FLAG_IO_REPAIR);
3893				commit_txg = spa_first_txg(spa);
3894			}
3895			ASSERT(commit_txg >= spa_syncing_txg(spa));
3896			if (vdev_dtl_contains(vd, DTL_MISSING, txg, 1))
3897				return;
3898			for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
3899				vdev_dtl_dirty(pvd, DTL_PARTIAL, txg, 1);
3900			vdev_dirty(vd->vdev_top, VDD_DTL, vd, commit_txg);
3901		}
3902		if (vd != rvd)
3903			vdev_dtl_dirty(vd, DTL_MISSING, txg, 1);
3904	}
3905}
3906
3907int64_t
3908vdev_deflated_space(vdev_t *vd, int64_t space)
3909{
3910	ASSERT((space & (SPA_MINBLOCKSIZE-1)) == 0);
3911	ASSERT(vd->vdev_deflate_ratio != 0 || vd->vdev_isl2cache);
3912
3913	return ((space >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio);
3914}
3915
3916/*
3917 * Update the in-core space usage stats for this vdev, its metaslab class,
3918 * and the root vdev.
3919 */
3920void
3921vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
3922    int64_t space_delta)
3923{
3924	int64_t dspace_delta;
3925	spa_t *spa = vd->vdev_spa;
3926	vdev_t *rvd = spa->spa_root_vdev;
3927
3928	ASSERT(vd == vd->vdev_top);
3929
3930	/*
3931	 * Apply the inverse of the psize-to-asize (ie. RAID-Z) space-expansion
3932	 * factor.  We must calculate this here and not at the root vdev
3933	 * because the root vdev's psize-to-asize is simply the max of its
3934	 * childrens', thus not accurate enough for us.
3935	 */
3936	dspace_delta = vdev_deflated_space(vd, space_delta);
3937
3938	mutex_enter(&vd->vdev_stat_lock);
3939	/* ensure we won't underflow */
3940	if (alloc_delta < 0) {
3941		ASSERT3U(vd->vdev_stat.vs_alloc, >=, -alloc_delta);
3942	}
3943
3944	vd->vdev_stat.vs_alloc += alloc_delta;
3945	vd->vdev_stat.vs_space += space_delta;
3946	vd->vdev_stat.vs_dspace += dspace_delta;
3947	mutex_exit(&vd->vdev_stat_lock);
3948
3949	/* every class but log contributes to root space stats */
3950	if (vd->vdev_mg != NULL && !vd->vdev_islog) {
3951		ASSERT(!vd->vdev_isl2cache);
3952		mutex_enter(&rvd->vdev_stat_lock);
3953		rvd->vdev_stat.vs_alloc += alloc_delta;
3954		rvd->vdev_stat.vs_space += space_delta;
3955		rvd->vdev_stat.vs_dspace += dspace_delta;
3956		mutex_exit(&rvd->vdev_stat_lock);
3957	}
3958	/* Note: metaslab_class_space_update moved to metaslab_space_update */
3959}
3960
3961/*
3962 * Mark a top-level vdev's config as dirty, placing it on the dirty list
3963 * so that it will be written out next time the vdev configuration is synced.
3964 * If the root vdev is specified (vdev_top == NULL), dirty all top-level vdevs.
3965 */
3966void
3967vdev_config_dirty(vdev_t *vd)
3968{
3969	spa_t *spa = vd->vdev_spa;
3970	vdev_t *rvd = spa->spa_root_vdev;
3971	int c;
3972
3973	ASSERT(spa_writeable(spa));
3974
3975	/*
3976	 * If this is an aux vdev (as with l2cache and spare devices), then we
3977	 * update the vdev config manually and set the sync flag.
3978	 */
3979	if (vd->vdev_aux != NULL) {
3980		spa_aux_vdev_t *sav = vd->vdev_aux;
3981		nvlist_t **aux;
3982		uint_t naux;
3983
3984		for (c = 0; c < sav->sav_count; c++) {
3985			if (sav->sav_vdevs[c] == vd)
3986				break;
3987		}
3988
3989		if (c == sav->sav_count) {
3990			/*
3991			 * We're being removed.  There's nothing more to do.
3992			 */
3993			ASSERT(sav->sav_sync == B_TRUE);
3994			return;
3995		}
3996
3997		sav->sav_sync = B_TRUE;
3998
3999		if (nvlist_lookup_nvlist_array(sav->sav_config,
4000		    ZPOOL_CONFIG_L2CACHE, &aux, &naux) != 0) {
4001			VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
4002			    ZPOOL_CONFIG_SPARES, &aux, &naux) == 0);
4003		}
4004
4005		ASSERT(c < naux);
4006
4007		/*
4008		 * Setting the nvlist in the middle if the array is a little
4009		 * sketchy, but it will work.
4010		 */
4011		nvlist_free(aux[c]);
4012		aux[c] = vdev_config_generate(spa, vd, B_TRUE, 0);
4013
4014		return;
4015	}
4016
4017	/*
4018	 * The dirty list is protected by the SCL_CONFIG lock.  The caller
4019	 * must either hold SCL_CONFIG as writer, or must be the sync thread
4020	 * (which holds SCL_CONFIG as reader).  There's only one sync thread,
4021	 * so this is sufficient to ensure mutual exclusion.
4022	 */
4023	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
4024	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
4025	    spa_config_held(spa, SCL_CONFIG, RW_READER)));
4026
4027	if (vd == rvd) {
4028		for (c = 0; c < rvd->vdev_children; c++)
4029			vdev_config_dirty(rvd->vdev_child[c]);
4030	} else {
4031		ASSERT(vd == vd->vdev_top);
4032
4033		if (!list_link_active(&vd->vdev_config_dirty_node) &&
4034		    vdev_is_concrete(vd)) {
4035			list_insert_head(&spa->spa_config_dirty_list, vd);
4036		}
4037	}
4038}
4039
4040void
4041vdev_config_clean(vdev_t *vd)
4042{
4043	spa_t *spa = vd->vdev_spa;
4044
4045	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
4046	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
4047	    spa_config_held(spa, SCL_CONFIG, RW_READER)));
4048
4049	ASSERT(list_link_active(&vd->vdev_config_dirty_node));
4050	list_remove(&spa->spa_config_dirty_list, vd);
4051}
4052
4053/*
4054 * Mark a top-level vdev's state as dirty, so that the next pass of
4055 * spa_sync() can convert this into vdev_config_dirty().  We distinguish
4056 * the state changes from larger config changes because they require
4057 * much less locking, and are often needed for administrative actions.
4058 */
4059void
4060vdev_state_dirty(vdev_t *vd)
4061{
4062	spa_t *spa = vd->vdev_spa;
4063
4064	ASSERT(spa_writeable(spa));
4065	ASSERT(vd == vd->vdev_top);
4066
4067	/*
4068	 * The state list is protected by the SCL_STATE lock.  The caller
4069	 * must either hold SCL_STATE as writer, or must be the sync thread
4070	 * (which holds SCL_STATE as reader).  There's only one sync thread,
4071	 * so this is sufficient to ensure mutual exclusion.
4072	 */
4073	ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
4074	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
4075	    spa_config_held(spa, SCL_STATE, RW_READER)));
4076
4077	if (!list_link_active(&vd->vdev_state_dirty_node) &&
4078	    vdev_is_concrete(vd))
4079		list_insert_head(&spa->spa_state_dirty_list, vd);
4080}
4081
4082void
4083vdev_state_clean(vdev_t *vd)
4084{
4085	spa_t *spa = vd->vdev_spa;
4086
4087	ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
4088	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
4089	    spa_config_held(spa, SCL_STATE, RW_READER)));
4090
4091	ASSERT(list_link_active(&vd->vdev_state_dirty_node));
4092	list_remove(&spa->spa_state_dirty_list, vd);
4093}
4094
4095/*
4096 * Propagate vdev state up from children to parent.
4097 */
4098void
4099vdev_propagate_state(vdev_t *vd)
4100{
4101	spa_t *spa = vd->vdev_spa;
4102	vdev_t *rvd = spa->spa_root_vdev;
4103	int degraded = 0, faulted = 0;
4104	int corrupted = 0;
4105	vdev_t *child;
4106
4107	if (vd->vdev_children > 0) {
4108		for (int c = 0; c < vd->vdev_children; c++) {
4109			child = vd->vdev_child[c];
4110
4111			/*
4112			 * Don't factor holes or indirect vdevs into the
4113			 * decision.
4114			 */
4115			if (!vdev_is_concrete(child))
4116				continue;
4117
4118			if (!vdev_readable(child) ||
4119			    (!vdev_writeable(child) && spa_writeable(spa))) {
4120				/*
4121				 * Root special: if there is a top-level log
4122				 * device, treat the root vdev as if it were
4123				 * degraded.
4124				 */
4125				if (child->vdev_islog && vd == rvd)
4126					degraded++;
4127				else
4128					faulted++;
4129			} else if (child->vdev_state <= VDEV_STATE_DEGRADED) {
4130				degraded++;
4131			}
4132
4133			if (child->vdev_stat.vs_aux == VDEV_AUX_CORRUPT_DATA)
4134				corrupted++;
4135		}
4136
4137		vd->vdev_ops->vdev_op_state_change(vd, faulted, degraded);
4138
4139		/*
4140		 * Root special: if there is a top-level vdev that cannot be
4141		 * opened due to corrupted metadata, then propagate the root
4142		 * vdev's aux state as 'corrupt' rather than 'insufficient
4143		 * replicas'.
4144		 */
4145		if (corrupted && vd == rvd &&
4146		    rvd->vdev_state == VDEV_STATE_CANT_OPEN)
4147			vdev_set_state(rvd, B_FALSE, VDEV_STATE_CANT_OPEN,
4148			    VDEV_AUX_CORRUPT_DATA);
4149	}
4150
4151	if (vd->vdev_parent)
4152		vdev_propagate_state(vd->vdev_parent);
4153}
4154
4155/*
4156 * Set a vdev's state.  If this is during an open, we don't update the parent
4157 * state, because we're in the process of opening children depth-first.
4158 * Otherwise, we propagate the change to the parent.
4159 *
4160 * If this routine places a device in a faulted state, an appropriate ereport is
4161 * generated.
4162 */
4163void
4164vdev_set_state(vdev_t *vd, boolean_t isopen, vdev_state_t state, vdev_aux_t aux)
4165{
4166	uint64_t save_state;
4167	spa_t *spa = vd->vdev_spa;
4168
4169	if (state == vd->vdev_state) {
4170		vd->vdev_stat.vs_aux = aux;
4171		return;
4172	}
4173
4174	save_state = vd->vdev_state;
4175
4176	vd->vdev_state = state;
4177	vd->vdev_stat.vs_aux = aux;
4178
4179	/*
4180	 * If we are setting the vdev state to anything but an open state, then
4181	 * always close the underlying device unless the device has requested
4182	 * a delayed close (i.e. we're about to remove or fault the device).
4183	 * Otherwise, we keep accessible but invalid devices open forever.
4184	 * We don't call vdev_close() itself, because that implies some extra
4185	 * checks (offline, etc) that we don't want here.  This is limited to
4186	 * leaf devices, because otherwise closing the device will affect other
4187	 * children.
4188	 */
4189	if (!vd->vdev_delayed_close && vdev_is_dead(vd) &&
4190	    vd->vdev_ops->vdev_op_leaf)
4191		vd->vdev_ops->vdev_op_close(vd);
4192
4193	/*
4194	 * If we have brought this vdev back into service, we need
4195	 * to notify fmd so that it can gracefully repair any outstanding
4196	 * cases due to a missing device.  We do this in all cases, even those
4197	 * that probably don't correlate to a repaired fault.  This is sure to
4198	 * catch all cases, and we let the zfs-retire agent sort it out.  If
4199	 * this is a transient state it's OK, as the retire agent will
4200	 * double-check the state of the vdev before repairing it.
4201	 */
4202	if (state == VDEV_STATE_HEALTHY && vd->vdev_ops->vdev_op_leaf &&
4203	    vd->vdev_prevstate != state)
4204		zfs_post_state_change(spa, vd);
4205
4206	if (vd->vdev_removed &&
4207	    state == VDEV_STATE_CANT_OPEN &&
4208	    (aux == VDEV_AUX_OPEN_FAILED || vd->vdev_checkremove)) {
4209		/*
4210		 * If the previous state is set to VDEV_STATE_REMOVED, then this
4211		 * device was previously marked removed and someone attempted to
4212		 * reopen it.  If this failed due to a nonexistent device, then
4213		 * keep the device in the REMOVED state.  We also let this be if
4214		 * it is one of our special test online cases, which is only
4215		 * attempting to online the device and shouldn't generate an FMA
4216		 * fault.
4217		 */
4218		vd->vdev_state = VDEV_STATE_REMOVED;
4219		vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
4220	} else if (state == VDEV_STATE_REMOVED) {
4221		vd->vdev_removed = B_TRUE;
4222	} else if (state == VDEV_STATE_CANT_OPEN) {
4223		/*
4224		 * If we fail to open a vdev during an import or recovery, we
4225		 * mark it as "not available", which signifies that it was
4226		 * never there to begin with.  Failure to open such a device
4227		 * is not considered an error.
4228		 */
4229		if ((spa_load_state(spa) == SPA_LOAD_IMPORT ||
4230		    spa_load_state(spa) == SPA_LOAD_RECOVER) &&
4231		    vd->vdev_ops->vdev_op_leaf)
4232			vd->vdev_not_present = 1;
4233
4234		/*
4235		 * Post the appropriate ereport.  If the 'prevstate' field is
4236		 * set to something other than VDEV_STATE_UNKNOWN, it indicates
4237		 * that this is part of a vdev_reopen().  In this case, we don't
4238		 * want to post the ereport if the device was already in the
4239		 * CANT_OPEN state beforehand.
4240		 *
4241		 * If the 'checkremove' flag is set, then this is an attempt to
4242		 * online the device in response to an insertion event.  If we
4243		 * hit this case, then we have detected an insertion event for a
4244		 * faulted or offline device that wasn't in the removed state.
4245		 * In this scenario, we don't post an ereport because we are
4246		 * about to replace the device, or attempt an online with
4247		 * vdev_forcefault, which will generate the fault for us.
4248		 */
4249		if ((vd->vdev_prevstate != state || vd->vdev_forcefault) &&
4250		    !vd->vdev_not_present && !vd->vdev_checkremove &&
4251		    vd != spa->spa_root_vdev) {
4252			const char *class;
4253
4254			switch (aux) {
4255			case VDEV_AUX_OPEN_FAILED:
4256				class = FM_EREPORT_ZFS_DEVICE_OPEN_FAILED;
4257				break;
4258			case VDEV_AUX_CORRUPT_DATA:
4259				class = FM_EREPORT_ZFS_DEVICE_CORRUPT_DATA;
4260				break;
4261			case VDEV_AUX_NO_REPLICAS:
4262				class = FM_EREPORT_ZFS_DEVICE_NO_REPLICAS;
4263				break;
4264			case VDEV_AUX_BAD_GUID_SUM:
4265				class = FM_EREPORT_ZFS_DEVICE_BAD_GUID_SUM;
4266				break;
4267			case VDEV_AUX_TOO_SMALL:
4268				class = FM_EREPORT_ZFS_DEVICE_TOO_SMALL;
4269				break;
4270			case VDEV_AUX_BAD_LABEL:
4271				class = FM_EREPORT_ZFS_DEVICE_BAD_LABEL;
4272				break;
4273			case VDEV_AUX_BAD_ASHIFT:
4274				class = FM_EREPORT_ZFS_DEVICE_BAD_ASHIFT;
4275				break;
4276			default:
4277				class = FM_EREPORT_ZFS_DEVICE_UNKNOWN;
4278			}
4279
4280			zfs_ereport_post(class, spa, vd, NULL, NULL,
4281			    save_state, 0);
4282		}
4283
4284		/* Erase any notion of persistent removed state */
4285		vd->vdev_removed = B_FALSE;
4286	} else {
4287		vd->vdev_removed = B_FALSE;
4288	}
4289
4290	if (!isopen && vd->vdev_parent)
4291		vdev_propagate_state(vd->vdev_parent);
4292}
4293
4294boolean_t
4295vdev_children_are_offline(vdev_t *vd)
4296{
4297	ASSERT(!vd->vdev_ops->vdev_op_leaf);
4298
4299	for (uint64_t i = 0; i < vd->vdev_children; i++) {
4300		if (vd->vdev_child[i]->vdev_state != VDEV_STATE_OFFLINE)
4301			return (B_FALSE);
4302	}
4303
4304	return (B_TRUE);
4305}
4306
4307/*
4308 * Check the vdev configuration to ensure that it's capable of supporting
4309 * a root pool. We do not support partial configuration.
4310 * In addition, only a single top-level vdev is allowed.
4311 */
4312boolean_t
4313vdev_is_bootable(vdev_t *vd)
4314{
4315	if (!vd->vdev_ops->vdev_op_leaf) {
4316		char *vdev_type = vd->vdev_ops->vdev_op_type;
4317
4318		if (strcmp(vdev_type, VDEV_TYPE_ROOT) == 0 &&
4319		    vd->vdev_children > 1) {
4320			int non_indirect = 0;
4321
4322			for (int c = 0; c < vd->vdev_children; c++) {
4323				vdev_type =
4324				    vd->vdev_child[c]->vdev_ops->vdev_op_type;
4325				if (strcmp(vdev_type, VDEV_TYPE_INDIRECT) != 0)
4326					non_indirect++;
4327			}
4328			/*
4329			 * non_indirect > 1 means we have more than one
4330			 * top-level vdev, so we stop here.
4331			 */
4332			if (non_indirect > 1)
4333				return (B_FALSE);
4334		} else if (strcmp(vdev_type, VDEV_TYPE_MISSING) == 0) {
4335			return (B_FALSE);
4336		}
4337	}
4338
4339	for (int c = 0; c < vd->vdev_children; c++) {
4340		if (!vdev_is_bootable(vd->vdev_child[c]))
4341			return (B_FALSE);
4342	}
4343	return (B_TRUE);
4344}
4345
4346boolean_t
4347vdev_is_concrete(vdev_t *vd)
4348{
4349	vdev_ops_t *ops = vd->vdev_ops;
4350	if (ops == &vdev_indirect_ops || ops == &vdev_hole_ops ||
4351	    ops == &vdev_missing_ops || ops == &vdev_root_ops) {
4352		return (B_FALSE);
4353	} else {
4354		return (B_TRUE);
4355	}
4356}
4357
4358/*
4359 * Determine if a log device has valid content.  If the vdev was
4360 * removed or faulted in the MOS config then we know that
4361 * the content on the log device has already been written to the pool.
4362 */
4363boolean_t
4364vdev_log_state_valid(vdev_t *vd)
4365{
4366	if (vd->vdev_ops->vdev_op_leaf && !vd->vdev_faulted &&
4367	    !vd->vdev_removed)
4368		return (B_TRUE);
4369
4370	for (int c = 0; c < vd->vdev_children; c++)
4371		if (vdev_log_state_valid(vd->vdev_child[c]))
4372			return (B_TRUE);
4373
4374	return (B_FALSE);
4375}
4376
4377/*
4378 * Expand a vdev if possible.
4379 */
4380void
4381vdev_expand(vdev_t *vd, uint64_t txg)
4382{
4383	ASSERT(vd->vdev_top == vd);
4384	ASSERT(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4385	ASSERT(vdev_is_concrete(vd));
4386
4387	vdev_set_deflate_ratio(vd);
4388
4389	if ((vd->vdev_asize >> vd->vdev_ms_shift) > vd->vdev_ms_count &&
4390	    vdev_is_concrete(vd)) {
4391		vdev_metaslab_group_create(vd);
4392		VERIFY(vdev_metaslab_init(vd, txg) == 0);
4393		vdev_config_dirty(vd);
4394	}
4395}
4396
4397/*
4398 * Split a vdev.
4399 */
4400void
4401vdev_split(vdev_t *vd)
4402{
4403	vdev_t *cvd, *pvd = vd->vdev_parent;
4404
4405	vdev_remove_child(pvd, vd);
4406	vdev_compact_children(pvd);
4407
4408	cvd = pvd->vdev_child[0];
4409	if (pvd->vdev_children == 1) {
4410		vdev_remove_parent(cvd);
4411		cvd->vdev_splitting = B_TRUE;
4412	}
4413	vdev_propagate_state(cvd);
4414}
4415
4416void
4417vdev_deadman(vdev_t *vd)
4418{
4419	for (int c = 0; c < vd->vdev_children; c++) {
4420		vdev_t *cvd = vd->vdev_child[c];
4421
4422		vdev_deadman(cvd);
4423	}
4424
4425	if (vd->vdev_ops->vdev_op_leaf) {
4426		vdev_queue_t *vq = &vd->vdev_queue;
4427
4428		mutex_enter(&vq->vq_lock);
4429		if (avl_numnodes(&vq->vq_active_tree) > 0) {
4430			spa_t *spa = vd->vdev_spa;
4431			zio_t *fio;
4432			uint64_t delta;
4433
4434			/*
4435			 * Look at the head of all the pending queues,
4436			 * if any I/O has been outstanding for longer than
4437			 * the spa_deadman_synctime we panic the system.
4438			 */
4439			fio = avl_first(&vq->vq_active_tree);
4440			delta = gethrtime() - fio->io_timestamp;
4441			if (delta > spa_deadman_synctime(spa)) {
4442				vdev_dbgmsg(vd, "SLOW IO: zio timestamp "
4443				    "%lluns, delta %lluns, last io %lluns",
4444				    fio->io_timestamp, (u_longlong_t)delta,
4445				    vq->vq_io_complete_ts);
4446				fm_panic("I/O to pool '%s' appears to be "
4447				    "hung.", spa_name(spa));
4448			}
4449		}
4450		mutex_exit(&vq->vq_lock);
4451	}
4452}
4453
4454void
4455vdev_set_deferred_resilver(spa_t *spa, vdev_t *vd)
4456{
4457	for (uint64_t i = 0; i < vd->vdev_children; i++)
4458		vdev_set_deferred_resilver(spa, vd->vdev_child[i]);
4459
4460	if (!vd->vdev_ops->vdev_op_leaf || !vdev_writeable(vd) ||
4461	    range_tree_is_empty(vd->vdev_dtl[DTL_MISSING])) {
4462		return;
4463	}
4464
4465	vd->vdev_resilver_deferred = B_TRUE;
4466	spa->spa_resilver_deferred = B_TRUE;
4467}
4468
4469/*
4470 * Translate a logical range to the physical range for the specified vdev_t.
4471 * This function is initially called with a leaf vdev and will walk each
4472 * parent vdev until it reaches a top-level vdev. Once the top-level is
4473 * reached the physical range is initialized and the recursive function
4474 * begins to unwind. As it unwinds it calls the parent's vdev specific
4475 * translation function to do the real conversion.
4476 */
4477void
4478vdev_xlate(vdev_t *vd, const range_seg_t *logical_rs, range_seg_t *physical_rs)
4479{
4480	/*
4481	 * Walk up the vdev tree
4482	 */
4483	if (vd != vd->vdev_top) {
4484		vdev_xlate(vd->vdev_parent, logical_rs, physical_rs);
4485	} else {
4486		/*
4487		 * We've reached the top-level vdev, initialize the
4488		 * physical range to the logical range and start to
4489		 * unwind.
4490		 */
4491		physical_rs->rs_start = logical_rs->rs_start;
4492		physical_rs->rs_end = logical_rs->rs_end;
4493		return;
4494	}
4495
4496	vdev_t *pvd = vd->vdev_parent;
4497	ASSERT3P(pvd, !=, NULL);
4498	ASSERT3P(pvd->vdev_ops->vdev_op_xlate, !=, NULL);
4499
4500	/*
4501	 * As this recursive function unwinds, translate the logical
4502	 * range into its physical components by calling the
4503	 * vdev specific translate function.
4504	 */
4505	range_seg_t intermediate = { { { 0, 0 } } };
4506	pvd->vdev_ops->vdev_op_xlate(vd, physical_rs, &intermediate);
4507
4508	physical_rs->rs_start = intermediate.rs_start;
4509	physical_rs->rs_end = intermediate.rs_end;
4510}
4511