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