vdev.c revision 284193
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 2011 Nexenta Systems, Inc.  All rights reserved.
25 * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
26 * Copyright 2013 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
27 */
28
29#include <sys/zfs_context.h>
30#include <sys/fm/fs/zfs.h>
31#include <sys/spa.h>
32#include <sys/spa_impl.h>
33#include <sys/dmu.h>
34#include <sys/dmu_tx.h>
35#include <sys/vdev_impl.h>
36#include <sys/uberblock_impl.h>
37#include <sys/metaslab.h>
38#include <sys/metaslab_impl.h>
39#include <sys/space_map.h>
40#include <sys/space_reftree.h>
41#include <sys/zio.h>
42#include <sys/zap.h>
43#include <sys/fs/zfs.h>
44#include <sys/arc.h>
45#include <sys/zil.h>
46#include <sys/dsl_scan.h>
47#include <sys/trim_map.h>
48
49SYSCTL_DECL(_vfs_zfs);
50SYSCTL_NODE(_vfs_zfs, OID_AUTO, vdev, CTLFLAG_RW, 0, "ZFS VDEV");
51
52/*
53 * Virtual device management.
54 */
55
56/*
57 * The limit for ZFS to automatically increase a top-level vdev's ashift
58 * from logical ashift to physical ashift.
59 *
60 * Example: one or more 512B emulation child vdevs
61 *          child->vdev_ashift = 9 (512 bytes)
62 *          child->vdev_physical_ashift = 12 (4096 bytes)
63 *          zfs_max_auto_ashift = 11 (2048 bytes)
64 *          zfs_min_auto_ashift = 9 (512 bytes)
65 *
66 * On pool creation or the addition of a new top-level vdev, ZFS will
67 * increase the ashift of the top-level vdev to 2048 as limited by
68 * zfs_max_auto_ashift.
69 *
70 * Example: one or more 512B emulation child vdevs
71 *          child->vdev_ashift = 9 (512 bytes)
72 *          child->vdev_physical_ashift = 12 (4096 bytes)
73 *          zfs_max_auto_ashift = 13 (8192 bytes)
74 *          zfs_min_auto_ashift = 9 (512 bytes)
75 *
76 * On pool creation or the addition of a new top-level vdev, ZFS will
77 * increase the ashift of the top-level vdev to 4096 to match the
78 * max vdev_physical_ashift.
79 *
80 * Example: one or more 512B emulation child vdevs
81 *          child->vdev_ashift = 9 (512 bytes)
82 *          child->vdev_physical_ashift = 9 (512 bytes)
83 *          zfs_max_auto_ashift = 13 (8192 bytes)
84 *          zfs_min_auto_ashift = 12 (4096 bytes)
85 *
86 * On pool creation or the addition of a new top-level vdev, ZFS will
87 * increase the ashift of the top-level vdev to 4096 to match the
88 * zfs_min_auto_ashift.
89 */
90static uint64_t zfs_max_auto_ashift = SPA_MAXASHIFT;
91static uint64_t zfs_min_auto_ashift = SPA_MINASHIFT;
92
93static int
94sysctl_vfs_zfs_max_auto_ashift(SYSCTL_HANDLER_ARGS)
95{
96	uint64_t val;
97	int err;
98
99	val = zfs_max_auto_ashift;
100	err = sysctl_handle_64(oidp, &val, 0, req);
101	if (err != 0 || req->newptr == NULL)
102		return (err);
103
104	if (val > SPA_MAXASHIFT || val < zfs_min_auto_ashift)
105		return (EINVAL);
106
107	zfs_max_auto_ashift = val;
108
109	return (0);
110}
111SYSCTL_PROC(_vfs_zfs, OID_AUTO, max_auto_ashift,
112    CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
113    sysctl_vfs_zfs_max_auto_ashift, "QU",
114    "Max ashift used when optimising for logical -> physical sectors size on "
115    "new top-level vdevs.");
116
117static int
118sysctl_vfs_zfs_min_auto_ashift(SYSCTL_HANDLER_ARGS)
119{
120	uint64_t val;
121	int err;
122
123	val = zfs_min_auto_ashift;
124	err = sysctl_handle_64(oidp, &val, 0, req);
125	if (err != 0 || req->newptr == NULL)
126		return (err);
127
128	if (val < SPA_MINASHIFT || val > zfs_max_auto_ashift)
129		return (EINVAL);
130
131	zfs_min_auto_ashift = val;
132
133	return (0);
134}
135SYSCTL_PROC(_vfs_zfs, OID_AUTO, min_auto_ashift,
136    CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
137    sysctl_vfs_zfs_min_auto_ashift, "QU",
138    "Min ashift used when creating new top-level vdevs.");
139
140static vdev_ops_t *vdev_ops_table[] = {
141	&vdev_root_ops,
142	&vdev_raidz_ops,
143	&vdev_mirror_ops,
144	&vdev_replacing_ops,
145	&vdev_spare_ops,
146#ifdef _KERNEL
147	&vdev_geom_ops,
148#else
149	&vdev_disk_ops,
150#endif
151	&vdev_file_ops,
152	&vdev_missing_ops,
153	&vdev_hole_ops,
154	NULL
155};
156
157
158/*
159 * Given a vdev type, return the appropriate ops vector.
160 */
161static vdev_ops_t *
162vdev_getops(const char *type)
163{
164	vdev_ops_t *ops, **opspp;
165
166	for (opspp = vdev_ops_table; (ops = *opspp) != NULL; opspp++)
167		if (strcmp(ops->vdev_op_type, type) == 0)
168			break;
169
170	return (ops);
171}
172
173/*
174 * Default asize function: return the MAX of psize with the asize of
175 * all children.  This is what's used by anything other than RAID-Z.
176 */
177uint64_t
178vdev_default_asize(vdev_t *vd, uint64_t psize)
179{
180	uint64_t asize = P2ROUNDUP(psize, 1ULL << vd->vdev_top->vdev_ashift);
181	uint64_t csize;
182
183	for (int c = 0; c < vd->vdev_children; c++) {
184		csize = vdev_psize_to_asize(vd->vdev_child[c], psize);
185		asize = MAX(asize, csize);
186	}
187
188	return (asize);
189}
190
191/*
192 * Get the minimum allocatable size. We define the allocatable size as
193 * the vdev's asize rounded to the nearest metaslab. This allows us to
194 * replace or attach devices which don't have the same physical size but
195 * can still satisfy the same number of allocations.
196 */
197uint64_t
198vdev_get_min_asize(vdev_t *vd)
199{
200	vdev_t *pvd = vd->vdev_parent;
201
202	/*
203	 * If our parent is NULL (inactive spare or cache) or is the root,
204	 * just return our own asize.
205	 */
206	if (pvd == NULL)
207		return (vd->vdev_asize);
208
209	/*
210	 * The top-level vdev just returns the allocatable size rounded
211	 * to the nearest metaslab.
212	 */
213	if (vd == vd->vdev_top)
214		return (P2ALIGN(vd->vdev_asize, 1ULL << vd->vdev_ms_shift));
215
216	/*
217	 * The allocatable space for a raidz vdev is N * sizeof(smallest child),
218	 * so each child must provide at least 1/Nth of its asize.
219	 */
220	if (pvd->vdev_ops == &vdev_raidz_ops)
221		return (pvd->vdev_min_asize / pvd->vdev_children);
222
223	return (pvd->vdev_min_asize);
224}
225
226void
227vdev_set_min_asize(vdev_t *vd)
228{
229	vd->vdev_min_asize = vdev_get_min_asize(vd);
230
231	for (int c = 0; c < vd->vdev_children; c++)
232		vdev_set_min_asize(vd->vdev_child[c]);
233}
234
235vdev_t *
236vdev_lookup_top(spa_t *spa, uint64_t vdev)
237{
238	vdev_t *rvd = spa->spa_root_vdev;
239
240	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
241
242	if (vdev < rvd->vdev_children) {
243		ASSERT(rvd->vdev_child[vdev] != NULL);
244		return (rvd->vdev_child[vdev]);
245	}
246
247	return (NULL);
248}
249
250vdev_t *
251vdev_lookup_by_guid(vdev_t *vd, uint64_t guid)
252{
253	vdev_t *mvd;
254
255	if (vd->vdev_guid == guid)
256		return (vd);
257
258	for (int c = 0; c < vd->vdev_children; c++)
259		if ((mvd = vdev_lookup_by_guid(vd->vdev_child[c], guid)) !=
260		    NULL)
261			return (mvd);
262
263	return (NULL);
264}
265
266void
267vdev_add_child(vdev_t *pvd, vdev_t *cvd)
268{
269	size_t oldsize, newsize;
270	uint64_t id = cvd->vdev_id;
271	vdev_t **newchild;
272
273	ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
274	ASSERT(cvd->vdev_parent == NULL);
275
276	cvd->vdev_parent = pvd;
277
278	if (pvd == NULL)
279		return;
280
281	ASSERT(id >= pvd->vdev_children || pvd->vdev_child[id] == NULL);
282
283	oldsize = pvd->vdev_children * sizeof (vdev_t *);
284	pvd->vdev_children = MAX(pvd->vdev_children, id + 1);
285	newsize = pvd->vdev_children * sizeof (vdev_t *);
286
287	newchild = kmem_zalloc(newsize, KM_SLEEP);
288	if (pvd->vdev_child != NULL) {
289		bcopy(pvd->vdev_child, newchild, oldsize);
290		kmem_free(pvd->vdev_child, oldsize);
291	}
292
293	pvd->vdev_child = newchild;
294	pvd->vdev_child[id] = cvd;
295
296	cvd->vdev_top = (pvd->vdev_top ? pvd->vdev_top: cvd);
297	ASSERT(cvd->vdev_top->vdev_parent->vdev_parent == NULL);
298
299	/*
300	 * Walk up all ancestors to update guid sum.
301	 */
302	for (; pvd != NULL; pvd = pvd->vdev_parent)
303		pvd->vdev_guid_sum += cvd->vdev_guid_sum;
304}
305
306void
307vdev_remove_child(vdev_t *pvd, vdev_t *cvd)
308{
309	int c;
310	uint_t id = cvd->vdev_id;
311
312	ASSERT(cvd->vdev_parent == pvd);
313
314	if (pvd == NULL)
315		return;
316
317	ASSERT(id < pvd->vdev_children);
318	ASSERT(pvd->vdev_child[id] == cvd);
319
320	pvd->vdev_child[id] = NULL;
321	cvd->vdev_parent = NULL;
322
323	for (c = 0; c < pvd->vdev_children; c++)
324		if (pvd->vdev_child[c])
325			break;
326
327	if (c == pvd->vdev_children) {
328		kmem_free(pvd->vdev_child, c * sizeof (vdev_t *));
329		pvd->vdev_child = NULL;
330		pvd->vdev_children = 0;
331	}
332
333	/*
334	 * Walk up all ancestors to update guid sum.
335	 */
336	for (; pvd != NULL; pvd = pvd->vdev_parent)
337		pvd->vdev_guid_sum -= cvd->vdev_guid_sum;
338}
339
340/*
341 * Remove any holes in the child array.
342 */
343void
344vdev_compact_children(vdev_t *pvd)
345{
346	vdev_t **newchild, *cvd;
347	int oldc = pvd->vdev_children;
348	int newc;
349
350	ASSERT(spa_config_held(pvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
351
352	for (int c = newc = 0; c < oldc; c++)
353		if (pvd->vdev_child[c])
354			newc++;
355
356	newchild = kmem_alloc(newc * sizeof (vdev_t *), KM_SLEEP);
357
358	for (int c = newc = 0; c < oldc; c++) {
359		if ((cvd = pvd->vdev_child[c]) != NULL) {
360			newchild[newc] = cvd;
361			cvd->vdev_id = newc++;
362		}
363	}
364
365	kmem_free(pvd->vdev_child, oldc * sizeof (vdev_t *));
366	pvd->vdev_child = newchild;
367	pvd->vdev_children = newc;
368}
369
370/*
371 * Allocate and minimally initialize a vdev_t.
372 */
373vdev_t *
374vdev_alloc_common(spa_t *spa, uint_t id, uint64_t guid, vdev_ops_t *ops)
375{
376	vdev_t *vd;
377
378	vd = kmem_zalloc(sizeof (vdev_t), KM_SLEEP);
379
380	if (spa->spa_root_vdev == NULL) {
381		ASSERT(ops == &vdev_root_ops);
382		spa->spa_root_vdev = vd;
383		spa->spa_load_guid = spa_generate_guid(NULL);
384	}
385
386	if (guid == 0 && ops != &vdev_hole_ops) {
387		if (spa->spa_root_vdev == vd) {
388			/*
389			 * The root vdev's guid will also be the pool guid,
390			 * which must be unique among all pools.
391			 */
392			guid = spa_generate_guid(NULL);
393		} else {
394			/*
395			 * Any other vdev's guid must be unique within the pool.
396			 */
397			guid = spa_generate_guid(spa);
398		}
399		ASSERT(!spa_guid_exists(spa_guid(spa), guid));
400	}
401
402	vd->vdev_spa = spa;
403	vd->vdev_id = id;
404	vd->vdev_guid = guid;
405	vd->vdev_guid_sum = guid;
406	vd->vdev_ops = ops;
407	vd->vdev_state = VDEV_STATE_CLOSED;
408	vd->vdev_ishole = (ops == &vdev_hole_ops);
409
410	mutex_init(&vd->vdev_dtl_lock, NULL, MUTEX_DEFAULT, NULL);
411	mutex_init(&vd->vdev_stat_lock, NULL, MUTEX_DEFAULT, NULL);
412	mutex_init(&vd->vdev_probe_lock, NULL, MUTEX_DEFAULT, NULL);
413	for (int t = 0; t < DTL_TYPES; t++) {
414		vd->vdev_dtl[t] = range_tree_create(NULL, NULL,
415		    &vd->vdev_dtl_lock);
416	}
417	txg_list_create(&vd->vdev_ms_list,
418	    offsetof(struct metaslab, ms_txg_node));
419	txg_list_create(&vd->vdev_dtl_list,
420	    offsetof(struct vdev, vdev_dtl_node));
421	vd->vdev_stat.vs_timestamp = gethrtime();
422	vdev_queue_init(vd);
423	vdev_cache_init(vd);
424
425	return (vd);
426}
427
428/*
429 * Allocate a new vdev.  The 'alloctype' is used to control whether we are
430 * creating a new vdev or loading an existing one - the behavior is slightly
431 * different for each case.
432 */
433int
434vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
435    int alloctype)
436{
437	vdev_ops_t *ops;
438	char *type;
439	uint64_t guid = 0, islog, nparity;
440	vdev_t *vd;
441
442	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
443
444	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
445		return (SET_ERROR(EINVAL));
446
447	if ((ops = vdev_getops(type)) == NULL)
448		return (SET_ERROR(EINVAL));
449
450	/*
451	 * If this is a load, get the vdev guid from the nvlist.
452	 * Otherwise, vdev_alloc_common() will generate one for us.
453	 */
454	if (alloctype == VDEV_ALLOC_LOAD) {
455		uint64_t label_id;
456
457		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID, &label_id) ||
458		    label_id != id)
459			return (SET_ERROR(EINVAL));
460
461		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
462			return (SET_ERROR(EINVAL));
463	} else if (alloctype == VDEV_ALLOC_SPARE) {
464		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
465			return (SET_ERROR(EINVAL));
466	} else if (alloctype == VDEV_ALLOC_L2CACHE) {
467		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
468			return (SET_ERROR(EINVAL));
469	} else if (alloctype == VDEV_ALLOC_ROOTPOOL) {
470		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
471			return (SET_ERROR(EINVAL));
472	}
473
474	/*
475	 * The first allocated vdev must be of type 'root'.
476	 */
477	if (ops != &vdev_root_ops && spa->spa_root_vdev == NULL)
478		return (SET_ERROR(EINVAL));
479
480	/*
481	 * Determine whether we're a log vdev.
482	 */
483	islog = 0;
484	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &islog);
485	if (islog && spa_version(spa) < SPA_VERSION_SLOGS)
486		return (SET_ERROR(ENOTSUP));
487
488	if (ops == &vdev_hole_ops && spa_version(spa) < SPA_VERSION_HOLES)
489		return (SET_ERROR(ENOTSUP));
490
491	/*
492	 * Set the nparity property for RAID-Z vdevs.
493	 */
494	nparity = -1ULL;
495	if (ops == &vdev_raidz_ops) {
496		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
497		    &nparity) == 0) {
498			if (nparity == 0 || nparity > VDEV_RAIDZ_MAXPARITY)
499				return (SET_ERROR(EINVAL));
500			/*
501			 * Previous versions could only support 1 or 2 parity
502			 * device.
503			 */
504			if (nparity > 1 &&
505			    spa_version(spa) < SPA_VERSION_RAIDZ2)
506				return (SET_ERROR(ENOTSUP));
507			if (nparity > 2 &&
508			    spa_version(spa) < SPA_VERSION_RAIDZ3)
509				return (SET_ERROR(ENOTSUP));
510		} else {
511			/*
512			 * We require the parity to be specified for SPAs that
513			 * support multiple parity levels.
514			 */
515			if (spa_version(spa) >= SPA_VERSION_RAIDZ2)
516				return (SET_ERROR(EINVAL));
517			/*
518			 * Otherwise, we default to 1 parity device for RAID-Z.
519			 */
520			nparity = 1;
521		}
522	} else {
523		nparity = 0;
524	}
525	ASSERT(nparity != -1ULL);
526
527	vd = vdev_alloc_common(spa, id, guid, ops);
528
529	vd->vdev_islog = islog;
530	vd->vdev_nparity = nparity;
531
532	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &vd->vdev_path) == 0)
533		vd->vdev_path = spa_strdup(vd->vdev_path);
534	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &vd->vdev_devid) == 0)
535		vd->vdev_devid = spa_strdup(vd->vdev_devid);
536	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PHYS_PATH,
537	    &vd->vdev_physpath) == 0)
538		vd->vdev_physpath = spa_strdup(vd->vdev_physpath);
539	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_FRU, &vd->vdev_fru) == 0)
540		vd->vdev_fru = spa_strdup(vd->vdev_fru);
541
542	/*
543	 * Set the whole_disk property.  If it's not specified, leave the value
544	 * as -1.
545	 */
546	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
547	    &vd->vdev_wholedisk) != 0)
548		vd->vdev_wholedisk = -1ULL;
549
550	/*
551	 * Look for the 'not present' flag.  This will only be set if the device
552	 * was not present at the time of import.
553	 */
554	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
555	    &vd->vdev_not_present);
556
557	/*
558	 * Get the alignment requirement.
559	 */
560	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT, &vd->vdev_ashift);
561
562	/*
563	 * Retrieve the vdev creation time.
564	 */
565	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_CREATE_TXG,
566	    &vd->vdev_crtxg);
567
568	/*
569	 * If we're a top-level vdev, try to load the allocation parameters.
570	 */
571	if (parent && !parent->vdev_parent &&
572	    (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
573		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
574		    &vd->vdev_ms_array);
575		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
576		    &vd->vdev_ms_shift);
577		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASIZE,
578		    &vd->vdev_asize);
579		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVING,
580		    &vd->vdev_removing);
581	}
582
583	if (parent && !parent->vdev_parent && alloctype != VDEV_ALLOC_ATTACH) {
584		ASSERT(alloctype == VDEV_ALLOC_LOAD ||
585		    alloctype == VDEV_ALLOC_ADD ||
586		    alloctype == VDEV_ALLOC_SPLIT ||
587		    alloctype == VDEV_ALLOC_ROOTPOOL);
588		vd->vdev_mg = metaslab_group_create(islog ?
589		    spa_log_class(spa) : spa_normal_class(spa), vd);
590	}
591
592	/*
593	 * If we're a leaf vdev, try to load the DTL object and other state.
594	 */
595	if (vd->vdev_ops->vdev_op_leaf &&
596	    (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_L2CACHE ||
597	    alloctype == VDEV_ALLOC_ROOTPOOL)) {
598		if (alloctype == VDEV_ALLOC_LOAD) {
599			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DTL,
600			    &vd->vdev_dtl_object);
601			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_UNSPARE,
602			    &vd->vdev_unspare);
603		}
604
605		if (alloctype == VDEV_ALLOC_ROOTPOOL) {
606			uint64_t spare = 0;
607
608			if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
609			    &spare) == 0 && spare)
610				spa_spare_add(vd);
611		}
612
613		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE,
614		    &vd->vdev_offline);
615
616		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_RESILVER_TXG,
617		    &vd->vdev_resilver_txg);
618
619		/*
620		 * When importing a pool, we want to ignore the persistent fault
621		 * state, as the diagnosis made on another system may not be
622		 * valid in the current context.  Local vdevs will
623		 * remain in the faulted state.
624		 */
625		if (spa_load_state(spa) == SPA_LOAD_OPEN) {
626			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED,
627			    &vd->vdev_faulted);
628			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DEGRADED,
629			    &vd->vdev_degraded);
630			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED,
631			    &vd->vdev_removed);
632
633			if (vd->vdev_faulted || vd->vdev_degraded) {
634				char *aux;
635
636				vd->vdev_label_aux =
637				    VDEV_AUX_ERR_EXCEEDED;
638				if (nvlist_lookup_string(nv,
639				    ZPOOL_CONFIG_AUX_STATE, &aux) == 0 &&
640				    strcmp(aux, "external") == 0)
641					vd->vdev_label_aux = VDEV_AUX_EXTERNAL;
642			}
643		}
644	}
645
646	/*
647	 * Add ourselves to the parent's list of children.
648	 */
649	vdev_add_child(parent, vd);
650
651	*vdp = vd;
652
653	return (0);
654}
655
656void
657vdev_free(vdev_t *vd)
658{
659	spa_t *spa = vd->vdev_spa;
660
661	/*
662	 * vdev_free() implies closing the vdev first.  This is simpler than
663	 * trying to ensure complicated semantics for all callers.
664	 */
665	vdev_close(vd);
666
667	ASSERT(!list_link_active(&vd->vdev_config_dirty_node));
668	ASSERT(!list_link_active(&vd->vdev_state_dirty_node));
669
670	/*
671	 * Free all children.
672	 */
673	for (int c = 0; c < vd->vdev_children; c++)
674		vdev_free(vd->vdev_child[c]);
675
676	ASSERT(vd->vdev_child == NULL);
677	ASSERT(vd->vdev_guid_sum == vd->vdev_guid);
678
679	/*
680	 * Discard allocation state.
681	 */
682	if (vd->vdev_mg != NULL) {
683		vdev_metaslab_fini(vd);
684		metaslab_group_destroy(vd->vdev_mg);
685	}
686
687	ASSERT0(vd->vdev_stat.vs_space);
688	ASSERT0(vd->vdev_stat.vs_dspace);
689	ASSERT0(vd->vdev_stat.vs_alloc);
690
691	/*
692	 * Remove this vdev from its parent's child list.
693	 */
694	vdev_remove_child(vd->vdev_parent, vd);
695
696	ASSERT(vd->vdev_parent == NULL);
697
698	/*
699	 * Clean up vdev structure.
700	 */
701	vdev_queue_fini(vd);
702	vdev_cache_fini(vd);
703
704	if (vd->vdev_path)
705		spa_strfree(vd->vdev_path);
706	if (vd->vdev_devid)
707		spa_strfree(vd->vdev_devid);
708	if (vd->vdev_physpath)
709		spa_strfree(vd->vdev_physpath);
710	if (vd->vdev_fru)
711		spa_strfree(vd->vdev_fru);
712
713	if (vd->vdev_isspare)
714		spa_spare_remove(vd);
715	if (vd->vdev_isl2cache)
716		spa_l2cache_remove(vd);
717
718	txg_list_destroy(&vd->vdev_ms_list);
719	txg_list_destroy(&vd->vdev_dtl_list);
720
721	mutex_enter(&vd->vdev_dtl_lock);
722	space_map_close(vd->vdev_dtl_sm);
723	for (int t = 0; t < DTL_TYPES; t++) {
724		range_tree_vacate(vd->vdev_dtl[t], NULL, NULL);
725		range_tree_destroy(vd->vdev_dtl[t]);
726	}
727	mutex_exit(&vd->vdev_dtl_lock);
728
729	mutex_destroy(&vd->vdev_dtl_lock);
730	mutex_destroy(&vd->vdev_stat_lock);
731	mutex_destroy(&vd->vdev_probe_lock);
732
733	if (vd == spa->spa_root_vdev)
734		spa->spa_root_vdev = NULL;
735
736	kmem_free(vd, sizeof (vdev_t));
737}
738
739/*
740 * Transfer top-level vdev state from svd to tvd.
741 */
742static void
743vdev_top_transfer(vdev_t *svd, vdev_t *tvd)
744{
745	spa_t *spa = svd->vdev_spa;
746	metaslab_t *msp;
747	vdev_t *vd;
748	int t;
749
750	ASSERT(tvd == tvd->vdev_top);
751
752	tvd->vdev_ms_array = svd->vdev_ms_array;
753	tvd->vdev_ms_shift = svd->vdev_ms_shift;
754	tvd->vdev_ms_count = svd->vdev_ms_count;
755
756	svd->vdev_ms_array = 0;
757	svd->vdev_ms_shift = 0;
758	svd->vdev_ms_count = 0;
759
760	if (tvd->vdev_mg)
761		ASSERT3P(tvd->vdev_mg, ==, svd->vdev_mg);
762	tvd->vdev_mg = svd->vdev_mg;
763	tvd->vdev_ms = svd->vdev_ms;
764
765	svd->vdev_mg = NULL;
766	svd->vdev_ms = NULL;
767
768	if (tvd->vdev_mg != NULL)
769		tvd->vdev_mg->mg_vd = tvd;
770
771	tvd->vdev_stat.vs_alloc = svd->vdev_stat.vs_alloc;
772	tvd->vdev_stat.vs_space = svd->vdev_stat.vs_space;
773	tvd->vdev_stat.vs_dspace = svd->vdev_stat.vs_dspace;
774
775	svd->vdev_stat.vs_alloc = 0;
776	svd->vdev_stat.vs_space = 0;
777	svd->vdev_stat.vs_dspace = 0;
778
779	for (t = 0; t < TXG_SIZE; t++) {
780		while ((msp = txg_list_remove(&svd->vdev_ms_list, t)) != NULL)
781			(void) txg_list_add(&tvd->vdev_ms_list, msp, t);
782		while ((vd = txg_list_remove(&svd->vdev_dtl_list, t)) != NULL)
783			(void) txg_list_add(&tvd->vdev_dtl_list, vd, t);
784		if (txg_list_remove_this(&spa->spa_vdev_txg_list, svd, t))
785			(void) txg_list_add(&spa->spa_vdev_txg_list, tvd, t);
786	}
787
788	if (list_link_active(&svd->vdev_config_dirty_node)) {
789		vdev_config_clean(svd);
790		vdev_config_dirty(tvd);
791	}
792
793	if (list_link_active(&svd->vdev_state_dirty_node)) {
794		vdev_state_clean(svd);
795		vdev_state_dirty(tvd);
796	}
797
798	tvd->vdev_deflate_ratio = svd->vdev_deflate_ratio;
799	svd->vdev_deflate_ratio = 0;
800
801	tvd->vdev_islog = svd->vdev_islog;
802	svd->vdev_islog = 0;
803}
804
805static void
806vdev_top_update(vdev_t *tvd, vdev_t *vd)
807{
808	if (vd == NULL)
809		return;
810
811	vd->vdev_top = tvd;
812
813	for (int c = 0; c < vd->vdev_children; c++)
814		vdev_top_update(tvd, vd->vdev_child[c]);
815}
816
817/*
818 * Add a mirror/replacing vdev above an existing vdev.
819 */
820vdev_t *
821vdev_add_parent(vdev_t *cvd, vdev_ops_t *ops)
822{
823	spa_t *spa = cvd->vdev_spa;
824	vdev_t *pvd = cvd->vdev_parent;
825	vdev_t *mvd;
826
827	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
828
829	mvd = vdev_alloc_common(spa, cvd->vdev_id, 0, ops);
830
831	mvd->vdev_asize = cvd->vdev_asize;
832	mvd->vdev_min_asize = cvd->vdev_min_asize;
833	mvd->vdev_max_asize = cvd->vdev_max_asize;
834	mvd->vdev_ashift = cvd->vdev_ashift;
835	mvd->vdev_logical_ashift = cvd->vdev_logical_ashift;
836	mvd->vdev_physical_ashift = cvd->vdev_physical_ashift;
837	mvd->vdev_state = cvd->vdev_state;
838	mvd->vdev_crtxg = cvd->vdev_crtxg;
839
840	vdev_remove_child(pvd, cvd);
841	vdev_add_child(pvd, mvd);
842	cvd->vdev_id = mvd->vdev_children;
843	vdev_add_child(mvd, cvd);
844	vdev_top_update(cvd->vdev_top, cvd->vdev_top);
845
846	if (mvd == mvd->vdev_top)
847		vdev_top_transfer(cvd, mvd);
848
849	return (mvd);
850}
851
852/*
853 * Remove a 1-way mirror/replacing vdev from the tree.
854 */
855void
856vdev_remove_parent(vdev_t *cvd)
857{
858	vdev_t *mvd = cvd->vdev_parent;
859	vdev_t *pvd = mvd->vdev_parent;
860
861	ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
862
863	ASSERT(mvd->vdev_children == 1);
864	ASSERT(mvd->vdev_ops == &vdev_mirror_ops ||
865	    mvd->vdev_ops == &vdev_replacing_ops ||
866	    mvd->vdev_ops == &vdev_spare_ops);
867	cvd->vdev_ashift = mvd->vdev_ashift;
868	cvd->vdev_logical_ashift = mvd->vdev_logical_ashift;
869	cvd->vdev_physical_ashift = mvd->vdev_physical_ashift;
870
871	vdev_remove_child(mvd, cvd);
872	vdev_remove_child(pvd, mvd);
873
874	/*
875	 * If cvd will replace mvd as a top-level vdev, preserve mvd's guid.
876	 * Otherwise, we could have detached an offline device, and when we
877	 * go to import the pool we'll think we have two top-level vdevs,
878	 * instead of a different version of the same top-level vdev.
879	 */
880	if (mvd->vdev_top == mvd) {
881		uint64_t guid_delta = mvd->vdev_guid - cvd->vdev_guid;
882		cvd->vdev_orig_guid = cvd->vdev_guid;
883		cvd->vdev_guid += guid_delta;
884		cvd->vdev_guid_sum += guid_delta;
885	}
886	cvd->vdev_id = mvd->vdev_id;
887	vdev_add_child(pvd, cvd);
888	vdev_top_update(cvd->vdev_top, cvd->vdev_top);
889
890	if (cvd == cvd->vdev_top)
891		vdev_top_transfer(mvd, cvd);
892
893	ASSERT(mvd->vdev_children == 0);
894	vdev_free(mvd);
895}
896
897int
898vdev_metaslab_init(vdev_t *vd, uint64_t txg)
899{
900	spa_t *spa = vd->vdev_spa;
901	objset_t *mos = spa->spa_meta_objset;
902	uint64_t m;
903	uint64_t oldc = vd->vdev_ms_count;
904	uint64_t newc = vd->vdev_asize >> vd->vdev_ms_shift;
905	metaslab_t **mspp;
906	int error;
907
908	ASSERT(txg == 0 || spa_config_held(spa, SCL_ALLOC, RW_WRITER));
909
910	/*
911	 * This vdev is not being allocated from yet or is a hole.
912	 */
913	if (vd->vdev_ms_shift == 0)
914		return (0);
915
916	ASSERT(!vd->vdev_ishole);
917
918	/*
919	 * Compute the raidz-deflation ratio.  Note, we hard-code
920	 * in 128k (1 << 17) because it is the current "typical" blocksize.
921	 * Even if SPA_MAXBLOCKSIZE changes, this algorithm must never change,
922	 * or we will inconsistently account for existing bp's.
923	 */
924	vd->vdev_deflate_ratio = (1 << 17) /
925	    (vdev_psize_to_asize(vd, 1 << 17) >> SPA_MINBLOCKSHIFT);
926
927	ASSERT(oldc <= newc);
928
929	mspp = kmem_zalloc(newc * sizeof (*mspp), KM_SLEEP);
930
931	if (oldc != 0) {
932		bcopy(vd->vdev_ms, mspp, oldc * sizeof (*mspp));
933		kmem_free(vd->vdev_ms, oldc * sizeof (*mspp));
934	}
935
936	vd->vdev_ms = mspp;
937	vd->vdev_ms_count = newc;
938
939	for (m = oldc; m < newc; m++) {
940		uint64_t object = 0;
941
942		if (txg == 0) {
943			error = dmu_read(mos, vd->vdev_ms_array,
944			    m * sizeof (uint64_t), sizeof (uint64_t), &object,
945			    DMU_READ_PREFETCH);
946			if (error)
947				return (error);
948		}
949		vd->vdev_ms[m] = metaslab_init(vd->vdev_mg, m, object, txg);
950	}
951
952	if (txg == 0)
953		spa_config_enter(spa, SCL_ALLOC, FTAG, RW_WRITER);
954
955	/*
956	 * If the vdev is being removed we don't activate
957	 * the metaslabs since we want to ensure that no new
958	 * allocations are performed on this device.
959	 */
960	if (oldc == 0 && !vd->vdev_removing)
961		metaslab_group_activate(vd->vdev_mg);
962
963	if (txg == 0)
964		spa_config_exit(spa, SCL_ALLOC, FTAG);
965
966	return (0);
967}
968
969void
970vdev_metaslab_fini(vdev_t *vd)
971{
972	uint64_t m;
973	uint64_t count = vd->vdev_ms_count;
974
975	if (vd->vdev_ms != NULL) {
976		metaslab_group_passivate(vd->vdev_mg);
977		for (m = 0; m < count; m++) {
978			metaslab_t *msp = vd->vdev_ms[m];
979
980			if (msp != NULL)
981				metaslab_fini(msp);
982		}
983		kmem_free(vd->vdev_ms, count * sizeof (metaslab_t *));
984		vd->vdev_ms = NULL;
985	}
986}
987
988typedef struct vdev_probe_stats {
989	boolean_t	vps_readable;
990	boolean_t	vps_writeable;
991	int		vps_flags;
992} vdev_probe_stats_t;
993
994static void
995vdev_probe_done(zio_t *zio)
996{
997	spa_t *spa = zio->io_spa;
998	vdev_t *vd = zio->io_vd;
999	vdev_probe_stats_t *vps = zio->io_private;
1000
1001	ASSERT(vd->vdev_probe_zio != NULL);
1002
1003	if (zio->io_type == ZIO_TYPE_READ) {
1004		if (zio->io_error == 0)
1005			vps->vps_readable = 1;
1006		if (zio->io_error == 0 && spa_writeable(spa)) {
1007			zio_nowait(zio_write_phys(vd->vdev_probe_zio, vd,
1008			    zio->io_offset, zio->io_size, zio->io_data,
1009			    ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1010			    ZIO_PRIORITY_SYNC_WRITE, vps->vps_flags, B_TRUE));
1011		} else {
1012			zio_buf_free(zio->io_data, zio->io_size);
1013		}
1014	} else if (zio->io_type == ZIO_TYPE_WRITE) {
1015		if (zio->io_error == 0)
1016			vps->vps_writeable = 1;
1017		zio_buf_free(zio->io_data, zio->io_size);
1018	} else if (zio->io_type == ZIO_TYPE_NULL) {
1019		zio_t *pio;
1020
1021		vd->vdev_cant_read |= !vps->vps_readable;
1022		vd->vdev_cant_write |= !vps->vps_writeable;
1023
1024		if (vdev_readable(vd) &&
1025		    (vdev_writeable(vd) || !spa_writeable(spa))) {
1026			zio->io_error = 0;
1027		} else {
1028			ASSERT(zio->io_error != 0);
1029			zfs_ereport_post(FM_EREPORT_ZFS_PROBE_FAILURE,
1030			    spa, vd, NULL, 0, 0);
1031			zio->io_error = SET_ERROR(ENXIO);
1032		}
1033
1034		mutex_enter(&vd->vdev_probe_lock);
1035		ASSERT(vd->vdev_probe_zio == zio);
1036		vd->vdev_probe_zio = NULL;
1037		mutex_exit(&vd->vdev_probe_lock);
1038
1039		while ((pio = zio_walk_parents(zio)) != NULL)
1040			if (!vdev_accessible(vd, pio))
1041				pio->io_error = SET_ERROR(ENXIO);
1042
1043		kmem_free(vps, sizeof (*vps));
1044	}
1045}
1046
1047/*
1048 * Determine whether this device is accessible.
1049 *
1050 * Read and write to several known locations: the pad regions of each
1051 * vdev label but the first, which we leave alone in case it contains
1052 * a VTOC.
1053 */
1054zio_t *
1055vdev_probe(vdev_t *vd, zio_t *zio)
1056{
1057	spa_t *spa = vd->vdev_spa;
1058	vdev_probe_stats_t *vps = NULL;
1059	zio_t *pio;
1060
1061	ASSERT(vd->vdev_ops->vdev_op_leaf);
1062
1063	/*
1064	 * Don't probe the probe.
1065	 */
1066	if (zio && (zio->io_flags & ZIO_FLAG_PROBE))
1067		return (NULL);
1068
1069	/*
1070	 * To prevent 'probe storms' when a device fails, we create
1071	 * just one probe i/o at a time.  All zios that want to probe
1072	 * this vdev will become parents of the probe io.
1073	 */
1074	mutex_enter(&vd->vdev_probe_lock);
1075
1076	if ((pio = vd->vdev_probe_zio) == NULL) {
1077		vps = kmem_zalloc(sizeof (*vps), KM_SLEEP);
1078
1079		vps->vps_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_PROBE |
1080		    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE |
1081		    ZIO_FLAG_TRYHARD;
1082
1083		if (spa_config_held(spa, SCL_ZIO, RW_WRITER)) {
1084			/*
1085			 * vdev_cant_read and vdev_cant_write can only
1086			 * transition from TRUE to FALSE when we have the
1087			 * SCL_ZIO lock as writer; otherwise they can only
1088			 * transition from FALSE to TRUE.  This ensures that
1089			 * any zio looking at these values can assume that
1090			 * failures persist for the life of the I/O.  That's
1091			 * important because when a device has intermittent
1092			 * connectivity problems, we want to ensure that
1093			 * they're ascribed to the device (ENXIO) and not
1094			 * the zio (EIO).
1095			 *
1096			 * Since we hold SCL_ZIO as writer here, clear both
1097			 * values so the probe can reevaluate from first
1098			 * principles.
1099			 */
1100			vps->vps_flags |= ZIO_FLAG_CONFIG_WRITER;
1101			vd->vdev_cant_read = B_FALSE;
1102			vd->vdev_cant_write = B_FALSE;
1103		}
1104
1105		vd->vdev_probe_zio = pio = zio_null(NULL, spa, vd,
1106		    vdev_probe_done, vps,
1107		    vps->vps_flags | ZIO_FLAG_DONT_PROPAGATE);
1108
1109		/*
1110		 * We can't change the vdev state in this context, so we
1111		 * kick off an async task to do it on our behalf.
1112		 */
1113		if (zio != NULL) {
1114			vd->vdev_probe_wanted = B_TRUE;
1115			spa_async_request(spa, SPA_ASYNC_PROBE);
1116		}
1117	}
1118
1119	if (zio != NULL)
1120		zio_add_child(zio, pio);
1121
1122	mutex_exit(&vd->vdev_probe_lock);
1123
1124	if (vps == NULL) {
1125		ASSERT(zio != NULL);
1126		return (NULL);
1127	}
1128
1129	for (int l = 1; l < VDEV_LABELS; l++) {
1130		zio_nowait(zio_read_phys(pio, vd,
1131		    vdev_label_offset(vd->vdev_psize, l,
1132		    offsetof(vdev_label_t, vl_pad2)),
1133		    VDEV_PAD_SIZE, zio_buf_alloc(VDEV_PAD_SIZE),
1134		    ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1135		    ZIO_PRIORITY_SYNC_READ, vps->vps_flags, B_TRUE));
1136	}
1137
1138	if (zio == NULL)
1139		return (pio);
1140
1141	zio_nowait(pio);
1142	return (NULL);
1143}
1144
1145static void
1146vdev_open_child(void *arg)
1147{
1148	vdev_t *vd = arg;
1149
1150	vd->vdev_open_thread = curthread;
1151	vd->vdev_open_error = vdev_open(vd);
1152	vd->vdev_open_thread = NULL;
1153}
1154
1155boolean_t
1156vdev_uses_zvols(vdev_t *vd)
1157{
1158	if (vd->vdev_path && strncmp(vd->vdev_path, ZVOL_DIR,
1159	    strlen(ZVOL_DIR)) == 0)
1160		return (B_TRUE);
1161	for (int c = 0; c < vd->vdev_children; c++)
1162		if (vdev_uses_zvols(vd->vdev_child[c]))
1163			return (B_TRUE);
1164	return (B_FALSE);
1165}
1166
1167void
1168vdev_open_children(vdev_t *vd)
1169{
1170	taskq_t *tq;
1171	int children = vd->vdev_children;
1172
1173	/*
1174	 * in order to handle pools on top of zvols, do the opens
1175	 * in a single thread so that the same thread holds the
1176	 * spa_namespace_lock
1177	 */
1178	if (B_TRUE || vdev_uses_zvols(vd)) {
1179		for (int c = 0; c < children; c++)
1180			vd->vdev_child[c]->vdev_open_error =
1181			    vdev_open(vd->vdev_child[c]);
1182		return;
1183	}
1184	tq = taskq_create("vdev_open", children, minclsyspri,
1185	    children, children, TASKQ_PREPOPULATE);
1186
1187	for (int c = 0; c < children; c++)
1188		VERIFY(taskq_dispatch(tq, vdev_open_child, vd->vdev_child[c],
1189		    TQ_SLEEP) != 0);
1190
1191	taskq_destroy(tq);
1192}
1193
1194/*
1195 * Prepare a virtual device for access.
1196 */
1197int
1198vdev_open(vdev_t *vd)
1199{
1200	spa_t *spa = vd->vdev_spa;
1201	int error;
1202	uint64_t osize = 0;
1203	uint64_t max_osize = 0;
1204	uint64_t asize, max_asize, psize;
1205	uint64_t logical_ashift = 0;
1206	uint64_t physical_ashift = 0;
1207
1208	ASSERT(vd->vdev_open_thread == curthread ||
1209	    spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1210	ASSERT(vd->vdev_state == VDEV_STATE_CLOSED ||
1211	    vd->vdev_state == VDEV_STATE_CANT_OPEN ||
1212	    vd->vdev_state == VDEV_STATE_OFFLINE);
1213
1214	vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
1215	vd->vdev_cant_read = B_FALSE;
1216	vd->vdev_cant_write = B_FALSE;
1217	vd->vdev_notrim = B_FALSE;
1218	vd->vdev_min_asize = vdev_get_min_asize(vd);
1219
1220	/*
1221	 * If this vdev is not removed, check its fault status.  If it's
1222	 * faulted, bail out of the open.
1223	 */
1224	if (!vd->vdev_removed && vd->vdev_faulted) {
1225		ASSERT(vd->vdev_children == 0);
1226		ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1227		    vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1228		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1229		    vd->vdev_label_aux);
1230		return (SET_ERROR(ENXIO));
1231	} else if (vd->vdev_offline) {
1232		ASSERT(vd->vdev_children == 0);
1233		vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE, VDEV_AUX_NONE);
1234		return (SET_ERROR(ENXIO));
1235	}
1236
1237	error = vd->vdev_ops->vdev_op_open(vd, &osize, &max_osize,
1238	    &logical_ashift, &physical_ashift);
1239
1240	/*
1241	 * Reset the vdev_reopening flag so that we actually close
1242	 * the vdev on error.
1243	 */
1244	vd->vdev_reopening = B_FALSE;
1245	if (zio_injection_enabled && error == 0)
1246		error = zio_handle_device_injection(vd, NULL, ENXIO);
1247
1248	if (error) {
1249		if (vd->vdev_removed &&
1250		    vd->vdev_stat.vs_aux != VDEV_AUX_OPEN_FAILED)
1251			vd->vdev_removed = B_FALSE;
1252
1253		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1254		    vd->vdev_stat.vs_aux);
1255		return (error);
1256	}
1257
1258	vd->vdev_removed = B_FALSE;
1259
1260	/*
1261	 * Recheck the faulted flag now that we have confirmed that
1262	 * the vdev is accessible.  If we're faulted, bail.
1263	 */
1264	if (vd->vdev_faulted) {
1265		ASSERT(vd->vdev_children == 0);
1266		ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1267		    vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1268		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1269		    vd->vdev_label_aux);
1270		return (SET_ERROR(ENXIO));
1271	}
1272
1273	if (vd->vdev_degraded) {
1274		ASSERT(vd->vdev_children == 0);
1275		vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1276		    VDEV_AUX_ERR_EXCEEDED);
1277	} else {
1278		vdev_set_state(vd, B_TRUE, VDEV_STATE_HEALTHY, 0);
1279	}
1280
1281	/*
1282	 * For hole or missing vdevs we just return success.
1283	 */
1284	if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops)
1285		return (0);
1286
1287	if (zfs_trim_enabled && !vd->vdev_notrim && vd->vdev_ops->vdev_op_leaf)
1288		trim_map_create(vd);
1289
1290	for (int c = 0; c < vd->vdev_children; c++) {
1291		if (vd->vdev_child[c]->vdev_state != VDEV_STATE_HEALTHY) {
1292			vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1293			    VDEV_AUX_NONE);
1294			break;
1295		}
1296	}
1297
1298	osize = P2ALIGN(osize, (uint64_t)sizeof (vdev_label_t));
1299	max_osize = P2ALIGN(max_osize, (uint64_t)sizeof (vdev_label_t));
1300
1301	if (vd->vdev_children == 0) {
1302		if (osize < SPA_MINDEVSIZE) {
1303			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1304			    VDEV_AUX_TOO_SMALL);
1305			return (SET_ERROR(EOVERFLOW));
1306		}
1307		psize = osize;
1308		asize = osize - (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE);
1309		max_asize = max_osize - (VDEV_LABEL_START_SIZE +
1310		    VDEV_LABEL_END_SIZE);
1311	} else {
1312		if (vd->vdev_parent != NULL && osize < SPA_MINDEVSIZE -
1313		    (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE)) {
1314			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1315			    VDEV_AUX_TOO_SMALL);
1316			return (SET_ERROR(EOVERFLOW));
1317		}
1318		psize = 0;
1319		asize = osize;
1320		max_asize = max_osize;
1321	}
1322
1323	vd->vdev_psize = psize;
1324
1325	/*
1326	 * Make sure the allocatable size hasn't shrunk.
1327	 */
1328	if (asize < vd->vdev_min_asize) {
1329		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1330		    VDEV_AUX_BAD_LABEL);
1331		return (SET_ERROR(EINVAL));
1332	}
1333
1334	vd->vdev_physical_ashift =
1335	    MAX(physical_ashift, vd->vdev_physical_ashift);
1336	vd->vdev_logical_ashift = MAX(logical_ashift, vd->vdev_logical_ashift);
1337	vd->vdev_ashift = MAX(vd->vdev_logical_ashift, vd->vdev_ashift);
1338
1339	if (vd->vdev_logical_ashift > SPA_MAXASHIFT) {
1340		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1341		    VDEV_AUX_ASHIFT_TOO_BIG);
1342		return (EINVAL);
1343	}
1344
1345	if (vd->vdev_asize == 0) {
1346		/*
1347		 * This is the first-ever open, so use the computed values.
1348		 * For testing purposes, a higher ashift can be requested.
1349		 */
1350		vd->vdev_asize = asize;
1351		vd->vdev_max_asize = max_asize;
1352	} else {
1353		/*
1354		 * Make sure the alignment requirement hasn't increased.
1355		 */
1356		if (vd->vdev_ashift > vd->vdev_top->vdev_ashift &&
1357		    vd->vdev_ops->vdev_op_leaf) {
1358			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1359			    VDEV_AUX_BAD_LABEL);
1360			return (EINVAL);
1361		}
1362		vd->vdev_max_asize = max_asize;
1363	}
1364
1365	/*
1366	 * If all children are healthy and the asize has increased,
1367	 * then we've experienced dynamic LUN growth.  If automatic
1368	 * expansion is enabled then use the additional space.
1369	 */
1370	if (vd->vdev_state == VDEV_STATE_HEALTHY && asize > vd->vdev_asize &&
1371	    (vd->vdev_expanding || spa->spa_autoexpand))
1372		vd->vdev_asize = asize;
1373
1374	vdev_set_min_asize(vd);
1375
1376	/*
1377	 * Ensure we can issue some IO before declaring the
1378	 * vdev open for business.
1379	 */
1380	if (vd->vdev_ops->vdev_op_leaf &&
1381	    (error = zio_wait(vdev_probe(vd, NULL))) != 0) {
1382		vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1383		    VDEV_AUX_ERR_EXCEEDED);
1384		return (error);
1385	}
1386
1387	/*
1388	 * If a leaf vdev has a DTL, and seems healthy, then kick off a
1389	 * resilver.  But don't do this if we are doing a reopen for a scrub,
1390	 * since this would just restart the scrub we are already doing.
1391	 */
1392	if (vd->vdev_ops->vdev_op_leaf && !spa->spa_scrub_reopen &&
1393	    vdev_resilver_needed(vd, NULL, NULL))
1394		spa_async_request(spa, SPA_ASYNC_RESILVER);
1395
1396	return (0);
1397}
1398
1399/*
1400 * Called once the vdevs are all opened, this routine validates the label
1401 * contents.  This needs to be done before vdev_load() so that we don't
1402 * inadvertently do repair I/Os to the wrong device.
1403 *
1404 * If 'strict' is false ignore the spa guid check. This is necessary because
1405 * if the machine crashed during a re-guid the new guid might have been written
1406 * to all of the vdev labels, but not the cached config. The strict check
1407 * will be performed when the pool is opened again using the mos config.
1408 *
1409 * This function will only return failure if one of the vdevs indicates that it
1410 * has since been destroyed or exported.  This is only possible if
1411 * /etc/zfs/zpool.cache was readonly at the time.  Otherwise, the vdev state
1412 * will be updated but the function will return 0.
1413 */
1414int
1415vdev_validate(vdev_t *vd, boolean_t strict)
1416{
1417	spa_t *spa = vd->vdev_spa;
1418	nvlist_t *label;
1419	uint64_t guid = 0, top_guid;
1420	uint64_t state;
1421
1422	for (int c = 0; c < vd->vdev_children; c++)
1423		if (vdev_validate(vd->vdev_child[c], strict) != 0)
1424			return (SET_ERROR(EBADF));
1425
1426	/*
1427	 * If the device has already failed, or was marked offline, don't do
1428	 * any further validation.  Otherwise, label I/O will fail and we will
1429	 * overwrite the previous state.
1430	 */
1431	if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
1432		uint64_t aux_guid = 0;
1433		nvlist_t *nvl;
1434		uint64_t txg = spa_last_synced_txg(spa) != 0 ?
1435		    spa_last_synced_txg(spa) : -1ULL;
1436
1437		if ((label = vdev_label_read_config(vd, txg)) == NULL) {
1438			vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1439			    VDEV_AUX_BAD_LABEL);
1440			return (0);
1441		}
1442
1443		/*
1444		 * Determine if this vdev has been split off into another
1445		 * pool.  If so, then refuse to open it.
1446		 */
1447		if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_SPLIT_GUID,
1448		    &aux_guid) == 0 && aux_guid == spa_guid(spa)) {
1449			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1450			    VDEV_AUX_SPLIT_POOL);
1451			nvlist_free(label);
1452			return (0);
1453		}
1454
1455		if (strict && (nvlist_lookup_uint64(label,
1456		    ZPOOL_CONFIG_POOL_GUID, &guid) != 0 ||
1457		    guid != spa_guid(spa))) {
1458			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1459			    VDEV_AUX_CORRUPT_DATA);
1460			nvlist_free(label);
1461			return (0);
1462		}
1463
1464		if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvl)
1465		    != 0 || nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_ORIG_GUID,
1466		    &aux_guid) != 0)
1467			aux_guid = 0;
1468
1469		/*
1470		 * If this vdev just became a top-level vdev because its
1471		 * sibling was detached, it will have adopted the parent's
1472		 * vdev guid -- but the label may or may not be on disk yet.
1473		 * Fortunately, either version of the label will have the
1474		 * same top guid, so if we're a top-level vdev, we can
1475		 * safely compare to that instead.
1476		 *
1477		 * If we split this vdev off instead, then we also check the
1478		 * original pool's guid.  We don't want to consider the vdev
1479		 * corrupt if it is partway through a split operation.
1480		 */
1481		if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
1482		    &guid) != 0 ||
1483		    nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID,
1484		    &top_guid) != 0 ||
1485		    ((vd->vdev_guid != guid && vd->vdev_guid != aux_guid) &&
1486		    (vd->vdev_guid != top_guid || vd != vd->vdev_top))) {
1487			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1488			    VDEV_AUX_CORRUPT_DATA);
1489			nvlist_free(label);
1490			return (0);
1491		}
1492
1493		if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
1494		    &state) != 0) {
1495			vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1496			    VDEV_AUX_CORRUPT_DATA);
1497			nvlist_free(label);
1498			return (0);
1499		}
1500
1501		nvlist_free(label);
1502
1503		/*
1504		 * If this is a verbatim import, no need to check the
1505		 * state of the pool.
1506		 */
1507		if (!(spa->spa_import_flags & ZFS_IMPORT_VERBATIM) &&
1508		    spa_load_state(spa) == SPA_LOAD_OPEN &&
1509		    state != POOL_STATE_ACTIVE)
1510			return (SET_ERROR(EBADF));
1511
1512		/*
1513		 * If we were able to open and validate a vdev that was
1514		 * previously marked permanently unavailable, clear that state
1515		 * now.
1516		 */
1517		if (vd->vdev_not_present)
1518			vd->vdev_not_present = 0;
1519	}
1520
1521	return (0);
1522}
1523
1524/*
1525 * Close a virtual device.
1526 */
1527void
1528vdev_close(vdev_t *vd)
1529{
1530	spa_t *spa = vd->vdev_spa;
1531	vdev_t *pvd = vd->vdev_parent;
1532
1533	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1534
1535	/*
1536	 * If our parent is reopening, then we are as well, unless we are
1537	 * going offline.
1538	 */
1539	if (pvd != NULL && pvd->vdev_reopening)
1540		vd->vdev_reopening = (pvd->vdev_reopening && !vd->vdev_offline);
1541
1542	vd->vdev_ops->vdev_op_close(vd);
1543
1544	vdev_cache_purge(vd);
1545
1546	if (vd->vdev_ops->vdev_op_leaf)
1547		trim_map_destroy(vd);
1548
1549	/*
1550	 * We record the previous state before we close it, so that if we are
1551	 * doing a reopen(), we don't generate FMA ereports if we notice that
1552	 * it's still faulted.
1553	 */
1554	vd->vdev_prevstate = vd->vdev_state;
1555
1556	if (vd->vdev_offline)
1557		vd->vdev_state = VDEV_STATE_OFFLINE;
1558	else
1559		vd->vdev_state = VDEV_STATE_CLOSED;
1560	vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
1561}
1562
1563void
1564vdev_hold(vdev_t *vd)
1565{
1566	spa_t *spa = vd->vdev_spa;
1567
1568	ASSERT(spa_is_root(spa));
1569	if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1570		return;
1571
1572	for (int c = 0; c < vd->vdev_children; c++)
1573		vdev_hold(vd->vdev_child[c]);
1574
1575	if (vd->vdev_ops->vdev_op_leaf)
1576		vd->vdev_ops->vdev_op_hold(vd);
1577}
1578
1579void
1580vdev_rele(vdev_t *vd)
1581{
1582	spa_t *spa = vd->vdev_spa;
1583
1584	ASSERT(spa_is_root(spa));
1585	for (int c = 0; c < vd->vdev_children; c++)
1586		vdev_rele(vd->vdev_child[c]);
1587
1588	if (vd->vdev_ops->vdev_op_leaf)
1589		vd->vdev_ops->vdev_op_rele(vd);
1590}
1591
1592/*
1593 * Reopen all interior vdevs and any unopened leaves.  We don't actually
1594 * reopen leaf vdevs which had previously been opened as they might deadlock
1595 * on the spa_config_lock.  Instead we only obtain the leaf's physical size.
1596 * If the leaf has never been opened then open it, as usual.
1597 */
1598void
1599vdev_reopen(vdev_t *vd)
1600{
1601	spa_t *spa = vd->vdev_spa;
1602
1603	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1604
1605	/* set the reopening flag unless we're taking the vdev offline */
1606	vd->vdev_reopening = !vd->vdev_offline;
1607	vdev_close(vd);
1608	(void) vdev_open(vd);
1609
1610	/*
1611	 * Call vdev_validate() here to make sure we have the same device.
1612	 * Otherwise, a device with an invalid label could be successfully
1613	 * opened in response to vdev_reopen().
1614	 */
1615	if (vd->vdev_aux) {
1616		(void) vdev_validate_aux(vd);
1617		if (vdev_readable(vd) && vdev_writeable(vd) &&
1618		    vd->vdev_aux == &spa->spa_l2cache &&
1619		    !l2arc_vdev_present(vd))
1620			l2arc_add_vdev(spa, vd);
1621	} else {
1622		(void) vdev_validate(vd, B_TRUE);
1623	}
1624
1625	/*
1626	 * Reassess parent vdev's health.
1627	 */
1628	vdev_propagate_state(vd);
1629}
1630
1631int
1632vdev_create(vdev_t *vd, uint64_t txg, boolean_t isreplacing)
1633{
1634	int error;
1635
1636	/*
1637	 * Normally, partial opens (e.g. of a mirror) are allowed.
1638	 * For a create, however, we want to fail the request if
1639	 * there are any components we can't open.
1640	 */
1641	error = vdev_open(vd);
1642
1643	if (error || vd->vdev_state != VDEV_STATE_HEALTHY) {
1644		vdev_close(vd);
1645		return (error ? error : ENXIO);
1646	}
1647
1648	/*
1649	 * Recursively load DTLs and initialize all labels.
1650	 */
1651	if ((error = vdev_dtl_load(vd)) != 0 ||
1652	    (error = vdev_label_init(vd, txg, isreplacing ?
1653	    VDEV_LABEL_REPLACE : VDEV_LABEL_CREATE)) != 0) {
1654		vdev_close(vd);
1655		return (error);
1656	}
1657
1658	return (0);
1659}
1660
1661void
1662vdev_metaslab_set_size(vdev_t *vd)
1663{
1664	/*
1665	 * Aim for roughly 200 metaslabs per vdev.
1666	 */
1667	vd->vdev_ms_shift = highbit64(vd->vdev_asize / 200);
1668	vd->vdev_ms_shift = MAX(vd->vdev_ms_shift, SPA_MAXBLOCKSHIFT);
1669}
1670
1671/*
1672 * Maximize performance by inflating the configured ashift for top level
1673 * vdevs to be as close to the physical ashift as possible while maintaining
1674 * administrator defined limits and ensuring it doesn't go below the
1675 * logical ashift.
1676 */
1677void
1678vdev_ashift_optimize(vdev_t *vd)
1679{
1680	if (vd == vd->vdev_top) {
1681		if (vd->vdev_ashift < vd->vdev_physical_ashift) {
1682			vd->vdev_ashift = MIN(
1683			    MAX(zfs_max_auto_ashift, vd->vdev_ashift),
1684			    MAX(zfs_min_auto_ashift, vd->vdev_physical_ashift));
1685		} else {
1686			/*
1687			 * Unusual case where logical ashift > physical ashift
1688			 * so we can't cap the calculated ashift based on max
1689			 * ashift as that would cause failures.
1690			 * We still check if we need to increase it to match
1691			 * the min ashift.
1692			 */
1693			vd->vdev_ashift = MAX(zfs_min_auto_ashift,
1694			    vd->vdev_ashift);
1695		}
1696	}
1697}
1698
1699void
1700vdev_dirty(vdev_t *vd, int flags, void *arg, uint64_t txg)
1701{
1702	ASSERT(vd == vd->vdev_top);
1703	ASSERT(!vd->vdev_ishole);
1704	ASSERT(ISP2(flags));
1705	ASSERT(spa_writeable(vd->vdev_spa));
1706
1707	if (flags & VDD_METASLAB)
1708		(void) txg_list_add(&vd->vdev_ms_list, arg, txg);
1709
1710	if (flags & VDD_DTL)
1711		(void) txg_list_add(&vd->vdev_dtl_list, arg, txg);
1712
1713	(void) txg_list_add(&vd->vdev_spa->spa_vdev_txg_list, vd, txg);
1714}
1715
1716void
1717vdev_dirty_leaves(vdev_t *vd, int flags, uint64_t txg)
1718{
1719	for (int c = 0; c < vd->vdev_children; c++)
1720		vdev_dirty_leaves(vd->vdev_child[c], flags, txg);
1721
1722	if (vd->vdev_ops->vdev_op_leaf)
1723		vdev_dirty(vd->vdev_top, flags, vd, txg);
1724}
1725
1726/*
1727 * DTLs.
1728 *
1729 * A vdev's DTL (dirty time log) is the set of transaction groups for which
1730 * the vdev has less than perfect replication.  There are four kinds of DTL:
1731 *
1732 * DTL_MISSING: txgs for which the vdev has no valid copies of the data
1733 *
1734 * DTL_PARTIAL: txgs for which data is available, but not fully replicated
1735 *
1736 * DTL_SCRUB: the txgs that could not be repaired by the last scrub; upon
1737 *	scrub completion, DTL_SCRUB replaces DTL_MISSING in the range of
1738 *	txgs that was scrubbed.
1739 *
1740 * DTL_OUTAGE: txgs which cannot currently be read, whether due to
1741 *	persistent errors or just some device being offline.
1742 *	Unlike the other three, the DTL_OUTAGE map is not generally
1743 *	maintained; it's only computed when needed, typically to
1744 *	determine whether a device can be detached.
1745 *
1746 * For leaf vdevs, DTL_MISSING and DTL_PARTIAL are identical: the device
1747 * either has the data or it doesn't.
1748 *
1749 * For interior vdevs such as mirror and RAID-Z the picture is more complex.
1750 * A vdev's DTL_PARTIAL is the union of its children's DTL_PARTIALs, because
1751 * if any child is less than fully replicated, then so is its parent.
1752 * A vdev's DTL_MISSING is a modified union of its children's DTL_MISSINGs,
1753 * comprising only those txgs which appear in 'maxfaults' or more children;
1754 * those are the txgs we don't have enough replication to read.  For example,
1755 * double-parity RAID-Z can tolerate up to two missing devices (maxfaults == 2);
1756 * thus, its DTL_MISSING consists of the set of txgs that appear in more than
1757 * two child DTL_MISSING maps.
1758 *
1759 * It should be clear from the above that to compute the DTLs and outage maps
1760 * for all vdevs, it suffices to know just the leaf vdevs' DTL_MISSING maps.
1761 * Therefore, that is all we keep on disk.  When loading the pool, or after
1762 * a configuration change, we generate all other DTLs from first principles.
1763 */
1764void
1765vdev_dtl_dirty(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
1766{
1767	range_tree_t *rt = vd->vdev_dtl[t];
1768
1769	ASSERT(t < DTL_TYPES);
1770	ASSERT(vd != vd->vdev_spa->spa_root_vdev);
1771	ASSERT(spa_writeable(vd->vdev_spa));
1772
1773	mutex_enter(rt->rt_lock);
1774	if (!range_tree_contains(rt, txg, size))
1775		range_tree_add(rt, txg, size);
1776	mutex_exit(rt->rt_lock);
1777}
1778
1779boolean_t
1780vdev_dtl_contains(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
1781{
1782	range_tree_t *rt = vd->vdev_dtl[t];
1783	boolean_t dirty = B_FALSE;
1784
1785	ASSERT(t < DTL_TYPES);
1786	ASSERT(vd != vd->vdev_spa->spa_root_vdev);
1787
1788	mutex_enter(rt->rt_lock);
1789	if (range_tree_space(rt) != 0)
1790		dirty = range_tree_contains(rt, txg, size);
1791	mutex_exit(rt->rt_lock);
1792
1793	return (dirty);
1794}
1795
1796boolean_t
1797vdev_dtl_empty(vdev_t *vd, vdev_dtl_type_t t)
1798{
1799	range_tree_t *rt = vd->vdev_dtl[t];
1800	boolean_t empty;
1801
1802	mutex_enter(rt->rt_lock);
1803	empty = (range_tree_space(rt) == 0);
1804	mutex_exit(rt->rt_lock);
1805
1806	return (empty);
1807}
1808
1809/*
1810 * Returns the lowest txg in the DTL range.
1811 */
1812static uint64_t
1813vdev_dtl_min(vdev_t *vd)
1814{
1815	range_seg_t *rs;
1816
1817	ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
1818	ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
1819	ASSERT0(vd->vdev_children);
1820
1821	rs = avl_first(&vd->vdev_dtl[DTL_MISSING]->rt_root);
1822	return (rs->rs_start - 1);
1823}
1824
1825/*
1826 * Returns the highest txg in the DTL.
1827 */
1828static uint64_t
1829vdev_dtl_max(vdev_t *vd)
1830{
1831	range_seg_t *rs;
1832
1833	ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
1834	ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
1835	ASSERT0(vd->vdev_children);
1836
1837	rs = avl_last(&vd->vdev_dtl[DTL_MISSING]->rt_root);
1838	return (rs->rs_end);
1839}
1840
1841/*
1842 * Determine if a resilvering vdev should remove any DTL entries from
1843 * its range. If the vdev was resilvering for the entire duration of the
1844 * scan then it should excise that range from its DTLs. Otherwise, this
1845 * vdev is considered partially resilvered and should leave its DTL
1846 * entries intact. The comment in vdev_dtl_reassess() describes how we
1847 * excise the DTLs.
1848 */
1849static boolean_t
1850vdev_dtl_should_excise(vdev_t *vd)
1851{
1852	spa_t *spa = vd->vdev_spa;
1853	dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
1854
1855	ASSERT0(scn->scn_phys.scn_errors);
1856	ASSERT0(vd->vdev_children);
1857
1858	if (vd->vdev_resilver_txg == 0 ||
1859	    range_tree_space(vd->vdev_dtl[DTL_MISSING]) == 0)
1860		return (B_TRUE);
1861
1862	/*
1863	 * When a resilver is initiated the scan will assign the scn_max_txg
1864	 * value to the highest txg value that exists in all DTLs. If this
1865	 * device's max DTL is not part of this scan (i.e. it is not in
1866	 * the range (scn_min_txg, scn_max_txg] then it is not eligible
1867	 * for excision.
1868	 */
1869	if (vdev_dtl_max(vd) <= scn->scn_phys.scn_max_txg) {
1870		ASSERT3U(scn->scn_phys.scn_min_txg, <=, vdev_dtl_min(vd));
1871		ASSERT3U(scn->scn_phys.scn_min_txg, <, vd->vdev_resilver_txg);
1872		ASSERT3U(vd->vdev_resilver_txg, <=, scn->scn_phys.scn_max_txg);
1873		return (B_TRUE);
1874	}
1875	return (B_FALSE);
1876}
1877
1878/*
1879 * Reassess DTLs after a config change or scrub completion.
1880 */
1881void
1882vdev_dtl_reassess(vdev_t *vd, uint64_t txg, uint64_t scrub_txg, int scrub_done)
1883{
1884	spa_t *spa = vd->vdev_spa;
1885	avl_tree_t reftree;
1886	int minref;
1887
1888	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1889
1890	for (int c = 0; c < vd->vdev_children; c++)
1891		vdev_dtl_reassess(vd->vdev_child[c], txg,
1892		    scrub_txg, scrub_done);
1893
1894	if (vd == spa->spa_root_vdev || vd->vdev_ishole || vd->vdev_aux)
1895		return;
1896
1897	if (vd->vdev_ops->vdev_op_leaf) {
1898		dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
1899
1900		mutex_enter(&vd->vdev_dtl_lock);
1901
1902		/*
1903		 * If we've completed a scan cleanly then determine
1904		 * if this vdev should remove any DTLs. We only want to
1905		 * excise regions on vdevs that were available during
1906		 * the entire duration of this scan.
1907		 */
1908		if (scrub_txg != 0 &&
1909		    (spa->spa_scrub_started ||
1910		    (scn != NULL && scn->scn_phys.scn_errors == 0)) &&
1911		    vdev_dtl_should_excise(vd)) {
1912			/*
1913			 * We completed a scrub up to scrub_txg.  If we
1914			 * did it without rebooting, then the scrub dtl
1915			 * will be valid, so excise the old region and
1916			 * fold in the scrub dtl.  Otherwise, leave the
1917			 * dtl as-is if there was an error.
1918			 *
1919			 * There's little trick here: to excise the beginning
1920			 * of the DTL_MISSING map, we put it into a reference
1921			 * tree and then add a segment with refcnt -1 that
1922			 * covers the range [0, scrub_txg).  This means
1923			 * that each txg in that range has refcnt -1 or 0.
1924			 * We then add DTL_SCRUB with a refcnt of 2, so that
1925			 * entries in the range [0, scrub_txg) will have a
1926			 * positive refcnt -- either 1 or 2.  We then convert
1927			 * the reference tree into the new DTL_MISSING map.
1928			 */
1929			space_reftree_create(&reftree);
1930			space_reftree_add_map(&reftree,
1931			    vd->vdev_dtl[DTL_MISSING], 1);
1932			space_reftree_add_seg(&reftree, 0, scrub_txg, -1);
1933			space_reftree_add_map(&reftree,
1934			    vd->vdev_dtl[DTL_SCRUB], 2);
1935			space_reftree_generate_map(&reftree,
1936			    vd->vdev_dtl[DTL_MISSING], 1);
1937			space_reftree_destroy(&reftree);
1938		}
1939		range_tree_vacate(vd->vdev_dtl[DTL_PARTIAL], NULL, NULL);
1940		range_tree_walk(vd->vdev_dtl[DTL_MISSING],
1941		    range_tree_add, vd->vdev_dtl[DTL_PARTIAL]);
1942		if (scrub_done)
1943			range_tree_vacate(vd->vdev_dtl[DTL_SCRUB], NULL, NULL);
1944		range_tree_vacate(vd->vdev_dtl[DTL_OUTAGE], NULL, NULL);
1945		if (!vdev_readable(vd))
1946			range_tree_add(vd->vdev_dtl[DTL_OUTAGE], 0, -1ULL);
1947		else
1948			range_tree_walk(vd->vdev_dtl[DTL_MISSING],
1949			    range_tree_add, vd->vdev_dtl[DTL_OUTAGE]);
1950
1951		/*
1952		 * If the vdev was resilvering and no longer has any
1953		 * DTLs then reset its resilvering flag and dirty
1954		 * the top level so that we persist the change.
1955		 */
1956		if (vd->vdev_resilver_txg != 0 &&
1957		    range_tree_space(vd->vdev_dtl[DTL_MISSING]) == 0 &&
1958		    range_tree_space(vd->vdev_dtl[DTL_OUTAGE]) == 0) {
1959			vd->vdev_resilver_txg = 0;
1960			vdev_config_dirty(vd->vdev_top);
1961		}
1962
1963		mutex_exit(&vd->vdev_dtl_lock);
1964
1965		if (txg != 0)
1966			vdev_dirty(vd->vdev_top, VDD_DTL, vd, txg);
1967		return;
1968	}
1969
1970	mutex_enter(&vd->vdev_dtl_lock);
1971	for (int t = 0; t < DTL_TYPES; t++) {
1972		/* account for child's outage in parent's missing map */
1973		int s = (t == DTL_MISSING) ? DTL_OUTAGE: t;
1974		if (t == DTL_SCRUB)
1975			continue;			/* leaf vdevs only */
1976		if (t == DTL_PARTIAL)
1977			minref = 1;			/* i.e. non-zero */
1978		else if (vd->vdev_nparity != 0)
1979			minref = vd->vdev_nparity + 1;	/* RAID-Z */
1980		else
1981			minref = vd->vdev_children;	/* any kind of mirror */
1982		space_reftree_create(&reftree);
1983		for (int c = 0; c < vd->vdev_children; c++) {
1984			vdev_t *cvd = vd->vdev_child[c];
1985			mutex_enter(&cvd->vdev_dtl_lock);
1986			space_reftree_add_map(&reftree, cvd->vdev_dtl[s], 1);
1987			mutex_exit(&cvd->vdev_dtl_lock);
1988		}
1989		space_reftree_generate_map(&reftree, vd->vdev_dtl[t], minref);
1990		space_reftree_destroy(&reftree);
1991	}
1992	mutex_exit(&vd->vdev_dtl_lock);
1993}
1994
1995int
1996vdev_dtl_load(vdev_t *vd)
1997{
1998	spa_t *spa = vd->vdev_spa;
1999	objset_t *mos = spa->spa_meta_objset;
2000	int error = 0;
2001
2002	if (vd->vdev_ops->vdev_op_leaf && vd->vdev_dtl_object != 0) {
2003		ASSERT(!vd->vdev_ishole);
2004
2005		error = space_map_open(&vd->vdev_dtl_sm, mos,
2006		    vd->vdev_dtl_object, 0, -1ULL, 0, &vd->vdev_dtl_lock);
2007		if (error)
2008			return (error);
2009		ASSERT(vd->vdev_dtl_sm != NULL);
2010
2011		mutex_enter(&vd->vdev_dtl_lock);
2012
2013		/*
2014		 * Now that we've opened the space_map we need to update
2015		 * the in-core DTL.
2016		 */
2017		space_map_update(vd->vdev_dtl_sm);
2018
2019		error = space_map_load(vd->vdev_dtl_sm,
2020		    vd->vdev_dtl[DTL_MISSING], SM_ALLOC);
2021		mutex_exit(&vd->vdev_dtl_lock);
2022
2023		return (error);
2024	}
2025
2026	for (int c = 0; c < vd->vdev_children; c++) {
2027		error = vdev_dtl_load(vd->vdev_child[c]);
2028		if (error != 0)
2029			break;
2030	}
2031
2032	return (error);
2033}
2034
2035void
2036vdev_dtl_sync(vdev_t *vd, uint64_t txg)
2037{
2038	spa_t *spa = vd->vdev_spa;
2039	range_tree_t *rt = vd->vdev_dtl[DTL_MISSING];
2040	objset_t *mos = spa->spa_meta_objset;
2041	range_tree_t *rtsync;
2042	kmutex_t rtlock;
2043	dmu_tx_t *tx;
2044	uint64_t object = space_map_object(vd->vdev_dtl_sm);
2045
2046	ASSERT(!vd->vdev_ishole);
2047	ASSERT(vd->vdev_ops->vdev_op_leaf);
2048
2049	tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
2050
2051	if (vd->vdev_detached || vd->vdev_top->vdev_removing) {
2052		mutex_enter(&vd->vdev_dtl_lock);
2053		space_map_free(vd->vdev_dtl_sm, tx);
2054		space_map_close(vd->vdev_dtl_sm);
2055		vd->vdev_dtl_sm = NULL;
2056		mutex_exit(&vd->vdev_dtl_lock);
2057		dmu_tx_commit(tx);
2058		return;
2059	}
2060
2061	if (vd->vdev_dtl_sm == NULL) {
2062		uint64_t new_object;
2063
2064		new_object = space_map_alloc(mos, tx);
2065		VERIFY3U(new_object, !=, 0);
2066
2067		VERIFY0(space_map_open(&vd->vdev_dtl_sm, mos, new_object,
2068		    0, -1ULL, 0, &vd->vdev_dtl_lock));
2069		ASSERT(vd->vdev_dtl_sm != NULL);
2070	}
2071
2072	bzero(&rtlock, sizeof(rtlock));
2073	mutex_init(&rtlock, NULL, MUTEX_DEFAULT, NULL);
2074
2075	rtsync = range_tree_create(NULL, NULL, &rtlock);
2076
2077	mutex_enter(&rtlock);
2078
2079	mutex_enter(&vd->vdev_dtl_lock);
2080	range_tree_walk(rt, range_tree_add, rtsync);
2081	mutex_exit(&vd->vdev_dtl_lock);
2082
2083	space_map_truncate(vd->vdev_dtl_sm, tx);
2084	space_map_write(vd->vdev_dtl_sm, rtsync, SM_ALLOC, tx);
2085	range_tree_vacate(rtsync, NULL, NULL);
2086
2087	range_tree_destroy(rtsync);
2088
2089	mutex_exit(&rtlock);
2090	mutex_destroy(&rtlock);
2091
2092	/*
2093	 * If the object for the space map has changed then dirty
2094	 * the top level so that we update the config.
2095	 */
2096	if (object != space_map_object(vd->vdev_dtl_sm)) {
2097		zfs_dbgmsg("txg %llu, spa %s, DTL old object %llu, "
2098		    "new object %llu", txg, spa_name(spa), object,
2099		    space_map_object(vd->vdev_dtl_sm));
2100		vdev_config_dirty(vd->vdev_top);
2101	}
2102
2103	dmu_tx_commit(tx);
2104
2105	mutex_enter(&vd->vdev_dtl_lock);
2106	space_map_update(vd->vdev_dtl_sm);
2107	mutex_exit(&vd->vdev_dtl_lock);
2108}
2109
2110/*
2111 * Determine whether the specified vdev can be offlined/detached/removed
2112 * without losing data.
2113 */
2114boolean_t
2115vdev_dtl_required(vdev_t *vd)
2116{
2117	spa_t *spa = vd->vdev_spa;
2118	vdev_t *tvd = vd->vdev_top;
2119	uint8_t cant_read = vd->vdev_cant_read;
2120	boolean_t required;
2121
2122	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2123
2124	if (vd == spa->spa_root_vdev || vd == tvd)
2125		return (B_TRUE);
2126
2127	/*
2128	 * Temporarily mark the device as unreadable, and then determine
2129	 * whether this results in any DTL outages in the top-level vdev.
2130	 * If not, we can safely offline/detach/remove the device.
2131	 */
2132	vd->vdev_cant_read = B_TRUE;
2133	vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2134	required = !vdev_dtl_empty(tvd, DTL_OUTAGE);
2135	vd->vdev_cant_read = cant_read;
2136	vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2137
2138	if (!required && zio_injection_enabled)
2139		required = !!zio_handle_device_injection(vd, NULL, ECHILD);
2140
2141	return (required);
2142}
2143
2144/*
2145 * Determine if resilver is needed, and if so the txg range.
2146 */
2147boolean_t
2148vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
2149{
2150	boolean_t needed = B_FALSE;
2151	uint64_t thismin = UINT64_MAX;
2152	uint64_t thismax = 0;
2153
2154	if (vd->vdev_children == 0) {
2155		mutex_enter(&vd->vdev_dtl_lock);
2156		if (range_tree_space(vd->vdev_dtl[DTL_MISSING]) != 0 &&
2157		    vdev_writeable(vd)) {
2158
2159			thismin = vdev_dtl_min(vd);
2160			thismax = vdev_dtl_max(vd);
2161			needed = B_TRUE;
2162		}
2163		mutex_exit(&vd->vdev_dtl_lock);
2164	} else {
2165		for (int c = 0; c < vd->vdev_children; c++) {
2166			vdev_t *cvd = vd->vdev_child[c];
2167			uint64_t cmin, cmax;
2168
2169			if (vdev_resilver_needed(cvd, &cmin, &cmax)) {
2170				thismin = MIN(thismin, cmin);
2171				thismax = MAX(thismax, cmax);
2172				needed = B_TRUE;
2173			}
2174		}
2175	}
2176
2177	if (needed && minp) {
2178		*minp = thismin;
2179		*maxp = thismax;
2180	}
2181	return (needed);
2182}
2183
2184void
2185vdev_load(vdev_t *vd)
2186{
2187	/*
2188	 * Recursively load all children.
2189	 */
2190	for (int c = 0; c < vd->vdev_children; c++)
2191		vdev_load(vd->vdev_child[c]);
2192
2193	/*
2194	 * If this is a top-level vdev, initialize its metaslabs.
2195	 */
2196	if (vd == vd->vdev_top && !vd->vdev_ishole &&
2197	    (vd->vdev_ashift == 0 || vd->vdev_asize == 0 ||
2198	    vdev_metaslab_init(vd, 0) != 0))
2199		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2200		    VDEV_AUX_CORRUPT_DATA);
2201
2202	/*
2203	 * If this is a leaf vdev, load its DTL.
2204	 */
2205	if (vd->vdev_ops->vdev_op_leaf && vdev_dtl_load(vd) != 0)
2206		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2207		    VDEV_AUX_CORRUPT_DATA);
2208}
2209
2210/*
2211 * The special vdev case is used for hot spares and l2cache devices.  Its
2212 * sole purpose it to set the vdev state for the associated vdev.  To do this,
2213 * we make sure that we can open the underlying device, then try to read the
2214 * label, and make sure that the label is sane and that it hasn't been
2215 * repurposed to another pool.
2216 */
2217int
2218vdev_validate_aux(vdev_t *vd)
2219{
2220	nvlist_t *label;
2221	uint64_t guid, version;
2222	uint64_t state;
2223
2224	if (!vdev_readable(vd))
2225		return (0);
2226
2227	if ((label = vdev_label_read_config(vd, -1ULL)) == NULL) {
2228		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2229		    VDEV_AUX_CORRUPT_DATA);
2230		return (-1);
2231	}
2232
2233	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_VERSION, &version) != 0 ||
2234	    !SPA_VERSION_IS_SUPPORTED(version) ||
2235	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0 ||
2236	    guid != vd->vdev_guid ||
2237	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE, &state) != 0) {
2238		vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2239		    VDEV_AUX_CORRUPT_DATA);
2240		nvlist_free(label);
2241		return (-1);
2242	}
2243
2244	/*
2245	 * We don't actually check the pool state here.  If it's in fact in
2246	 * use by another pool, we update this fact on the fly when requested.
2247	 */
2248	nvlist_free(label);
2249	return (0);
2250}
2251
2252void
2253vdev_remove(vdev_t *vd, uint64_t txg)
2254{
2255	spa_t *spa = vd->vdev_spa;
2256	objset_t *mos = spa->spa_meta_objset;
2257	dmu_tx_t *tx;
2258
2259	tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
2260
2261	if (vd->vdev_ms != NULL) {
2262		metaslab_group_t *mg = vd->vdev_mg;
2263
2264		metaslab_group_histogram_verify(mg);
2265		metaslab_class_histogram_verify(mg->mg_class);
2266
2267		for (int m = 0; m < vd->vdev_ms_count; m++) {
2268			metaslab_t *msp = vd->vdev_ms[m];
2269
2270			if (msp == NULL || msp->ms_sm == NULL)
2271				continue;
2272
2273			mutex_enter(&msp->ms_lock);
2274			/*
2275			 * If the metaslab was not loaded when the vdev
2276			 * was removed then the histogram accounting may
2277			 * not be accurate. Update the histogram information
2278			 * here so that we ensure that the metaslab group
2279			 * and metaslab class are up-to-date.
2280			 */
2281			metaslab_group_histogram_remove(mg, msp);
2282
2283			VERIFY0(space_map_allocated(msp->ms_sm));
2284			space_map_free(msp->ms_sm, tx);
2285			space_map_close(msp->ms_sm);
2286			msp->ms_sm = NULL;
2287			mutex_exit(&msp->ms_lock);
2288		}
2289
2290		metaslab_group_histogram_verify(mg);
2291		metaslab_class_histogram_verify(mg->mg_class);
2292		for (int i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
2293			ASSERT0(mg->mg_histogram[i]);
2294
2295	}
2296
2297	if (vd->vdev_ms_array) {
2298		(void) dmu_object_free(mos, vd->vdev_ms_array, tx);
2299		vd->vdev_ms_array = 0;
2300	}
2301	dmu_tx_commit(tx);
2302}
2303
2304void
2305vdev_sync_done(vdev_t *vd, uint64_t txg)
2306{
2307	metaslab_t *msp;
2308	boolean_t reassess = !txg_list_empty(&vd->vdev_ms_list, TXG_CLEAN(txg));
2309
2310	ASSERT(!vd->vdev_ishole);
2311
2312	while (msp = txg_list_remove(&vd->vdev_ms_list, TXG_CLEAN(txg)))
2313		metaslab_sync_done(msp, txg);
2314
2315	if (reassess)
2316		metaslab_sync_reassess(vd->vdev_mg);
2317}
2318
2319void
2320vdev_sync(vdev_t *vd, uint64_t txg)
2321{
2322	spa_t *spa = vd->vdev_spa;
2323	vdev_t *lvd;
2324	metaslab_t *msp;
2325	dmu_tx_t *tx;
2326
2327	ASSERT(!vd->vdev_ishole);
2328
2329	if (vd->vdev_ms_array == 0 && vd->vdev_ms_shift != 0) {
2330		ASSERT(vd == vd->vdev_top);
2331		tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
2332		vd->vdev_ms_array = dmu_object_alloc(spa->spa_meta_objset,
2333		    DMU_OT_OBJECT_ARRAY, 0, DMU_OT_NONE, 0, tx);
2334		ASSERT(vd->vdev_ms_array != 0);
2335		vdev_config_dirty(vd);
2336		dmu_tx_commit(tx);
2337	}
2338
2339	/*
2340	 * Remove the metadata associated with this vdev once it's empty.
2341	 */
2342	if (vd->vdev_stat.vs_alloc == 0 && vd->vdev_removing)
2343		vdev_remove(vd, txg);
2344
2345	while ((msp = txg_list_remove(&vd->vdev_ms_list, txg)) != NULL) {
2346		metaslab_sync(msp, txg);
2347		(void) txg_list_add(&vd->vdev_ms_list, msp, TXG_CLEAN(txg));
2348	}
2349
2350	while ((lvd = txg_list_remove(&vd->vdev_dtl_list, txg)) != NULL)
2351		vdev_dtl_sync(lvd, txg);
2352
2353	(void) txg_list_add(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg));
2354}
2355
2356uint64_t
2357vdev_psize_to_asize(vdev_t *vd, uint64_t psize)
2358{
2359	return (vd->vdev_ops->vdev_op_asize(vd, psize));
2360}
2361
2362/*
2363 * Mark the given vdev faulted.  A faulted vdev behaves as if the device could
2364 * not be opened, and no I/O is attempted.
2365 */
2366int
2367vdev_fault(spa_t *spa, uint64_t guid, vdev_aux_t aux)
2368{
2369	vdev_t *vd, *tvd;
2370
2371	spa_vdev_state_enter(spa, SCL_NONE);
2372
2373	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2374		return (spa_vdev_state_exit(spa, NULL, ENODEV));
2375
2376	if (!vd->vdev_ops->vdev_op_leaf)
2377		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2378
2379	tvd = vd->vdev_top;
2380
2381	/*
2382	 * We don't directly use the aux state here, but if we do a
2383	 * vdev_reopen(), we need this value to be present to remember why we
2384	 * were faulted.
2385	 */
2386	vd->vdev_label_aux = aux;
2387
2388	/*
2389	 * Faulted state takes precedence over degraded.
2390	 */
2391	vd->vdev_delayed_close = B_FALSE;
2392	vd->vdev_faulted = 1ULL;
2393	vd->vdev_degraded = 0ULL;
2394	vdev_set_state(vd, B_FALSE, VDEV_STATE_FAULTED, aux);
2395
2396	/*
2397	 * If this device has the only valid copy of the data, then
2398	 * back off and simply mark the vdev as degraded instead.
2399	 */
2400	if (!tvd->vdev_islog && vd->vdev_aux == NULL && vdev_dtl_required(vd)) {
2401		vd->vdev_degraded = 1ULL;
2402		vd->vdev_faulted = 0ULL;
2403
2404		/*
2405		 * If we reopen the device and it's not dead, only then do we
2406		 * mark it degraded.
2407		 */
2408		vdev_reopen(tvd);
2409
2410		if (vdev_readable(vd))
2411			vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED, aux);
2412	}
2413
2414	return (spa_vdev_state_exit(spa, vd, 0));
2415}
2416
2417/*
2418 * Mark the given vdev degraded.  A degraded vdev is purely an indication to the
2419 * user that something is wrong.  The vdev continues to operate as normal as far
2420 * as I/O is concerned.
2421 */
2422int
2423vdev_degrade(spa_t *spa, uint64_t guid, vdev_aux_t aux)
2424{
2425	vdev_t *vd;
2426
2427	spa_vdev_state_enter(spa, SCL_NONE);
2428
2429	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2430		return (spa_vdev_state_exit(spa, NULL, ENODEV));
2431
2432	if (!vd->vdev_ops->vdev_op_leaf)
2433		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2434
2435	/*
2436	 * If the vdev is already faulted, then don't do anything.
2437	 */
2438	if (vd->vdev_faulted || vd->vdev_degraded)
2439		return (spa_vdev_state_exit(spa, NULL, 0));
2440
2441	vd->vdev_degraded = 1ULL;
2442	if (!vdev_is_dead(vd))
2443		vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED,
2444		    aux);
2445
2446	return (spa_vdev_state_exit(spa, vd, 0));
2447}
2448
2449/*
2450 * Online the given vdev.
2451 *
2452 * If 'ZFS_ONLINE_UNSPARE' is set, it implies two things.  First, any attached
2453 * spare device should be detached when the device finishes resilvering.
2454 * Second, the online should be treated like a 'test' online case, so no FMA
2455 * events are generated if the device fails to open.
2456 */
2457int
2458vdev_online(spa_t *spa, uint64_t guid, uint64_t flags, vdev_state_t *newstate)
2459{
2460	vdev_t *vd, *tvd, *pvd, *rvd = spa->spa_root_vdev;
2461
2462	spa_vdev_state_enter(spa, SCL_NONE);
2463
2464	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2465		return (spa_vdev_state_exit(spa, NULL, ENODEV));
2466
2467	if (!vd->vdev_ops->vdev_op_leaf)
2468		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2469
2470	tvd = vd->vdev_top;
2471	vd->vdev_offline = B_FALSE;
2472	vd->vdev_tmpoffline = B_FALSE;
2473	vd->vdev_checkremove = !!(flags & ZFS_ONLINE_CHECKREMOVE);
2474	vd->vdev_forcefault = !!(flags & ZFS_ONLINE_FORCEFAULT);
2475
2476	/* XXX - L2ARC 1.0 does not support expansion */
2477	if (!vd->vdev_aux) {
2478		for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
2479			pvd->vdev_expanding = !!(flags & ZFS_ONLINE_EXPAND);
2480	}
2481
2482	vdev_reopen(tvd);
2483	vd->vdev_checkremove = vd->vdev_forcefault = B_FALSE;
2484
2485	if (!vd->vdev_aux) {
2486		for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
2487			pvd->vdev_expanding = B_FALSE;
2488	}
2489
2490	if (newstate)
2491		*newstate = vd->vdev_state;
2492	if ((flags & ZFS_ONLINE_UNSPARE) &&
2493	    !vdev_is_dead(vd) && vd->vdev_parent &&
2494	    vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
2495	    vd->vdev_parent->vdev_child[0] == vd)
2496		vd->vdev_unspare = B_TRUE;
2497
2498	if ((flags & ZFS_ONLINE_EXPAND) || spa->spa_autoexpand) {
2499
2500		/* XXX - L2ARC 1.0 does not support expansion */
2501		if (vd->vdev_aux)
2502			return (spa_vdev_state_exit(spa, vd, ENOTSUP));
2503		spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
2504	}
2505	return (spa_vdev_state_exit(spa, vd, 0));
2506}
2507
2508static int
2509vdev_offline_locked(spa_t *spa, uint64_t guid, uint64_t flags)
2510{
2511	vdev_t *vd, *tvd;
2512	int error = 0;
2513	uint64_t generation;
2514	metaslab_group_t *mg;
2515
2516top:
2517	spa_vdev_state_enter(spa, SCL_ALLOC);
2518
2519	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2520		return (spa_vdev_state_exit(spa, NULL, ENODEV));
2521
2522	if (!vd->vdev_ops->vdev_op_leaf)
2523		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2524
2525	tvd = vd->vdev_top;
2526	mg = tvd->vdev_mg;
2527	generation = spa->spa_config_generation + 1;
2528
2529	/*
2530	 * If the device isn't already offline, try to offline it.
2531	 */
2532	if (!vd->vdev_offline) {
2533		/*
2534		 * If this device has the only valid copy of some data,
2535		 * don't allow it to be offlined. Log devices are always
2536		 * expendable.
2537		 */
2538		if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
2539		    vdev_dtl_required(vd))
2540			return (spa_vdev_state_exit(spa, NULL, EBUSY));
2541
2542		/*
2543		 * If the top-level is a slog and it has had allocations
2544		 * then proceed.  We check that the vdev's metaslab group
2545		 * is not NULL since it's possible that we may have just
2546		 * added this vdev but not yet initialized its metaslabs.
2547		 */
2548		if (tvd->vdev_islog && mg != NULL) {
2549			/*
2550			 * Prevent any future allocations.
2551			 */
2552			metaslab_group_passivate(mg);
2553			(void) spa_vdev_state_exit(spa, vd, 0);
2554
2555			error = spa_offline_log(spa);
2556
2557			spa_vdev_state_enter(spa, SCL_ALLOC);
2558
2559			/*
2560			 * Check to see if the config has changed.
2561			 */
2562			if (error || generation != spa->spa_config_generation) {
2563				metaslab_group_activate(mg);
2564				if (error)
2565					return (spa_vdev_state_exit(spa,
2566					    vd, error));
2567				(void) spa_vdev_state_exit(spa, vd, 0);
2568				goto top;
2569			}
2570			ASSERT0(tvd->vdev_stat.vs_alloc);
2571		}
2572
2573		/*
2574		 * Offline this device and reopen its top-level vdev.
2575		 * If the top-level vdev is a log device then just offline
2576		 * it. Otherwise, if this action results in the top-level
2577		 * vdev becoming unusable, undo it and fail the request.
2578		 */
2579		vd->vdev_offline = B_TRUE;
2580		vdev_reopen(tvd);
2581
2582		if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
2583		    vdev_is_dead(tvd)) {
2584			vd->vdev_offline = B_FALSE;
2585			vdev_reopen(tvd);
2586			return (spa_vdev_state_exit(spa, NULL, EBUSY));
2587		}
2588
2589		/*
2590		 * Add the device back into the metaslab rotor so that
2591		 * once we online the device it's open for business.
2592		 */
2593		if (tvd->vdev_islog && mg != NULL)
2594			metaslab_group_activate(mg);
2595	}
2596
2597	vd->vdev_tmpoffline = !!(flags & ZFS_OFFLINE_TEMPORARY);
2598
2599	return (spa_vdev_state_exit(spa, vd, 0));
2600}
2601
2602int
2603vdev_offline(spa_t *spa, uint64_t guid, uint64_t flags)
2604{
2605	int error;
2606
2607	mutex_enter(&spa->spa_vdev_top_lock);
2608	error = vdev_offline_locked(spa, guid, flags);
2609	mutex_exit(&spa->spa_vdev_top_lock);
2610
2611	return (error);
2612}
2613
2614/*
2615 * Clear the error counts associated with this vdev.  Unlike vdev_online() and
2616 * vdev_offline(), we assume the spa config is locked.  We also clear all
2617 * children.  If 'vd' is NULL, then the user wants to clear all vdevs.
2618 */
2619void
2620vdev_clear(spa_t *spa, vdev_t *vd)
2621{
2622	vdev_t *rvd = spa->spa_root_vdev;
2623
2624	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2625
2626	if (vd == NULL)
2627		vd = rvd;
2628
2629	vd->vdev_stat.vs_read_errors = 0;
2630	vd->vdev_stat.vs_write_errors = 0;
2631	vd->vdev_stat.vs_checksum_errors = 0;
2632
2633	for (int c = 0; c < vd->vdev_children; c++)
2634		vdev_clear(spa, vd->vdev_child[c]);
2635
2636	if (vd == rvd) {
2637		for (int c = 0; c < spa->spa_l2cache.sav_count; c++)
2638			vdev_clear(spa, spa->spa_l2cache.sav_vdevs[c]);
2639
2640		for (int c = 0; c < spa->spa_spares.sav_count; c++)
2641			vdev_clear(spa, spa->spa_spares.sav_vdevs[c]);
2642	}
2643
2644	/*
2645	 * If we're in the FAULTED state or have experienced failed I/O, then
2646	 * clear the persistent state and attempt to reopen the device.  We
2647	 * also mark the vdev config dirty, so that the new faulted state is
2648	 * written out to disk.
2649	 */
2650	if (vd->vdev_faulted || vd->vdev_degraded ||
2651	    !vdev_readable(vd) || !vdev_writeable(vd)) {
2652
2653		/*
2654		 * When reopening in reponse to a clear event, it may be due to
2655		 * a fmadm repair request.  In this case, if the device is
2656		 * still broken, we want to still post the ereport again.
2657		 */
2658		vd->vdev_forcefault = B_TRUE;
2659
2660		vd->vdev_faulted = vd->vdev_degraded = 0ULL;
2661		vd->vdev_cant_read = B_FALSE;
2662		vd->vdev_cant_write = B_FALSE;
2663
2664		vdev_reopen(vd == rvd ? rvd : vd->vdev_top);
2665
2666		vd->vdev_forcefault = B_FALSE;
2667
2668		if (vd != rvd && vdev_writeable(vd->vdev_top))
2669			vdev_state_dirty(vd->vdev_top);
2670
2671		if (vd->vdev_aux == NULL && !vdev_is_dead(vd))
2672			spa_async_request(spa, SPA_ASYNC_RESILVER);
2673
2674		spa_event_notify(spa, vd, ESC_ZFS_VDEV_CLEAR);
2675	}
2676
2677	/*
2678	 * When clearing a FMA-diagnosed fault, we always want to
2679	 * unspare the device, as we assume that the original spare was
2680	 * done in response to the FMA fault.
2681	 */
2682	if (!vdev_is_dead(vd) && vd->vdev_parent != NULL &&
2683	    vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
2684	    vd->vdev_parent->vdev_child[0] == vd)
2685		vd->vdev_unspare = B_TRUE;
2686}
2687
2688boolean_t
2689vdev_is_dead(vdev_t *vd)
2690{
2691	/*
2692	 * Holes and missing devices are always considered "dead".
2693	 * This simplifies the code since we don't have to check for
2694	 * these types of devices in the various code paths.
2695	 * Instead we rely on the fact that we skip over dead devices
2696	 * before issuing I/O to them.
2697	 */
2698	return (vd->vdev_state < VDEV_STATE_DEGRADED || vd->vdev_ishole ||
2699	    vd->vdev_ops == &vdev_missing_ops);
2700}
2701
2702boolean_t
2703vdev_readable(vdev_t *vd)
2704{
2705	return (!vdev_is_dead(vd) && !vd->vdev_cant_read);
2706}
2707
2708boolean_t
2709vdev_writeable(vdev_t *vd)
2710{
2711	return (!vdev_is_dead(vd) && !vd->vdev_cant_write);
2712}
2713
2714boolean_t
2715vdev_allocatable(vdev_t *vd)
2716{
2717	uint64_t state = vd->vdev_state;
2718
2719	/*
2720	 * We currently allow allocations from vdevs which may be in the
2721	 * process of reopening (i.e. VDEV_STATE_CLOSED). If the device
2722	 * fails to reopen then we'll catch it later when we're holding
2723	 * the proper locks.  Note that we have to get the vdev state
2724	 * in a local variable because although it changes atomically,
2725	 * we're asking two separate questions about it.
2726	 */
2727	return (!(state < VDEV_STATE_DEGRADED && state != VDEV_STATE_CLOSED) &&
2728	    !vd->vdev_cant_write && !vd->vdev_ishole);
2729}
2730
2731boolean_t
2732vdev_accessible(vdev_t *vd, zio_t *zio)
2733{
2734	ASSERT(zio->io_vd == vd);
2735
2736	if (vdev_is_dead(vd) || vd->vdev_remove_wanted)
2737		return (B_FALSE);
2738
2739	if (zio->io_type == ZIO_TYPE_READ)
2740		return (!vd->vdev_cant_read);
2741
2742	if (zio->io_type == ZIO_TYPE_WRITE)
2743		return (!vd->vdev_cant_write);
2744
2745	return (B_TRUE);
2746}
2747
2748/*
2749 * Get statistics for the given vdev.
2750 */
2751void
2752vdev_get_stats(vdev_t *vd, vdev_stat_t *vs)
2753{
2754	spa_t *spa = vd->vdev_spa;
2755	vdev_t *rvd = spa->spa_root_vdev;
2756
2757	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
2758
2759	mutex_enter(&vd->vdev_stat_lock);
2760	bcopy(&vd->vdev_stat, vs, sizeof (*vs));
2761	vs->vs_timestamp = gethrtime() - vs->vs_timestamp;
2762	vs->vs_state = vd->vdev_state;
2763	vs->vs_rsize = vdev_get_min_asize(vd);
2764	if (vd->vdev_ops->vdev_op_leaf)
2765		vs->vs_rsize += VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE;
2766	vs->vs_esize = vd->vdev_max_asize - vd->vdev_asize;
2767	vs->vs_configured_ashift = vd->vdev_top != NULL
2768	    ? vd->vdev_top->vdev_ashift : vd->vdev_ashift;
2769	vs->vs_logical_ashift = vd->vdev_logical_ashift;
2770	vs->vs_physical_ashift = vd->vdev_physical_ashift;
2771	if (vd->vdev_aux == NULL && vd == vd->vdev_top && !vd->vdev_ishole) {
2772		vs->vs_fragmentation = vd->vdev_mg->mg_fragmentation;
2773	}
2774
2775	/*
2776	 * If we're getting stats on the root vdev, aggregate the I/O counts
2777	 * over all top-level vdevs (i.e. the direct children of the root).
2778	 */
2779	if (vd == rvd) {
2780		for (int c = 0; c < rvd->vdev_children; c++) {
2781			vdev_t *cvd = rvd->vdev_child[c];
2782			vdev_stat_t *cvs = &cvd->vdev_stat;
2783
2784			for (int t = 0; t < ZIO_TYPES; t++) {
2785				vs->vs_ops[t] += cvs->vs_ops[t];
2786				vs->vs_bytes[t] += cvs->vs_bytes[t];
2787			}
2788			cvs->vs_scan_removing = cvd->vdev_removing;
2789		}
2790	}
2791	mutex_exit(&vd->vdev_stat_lock);
2792}
2793
2794void
2795vdev_clear_stats(vdev_t *vd)
2796{
2797	mutex_enter(&vd->vdev_stat_lock);
2798	vd->vdev_stat.vs_space = 0;
2799	vd->vdev_stat.vs_dspace = 0;
2800	vd->vdev_stat.vs_alloc = 0;
2801	mutex_exit(&vd->vdev_stat_lock);
2802}
2803
2804void
2805vdev_scan_stat_init(vdev_t *vd)
2806{
2807	vdev_stat_t *vs = &vd->vdev_stat;
2808
2809	for (int c = 0; c < vd->vdev_children; c++)
2810		vdev_scan_stat_init(vd->vdev_child[c]);
2811
2812	mutex_enter(&vd->vdev_stat_lock);
2813	vs->vs_scan_processed = 0;
2814	mutex_exit(&vd->vdev_stat_lock);
2815}
2816
2817void
2818vdev_stat_update(zio_t *zio, uint64_t psize)
2819{
2820	spa_t *spa = zio->io_spa;
2821	vdev_t *rvd = spa->spa_root_vdev;
2822	vdev_t *vd = zio->io_vd ? zio->io_vd : rvd;
2823	vdev_t *pvd;
2824	uint64_t txg = zio->io_txg;
2825	vdev_stat_t *vs = &vd->vdev_stat;
2826	zio_type_t type = zio->io_type;
2827	int flags = zio->io_flags;
2828
2829	/*
2830	 * If this i/o is a gang leader, it didn't do any actual work.
2831	 */
2832	if (zio->io_gang_tree)
2833		return;
2834
2835	if (zio->io_error == 0) {
2836		/*
2837		 * If this is a root i/o, don't count it -- we've already
2838		 * counted the top-level vdevs, and vdev_get_stats() will
2839		 * aggregate them when asked.  This reduces contention on
2840		 * the root vdev_stat_lock and implicitly handles blocks
2841		 * that compress away to holes, for which there is no i/o.
2842		 * (Holes never create vdev children, so all the counters
2843		 * remain zero, which is what we want.)
2844		 *
2845		 * Note: this only applies to successful i/o (io_error == 0)
2846		 * because unlike i/o counts, errors are not additive.
2847		 * When reading a ditto block, for example, failure of
2848		 * one top-level vdev does not imply a root-level error.
2849		 */
2850		if (vd == rvd)
2851			return;
2852
2853		ASSERT(vd == zio->io_vd);
2854
2855		if (flags & ZIO_FLAG_IO_BYPASS)
2856			return;
2857
2858		mutex_enter(&vd->vdev_stat_lock);
2859
2860		if (flags & ZIO_FLAG_IO_REPAIR) {
2861			if (flags & ZIO_FLAG_SCAN_THREAD) {
2862				dsl_scan_phys_t *scn_phys =
2863				    &spa->spa_dsl_pool->dp_scan->scn_phys;
2864				uint64_t *processed = &scn_phys->scn_processed;
2865
2866				/* XXX cleanup? */
2867				if (vd->vdev_ops->vdev_op_leaf)
2868					atomic_add_64(processed, psize);
2869				vs->vs_scan_processed += psize;
2870			}
2871
2872			if (flags & ZIO_FLAG_SELF_HEAL)
2873				vs->vs_self_healed += psize;
2874		}
2875
2876		vs->vs_ops[type]++;
2877		vs->vs_bytes[type] += psize;
2878
2879		mutex_exit(&vd->vdev_stat_lock);
2880		return;
2881	}
2882
2883	if (flags & ZIO_FLAG_SPECULATIVE)
2884		return;
2885
2886	/*
2887	 * If this is an I/O error that is going to be retried, then ignore the
2888	 * error.  Otherwise, the user may interpret B_FAILFAST I/O errors as
2889	 * hard errors, when in reality they can happen for any number of
2890	 * innocuous reasons (bus resets, MPxIO link failure, etc).
2891	 */
2892	if (zio->io_error == EIO &&
2893	    !(zio->io_flags & ZIO_FLAG_IO_RETRY))
2894		return;
2895
2896	/*
2897	 * Intent logs writes won't propagate their error to the root
2898	 * I/O so don't mark these types of failures as pool-level
2899	 * errors.
2900	 */
2901	if (zio->io_vd == NULL && (zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
2902		return;
2903
2904	mutex_enter(&vd->vdev_stat_lock);
2905	if (type == ZIO_TYPE_READ && !vdev_is_dead(vd)) {
2906		if (zio->io_error == ECKSUM)
2907			vs->vs_checksum_errors++;
2908		else
2909			vs->vs_read_errors++;
2910	}
2911	if (type == ZIO_TYPE_WRITE && !vdev_is_dead(vd))
2912		vs->vs_write_errors++;
2913	mutex_exit(&vd->vdev_stat_lock);
2914
2915	if (type == ZIO_TYPE_WRITE && txg != 0 &&
2916	    (!(flags & ZIO_FLAG_IO_REPAIR) ||
2917	    (flags & ZIO_FLAG_SCAN_THREAD) ||
2918	    spa->spa_claiming)) {
2919		/*
2920		 * This is either a normal write (not a repair), or it's
2921		 * a repair induced by the scrub thread, or it's a repair
2922		 * made by zil_claim() during spa_load() in the first txg.
2923		 * In the normal case, we commit the DTL change in the same
2924		 * txg as the block was born.  In the scrub-induced repair
2925		 * case, we know that scrubs run in first-pass syncing context,
2926		 * so we commit the DTL change in spa_syncing_txg(spa).
2927		 * In the zil_claim() case, we commit in spa_first_txg(spa).
2928		 *
2929		 * We currently do not make DTL entries for failed spontaneous
2930		 * self-healing writes triggered by normal (non-scrubbing)
2931		 * reads, because we have no transactional context in which to
2932		 * do so -- and it's not clear that it'd be desirable anyway.
2933		 */
2934		if (vd->vdev_ops->vdev_op_leaf) {
2935			uint64_t commit_txg = txg;
2936			if (flags & ZIO_FLAG_SCAN_THREAD) {
2937				ASSERT(flags & ZIO_FLAG_IO_REPAIR);
2938				ASSERT(spa_sync_pass(spa) == 1);
2939				vdev_dtl_dirty(vd, DTL_SCRUB, txg, 1);
2940				commit_txg = spa_syncing_txg(spa);
2941			} else if (spa->spa_claiming) {
2942				ASSERT(flags & ZIO_FLAG_IO_REPAIR);
2943				commit_txg = spa_first_txg(spa);
2944			}
2945			ASSERT(commit_txg >= spa_syncing_txg(spa));
2946			if (vdev_dtl_contains(vd, DTL_MISSING, txg, 1))
2947				return;
2948			for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
2949				vdev_dtl_dirty(pvd, DTL_PARTIAL, txg, 1);
2950			vdev_dirty(vd->vdev_top, VDD_DTL, vd, commit_txg);
2951		}
2952		if (vd != rvd)
2953			vdev_dtl_dirty(vd, DTL_MISSING, txg, 1);
2954	}
2955}
2956
2957/*
2958 * Update the in-core space usage stats for this vdev, its metaslab class,
2959 * and the root vdev.
2960 */
2961void
2962vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
2963    int64_t space_delta)
2964{
2965	int64_t dspace_delta = space_delta;
2966	spa_t *spa = vd->vdev_spa;
2967	vdev_t *rvd = spa->spa_root_vdev;
2968	metaslab_group_t *mg = vd->vdev_mg;
2969	metaslab_class_t *mc = mg ? mg->mg_class : NULL;
2970
2971	ASSERT(vd == vd->vdev_top);
2972
2973	/*
2974	 * Apply the inverse of the psize-to-asize (ie. RAID-Z) space-expansion
2975	 * factor.  We must calculate this here and not at the root vdev
2976	 * because the root vdev's psize-to-asize is simply the max of its
2977	 * childrens', thus not accurate enough for us.
2978	 */
2979	ASSERT((dspace_delta & (SPA_MINBLOCKSIZE-1)) == 0);
2980	ASSERT(vd->vdev_deflate_ratio != 0 || vd->vdev_isl2cache);
2981	dspace_delta = (dspace_delta >> SPA_MINBLOCKSHIFT) *
2982	    vd->vdev_deflate_ratio;
2983
2984	mutex_enter(&vd->vdev_stat_lock);
2985	vd->vdev_stat.vs_alloc += alloc_delta;
2986	vd->vdev_stat.vs_space += space_delta;
2987	vd->vdev_stat.vs_dspace += dspace_delta;
2988	mutex_exit(&vd->vdev_stat_lock);
2989
2990	if (mc == spa_normal_class(spa)) {
2991		mutex_enter(&rvd->vdev_stat_lock);
2992		rvd->vdev_stat.vs_alloc += alloc_delta;
2993		rvd->vdev_stat.vs_space += space_delta;
2994		rvd->vdev_stat.vs_dspace += dspace_delta;
2995		mutex_exit(&rvd->vdev_stat_lock);
2996	}
2997
2998	if (mc != NULL) {
2999		ASSERT(rvd == vd->vdev_parent);
3000		ASSERT(vd->vdev_ms_count != 0);
3001
3002		metaslab_class_space_update(mc,
3003		    alloc_delta, defer_delta, space_delta, dspace_delta);
3004	}
3005}
3006
3007/*
3008 * Mark a top-level vdev's config as dirty, placing it on the dirty list
3009 * so that it will be written out next time the vdev configuration is synced.
3010 * If the root vdev is specified (vdev_top == NULL), dirty all top-level vdevs.
3011 */
3012void
3013vdev_config_dirty(vdev_t *vd)
3014{
3015	spa_t *spa = vd->vdev_spa;
3016	vdev_t *rvd = spa->spa_root_vdev;
3017	int c;
3018
3019	ASSERT(spa_writeable(spa));
3020
3021	/*
3022	 * If this is an aux vdev (as with l2cache and spare devices), then we
3023	 * update the vdev config manually and set the sync flag.
3024	 */
3025	if (vd->vdev_aux != NULL) {
3026		spa_aux_vdev_t *sav = vd->vdev_aux;
3027		nvlist_t **aux;
3028		uint_t naux;
3029
3030		for (c = 0; c < sav->sav_count; c++) {
3031			if (sav->sav_vdevs[c] == vd)
3032				break;
3033		}
3034
3035		if (c == sav->sav_count) {
3036			/*
3037			 * We're being removed.  There's nothing more to do.
3038			 */
3039			ASSERT(sav->sav_sync == B_TRUE);
3040			return;
3041		}
3042
3043		sav->sav_sync = B_TRUE;
3044
3045		if (nvlist_lookup_nvlist_array(sav->sav_config,
3046		    ZPOOL_CONFIG_L2CACHE, &aux, &naux) != 0) {
3047			VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
3048			    ZPOOL_CONFIG_SPARES, &aux, &naux) == 0);
3049		}
3050
3051		ASSERT(c < naux);
3052
3053		/*
3054		 * Setting the nvlist in the middle if the array is a little
3055		 * sketchy, but it will work.
3056		 */
3057		nvlist_free(aux[c]);
3058		aux[c] = vdev_config_generate(spa, vd, B_TRUE, 0);
3059
3060		return;
3061	}
3062
3063	/*
3064	 * The dirty list is protected by the SCL_CONFIG lock.  The caller
3065	 * must either hold SCL_CONFIG as writer, or must be the sync thread
3066	 * (which holds SCL_CONFIG as reader).  There's only one sync thread,
3067	 * so this is sufficient to ensure mutual exclusion.
3068	 */
3069	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
3070	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3071	    spa_config_held(spa, SCL_CONFIG, RW_READER)));
3072
3073	if (vd == rvd) {
3074		for (c = 0; c < rvd->vdev_children; c++)
3075			vdev_config_dirty(rvd->vdev_child[c]);
3076	} else {
3077		ASSERT(vd == vd->vdev_top);
3078
3079		if (!list_link_active(&vd->vdev_config_dirty_node) &&
3080		    !vd->vdev_ishole)
3081			list_insert_head(&spa->spa_config_dirty_list, vd);
3082	}
3083}
3084
3085void
3086vdev_config_clean(vdev_t *vd)
3087{
3088	spa_t *spa = vd->vdev_spa;
3089
3090	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
3091	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3092	    spa_config_held(spa, SCL_CONFIG, RW_READER)));
3093
3094	ASSERT(list_link_active(&vd->vdev_config_dirty_node));
3095	list_remove(&spa->spa_config_dirty_list, vd);
3096}
3097
3098/*
3099 * Mark a top-level vdev's state as dirty, so that the next pass of
3100 * spa_sync() can convert this into vdev_config_dirty().  We distinguish
3101 * the state changes from larger config changes because they require
3102 * much less locking, and are often needed for administrative actions.
3103 */
3104void
3105vdev_state_dirty(vdev_t *vd)
3106{
3107	spa_t *spa = vd->vdev_spa;
3108
3109	ASSERT(spa_writeable(spa));
3110	ASSERT(vd == vd->vdev_top);
3111
3112	/*
3113	 * The state list is protected by the SCL_STATE lock.  The caller
3114	 * must either hold SCL_STATE as writer, or must be the sync thread
3115	 * (which holds SCL_STATE as reader).  There's only one sync thread,
3116	 * so this is sufficient to ensure mutual exclusion.
3117	 */
3118	ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
3119	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3120	    spa_config_held(spa, SCL_STATE, RW_READER)));
3121
3122	if (!list_link_active(&vd->vdev_state_dirty_node) && !vd->vdev_ishole)
3123		list_insert_head(&spa->spa_state_dirty_list, vd);
3124}
3125
3126void
3127vdev_state_clean(vdev_t *vd)
3128{
3129	spa_t *spa = vd->vdev_spa;
3130
3131	ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
3132	    (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3133	    spa_config_held(spa, SCL_STATE, RW_READER)));
3134
3135	ASSERT(list_link_active(&vd->vdev_state_dirty_node));
3136	list_remove(&spa->spa_state_dirty_list, vd);
3137}
3138
3139/*
3140 * Propagate vdev state up from children to parent.
3141 */
3142void
3143vdev_propagate_state(vdev_t *vd)
3144{
3145	spa_t *spa = vd->vdev_spa;
3146	vdev_t *rvd = spa->spa_root_vdev;
3147	int degraded = 0, faulted = 0;
3148	int corrupted = 0;
3149	vdev_t *child;
3150
3151	if (vd->vdev_children > 0) {
3152		for (int c = 0; c < vd->vdev_children; c++) {
3153			child = vd->vdev_child[c];
3154
3155			/*
3156			 * Don't factor holes into the decision.
3157			 */
3158			if (child->vdev_ishole)
3159				continue;
3160
3161			if (!vdev_readable(child) ||
3162			    (!vdev_writeable(child) && spa_writeable(spa))) {
3163				/*
3164				 * Root special: if there is a top-level log
3165				 * device, treat the root vdev as if it were
3166				 * degraded.
3167				 */
3168				if (child->vdev_islog && vd == rvd)
3169					degraded++;
3170				else
3171					faulted++;
3172			} else if (child->vdev_state <= VDEV_STATE_DEGRADED) {
3173				degraded++;
3174			}
3175
3176			if (child->vdev_stat.vs_aux == VDEV_AUX_CORRUPT_DATA)
3177				corrupted++;
3178		}
3179
3180		vd->vdev_ops->vdev_op_state_change(vd, faulted, degraded);
3181
3182		/*
3183		 * Root special: if there is a top-level vdev that cannot be
3184		 * opened due to corrupted metadata, then propagate the root
3185		 * vdev's aux state as 'corrupt' rather than 'insufficient
3186		 * replicas'.
3187		 */
3188		if (corrupted && vd == rvd &&
3189		    rvd->vdev_state == VDEV_STATE_CANT_OPEN)
3190			vdev_set_state(rvd, B_FALSE, VDEV_STATE_CANT_OPEN,
3191			    VDEV_AUX_CORRUPT_DATA);
3192	}
3193
3194	if (vd->vdev_parent)
3195		vdev_propagate_state(vd->vdev_parent);
3196}
3197
3198/*
3199 * Set a vdev's state.  If this is during an open, we don't update the parent
3200 * state, because we're in the process of opening children depth-first.
3201 * Otherwise, we propagate the change to the parent.
3202 *
3203 * If this routine places a device in a faulted state, an appropriate ereport is
3204 * generated.
3205 */
3206void
3207vdev_set_state(vdev_t *vd, boolean_t isopen, vdev_state_t state, vdev_aux_t aux)
3208{
3209	uint64_t save_state;
3210	spa_t *spa = vd->vdev_spa;
3211
3212	if (state == vd->vdev_state) {
3213		vd->vdev_stat.vs_aux = aux;
3214		return;
3215	}
3216
3217	save_state = vd->vdev_state;
3218
3219	vd->vdev_state = state;
3220	vd->vdev_stat.vs_aux = aux;
3221
3222	/*
3223	 * If we are setting the vdev state to anything but an open state, then
3224	 * always close the underlying device unless the device has requested
3225	 * a delayed close (i.e. we're about to remove or fault the device).
3226	 * Otherwise, we keep accessible but invalid devices open forever.
3227	 * We don't call vdev_close() itself, because that implies some extra
3228	 * checks (offline, etc) that we don't want here.  This is limited to
3229	 * leaf devices, because otherwise closing the device will affect other
3230	 * children.
3231	 */
3232	if (!vd->vdev_delayed_close && vdev_is_dead(vd) &&
3233	    vd->vdev_ops->vdev_op_leaf)
3234		vd->vdev_ops->vdev_op_close(vd);
3235
3236	/*
3237	 * If we have brought this vdev back into service, we need
3238	 * to notify fmd so that it can gracefully repair any outstanding
3239	 * cases due to a missing device.  We do this in all cases, even those
3240	 * that probably don't correlate to a repaired fault.  This is sure to
3241	 * catch all cases, and we let the zfs-retire agent sort it out.  If
3242	 * this is a transient state it's OK, as the retire agent will
3243	 * double-check the state of the vdev before repairing it.
3244	 */
3245	if (state == VDEV_STATE_HEALTHY && vd->vdev_ops->vdev_op_leaf &&
3246	    vd->vdev_prevstate != state)
3247		zfs_post_state_change(spa, vd);
3248
3249	if (vd->vdev_removed &&
3250	    state == VDEV_STATE_CANT_OPEN &&
3251	    (aux == VDEV_AUX_OPEN_FAILED || vd->vdev_checkremove)) {
3252		/*
3253		 * If the previous state is set to VDEV_STATE_REMOVED, then this
3254		 * device was previously marked removed and someone attempted to
3255		 * reopen it.  If this failed due to a nonexistent device, then
3256		 * keep the device in the REMOVED state.  We also let this be if
3257		 * it is one of our special test online cases, which is only
3258		 * attempting to online the device and shouldn't generate an FMA
3259		 * fault.
3260		 */
3261		vd->vdev_state = VDEV_STATE_REMOVED;
3262		vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
3263	} else if (state == VDEV_STATE_REMOVED) {
3264		vd->vdev_removed = B_TRUE;
3265	} else if (state == VDEV_STATE_CANT_OPEN) {
3266		/*
3267		 * If we fail to open a vdev during an import or recovery, we
3268		 * mark it as "not available", which signifies that it was
3269		 * never there to begin with.  Failure to open such a device
3270		 * is not considered an error.
3271		 */
3272		if ((spa_load_state(spa) == SPA_LOAD_IMPORT ||
3273		    spa_load_state(spa) == SPA_LOAD_RECOVER) &&
3274		    vd->vdev_ops->vdev_op_leaf)
3275			vd->vdev_not_present = 1;
3276
3277		/*
3278		 * Post the appropriate ereport.  If the 'prevstate' field is
3279		 * set to something other than VDEV_STATE_UNKNOWN, it indicates
3280		 * that this is part of a vdev_reopen().  In this case, we don't
3281		 * want to post the ereport if the device was already in the
3282		 * CANT_OPEN state beforehand.
3283		 *
3284		 * If the 'checkremove' flag is set, then this is an attempt to
3285		 * online the device in response to an insertion event.  If we
3286		 * hit this case, then we have detected an insertion event for a
3287		 * faulted or offline device that wasn't in the removed state.
3288		 * In this scenario, we don't post an ereport because we are
3289		 * about to replace the device, or attempt an online with
3290		 * vdev_forcefault, which will generate the fault for us.
3291		 */
3292		if ((vd->vdev_prevstate != state || vd->vdev_forcefault) &&
3293		    !vd->vdev_not_present && !vd->vdev_checkremove &&
3294		    vd != spa->spa_root_vdev) {
3295			const char *class;
3296
3297			switch (aux) {
3298			case VDEV_AUX_OPEN_FAILED:
3299				class = FM_EREPORT_ZFS_DEVICE_OPEN_FAILED;
3300				break;
3301			case VDEV_AUX_CORRUPT_DATA:
3302				class = FM_EREPORT_ZFS_DEVICE_CORRUPT_DATA;
3303				break;
3304			case VDEV_AUX_NO_REPLICAS:
3305				class = FM_EREPORT_ZFS_DEVICE_NO_REPLICAS;
3306				break;
3307			case VDEV_AUX_BAD_GUID_SUM:
3308				class = FM_EREPORT_ZFS_DEVICE_BAD_GUID_SUM;
3309				break;
3310			case VDEV_AUX_TOO_SMALL:
3311				class = FM_EREPORT_ZFS_DEVICE_TOO_SMALL;
3312				break;
3313			case VDEV_AUX_BAD_LABEL:
3314				class = FM_EREPORT_ZFS_DEVICE_BAD_LABEL;
3315				break;
3316			default:
3317				class = FM_EREPORT_ZFS_DEVICE_UNKNOWN;
3318			}
3319
3320			zfs_ereport_post(class, spa, vd, NULL, save_state, 0);
3321		}
3322
3323		/* Erase any notion of persistent removed state */
3324		vd->vdev_removed = B_FALSE;
3325	} else {
3326		vd->vdev_removed = B_FALSE;
3327	}
3328
3329	if (!isopen && vd->vdev_parent)
3330		vdev_propagate_state(vd->vdev_parent);
3331}
3332
3333/*
3334 * Check the vdev configuration to ensure that it's capable of supporting
3335 * a root pool.
3336 *
3337 * On Solaris, we do not support RAID-Z or partial configuration.  In
3338 * addition, only a single top-level vdev is allowed and none of the
3339 * leaves can be wholedisks.
3340 *
3341 * For FreeBSD, we can boot from any configuration. There is a
3342 * limitation that the boot filesystem must be either uncompressed or
3343 * compresses with lzjb compression but I'm not sure how to enforce
3344 * that here.
3345 */
3346boolean_t
3347vdev_is_bootable(vdev_t *vd)
3348{
3349#ifdef sun
3350	if (!vd->vdev_ops->vdev_op_leaf) {
3351		char *vdev_type = vd->vdev_ops->vdev_op_type;
3352
3353		if (strcmp(vdev_type, VDEV_TYPE_ROOT) == 0 &&
3354		    vd->vdev_children > 1) {
3355			return (B_FALSE);
3356		} else if (strcmp(vdev_type, VDEV_TYPE_RAIDZ) == 0 ||
3357		    strcmp(vdev_type, VDEV_TYPE_MISSING) == 0) {
3358			return (B_FALSE);
3359		}
3360	} else if (vd->vdev_wholedisk == 1) {
3361		return (B_FALSE);
3362	}
3363
3364	for (int c = 0; c < vd->vdev_children; c++) {
3365		if (!vdev_is_bootable(vd->vdev_child[c]))
3366			return (B_FALSE);
3367	}
3368#endif	/* sun */
3369	return (B_TRUE);
3370}
3371
3372/*
3373 * Load the state from the original vdev tree (ovd) which
3374 * we've retrieved from the MOS config object. If the original
3375 * vdev was offline or faulted then we transfer that state to the
3376 * device in the current vdev tree (nvd).
3377 */
3378void
3379vdev_load_log_state(vdev_t *nvd, vdev_t *ovd)
3380{
3381	spa_t *spa = nvd->vdev_spa;
3382
3383	ASSERT(nvd->vdev_top->vdev_islog);
3384	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
3385	ASSERT3U(nvd->vdev_guid, ==, ovd->vdev_guid);
3386
3387	for (int c = 0; c < nvd->vdev_children; c++)
3388		vdev_load_log_state(nvd->vdev_child[c], ovd->vdev_child[c]);
3389
3390	if (nvd->vdev_ops->vdev_op_leaf) {
3391		/*
3392		 * Restore the persistent vdev state
3393		 */
3394		nvd->vdev_offline = ovd->vdev_offline;
3395		nvd->vdev_faulted = ovd->vdev_faulted;
3396		nvd->vdev_degraded = ovd->vdev_degraded;
3397		nvd->vdev_removed = ovd->vdev_removed;
3398	}
3399}
3400
3401/*
3402 * Determine if a log device has valid content.  If the vdev was
3403 * removed or faulted in the MOS config then we know that
3404 * the content on the log device has already been written to the pool.
3405 */
3406boolean_t
3407vdev_log_state_valid(vdev_t *vd)
3408{
3409	if (vd->vdev_ops->vdev_op_leaf && !vd->vdev_faulted &&
3410	    !vd->vdev_removed)
3411		return (B_TRUE);
3412
3413	for (int c = 0; c < vd->vdev_children; c++)
3414		if (vdev_log_state_valid(vd->vdev_child[c]))
3415			return (B_TRUE);
3416
3417	return (B_FALSE);
3418}
3419
3420/*
3421 * Expand a vdev if possible.
3422 */
3423void
3424vdev_expand(vdev_t *vd, uint64_t txg)
3425{
3426	ASSERT(vd->vdev_top == vd);
3427	ASSERT(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3428
3429	if ((vd->vdev_asize >> vd->vdev_ms_shift) > vd->vdev_ms_count) {
3430		VERIFY(vdev_metaslab_init(vd, txg) == 0);
3431		vdev_config_dirty(vd);
3432	}
3433}
3434
3435/*
3436 * Split a vdev.
3437 */
3438void
3439vdev_split(vdev_t *vd)
3440{
3441	vdev_t *cvd, *pvd = vd->vdev_parent;
3442
3443	vdev_remove_child(pvd, vd);
3444	vdev_compact_children(pvd);
3445
3446	cvd = pvd->vdev_child[0];
3447	if (pvd->vdev_children == 1) {
3448		vdev_remove_parent(cvd);
3449		cvd->vdev_splitting = B_TRUE;
3450	}
3451	vdev_propagate_state(cvd);
3452}
3453
3454void
3455vdev_deadman(vdev_t *vd)
3456{
3457	for (int c = 0; c < vd->vdev_children; c++) {
3458		vdev_t *cvd = vd->vdev_child[c];
3459
3460		vdev_deadman(cvd);
3461	}
3462
3463	if (vd->vdev_ops->vdev_op_leaf) {
3464		vdev_queue_t *vq = &vd->vdev_queue;
3465
3466		mutex_enter(&vq->vq_lock);
3467		if (avl_numnodes(&vq->vq_active_tree) > 0) {
3468			spa_t *spa = vd->vdev_spa;
3469			zio_t *fio;
3470			uint64_t delta;
3471
3472			/*
3473			 * Look at the head of all the pending queues,
3474			 * if any I/O has been outstanding for longer than
3475			 * the spa_deadman_synctime we panic the system.
3476			 */
3477			fio = avl_first(&vq->vq_active_tree);
3478			delta = gethrtime() - fio->io_timestamp;
3479			if (delta > spa_deadman_synctime(spa)) {
3480				zfs_dbgmsg("SLOW IO: zio timestamp %lluns, "
3481				    "delta %lluns, last io %lluns",
3482				    fio->io_timestamp, delta,
3483				    vq->vq_io_complete_ts);
3484				fm_panic("I/O to pool '%s' appears to be "
3485				    "hung on vdev guid %llu at '%s'.",
3486				    spa_name(spa),
3487				    (long long unsigned int) vd->vdev_guid,
3488				    vd->vdev_path);
3489			}
3490		}
3491		mutex_exit(&vq->vq_lock);
3492	}
3493}
3494