spa.c revision 324010
1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22/*
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
25 * Copyright (c) 2015, Nexenta Systems, Inc.  All rights reserved.
26 * Copyright (c) 2013 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
27 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28 * Copyright 2013 Saso Kiselkov. All rights reserved.
29 * Copyright (c) 2014 Integros [integros.com]
30 * Copyright (c) 2017 Datto Inc.
31 */
32
33/*
34 * SPA: Storage Pool Allocator
35 *
36 * This file contains all the routines used when modifying on-disk SPA state.
37 * This includes opening, importing, destroying, exporting a pool, and syncing a
38 * pool.
39 */
40
41#include <sys/zfs_context.h>
42#include <sys/fm/fs/zfs.h>
43#include <sys/spa_impl.h>
44#include <sys/zio.h>
45#include <sys/zio_checksum.h>
46#include <sys/dmu.h>
47#include <sys/dmu_tx.h>
48#include <sys/zap.h>
49#include <sys/zil.h>
50#include <sys/ddt.h>
51#include <sys/vdev_impl.h>
52#include <sys/metaslab.h>
53#include <sys/metaslab_impl.h>
54#include <sys/uberblock_impl.h>
55#include <sys/txg.h>
56#include <sys/avl.h>
57#include <sys/dmu_traverse.h>
58#include <sys/dmu_objset.h>
59#include <sys/unique.h>
60#include <sys/dsl_pool.h>
61#include <sys/dsl_dataset.h>
62#include <sys/dsl_dir.h>
63#include <sys/dsl_prop.h>
64#include <sys/dsl_synctask.h>
65#include <sys/fs/zfs.h>
66#include <sys/arc.h>
67#include <sys/callb.h>
68#include <sys/spa_boot.h>
69#include <sys/zfs_ioctl.h>
70#include <sys/dsl_scan.h>
71#include <sys/dmu_send.h>
72#include <sys/dsl_destroy.h>
73#include <sys/dsl_userhold.h>
74#include <sys/zfeature.h>
75#include <sys/zvol.h>
76#include <sys/trim_map.h>
77#include <sys/abd.h>
78
79#ifdef	_KERNEL
80#include <sys/callb.h>
81#include <sys/cpupart.h>
82#include <sys/zone.h>
83#endif	/* _KERNEL */
84
85#include "zfs_prop.h"
86#include "zfs_comutil.h"
87
88/* Check hostid on import? */
89static int check_hostid = 1;
90
91/*
92 * The interval, in seconds, at which failed configuration cache file writes
93 * should be retried.
94 */
95static int zfs_ccw_retry_interval = 300;
96
97SYSCTL_DECL(_vfs_zfs);
98SYSCTL_INT(_vfs_zfs, OID_AUTO, check_hostid, CTLFLAG_RWTUN, &check_hostid, 0,
99    "Check hostid on import?");
100TUNABLE_INT("vfs.zfs.ccw_retry_interval", &zfs_ccw_retry_interval);
101SYSCTL_INT(_vfs_zfs, OID_AUTO, ccw_retry_interval, CTLFLAG_RW,
102    &zfs_ccw_retry_interval, 0,
103    "Configuration cache file write, retry after failure, interval (seconds)");
104
105typedef enum zti_modes {
106	ZTI_MODE_FIXED,			/* value is # of threads (min 1) */
107	ZTI_MODE_BATCH,			/* cpu-intensive; value is ignored */
108	ZTI_MODE_NULL,			/* don't create a taskq */
109	ZTI_NMODES
110} zti_modes_t;
111
112#define	ZTI_P(n, q)	{ ZTI_MODE_FIXED, (n), (q) }
113#define	ZTI_BATCH	{ ZTI_MODE_BATCH, 0, 1 }
114#define	ZTI_NULL	{ ZTI_MODE_NULL, 0, 0 }
115
116#define	ZTI_N(n)	ZTI_P(n, 1)
117#define	ZTI_ONE		ZTI_N(1)
118
119typedef struct zio_taskq_info {
120	zti_modes_t zti_mode;
121	uint_t zti_value;
122	uint_t zti_count;
123} zio_taskq_info_t;
124
125static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
126	"issue", "issue_high", "intr", "intr_high"
127};
128
129/*
130 * This table defines the taskq settings for each ZFS I/O type. When
131 * initializing a pool, we use this table to create an appropriately sized
132 * taskq. Some operations are low volume and therefore have a small, static
133 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
134 * macros. Other operations process a large amount of data; the ZTI_BATCH
135 * macro causes us to create a taskq oriented for throughput. Some operations
136 * are so high frequency and short-lived that the taskq itself can become a a
137 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
138 * additional degree of parallelism specified by the number of threads per-
139 * taskq and the number of taskqs; when dispatching an event in this case, the
140 * particular taskq is chosen at random.
141 *
142 * The different taskq priorities are to handle the different contexts (issue
143 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
144 * need to be handled with minimum delay.
145 */
146const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
147	/* ISSUE	ISSUE_HIGH	INTR		INTR_HIGH */
148	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* NULL */
149	{ ZTI_N(8),	ZTI_NULL,	ZTI_P(12, 8),	ZTI_NULL }, /* READ */
150	{ ZTI_BATCH,	ZTI_N(5),	ZTI_N(8),	ZTI_N(5) }, /* WRITE */
151	{ ZTI_P(12, 8),	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* FREE */
152	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* CLAIM */
153	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* IOCTL */
154};
155
156static sysevent_t *spa_event_create(spa_t *spa, vdev_t *vd, const char *name);
157static void spa_event_post(sysevent_t *ev);
158static void spa_sync_version(void *arg, dmu_tx_t *tx);
159static void spa_sync_props(void *arg, dmu_tx_t *tx);
160static boolean_t spa_has_active_shared_spare(spa_t *spa);
161static int spa_load_impl(spa_t *spa, uint64_t, nvlist_t *config,
162    spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
163    char **ereport);
164static void spa_vdev_resilver_done(spa_t *spa);
165
166uint_t		zio_taskq_batch_pct = 75;	/* 1 thread per cpu in pset */
167#ifdef PSRSET_BIND
168id_t		zio_taskq_psrset_bind = PS_NONE;
169#endif
170#ifdef SYSDC
171boolean_t	zio_taskq_sysdc = B_TRUE;	/* use SDC scheduling class */
172uint_t		zio_taskq_basedc = 80;		/* base duty cycle */
173#endif
174
175boolean_t	spa_create_process = B_TRUE;	/* no process ==> no sysdc */
176extern int	zfs_sync_pass_deferred_free;
177
178/*
179 * This (illegal) pool name is used when temporarily importing a spa_t in order
180 * to get the vdev stats associated with the imported devices.
181 */
182#define	TRYIMPORT_NAME	"$import"
183
184/*
185 * ==========================================================================
186 * SPA properties routines
187 * ==========================================================================
188 */
189
190/*
191 * Add a (source=src, propname=propval) list to an nvlist.
192 */
193static void
194spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
195    uint64_t intval, zprop_source_t src)
196{
197	const char *propname = zpool_prop_to_name(prop);
198	nvlist_t *propval;
199
200	VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
201	VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
202
203	if (strval != NULL)
204		VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
205	else
206		VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
207
208	VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
209	nvlist_free(propval);
210}
211
212/*
213 * Get property values from the spa configuration.
214 */
215static void
216spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
217{
218	vdev_t *rvd = spa->spa_root_vdev;
219	dsl_pool_t *pool = spa->spa_dsl_pool;
220	uint64_t size, alloc, cap, version;
221	zprop_source_t src = ZPROP_SRC_NONE;
222	spa_config_dirent_t *dp;
223	metaslab_class_t *mc = spa_normal_class(spa);
224
225	ASSERT(MUTEX_HELD(&spa->spa_props_lock));
226
227	if (rvd != NULL) {
228		alloc = metaslab_class_get_alloc(spa_normal_class(spa));
229		size = metaslab_class_get_space(spa_normal_class(spa));
230		spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
231		spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
232		spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
233		spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
234		    size - alloc, src);
235
236		spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
237		    metaslab_class_fragmentation(mc), src);
238		spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
239		    metaslab_class_expandable_space(mc), src);
240		spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
241		    (spa_mode(spa) == FREAD), src);
242
243		cap = (size == 0) ? 0 : (alloc * 100 / size);
244		spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
245
246		spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
247		    ddt_get_pool_dedup_ratio(spa), src);
248
249		spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
250		    rvd->vdev_state, src);
251
252		version = spa_version(spa);
253		if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
254			src = ZPROP_SRC_DEFAULT;
255		else
256			src = ZPROP_SRC_LOCAL;
257		spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
258	}
259
260	if (pool != NULL) {
261		/*
262		 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
263		 * when opening pools before this version freedir will be NULL.
264		 */
265		if (pool->dp_free_dir != NULL) {
266			spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
267			    dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
268			    src);
269		} else {
270			spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
271			    NULL, 0, src);
272		}
273
274		if (pool->dp_leak_dir != NULL) {
275			spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
276			    dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
277			    src);
278		} else {
279			spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
280			    NULL, 0, src);
281		}
282	}
283
284	spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
285
286	if (spa->spa_comment != NULL) {
287		spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
288		    0, ZPROP_SRC_LOCAL);
289	}
290
291	if (spa->spa_root != NULL)
292		spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
293		    0, ZPROP_SRC_LOCAL);
294
295	if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
296		spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
297		    MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
298	} else {
299		spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
300		    SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
301	}
302
303	if ((dp = list_head(&spa->spa_config_list)) != NULL) {
304		if (dp->scd_path == NULL) {
305			spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
306			    "none", 0, ZPROP_SRC_LOCAL);
307		} else if (strcmp(dp->scd_path, spa_config_path) != 0) {
308			spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
309			    dp->scd_path, 0, ZPROP_SRC_LOCAL);
310		}
311	}
312}
313
314/*
315 * Get zpool property values.
316 */
317int
318spa_prop_get(spa_t *spa, nvlist_t **nvp)
319{
320	objset_t *mos = spa->spa_meta_objset;
321	zap_cursor_t zc;
322	zap_attribute_t za;
323	int err;
324
325	VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
326
327	mutex_enter(&spa->spa_props_lock);
328
329	/*
330	 * Get properties from the spa config.
331	 */
332	spa_prop_get_config(spa, nvp);
333
334	/* If no pool property object, no more prop to get. */
335	if (mos == NULL || spa->spa_pool_props_object == 0) {
336		mutex_exit(&spa->spa_props_lock);
337		return (0);
338	}
339
340	/*
341	 * Get properties from the MOS pool property object.
342	 */
343	for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
344	    (err = zap_cursor_retrieve(&zc, &za)) == 0;
345	    zap_cursor_advance(&zc)) {
346		uint64_t intval = 0;
347		char *strval = NULL;
348		zprop_source_t src = ZPROP_SRC_DEFAULT;
349		zpool_prop_t prop;
350
351		if ((prop = zpool_name_to_prop(za.za_name)) == ZPROP_INVAL)
352			continue;
353
354		switch (za.za_integer_length) {
355		case 8:
356			/* integer property */
357			if (za.za_first_integer !=
358			    zpool_prop_default_numeric(prop))
359				src = ZPROP_SRC_LOCAL;
360
361			if (prop == ZPOOL_PROP_BOOTFS) {
362				dsl_pool_t *dp;
363				dsl_dataset_t *ds = NULL;
364
365				dp = spa_get_dsl(spa);
366				dsl_pool_config_enter(dp, FTAG);
367				if (err = dsl_dataset_hold_obj(dp,
368				    za.za_first_integer, FTAG, &ds)) {
369					dsl_pool_config_exit(dp, FTAG);
370					break;
371				}
372
373				strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
374				    KM_SLEEP);
375				dsl_dataset_name(ds, strval);
376				dsl_dataset_rele(ds, FTAG);
377				dsl_pool_config_exit(dp, FTAG);
378			} else {
379				strval = NULL;
380				intval = za.za_first_integer;
381			}
382
383			spa_prop_add_list(*nvp, prop, strval, intval, src);
384
385			if (strval != NULL)
386				kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
387
388			break;
389
390		case 1:
391			/* string property */
392			strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
393			err = zap_lookup(mos, spa->spa_pool_props_object,
394			    za.za_name, 1, za.za_num_integers, strval);
395			if (err) {
396				kmem_free(strval, za.za_num_integers);
397				break;
398			}
399			spa_prop_add_list(*nvp, prop, strval, 0, src);
400			kmem_free(strval, za.za_num_integers);
401			break;
402
403		default:
404			break;
405		}
406	}
407	zap_cursor_fini(&zc);
408	mutex_exit(&spa->spa_props_lock);
409out:
410	if (err && err != ENOENT) {
411		nvlist_free(*nvp);
412		*nvp = NULL;
413		return (err);
414	}
415
416	return (0);
417}
418
419/*
420 * Validate the given pool properties nvlist and modify the list
421 * for the property values to be set.
422 */
423static int
424spa_prop_validate(spa_t *spa, nvlist_t *props)
425{
426	nvpair_t *elem;
427	int error = 0, reset_bootfs = 0;
428	uint64_t objnum = 0;
429	boolean_t has_feature = B_FALSE;
430
431	elem = NULL;
432	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
433		uint64_t intval;
434		char *strval, *slash, *check, *fname;
435		const char *propname = nvpair_name(elem);
436		zpool_prop_t prop = zpool_name_to_prop(propname);
437
438		switch (prop) {
439		case ZPROP_INVAL:
440			if (!zpool_prop_feature(propname)) {
441				error = SET_ERROR(EINVAL);
442				break;
443			}
444
445			/*
446			 * Sanitize the input.
447			 */
448			if (nvpair_type(elem) != DATA_TYPE_UINT64) {
449				error = SET_ERROR(EINVAL);
450				break;
451			}
452
453			if (nvpair_value_uint64(elem, &intval) != 0) {
454				error = SET_ERROR(EINVAL);
455				break;
456			}
457
458			if (intval != 0) {
459				error = SET_ERROR(EINVAL);
460				break;
461			}
462
463			fname = strchr(propname, '@') + 1;
464			if (zfeature_lookup_name(fname, NULL) != 0) {
465				error = SET_ERROR(EINVAL);
466				break;
467			}
468
469			has_feature = B_TRUE;
470			break;
471
472		case ZPOOL_PROP_VERSION:
473			error = nvpair_value_uint64(elem, &intval);
474			if (!error &&
475			    (intval < spa_version(spa) ||
476			    intval > SPA_VERSION_BEFORE_FEATURES ||
477			    has_feature))
478				error = SET_ERROR(EINVAL);
479			break;
480
481		case ZPOOL_PROP_DELEGATION:
482		case ZPOOL_PROP_AUTOREPLACE:
483		case ZPOOL_PROP_LISTSNAPS:
484		case ZPOOL_PROP_AUTOEXPAND:
485			error = nvpair_value_uint64(elem, &intval);
486			if (!error && intval > 1)
487				error = SET_ERROR(EINVAL);
488			break;
489
490		case ZPOOL_PROP_BOOTFS:
491			/*
492			 * If the pool version is less than SPA_VERSION_BOOTFS,
493			 * or the pool is still being created (version == 0),
494			 * the bootfs property cannot be set.
495			 */
496			if (spa_version(spa) < SPA_VERSION_BOOTFS) {
497				error = SET_ERROR(ENOTSUP);
498				break;
499			}
500
501			/*
502			 * Make sure the vdev config is bootable
503			 */
504			if (!vdev_is_bootable(spa->spa_root_vdev)) {
505				error = SET_ERROR(ENOTSUP);
506				break;
507			}
508
509			reset_bootfs = 1;
510
511			error = nvpair_value_string(elem, &strval);
512
513			if (!error) {
514				objset_t *os;
515				uint64_t propval;
516
517				if (strval == NULL || strval[0] == '\0') {
518					objnum = zpool_prop_default_numeric(
519					    ZPOOL_PROP_BOOTFS);
520					break;
521				}
522
523				if (error = dmu_objset_hold(strval, FTAG, &os))
524					break;
525
526				/*
527				 * Must be ZPL, and its property settings
528				 * must be supported by GRUB (compression
529				 * is not gzip, and large blocks are not used).
530				 */
531
532				if (dmu_objset_type(os) != DMU_OST_ZFS) {
533					error = SET_ERROR(ENOTSUP);
534				} else if ((error =
535				    dsl_prop_get_int_ds(dmu_objset_ds(os),
536				    zfs_prop_to_name(ZFS_PROP_COMPRESSION),
537				    &propval)) == 0 &&
538				    !BOOTFS_COMPRESS_VALID(propval)) {
539					error = SET_ERROR(ENOTSUP);
540				} else if ((error =
541				    dsl_prop_get_int_ds(dmu_objset_ds(os),
542				    zfs_prop_to_name(ZFS_PROP_RECORDSIZE),
543				    &propval)) == 0 &&
544				    propval > SPA_OLD_MAXBLOCKSIZE) {
545					error = SET_ERROR(ENOTSUP);
546				} else {
547					objnum = dmu_objset_id(os);
548				}
549				dmu_objset_rele(os, FTAG);
550			}
551			break;
552
553		case ZPOOL_PROP_FAILUREMODE:
554			error = nvpair_value_uint64(elem, &intval);
555			if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
556			    intval > ZIO_FAILURE_MODE_PANIC))
557				error = SET_ERROR(EINVAL);
558
559			/*
560			 * This is a special case which only occurs when
561			 * the pool has completely failed. This allows
562			 * the user to change the in-core failmode property
563			 * without syncing it out to disk (I/Os might
564			 * currently be blocked). We do this by returning
565			 * EIO to the caller (spa_prop_set) to trick it
566			 * into thinking we encountered a property validation
567			 * error.
568			 */
569			if (!error && spa_suspended(spa)) {
570				spa->spa_failmode = intval;
571				error = SET_ERROR(EIO);
572			}
573			break;
574
575		case ZPOOL_PROP_CACHEFILE:
576			if ((error = nvpair_value_string(elem, &strval)) != 0)
577				break;
578
579			if (strval[0] == '\0')
580				break;
581
582			if (strcmp(strval, "none") == 0)
583				break;
584
585			if (strval[0] != '/') {
586				error = SET_ERROR(EINVAL);
587				break;
588			}
589
590			slash = strrchr(strval, '/');
591			ASSERT(slash != NULL);
592
593			if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
594			    strcmp(slash, "/..") == 0)
595				error = SET_ERROR(EINVAL);
596			break;
597
598		case ZPOOL_PROP_COMMENT:
599			if ((error = nvpair_value_string(elem, &strval)) != 0)
600				break;
601			for (check = strval; *check != '\0'; check++) {
602				/*
603				 * The kernel doesn't have an easy isprint()
604				 * check.  For this kernel check, we merely
605				 * check ASCII apart from DEL.  Fix this if
606				 * there is an easy-to-use kernel isprint().
607				 */
608				if (*check >= 0x7f) {
609					error = SET_ERROR(EINVAL);
610					break;
611				}
612			}
613			if (strlen(strval) > ZPROP_MAX_COMMENT)
614				error = E2BIG;
615			break;
616
617		case ZPOOL_PROP_DEDUPDITTO:
618			if (spa_version(spa) < SPA_VERSION_DEDUP)
619				error = SET_ERROR(ENOTSUP);
620			else
621				error = nvpair_value_uint64(elem, &intval);
622			if (error == 0 &&
623			    intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
624				error = SET_ERROR(EINVAL);
625			break;
626		}
627
628		if (error)
629			break;
630	}
631
632	if (!error && reset_bootfs) {
633		error = nvlist_remove(props,
634		    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
635
636		if (!error) {
637			error = nvlist_add_uint64(props,
638			    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
639		}
640	}
641
642	return (error);
643}
644
645void
646spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
647{
648	char *cachefile;
649	spa_config_dirent_t *dp;
650
651	if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
652	    &cachefile) != 0)
653		return;
654
655	dp = kmem_alloc(sizeof (spa_config_dirent_t),
656	    KM_SLEEP);
657
658	if (cachefile[0] == '\0')
659		dp->scd_path = spa_strdup(spa_config_path);
660	else if (strcmp(cachefile, "none") == 0)
661		dp->scd_path = NULL;
662	else
663		dp->scd_path = spa_strdup(cachefile);
664
665	list_insert_head(&spa->spa_config_list, dp);
666	if (need_sync)
667		spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
668}
669
670int
671spa_prop_set(spa_t *spa, nvlist_t *nvp)
672{
673	int error;
674	nvpair_t *elem = NULL;
675	boolean_t need_sync = B_FALSE;
676
677	if ((error = spa_prop_validate(spa, nvp)) != 0)
678		return (error);
679
680	while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
681		zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
682
683		if (prop == ZPOOL_PROP_CACHEFILE ||
684		    prop == ZPOOL_PROP_ALTROOT ||
685		    prop == ZPOOL_PROP_READONLY)
686			continue;
687
688		if (prop == ZPOOL_PROP_VERSION || prop == ZPROP_INVAL) {
689			uint64_t ver;
690
691			if (prop == ZPOOL_PROP_VERSION) {
692				VERIFY(nvpair_value_uint64(elem, &ver) == 0);
693			} else {
694				ASSERT(zpool_prop_feature(nvpair_name(elem)));
695				ver = SPA_VERSION_FEATURES;
696				need_sync = B_TRUE;
697			}
698
699			/* Save time if the version is already set. */
700			if (ver == spa_version(spa))
701				continue;
702
703			/*
704			 * In addition to the pool directory object, we might
705			 * create the pool properties object, the features for
706			 * read object, the features for write object, or the
707			 * feature descriptions object.
708			 */
709			error = dsl_sync_task(spa->spa_name, NULL,
710			    spa_sync_version, &ver,
711			    6, ZFS_SPACE_CHECK_RESERVED);
712			if (error)
713				return (error);
714			continue;
715		}
716
717		need_sync = B_TRUE;
718		break;
719	}
720
721	if (need_sync) {
722		return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
723		    nvp, 6, ZFS_SPACE_CHECK_RESERVED));
724	}
725
726	return (0);
727}
728
729/*
730 * If the bootfs property value is dsobj, clear it.
731 */
732void
733spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
734{
735	if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
736		VERIFY(zap_remove(spa->spa_meta_objset,
737		    spa->spa_pool_props_object,
738		    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
739		spa->spa_bootfs = 0;
740	}
741}
742
743/*ARGSUSED*/
744static int
745spa_change_guid_check(void *arg, dmu_tx_t *tx)
746{
747	uint64_t *newguid = arg;
748	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
749	vdev_t *rvd = spa->spa_root_vdev;
750	uint64_t vdev_state;
751
752	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
753	vdev_state = rvd->vdev_state;
754	spa_config_exit(spa, SCL_STATE, FTAG);
755
756	if (vdev_state != VDEV_STATE_HEALTHY)
757		return (SET_ERROR(ENXIO));
758
759	ASSERT3U(spa_guid(spa), !=, *newguid);
760
761	return (0);
762}
763
764static void
765spa_change_guid_sync(void *arg, dmu_tx_t *tx)
766{
767	uint64_t *newguid = arg;
768	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
769	uint64_t oldguid;
770	vdev_t *rvd = spa->spa_root_vdev;
771
772	oldguid = spa_guid(spa);
773
774	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
775	rvd->vdev_guid = *newguid;
776	rvd->vdev_guid_sum += (*newguid - oldguid);
777	vdev_config_dirty(rvd);
778	spa_config_exit(spa, SCL_STATE, FTAG);
779
780	spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
781	    oldguid, *newguid);
782}
783
784/*
785 * Change the GUID for the pool.  This is done so that we can later
786 * re-import a pool built from a clone of our own vdevs.  We will modify
787 * the root vdev's guid, our own pool guid, and then mark all of our
788 * vdevs dirty.  Note that we must make sure that all our vdevs are
789 * online when we do this, or else any vdevs that weren't present
790 * would be orphaned from our pool.  We are also going to issue a
791 * sysevent to update any watchers.
792 */
793int
794spa_change_guid(spa_t *spa)
795{
796	int error;
797	uint64_t guid;
798
799	mutex_enter(&spa->spa_vdev_top_lock);
800	mutex_enter(&spa_namespace_lock);
801	guid = spa_generate_guid(NULL);
802
803	error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
804	    spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
805
806	if (error == 0) {
807		spa_config_sync(spa, B_FALSE, B_TRUE);
808		spa_event_notify(spa, NULL, ESC_ZFS_POOL_REGUID);
809	}
810
811	mutex_exit(&spa_namespace_lock);
812	mutex_exit(&spa->spa_vdev_top_lock);
813
814	return (error);
815}
816
817/*
818 * ==========================================================================
819 * SPA state manipulation (open/create/destroy/import/export)
820 * ==========================================================================
821 */
822
823static int
824spa_error_entry_compare(const void *a, const void *b)
825{
826	spa_error_entry_t *sa = (spa_error_entry_t *)a;
827	spa_error_entry_t *sb = (spa_error_entry_t *)b;
828	int ret;
829
830	ret = bcmp(&sa->se_bookmark, &sb->se_bookmark,
831	    sizeof (zbookmark_phys_t));
832
833	if (ret < 0)
834		return (-1);
835	else if (ret > 0)
836		return (1);
837	else
838		return (0);
839}
840
841/*
842 * Utility function which retrieves copies of the current logs and
843 * re-initializes them in the process.
844 */
845void
846spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
847{
848	ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
849
850	bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
851	bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
852
853	avl_create(&spa->spa_errlist_scrub,
854	    spa_error_entry_compare, sizeof (spa_error_entry_t),
855	    offsetof(spa_error_entry_t, se_avl));
856	avl_create(&spa->spa_errlist_last,
857	    spa_error_entry_compare, sizeof (spa_error_entry_t),
858	    offsetof(spa_error_entry_t, se_avl));
859}
860
861static void
862spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
863{
864	const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
865	enum zti_modes mode = ztip->zti_mode;
866	uint_t value = ztip->zti_value;
867	uint_t count = ztip->zti_count;
868	spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
869	char name[32];
870	uint_t flags = 0;
871	boolean_t batch = B_FALSE;
872
873	if (mode == ZTI_MODE_NULL) {
874		tqs->stqs_count = 0;
875		tqs->stqs_taskq = NULL;
876		return;
877	}
878
879	ASSERT3U(count, >, 0);
880
881	tqs->stqs_count = count;
882	tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
883
884	switch (mode) {
885	case ZTI_MODE_FIXED:
886		ASSERT3U(value, >=, 1);
887		value = MAX(value, 1);
888		break;
889
890	case ZTI_MODE_BATCH:
891		batch = B_TRUE;
892		flags |= TASKQ_THREADS_CPU_PCT;
893		value = zio_taskq_batch_pct;
894		break;
895
896	default:
897		panic("unrecognized mode for %s_%s taskq (%u:%u) in "
898		    "spa_activate()",
899		    zio_type_name[t], zio_taskq_types[q], mode, value);
900		break;
901	}
902
903	for (uint_t i = 0; i < count; i++) {
904		taskq_t *tq;
905
906		if (count > 1) {
907			(void) snprintf(name, sizeof (name), "%s_%s_%u",
908			    zio_type_name[t], zio_taskq_types[q], i);
909		} else {
910			(void) snprintf(name, sizeof (name), "%s_%s",
911			    zio_type_name[t], zio_taskq_types[q]);
912		}
913
914#ifdef SYSDC
915		if (zio_taskq_sysdc && spa->spa_proc != &p0) {
916			if (batch)
917				flags |= TASKQ_DC_BATCH;
918
919			tq = taskq_create_sysdc(name, value, 50, INT_MAX,
920			    spa->spa_proc, zio_taskq_basedc, flags);
921		} else {
922#endif
923			pri_t pri = maxclsyspri;
924			/*
925			 * The write issue taskq can be extremely CPU
926			 * intensive.  Run it at slightly lower priority
927			 * than the other taskqs.
928			 * FreeBSD notes:
929			 * - numerically higher priorities are lower priorities;
930			 * - if priorities divided by four (RQ_PPQ) are equal
931			 *   then a difference between them is insignificant.
932			 */
933			if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
934#ifdef illumos
935				pri--;
936#else
937				pri += 4;
938#endif
939
940			tq = taskq_create_proc(name, value, pri, 50,
941			    INT_MAX, spa->spa_proc, flags);
942#ifdef SYSDC
943		}
944#endif
945
946		tqs->stqs_taskq[i] = tq;
947	}
948}
949
950static void
951spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
952{
953	spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
954
955	if (tqs->stqs_taskq == NULL) {
956		ASSERT0(tqs->stqs_count);
957		return;
958	}
959
960	for (uint_t i = 0; i < tqs->stqs_count; i++) {
961		ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
962		taskq_destroy(tqs->stqs_taskq[i]);
963	}
964
965	kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
966	tqs->stqs_taskq = NULL;
967}
968
969/*
970 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
971 * Note that a type may have multiple discrete taskqs to avoid lock contention
972 * on the taskq itself. In that case we choose which taskq at random by using
973 * the low bits of gethrtime().
974 */
975void
976spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
977    task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
978{
979	spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
980	taskq_t *tq;
981
982	ASSERT3P(tqs->stqs_taskq, !=, NULL);
983	ASSERT3U(tqs->stqs_count, !=, 0);
984
985	if (tqs->stqs_count == 1) {
986		tq = tqs->stqs_taskq[0];
987	} else {
988#ifdef _KERNEL
989		tq = tqs->stqs_taskq[cpu_ticks() % tqs->stqs_count];
990#else
991		tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
992#endif
993	}
994
995	taskq_dispatch_ent(tq, func, arg, flags, ent);
996}
997
998static void
999spa_create_zio_taskqs(spa_t *spa)
1000{
1001	for (int t = 0; t < ZIO_TYPES; t++) {
1002		for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1003			spa_taskqs_init(spa, t, q);
1004		}
1005	}
1006}
1007
1008#ifdef _KERNEL
1009#ifdef SPA_PROCESS
1010static void
1011spa_thread(void *arg)
1012{
1013	callb_cpr_t cprinfo;
1014
1015	spa_t *spa = arg;
1016	user_t *pu = PTOU(curproc);
1017
1018	CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1019	    spa->spa_name);
1020
1021	ASSERT(curproc != &p0);
1022	(void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1023	    "zpool-%s", spa->spa_name);
1024	(void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1025
1026#ifdef PSRSET_BIND
1027	/* bind this thread to the requested psrset */
1028	if (zio_taskq_psrset_bind != PS_NONE) {
1029		pool_lock();
1030		mutex_enter(&cpu_lock);
1031		mutex_enter(&pidlock);
1032		mutex_enter(&curproc->p_lock);
1033
1034		if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1035		    0, NULL, NULL) == 0)  {
1036			curthread->t_bind_pset = zio_taskq_psrset_bind;
1037		} else {
1038			cmn_err(CE_WARN,
1039			    "Couldn't bind process for zfs pool \"%s\" to "
1040			    "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1041		}
1042
1043		mutex_exit(&curproc->p_lock);
1044		mutex_exit(&pidlock);
1045		mutex_exit(&cpu_lock);
1046		pool_unlock();
1047	}
1048#endif
1049
1050#ifdef SYSDC
1051	if (zio_taskq_sysdc) {
1052		sysdc_thread_enter(curthread, 100, 0);
1053	}
1054#endif
1055
1056	spa->spa_proc = curproc;
1057	spa->spa_did = curthread->t_did;
1058
1059	spa_create_zio_taskqs(spa);
1060
1061	mutex_enter(&spa->spa_proc_lock);
1062	ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1063
1064	spa->spa_proc_state = SPA_PROC_ACTIVE;
1065	cv_broadcast(&spa->spa_proc_cv);
1066
1067	CALLB_CPR_SAFE_BEGIN(&cprinfo);
1068	while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1069		cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1070	CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1071
1072	ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1073	spa->spa_proc_state = SPA_PROC_GONE;
1074	spa->spa_proc = &p0;
1075	cv_broadcast(&spa->spa_proc_cv);
1076	CALLB_CPR_EXIT(&cprinfo);	/* drops spa_proc_lock */
1077
1078	mutex_enter(&curproc->p_lock);
1079	lwp_exit();
1080}
1081#endif	/* SPA_PROCESS */
1082#endif
1083
1084/*
1085 * Activate an uninitialized pool.
1086 */
1087static void
1088spa_activate(spa_t *spa, int mode)
1089{
1090	ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1091
1092	spa->spa_state = POOL_STATE_ACTIVE;
1093	spa->spa_mode = mode;
1094
1095	spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1096	spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1097
1098	/* Try to create a covering process */
1099	mutex_enter(&spa->spa_proc_lock);
1100	ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1101	ASSERT(spa->spa_proc == &p0);
1102	spa->spa_did = 0;
1103
1104#ifdef SPA_PROCESS
1105	/* Only create a process if we're going to be around a while. */
1106	if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1107		if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1108		    NULL, 0) == 0) {
1109			spa->spa_proc_state = SPA_PROC_CREATED;
1110			while (spa->spa_proc_state == SPA_PROC_CREATED) {
1111				cv_wait(&spa->spa_proc_cv,
1112				    &spa->spa_proc_lock);
1113			}
1114			ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1115			ASSERT(spa->spa_proc != &p0);
1116			ASSERT(spa->spa_did != 0);
1117		} else {
1118#ifdef _KERNEL
1119			cmn_err(CE_WARN,
1120			    "Couldn't create process for zfs pool \"%s\"\n",
1121			    spa->spa_name);
1122#endif
1123		}
1124	}
1125#endif	/* SPA_PROCESS */
1126	mutex_exit(&spa->spa_proc_lock);
1127
1128	/* If we didn't create a process, we need to create our taskqs. */
1129	ASSERT(spa->spa_proc == &p0);
1130	if (spa->spa_proc == &p0) {
1131		spa_create_zio_taskqs(spa);
1132	}
1133
1134	/*
1135	 * Start TRIM thread.
1136	 */
1137	trim_thread_create(spa);
1138
1139	list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1140	    offsetof(vdev_t, vdev_config_dirty_node));
1141	list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1142	    offsetof(objset_t, os_evicting_node));
1143	list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1144	    offsetof(vdev_t, vdev_state_dirty_node));
1145
1146	txg_list_create(&spa->spa_vdev_txg_list, spa,
1147	    offsetof(struct vdev, vdev_txg_node));
1148
1149	avl_create(&spa->spa_errlist_scrub,
1150	    spa_error_entry_compare, sizeof (spa_error_entry_t),
1151	    offsetof(spa_error_entry_t, se_avl));
1152	avl_create(&spa->spa_errlist_last,
1153	    spa_error_entry_compare, sizeof (spa_error_entry_t),
1154	    offsetof(spa_error_entry_t, se_avl));
1155}
1156
1157/*
1158 * Opposite of spa_activate().
1159 */
1160static void
1161spa_deactivate(spa_t *spa)
1162{
1163	ASSERT(spa->spa_sync_on == B_FALSE);
1164	ASSERT(spa->spa_dsl_pool == NULL);
1165	ASSERT(spa->spa_root_vdev == NULL);
1166	ASSERT(spa->spa_async_zio_root == NULL);
1167	ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1168
1169	/*
1170	 * Stop TRIM thread in case spa_unload() wasn't called directly
1171	 * before spa_deactivate().
1172	 */
1173	trim_thread_destroy(spa);
1174
1175	spa_evicting_os_wait(spa);
1176
1177	txg_list_destroy(&spa->spa_vdev_txg_list);
1178
1179	list_destroy(&spa->spa_config_dirty_list);
1180	list_destroy(&spa->spa_evicting_os_list);
1181	list_destroy(&spa->spa_state_dirty_list);
1182
1183	for (int t = 0; t < ZIO_TYPES; t++) {
1184		for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1185			spa_taskqs_fini(spa, t, q);
1186		}
1187	}
1188
1189	metaslab_class_destroy(spa->spa_normal_class);
1190	spa->spa_normal_class = NULL;
1191
1192	metaslab_class_destroy(spa->spa_log_class);
1193	spa->spa_log_class = NULL;
1194
1195	/*
1196	 * If this was part of an import or the open otherwise failed, we may
1197	 * still have errors left in the queues.  Empty them just in case.
1198	 */
1199	spa_errlog_drain(spa);
1200
1201	avl_destroy(&spa->spa_errlist_scrub);
1202	avl_destroy(&spa->spa_errlist_last);
1203
1204	spa->spa_state = POOL_STATE_UNINITIALIZED;
1205
1206	mutex_enter(&spa->spa_proc_lock);
1207	if (spa->spa_proc_state != SPA_PROC_NONE) {
1208		ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1209		spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1210		cv_broadcast(&spa->spa_proc_cv);
1211		while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1212			ASSERT(spa->spa_proc != &p0);
1213			cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1214		}
1215		ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1216		spa->spa_proc_state = SPA_PROC_NONE;
1217	}
1218	ASSERT(spa->spa_proc == &p0);
1219	mutex_exit(&spa->spa_proc_lock);
1220
1221#ifdef SPA_PROCESS
1222	/*
1223	 * We want to make sure spa_thread() has actually exited the ZFS
1224	 * module, so that the module can't be unloaded out from underneath
1225	 * it.
1226	 */
1227	if (spa->spa_did != 0) {
1228		thread_join(spa->spa_did);
1229		spa->spa_did = 0;
1230	}
1231#endif	/* SPA_PROCESS */
1232}
1233
1234/*
1235 * Verify a pool configuration, and construct the vdev tree appropriately.  This
1236 * will create all the necessary vdevs in the appropriate layout, with each vdev
1237 * in the CLOSED state.  This will prep the pool before open/creation/import.
1238 * All vdev validation is done by the vdev_alloc() routine.
1239 */
1240static int
1241spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1242    uint_t id, int atype)
1243{
1244	nvlist_t **child;
1245	uint_t children;
1246	int error;
1247
1248	if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1249		return (error);
1250
1251	if ((*vdp)->vdev_ops->vdev_op_leaf)
1252		return (0);
1253
1254	error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1255	    &child, &children);
1256
1257	if (error == ENOENT)
1258		return (0);
1259
1260	if (error) {
1261		vdev_free(*vdp);
1262		*vdp = NULL;
1263		return (SET_ERROR(EINVAL));
1264	}
1265
1266	for (int c = 0; c < children; c++) {
1267		vdev_t *vd;
1268		if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1269		    atype)) != 0) {
1270			vdev_free(*vdp);
1271			*vdp = NULL;
1272			return (error);
1273		}
1274	}
1275
1276	ASSERT(*vdp != NULL);
1277
1278	return (0);
1279}
1280
1281/*
1282 * Opposite of spa_load().
1283 */
1284static void
1285spa_unload(spa_t *spa)
1286{
1287	int i;
1288
1289	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1290
1291	/*
1292	 * Stop TRIM thread.
1293	 */
1294	trim_thread_destroy(spa);
1295
1296	/*
1297	 * Stop async tasks.
1298	 */
1299	spa_async_suspend(spa);
1300
1301	/*
1302	 * Stop syncing.
1303	 */
1304	if (spa->spa_sync_on) {
1305		txg_sync_stop(spa->spa_dsl_pool);
1306		spa->spa_sync_on = B_FALSE;
1307	}
1308
1309	/*
1310	 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1311	 * to call it earlier, before we wait for async i/o to complete.
1312	 * This ensures that there is no async metaslab prefetching, by
1313	 * calling taskq_wait(mg_taskq).
1314	 */
1315	if (spa->spa_root_vdev != NULL) {
1316		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1317		for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1318			vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1319		spa_config_exit(spa, SCL_ALL, FTAG);
1320	}
1321
1322	/*
1323	 * Wait for any outstanding async I/O to complete.
1324	 */
1325	if (spa->spa_async_zio_root != NULL) {
1326		for (int i = 0; i < max_ncpus; i++)
1327			(void) zio_wait(spa->spa_async_zio_root[i]);
1328		kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1329		spa->spa_async_zio_root = NULL;
1330	}
1331
1332	bpobj_close(&spa->spa_deferred_bpobj);
1333
1334	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1335
1336	/*
1337	 * Close all vdevs.
1338	 */
1339	if (spa->spa_root_vdev)
1340		vdev_free(spa->spa_root_vdev);
1341	ASSERT(spa->spa_root_vdev == NULL);
1342
1343	/*
1344	 * Close the dsl pool.
1345	 */
1346	if (spa->spa_dsl_pool) {
1347		dsl_pool_close(spa->spa_dsl_pool);
1348		spa->spa_dsl_pool = NULL;
1349		spa->spa_meta_objset = NULL;
1350	}
1351
1352	ddt_unload(spa);
1353
1354	/*
1355	 * Drop and purge level 2 cache
1356	 */
1357	spa_l2cache_drop(spa);
1358
1359	for (i = 0; i < spa->spa_spares.sav_count; i++)
1360		vdev_free(spa->spa_spares.sav_vdevs[i]);
1361	if (spa->spa_spares.sav_vdevs) {
1362		kmem_free(spa->spa_spares.sav_vdevs,
1363		    spa->spa_spares.sav_count * sizeof (void *));
1364		spa->spa_spares.sav_vdevs = NULL;
1365	}
1366	if (spa->spa_spares.sav_config) {
1367		nvlist_free(spa->spa_spares.sav_config);
1368		spa->spa_spares.sav_config = NULL;
1369	}
1370	spa->spa_spares.sav_count = 0;
1371
1372	for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1373		vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1374		vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1375	}
1376	if (spa->spa_l2cache.sav_vdevs) {
1377		kmem_free(spa->spa_l2cache.sav_vdevs,
1378		    spa->spa_l2cache.sav_count * sizeof (void *));
1379		spa->spa_l2cache.sav_vdevs = NULL;
1380	}
1381	if (spa->spa_l2cache.sav_config) {
1382		nvlist_free(spa->spa_l2cache.sav_config);
1383		spa->spa_l2cache.sav_config = NULL;
1384	}
1385	spa->spa_l2cache.sav_count = 0;
1386
1387	spa->spa_async_suspended = 0;
1388
1389	if (spa->spa_comment != NULL) {
1390		spa_strfree(spa->spa_comment);
1391		spa->spa_comment = NULL;
1392	}
1393
1394	spa_config_exit(spa, SCL_ALL, FTAG);
1395}
1396
1397/*
1398 * Load (or re-load) the current list of vdevs describing the active spares for
1399 * this pool.  When this is called, we have some form of basic information in
1400 * 'spa_spares.sav_config'.  We parse this into vdevs, try to open them, and
1401 * then re-generate a more complete list including status information.
1402 */
1403static void
1404spa_load_spares(spa_t *spa)
1405{
1406	nvlist_t **spares;
1407	uint_t nspares;
1408	int i;
1409	vdev_t *vd, *tvd;
1410
1411	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1412
1413	/*
1414	 * First, close and free any existing spare vdevs.
1415	 */
1416	for (i = 0; i < spa->spa_spares.sav_count; i++) {
1417		vd = spa->spa_spares.sav_vdevs[i];
1418
1419		/* Undo the call to spa_activate() below */
1420		if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1421		    B_FALSE)) != NULL && tvd->vdev_isspare)
1422			spa_spare_remove(tvd);
1423		vdev_close(vd);
1424		vdev_free(vd);
1425	}
1426
1427	if (spa->spa_spares.sav_vdevs)
1428		kmem_free(spa->spa_spares.sav_vdevs,
1429		    spa->spa_spares.sav_count * sizeof (void *));
1430
1431	if (spa->spa_spares.sav_config == NULL)
1432		nspares = 0;
1433	else
1434		VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1435		    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1436
1437	spa->spa_spares.sav_count = (int)nspares;
1438	spa->spa_spares.sav_vdevs = NULL;
1439
1440	if (nspares == 0)
1441		return;
1442
1443	/*
1444	 * Construct the array of vdevs, opening them to get status in the
1445	 * process.   For each spare, there is potentially two different vdev_t
1446	 * structures associated with it: one in the list of spares (used only
1447	 * for basic validation purposes) and one in the active vdev
1448	 * configuration (if it's spared in).  During this phase we open and
1449	 * validate each vdev on the spare list.  If the vdev also exists in the
1450	 * active configuration, then we also mark this vdev as an active spare.
1451	 */
1452	spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1453	    KM_SLEEP);
1454	for (i = 0; i < spa->spa_spares.sav_count; i++) {
1455		VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1456		    VDEV_ALLOC_SPARE) == 0);
1457		ASSERT(vd != NULL);
1458
1459		spa->spa_spares.sav_vdevs[i] = vd;
1460
1461		if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1462		    B_FALSE)) != NULL) {
1463			if (!tvd->vdev_isspare)
1464				spa_spare_add(tvd);
1465
1466			/*
1467			 * We only mark the spare active if we were successfully
1468			 * able to load the vdev.  Otherwise, importing a pool
1469			 * with a bad active spare would result in strange
1470			 * behavior, because multiple pool would think the spare
1471			 * is actively in use.
1472			 *
1473			 * There is a vulnerability here to an equally bizarre
1474			 * circumstance, where a dead active spare is later
1475			 * brought back to life (onlined or otherwise).  Given
1476			 * the rarity of this scenario, and the extra complexity
1477			 * it adds, we ignore the possibility.
1478			 */
1479			if (!vdev_is_dead(tvd))
1480				spa_spare_activate(tvd);
1481		}
1482
1483		vd->vdev_top = vd;
1484		vd->vdev_aux = &spa->spa_spares;
1485
1486		if (vdev_open(vd) != 0)
1487			continue;
1488
1489		if (vdev_validate_aux(vd) == 0)
1490			spa_spare_add(vd);
1491	}
1492
1493	/*
1494	 * Recompute the stashed list of spares, with status information
1495	 * this time.
1496	 */
1497	VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1498	    DATA_TYPE_NVLIST_ARRAY) == 0);
1499
1500	spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1501	    KM_SLEEP);
1502	for (i = 0; i < spa->spa_spares.sav_count; i++)
1503		spares[i] = vdev_config_generate(spa,
1504		    spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1505	VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1506	    ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1507	for (i = 0; i < spa->spa_spares.sav_count; i++)
1508		nvlist_free(spares[i]);
1509	kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1510}
1511
1512/*
1513 * Load (or re-load) the current list of vdevs describing the active l2cache for
1514 * this pool.  When this is called, we have some form of basic information in
1515 * 'spa_l2cache.sav_config'.  We parse this into vdevs, try to open them, and
1516 * then re-generate a more complete list including status information.
1517 * Devices which are already active have their details maintained, and are
1518 * not re-opened.
1519 */
1520static void
1521spa_load_l2cache(spa_t *spa)
1522{
1523	nvlist_t **l2cache;
1524	uint_t nl2cache;
1525	int i, j, oldnvdevs;
1526	uint64_t guid;
1527	vdev_t *vd, **oldvdevs, **newvdevs;
1528	spa_aux_vdev_t *sav = &spa->spa_l2cache;
1529
1530	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1531
1532	if (sav->sav_config != NULL) {
1533		VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1534		    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1535		newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1536	} else {
1537		nl2cache = 0;
1538		newvdevs = NULL;
1539	}
1540
1541	oldvdevs = sav->sav_vdevs;
1542	oldnvdevs = sav->sav_count;
1543	sav->sav_vdevs = NULL;
1544	sav->sav_count = 0;
1545
1546	/*
1547	 * Process new nvlist of vdevs.
1548	 */
1549	for (i = 0; i < nl2cache; i++) {
1550		VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1551		    &guid) == 0);
1552
1553		newvdevs[i] = NULL;
1554		for (j = 0; j < oldnvdevs; j++) {
1555			vd = oldvdevs[j];
1556			if (vd != NULL && guid == vd->vdev_guid) {
1557				/*
1558				 * Retain previous vdev for add/remove ops.
1559				 */
1560				newvdevs[i] = vd;
1561				oldvdevs[j] = NULL;
1562				break;
1563			}
1564		}
1565
1566		if (newvdevs[i] == NULL) {
1567			/*
1568			 * Create new vdev
1569			 */
1570			VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1571			    VDEV_ALLOC_L2CACHE) == 0);
1572			ASSERT(vd != NULL);
1573			newvdevs[i] = vd;
1574
1575			/*
1576			 * Commit this vdev as an l2cache device,
1577			 * even if it fails to open.
1578			 */
1579			spa_l2cache_add(vd);
1580
1581			vd->vdev_top = vd;
1582			vd->vdev_aux = sav;
1583
1584			spa_l2cache_activate(vd);
1585
1586			if (vdev_open(vd) != 0)
1587				continue;
1588
1589			(void) vdev_validate_aux(vd);
1590
1591			if (!vdev_is_dead(vd))
1592				l2arc_add_vdev(spa, vd);
1593		}
1594	}
1595
1596	/*
1597	 * Purge vdevs that were dropped
1598	 */
1599	for (i = 0; i < oldnvdevs; i++) {
1600		uint64_t pool;
1601
1602		vd = oldvdevs[i];
1603		if (vd != NULL) {
1604			ASSERT(vd->vdev_isl2cache);
1605
1606			if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1607			    pool != 0ULL && l2arc_vdev_present(vd))
1608				l2arc_remove_vdev(vd);
1609			vdev_clear_stats(vd);
1610			vdev_free(vd);
1611		}
1612	}
1613
1614	if (oldvdevs)
1615		kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1616
1617	if (sav->sav_config == NULL)
1618		goto out;
1619
1620	sav->sav_vdevs = newvdevs;
1621	sav->sav_count = (int)nl2cache;
1622
1623	/*
1624	 * Recompute the stashed list of l2cache devices, with status
1625	 * information this time.
1626	 */
1627	VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1628	    DATA_TYPE_NVLIST_ARRAY) == 0);
1629
1630	l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1631	for (i = 0; i < sav->sav_count; i++)
1632		l2cache[i] = vdev_config_generate(spa,
1633		    sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1634	VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1635	    ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1636out:
1637	for (i = 0; i < sav->sav_count; i++)
1638		nvlist_free(l2cache[i]);
1639	if (sav->sav_count)
1640		kmem_free(l2cache, sav->sav_count * sizeof (void *));
1641}
1642
1643static int
1644load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1645{
1646	dmu_buf_t *db;
1647	char *packed = NULL;
1648	size_t nvsize = 0;
1649	int error;
1650	*value = NULL;
1651
1652	error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1653	if (error != 0)
1654		return (error);
1655
1656	nvsize = *(uint64_t *)db->db_data;
1657	dmu_buf_rele(db, FTAG);
1658
1659	packed = kmem_alloc(nvsize, KM_SLEEP);
1660	error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1661	    DMU_READ_PREFETCH);
1662	if (error == 0)
1663		error = nvlist_unpack(packed, nvsize, value, 0);
1664	kmem_free(packed, nvsize);
1665
1666	return (error);
1667}
1668
1669/*
1670 * Checks to see if the given vdev could not be opened, in which case we post a
1671 * sysevent to notify the autoreplace code that the device has been removed.
1672 */
1673static void
1674spa_check_removed(vdev_t *vd)
1675{
1676	for (int c = 0; c < vd->vdev_children; c++)
1677		spa_check_removed(vd->vdev_child[c]);
1678
1679	if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1680	    !vd->vdev_ishole) {
1681		zfs_post_autoreplace(vd->vdev_spa, vd);
1682		spa_event_notify(vd->vdev_spa, vd, ESC_ZFS_VDEV_CHECK);
1683	}
1684}
1685
1686static void
1687spa_config_valid_zaps(vdev_t *vd, vdev_t *mvd)
1688{
1689	ASSERT3U(vd->vdev_children, ==, mvd->vdev_children);
1690
1691	vd->vdev_top_zap = mvd->vdev_top_zap;
1692	vd->vdev_leaf_zap = mvd->vdev_leaf_zap;
1693
1694	for (uint64_t i = 0; i < vd->vdev_children; i++) {
1695		spa_config_valid_zaps(vd->vdev_child[i], mvd->vdev_child[i]);
1696	}
1697}
1698
1699/*
1700 * Validate the current config against the MOS config
1701 */
1702static boolean_t
1703spa_config_valid(spa_t *spa, nvlist_t *config)
1704{
1705	vdev_t *mrvd, *rvd = spa->spa_root_vdev;
1706	nvlist_t *nv;
1707
1708	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nv) == 0);
1709
1710	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1711	VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
1712
1713	ASSERT3U(rvd->vdev_children, ==, mrvd->vdev_children);
1714
1715	/*
1716	 * If we're doing a normal import, then build up any additional
1717	 * diagnostic information about missing devices in this config.
1718	 * We'll pass this up to the user for further processing.
1719	 */
1720	if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1721		nvlist_t **child, *nv;
1722		uint64_t idx = 0;
1723
1724		child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1725		    KM_SLEEP);
1726		VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1727
1728		for (int c = 0; c < rvd->vdev_children; c++) {
1729			vdev_t *tvd = rvd->vdev_child[c];
1730			vdev_t *mtvd  = mrvd->vdev_child[c];
1731
1732			if (tvd->vdev_ops == &vdev_missing_ops &&
1733			    mtvd->vdev_ops != &vdev_missing_ops &&
1734			    mtvd->vdev_islog)
1735				child[idx++] = vdev_config_generate(spa, mtvd,
1736				    B_FALSE, 0);
1737		}
1738
1739		if (idx) {
1740			VERIFY(nvlist_add_nvlist_array(nv,
1741			    ZPOOL_CONFIG_CHILDREN, child, idx) == 0);
1742			VERIFY(nvlist_add_nvlist(spa->spa_load_info,
1743			    ZPOOL_CONFIG_MISSING_DEVICES, nv) == 0);
1744
1745			for (int i = 0; i < idx; i++)
1746				nvlist_free(child[i]);
1747		}
1748		nvlist_free(nv);
1749		kmem_free(child, rvd->vdev_children * sizeof (char **));
1750	}
1751
1752	/*
1753	 * Compare the root vdev tree with the information we have
1754	 * from the MOS config (mrvd). Check each top-level vdev
1755	 * with the corresponding MOS config top-level (mtvd).
1756	 */
1757	for (int c = 0; c < rvd->vdev_children; c++) {
1758		vdev_t *tvd = rvd->vdev_child[c];
1759		vdev_t *mtvd  = mrvd->vdev_child[c];
1760
1761		/*
1762		 * Resolve any "missing" vdevs in the current configuration.
1763		 * If we find that the MOS config has more accurate information
1764		 * about the top-level vdev then use that vdev instead.
1765		 */
1766		if (tvd->vdev_ops == &vdev_missing_ops &&
1767		    mtvd->vdev_ops != &vdev_missing_ops) {
1768
1769			if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG))
1770				continue;
1771
1772			/*
1773			 * Device specific actions.
1774			 */
1775			if (mtvd->vdev_islog) {
1776				spa_set_log_state(spa, SPA_LOG_CLEAR);
1777			} else {
1778				/*
1779				 * XXX - once we have 'readonly' pool
1780				 * support we should be able to handle
1781				 * missing data devices by transitioning
1782				 * the pool to readonly.
1783				 */
1784				continue;
1785			}
1786
1787			/*
1788			 * Swap the missing vdev with the data we were
1789			 * able to obtain from the MOS config.
1790			 */
1791			vdev_remove_child(rvd, tvd);
1792			vdev_remove_child(mrvd, mtvd);
1793
1794			vdev_add_child(rvd, mtvd);
1795			vdev_add_child(mrvd, tvd);
1796
1797			spa_config_exit(spa, SCL_ALL, FTAG);
1798			vdev_load(mtvd);
1799			spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1800
1801			vdev_reopen(rvd);
1802		} else {
1803			if (mtvd->vdev_islog) {
1804				/*
1805				 * Load the slog device's state from the MOS
1806				 * config since it's possible that the label
1807				 * does not contain the most up-to-date
1808				 * information.
1809				 */
1810				vdev_load_log_state(tvd, mtvd);
1811				vdev_reopen(tvd);
1812			}
1813
1814			/*
1815			 * Per-vdev ZAP info is stored exclusively in the MOS.
1816			 */
1817			spa_config_valid_zaps(tvd, mtvd);
1818		}
1819	}
1820
1821	vdev_free(mrvd);
1822	spa_config_exit(spa, SCL_ALL, FTAG);
1823
1824	/*
1825	 * Ensure we were able to validate the config.
1826	 */
1827	return (rvd->vdev_guid_sum == spa->spa_uberblock.ub_guid_sum);
1828}
1829
1830/*
1831 * Check for missing log devices
1832 */
1833static boolean_t
1834spa_check_logs(spa_t *spa)
1835{
1836	boolean_t rv = B_FALSE;
1837	dsl_pool_t *dp = spa_get_dsl(spa);
1838
1839	switch (spa->spa_log_state) {
1840	case SPA_LOG_MISSING:
1841		/* need to recheck in case slog has been restored */
1842	case SPA_LOG_UNKNOWN:
1843		rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1844		    zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
1845		if (rv)
1846			spa_set_log_state(spa, SPA_LOG_MISSING);
1847		break;
1848	}
1849	return (rv);
1850}
1851
1852static boolean_t
1853spa_passivate_log(spa_t *spa)
1854{
1855	vdev_t *rvd = spa->spa_root_vdev;
1856	boolean_t slog_found = B_FALSE;
1857
1858	ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1859
1860	if (!spa_has_slogs(spa))
1861		return (B_FALSE);
1862
1863	for (int c = 0; c < rvd->vdev_children; c++) {
1864		vdev_t *tvd = rvd->vdev_child[c];
1865		metaslab_group_t *mg = tvd->vdev_mg;
1866
1867		if (tvd->vdev_islog) {
1868			metaslab_group_passivate(mg);
1869			slog_found = B_TRUE;
1870		}
1871	}
1872
1873	return (slog_found);
1874}
1875
1876static void
1877spa_activate_log(spa_t *spa)
1878{
1879	vdev_t *rvd = spa->spa_root_vdev;
1880
1881	ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1882
1883	for (int c = 0; c < rvd->vdev_children; c++) {
1884		vdev_t *tvd = rvd->vdev_child[c];
1885		metaslab_group_t *mg = tvd->vdev_mg;
1886
1887		if (tvd->vdev_islog)
1888			metaslab_group_activate(mg);
1889	}
1890}
1891
1892int
1893spa_offline_log(spa_t *spa)
1894{
1895	int error;
1896
1897	error = dmu_objset_find(spa_name(spa), zil_vdev_offline,
1898	    NULL, DS_FIND_CHILDREN);
1899	if (error == 0) {
1900		/*
1901		 * We successfully offlined the log device, sync out the
1902		 * current txg so that the "stubby" block can be removed
1903		 * by zil_sync().
1904		 */
1905		txg_wait_synced(spa->spa_dsl_pool, 0);
1906	}
1907	return (error);
1908}
1909
1910static void
1911spa_aux_check_removed(spa_aux_vdev_t *sav)
1912{
1913	int i;
1914
1915	for (i = 0; i < sav->sav_count; i++)
1916		spa_check_removed(sav->sav_vdevs[i]);
1917}
1918
1919void
1920spa_claim_notify(zio_t *zio)
1921{
1922	spa_t *spa = zio->io_spa;
1923
1924	if (zio->io_error)
1925		return;
1926
1927	mutex_enter(&spa->spa_props_lock);	/* any mutex will do */
1928	if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
1929		spa->spa_claim_max_txg = zio->io_bp->blk_birth;
1930	mutex_exit(&spa->spa_props_lock);
1931}
1932
1933typedef struct spa_load_error {
1934	uint64_t	sle_meta_count;
1935	uint64_t	sle_data_count;
1936} spa_load_error_t;
1937
1938static void
1939spa_load_verify_done(zio_t *zio)
1940{
1941	blkptr_t *bp = zio->io_bp;
1942	spa_load_error_t *sle = zio->io_private;
1943	dmu_object_type_t type = BP_GET_TYPE(bp);
1944	int error = zio->io_error;
1945	spa_t *spa = zio->io_spa;
1946
1947	abd_free(zio->io_abd);
1948	if (error) {
1949		if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
1950		    type != DMU_OT_INTENT_LOG)
1951			atomic_inc_64(&sle->sle_meta_count);
1952		else
1953			atomic_inc_64(&sle->sle_data_count);
1954	}
1955
1956	mutex_enter(&spa->spa_scrub_lock);
1957	spa->spa_scrub_inflight--;
1958	cv_broadcast(&spa->spa_scrub_io_cv);
1959	mutex_exit(&spa->spa_scrub_lock);
1960}
1961
1962/*
1963 * Maximum number of concurrent scrub i/os to create while verifying
1964 * a pool while importing it.
1965 */
1966int spa_load_verify_maxinflight = 10000;
1967boolean_t spa_load_verify_metadata = B_TRUE;
1968boolean_t spa_load_verify_data = B_TRUE;
1969
1970SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_maxinflight, CTLFLAG_RWTUN,
1971    &spa_load_verify_maxinflight, 0,
1972    "Maximum number of concurrent scrub I/Os to create while verifying a "
1973    "pool while importing it");
1974
1975SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_metadata, CTLFLAG_RWTUN,
1976    &spa_load_verify_metadata, 0,
1977    "Check metadata on import?");
1978
1979SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_data, CTLFLAG_RWTUN,
1980    &spa_load_verify_data, 0,
1981    "Check user data on import?");
1982
1983/*ARGSUSED*/
1984static int
1985spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1986    const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
1987{
1988	if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
1989		return (0);
1990	/*
1991	 * Note: normally this routine will not be called if
1992	 * spa_load_verify_metadata is not set.  However, it may be useful
1993	 * to manually set the flag after the traversal has begun.
1994	 */
1995	if (!spa_load_verify_metadata)
1996		return (0);
1997	if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
1998		return (0);
1999
2000	zio_t *rio = arg;
2001	size_t size = BP_GET_PSIZE(bp);
2002
2003	mutex_enter(&spa->spa_scrub_lock);
2004	while (spa->spa_scrub_inflight >= spa_load_verify_maxinflight)
2005		cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2006	spa->spa_scrub_inflight++;
2007	mutex_exit(&spa->spa_scrub_lock);
2008
2009	zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2010	    spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2011	    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2012	    ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2013	return (0);
2014}
2015
2016/* ARGSUSED */
2017int
2018verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2019{
2020	if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2021		return (SET_ERROR(ENAMETOOLONG));
2022
2023	return (0);
2024}
2025
2026static int
2027spa_load_verify(spa_t *spa)
2028{
2029	zio_t *rio;
2030	spa_load_error_t sle = { 0 };
2031	zpool_rewind_policy_t policy;
2032	boolean_t verify_ok = B_FALSE;
2033	int error = 0;
2034
2035	zpool_get_rewind_policy(spa->spa_config, &policy);
2036
2037	if (policy.zrp_request & ZPOOL_NEVER_REWIND)
2038		return (0);
2039
2040	dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2041	error = dmu_objset_find_dp(spa->spa_dsl_pool,
2042	    spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2043	    DS_FIND_CHILDREN);
2044	dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2045	if (error != 0)
2046		return (error);
2047
2048	rio = zio_root(spa, NULL, &sle,
2049	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2050
2051	if (spa_load_verify_metadata) {
2052		error = traverse_pool(spa, spa->spa_verify_min_txg,
2053		    TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2054		    spa_load_verify_cb, rio);
2055	}
2056
2057	(void) zio_wait(rio);
2058
2059	spa->spa_load_meta_errors = sle.sle_meta_count;
2060	spa->spa_load_data_errors = sle.sle_data_count;
2061
2062	if (!error && sle.sle_meta_count <= policy.zrp_maxmeta &&
2063	    sle.sle_data_count <= policy.zrp_maxdata) {
2064		int64_t loss = 0;
2065
2066		verify_ok = B_TRUE;
2067		spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2068		spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2069
2070		loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2071		VERIFY(nvlist_add_uint64(spa->spa_load_info,
2072		    ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2073		VERIFY(nvlist_add_int64(spa->spa_load_info,
2074		    ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2075		VERIFY(nvlist_add_uint64(spa->spa_load_info,
2076		    ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2077	} else {
2078		spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2079	}
2080
2081	if (error) {
2082		if (error != ENXIO && error != EIO)
2083			error = SET_ERROR(EIO);
2084		return (error);
2085	}
2086
2087	return (verify_ok ? 0 : EIO);
2088}
2089
2090/*
2091 * Find a value in the pool props object.
2092 */
2093static void
2094spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2095{
2096	(void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2097	    zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2098}
2099
2100/*
2101 * Find a value in the pool directory object.
2102 */
2103static int
2104spa_dir_prop(spa_t *spa, const char *name, uint64_t *val)
2105{
2106	return (zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2107	    name, sizeof (uint64_t), 1, val));
2108}
2109
2110static int
2111spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2112{
2113	vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2114	return (err);
2115}
2116
2117/*
2118 * Fix up config after a partly-completed split.  This is done with the
2119 * ZPOOL_CONFIG_SPLIT nvlist.  Both the splitting pool and the split-off
2120 * pool have that entry in their config, but only the splitting one contains
2121 * a list of all the guids of the vdevs that are being split off.
2122 *
2123 * This function determines what to do with that list: either rejoin
2124 * all the disks to the pool, or complete the splitting process.  To attempt
2125 * the rejoin, each disk that is offlined is marked online again, and
2126 * we do a reopen() call.  If the vdev label for every disk that was
2127 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2128 * then we call vdev_split() on each disk, and complete the split.
2129 *
2130 * Otherwise we leave the config alone, with all the vdevs in place in
2131 * the original pool.
2132 */
2133static void
2134spa_try_repair(spa_t *spa, nvlist_t *config)
2135{
2136	uint_t extracted;
2137	uint64_t *glist;
2138	uint_t i, gcount;
2139	nvlist_t *nvl;
2140	vdev_t **vd;
2141	boolean_t attempt_reopen;
2142
2143	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2144		return;
2145
2146	/* check that the config is complete */
2147	if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2148	    &glist, &gcount) != 0)
2149		return;
2150
2151	vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2152
2153	/* attempt to online all the vdevs & validate */
2154	attempt_reopen = B_TRUE;
2155	for (i = 0; i < gcount; i++) {
2156		if (glist[i] == 0)	/* vdev is hole */
2157			continue;
2158
2159		vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2160		if (vd[i] == NULL) {
2161			/*
2162			 * Don't bother attempting to reopen the disks;
2163			 * just do the split.
2164			 */
2165			attempt_reopen = B_FALSE;
2166		} else {
2167			/* attempt to re-online it */
2168			vd[i]->vdev_offline = B_FALSE;
2169		}
2170	}
2171
2172	if (attempt_reopen) {
2173		vdev_reopen(spa->spa_root_vdev);
2174
2175		/* check each device to see what state it's in */
2176		for (extracted = 0, i = 0; i < gcount; i++) {
2177			if (vd[i] != NULL &&
2178			    vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2179				break;
2180			++extracted;
2181		}
2182	}
2183
2184	/*
2185	 * If every disk has been moved to the new pool, or if we never
2186	 * even attempted to look at them, then we split them off for
2187	 * good.
2188	 */
2189	if (!attempt_reopen || gcount == extracted) {
2190		for (i = 0; i < gcount; i++)
2191			if (vd[i] != NULL)
2192				vdev_split(vd[i]);
2193		vdev_reopen(spa->spa_root_vdev);
2194	}
2195
2196	kmem_free(vd, gcount * sizeof (vdev_t *));
2197}
2198
2199static int
2200spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type,
2201    boolean_t mosconfig)
2202{
2203	nvlist_t *config = spa->spa_config;
2204	char *ereport = FM_EREPORT_ZFS_POOL;
2205	char *comment;
2206	int error;
2207	uint64_t pool_guid;
2208	nvlist_t *nvl;
2209
2210	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid))
2211		return (SET_ERROR(EINVAL));
2212
2213	ASSERT(spa->spa_comment == NULL);
2214	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2215		spa->spa_comment = spa_strdup(comment);
2216
2217	/*
2218	 * Versioning wasn't explicitly added to the label until later, so if
2219	 * it's not present treat it as the initial version.
2220	 */
2221	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2222	    &spa->spa_ubsync.ub_version) != 0)
2223		spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2224
2225	(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2226	    &spa->spa_config_txg);
2227
2228	if ((state == SPA_LOAD_IMPORT || state == SPA_LOAD_TRYIMPORT) &&
2229	    spa_guid_exists(pool_guid, 0)) {
2230		error = SET_ERROR(EEXIST);
2231	} else {
2232		spa->spa_config_guid = pool_guid;
2233
2234		if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT,
2235		    &nvl) == 0) {
2236			VERIFY(nvlist_dup(nvl, &spa->spa_config_splitting,
2237			    KM_SLEEP) == 0);
2238		}
2239
2240		nvlist_free(spa->spa_load_info);
2241		spa->spa_load_info = fnvlist_alloc();
2242
2243		gethrestime(&spa->spa_loaded_ts);
2244		error = spa_load_impl(spa, pool_guid, config, state, type,
2245		    mosconfig, &ereport);
2246	}
2247
2248	/*
2249	 * Don't count references from objsets that are already closed
2250	 * and are making their way through the eviction process.
2251	 */
2252	spa_evicting_os_wait(spa);
2253	spa->spa_minref = refcount_count(&spa->spa_refcount);
2254	if (error) {
2255		if (error != EEXIST) {
2256			spa->spa_loaded_ts.tv_sec = 0;
2257			spa->spa_loaded_ts.tv_nsec = 0;
2258		}
2259		if (error != EBADF) {
2260			zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2261		}
2262	}
2263	spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2264	spa->spa_ena = 0;
2265
2266	return (error);
2267}
2268
2269/*
2270 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2271 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2272 * spa's per-vdev ZAP list.
2273 */
2274static uint64_t
2275vdev_count_verify_zaps(vdev_t *vd)
2276{
2277	spa_t *spa = vd->vdev_spa;
2278	uint64_t total = 0;
2279	if (vd->vdev_top_zap != 0) {
2280		total++;
2281		ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2282		    spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2283	}
2284	if (vd->vdev_leaf_zap != 0) {
2285		total++;
2286		ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2287		    spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2288	}
2289
2290	for (uint64_t i = 0; i < vd->vdev_children; i++) {
2291		total += vdev_count_verify_zaps(vd->vdev_child[i]);
2292	}
2293
2294	return (total);
2295}
2296
2297/*
2298 * Load an existing storage pool, using the pool's builtin spa_config as a
2299 * source of configuration information.
2300 */
2301static int
2302spa_load_impl(spa_t *spa, uint64_t pool_guid, nvlist_t *config,
2303    spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
2304    char **ereport)
2305{
2306	int error = 0;
2307	nvlist_t *nvroot = NULL;
2308	nvlist_t *label;
2309	vdev_t *rvd;
2310	uberblock_t *ub = &spa->spa_uberblock;
2311	uint64_t children, config_cache_txg = spa->spa_config_txg;
2312	int orig_mode = spa->spa_mode;
2313	int parse;
2314	uint64_t obj;
2315	boolean_t missing_feat_write = B_FALSE;
2316
2317	/*
2318	 * If this is an untrusted config, access the pool in read-only mode.
2319	 * This prevents things like resilvering recently removed devices.
2320	 */
2321	if (!mosconfig)
2322		spa->spa_mode = FREAD;
2323
2324	ASSERT(MUTEX_HELD(&spa_namespace_lock));
2325
2326	spa->spa_load_state = state;
2327
2328	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvroot))
2329		return (SET_ERROR(EINVAL));
2330
2331	parse = (type == SPA_IMPORT_EXISTING ?
2332	    VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2333
2334	/*
2335	 * Create "The Godfather" zio to hold all async IOs
2336	 */
2337	spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2338	    KM_SLEEP);
2339	for (int i = 0; i < max_ncpus; i++) {
2340		spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2341		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2342		    ZIO_FLAG_GODFATHER);
2343	}
2344
2345	/*
2346	 * Parse the configuration into a vdev tree.  We explicitly set the
2347	 * value that will be returned by spa_version() since parsing the
2348	 * configuration requires knowing the version number.
2349	 */
2350	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2351	error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, parse);
2352	spa_config_exit(spa, SCL_ALL, FTAG);
2353
2354	if (error != 0)
2355		return (error);
2356
2357	ASSERT(spa->spa_root_vdev == rvd);
2358	ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2359	ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2360
2361	if (type != SPA_IMPORT_ASSEMBLE) {
2362		ASSERT(spa_guid(spa) == pool_guid);
2363	}
2364
2365	/*
2366	 * Try to open all vdevs, loading each label in the process.
2367	 */
2368	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2369	error = vdev_open(rvd);
2370	spa_config_exit(spa, SCL_ALL, FTAG);
2371	if (error != 0)
2372		return (error);
2373
2374	/*
2375	 * We need to validate the vdev labels against the configuration that
2376	 * we have in hand, which is dependent on the setting of mosconfig. If
2377	 * mosconfig is true then we're validating the vdev labels based on
2378	 * that config.  Otherwise, we're validating against the cached config
2379	 * (zpool.cache) that was read when we loaded the zfs module, and then
2380	 * later we will recursively call spa_load() and validate against
2381	 * the vdev config.
2382	 *
2383	 * If we're assembling a new pool that's been split off from an
2384	 * existing pool, the labels haven't yet been updated so we skip
2385	 * validation for now.
2386	 */
2387	if (type != SPA_IMPORT_ASSEMBLE) {
2388		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2389		error = vdev_validate(rvd, mosconfig);
2390		spa_config_exit(spa, SCL_ALL, FTAG);
2391
2392		if (error != 0)
2393			return (error);
2394
2395		if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2396			return (SET_ERROR(ENXIO));
2397	}
2398
2399	/*
2400	 * Find the best uberblock.
2401	 */
2402	vdev_uberblock_load(rvd, ub, &label);
2403
2404	/*
2405	 * If we weren't able to find a single valid uberblock, return failure.
2406	 */
2407	if (ub->ub_txg == 0) {
2408		nvlist_free(label);
2409		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2410	}
2411
2412	/*
2413	 * If the pool has an unsupported version we can't open it.
2414	 */
2415	if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2416		nvlist_free(label);
2417		return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2418	}
2419
2420	if (ub->ub_version >= SPA_VERSION_FEATURES) {
2421		nvlist_t *features;
2422
2423		/*
2424		 * If we weren't able to find what's necessary for reading the
2425		 * MOS in the label, return failure.
2426		 */
2427		if (label == NULL || nvlist_lookup_nvlist(label,
2428		    ZPOOL_CONFIG_FEATURES_FOR_READ, &features) != 0) {
2429			nvlist_free(label);
2430			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2431			    ENXIO));
2432		}
2433
2434		/*
2435		 * Update our in-core representation with the definitive values
2436		 * from the label.
2437		 */
2438		nvlist_free(spa->spa_label_features);
2439		VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2440	}
2441
2442	nvlist_free(label);
2443
2444	/*
2445	 * Look through entries in the label nvlist's features_for_read. If
2446	 * there is a feature listed there which we don't understand then we
2447	 * cannot open a pool.
2448	 */
2449	if (ub->ub_version >= SPA_VERSION_FEATURES) {
2450		nvlist_t *unsup_feat;
2451
2452		VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2453		    0);
2454
2455		for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2456		    NULL); nvp != NULL;
2457		    nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2458			if (!zfeature_is_supported(nvpair_name(nvp))) {
2459				VERIFY(nvlist_add_string(unsup_feat,
2460				    nvpair_name(nvp), "") == 0);
2461			}
2462		}
2463
2464		if (!nvlist_empty(unsup_feat)) {
2465			VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2466			    ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2467			nvlist_free(unsup_feat);
2468			return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2469			    ENOTSUP));
2470		}
2471
2472		nvlist_free(unsup_feat);
2473	}
2474
2475	/*
2476	 * If the vdev guid sum doesn't match the uberblock, we have an
2477	 * incomplete configuration.  We first check to see if the pool
2478	 * is aware of the complete config (i.e ZPOOL_CONFIG_VDEV_CHILDREN).
2479	 * If it is, defer the vdev_guid_sum check till later so we
2480	 * can handle missing vdevs.
2481	 */
2482	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VDEV_CHILDREN,
2483	    &children) != 0 && mosconfig && type != SPA_IMPORT_ASSEMBLE &&
2484	    rvd->vdev_guid_sum != ub->ub_guid_sum)
2485		return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2486
2487	if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2488		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2489		spa_try_repair(spa, config);
2490		spa_config_exit(spa, SCL_ALL, FTAG);
2491		nvlist_free(spa->spa_config_splitting);
2492		spa->spa_config_splitting = NULL;
2493	}
2494
2495	/*
2496	 * Initialize internal SPA structures.
2497	 */
2498	spa->spa_state = POOL_STATE_ACTIVE;
2499	spa->spa_ubsync = spa->spa_uberblock;
2500	spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2501	    TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2502	spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2503	    spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2504	spa->spa_claim_max_txg = spa->spa_first_txg;
2505	spa->spa_prev_software_version = ub->ub_software_version;
2506
2507	error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2508	if (error)
2509		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2510	spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2511
2512	if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object) != 0)
2513		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2514
2515	if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2516		boolean_t missing_feat_read = B_FALSE;
2517		nvlist_t *unsup_feat, *enabled_feat;
2518
2519		if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
2520		    &spa->spa_feat_for_read_obj) != 0) {
2521			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2522		}
2523
2524		if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
2525		    &spa->spa_feat_for_write_obj) != 0) {
2526			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2527		}
2528
2529		if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
2530		    &spa->spa_feat_desc_obj) != 0) {
2531			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2532		}
2533
2534		enabled_feat = fnvlist_alloc();
2535		unsup_feat = fnvlist_alloc();
2536
2537		if (!spa_features_check(spa, B_FALSE,
2538		    unsup_feat, enabled_feat))
2539			missing_feat_read = B_TRUE;
2540
2541		if (spa_writeable(spa) || state == SPA_LOAD_TRYIMPORT) {
2542			if (!spa_features_check(spa, B_TRUE,
2543			    unsup_feat, enabled_feat)) {
2544				missing_feat_write = B_TRUE;
2545			}
2546		}
2547
2548		fnvlist_add_nvlist(spa->spa_load_info,
2549		    ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
2550
2551		if (!nvlist_empty(unsup_feat)) {
2552			fnvlist_add_nvlist(spa->spa_load_info,
2553			    ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
2554		}
2555
2556		fnvlist_free(enabled_feat);
2557		fnvlist_free(unsup_feat);
2558
2559		if (!missing_feat_read) {
2560			fnvlist_add_boolean(spa->spa_load_info,
2561			    ZPOOL_CONFIG_CAN_RDONLY);
2562		}
2563
2564		/*
2565		 * If the state is SPA_LOAD_TRYIMPORT, our objective is
2566		 * twofold: to determine whether the pool is available for
2567		 * import in read-write mode and (if it is not) whether the
2568		 * pool is available for import in read-only mode. If the pool
2569		 * is available for import in read-write mode, it is displayed
2570		 * as available in userland; if it is not available for import
2571		 * in read-only mode, it is displayed as unavailable in
2572		 * userland. If the pool is available for import in read-only
2573		 * mode but not read-write mode, it is displayed as unavailable
2574		 * in userland with a special note that the pool is actually
2575		 * available for open in read-only mode.
2576		 *
2577		 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
2578		 * missing a feature for write, we must first determine whether
2579		 * the pool can be opened read-only before returning to
2580		 * userland in order to know whether to display the
2581		 * abovementioned note.
2582		 */
2583		if (missing_feat_read || (missing_feat_write &&
2584		    spa_writeable(spa))) {
2585			return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2586			    ENOTSUP));
2587		}
2588
2589		/*
2590		 * Load refcounts for ZFS features from disk into an in-memory
2591		 * cache during SPA initialization.
2592		 */
2593		for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
2594			uint64_t refcount;
2595
2596			error = feature_get_refcount_from_disk(spa,
2597			    &spa_feature_table[i], &refcount);
2598			if (error == 0) {
2599				spa->spa_feat_refcount_cache[i] = refcount;
2600			} else if (error == ENOTSUP) {
2601				spa->spa_feat_refcount_cache[i] =
2602				    SPA_FEATURE_DISABLED;
2603			} else {
2604				return (spa_vdev_err(rvd,
2605				    VDEV_AUX_CORRUPT_DATA, EIO));
2606			}
2607		}
2608	}
2609
2610	if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
2611		if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
2612		    &spa->spa_feat_enabled_txg_obj) != 0)
2613			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2614	}
2615
2616	spa->spa_is_initializing = B_TRUE;
2617	error = dsl_pool_open(spa->spa_dsl_pool);
2618	spa->spa_is_initializing = B_FALSE;
2619	if (error != 0)
2620		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2621
2622	if (!mosconfig) {
2623		uint64_t hostid;
2624		nvlist_t *policy = NULL, *nvconfig;
2625
2626		if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
2627			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2628
2629		if (!spa_is_root(spa) && nvlist_lookup_uint64(nvconfig,
2630		    ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2631			char *hostname;
2632			unsigned long myhostid = 0;
2633
2634			VERIFY(nvlist_lookup_string(nvconfig,
2635			    ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
2636
2637#ifdef	_KERNEL
2638			myhostid = zone_get_hostid(NULL);
2639#else	/* _KERNEL */
2640			/*
2641			 * We're emulating the system's hostid in userland, so
2642			 * we can't use zone_get_hostid().
2643			 */
2644			(void) ddi_strtoul(hw_serial, NULL, 10, &myhostid);
2645#endif	/* _KERNEL */
2646			if (check_hostid && hostid != 0 && myhostid != 0 &&
2647			    hostid != myhostid) {
2648				nvlist_free(nvconfig);
2649				cmn_err(CE_WARN, "pool '%s' could not be "
2650				    "loaded as it was last accessed by "
2651				    "another system (host: %s hostid: 0x%lx). "
2652				    "See: http://illumos.org/msg/ZFS-8000-EY",
2653				    spa_name(spa), hostname,
2654				    (unsigned long)hostid);
2655				return (SET_ERROR(EBADF));
2656			}
2657		}
2658		if (nvlist_lookup_nvlist(spa->spa_config,
2659		    ZPOOL_REWIND_POLICY, &policy) == 0)
2660			VERIFY(nvlist_add_nvlist(nvconfig,
2661			    ZPOOL_REWIND_POLICY, policy) == 0);
2662
2663		spa_config_set(spa, nvconfig);
2664		spa_unload(spa);
2665		spa_deactivate(spa);
2666		spa_activate(spa, orig_mode);
2667
2668		return (spa_load(spa, state, SPA_IMPORT_EXISTING, B_TRUE));
2669	}
2670
2671	/* Grab the secret checksum salt from the MOS. */
2672	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2673	    DMU_POOL_CHECKSUM_SALT, 1,
2674	    sizeof (spa->spa_cksum_salt.zcs_bytes),
2675	    spa->spa_cksum_salt.zcs_bytes);
2676	if (error == ENOENT) {
2677		/* Generate a new salt for subsequent use */
2678		(void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
2679		    sizeof (spa->spa_cksum_salt.zcs_bytes));
2680	} else if (error != 0) {
2681		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2682	}
2683
2684	if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj) != 0)
2685		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2686	error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
2687	if (error != 0)
2688		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2689
2690	/*
2691	 * Load the bit that tells us to use the new accounting function
2692	 * (raid-z deflation).  If we have an older pool, this will not
2693	 * be present.
2694	 */
2695	error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate);
2696	if (error != 0 && error != ENOENT)
2697		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2698
2699	error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
2700	    &spa->spa_creation_version);
2701	if (error != 0 && error != ENOENT)
2702		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2703
2704	/*
2705	 * Load the persistent error log.  If we have an older pool, this will
2706	 * not be present.
2707	 */
2708	error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last);
2709	if (error != 0 && error != ENOENT)
2710		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2711
2712	error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
2713	    &spa->spa_errlog_scrub);
2714	if (error != 0 && error != ENOENT)
2715		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2716
2717	/*
2718	 * Load the history object.  If we have an older pool, this
2719	 * will not be present.
2720	 */
2721	error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history);
2722	if (error != 0 && error != ENOENT)
2723		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2724
2725	/*
2726	 * Load the per-vdev ZAP map. If we have an older pool, this will not
2727	 * be present; in this case, defer its creation to a later time to
2728	 * avoid dirtying the MOS this early / out of sync context. See
2729	 * spa_sync_config_object.
2730	 */
2731
2732	/* The sentinel is only available in the MOS config. */
2733	nvlist_t *mos_config;
2734	if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0)
2735		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2736
2737	error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
2738	    &spa->spa_all_vdev_zaps);
2739
2740	if (error == ENOENT) {
2741		VERIFY(!nvlist_exists(mos_config,
2742		    ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
2743		spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
2744		ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
2745	} else if (error != 0) {
2746		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2747	} else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
2748		/*
2749		 * An older version of ZFS overwrote the sentinel value, so
2750		 * we have orphaned per-vdev ZAPs in the MOS. Defer their
2751		 * destruction to later; see spa_sync_config_object.
2752		 */
2753		spa->spa_avz_action = AVZ_ACTION_DESTROY;
2754		/*
2755		 * We're assuming that no vdevs have had their ZAPs created
2756		 * before this. Better be sure of it.
2757		 */
2758		ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
2759	}
2760	nvlist_free(mos_config);
2761
2762	/*
2763	 * If we're assembling the pool from the split-off vdevs of
2764	 * an existing pool, we don't want to attach the spares & cache
2765	 * devices.
2766	 */
2767
2768	/*
2769	 * Load any hot spares for this pool.
2770	 */
2771	error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object);
2772	if (error != 0 && error != ENOENT)
2773		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2774	if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
2775		ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
2776		if (load_nvlist(spa, spa->spa_spares.sav_object,
2777		    &spa->spa_spares.sav_config) != 0)
2778			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2779
2780		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2781		spa_load_spares(spa);
2782		spa_config_exit(spa, SCL_ALL, FTAG);
2783	} else if (error == 0) {
2784		spa->spa_spares.sav_sync = B_TRUE;
2785	}
2786
2787	/*
2788	 * Load any level 2 ARC devices for this pool.
2789	 */
2790	error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
2791	    &spa->spa_l2cache.sav_object);
2792	if (error != 0 && error != ENOENT)
2793		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2794	if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
2795		ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
2796		if (load_nvlist(spa, spa->spa_l2cache.sav_object,
2797		    &spa->spa_l2cache.sav_config) != 0)
2798			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2799
2800		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2801		spa_load_l2cache(spa);
2802		spa_config_exit(spa, SCL_ALL, FTAG);
2803	} else if (error == 0) {
2804		spa->spa_l2cache.sav_sync = B_TRUE;
2805	}
2806
2807	spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
2808
2809	error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object);
2810	if (error && error != ENOENT)
2811		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2812
2813	if (error == 0) {
2814		uint64_t autoreplace;
2815
2816		spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
2817		spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
2818		spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
2819		spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
2820		spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
2821		spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
2822		    &spa->spa_dedup_ditto);
2823
2824		spa->spa_autoreplace = (autoreplace != 0);
2825	}
2826
2827	/*
2828	 * If the 'autoreplace' property is set, then post a resource notifying
2829	 * the ZFS DE that it should not issue any faults for unopenable
2830	 * devices.  We also iterate over the vdevs, and post a sysevent for any
2831	 * unopenable vdevs so that the normal autoreplace handler can take
2832	 * over.
2833	 */
2834	if (spa->spa_autoreplace && state != SPA_LOAD_TRYIMPORT) {
2835		spa_check_removed(spa->spa_root_vdev);
2836		/*
2837		 * For the import case, this is done in spa_import(), because
2838		 * at this point we're using the spare definitions from
2839		 * the MOS config, not necessarily from the userland config.
2840		 */
2841		if (state != SPA_LOAD_IMPORT) {
2842			spa_aux_check_removed(&spa->spa_spares);
2843			spa_aux_check_removed(&spa->spa_l2cache);
2844		}
2845	}
2846
2847	/*
2848	 * Load the vdev state for all toplevel vdevs.
2849	 */
2850	vdev_load(rvd);
2851
2852	/*
2853	 * Propagate the leaf DTLs we just loaded all the way up the tree.
2854	 */
2855	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2856	vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
2857	spa_config_exit(spa, SCL_ALL, FTAG);
2858
2859	/*
2860	 * Load the DDTs (dedup tables).
2861	 */
2862	error = ddt_load(spa);
2863	if (error != 0)
2864		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2865
2866	spa_update_dspace(spa);
2867
2868	/*
2869	 * Validate the config, using the MOS config to fill in any
2870	 * information which might be missing.  If we fail to validate
2871	 * the config then declare the pool unfit for use. If we're
2872	 * assembling a pool from a split, the log is not transferred
2873	 * over.
2874	 */
2875	if (type != SPA_IMPORT_ASSEMBLE) {
2876		nvlist_t *nvconfig;
2877
2878		if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
2879			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2880
2881		if (!spa_config_valid(spa, nvconfig)) {
2882			nvlist_free(nvconfig);
2883			return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
2884			    ENXIO));
2885		}
2886		nvlist_free(nvconfig);
2887
2888		/*
2889		 * Now that we've validated the config, check the state of the
2890		 * root vdev.  If it can't be opened, it indicates one or
2891		 * more toplevel vdevs are faulted.
2892		 */
2893		if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2894			return (SET_ERROR(ENXIO));
2895
2896		if (spa_writeable(spa) && spa_check_logs(spa)) {
2897			*ereport = FM_EREPORT_ZFS_LOG_REPLAY;
2898			return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG, ENXIO));
2899		}
2900	}
2901
2902	if (missing_feat_write) {
2903		ASSERT(state == SPA_LOAD_TRYIMPORT);
2904
2905		/*
2906		 * At this point, we know that we can open the pool in
2907		 * read-only mode but not read-write mode. We now have enough
2908		 * information and can return to userland.
2909		 */
2910		return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT, ENOTSUP));
2911	}
2912
2913	/*
2914	 * We've successfully opened the pool, verify that we're ready
2915	 * to start pushing transactions.
2916	 */
2917	if (state != SPA_LOAD_TRYIMPORT) {
2918		if (error = spa_load_verify(spa))
2919			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2920			    error));
2921	}
2922
2923	if (spa_writeable(spa) && (state == SPA_LOAD_RECOVER ||
2924	    spa->spa_load_max_txg == UINT64_MAX)) {
2925		dmu_tx_t *tx;
2926		int need_update = B_FALSE;
2927		dsl_pool_t *dp = spa_get_dsl(spa);
2928
2929		ASSERT(state != SPA_LOAD_TRYIMPORT);
2930
2931		/*
2932		 * Claim log blocks that haven't been committed yet.
2933		 * This must all happen in a single txg.
2934		 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
2935		 * invoked from zil_claim_log_block()'s i/o done callback.
2936		 * Price of rollback is that we abandon the log.
2937		 */
2938		spa->spa_claiming = B_TRUE;
2939
2940		tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
2941		(void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2942		    zil_claim, tx, DS_FIND_CHILDREN);
2943		dmu_tx_commit(tx);
2944
2945		spa->spa_claiming = B_FALSE;
2946
2947		spa_set_log_state(spa, SPA_LOG_GOOD);
2948		spa->spa_sync_on = B_TRUE;
2949		txg_sync_start(spa->spa_dsl_pool);
2950
2951		/*
2952		 * Wait for all claims to sync.  We sync up to the highest
2953		 * claimed log block birth time so that claimed log blocks
2954		 * don't appear to be from the future.  spa_claim_max_txg
2955		 * will have been set for us by either zil_check_log_chain()
2956		 * (invoked from spa_check_logs()) or zil_claim() above.
2957		 */
2958		txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
2959
2960		/*
2961		 * If the config cache is stale, or we have uninitialized
2962		 * metaslabs (see spa_vdev_add()), then update the config.
2963		 *
2964		 * If this is a verbatim import, trust the current
2965		 * in-core spa_config and update the disk labels.
2966		 */
2967		if (config_cache_txg != spa->spa_config_txg ||
2968		    state == SPA_LOAD_IMPORT ||
2969		    state == SPA_LOAD_RECOVER ||
2970		    (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
2971			need_update = B_TRUE;
2972
2973		for (int c = 0; c < rvd->vdev_children; c++)
2974			if (rvd->vdev_child[c]->vdev_ms_array == 0)
2975				need_update = B_TRUE;
2976
2977		/*
2978		 * Update the config cache asychronously in case we're the
2979		 * root pool, in which case the config cache isn't writable yet.
2980		 */
2981		if (need_update)
2982			spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
2983
2984		/*
2985		 * Check all DTLs to see if anything needs resilvering.
2986		 */
2987		if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
2988		    vdev_resilver_needed(rvd, NULL, NULL))
2989			spa_async_request(spa, SPA_ASYNC_RESILVER);
2990
2991		/*
2992		 * Log the fact that we booted up (so that we can detect if
2993		 * we rebooted in the middle of an operation).
2994		 */
2995		spa_history_log_version(spa, "open");
2996
2997		/*
2998		 * Delete any inconsistent datasets.
2999		 */
3000		(void) dmu_objset_find(spa_name(spa),
3001		    dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
3002
3003		/*
3004		 * Clean up any stale temporary dataset userrefs.
3005		 */
3006		dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
3007	}
3008
3009	return (0);
3010}
3011
3012static int
3013spa_load_retry(spa_t *spa, spa_load_state_t state, int mosconfig)
3014{
3015	int mode = spa->spa_mode;
3016
3017	spa_unload(spa);
3018	spa_deactivate(spa);
3019
3020	spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
3021
3022	spa_activate(spa, mode);
3023	spa_async_suspend(spa);
3024
3025	return (spa_load(spa, state, SPA_IMPORT_EXISTING, mosconfig));
3026}
3027
3028/*
3029 * If spa_load() fails this function will try loading prior txg's. If
3030 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
3031 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
3032 * function will not rewind the pool and will return the same error as
3033 * spa_load().
3034 */
3035static int
3036spa_load_best(spa_t *spa, spa_load_state_t state, int mosconfig,
3037    uint64_t max_request, int rewind_flags)
3038{
3039	nvlist_t *loadinfo = NULL;
3040	nvlist_t *config = NULL;
3041	int load_error, rewind_error;
3042	uint64_t safe_rewind_txg;
3043	uint64_t min_txg;
3044
3045	if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
3046		spa->spa_load_max_txg = spa->spa_load_txg;
3047		spa_set_log_state(spa, SPA_LOG_CLEAR);
3048	} else {
3049		spa->spa_load_max_txg = max_request;
3050		if (max_request != UINT64_MAX)
3051			spa->spa_extreme_rewind = B_TRUE;
3052	}
3053
3054	load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING,
3055	    mosconfig);
3056	if (load_error == 0)
3057		return (0);
3058
3059	if (spa->spa_root_vdev != NULL)
3060		config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
3061
3062	spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
3063	spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
3064
3065	if (rewind_flags & ZPOOL_NEVER_REWIND) {
3066		nvlist_free(config);
3067		return (load_error);
3068	}
3069
3070	if (state == SPA_LOAD_RECOVER) {
3071		/* Price of rolling back is discarding txgs, including log */
3072		spa_set_log_state(spa, SPA_LOG_CLEAR);
3073	} else {
3074		/*
3075		 * If we aren't rolling back save the load info from our first
3076		 * import attempt so that we can restore it after attempting
3077		 * to rewind.
3078		 */
3079		loadinfo = spa->spa_load_info;
3080		spa->spa_load_info = fnvlist_alloc();
3081	}
3082
3083	spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
3084	safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
3085	min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
3086	    TXG_INITIAL : safe_rewind_txg;
3087
3088	/*
3089	 * Continue as long as we're finding errors, we're still within
3090	 * the acceptable rewind range, and we're still finding uberblocks
3091	 */
3092	while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
3093	    spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
3094		if (spa->spa_load_max_txg < safe_rewind_txg)
3095			spa->spa_extreme_rewind = B_TRUE;
3096		rewind_error = spa_load_retry(spa, state, mosconfig);
3097	}
3098
3099	spa->spa_extreme_rewind = B_FALSE;
3100	spa->spa_load_max_txg = UINT64_MAX;
3101
3102	if (config && (rewind_error || state != SPA_LOAD_RECOVER))
3103		spa_config_set(spa, config);
3104
3105	if (state == SPA_LOAD_RECOVER) {
3106		ASSERT3P(loadinfo, ==, NULL);
3107		return (rewind_error);
3108	} else {
3109		/* Store the rewind info as part of the initial load info */
3110		fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
3111		    spa->spa_load_info);
3112
3113		/* Restore the initial load info */
3114		fnvlist_free(spa->spa_load_info);
3115		spa->spa_load_info = loadinfo;
3116
3117		return (load_error);
3118	}
3119}
3120
3121/*
3122 * Pool Open/Import
3123 *
3124 * The import case is identical to an open except that the configuration is sent
3125 * down from userland, instead of grabbed from the configuration cache.  For the
3126 * case of an open, the pool configuration will exist in the
3127 * POOL_STATE_UNINITIALIZED state.
3128 *
3129 * The stats information (gen/count/ustats) is used to gather vdev statistics at
3130 * the same time open the pool, without having to keep around the spa_t in some
3131 * ambiguous state.
3132 */
3133static int
3134spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
3135    nvlist_t **config)
3136{
3137	spa_t *spa;
3138	spa_load_state_t state = SPA_LOAD_OPEN;
3139	int error;
3140	int locked = B_FALSE;
3141	int firstopen = B_FALSE;
3142
3143	*spapp = NULL;
3144
3145	/*
3146	 * As disgusting as this is, we need to support recursive calls to this
3147	 * function because dsl_dir_open() is called during spa_load(), and ends
3148	 * up calling spa_open() again.  The real fix is to figure out how to
3149	 * avoid dsl_dir_open() calling this in the first place.
3150	 */
3151	if (mutex_owner(&spa_namespace_lock) != curthread) {
3152		mutex_enter(&spa_namespace_lock);
3153		locked = B_TRUE;
3154	}
3155
3156	if ((spa = spa_lookup(pool)) == NULL) {
3157		if (locked)
3158			mutex_exit(&spa_namespace_lock);
3159		return (SET_ERROR(ENOENT));
3160	}
3161
3162	if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
3163		zpool_rewind_policy_t policy;
3164
3165		firstopen = B_TRUE;
3166
3167		zpool_get_rewind_policy(nvpolicy ? nvpolicy : spa->spa_config,
3168		    &policy);
3169		if (policy.zrp_request & ZPOOL_DO_REWIND)
3170			state = SPA_LOAD_RECOVER;
3171
3172		spa_activate(spa, spa_mode_global);
3173
3174		if (state != SPA_LOAD_RECOVER)
3175			spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
3176
3177		error = spa_load_best(spa, state, B_FALSE, policy.zrp_txg,
3178		    policy.zrp_request);
3179
3180		if (error == EBADF) {
3181			/*
3182			 * If vdev_validate() returns failure (indicated by
3183			 * EBADF), it indicates that one of the vdevs indicates
3184			 * that the pool has been exported or destroyed.  If
3185			 * this is the case, the config cache is out of sync and
3186			 * we should remove the pool from the namespace.
3187			 */
3188			spa_unload(spa);
3189			spa_deactivate(spa);
3190			spa_config_sync(spa, B_TRUE, B_TRUE);
3191			spa_remove(spa);
3192			if (locked)
3193				mutex_exit(&spa_namespace_lock);
3194			return (SET_ERROR(ENOENT));
3195		}
3196
3197		if (error) {
3198			/*
3199			 * We can't open the pool, but we still have useful
3200			 * information: the state of each vdev after the
3201			 * attempted vdev_open().  Return this to the user.
3202			 */
3203			if (config != NULL && spa->spa_config) {
3204				VERIFY(nvlist_dup(spa->spa_config, config,
3205				    KM_SLEEP) == 0);
3206				VERIFY(nvlist_add_nvlist(*config,
3207				    ZPOOL_CONFIG_LOAD_INFO,
3208				    spa->spa_load_info) == 0);
3209			}
3210			spa_unload(spa);
3211			spa_deactivate(spa);
3212			spa->spa_last_open_failed = error;
3213			if (locked)
3214				mutex_exit(&spa_namespace_lock);
3215			*spapp = NULL;
3216			return (error);
3217		}
3218	}
3219
3220	spa_open_ref(spa, tag);
3221
3222	if (config != NULL)
3223		*config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
3224
3225	/*
3226	 * If we've recovered the pool, pass back any information we
3227	 * gathered while doing the load.
3228	 */
3229	if (state == SPA_LOAD_RECOVER) {
3230		VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
3231		    spa->spa_load_info) == 0);
3232	}
3233
3234	if (locked) {
3235		spa->spa_last_open_failed = 0;
3236		spa->spa_last_ubsync_txg = 0;
3237		spa->spa_load_txg = 0;
3238		mutex_exit(&spa_namespace_lock);
3239#ifdef __FreeBSD__
3240#ifdef _KERNEL
3241		if (firstopen)
3242			zvol_create_minors(spa->spa_name);
3243#endif
3244#endif
3245	}
3246
3247	*spapp = spa;
3248
3249	return (0);
3250}
3251
3252int
3253spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
3254    nvlist_t **config)
3255{
3256	return (spa_open_common(name, spapp, tag, policy, config));
3257}
3258
3259int
3260spa_open(const char *name, spa_t **spapp, void *tag)
3261{
3262	return (spa_open_common(name, spapp, tag, NULL, NULL));
3263}
3264
3265/*
3266 * Lookup the given spa_t, incrementing the inject count in the process,
3267 * preventing it from being exported or destroyed.
3268 */
3269spa_t *
3270spa_inject_addref(char *name)
3271{
3272	spa_t *spa;
3273
3274	mutex_enter(&spa_namespace_lock);
3275	if ((spa = spa_lookup(name)) == NULL) {
3276		mutex_exit(&spa_namespace_lock);
3277		return (NULL);
3278	}
3279	spa->spa_inject_ref++;
3280	mutex_exit(&spa_namespace_lock);
3281
3282	return (spa);
3283}
3284
3285void
3286spa_inject_delref(spa_t *spa)
3287{
3288	mutex_enter(&spa_namespace_lock);
3289	spa->spa_inject_ref--;
3290	mutex_exit(&spa_namespace_lock);
3291}
3292
3293/*
3294 * Add spares device information to the nvlist.
3295 */
3296static void
3297spa_add_spares(spa_t *spa, nvlist_t *config)
3298{
3299	nvlist_t **spares;
3300	uint_t i, nspares;
3301	nvlist_t *nvroot;
3302	uint64_t guid;
3303	vdev_stat_t *vs;
3304	uint_t vsc;
3305	uint64_t pool;
3306
3307	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3308
3309	if (spa->spa_spares.sav_count == 0)
3310		return;
3311
3312	VERIFY(nvlist_lookup_nvlist(config,
3313	    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3314	VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
3315	    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3316	if (nspares != 0) {
3317		VERIFY(nvlist_add_nvlist_array(nvroot,
3318		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3319		VERIFY(nvlist_lookup_nvlist_array(nvroot,
3320		    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3321
3322		/*
3323		 * Go through and find any spares which have since been
3324		 * repurposed as an active spare.  If this is the case, update
3325		 * their status appropriately.
3326		 */
3327		for (i = 0; i < nspares; i++) {
3328			VERIFY(nvlist_lookup_uint64(spares[i],
3329			    ZPOOL_CONFIG_GUID, &guid) == 0);
3330			if (spa_spare_exists(guid, &pool, NULL) &&
3331			    pool != 0ULL) {
3332				VERIFY(nvlist_lookup_uint64_array(
3333				    spares[i], ZPOOL_CONFIG_VDEV_STATS,
3334				    (uint64_t **)&vs, &vsc) == 0);
3335				vs->vs_state = VDEV_STATE_CANT_OPEN;
3336				vs->vs_aux = VDEV_AUX_SPARED;
3337			}
3338		}
3339	}
3340}
3341
3342/*
3343 * Add l2cache device information to the nvlist, including vdev stats.
3344 */
3345static void
3346spa_add_l2cache(spa_t *spa, nvlist_t *config)
3347{
3348	nvlist_t **l2cache;
3349	uint_t i, j, nl2cache;
3350	nvlist_t *nvroot;
3351	uint64_t guid;
3352	vdev_t *vd;
3353	vdev_stat_t *vs;
3354	uint_t vsc;
3355
3356	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3357
3358	if (spa->spa_l2cache.sav_count == 0)
3359		return;
3360
3361	VERIFY(nvlist_lookup_nvlist(config,
3362	    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3363	VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
3364	    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3365	if (nl2cache != 0) {
3366		VERIFY(nvlist_add_nvlist_array(nvroot,
3367		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3368		VERIFY(nvlist_lookup_nvlist_array(nvroot,
3369		    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3370
3371		/*
3372		 * Update level 2 cache device stats.
3373		 */
3374
3375		for (i = 0; i < nl2cache; i++) {
3376			VERIFY(nvlist_lookup_uint64(l2cache[i],
3377			    ZPOOL_CONFIG_GUID, &guid) == 0);
3378
3379			vd = NULL;
3380			for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
3381				if (guid ==
3382				    spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
3383					vd = spa->spa_l2cache.sav_vdevs[j];
3384					break;
3385				}
3386			}
3387			ASSERT(vd != NULL);
3388
3389			VERIFY(nvlist_lookup_uint64_array(l2cache[i],
3390			    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
3391			    == 0);
3392			vdev_get_stats(vd, vs);
3393		}
3394	}
3395}
3396
3397static void
3398spa_add_feature_stats(spa_t *spa, nvlist_t *config)
3399{
3400	nvlist_t *features;
3401	zap_cursor_t zc;
3402	zap_attribute_t za;
3403
3404	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3405	VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3406
3407	/* We may be unable to read features if pool is suspended. */
3408	if (spa_suspended(spa))
3409		goto out;
3410
3411	if (spa->spa_feat_for_read_obj != 0) {
3412		for (zap_cursor_init(&zc, spa->spa_meta_objset,
3413		    spa->spa_feat_for_read_obj);
3414		    zap_cursor_retrieve(&zc, &za) == 0;
3415		    zap_cursor_advance(&zc)) {
3416			ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3417			    za.za_num_integers == 1);
3418			VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
3419			    za.za_first_integer));
3420		}
3421		zap_cursor_fini(&zc);
3422	}
3423
3424	if (spa->spa_feat_for_write_obj != 0) {
3425		for (zap_cursor_init(&zc, spa->spa_meta_objset,
3426		    spa->spa_feat_for_write_obj);
3427		    zap_cursor_retrieve(&zc, &za) == 0;
3428		    zap_cursor_advance(&zc)) {
3429			ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3430			    za.za_num_integers == 1);
3431			VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
3432			    za.za_first_integer));
3433		}
3434		zap_cursor_fini(&zc);
3435	}
3436
3437out:
3438	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
3439	    features) == 0);
3440	nvlist_free(features);
3441}
3442
3443int
3444spa_get_stats(const char *name, nvlist_t **config,
3445    char *altroot, size_t buflen)
3446{
3447	int error;
3448	spa_t *spa;
3449
3450	*config = NULL;
3451	error = spa_open_common(name, &spa, FTAG, NULL, config);
3452
3453	if (spa != NULL) {
3454		/*
3455		 * This still leaves a window of inconsistency where the spares
3456		 * or l2cache devices could change and the config would be
3457		 * self-inconsistent.
3458		 */
3459		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3460
3461		if (*config != NULL) {
3462			uint64_t loadtimes[2];
3463
3464			loadtimes[0] = spa->spa_loaded_ts.tv_sec;
3465			loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
3466			VERIFY(nvlist_add_uint64_array(*config,
3467			    ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
3468
3469			VERIFY(nvlist_add_uint64(*config,
3470			    ZPOOL_CONFIG_ERRCOUNT,
3471			    spa_get_errlog_size(spa)) == 0);
3472
3473			if (spa_suspended(spa))
3474				VERIFY(nvlist_add_uint64(*config,
3475				    ZPOOL_CONFIG_SUSPENDED,
3476				    spa->spa_failmode) == 0);
3477
3478			spa_add_spares(spa, *config);
3479			spa_add_l2cache(spa, *config);
3480			spa_add_feature_stats(spa, *config);
3481		}
3482	}
3483
3484	/*
3485	 * We want to get the alternate root even for faulted pools, so we cheat
3486	 * and call spa_lookup() directly.
3487	 */
3488	if (altroot) {
3489		if (spa == NULL) {
3490			mutex_enter(&spa_namespace_lock);
3491			spa = spa_lookup(name);
3492			if (spa)
3493				spa_altroot(spa, altroot, buflen);
3494			else
3495				altroot[0] = '\0';
3496			spa = NULL;
3497			mutex_exit(&spa_namespace_lock);
3498		} else {
3499			spa_altroot(spa, altroot, buflen);
3500		}
3501	}
3502
3503	if (spa != NULL) {
3504		spa_config_exit(spa, SCL_CONFIG, FTAG);
3505		spa_close(spa, FTAG);
3506	}
3507
3508	return (error);
3509}
3510
3511/*
3512 * Validate that the auxiliary device array is well formed.  We must have an
3513 * array of nvlists, each which describes a valid leaf vdev.  If this is an
3514 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
3515 * specified, as long as they are well-formed.
3516 */
3517static int
3518spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
3519    spa_aux_vdev_t *sav, const char *config, uint64_t version,
3520    vdev_labeltype_t label)
3521{
3522	nvlist_t **dev;
3523	uint_t i, ndev;
3524	vdev_t *vd;
3525	int error;
3526
3527	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3528
3529	/*
3530	 * It's acceptable to have no devs specified.
3531	 */
3532	if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
3533		return (0);
3534
3535	if (ndev == 0)
3536		return (SET_ERROR(EINVAL));
3537
3538	/*
3539	 * Make sure the pool is formatted with a version that supports this
3540	 * device type.
3541	 */
3542	if (spa_version(spa) < version)
3543		return (SET_ERROR(ENOTSUP));
3544
3545	/*
3546	 * Set the pending device list so we correctly handle device in-use
3547	 * checking.
3548	 */
3549	sav->sav_pending = dev;
3550	sav->sav_npending = ndev;
3551
3552	for (i = 0; i < ndev; i++) {
3553		if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
3554		    mode)) != 0)
3555			goto out;
3556
3557		if (!vd->vdev_ops->vdev_op_leaf) {
3558			vdev_free(vd);
3559			error = SET_ERROR(EINVAL);
3560			goto out;
3561		}
3562
3563		/*
3564		 * The L2ARC currently only supports disk devices in
3565		 * kernel context.  For user-level testing, we allow it.
3566		 */
3567#ifdef _KERNEL
3568		if ((strcmp(config, ZPOOL_CONFIG_L2CACHE) == 0) &&
3569		    strcmp(vd->vdev_ops->vdev_op_type, VDEV_TYPE_DISK) != 0) {
3570			error = SET_ERROR(ENOTBLK);
3571			vdev_free(vd);
3572			goto out;
3573		}
3574#endif
3575		vd->vdev_top = vd;
3576
3577		if ((error = vdev_open(vd)) == 0 &&
3578		    (error = vdev_label_init(vd, crtxg, label)) == 0) {
3579			VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
3580			    vd->vdev_guid) == 0);
3581		}
3582
3583		vdev_free(vd);
3584
3585		if (error &&
3586		    (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
3587			goto out;
3588		else
3589			error = 0;
3590	}
3591
3592out:
3593	sav->sav_pending = NULL;
3594	sav->sav_npending = 0;
3595	return (error);
3596}
3597
3598static int
3599spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
3600{
3601	int error;
3602
3603	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3604
3605	if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3606	    &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
3607	    VDEV_LABEL_SPARE)) != 0) {
3608		return (error);
3609	}
3610
3611	return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3612	    &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
3613	    VDEV_LABEL_L2CACHE));
3614}
3615
3616static void
3617spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
3618    const char *config)
3619{
3620	int i;
3621
3622	if (sav->sav_config != NULL) {
3623		nvlist_t **olddevs;
3624		uint_t oldndevs;
3625		nvlist_t **newdevs;
3626
3627		/*
3628		 * Generate new dev list by concatentating with the
3629		 * current dev list.
3630		 */
3631		VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
3632		    &olddevs, &oldndevs) == 0);
3633
3634		newdevs = kmem_alloc(sizeof (void *) *
3635		    (ndevs + oldndevs), KM_SLEEP);
3636		for (i = 0; i < oldndevs; i++)
3637			VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
3638			    KM_SLEEP) == 0);
3639		for (i = 0; i < ndevs; i++)
3640			VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
3641			    KM_SLEEP) == 0);
3642
3643		VERIFY(nvlist_remove(sav->sav_config, config,
3644		    DATA_TYPE_NVLIST_ARRAY) == 0);
3645
3646		VERIFY(nvlist_add_nvlist_array(sav->sav_config,
3647		    config, newdevs, ndevs + oldndevs) == 0);
3648		for (i = 0; i < oldndevs + ndevs; i++)
3649			nvlist_free(newdevs[i]);
3650		kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
3651	} else {
3652		/*
3653		 * Generate a new dev list.
3654		 */
3655		VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
3656		    KM_SLEEP) == 0);
3657		VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
3658		    devs, ndevs) == 0);
3659	}
3660}
3661
3662/*
3663 * Stop and drop level 2 ARC devices
3664 */
3665void
3666spa_l2cache_drop(spa_t *spa)
3667{
3668	vdev_t *vd;
3669	int i;
3670	spa_aux_vdev_t *sav = &spa->spa_l2cache;
3671
3672	for (i = 0; i < sav->sav_count; i++) {
3673		uint64_t pool;
3674
3675		vd = sav->sav_vdevs[i];
3676		ASSERT(vd != NULL);
3677
3678		if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
3679		    pool != 0ULL && l2arc_vdev_present(vd))
3680			l2arc_remove_vdev(vd);
3681	}
3682}
3683
3684/*
3685 * Pool Creation
3686 */
3687int
3688spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
3689    nvlist_t *zplprops)
3690{
3691	spa_t *spa;
3692	char *altroot = NULL;
3693	vdev_t *rvd;
3694	dsl_pool_t *dp;
3695	dmu_tx_t *tx;
3696	int error = 0;
3697	uint64_t txg = TXG_INITIAL;
3698	nvlist_t **spares, **l2cache;
3699	uint_t nspares, nl2cache;
3700	uint64_t version, obj;
3701	boolean_t has_features;
3702
3703	/*
3704	 * If this pool already exists, return failure.
3705	 */
3706	mutex_enter(&spa_namespace_lock);
3707	if (spa_lookup(pool) != NULL) {
3708		mutex_exit(&spa_namespace_lock);
3709		return (SET_ERROR(EEXIST));
3710	}
3711
3712	/*
3713	 * Allocate a new spa_t structure.
3714	 */
3715	(void) nvlist_lookup_string(props,
3716	    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
3717	spa = spa_add(pool, NULL, altroot);
3718	spa_activate(spa, spa_mode_global);
3719
3720	if (props && (error = spa_prop_validate(spa, props))) {
3721		spa_deactivate(spa);
3722		spa_remove(spa);
3723		mutex_exit(&spa_namespace_lock);
3724		return (error);
3725	}
3726
3727	has_features = B_FALSE;
3728	for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
3729	    elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
3730		if (zpool_prop_feature(nvpair_name(elem)))
3731			has_features = B_TRUE;
3732	}
3733
3734	if (has_features || nvlist_lookup_uint64(props,
3735	    zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
3736		version = SPA_VERSION;
3737	}
3738	ASSERT(SPA_VERSION_IS_SUPPORTED(version));
3739
3740	spa->spa_first_txg = txg;
3741	spa->spa_uberblock.ub_txg = txg - 1;
3742	spa->spa_uberblock.ub_version = version;
3743	spa->spa_ubsync = spa->spa_uberblock;
3744	spa->spa_load_state = SPA_LOAD_CREATE;
3745
3746	/*
3747	 * Create "The Godfather" zio to hold all async IOs
3748	 */
3749	spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
3750	    KM_SLEEP);
3751	for (int i = 0; i < max_ncpus; i++) {
3752		spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
3753		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
3754		    ZIO_FLAG_GODFATHER);
3755	}
3756
3757	/*
3758	 * Create the root vdev.
3759	 */
3760	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3761
3762	error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
3763
3764	ASSERT(error != 0 || rvd != NULL);
3765	ASSERT(error != 0 || spa->spa_root_vdev == rvd);
3766
3767	if (error == 0 && !zfs_allocatable_devs(nvroot))
3768		error = SET_ERROR(EINVAL);
3769
3770	if (error == 0 &&
3771	    (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
3772	    (error = spa_validate_aux(spa, nvroot, txg,
3773	    VDEV_ALLOC_ADD)) == 0) {
3774		for (int c = 0; c < rvd->vdev_children; c++) {
3775			vdev_ashift_optimize(rvd->vdev_child[c]);
3776			vdev_metaslab_set_size(rvd->vdev_child[c]);
3777			vdev_expand(rvd->vdev_child[c], txg);
3778		}
3779	}
3780
3781	spa_config_exit(spa, SCL_ALL, FTAG);
3782
3783	if (error != 0) {
3784		spa_unload(spa);
3785		spa_deactivate(spa);
3786		spa_remove(spa);
3787		mutex_exit(&spa_namespace_lock);
3788		return (error);
3789	}
3790
3791	/*
3792	 * Get the list of spares, if specified.
3793	 */
3794	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
3795	    &spares, &nspares) == 0) {
3796		VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
3797		    KM_SLEEP) == 0);
3798		VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
3799		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3800		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3801		spa_load_spares(spa);
3802		spa_config_exit(spa, SCL_ALL, FTAG);
3803		spa->spa_spares.sav_sync = B_TRUE;
3804	}
3805
3806	/*
3807	 * Get the list of level 2 cache devices, if specified.
3808	 */
3809	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
3810	    &l2cache, &nl2cache) == 0) {
3811		VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
3812		    NV_UNIQUE_NAME, KM_SLEEP) == 0);
3813		VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
3814		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3815		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3816		spa_load_l2cache(spa);
3817		spa_config_exit(spa, SCL_ALL, FTAG);
3818		spa->spa_l2cache.sav_sync = B_TRUE;
3819	}
3820
3821	spa->spa_is_initializing = B_TRUE;
3822	spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
3823	spa->spa_meta_objset = dp->dp_meta_objset;
3824	spa->spa_is_initializing = B_FALSE;
3825
3826	/*
3827	 * Create DDTs (dedup tables).
3828	 */
3829	ddt_create(spa);
3830
3831	spa_update_dspace(spa);
3832
3833	tx = dmu_tx_create_assigned(dp, txg);
3834
3835	/*
3836	 * Create the pool config object.
3837	 */
3838	spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
3839	    DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
3840	    DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
3841
3842	if (zap_add(spa->spa_meta_objset,
3843	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
3844	    sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
3845		cmn_err(CE_PANIC, "failed to add pool config");
3846	}
3847
3848	if (spa_version(spa) >= SPA_VERSION_FEATURES)
3849		spa_feature_create_zap_objects(spa, tx);
3850
3851	if (zap_add(spa->spa_meta_objset,
3852	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
3853	    sizeof (uint64_t), 1, &version, tx) != 0) {
3854		cmn_err(CE_PANIC, "failed to add pool version");
3855	}
3856
3857	/* Newly created pools with the right version are always deflated. */
3858	if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
3859		spa->spa_deflate = TRUE;
3860		if (zap_add(spa->spa_meta_objset,
3861		    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
3862		    sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
3863			cmn_err(CE_PANIC, "failed to add deflate");
3864		}
3865	}
3866
3867	/*
3868	 * Create the deferred-free bpobj.  Turn off compression
3869	 * because sync-to-convergence takes longer if the blocksize
3870	 * keeps changing.
3871	 */
3872	obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
3873	dmu_object_set_compress(spa->spa_meta_objset, obj,
3874	    ZIO_COMPRESS_OFF, tx);
3875	if (zap_add(spa->spa_meta_objset,
3876	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
3877	    sizeof (uint64_t), 1, &obj, tx) != 0) {
3878		cmn_err(CE_PANIC, "failed to add bpobj");
3879	}
3880	VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
3881	    spa->spa_meta_objset, obj));
3882
3883	/*
3884	 * Create the pool's history object.
3885	 */
3886	if (version >= SPA_VERSION_ZPOOL_HISTORY)
3887		spa_history_create_obj(spa, tx);
3888
3889	/*
3890	 * Generate some random noise for salted checksums to operate on.
3891	 */
3892	(void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3893	    sizeof (spa->spa_cksum_salt.zcs_bytes));
3894
3895	/*
3896	 * Set pool properties.
3897	 */
3898	spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
3899	spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3900	spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
3901	spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
3902
3903	if (props != NULL) {
3904		spa_configfile_set(spa, props, B_FALSE);
3905		spa_sync_props(props, tx);
3906	}
3907
3908	dmu_tx_commit(tx);
3909
3910	spa->spa_sync_on = B_TRUE;
3911	txg_sync_start(spa->spa_dsl_pool);
3912
3913	/*
3914	 * We explicitly wait for the first transaction to complete so that our
3915	 * bean counters are appropriately updated.
3916	 */
3917	txg_wait_synced(spa->spa_dsl_pool, txg);
3918
3919	spa_config_sync(spa, B_FALSE, B_TRUE);
3920	spa_event_notify(spa, NULL, ESC_ZFS_POOL_CREATE);
3921
3922	spa_history_log_version(spa, "create");
3923
3924	/*
3925	 * Don't count references from objsets that are already closed
3926	 * and are making their way through the eviction process.
3927	 */
3928	spa_evicting_os_wait(spa);
3929	spa->spa_minref = refcount_count(&spa->spa_refcount);
3930	spa->spa_load_state = SPA_LOAD_NONE;
3931
3932	mutex_exit(&spa_namespace_lock);
3933
3934	return (0);
3935}
3936
3937#ifdef _KERNEL
3938#ifdef illumos
3939/*
3940 * Get the root pool information from the root disk, then import the root pool
3941 * during the system boot up time.
3942 */
3943extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
3944
3945static nvlist_t *
3946spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
3947{
3948	nvlist_t *config;
3949	nvlist_t *nvtop, *nvroot;
3950	uint64_t pgid;
3951
3952	if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
3953		return (NULL);
3954
3955	/*
3956	 * Add this top-level vdev to the child array.
3957	 */
3958	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
3959	    &nvtop) == 0);
3960	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
3961	    &pgid) == 0);
3962	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
3963
3964	/*
3965	 * Put this pool's top-level vdevs into a root vdev.
3966	 */
3967	VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3968	VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
3969	    VDEV_TYPE_ROOT) == 0);
3970	VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
3971	VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
3972	VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
3973	    &nvtop, 1) == 0);
3974
3975	/*
3976	 * Replace the existing vdev_tree with the new root vdev in
3977	 * this pool's configuration (remove the old, add the new).
3978	 */
3979	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
3980	nvlist_free(nvroot);
3981	return (config);
3982}
3983
3984/*
3985 * Walk the vdev tree and see if we can find a device with "better"
3986 * configuration. A configuration is "better" if the label on that
3987 * device has a more recent txg.
3988 */
3989static void
3990spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
3991{
3992	for (int c = 0; c < vd->vdev_children; c++)
3993		spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
3994
3995	if (vd->vdev_ops->vdev_op_leaf) {
3996		nvlist_t *label;
3997		uint64_t label_txg;
3998
3999		if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
4000		    &label) != 0)
4001			return;
4002
4003		VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
4004		    &label_txg) == 0);
4005
4006		/*
4007		 * Do we have a better boot device?
4008		 */
4009		if (label_txg > *txg) {
4010			*txg = label_txg;
4011			*avd = vd;
4012		}
4013		nvlist_free(label);
4014	}
4015}
4016
4017/*
4018 * Import a root pool.
4019 *
4020 * For x86. devpath_list will consist of devid and/or physpath name of
4021 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
4022 * The GRUB "findroot" command will return the vdev we should boot.
4023 *
4024 * For Sparc, devpath_list consists the physpath name of the booting device
4025 * no matter the rootpool is a single device pool or a mirrored pool.
4026 * e.g.
4027 *	"/pci@1f,0/ide@d/disk@0,0:a"
4028 */
4029int
4030spa_import_rootpool(char *devpath, char *devid)
4031{
4032	spa_t *spa;
4033	vdev_t *rvd, *bvd, *avd = NULL;
4034	nvlist_t *config, *nvtop;
4035	uint64_t guid, txg;
4036	char *pname;
4037	int error;
4038
4039	/*
4040	 * Read the label from the boot device and generate a configuration.
4041	 */
4042	config = spa_generate_rootconf(devpath, devid, &guid);
4043#if defined(_OBP) && defined(_KERNEL)
4044	if (config == NULL) {
4045		if (strstr(devpath, "/iscsi/ssd") != NULL) {
4046			/* iscsi boot */
4047			get_iscsi_bootpath_phy(devpath);
4048			config = spa_generate_rootconf(devpath, devid, &guid);
4049		}
4050	}
4051#endif
4052	if (config == NULL) {
4053		cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
4054		    devpath);
4055		return (SET_ERROR(EIO));
4056	}
4057
4058	VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
4059	    &pname) == 0);
4060	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
4061
4062	mutex_enter(&spa_namespace_lock);
4063	if ((spa = spa_lookup(pname)) != NULL) {
4064		/*
4065		 * Remove the existing root pool from the namespace so that we
4066		 * can replace it with the correct config we just read in.
4067		 */
4068		spa_remove(spa);
4069	}
4070
4071	spa = spa_add(pname, config, NULL);
4072	spa->spa_is_root = B_TRUE;
4073	spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
4074
4075	/*
4076	 * Build up a vdev tree based on the boot device's label config.
4077	 */
4078	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4079	    &nvtop) == 0);
4080	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4081	error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
4082	    VDEV_ALLOC_ROOTPOOL);
4083	spa_config_exit(spa, SCL_ALL, FTAG);
4084	if (error) {
4085		mutex_exit(&spa_namespace_lock);
4086		nvlist_free(config);
4087		cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
4088		    pname);
4089		return (error);
4090	}
4091
4092	/*
4093	 * Get the boot vdev.
4094	 */
4095	if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
4096		cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
4097		    (u_longlong_t)guid);
4098		error = SET_ERROR(ENOENT);
4099		goto out;
4100	}
4101
4102	/*
4103	 * Determine if there is a better boot device.
4104	 */
4105	avd = bvd;
4106	spa_alt_rootvdev(rvd, &avd, &txg);
4107	if (avd != bvd) {
4108		cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
4109		    "try booting from '%s'", avd->vdev_path);
4110		error = SET_ERROR(EINVAL);
4111		goto out;
4112	}
4113
4114	/*
4115	 * If the boot device is part of a spare vdev then ensure that
4116	 * we're booting off the active spare.
4117	 */
4118	if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
4119	    !bvd->vdev_isspare) {
4120		cmn_err(CE_NOTE, "The boot device is currently spared. Please "
4121		    "try booting from '%s'",
4122		    bvd->vdev_parent->
4123		    vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
4124		error = SET_ERROR(EINVAL);
4125		goto out;
4126	}
4127
4128	error = 0;
4129out:
4130	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4131	vdev_free(rvd);
4132	spa_config_exit(spa, SCL_ALL, FTAG);
4133	mutex_exit(&spa_namespace_lock);
4134
4135	nvlist_free(config);
4136	return (error);
4137}
4138
4139#else	/* !illumos */
4140
4141extern int vdev_geom_read_pool_label(const char *name, nvlist_t ***configs,
4142    uint64_t *count);
4143
4144static nvlist_t *
4145spa_generate_rootconf(const char *name)
4146{
4147	nvlist_t **configs, **tops;
4148	nvlist_t *config;
4149	nvlist_t *best_cfg, *nvtop, *nvroot;
4150	uint64_t *holes;
4151	uint64_t best_txg;
4152	uint64_t nchildren;
4153	uint64_t pgid;
4154	uint64_t count;
4155	uint64_t i;
4156	uint_t   nholes;
4157
4158	if (vdev_geom_read_pool_label(name, &configs, &count) != 0)
4159		return (NULL);
4160
4161	ASSERT3U(count, !=, 0);
4162	best_txg = 0;
4163	for (i = 0; i < count; i++) {
4164		uint64_t txg;
4165
4166		VERIFY(nvlist_lookup_uint64(configs[i], ZPOOL_CONFIG_POOL_TXG,
4167		    &txg) == 0);
4168		if (txg > best_txg) {
4169			best_txg = txg;
4170			best_cfg = configs[i];
4171		}
4172	}
4173
4174	nchildren = 1;
4175	nvlist_lookup_uint64(best_cfg, ZPOOL_CONFIG_VDEV_CHILDREN, &nchildren);
4176	holes = NULL;
4177	nvlist_lookup_uint64_array(best_cfg, ZPOOL_CONFIG_HOLE_ARRAY,
4178	    &holes, &nholes);
4179
4180	tops = kmem_zalloc(nchildren * sizeof(void *), KM_SLEEP);
4181	for (i = 0; i < nchildren; i++) {
4182		if (i >= count)
4183			break;
4184		if (configs[i] == NULL)
4185			continue;
4186		VERIFY(nvlist_lookup_nvlist(configs[i], ZPOOL_CONFIG_VDEV_TREE,
4187		    &nvtop) == 0);
4188		nvlist_dup(nvtop, &tops[i], KM_SLEEP);
4189	}
4190	for (i = 0; holes != NULL && i < nholes; i++) {
4191		if (i >= nchildren)
4192			continue;
4193		if (tops[holes[i]] != NULL)
4194			continue;
4195		nvlist_alloc(&tops[holes[i]], NV_UNIQUE_NAME, KM_SLEEP);
4196		VERIFY(nvlist_add_string(tops[holes[i]], ZPOOL_CONFIG_TYPE,
4197		    VDEV_TYPE_HOLE) == 0);
4198		VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_ID,
4199		    holes[i]) == 0);
4200		VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_GUID,
4201		    0) == 0);
4202	}
4203	for (i = 0; i < nchildren; i++) {
4204		if (tops[i] != NULL)
4205			continue;
4206		nvlist_alloc(&tops[i], NV_UNIQUE_NAME, KM_SLEEP);
4207		VERIFY(nvlist_add_string(tops[i], ZPOOL_CONFIG_TYPE,
4208		    VDEV_TYPE_MISSING) == 0);
4209		VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_ID,
4210		    i) == 0);
4211		VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_GUID,
4212		    0) == 0);
4213	}
4214
4215	/*
4216	 * Create pool config based on the best vdev config.
4217	 */
4218	nvlist_dup(best_cfg, &config, KM_SLEEP);
4219
4220	/*
4221	 * Put this pool's top-level vdevs into a root vdev.
4222	 */
4223	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4224	    &pgid) == 0);
4225	VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4226	VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
4227	    VDEV_TYPE_ROOT) == 0);
4228	VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
4229	VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
4230	VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
4231	    tops, nchildren) == 0);
4232
4233	/*
4234	 * Replace the existing vdev_tree with the new root vdev in
4235	 * this pool's configuration (remove the old, add the new).
4236	 */
4237	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
4238
4239	/*
4240	 * Drop vdev config elements that should not be present at pool level.
4241	 */
4242	nvlist_remove(config, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64);
4243	nvlist_remove(config, ZPOOL_CONFIG_TOP_GUID, DATA_TYPE_UINT64);
4244
4245	for (i = 0; i < count; i++)
4246		nvlist_free(configs[i]);
4247	kmem_free(configs, count * sizeof(void *));
4248	for (i = 0; i < nchildren; i++)
4249		nvlist_free(tops[i]);
4250	kmem_free(tops, nchildren * sizeof(void *));
4251	nvlist_free(nvroot);
4252	return (config);
4253}
4254
4255int
4256spa_import_rootpool(const char *name)
4257{
4258	spa_t *spa;
4259	vdev_t *rvd, *bvd, *avd = NULL;
4260	nvlist_t *config, *nvtop;
4261	uint64_t txg;
4262	char *pname;
4263	int error;
4264
4265	/*
4266	 * Read the label from the boot device and generate a configuration.
4267	 */
4268	config = spa_generate_rootconf(name);
4269
4270	mutex_enter(&spa_namespace_lock);
4271	if (config != NULL) {
4272		VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
4273		    &pname) == 0 && strcmp(name, pname) == 0);
4274		VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg)
4275		    == 0);
4276
4277		if ((spa = spa_lookup(pname)) != NULL) {
4278			/*
4279			 * The pool could already be imported,
4280			 * e.g., after reboot -r.
4281			 */
4282			if (spa->spa_state == POOL_STATE_ACTIVE) {
4283				mutex_exit(&spa_namespace_lock);
4284				nvlist_free(config);
4285				return (0);
4286			}
4287
4288			/*
4289			 * Remove the existing root pool from the namespace so
4290			 * that we can replace it with the correct config
4291			 * we just read in.
4292			 */
4293			spa_remove(spa);
4294		}
4295		spa = spa_add(pname, config, NULL);
4296
4297		/*
4298		 * Set spa_ubsync.ub_version as it can be used in vdev_alloc()
4299		 * via spa_version().
4300		 */
4301		if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
4302		    &spa->spa_ubsync.ub_version) != 0)
4303			spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
4304	} else if ((spa = spa_lookup(name)) == NULL) {
4305		mutex_exit(&spa_namespace_lock);
4306		nvlist_free(config);
4307		cmn_err(CE_NOTE, "Cannot find the pool label for '%s'",
4308		    name);
4309		return (EIO);
4310	} else {
4311		VERIFY(nvlist_dup(spa->spa_config, &config, KM_SLEEP) == 0);
4312	}
4313	spa->spa_is_root = B_TRUE;
4314	spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
4315
4316	/*
4317	 * Build up a vdev tree based on the boot device's label config.
4318	 */
4319	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4320	    &nvtop) == 0);
4321	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4322	error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
4323	    VDEV_ALLOC_ROOTPOOL);
4324	spa_config_exit(spa, SCL_ALL, FTAG);
4325	if (error) {
4326		mutex_exit(&spa_namespace_lock);
4327		nvlist_free(config);
4328		cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
4329		    pname);
4330		return (error);
4331	}
4332
4333	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4334	vdev_free(rvd);
4335	spa_config_exit(spa, SCL_ALL, FTAG);
4336	mutex_exit(&spa_namespace_lock);
4337
4338	nvlist_free(config);
4339	return (0);
4340}
4341
4342#endif	/* illumos */
4343#endif	/* _KERNEL */
4344
4345/*
4346 * Import a non-root pool into the system.
4347 */
4348int
4349spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
4350{
4351	spa_t *spa;
4352	char *altroot = NULL;
4353	spa_load_state_t state = SPA_LOAD_IMPORT;
4354	zpool_rewind_policy_t policy;
4355	uint64_t mode = spa_mode_global;
4356	uint64_t readonly = B_FALSE;
4357	int error;
4358	nvlist_t *nvroot;
4359	nvlist_t **spares, **l2cache;
4360	uint_t nspares, nl2cache;
4361
4362	/*
4363	 * If a pool with this name exists, return failure.
4364	 */
4365	mutex_enter(&spa_namespace_lock);
4366	if (spa_lookup(pool) != NULL) {
4367		mutex_exit(&spa_namespace_lock);
4368		return (SET_ERROR(EEXIST));
4369	}
4370
4371	/*
4372	 * Create and initialize the spa structure.
4373	 */
4374	(void) nvlist_lookup_string(props,
4375	    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4376	(void) nvlist_lookup_uint64(props,
4377	    zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
4378	if (readonly)
4379		mode = FREAD;
4380	spa = spa_add(pool, config, altroot);
4381	spa->spa_import_flags = flags;
4382
4383	/*
4384	 * Verbatim import - Take a pool and insert it into the namespace
4385	 * as if it had been loaded at boot.
4386	 */
4387	if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
4388		if (props != NULL)
4389			spa_configfile_set(spa, props, B_FALSE);
4390
4391		spa_config_sync(spa, B_FALSE, B_TRUE);
4392		spa_event_notify(spa, NULL, ESC_ZFS_POOL_IMPORT);
4393
4394		mutex_exit(&spa_namespace_lock);
4395		return (0);
4396	}
4397
4398	spa_activate(spa, mode);
4399
4400	/*
4401	 * Don't start async tasks until we know everything is healthy.
4402	 */
4403	spa_async_suspend(spa);
4404
4405	zpool_get_rewind_policy(config, &policy);
4406	if (policy.zrp_request & ZPOOL_DO_REWIND)
4407		state = SPA_LOAD_RECOVER;
4408
4409	/*
4410	 * Pass off the heavy lifting to spa_load().  Pass TRUE for mosconfig
4411	 * because the user-supplied config is actually the one to trust when
4412	 * doing an import.
4413	 */
4414	if (state != SPA_LOAD_RECOVER)
4415		spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4416
4417	error = spa_load_best(spa, state, B_TRUE, policy.zrp_txg,
4418	    policy.zrp_request);
4419
4420	/*
4421	 * Propagate anything learned while loading the pool and pass it
4422	 * back to caller (i.e. rewind info, missing devices, etc).
4423	 */
4424	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
4425	    spa->spa_load_info) == 0);
4426
4427	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4428	/*
4429	 * Toss any existing sparelist, as it doesn't have any validity
4430	 * anymore, and conflicts with spa_has_spare().
4431	 */
4432	if (spa->spa_spares.sav_config) {
4433		nvlist_free(spa->spa_spares.sav_config);
4434		spa->spa_spares.sav_config = NULL;
4435		spa_load_spares(spa);
4436	}
4437	if (spa->spa_l2cache.sav_config) {
4438		nvlist_free(spa->spa_l2cache.sav_config);
4439		spa->spa_l2cache.sav_config = NULL;
4440		spa_load_l2cache(spa);
4441	}
4442
4443	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4444	    &nvroot) == 0);
4445	if (error == 0)
4446		error = spa_validate_aux(spa, nvroot, -1ULL,
4447		    VDEV_ALLOC_SPARE);
4448	if (error == 0)
4449		error = spa_validate_aux(spa, nvroot, -1ULL,
4450		    VDEV_ALLOC_L2CACHE);
4451	spa_config_exit(spa, SCL_ALL, FTAG);
4452
4453	if (props != NULL)
4454		spa_configfile_set(spa, props, B_FALSE);
4455
4456	if (error != 0 || (props && spa_writeable(spa) &&
4457	    (error = spa_prop_set(spa, props)))) {
4458		spa_unload(spa);
4459		spa_deactivate(spa);
4460		spa_remove(spa);
4461		mutex_exit(&spa_namespace_lock);
4462		return (error);
4463	}
4464
4465	spa_async_resume(spa);
4466
4467	/*
4468	 * Override any spares and level 2 cache devices as specified by
4469	 * the user, as these may have correct device names/devids, etc.
4470	 */
4471	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4472	    &spares, &nspares) == 0) {
4473		if (spa->spa_spares.sav_config)
4474			VERIFY(nvlist_remove(spa->spa_spares.sav_config,
4475			    ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
4476		else
4477			VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
4478			    NV_UNIQUE_NAME, KM_SLEEP) == 0);
4479		VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4480		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4481		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4482		spa_load_spares(spa);
4483		spa_config_exit(spa, SCL_ALL, FTAG);
4484		spa->spa_spares.sav_sync = B_TRUE;
4485	}
4486	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4487	    &l2cache, &nl2cache) == 0) {
4488		if (spa->spa_l2cache.sav_config)
4489			VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
4490			    ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
4491		else
4492			VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
4493			    NV_UNIQUE_NAME, KM_SLEEP) == 0);
4494		VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4495		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4496		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4497		spa_load_l2cache(spa);
4498		spa_config_exit(spa, SCL_ALL, FTAG);
4499		spa->spa_l2cache.sav_sync = B_TRUE;
4500	}
4501
4502	/*
4503	 * Check for any removed devices.
4504	 */
4505	if (spa->spa_autoreplace) {
4506		spa_aux_check_removed(&spa->spa_spares);
4507		spa_aux_check_removed(&spa->spa_l2cache);
4508	}
4509
4510	if (spa_writeable(spa)) {
4511		/*
4512		 * Update the config cache to include the newly-imported pool.
4513		 */
4514		spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
4515	}
4516
4517	/*
4518	 * It's possible that the pool was expanded while it was exported.
4519	 * We kick off an async task to handle this for us.
4520	 */
4521	spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
4522
4523	spa_history_log_version(spa, "import");
4524
4525	spa_event_notify(spa, NULL, ESC_ZFS_POOL_IMPORT);
4526
4527	mutex_exit(&spa_namespace_lock);
4528
4529#ifdef __FreeBSD__
4530#ifdef _KERNEL
4531	zvol_create_minors(pool);
4532#endif
4533#endif
4534	return (0);
4535}
4536
4537nvlist_t *
4538spa_tryimport(nvlist_t *tryconfig)
4539{
4540	nvlist_t *config = NULL;
4541	char *poolname;
4542	spa_t *spa;
4543	uint64_t state;
4544	int error;
4545
4546	if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
4547		return (NULL);
4548
4549	if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
4550		return (NULL);
4551
4552	/*
4553	 * Create and initialize the spa structure.
4554	 */
4555	mutex_enter(&spa_namespace_lock);
4556	spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
4557	spa_activate(spa, FREAD);
4558
4559	/*
4560	 * Pass off the heavy lifting to spa_load().
4561	 * Pass TRUE for mosconfig because the user-supplied config
4562	 * is actually the one to trust when doing an import.
4563	 */
4564	error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING, B_TRUE);
4565
4566	/*
4567	 * If 'tryconfig' was at least parsable, return the current config.
4568	 */
4569	if (spa->spa_root_vdev != NULL) {
4570		config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4571		VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
4572		    poolname) == 0);
4573		VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4574		    state) == 0);
4575		VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
4576		    spa->spa_uberblock.ub_timestamp) == 0);
4577		VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
4578		    spa->spa_load_info) == 0);
4579
4580		/*
4581		 * If the bootfs property exists on this pool then we
4582		 * copy it out so that external consumers can tell which
4583		 * pools are bootable.
4584		 */
4585		if ((!error || error == EEXIST) && spa->spa_bootfs) {
4586			char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4587
4588			/*
4589			 * We have to play games with the name since the
4590			 * pool was opened as TRYIMPORT_NAME.
4591			 */
4592			if (dsl_dsobj_to_dsname(spa_name(spa),
4593			    spa->spa_bootfs, tmpname) == 0) {
4594				char *cp;
4595				char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4596
4597				cp = strchr(tmpname, '/');
4598				if (cp == NULL) {
4599					(void) strlcpy(dsname, tmpname,
4600					    MAXPATHLEN);
4601				} else {
4602					(void) snprintf(dsname, MAXPATHLEN,
4603					    "%s/%s", poolname, ++cp);
4604				}
4605				VERIFY(nvlist_add_string(config,
4606				    ZPOOL_CONFIG_BOOTFS, dsname) == 0);
4607				kmem_free(dsname, MAXPATHLEN);
4608			}
4609			kmem_free(tmpname, MAXPATHLEN);
4610		}
4611
4612		/*
4613		 * Add the list of hot spares and level 2 cache devices.
4614		 */
4615		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4616		spa_add_spares(spa, config);
4617		spa_add_l2cache(spa, config);
4618		spa_config_exit(spa, SCL_CONFIG, FTAG);
4619	}
4620
4621	spa_unload(spa);
4622	spa_deactivate(spa);
4623	spa_remove(spa);
4624	mutex_exit(&spa_namespace_lock);
4625
4626	return (config);
4627}
4628
4629/*
4630 * Pool export/destroy
4631 *
4632 * The act of destroying or exporting a pool is very simple.  We make sure there
4633 * is no more pending I/O and any references to the pool are gone.  Then, we
4634 * update the pool state and sync all the labels to disk, removing the
4635 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
4636 * we don't sync the labels or remove the configuration cache.
4637 */
4638static int
4639spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
4640    boolean_t force, boolean_t hardforce)
4641{
4642	spa_t *spa;
4643
4644	if (oldconfig)
4645		*oldconfig = NULL;
4646
4647	if (!(spa_mode_global & FWRITE))
4648		return (SET_ERROR(EROFS));
4649
4650	mutex_enter(&spa_namespace_lock);
4651	if ((spa = spa_lookup(pool)) == NULL) {
4652		mutex_exit(&spa_namespace_lock);
4653		return (SET_ERROR(ENOENT));
4654	}
4655
4656	/*
4657	 * Put a hold on the pool, drop the namespace lock, stop async tasks,
4658	 * reacquire the namespace lock, and see if we can export.
4659	 */
4660	spa_open_ref(spa, FTAG);
4661	mutex_exit(&spa_namespace_lock);
4662	spa_async_suspend(spa);
4663	mutex_enter(&spa_namespace_lock);
4664	spa_close(spa, FTAG);
4665
4666	/*
4667	 * The pool will be in core if it's openable,
4668	 * in which case we can modify its state.
4669	 */
4670	if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
4671		/*
4672		 * Objsets may be open only because they're dirty, so we
4673		 * have to force it to sync before checking spa_refcnt.
4674		 */
4675		txg_wait_synced(spa->spa_dsl_pool, 0);
4676		spa_evicting_os_wait(spa);
4677
4678		/*
4679		 * A pool cannot be exported or destroyed if there are active
4680		 * references.  If we are resetting a pool, allow references by
4681		 * fault injection handlers.
4682		 */
4683		if (!spa_refcount_zero(spa) ||
4684		    (spa->spa_inject_ref != 0 &&
4685		    new_state != POOL_STATE_UNINITIALIZED)) {
4686			spa_async_resume(spa);
4687			mutex_exit(&spa_namespace_lock);
4688			return (SET_ERROR(EBUSY));
4689		}
4690
4691		/*
4692		 * A pool cannot be exported if it has an active shared spare.
4693		 * This is to prevent other pools stealing the active spare
4694		 * from an exported pool. At user's own will, such pool can
4695		 * be forcedly exported.
4696		 */
4697		if (!force && new_state == POOL_STATE_EXPORTED &&
4698		    spa_has_active_shared_spare(spa)) {
4699			spa_async_resume(spa);
4700			mutex_exit(&spa_namespace_lock);
4701			return (SET_ERROR(EXDEV));
4702		}
4703
4704		/*
4705		 * We want this to be reflected on every label,
4706		 * so mark them all dirty.  spa_unload() will do the
4707		 * final sync that pushes these changes out.
4708		 */
4709		if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
4710			spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4711			spa->spa_state = new_state;
4712			spa->spa_final_txg = spa_last_synced_txg(spa) +
4713			    TXG_DEFER_SIZE + 1;
4714			vdev_config_dirty(spa->spa_root_vdev);
4715			spa_config_exit(spa, SCL_ALL, FTAG);
4716		}
4717	}
4718
4719	spa_event_notify(spa, NULL, ESC_ZFS_POOL_DESTROY);
4720
4721	if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
4722		spa_unload(spa);
4723		spa_deactivate(spa);
4724	}
4725
4726	if (oldconfig && spa->spa_config)
4727		VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
4728
4729	if (new_state != POOL_STATE_UNINITIALIZED) {
4730		if (!hardforce)
4731			spa_config_sync(spa, B_TRUE, B_TRUE);
4732		spa_remove(spa);
4733	}
4734	mutex_exit(&spa_namespace_lock);
4735
4736	return (0);
4737}
4738
4739/*
4740 * Destroy a storage pool.
4741 */
4742int
4743spa_destroy(char *pool)
4744{
4745	return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
4746	    B_FALSE, B_FALSE));
4747}
4748
4749/*
4750 * Export a storage pool.
4751 */
4752int
4753spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
4754    boolean_t hardforce)
4755{
4756	return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
4757	    force, hardforce));
4758}
4759
4760/*
4761 * Similar to spa_export(), this unloads the spa_t without actually removing it
4762 * from the namespace in any way.
4763 */
4764int
4765spa_reset(char *pool)
4766{
4767	return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
4768	    B_FALSE, B_FALSE));
4769}
4770
4771/*
4772 * ==========================================================================
4773 * Device manipulation
4774 * ==========================================================================
4775 */
4776
4777/*
4778 * Add a device to a storage pool.
4779 */
4780int
4781spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
4782{
4783	uint64_t txg, id;
4784	int error;
4785	vdev_t *rvd = spa->spa_root_vdev;
4786	vdev_t *vd, *tvd;
4787	nvlist_t **spares, **l2cache;
4788	uint_t nspares, nl2cache;
4789
4790	ASSERT(spa_writeable(spa));
4791
4792	txg = spa_vdev_enter(spa);
4793
4794	if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
4795	    VDEV_ALLOC_ADD)) != 0)
4796		return (spa_vdev_exit(spa, NULL, txg, error));
4797
4798	spa->spa_pending_vdev = vd;	/* spa_vdev_exit() will clear this */
4799
4800	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
4801	    &nspares) != 0)
4802		nspares = 0;
4803
4804	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
4805	    &nl2cache) != 0)
4806		nl2cache = 0;
4807
4808	if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
4809		return (spa_vdev_exit(spa, vd, txg, EINVAL));
4810
4811	if (vd->vdev_children != 0 &&
4812	    (error = vdev_create(vd, txg, B_FALSE)) != 0)
4813		return (spa_vdev_exit(spa, vd, txg, error));
4814
4815	/*
4816	 * We must validate the spares and l2cache devices after checking the
4817	 * children.  Otherwise, vdev_inuse() will blindly overwrite the spare.
4818	 */
4819	if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
4820		return (spa_vdev_exit(spa, vd, txg, error));
4821
4822	/*
4823	 * Transfer each new top-level vdev from vd to rvd.
4824	 */
4825	for (int c = 0; c < vd->vdev_children; c++) {
4826
4827		/*
4828		 * Set the vdev id to the first hole, if one exists.
4829		 */
4830		for (id = 0; id < rvd->vdev_children; id++) {
4831			if (rvd->vdev_child[id]->vdev_ishole) {
4832				vdev_free(rvd->vdev_child[id]);
4833				break;
4834			}
4835		}
4836		tvd = vd->vdev_child[c];
4837		vdev_remove_child(vd, tvd);
4838		tvd->vdev_id = id;
4839		vdev_add_child(rvd, tvd);
4840		vdev_config_dirty(tvd);
4841	}
4842
4843	if (nspares != 0) {
4844		spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
4845		    ZPOOL_CONFIG_SPARES);
4846		spa_load_spares(spa);
4847		spa->spa_spares.sav_sync = B_TRUE;
4848	}
4849
4850	if (nl2cache != 0) {
4851		spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
4852		    ZPOOL_CONFIG_L2CACHE);
4853		spa_load_l2cache(spa);
4854		spa->spa_l2cache.sav_sync = B_TRUE;
4855	}
4856
4857	/*
4858	 * We have to be careful when adding new vdevs to an existing pool.
4859	 * If other threads start allocating from these vdevs before we
4860	 * sync the config cache, and we lose power, then upon reboot we may
4861	 * fail to open the pool because there are DVAs that the config cache
4862	 * can't translate.  Therefore, we first add the vdevs without
4863	 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
4864	 * and then let spa_config_update() initialize the new metaslabs.
4865	 *
4866	 * spa_load() checks for added-but-not-initialized vdevs, so that
4867	 * if we lose power at any point in this sequence, the remaining
4868	 * steps will be completed the next time we load the pool.
4869	 */
4870	(void) spa_vdev_exit(spa, vd, txg, 0);
4871
4872	mutex_enter(&spa_namespace_lock);
4873	spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
4874	spa_event_notify(spa, NULL, ESC_ZFS_VDEV_ADD);
4875	mutex_exit(&spa_namespace_lock);
4876
4877	return (0);
4878}
4879
4880/*
4881 * Attach a device to a mirror.  The arguments are the path to any device
4882 * in the mirror, and the nvroot for the new device.  If the path specifies
4883 * a device that is not mirrored, we automatically insert the mirror vdev.
4884 *
4885 * If 'replacing' is specified, the new device is intended to replace the
4886 * existing device; in this case the two devices are made into their own
4887 * mirror using the 'replacing' vdev, which is functionally identical to
4888 * the mirror vdev (it actually reuses all the same ops) but has a few
4889 * extra rules: you can't attach to it after it's been created, and upon
4890 * completion of resilvering, the first disk (the one being replaced)
4891 * is automatically detached.
4892 */
4893int
4894spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
4895{
4896	uint64_t txg, dtl_max_txg;
4897	vdev_t *rvd = spa->spa_root_vdev;
4898	vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
4899	vdev_ops_t *pvops;
4900	char *oldvdpath, *newvdpath;
4901	int newvd_isspare;
4902	int error;
4903
4904	ASSERT(spa_writeable(spa));
4905
4906	txg = spa_vdev_enter(spa);
4907
4908	oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
4909
4910	if (oldvd == NULL)
4911		return (spa_vdev_exit(spa, NULL, txg, ENODEV));
4912
4913	if (!oldvd->vdev_ops->vdev_op_leaf)
4914		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
4915
4916	pvd = oldvd->vdev_parent;
4917
4918	if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
4919	    VDEV_ALLOC_ATTACH)) != 0)
4920		return (spa_vdev_exit(spa, NULL, txg, EINVAL));
4921
4922	if (newrootvd->vdev_children != 1)
4923		return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4924
4925	newvd = newrootvd->vdev_child[0];
4926
4927	if (!newvd->vdev_ops->vdev_op_leaf)
4928		return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
4929
4930	if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
4931		return (spa_vdev_exit(spa, newrootvd, txg, error));
4932
4933	/*
4934	 * Spares can't replace logs
4935	 */
4936	if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
4937		return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4938
4939	if (!replacing) {
4940		/*
4941		 * For attach, the only allowable parent is a mirror or the root
4942		 * vdev.
4943		 */
4944		if (pvd->vdev_ops != &vdev_mirror_ops &&
4945		    pvd->vdev_ops != &vdev_root_ops)
4946			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4947
4948		pvops = &vdev_mirror_ops;
4949	} else {
4950		/*
4951		 * Active hot spares can only be replaced by inactive hot
4952		 * spares.
4953		 */
4954		if (pvd->vdev_ops == &vdev_spare_ops &&
4955		    oldvd->vdev_isspare &&
4956		    !spa_has_spare(spa, newvd->vdev_guid))
4957			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4958
4959		/*
4960		 * If the source is a hot spare, and the parent isn't already a
4961		 * spare, then we want to create a new hot spare.  Otherwise, we
4962		 * want to create a replacing vdev.  The user is not allowed to
4963		 * attach to a spared vdev child unless the 'isspare' state is
4964		 * the same (spare replaces spare, non-spare replaces
4965		 * non-spare).
4966		 */
4967		if (pvd->vdev_ops == &vdev_replacing_ops &&
4968		    spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
4969			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4970		} else if (pvd->vdev_ops == &vdev_spare_ops &&
4971		    newvd->vdev_isspare != oldvd->vdev_isspare) {
4972			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
4973		}
4974
4975		if (newvd->vdev_isspare)
4976			pvops = &vdev_spare_ops;
4977		else
4978			pvops = &vdev_replacing_ops;
4979	}
4980
4981	/*
4982	 * Make sure the new device is big enough.
4983	 */
4984	if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
4985		return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
4986
4987	/*
4988	 * The new device cannot have a higher alignment requirement
4989	 * than the top-level vdev.
4990	 */
4991	if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
4992		return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
4993
4994	/*
4995	 * If this is an in-place replacement, update oldvd's path and devid
4996	 * to make it distinguishable from newvd, and unopenable from now on.
4997	 */
4998	if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
4999		spa_strfree(oldvd->vdev_path);
5000		oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
5001		    KM_SLEEP);
5002		(void) sprintf(oldvd->vdev_path, "%s/%s",
5003		    newvd->vdev_path, "old");
5004		if (oldvd->vdev_devid != NULL) {
5005			spa_strfree(oldvd->vdev_devid);
5006			oldvd->vdev_devid = NULL;
5007		}
5008	}
5009
5010	/* mark the device being resilvered */
5011	newvd->vdev_resilver_txg = txg;
5012
5013	/*
5014	 * If the parent is not a mirror, or if we're replacing, insert the new
5015	 * mirror/replacing/spare vdev above oldvd.
5016	 */
5017	if (pvd->vdev_ops != pvops)
5018		pvd = vdev_add_parent(oldvd, pvops);
5019
5020	ASSERT(pvd->vdev_top->vdev_parent == rvd);
5021	ASSERT(pvd->vdev_ops == pvops);
5022	ASSERT(oldvd->vdev_parent == pvd);
5023
5024	/*
5025	 * Extract the new device from its root and add it to pvd.
5026	 */
5027	vdev_remove_child(newrootvd, newvd);
5028	newvd->vdev_id = pvd->vdev_children;
5029	newvd->vdev_crtxg = oldvd->vdev_crtxg;
5030	vdev_add_child(pvd, newvd);
5031
5032	tvd = newvd->vdev_top;
5033	ASSERT(pvd->vdev_top == tvd);
5034	ASSERT(tvd->vdev_parent == rvd);
5035
5036	vdev_config_dirty(tvd);
5037
5038	/*
5039	 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
5040	 * for any dmu_sync-ed blocks.  It will propagate upward when
5041	 * spa_vdev_exit() calls vdev_dtl_reassess().
5042	 */
5043	dtl_max_txg = txg + TXG_CONCURRENT_STATES;
5044
5045	vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
5046	    dtl_max_txg - TXG_INITIAL);
5047
5048	if (newvd->vdev_isspare) {
5049		spa_spare_activate(newvd);
5050		spa_event_notify(spa, newvd, ESC_ZFS_VDEV_SPARE);
5051	}
5052
5053	oldvdpath = spa_strdup(oldvd->vdev_path);
5054	newvdpath = spa_strdup(newvd->vdev_path);
5055	newvd_isspare = newvd->vdev_isspare;
5056
5057	/*
5058	 * Mark newvd's DTL dirty in this txg.
5059	 */
5060	vdev_dirty(tvd, VDD_DTL, newvd, txg);
5061
5062	/*
5063	 * Schedule the resilver to restart in the future. We do this to
5064	 * ensure that dmu_sync-ed blocks have been stitched into the
5065	 * respective datasets.
5066	 */
5067	dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
5068
5069	if (spa->spa_bootfs)
5070		spa_event_notify(spa, newvd, ESC_ZFS_BOOTFS_VDEV_ATTACH);
5071
5072	spa_event_notify(spa, newvd, ESC_ZFS_VDEV_ATTACH);
5073
5074	/*
5075	 * Commit the config
5076	 */
5077	(void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
5078
5079	spa_history_log_internal(spa, "vdev attach", NULL,
5080	    "%s vdev=%s %s vdev=%s",
5081	    replacing && newvd_isspare ? "spare in" :
5082	    replacing ? "replace" : "attach", newvdpath,
5083	    replacing ? "for" : "to", oldvdpath);
5084
5085	spa_strfree(oldvdpath);
5086	spa_strfree(newvdpath);
5087
5088	return (0);
5089}
5090
5091/*
5092 * Detach a device from a mirror or replacing vdev.
5093 *
5094 * If 'replace_done' is specified, only detach if the parent
5095 * is a replacing vdev.
5096 */
5097int
5098spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
5099{
5100	uint64_t txg;
5101	int error;
5102	vdev_t *rvd = spa->spa_root_vdev;
5103	vdev_t *vd, *pvd, *cvd, *tvd;
5104	boolean_t unspare = B_FALSE;
5105	uint64_t unspare_guid = 0;
5106	char *vdpath;
5107
5108	ASSERT(spa_writeable(spa));
5109
5110	txg = spa_vdev_enter(spa);
5111
5112	vd = spa_lookup_by_guid(spa, guid, B_FALSE);
5113
5114	if (vd == NULL)
5115		return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5116
5117	if (!vd->vdev_ops->vdev_op_leaf)
5118		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5119
5120	pvd = vd->vdev_parent;
5121
5122	/*
5123	 * If the parent/child relationship is not as expected, don't do it.
5124	 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
5125	 * vdev that's replacing B with C.  The user's intent in replacing
5126	 * is to go from M(A,B) to M(A,C).  If the user decides to cancel
5127	 * the replace by detaching C, the expected behavior is to end up
5128	 * M(A,B).  But suppose that right after deciding to detach C,
5129	 * the replacement of B completes.  We would have M(A,C), and then
5130	 * ask to detach C, which would leave us with just A -- not what
5131	 * the user wanted.  To prevent this, we make sure that the
5132	 * parent/child relationship hasn't changed -- in this example,
5133	 * that C's parent is still the replacing vdev R.
5134	 */
5135	if (pvd->vdev_guid != pguid && pguid != 0)
5136		return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5137
5138	/*
5139	 * Only 'replacing' or 'spare' vdevs can be replaced.
5140	 */
5141	if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
5142	    pvd->vdev_ops != &vdev_spare_ops)
5143		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5144
5145	ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
5146	    spa_version(spa) >= SPA_VERSION_SPARES);
5147
5148	/*
5149	 * Only mirror, replacing, and spare vdevs support detach.
5150	 */
5151	if (pvd->vdev_ops != &vdev_replacing_ops &&
5152	    pvd->vdev_ops != &vdev_mirror_ops &&
5153	    pvd->vdev_ops != &vdev_spare_ops)
5154		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5155
5156	/*
5157	 * If this device has the only valid copy of some data,
5158	 * we cannot safely detach it.
5159	 */
5160	if (vdev_dtl_required(vd))
5161		return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5162
5163	ASSERT(pvd->vdev_children >= 2);
5164
5165	/*
5166	 * If we are detaching the second disk from a replacing vdev, then
5167	 * check to see if we changed the original vdev's path to have "/old"
5168	 * at the end in spa_vdev_attach().  If so, undo that change now.
5169	 */
5170	if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
5171	    vd->vdev_path != NULL) {
5172		size_t len = strlen(vd->vdev_path);
5173
5174		for (int c = 0; c < pvd->vdev_children; c++) {
5175			cvd = pvd->vdev_child[c];
5176
5177			if (cvd == vd || cvd->vdev_path == NULL)
5178				continue;
5179
5180			if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
5181			    strcmp(cvd->vdev_path + len, "/old") == 0) {
5182				spa_strfree(cvd->vdev_path);
5183				cvd->vdev_path = spa_strdup(vd->vdev_path);
5184				break;
5185			}
5186		}
5187	}
5188
5189	/*
5190	 * If we are detaching the original disk from a spare, then it implies
5191	 * that the spare should become a real disk, and be removed from the
5192	 * active spare list for the pool.
5193	 */
5194	if (pvd->vdev_ops == &vdev_spare_ops &&
5195	    vd->vdev_id == 0 &&
5196	    pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
5197		unspare = B_TRUE;
5198
5199	/*
5200	 * Erase the disk labels so the disk can be used for other things.
5201	 * This must be done after all other error cases are handled,
5202	 * but before we disembowel vd (so we can still do I/O to it).
5203	 * But if we can't do it, don't treat the error as fatal --
5204	 * it may be that the unwritability of the disk is the reason
5205	 * it's being detached!
5206	 */
5207	error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
5208
5209	/*
5210	 * Remove vd from its parent and compact the parent's children.
5211	 */
5212	vdev_remove_child(pvd, vd);
5213	vdev_compact_children(pvd);
5214
5215	/*
5216	 * Remember one of the remaining children so we can get tvd below.
5217	 */
5218	cvd = pvd->vdev_child[pvd->vdev_children - 1];
5219
5220	/*
5221	 * If we need to remove the remaining child from the list of hot spares,
5222	 * do it now, marking the vdev as no longer a spare in the process.
5223	 * We must do this before vdev_remove_parent(), because that can
5224	 * change the GUID if it creates a new toplevel GUID.  For a similar
5225	 * reason, we must remove the spare now, in the same txg as the detach;
5226	 * otherwise someone could attach a new sibling, change the GUID, and
5227	 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
5228	 */
5229	if (unspare) {
5230		ASSERT(cvd->vdev_isspare);
5231		spa_spare_remove(cvd);
5232		unspare_guid = cvd->vdev_guid;
5233		(void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
5234		cvd->vdev_unspare = B_TRUE;
5235	}
5236
5237	/*
5238	 * If the parent mirror/replacing vdev only has one child,
5239	 * the parent is no longer needed.  Remove it from the tree.
5240	 */
5241	if (pvd->vdev_children == 1) {
5242		if (pvd->vdev_ops == &vdev_spare_ops)
5243			cvd->vdev_unspare = B_FALSE;
5244		vdev_remove_parent(cvd);
5245	}
5246
5247
5248	/*
5249	 * We don't set tvd until now because the parent we just removed
5250	 * may have been the previous top-level vdev.
5251	 */
5252	tvd = cvd->vdev_top;
5253	ASSERT(tvd->vdev_parent == rvd);
5254
5255	/*
5256	 * Reevaluate the parent vdev state.
5257	 */
5258	vdev_propagate_state(cvd);
5259
5260	/*
5261	 * If the 'autoexpand' property is set on the pool then automatically
5262	 * try to expand the size of the pool. For example if the device we
5263	 * just detached was smaller than the others, it may be possible to
5264	 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
5265	 * first so that we can obtain the updated sizes of the leaf vdevs.
5266	 */
5267	if (spa->spa_autoexpand) {
5268		vdev_reopen(tvd);
5269		vdev_expand(tvd, txg);
5270	}
5271
5272	vdev_config_dirty(tvd);
5273
5274	/*
5275	 * Mark vd's DTL as dirty in this txg.  vdev_dtl_sync() will see that
5276	 * vd->vdev_detached is set and free vd's DTL object in syncing context.
5277	 * But first make sure we're not on any *other* txg's DTL list, to
5278	 * prevent vd from being accessed after it's freed.
5279	 */
5280	vdpath = spa_strdup(vd->vdev_path);
5281	for (int t = 0; t < TXG_SIZE; t++)
5282		(void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
5283	vd->vdev_detached = B_TRUE;
5284	vdev_dirty(tvd, VDD_DTL, vd, txg);
5285
5286	spa_event_notify(spa, vd, ESC_ZFS_VDEV_REMOVE);
5287
5288	/* hang on to the spa before we release the lock */
5289	spa_open_ref(spa, FTAG);
5290
5291	error = spa_vdev_exit(spa, vd, txg, 0);
5292
5293	spa_history_log_internal(spa, "detach", NULL,
5294	    "vdev=%s", vdpath);
5295	spa_strfree(vdpath);
5296
5297	/*
5298	 * If this was the removal of the original device in a hot spare vdev,
5299	 * then we want to go through and remove the device from the hot spare
5300	 * list of every other pool.
5301	 */
5302	if (unspare) {
5303		spa_t *altspa = NULL;
5304
5305		mutex_enter(&spa_namespace_lock);
5306		while ((altspa = spa_next(altspa)) != NULL) {
5307			if (altspa->spa_state != POOL_STATE_ACTIVE ||
5308			    altspa == spa)
5309				continue;
5310
5311			spa_open_ref(altspa, FTAG);
5312			mutex_exit(&spa_namespace_lock);
5313			(void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
5314			mutex_enter(&spa_namespace_lock);
5315			spa_close(altspa, FTAG);
5316		}
5317		mutex_exit(&spa_namespace_lock);
5318
5319		/* search the rest of the vdevs for spares to remove */
5320		spa_vdev_resilver_done(spa);
5321	}
5322
5323	/* all done with the spa; OK to release */
5324	mutex_enter(&spa_namespace_lock);
5325	spa_close(spa, FTAG);
5326	mutex_exit(&spa_namespace_lock);
5327
5328	return (error);
5329}
5330
5331/*
5332 * Split a set of devices from their mirrors, and create a new pool from them.
5333 */
5334int
5335spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
5336    nvlist_t *props, boolean_t exp)
5337{
5338	int error = 0;
5339	uint64_t txg, *glist;
5340	spa_t *newspa;
5341	uint_t c, children, lastlog;
5342	nvlist_t **child, *nvl, *tmp;
5343	dmu_tx_t *tx;
5344	char *altroot = NULL;
5345	vdev_t *rvd, **vml = NULL;			/* vdev modify list */
5346	boolean_t activate_slog;
5347
5348	ASSERT(spa_writeable(spa));
5349
5350	txg = spa_vdev_enter(spa);
5351
5352	/* clear the log and flush everything up to now */
5353	activate_slog = spa_passivate_log(spa);
5354	(void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5355	error = spa_offline_log(spa);
5356	txg = spa_vdev_config_enter(spa);
5357
5358	if (activate_slog)
5359		spa_activate_log(spa);
5360
5361	if (error != 0)
5362		return (spa_vdev_exit(spa, NULL, txg, error));
5363
5364	/* check new spa name before going any further */
5365	if (spa_lookup(newname) != NULL)
5366		return (spa_vdev_exit(spa, NULL, txg, EEXIST));
5367
5368	/*
5369	 * scan through all the children to ensure they're all mirrors
5370	 */
5371	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
5372	    nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
5373	    &children) != 0)
5374		return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5375
5376	/* first, check to ensure we've got the right child count */
5377	rvd = spa->spa_root_vdev;
5378	lastlog = 0;
5379	for (c = 0; c < rvd->vdev_children; c++) {
5380		vdev_t *vd = rvd->vdev_child[c];
5381
5382		/* don't count the holes & logs as children */
5383		if (vd->vdev_islog || vd->vdev_ishole) {
5384			if (lastlog == 0)
5385				lastlog = c;
5386			continue;
5387		}
5388
5389		lastlog = 0;
5390	}
5391	if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
5392		return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5393
5394	/* next, ensure no spare or cache devices are part of the split */
5395	if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
5396	    nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
5397		return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5398
5399	vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
5400	glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
5401
5402	/* then, loop over each vdev and validate it */
5403	for (c = 0; c < children; c++) {
5404		uint64_t is_hole = 0;
5405
5406		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
5407		    &is_hole);
5408
5409		if (is_hole != 0) {
5410			if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
5411			    spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
5412				continue;
5413			} else {
5414				error = SET_ERROR(EINVAL);
5415				break;
5416			}
5417		}
5418
5419		/* which disk is going to be split? */
5420		if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
5421		    &glist[c]) != 0) {
5422			error = SET_ERROR(EINVAL);
5423			break;
5424		}
5425
5426		/* look it up in the spa */
5427		vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
5428		if (vml[c] == NULL) {
5429			error = SET_ERROR(ENODEV);
5430			break;
5431		}
5432
5433		/* make sure there's nothing stopping the split */
5434		if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
5435		    vml[c]->vdev_islog ||
5436		    vml[c]->vdev_ishole ||
5437		    vml[c]->vdev_isspare ||
5438		    vml[c]->vdev_isl2cache ||
5439		    !vdev_writeable(vml[c]) ||
5440		    vml[c]->vdev_children != 0 ||
5441		    vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
5442		    c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
5443			error = SET_ERROR(EINVAL);
5444			break;
5445		}
5446
5447		if (vdev_dtl_required(vml[c])) {
5448			error = SET_ERROR(EBUSY);
5449			break;
5450		}
5451
5452		/* we need certain info from the top level */
5453		VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
5454		    vml[c]->vdev_top->vdev_ms_array) == 0);
5455		VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
5456		    vml[c]->vdev_top->vdev_ms_shift) == 0);
5457		VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
5458		    vml[c]->vdev_top->vdev_asize) == 0);
5459		VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
5460		    vml[c]->vdev_top->vdev_ashift) == 0);
5461
5462		/* transfer per-vdev ZAPs */
5463		ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
5464		VERIFY0(nvlist_add_uint64(child[c],
5465		    ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
5466
5467		ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
5468		VERIFY0(nvlist_add_uint64(child[c],
5469		    ZPOOL_CONFIG_VDEV_TOP_ZAP,
5470		    vml[c]->vdev_parent->vdev_top_zap));
5471	}
5472
5473	if (error != 0) {
5474		kmem_free(vml, children * sizeof (vdev_t *));
5475		kmem_free(glist, children * sizeof (uint64_t));
5476		return (spa_vdev_exit(spa, NULL, txg, error));
5477	}
5478
5479	/* stop writers from using the disks */
5480	for (c = 0; c < children; c++) {
5481		if (vml[c] != NULL)
5482			vml[c]->vdev_offline = B_TRUE;
5483	}
5484	vdev_reopen(spa->spa_root_vdev);
5485
5486	/*
5487	 * Temporarily record the splitting vdevs in the spa config.  This
5488	 * will disappear once the config is regenerated.
5489	 */
5490	VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5491	VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
5492	    glist, children) == 0);
5493	kmem_free(glist, children * sizeof (uint64_t));
5494
5495	mutex_enter(&spa->spa_props_lock);
5496	VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
5497	    nvl) == 0);
5498	mutex_exit(&spa->spa_props_lock);
5499	spa->spa_config_splitting = nvl;
5500	vdev_config_dirty(spa->spa_root_vdev);
5501
5502	/* configure and create the new pool */
5503	VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
5504	VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5505	    exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
5506	VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
5507	    spa_version(spa)) == 0);
5508	VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
5509	    spa->spa_config_txg) == 0);
5510	VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5511	    spa_generate_guid(NULL)) == 0);
5512	VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
5513	(void) nvlist_lookup_string(props,
5514	    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5515
5516	/* add the new pool to the namespace */
5517	newspa = spa_add(newname, config, altroot);
5518	newspa->spa_avz_action = AVZ_ACTION_REBUILD;
5519	newspa->spa_config_txg = spa->spa_config_txg;
5520	spa_set_log_state(newspa, SPA_LOG_CLEAR);
5521
5522	/* release the spa config lock, retaining the namespace lock */
5523	spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5524
5525	if (zio_injection_enabled)
5526		zio_handle_panic_injection(spa, FTAG, 1);
5527
5528	spa_activate(newspa, spa_mode_global);
5529	spa_async_suspend(newspa);
5530
5531#ifndef illumos
5532	/* mark that we are creating new spa by splitting */
5533	newspa->spa_splitting_newspa = B_TRUE;
5534#endif
5535	/* create the new pool from the disks of the original pool */
5536	error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE, B_TRUE);
5537#ifndef illumos
5538	newspa->spa_splitting_newspa = B_FALSE;
5539#endif
5540	if (error)
5541		goto out;
5542
5543	/* if that worked, generate a real config for the new pool */
5544	if (newspa->spa_root_vdev != NULL) {
5545		VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
5546		    NV_UNIQUE_NAME, KM_SLEEP) == 0);
5547		VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
5548		    ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
5549		spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
5550		    B_TRUE));
5551	}
5552
5553	/* set the props */
5554	if (props != NULL) {
5555		spa_configfile_set(newspa, props, B_FALSE);
5556		error = spa_prop_set(newspa, props);
5557		if (error)
5558			goto out;
5559	}
5560
5561	/* flush everything */
5562	txg = spa_vdev_config_enter(newspa);
5563	vdev_config_dirty(newspa->spa_root_vdev);
5564	(void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
5565
5566	if (zio_injection_enabled)
5567		zio_handle_panic_injection(spa, FTAG, 2);
5568
5569	spa_async_resume(newspa);
5570
5571	/* finally, update the original pool's config */
5572	txg = spa_vdev_config_enter(spa);
5573	tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
5574	error = dmu_tx_assign(tx, TXG_WAIT);
5575	if (error != 0)
5576		dmu_tx_abort(tx);
5577	for (c = 0; c < children; c++) {
5578		if (vml[c] != NULL) {
5579			vdev_split(vml[c]);
5580			if (error == 0)
5581				spa_history_log_internal(spa, "detach", tx,
5582				    "vdev=%s", vml[c]->vdev_path);
5583
5584			vdev_free(vml[c]);
5585		}
5586	}
5587	spa->spa_avz_action = AVZ_ACTION_REBUILD;
5588	vdev_config_dirty(spa->spa_root_vdev);
5589	spa->spa_config_splitting = NULL;
5590	nvlist_free(nvl);
5591	if (error == 0)
5592		dmu_tx_commit(tx);
5593	(void) spa_vdev_exit(spa, NULL, txg, 0);
5594
5595	if (zio_injection_enabled)
5596		zio_handle_panic_injection(spa, FTAG, 3);
5597
5598	/* split is complete; log a history record */
5599	spa_history_log_internal(newspa, "split", NULL,
5600	    "from pool %s", spa_name(spa));
5601
5602	kmem_free(vml, children * sizeof (vdev_t *));
5603
5604	/* if we're not going to mount the filesystems in userland, export */
5605	if (exp)
5606		error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
5607		    B_FALSE, B_FALSE);
5608
5609	return (error);
5610
5611out:
5612	spa_unload(newspa);
5613	spa_deactivate(newspa);
5614	spa_remove(newspa);
5615
5616	txg = spa_vdev_config_enter(spa);
5617
5618	/* re-online all offlined disks */
5619	for (c = 0; c < children; c++) {
5620		if (vml[c] != NULL)
5621			vml[c]->vdev_offline = B_FALSE;
5622	}
5623	vdev_reopen(spa->spa_root_vdev);
5624
5625	nvlist_free(spa->spa_config_splitting);
5626	spa->spa_config_splitting = NULL;
5627	(void) spa_vdev_exit(spa, NULL, txg, error);
5628
5629	kmem_free(vml, children * sizeof (vdev_t *));
5630	return (error);
5631}
5632
5633static nvlist_t *
5634spa_nvlist_lookup_by_guid(nvlist_t **nvpp, int count, uint64_t target_guid)
5635{
5636	for (int i = 0; i < count; i++) {
5637		uint64_t guid;
5638
5639		VERIFY(nvlist_lookup_uint64(nvpp[i], ZPOOL_CONFIG_GUID,
5640		    &guid) == 0);
5641
5642		if (guid == target_guid)
5643			return (nvpp[i]);
5644	}
5645
5646	return (NULL);
5647}
5648
5649static void
5650spa_vdev_remove_aux(nvlist_t *config, char *name, nvlist_t **dev, int count,
5651    nvlist_t *dev_to_remove)
5652{
5653	nvlist_t **newdev = NULL;
5654
5655	if (count > 1)
5656		newdev = kmem_alloc((count - 1) * sizeof (void *), KM_SLEEP);
5657
5658	for (int i = 0, j = 0; i < count; i++) {
5659		if (dev[i] == dev_to_remove)
5660			continue;
5661		VERIFY(nvlist_dup(dev[i], &newdev[j++], KM_SLEEP) == 0);
5662	}
5663
5664	VERIFY(nvlist_remove(config, name, DATA_TYPE_NVLIST_ARRAY) == 0);
5665	VERIFY(nvlist_add_nvlist_array(config, name, newdev, count - 1) == 0);
5666
5667	for (int i = 0; i < count - 1; i++)
5668		nvlist_free(newdev[i]);
5669
5670	if (count > 1)
5671		kmem_free(newdev, (count - 1) * sizeof (void *));
5672}
5673
5674/*
5675 * Evacuate the device.
5676 */
5677static int
5678spa_vdev_remove_evacuate(spa_t *spa, vdev_t *vd)
5679{
5680	uint64_t txg;
5681	int error = 0;
5682
5683	ASSERT(MUTEX_HELD(&spa_namespace_lock));
5684	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5685	ASSERT(vd == vd->vdev_top);
5686
5687	/*
5688	 * Evacuate the device.  We don't hold the config lock as writer
5689	 * since we need to do I/O but we do keep the
5690	 * spa_namespace_lock held.  Once this completes the device
5691	 * should no longer have any blocks allocated on it.
5692	 */
5693	if (vd->vdev_islog) {
5694		if (vd->vdev_stat.vs_alloc != 0)
5695			error = spa_offline_log(spa);
5696	} else {
5697		error = SET_ERROR(ENOTSUP);
5698	}
5699
5700	if (error)
5701		return (error);
5702
5703	/*
5704	 * The evacuation succeeded.  Remove any remaining MOS metadata
5705	 * associated with this vdev, and wait for these changes to sync.
5706	 */
5707	ASSERT0(vd->vdev_stat.vs_alloc);
5708	txg = spa_vdev_config_enter(spa);
5709	vd->vdev_removing = B_TRUE;
5710	vdev_dirty_leaves(vd, VDD_DTL, txg);
5711	vdev_config_dirty(vd);
5712	spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5713
5714	return (0);
5715}
5716
5717/*
5718 * Complete the removal by cleaning up the namespace.
5719 */
5720static void
5721spa_vdev_remove_from_namespace(spa_t *spa, vdev_t *vd)
5722{
5723	vdev_t *rvd = spa->spa_root_vdev;
5724	uint64_t id = vd->vdev_id;
5725	boolean_t last_vdev = (id == (rvd->vdev_children - 1));
5726
5727	ASSERT(MUTEX_HELD(&spa_namespace_lock));
5728	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5729	ASSERT(vd == vd->vdev_top);
5730
5731	/*
5732	 * Only remove any devices which are empty.
5733	 */
5734	if (vd->vdev_stat.vs_alloc != 0)
5735		return;
5736
5737	(void) vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
5738
5739	if (list_link_active(&vd->vdev_state_dirty_node))
5740		vdev_state_clean(vd);
5741	if (list_link_active(&vd->vdev_config_dirty_node))
5742		vdev_config_clean(vd);
5743
5744	vdev_free(vd);
5745
5746	if (last_vdev) {
5747		vdev_compact_children(rvd);
5748	} else {
5749		vd = vdev_alloc_common(spa, id, 0, &vdev_hole_ops);
5750		vdev_add_child(rvd, vd);
5751	}
5752	vdev_config_dirty(rvd);
5753
5754	/*
5755	 * Reassess the health of our root vdev.
5756	 */
5757	vdev_reopen(rvd);
5758}
5759
5760/*
5761 * Remove a device from the pool -
5762 *
5763 * Removing a device from the vdev namespace requires several steps
5764 * and can take a significant amount of time.  As a result we use
5765 * the spa_vdev_config_[enter/exit] functions which allow us to
5766 * grab and release the spa_config_lock while still holding the namespace
5767 * lock.  During each step the configuration is synced out.
5768 *
5769 * Currently, this supports removing only hot spares, slogs, and level 2 ARC
5770 * devices.
5771 */
5772int
5773spa_vdev_remove(spa_t *spa, uint64_t guid, boolean_t unspare)
5774{
5775	vdev_t *vd;
5776	sysevent_t *ev = NULL;
5777	metaslab_group_t *mg;
5778	nvlist_t **spares, **l2cache, *nv;
5779	uint64_t txg = 0;
5780	uint_t nspares, nl2cache;
5781	int error = 0;
5782	boolean_t locked = MUTEX_HELD(&spa_namespace_lock);
5783
5784	ASSERT(spa_writeable(spa));
5785
5786	if (!locked)
5787		txg = spa_vdev_enter(spa);
5788
5789	vd = spa_lookup_by_guid(spa, guid, B_FALSE);
5790
5791	if (spa->spa_spares.sav_vdevs != NULL &&
5792	    nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
5793	    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0 &&
5794	    (nv = spa_nvlist_lookup_by_guid(spares, nspares, guid)) != NULL) {
5795		/*
5796		 * Only remove the hot spare if it's not currently in use
5797		 * in this pool.
5798		 */
5799		if (vd == NULL || unspare) {
5800			if (vd == NULL)
5801				vd = spa_lookup_by_guid(spa, guid, B_TRUE);
5802			ev = spa_event_create(spa, vd, ESC_ZFS_VDEV_REMOVE_AUX);
5803			spa_vdev_remove_aux(spa->spa_spares.sav_config,
5804			    ZPOOL_CONFIG_SPARES, spares, nspares, nv);
5805			spa_load_spares(spa);
5806			spa->spa_spares.sav_sync = B_TRUE;
5807		} else {
5808			error = SET_ERROR(EBUSY);
5809		}
5810	} else if (spa->spa_l2cache.sav_vdevs != NULL &&
5811	    nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
5812	    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0 &&
5813	    (nv = spa_nvlist_lookup_by_guid(l2cache, nl2cache, guid)) != NULL) {
5814		/*
5815		 * Cache devices can always be removed.
5816		 */
5817		vd = spa_lookup_by_guid(spa, guid, B_TRUE);
5818		ev = spa_event_create(spa, vd, ESC_ZFS_VDEV_REMOVE_AUX);
5819		spa_vdev_remove_aux(spa->spa_l2cache.sav_config,
5820		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache, nv);
5821		spa_load_l2cache(spa);
5822		spa->spa_l2cache.sav_sync = B_TRUE;
5823	} else if (vd != NULL && vd->vdev_islog) {
5824		ASSERT(!locked);
5825		ASSERT(vd == vd->vdev_top);
5826
5827		mg = vd->vdev_mg;
5828
5829		/*
5830		 * Stop allocating from this vdev.
5831		 */
5832		metaslab_group_passivate(mg);
5833
5834		/*
5835		 * Wait for the youngest allocations and frees to sync,
5836		 * and then wait for the deferral of those frees to finish.
5837		 */
5838		spa_vdev_config_exit(spa, NULL,
5839		    txg + TXG_CONCURRENT_STATES + TXG_DEFER_SIZE, 0, FTAG);
5840
5841		/*
5842		 * Attempt to evacuate the vdev.
5843		 */
5844		error = spa_vdev_remove_evacuate(spa, vd);
5845
5846		txg = spa_vdev_config_enter(spa);
5847
5848		/*
5849		 * If we couldn't evacuate the vdev, unwind.
5850		 */
5851		if (error) {
5852			metaslab_group_activate(mg);
5853			return (spa_vdev_exit(spa, NULL, txg, error));
5854		}
5855
5856		/*
5857		 * Clean up the vdev namespace.
5858		 */
5859		ev = spa_event_create(spa, vd, ESC_ZFS_VDEV_REMOVE_DEV);
5860		spa_vdev_remove_from_namespace(spa, vd);
5861
5862	} else if (vd != NULL) {
5863		/*
5864		 * Normal vdevs cannot be removed (yet).
5865		 */
5866		error = SET_ERROR(ENOTSUP);
5867	} else {
5868		/*
5869		 * There is no vdev of any kind with the specified guid.
5870		 */
5871		error = SET_ERROR(ENOENT);
5872	}
5873
5874	if (!locked)
5875		error = spa_vdev_exit(spa, NULL, txg, error);
5876
5877	if (ev)
5878		spa_event_post(ev);
5879
5880	return (error);
5881}
5882
5883/*
5884 * Find any device that's done replacing, or a vdev marked 'unspare' that's
5885 * currently spared, so we can detach it.
5886 */
5887static vdev_t *
5888spa_vdev_resilver_done_hunt(vdev_t *vd)
5889{
5890	vdev_t *newvd, *oldvd;
5891
5892	for (int c = 0; c < vd->vdev_children; c++) {
5893		oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
5894		if (oldvd != NULL)
5895			return (oldvd);
5896	}
5897
5898	/*
5899	 * Check for a completed replacement.  We always consider the first
5900	 * vdev in the list to be the oldest vdev, and the last one to be
5901	 * the newest (see spa_vdev_attach() for how that works).  In
5902	 * the case where the newest vdev is faulted, we will not automatically
5903	 * remove it after a resilver completes.  This is OK as it will require
5904	 * user intervention to determine which disk the admin wishes to keep.
5905	 */
5906	if (vd->vdev_ops == &vdev_replacing_ops) {
5907		ASSERT(vd->vdev_children > 1);
5908
5909		newvd = vd->vdev_child[vd->vdev_children - 1];
5910		oldvd = vd->vdev_child[0];
5911
5912		if (vdev_dtl_empty(newvd, DTL_MISSING) &&
5913		    vdev_dtl_empty(newvd, DTL_OUTAGE) &&
5914		    !vdev_dtl_required(oldvd))
5915			return (oldvd);
5916	}
5917
5918	/*
5919	 * Check for a completed resilver with the 'unspare' flag set.
5920	 */
5921	if (vd->vdev_ops == &vdev_spare_ops) {
5922		vdev_t *first = vd->vdev_child[0];
5923		vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
5924
5925		if (last->vdev_unspare) {
5926			oldvd = first;
5927			newvd = last;
5928		} else if (first->vdev_unspare) {
5929			oldvd = last;
5930			newvd = first;
5931		} else {
5932			oldvd = NULL;
5933		}
5934
5935		if (oldvd != NULL &&
5936		    vdev_dtl_empty(newvd, DTL_MISSING) &&
5937		    vdev_dtl_empty(newvd, DTL_OUTAGE) &&
5938		    !vdev_dtl_required(oldvd))
5939			return (oldvd);
5940
5941		/*
5942		 * If there are more than two spares attached to a disk,
5943		 * and those spares are not required, then we want to
5944		 * attempt to free them up now so that they can be used
5945		 * by other pools.  Once we're back down to a single
5946		 * disk+spare, we stop removing them.
5947		 */
5948		if (vd->vdev_children > 2) {
5949			newvd = vd->vdev_child[1];
5950
5951			if (newvd->vdev_isspare && last->vdev_isspare &&
5952			    vdev_dtl_empty(last, DTL_MISSING) &&
5953			    vdev_dtl_empty(last, DTL_OUTAGE) &&
5954			    !vdev_dtl_required(newvd))
5955				return (newvd);
5956		}
5957	}
5958
5959	return (NULL);
5960}
5961
5962static void
5963spa_vdev_resilver_done(spa_t *spa)
5964{
5965	vdev_t *vd, *pvd, *ppvd;
5966	uint64_t guid, sguid, pguid, ppguid;
5967
5968	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5969
5970	while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
5971		pvd = vd->vdev_parent;
5972		ppvd = pvd->vdev_parent;
5973		guid = vd->vdev_guid;
5974		pguid = pvd->vdev_guid;
5975		ppguid = ppvd->vdev_guid;
5976		sguid = 0;
5977		/*
5978		 * If we have just finished replacing a hot spared device, then
5979		 * we need to detach the parent's first child (the original hot
5980		 * spare) as well.
5981		 */
5982		if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
5983		    ppvd->vdev_children == 2) {
5984			ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
5985			sguid = ppvd->vdev_child[1]->vdev_guid;
5986		}
5987		ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
5988
5989		spa_config_exit(spa, SCL_ALL, FTAG);
5990		if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
5991			return;
5992		if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
5993			return;
5994		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5995	}
5996
5997	spa_config_exit(spa, SCL_ALL, FTAG);
5998}
5999
6000/*
6001 * Update the stored path or FRU for this vdev.
6002 */
6003int
6004spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
6005    boolean_t ispath)
6006{
6007	vdev_t *vd;
6008	boolean_t sync = B_FALSE;
6009
6010	ASSERT(spa_writeable(spa));
6011
6012	spa_vdev_state_enter(spa, SCL_ALL);
6013
6014	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
6015		return (spa_vdev_state_exit(spa, NULL, ENOENT));
6016
6017	if (!vd->vdev_ops->vdev_op_leaf)
6018		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
6019
6020	if (ispath) {
6021		if (strcmp(value, vd->vdev_path) != 0) {
6022			spa_strfree(vd->vdev_path);
6023			vd->vdev_path = spa_strdup(value);
6024			sync = B_TRUE;
6025		}
6026	} else {
6027		if (vd->vdev_fru == NULL) {
6028			vd->vdev_fru = spa_strdup(value);
6029			sync = B_TRUE;
6030		} else if (strcmp(value, vd->vdev_fru) != 0) {
6031			spa_strfree(vd->vdev_fru);
6032			vd->vdev_fru = spa_strdup(value);
6033			sync = B_TRUE;
6034		}
6035	}
6036
6037	return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
6038}
6039
6040int
6041spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
6042{
6043	return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
6044}
6045
6046int
6047spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
6048{
6049	return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
6050}
6051
6052/*
6053 * ==========================================================================
6054 * SPA Scanning
6055 * ==========================================================================
6056 */
6057int
6058spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
6059{
6060	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6061
6062	if (dsl_scan_resilvering(spa->spa_dsl_pool))
6063		return (SET_ERROR(EBUSY));
6064
6065	return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
6066}
6067
6068int
6069spa_scan_stop(spa_t *spa)
6070{
6071	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6072	if (dsl_scan_resilvering(spa->spa_dsl_pool))
6073		return (SET_ERROR(EBUSY));
6074	return (dsl_scan_cancel(spa->spa_dsl_pool));
6075}
6076
6077int
6078spa_scan(spa_t *spa, pool_scan_func_t func)
6079{
6080	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6081
6082	if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
6083		return (SET_ERROR(ENOTSUP));
6084
6085	/*
6086	 * If a resilver was requested, but there is no DTL on a
6087	 * writeable leaf device, we have nothing to do.
6088	 */
6089	if (func == POOL_SCAN_RESILVER &&
6090	    !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
6091		spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
6092		return (0);
6093	}
6094
6095	return (dsl_scan(spa->spa_dsl_pool, func));
6096}
6097
6098/*
6099 * ==========================================================================
6100 * SPA async task processing
6101 * ==========================================================================
6102 */
6103
6104static void
6105spa_async_remove(spa_t *spa, vdev_t *vd)
6106{
6107	if (vd->vdev_remove_wanted) {
6108		vd->vdev_remove_wanted = B_FALSE;
6109		vd->vdev_delayed_close = B_FALSE;
6110		vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
6111
6112		/*
6113		 * We want to clear the stats, but we don't want to do a full
6114		 * vdev_clear() as that will cause us to throw away
6115		 * degraded/faulted state as well as attempt to reopen the
6116		 * device, all of which is a waste.
6117		 */
6118		vd->vdev_stat.vs_read_errors = 0;
6119		vd->vdev_stat.vs_write_errors = 0;
6120		vd->vdev_stat.vs_checksum_errors = 0;
6121
6122		vdev_state_dirty(vd->vdev_top);
6123		/* Tell userspace that the vdev is gone. */
6124		zfs_post_remove(spa, vd);
6125	}
6126
6127	for (int c = 0; c < vd->vdev_children; c++)
6128		spa_async_remove(spa, vd->vdev_child[c]);
6129}
6130
6131static void
6132spa_async_probe(spa_t *spa, vdev_t *vd)
6133{
6134	if (vd->vdev_probe_wanted) {
6135		vd->vdev_probe_wanted = B_FALSE;
6136		vdev_reopen(vd);	/* vdev_open() does the actual probe */
6137	}
6138
6139	for (int c = 0; c < vd->vdev_children; c++)
6140		spa_async_probe(spa, vd->vdev_child[c]);
6141}
6142
6143static void
6144spa_async_autoexpand(spa_t *spa, vdev_t *vd)
6145{
6146	sysevent_id_t eid;
6147	nvlist_t *attr;
6148	char *physpath;
6149
6150	if (!spa->spa_autoexpand)
6151		return;
6152
6153	for (int c = 0; c < vd->vdev_children; c++) {
6154		vdev_t *cvd = vd->vdev_child[c];
6155		spa_async_autoexpand(spa, cvd);
6156	}
6157
6158	if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
6159		return;
6160
6161	physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
6162	(void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
6163
6164	VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6165	VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
6166
6167	(void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
6168	    ESC_ZFS_VDEV_AUTOEXPAND, attr, &eid, DDI_SLEEP);
6169
6170	nvlist_free(attr);
6171	kmem_free(physpath, MAXPATHLEN);
6172}
6173
6174static void
6175spa_async_thread(void *arg)
6176{
6177	spa_t *spa = arg;
6178	int tasks;
6179
6180	ASSERT(spa->spa_sync_on);
6181
6182	mutex_enter(&spa->spa_async_lock);
6183	tasks = spa->spa_async_tasks;
6184	spa->spa_async_tasks &= SPA_ASYNC_REMOVE;
6185	mutex_exit(&spa->spa_async_lock);
6186
6187	/*
6188	 * See if the config needs to be updated.
6189	 */
6190	if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
6191		uint64_t old_space, new_space;
6192
6193		mutex_enter(&spa_namespace_lock);
6194		old_space = metaslab_class_get_space(spa_normal_class(spa));
6195		spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
6196		new_space = metaslab_class_get_space(spa_normal_class(spa));
6197		mutex_exit(&spa_namespace_lock);
6198
6199		/*
6200		 * If the pool grew as a result of the config update,
6201		 * then log an internal history event.
6202		 */
6203		if (new_space != old_space) {
6204			spa_history_log_internal(spa, "vdev online", NULL,
6205			    "pool '%s' size: %llu(+%llu)",
6206			    spa_name(spa), new_space, new_space - old_space);
6207		}
6208	}
6209
6210	if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
6211		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6212		spa_async_autoexpand(spa, spa->spa_root_vdev);
6213		spa_config_exit(spa, SCL_CONFIG, FTAG);
6214	}
6215
6216	/*
6217	 * See if any devices need to be probed.
6218	 */
6219	if (tasks & SPA_ASYNC_PROBE) {
6220		spa_vdev_state_enter(spa, SCL_NONE);
6221		spa_async_probe(spa, spa->spa_root_vdev);
6222		(void) spa_vdev_state_exit(spa, NULL, 0);
6223	}
6224
6225	/*
6226	 * If any devices are done replacing, detach them.
6227	 */
6228	if (tasks & SPA_ASYNC_RESILVER_DONE)
6229		spa_vdev_resilver_done(spa);
6230
6231	/*
6232	 * Kick off a resilver.
6233	 */
6234	if (tasks & SPA_ASYNC_RESILVER)
6235		dsl_resilver_restart(spa->spa_dsl_pool, 0);
6236
6237	/*
6238	 * Let the world know that we're done.
6239	 */
6240	mutex_enter(&spa->spa_async_lock);
6241	spa->spa_async_thread = NULL;
6242	cv_broadcast(&spa->spa_async_cv);
6243	mutex_exit(&spa->spa_async_lock);
6244	thread_exit();
6245}
6246
6247static void
6248spa_async_thread_vd(void *arg)
6249{
6250	spa_t *spa = arg;
6251	int tasks;
6252
6253	ASSERT(spa->spa_sync_on);
6254
6255	mutex_enter(&spa->spa_async_lock);
6256	tasks = spa->spa_async_tasks;
6257retry:
6258	spa->spa_async_tasks &= ~SPA_ASYNC_REMOVE;
6259	mutex_exit(&spa->spa_async_lock);
6260
6261	/*
6262	 * See if any devices need to be marked REMOVED.
6263	 */
6264	if (tasks & SPA_ASYNC_REMOVE) {
6265		spa_vdev_state_enter(spa, SCL_NONE);
6266		spa_async_remove(spa, spa->spa_root_vdev);
6267		for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
6268			spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
6269		for (int i = 0; i < spa->spa_spares.sav_count; i++)
6270			spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
6271		(void) spa_vdev_state_exit(spa, NULL, 0);
6272	}
6273
6274	/*
6275	 * Let the world know that we're done.
6276	 */
6277	mutex_enter(&spa->spa_async_lock);
6278	tasks = spa->spa_async_tasks;
6279	if ((tasks & SPA_ASYNC_REMOVE) != 0)
6280		goto retry;
6281	spa->spa_async_thread_vd = NULL;
6282	cv_broadcast(&spa->spa_async_cv);
6283	mutex_exit(&spa->spa_async_lock);
6284	thread_exit();
6285}
6286
6287void
6288spa_async_suspend(spa_t *spa)
6289{
6290	mutex_enter(&spa->spa_async_lock);
6291	spa->spa_async_suspended++;
6292	while (spa->spa_async_thread != NULL &&
6293	    spa->spa_async_thread_vd != NULL)
6294		cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
6295	mutex_exit(&spa->spa_async_lock);
6296}
6297
6298void
6299spa_async_resume(spa_t *spa)
6300{
6301	mutex_enter(&spa->spa_async_lock);
6302	ASSERT(spa->spa_async_suspended != 0);
6303	spa->spa_async_suspended--;
6304	mutex_exit(&spa->spa_async_lock);
6305}
6306
6307static boolean_t
6308spa_async_tasks_pending(spa_t *spa)
6309{
6310	uint_t non_config_tasks;
6311	uint_t config_task;
6312	boolean_t config_task_suspended;
6313
6314	non_config_tasks = spa->spa_async_tasks & ~(SPA_ASYNC_CONFIG_UPDATE |
6315	    SPA_ASYNC_REMOVE);
6316	config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
6317	if (spa->spa_ccw_fail_time == 0) {
6318		config_task_suspended = B_FALSE;
6319	} else {
6320		config_task_suspended =
6321		    (gethrtime() - spa->spa_ccw_fail_time) <
6322		    (zfs_ccw_retry_interval * NANOSEC);
6323	}
6324
6325	return (non_config_tasks || (config_task && !config_task_suspended));
6326}
6327
6328static void
6329spa_async_dispatch(spa_t *spa)
6330{
6331	mutex_enter(&spa->spa_async_lock);
6332	if (spa_async_tasks_pending(spa) &&
6333	    !spa->spa_async_suspended &&
6334	    spa->spa_async_thread == NULL &&
6335	    rootdir != NULL)
6336		spa->spa_async_thread = thread_create(NULL, 0,
6337		    spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
6338	mutex_exit(&spa->spa_async_lock);
6339}
6340
6341static void
6342spa_async_dispatch_vd(spa_t *spa)
6343{
6344	mutex_enter(&spa->spa_async_lock);
6345	if ((spa->spa_async_tasks & SPA_ASYNC_REMOVE) != 0 &&
6346	    !spa->spa_async_suspended &&
6347	    spa->spa_async_thread_vd == NULL &&
6348	    rootdir != NULL)
6349		spa->spa_async_thread_vd = thread_create(NULL, 0,
6350		    spa_async_thread_vd, spa, 0, &p0, TS_RUN, maxclsyspri);
6351	mutex_exit(&spa->spa_async_lock);
6352}
6353
6354void
6355spa_async_request(spa_t *spa, int task)
6356{
6357	zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
6358	mutex_enter(&spa->spa_async_lock);
6359	spa->spa_async_tasks |= task;
6360	mutex_exit(&spa->spa_async_lock);
6361	spa_async_dispatch_vd(spa);
6362}
6363
6364/*
6365 * ==========================================================================
6366 * SPA syncing routines
6367 * ==========================================================================
6368 */
6369
6370static int
6371bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6372{
6373	bpobj_t *bpo = arg;
6374	bpobj_enqueue(bpo, bp, tx);
6375	return (0);
6376}
6377
6378static int
6379spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6380{
6381	zio_t *zio = arg;
6382
6383	zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
6384	    BP_GET_PSIZE(bp), zio->io_flags));
6385	return (0);
6386}
6387
6388/*
6389 * Note: this simple function is not inlined to make it easier to dtrace the
6390 * amount of time spent syncing frees.
6391 */
6392static void
6393spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
6394{
6395	zio_t *zio = zio_root(spa, NULL, NULL, 0);
6396	bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
6397	VERIFY(zio_wait(zio) == 0);
6398}
6399
6400/*
6401 * Note: this simple function is not inlined to make it easier to dtrace the
6402 * amount of time spent syncing deferred frees.
6403 */
6404static void
6405spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
6406{
6407	zio_t *zio = zio_root(spa, NULL, NULL, 0);
6408	VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
6409	    spa_free_sync_cb, zio, tx), ==, 0);
6410	VERIFY0(zio_wait(zio));
6411}
6412
6413
6414static void
6415spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
6416{
6417	char *packed = NULL;
6418	size_t bufsize;
6419	size_t nvsize = 0;
6420	dmu_buf_t *db;
6421
6422	VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
6423
6424	/*
6425	 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
6426	 * information.  This avoids the dmu_buf_will_dirty() path and
6427	 * saves us a pre-read to get data we don't actually care about.
6428	 */
6429	bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
6430	packed = kmem_alloc(bufsize, KM_SLEEP);
6431
6432	VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
6433	    KM_SLEEP) == 0);
6434	bzero(packed + nvsize, bufsize - nvsize);
6435
6436	dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
6437
6438	kmem_free(packed, bufsize);
6439
6440	VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
6441	dmu_buf_will_dirty(db, tx);
6442	*(uint64_t *)db->db_data = nvsize;
6443	dmu_buf_rele(db, FTAG);
6444}
6445
6446static void
6447spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
6448    const char *config, const char *entry)
6449{
6450	nvlist_t *nvroot;
6451	nvlist_t **list;
6452	int i;
6453
6454	if (!sav->sav_sync)
6455		return;
6456
6457	/*
6458	 * Update the MOS nvlist describing the list of available devices.
6459	 * spa_validate_aux() will have already made sure this nvlist is
6460	 * valid and the vdevs are labeled appropriately.
6461	 */
6462	if (sav->sav_object == 0) {
6463		sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
6464		    DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
6465		    sizeof (uint64_t), tx);
6466		VERIFY(zap_update(spa->spa_meta_objset,
6467		    DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
6468		    &sav->sav_object, tx) == 0);
6469	}
6470
6471	VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6472	if (sav->sav_count == 0) {
6473		VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
6474	} else {
6475		list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
6476		for (i = 0; i < sav->sav_count; i++)
6477			list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
6478			    B_FALSE, VDEV_CONFIG_L2CACHE);
6479		VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
6480		    sav->sav_count) == 0);
6481		for (i = 0; i < sav->sav_count; i++)
6482			nvlist_free(list[i]);
6483		kmem_free(list, sav->sav_count * sizeof (void *));
6484	}
6485
6486	spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
6487	nvlist_free(nvroot);
6488
6489	sav->sav_sync = B_FALSE;
6490}
6491
6492/*
6493 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
6494 * The all-vdev ZAP must be empty.
6495 */
6496static void
6497spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
6498{
6499	spa_t *spa = vd->vdev_spa;
6500	if (vd->vdev_top_zap != 0) {
6501		VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
6502		    vd->vdev_top_zap, tx));
6503	}
6504	if (vd->vdev_leaf_zap != 0) {
6505		VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
6506		    vd->vdev_leaf_zap, tx));
6507	}
6508	for (uint64_t i = 0; i < vd->vdev_children; i++) {
6509		spa_avz_build(vd->vdev_child[i], avz, tx);
6510	}
6511}
6512
6513static void
6514spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
6515{
6516	nvlist_t *config;
6517
6518	/*
6519	 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
6520	 * its config may not be dirty but we still need to build per-vdev ZAPs.
6521	 * Similarly, if the pool is being assembled (e.g. after a split), we
6522	 * need to rebuild the AVZ although the config may not be dirty.
6523	 */
6524	if (list_is_empty(&spa->spa_config_dirty_list) &&
6525	    spa->spa_avz_action == AVZ_ACTION_NONE)
6526		return;
6527
6528	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6529
6530	ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
6531	    spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
6532	    spa->spa_all_vdev_zaps != 0);
6533
6534	if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
6535		/* Make and build the new AVZ */
6536		uint64_t new_avz = zap_create(spa->spa_meta_objset,
6537		    DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
6538		spa_avz_build(spa->spa_root_vdev, new_avz, tx);
6539
6540		/* Diff old AVZ with new one */
6541		zap_cursor_t zc;
6542		zap_attribute_t za;
6543
6544		for (zap_cursor_init(&zc, spa->spa_meta_objset,
6545		    spa->spa_all_vdev_zaps);
6546		    zap_cursor_retrieve(&zc, &za) == 0;
6547		    zap_cursor_advance(&zc)) {
6548			uint64_t vdzap = za.za_first_integer;
6549			if (zap_lookup_int(spa->spa_meta_objset, new_avz,
6550			    vdzap) == ENOENT) {
6551				/*
6552				 * ZAP is listed in old AVZ but not in new one;
6553				 * destroy it
6554				 */
6555				VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
6556				    tx));
6557			}
6558		}
6559
6560		zap_cursor_fini(&zc);
6561
6562		/* Destroy the old AVZ */
6563		VERIFY0(zap_destroy(spa->spa_meta_objset,
6564		    spa->spa_all_vdev_zaps, tx));
6565
6566		/* Replace the old AVZ in the dir obj with the new one */
6567		VERIFY0(zap_update(spa->spa_meta_objset,
6568		    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
6569		    sizeof (new_avz), 1, &new_avz, tx));
6570
6571		spa->spa_all_vdev_zaps = new_avz;
6572	} else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
6573		zap_cursor_t zc;
6574		zap_attribute_t za;
6575
6576		/* Walk through the AVZ and destroy all listed ZAPs */
6577		for (zap_cursor_init(&zc, spa->spa_meta_objset,
6578		    spa->spa_all_vdev_zaps);
6579		    zap_cursor_retrieve(&zc, &za) == 0;
6580		    zap_cursor_advance(&zc)) {
6581			uint64_t zap = za.za_first_integer;
6582			VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
6583		}
6584
6585		zap_cursor_fini(&zc);
6586
6587		/* Destroy and unlink the AVZ itself */
6588		VERIFY0(zap_destroy(spa->spa_meta_objset,
6589		    spa->spa_all_vdev_zaps, tx));
6590		VERIFY0(zap_remove(spa->spa_meta_objset,
6591		    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
6592		spa->spa_all_vdev_zaps = 0;
6593	}
6594
6595	if (spa->spa_all_vdev_zaps == 0) {
6596		spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
6597		    DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
6598		    DMU_POOL_VDEV_ZAP_MAP, tx);
6599	}
6600	spa->spa_avz_action = AVZ_ACTION_NONE;
6601
6602	/* Create ZAPs for vdevs that don't have them. */
6603	vdev_construct_zaps(spa->spa_root_vdev, tx);
6604
6605	config = spa_config_generate(spa, spa->spa_root_vdev,
6606	    dmu_tx_get_txg(tx), B_FALSE);
6607
6608	/*
6609	 * If we're upgrading the spa version then make sure that
6610	 * the config object gets updated with the correct version.
6611	 */
6612	if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
6613		fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6614		    spa->spa_uberblock.ub_version);
6615
6616	spa_config_exit(spa, SCL_STATE, FTAG);
6617
6618	nvlist_free(spa->spa_config_syncing);
6619	spa->spa_config_syncing = config;
6620
6621	spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
6622}
6623
6624static void
6625spa_sync_version(void *arg, dmu_tx_t *tx)
6626{
6627	uint64_t *versionp = arg;
6628	uint64_t version = *versionp;
6629	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
6630
6631	/*
6632	 * Setting the version is special cased when first creating the pool.
6633	 */
6634	ASSERT(tx->tx_txg != TXG_INITIAL);
6635
6636	ASSERT(SPA_VERSION_IS_SUPPORTED(version));
6637	ASSERT(version >= spa_version(spa));
6638
6639	spa->spa_uberblock.ub_version = version;
6640	vdev_config_dirty(spa->spa_root_vdev);
6641	spa_history_log_internal(spa, "set", tx, "version=%lld", version);
6642}
6643
6644/*
6645 * Set zpool properties.
6646 */
6647static void
6648spa_sync_props(void *arg, dmu_tx_t *tx)
6649{
6650	nvlist_t *nvp = arg;
6651	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
6652	objset_t *mos = spa->spa_meta_objset;
6653	nvpair_t *elem = NULL;
6654
6655	mutex_enter(&spa->spa_props_lock);
6656
6657	while ((elem = nvlist_next_nvpair(nvp, elem))) {
6658		uint64_t intval;
6659		char *strval, *fname;
6660		zpool_prop_t prop;
6661		const char *propname;
6662		zprop_type_t proptype;
6663		spa_feature_t fid;
6664
6665		switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
6666		case ZPROP_INVAL:
6667			/*
6668			 * We checked this earlier in spa_prop_validate().
6669			 */
6670			ASSERT(zpool_prop_feature(nvpair_name(elem)));
6671
6672			fname = strchr(nvpair_name(elem), '@') + 1;
6673			VERIFY0(zfeature_lookup_name(fname, &fid));
6674
6675			spa_feature_enable(spa, fid, tx);
6676			spa_history_log_internal(spa, "set", tx,
6677			    "%s=enabled", nvpair_name(elem));
6678			break;
6679
6680		case ZPOOL_PROP_VERSION:
6681			intval = fnvpair_value_uint64(elem);
6682			/*
6683			 * The version is synced seperatly before other
6684			 * properties and should be correct by now.
6685			 */
6686			ASSERT3U(spa_version(spa), >=, intval);
6687			break;
6688
6689		case ZPOOL_PROP_ALTROOT:
6690			/*
6691			 * 'altroot' is a non-persistent property. It should
6692			 * have been set temporarily at creation or import time.
6693			 */
6694			ASSERT(spa->spa_root != NULL);
6695			break;
6696
6697		case ZPOOL_PROP_READONLY:
6698		case ZPOOL_PROP_CACHEFILE:
6699			/*
6700			 * 'readonly' and 'cachefile' are also non-persisitent
6701			 * properties.
6702			 */
6703			break;
6704		case ZPOOL_PROP_COMMENT:
6705			strval = fnvpair_value_string(elem);
6706			if (spa->spa_comment != NULL)
6707				spa_strfree(spa->spa_comment);
6708			spa->spa_comment = spa_strdup(strval);
6709			/*
6710			 * We need to dirty the configuration on all the vdevs
6711			 * so that their labels get updated.  It's unnecessary
6712			 * to do this for pool creation since the vdev's
6713			 * configuratoin has already been dirtied.
6714			 */
6715			if (tx->tx_txg != TXG_INITIAL)
6716				vdev_config_dirty(spa->spa_root_vdev);
6717			spa_history_log_internal(spa, "set", tx,
6718			    "%s=%s", nvpair_name(elem), strval);
6719			break;
6720		default:
6721			/*
6722			 * Set pool property values in the poolprops mos object.
6723			 */
6724			if (spa->spa_pool_props_object == 0) {
6725				spa->spa_pool_props_object =
6726				    zap_create_link(mos, DMU_OT_POOL_PROPS,
6727				    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
6728				    tx);
6729			}
6730
6731			/* normalize the property name */
6732			propname = zpool_prop_to_name(prop);
6733			proptype = zpool_prop_get_type(prop);
6734
6735			if (nvpair_type(elem) == DATA_TYPE_STRING) {
6736				ASSERT(proptype == PROP_TYPE_STRING);
6737				strval = fnvpair_value_string(elem);
6738				VERIFY0(zap_update(mos,
6739				    spa->spa_pool_props_object, propname,
6740				    1, strlen(strval) + 1, strval, tx));
6741				spa_history_log_internal(spa, "set", tx,
6742				    "%s=%s", nvpair_name(elem), strval);
6743			} else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
6744				intval = fnvpair_value_uint64(elem);
6745
6746				if (proptype == PROP_TYPE_INDEX) {
6747					const char *unused;
6748					VERIFY0(zpool_prop_index_to_string(
6749					    prop, intval, &unused));
6750				}
6751				VERIFY0(zap_update(mos,
6752				    spa->spa_pool_props_object, propname,
6753				    8, 1, &intval, tx));
6754				spa_history_log_internal(spa, "set", tx,
6755				    "%s=%lld", nvpair_name(elem), intval);
6756			} else {
6757				ASSERT(0); /* not allowed */
6758			}
6759
6760			switch (prop) {
6761			case ZPOOL_PROP_DELEGATION:
6762				spa->spa_delegation = intval;
6763				break;
6764			case ZPOOL_PROP_BOOTFS:
6765				spa->spa_bootfs = intval;
6766				break;
6767			case ZPOOL_PROP_FAILUREMODE:
6768				spa->spa_failmode = intval;
6769				break;
6770			case ZPOOL_PROP_AUTOEXPAND:
6771				spa->spa_autoexpand = intval;
6772				if (tx->tx_txg != TXG_INITIAL)
6773					spa_async_request(spa,
6774					    SPA_ASYNC_AUTOEXPAND);
6775				break;
6776			case ZPOOL_PROP_DEDUPDITTO:
6777				spa->spa_dedup_ditto = intval;
6778				break;
6779			default:
6780				break;
6781			}
6782		}
6783
6784	}
6785
6786	mutex_exit(&spa->spa_props_lock);
6787}
6788
6789/*
6790 * Perform one-time upgrade on-disk changes.  spa_version() does not
6791 * reflect the new version this txg, so there must be no changes this
6792 * txg to anything that the upgrade code depends on after it executes.
6793 * Therefore this must be called after dsl_pool_sync() does the sync
6794 * tasks.
6795 */
6796static void
6797spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
6798{
6799	dsl_pool_t *dp = spa->spa_dsl_pool;
6800
6801	ASSERT(spa->spa_sync_pass == 1);
6802
6803	rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
6804
6805	if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
6806	    spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
6807		dsl_pool_create_origin(dp, tx);
6808
6809		/* Keeping the origin open increases spa_minref */
6810		spa->spa_minref += 3;
6811	}
6812
6813	if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
6814	    spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
6815		dsl_pool_upgrade_clones(dp, tx);
6816	}
6817
6818	if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
6819	    spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
6820		dsl_pool_upgrade_dir_clones(dp, tx);
6821
6822		/* Keeping the freedir open increases spa_minref */
6823		spa->spa_minref += 3;
6824	}
6825
6826	if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
6827	    spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
6828		spa_feature_create_zap_objects(spa, tx);
6829	}
6830
6831	/*
6832	 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
6833	 * when possibility to use lz4 compression for metadata was added
6834	 * Old pools that have this feature enabled must be upgraded to have
6835	 * this feature active
6836	 */
6837	if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
6838		boolean_t lz4_en = spa_feature_is_enabled(spa,
6839		    SPA_FEATURE_LZ4_COMPRESS);
6840		boolean_t lz4_ac = spa_feature_is_active(spa,
6841		    SPA_FEATURE_LZ4_COMPRESS);
6842
6843		if (lz4_en && !lz4_ac)
6844			spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
6845	}
6846
6847	/*
6848	 * If we haven't written the salt, do so now.  Note that the
6849	 * feature may not be activated yet, but that's fine since
6850	 * the presence of this ZAP entry is backwards compatible.
6851	 */
6852	if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
6853	    DMU_POOL_CHECKSUM_SALT) == ENOENT) {
6854		VERIFY0(zap_add(spa->spa_meta_objset,
6855		    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
6856		    sizeof (spa->spa_cksum_salt.zcs_bytes),
6857		    spa->spa_cksum_salt.zcs_bytes, tx));
6858	}
6859
6860	rrw_exit(&dp->dp_config_rwlock, FTAG);
6861}
6862
6863/*
6864 * Sync the specified transaction group.  New blocks may be dirtied as
6865 * part of the process, so we iterate until it converges.
6866 */
6867void
6868spa_sync(spa_t *spa, uint64_t txg)
6869{
6870	dsl_pool_t *dp = spa->spa_dsl_pool;
6871	objset_t *mos = spa->spa_meta_objset;
6872	bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
6873	vdev_t *rvd = spa->spa_root_vdev;
6874	vdev_t *vd;
6875	dmu_tx_t *tx;
6876	int error;
6877	uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
6878	    zfs_vdev_queue_depth_pct / 100;
6879
6880	VERIFY(spa_writeable(spa));
6881
6882	/*
6883	 * Lock out configuration changes.
6884	 */
6885	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6886
6887	spa->spa_syncing_txg = txg;
6888	spa->spa_sync_pass = 0;
6889
6890	mutex_enter(&spa->spa_alloc_lock);
6891	VERIFY0(avl_numnodes(&spa->spa_alloc_tree));
6892	mutex_exit(&spa->spa_alloc_lock);
6893
6894	/*
6895	 * If there are any pending vdev state changes, convert them
6896	 * into config changes that go out with this transaction group.
6897	 */
6898	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6899	while (list_head(&spa->spa_state_dirty_list) != NULL) {
6900		/*
6901		 * We need the write lock here because, for aux vdevs,
6902		 * calling vdev_config_dirty() modifies sav_config.
6903		 * This is ugly and will become unnecessary when we
6904		 * eliminate the aux vdev wart by integrating all vdevs
6905		 * into the root vdev tree.
6906		 */
6907		spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6908		spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
6909		while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
6910			vdev_state_clean(vd);
6911			vdev_config_dirty(vd);
6912		}
6913		spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6914		spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6915	}
6916	spa_config_exit(spa, SCL_STATE, FTAG);
6917
6918	tx = dmu_tx_create_assigned(dp, txg);
6919
6920	spa->spa_sync_starttime = gethrtime();
6921#ifdef illumos
6922	VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
6923	    spa->spa_sync_starttime + spa->spa_deadman_synctime));
6924#else	/* !illumos */
6925#ifdef _KERNEL
6926	callout_schedule(&spa->spa_deadman_cycid,
6927	    hz * spa->spa_deadman_synctime / NANOSEC);
6928#endif
6929#endif	/* illumos */
6930
6931	/*
6932	 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
6933	 * set spa_deflate if we have no raid-z vdevs.
6934	 */
6935	if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
6936	    spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
6937		int i;
6938
6939		for (i = 0; i < rvd->vdev_children; i++) {
6940			vd = rvd->vdev_child[i];
6941			if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
6942				break;
6943		}
6944		if (i == rvd->vdev_children) {
6945			spa->spa_deflate = TRUE;
6946			VERIFY(0 == zap_add(spa->spa_meta_objset,
6947			    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
6948			    sizeof (uint64_t), 1, &spa->spa_deflate, tx));
6949		}
6950	}
6951
6952	/*
6953	 * Set the top-level vdev's max queue depth. Evaluate each
6954	 * top-level's async write queue depth in case it changed.
6955	 * The max queue depth will not change in the middle of syncing
6956	 * out this txg.
6957	 */
6958	uint64_t queue_depth_total = 0;
6959	for (int c = 0; c < rvd->vdev_children; c++) {
6960		vdev_t *tvd = rvd->vdev_child[c];
6961		metaslab_group_t *mg = tvd->vdev_mg;
6962
6963		if (mg == NULL || mg->mg_class != spa_normal_class(spa) ||
6964		    !metaslab_group_initialized(mg))
6965			continue;
6966
6967		/*
6968		 * It is safe to do a lock-free check here because only async
6969		 * allocations look at mg_max_alloc_queue_depth, and async
6970		 * allocations all happen from spa_sync().
6971		 */
6972		ASSERT0(refcount_count(&mg->mg_alloc_queue_depth));
6973		mg->mg_max_alloc_queue_depth = max_queue_depth;
6974		queue_depth_total += mg->mg_max_alloc_queue_depth;
6975	}
6976	metaslab_class_t *mc = spa_normal_class(spa);
6977	ASSERT0(refcount_count(&mc->mc_alloc_slots));
6978	mc->mc_alloc_max_slots = queue_depth_total;
6979	mc->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
6980
6981	ASSERT3U(mc->mc_alloc_max_slots, <=,
6982	    max_queue_depth * rvd->vdev_children);
6983
6984	/*
6985	 * Iterate to convergence.
6986	 */
6987	do {
6988		int pass = ++spa->spa_sync_pass;
6989
6990		spa_sync_config_object(spa, tx);
6991		spa_sync_aux_dev(spa, &spa->spa_spares, tx,
6992		    ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
6993		spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
6994		    ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
6995		spa_errlog_sync(spa, txg);
6996		dsl_pool_sync(dp, txg);
6997
6998		if (pass < zfs_sync_pass_deferred_free) {
6999			spa_sync_frees(spa, free_bpl, tx);
7000		} else {
7001			/*
7002			 * We can not defer frees in pass 1, because
7003			 * we sync the deferred frees later in pass 1.
7004			 */
7005			ASSERT3U(pass, >, 1);
7006			bplist_iterate(free_bpl, bpobj_enqueue_cb,
7007			    &spa->spa_deferred_bpobj, tx);
7008		}
7009
7010		ddt_sync(spa, txg);
7011		dsl_scan_sync(dp, tx);
7012
7013		while (vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
7014			vdev_sync(vd, txg);
7015
7016		if (pass == 1) {
7017			spa_sync_upgrades(spa, tx);
7018			ASSERT3U(txg, >=,
7019			    spa->spa_uberblock.ub_rootbp.blk_birth);
7020			/*
7021			 * Note: We need to check if the MOS is dirty
7022			 * because we could have marked the MOS dirty
7023			 * without updating the uberblock (e.g. if we
7024			 * have sync tasks but no dirty user data).  We
7025			 * need to check the uberblock's rootbp because
7026			 * it is updated if we have synced out dirty
7027			 * data (though in this case the MOS will most
7028			 * likely also be dirty due to second order
7029			 * effects, we don't want to rely on that here).
7030			 */
7031			if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
7032			    !dmu_objset_is_dirty(mos, txg)) {
7033				/*
7034				 * Nothing changed on the first pass,
7035				 * therefore this TXG is a no-op.  Avoid
7036				 * syncing deferred frees, so that we
7037				 * can keep this TXG as a no-op.
7038				 */
7039				ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
7040				    txg));
7041				ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
7042				ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
7043				break;
7044			}
7045			spa_sync_deferred_frees(spa, tx);
7046		}
7047
7048	} while (dmu_objset_is_dirty(mos, txg));
7049
7050	if (!list_is_empty(&spa->spa_config_dirty_list)) {
7051		/*
7052		 * Make sure that the number of ZAPs for all the vdevs matches
7053		 * the number of ZAPs in the per-vdev ZAP list. This only gets
7054		 * called if the config is dirty; otherwise there may be
7055		 * outstanding AVZ operations that weren't completed in
7056		 * spa_sync_config_object.
7057		 */
7058		uint64_t all_vdev_zap_entry_count;
7059		ASSERT0(zap_count(spa->spa_meta_objset,
7060		    spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
7061		ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
7062		    all_vdev_zap_entry_count);
7063	}
7064
7065	/*
7066	 * Rewrite the vdev configuration (which includes the uberblock)
7067	 * to commit the transaction group.
7068	 *
7069	 * If there are no dirty vdevs, we sync the uberblock to a few
7070	 * random top-level vdevs that are known to be visible in the
7071	 * config cache (see spa_vdev_add() for a complete description).
7072	 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
7073	 */
7074	for (;;) {
7075		/*
7076		 * We hold SCL_STATE to prevent vdev open/close/etc.
7077		 * while we're attempting to write the vdev labels.
7078		 */
7079		spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7080
7081		if (list_is_empty(&spa->spa_config_dirty_list)) {
7082			vdev_t *svd[SPA_DVAS_PER_BP];
7083			int svdcount = 0;
7084			int children = rvd->vdev_children;
7085			int c0 = spa_get_random(children);
7086
7087			for (int c = 0; c < children; c++) {
7088				vd = rvd->vdev_child[(c0 + c) % children];
7089				if (vd->vdev_ms_array == 0 || vd->vdev_islog)
7090					continue;
7091				svd[svdcount++] = vd;
7092				if (svdcount == SPA_DVAS_PER_BP)
7093					break;
7094			}
7095			error = vdev_config_sync(svd, svdcount, txg);
7096		} else {
7097			error = vdev_config_sync(rvd->vdev_child,
7098			    rvd->vdev_children, txg);
7099		}
7100
7101		if (error == 0)
7102			spa->spa_last_synced_guid = rvd->vdev_guid;
7103
7104		spa_config_exit(spa, SCL_STATE, FTAG);
7105
7106		if (error == 0)
7107			break;
7108		zio_suspend(spa, NULL);
7109		zio_resume_wait(spa);
7110	}
7111	dmu_tx_commit(tx);
7112
7113#ifdef illumos
7114	VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
7115#else	/* !illumos */
7116#ifdef _KERNEL
7117	callout_drain(&spa->spa_deadman_cycid);
7118#endif
7119#endif	/* illumos */
7120
7121	/*
7122	 * Clear the dirty config list.
7123	 */
7124	while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
7125		vdev_config_clean(vd);
7126
7127	/*
7128	 * Now that the new config has synced transactionally,
7129	 * let it become visible to the config cache.
7130	 */
7131	if (spa->spa_config_syncing != NULL) {
7132		spa_config_set(spa, spa->spa_config_syncing);
7133		spa->spa_config_txg = txg;
7134		spa->spa_config_syncing = NULL;
7135	}
7136
7137	dsl_pool_sync_done(dp, txg);
7138
7139	mutex_enter(&spa->spa_alloc_lock);
7140	VERIFY0(avl_numnodes(&spa->spa_alloc_tree));
7141	mutex_exit(&spa->spa_alloc_lock);
7142
7143	/*
7144	 * Update usable space statistics.
7145	 */
7146	while (vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
7147		vdev_sync_done(vd, txg);
7148
7149	spa_update_dspace(spa);
7150
7151	/*
7152	 * It had better be the case that we didn't dirty anything
7153	 * since vdev_config_sync().
7154	 */
7155	ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
7156	ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
7157	ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
7158
7159	spa->spa_sync_pass = 0;
7160
7161	/*
7162	 * Update the last synced uberblock here. We want to do this at
7163	 * the end of spa_sync() so that consumers of spa_last_synced_txg()
7164	 * will be guaranteed that all the processing associated with
7165	 * that txg has been completed.
7166	 */
7167	spa->spa_ubsync = spa->spa_uberblock;
7168	spa_config_exit(spa, SCL_CONFIG, FTAG);
7169
7170	spa_handle_ignored_writes(spa);
7171
7172	/*
7173	 * If any async tasks have been requested, kick them off.
7174	 */
7175	spa_async_dispatch(spa);
7176	spa_async_dispatch_vd(spa);
7177}
7178
7179/*
7180 * Sync all pools.  We don't want to hold the namespace lock across these
7181 * operations, so we take a reference on the spa_t and drop the lock during the
7182 * sync.
7183 */
7184void
7185spa_sync_allpools(void)
7186{
7187	spa_t *spa = NULL;
7188	mutex_enter(&spa_namespace_lock);
7189	while ((spa = spa_next(spa)) != NULL) {
7190		if (spa_state(spa) != POOL_STATE_ACTIVE ||
7191		    !spa_writeable(spa) || spa_suspended(spa))
7192			continue;
7193		spa_open_ref(spa, FTAG);
7194		mutex_exit(&spa_namespace_lock);
7195		txg_wait_synced(spa_get_dsl(spa), 0);
7196		mutex_enter(&spa_namespace_lock);
7197		spa_close(spa, FTAG);
7198	}
7199	mutex_exit(&spa_namespace_lock);
7200}
7201
7202/*
7203 * ==========================================================================
7204 * Miscellaneous routines
7205 * ==========================================================================
7206 */
7207
7208/*
7209 * Remove all pools in the system.
7210 */
7211void
7212spa_evict_all(void)
7213{
7214	spa_t *spa;
7215
7216	/*
7217	 * Remove all cached state.  All pools should be closed now,
7218	 * so every spa in the AVL tree should be unreferenced.
7219	 */
7220	mutex_enter(&spa_namespace_lock);
7221	while ((spa = spa_next(NULL)) != NULL) {
7222		/*
7223		 * Stop async tasks.  The async thread may need to detach
7224		 * a device that's been replaced, which requires grabbing
7225		 * spa_namespace_lock, so we must drop it here.
7226		 */
7227		spa_open_ref(spa, FTAG);
7228		mutex_exit(&spa_namespace_lock);
7229		spa_async_suspend(spa);
7230		mutex_enter(&spa_namespace_lock);
7231		spa_close(spa, FTAG);
7232
7233		if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
7234			spa_unload(spa);
7235			spa_deactivate(spa);
7236		}
7237		spa_remove(spa);
7238	}
7239	mutex_exit(&spa_namespace_lock);
7240}
7241
7242vdev_t *
7243spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
7244{
7245	vdev_t *vd;
7246	int i;
7247
7248	if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
7249		return (vd);
7250
7251	if (aux) {
7252		for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
7253			vd = spa->spa_l2cache.sav_vdevs[i];
7254			if (vd->vdev_guid == guid)
7255				return (vd);
7256		}
7257
7258		for (i = 0; i < spa->spa_spares.sav_count; i++) {
7259			vd = spa->spa_spares.sav_vdevs[i];
7260			if (vd->vdev_guid == guid)
7261				return (vd);
7262		}
7263	}
7264
7265	return (NULL);
7266}
7267
7268void
7269spa_upgrade(spa_t *spa, uint64_t version)
7270{
7271	ASSERT(spa_writeable(spa));
7272
7273	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7274
7275	/*
7276	 * This should only be called for a non-faulted pool, and since a
7277	 * future version would result in an unopenable pool, this shouldn't be
7278	 * possible.
7279	 */
7280	ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
7281	ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
7282
7283	spa->spa_uberblock.ub_version = version;
7284	vdev_config_dirty(spa->spa_root_vdev);
7285
7286	spa_config_exit(spa, SCL_ALL, FTAG);
7287
7288	txg_wait_synced(spa_get_dsl(spa), 0);
7289}
7290
7291boolean_t
7292spa_has_spare(spa_t *spa, uint64_t guid)
7293{
7294	int i;
7295	uint64_t spareguid;
7296	spa_aux_vdev_t *sav = &spa->spa_spares;
7297
7298	for (i = 0; i < sav->sav_count; i++)
7299		if (sav->sav_vdevs[i]->vdev_guid == guid)
7300			return (B_TRUE);
7301
7302	for (i = 0; i < sav->sav_npending; i++) {
7303		if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
7304		    &spareguid) == 0 && spareguid == guid)
7305			return (B_TRUE);
7306	}
7307
7308	return (B_FALSE);
7309}
7310
7311/*
7312 * Check if a pool has an active shared spare device.
7313 * Note: reference count of an active spare is 2, as a spare and as a replace
7314 */
7315static boolean_t
7316spa_has_active_shared_spare(spa_t *spa)
7317{
7318	int i, refcnt;
7319	uint64_t pool;
7320	spa_aux_vdev_t *sav = &spa->spa_spares;
7321
7322	for (i = 0; i < sav->sav_count; i++) {
7323		if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
7324		    &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
7325		    refcnt > 2)
7326			return (B_TRUE);
7327	}
7328
7329	return (B_FALSE);
7330}
7331
7332static sysevent_t *
7333spa_event_create(spa_t *spa, vdev_t *vd, const char *name)
7334{
7335	sysevent_t		*ev = NULL;
7336#ifdef _KERNEL
7337	sysevent_attr_list_t	*attr = NULL;
7338	sysevent_value_t	value;
7339
7340	ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
7341	    SE_SLEEP);
7342	ASSERT(ev != NULL);
7343
7344	value.value_type = SE_DATA_TYPE_STRING;
7345	value.value.sv_string = spa_name(spa);
7346	if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
7347		goto done;
7348
7349	value.value_type = SE_DATA_TYPE_UINT64;
7350	value.value.sv_uint64 = spa_guid(spa);
7351	if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
7352		goto done;
7353
7354	if (vd) {
7355		value.value_type = SE_DATA_TYPE_UINT64;
7356		value.value.sv_uint64 = vd->vdev_guid;
7357		if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
7358		    SE_SLEEP) != 0)
7359			goto done;
7360
7361		if (vd->vdev_path) {
7362			value.value_type = SE_DATA_TYPE_STRING;
7363			value.value.sv_string = vd->vdev_path;
7364			if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
7365			    &value, SE_SLEEP) != 0)
7366				goto done;
7367		}
7368	}
7369
7370	if (sysevent_attach_attributes(ev, attr) != 0)
7371		goto done;
7372	attr = NULL;
7373
7374done:
7375	if (attr)
7376		sysevent_free_attr(attr);
7377
7378#endif
7379	return (ev);
7380}
7381
7382static void
7383spa_event_post(sysevent_t *ev)
7384{
7385#ifdef _KERNEL
7386	sysevent_id_t		eid;
7387
7388	(void) log_sysevent(ev, SE_SLEEP, &eid);
7389	sysevent_free(ev);
7390#endif
7391}
7392
7393/*
7394 * Post a sysevent corresponding to the given event.  The 'name' must be one of
7395 * the event definitions in sys/sysevent/eventdefs.h.  The payload will be
7396 * filled in from the spa and (optionally) the vdev.  This doesn't do anything
7397 * in the userland libzpool, as we don't want consumers to misinterpret ztest
7398 * or zdb as real changes.
7399 */
7400void
7401spa_event_notify(spa_t *spa, vdev_t *vd, const char *name)
7402{
7403	spa_event_post(spa_event_create(spa, vd, name));
7404}
7405