spa.c revision 9740f25f0360eb7d9131fa15fabebf958bf19126
1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22/*
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2019 by Delphix. All rights reserved.
25 * Copyright (c) 2015, Nexenta Systems, Inc.  All rights reserved.
26 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27 * Copyright 2013 Saso Kiselkov. All rights reserved.
28 * Copyright (c) 2014 Integros [integros.com]
29 * Copyright 2016 Toomas Soome <tsoome@me.com>
30 * Copyright 2018 Joyent, Inc.
31 * Copyright (c) 2017, Intel Corporation.
32 * Copyright (c) 2017 Datto Inc.
33 * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
34 */
35
36/*
37 * SPA: Storage Pool Allocator
38 *
39 * This file contains all the routines used when modifying on-disk SPA state.
40 * This includes opening, importing, destroying, exporting a pool, and syncing a
41 * pool.
42 */
43
44#include <sys/zfs_context.h>
45#include <sys/fm/fs/zfs.h>
46#include <sys/spa_impl.h>
47#include <sys/zio.h>
48#include <sys/zio_checksum.h>
49#include <sys/dmu.h>
50#include <sys/dmu_tx.h>
51#include <sys/zap.h>
52#include <sys/zil.h>
53#include <sys/ddt.h>
54#include <sys/vdev_impl.h>
55#include <sys/vdev_removal.h>
56#include <sys/vdev_indirect_mapping.h>
57#include <sys/vdev_indirect_births.h>
58#include <sys/vdev_initialize.h>
59#include <sys/metaslab.h>
60#include <sys/metaslab_impl.h>
61#include <sys/mmp.h>
62#include <sys/uberblock_impl.h>
63#include <sys/txg.h>
64#include <sys/avl.h>
65#include <sys/bpobj.h>
66#include <sys/dmu_traverse.h>
67#include <sys/dmu_objset.h>
68#include <sys/unique.h>
69#include <sys/dsl_pool.h>
70#include <sys/dsl_dataset.h>
71#include <sys/dsl_dir.h>
72#include <sys/dsl_prop.h>
73#include <sys/dsl_synctask.h>
74#include <sys/fs/zfs.h>
75#include <sys/arc.h>
76#include <sys/callb.h>
77#include <sys/systeminfo.h>
78#include <sys/spa_boot.h>
79#include <sys/zfs_ioctl.h>
80#include <sys/dsl_scan.h>
81#include <sys/zfeature.h>
82#include <sys/dsl_destroy.h>
83#include <sys/abd.h>
84
85#ifdef	_KERNEL
86#include <sys/bootprops.h>
87#include <sys/callb.h>
88#include <sys/cpupart.h>
89#include <sys/pool.h>
90#include <sys/sysdc.h>
91#include <sys/zone.h>
92#endif	/* _KERNEL */
93
94#include "zfs_prop.h"
95#include "zfs_comutil.h"
96
97/*
98 * The interval, in seconds, at which failed configuration cache file writes
99 * should be retried.
100 */
101int zfs_ccw_retry_interval = 300;
102
103typedef enum zti_modes {
104	ZTI_MODE_FIXED,			/* value is # of threads (min 1) */
105	ZTI_MODE_BATCH,			/* cpu-intensive; value is ignored */
106	ZTI_MODE_NULL,			/* don't create a taskq */
107	ZTI_NMODES
108} zti_modes_t;
109
110#define	ZTI_P(n, q)	{ ZTI_MODE_FIXED, (n), (q) }
111#define	ZTI_BATCH	{ ZTI_MODE_BATCH, 0, 1 }
112#define	ZTI_NULL	{ ZTI_MODE_NULL, 0, 0 }
113
114#define	ZTI_N(n)	ZTI_P(n, 1)
115#define	ZTI_ONE		ZTI_N(1)
116
117typedef struct zio_taskq_info {
118	zti_modes_t zti_mode;
119	uint_t zti_value;
120	uint_t zti_count;
121} zio_taskq_info_t;
122
123static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
124	"issue", "issue_high", "intr", "intr_high"
125};
126
127/*
128 * This table defines the taskq settings for each ZFS I/O type. When
129 * initializing a pool, we use this table to create an appropriately sized
130 * taskq. Some operations are low volume and therefore have a small, static
131 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
132 * macros. Other operations process a large amount of data; the ZTI_BATCH
133 * macro causes us to create a taskq oriented for throughput. Some operations
134 * are so high frequency and short-lived that the taskq itself can become a a
135 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
136 * additional degree of parallelism specified by the number of threads per-
137 * taskq and the number of taskqs; when dispatching an event in this case, the
138 * particular taskq is chosen at random.
139 *
140 * The different taskq priorities are to handle the different contexts (issue
141 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
142 * need to be handled with minimum delay.
143 */
144const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
145	/* ISSUE	ISSUE_HIGH	INTR		INTR_HIGH */
146	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* NULL */
147	{ ZTI_N(8),	ZTI_NULL,	ZTI_P(12, 8),	ZTI_NULL }, /* READ */
148	{ ZTI_BATCH,	ZTI_N(5),	ZTI_N(8),	ZTI_N(5) }, /* WRITE */
149	{ ZTI_P(12, 8),	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* FREE */
150	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* CLAIM */
151	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* IOCTL */
152};
153
154static void spa_sync_version(void *arg, dmu_tx_t *tx);
155static void spa_sync_props(void *arg, dmu_tx_t *tx);
156static boolean_t spa_has_active_shared_spare(spa_t *spa);
157static int spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport);
158static void spa_vdev_resilver_done(spa_t *spa);
159
160uint_t		zio_taskq_batch_pct = 75;	/* 1 thread per cpu in pset */
161id_t		zio_taskq_psrset_bind = PS_NONE;
162boolean_t	zio_taskq_sysdc = B_TRUE;	/* use SDC scheduling class */
163uint_t		zio_taskq_basedc = 80;		/* base duty cycle */
164
165boolean_t	spa_create_process = B_TRUE;	/* no process ==> no sysdc */
166extern int	zfs_sync_pass_deferred_free;
167
168/*
169 * Report any spa_load_verify errors found, but do not fail spa_load.
170 * This is used by zdb to analyze non-idle pools.
171 */
172boolean_t	spa_load_verify_dryrun = B_FALSE;
173
174/*
175 * This (illegal) pool name is used when temporarily importing a spa_t in order
176 * to get the vdev stats associated with the imported devices.
177 */
178#define	TRYIMPORT_NAME	"$import"
179
180/*
181 * For debugging purposes: print out vdev tree during pool import.
182 */
183boolean_t	spa_load_print_vdev_tree = B_FALSE;
184
185/*
186 * A non-zero value for zfs_max_missing_tvds means that we allow importing
187 * pools with missing top-level vdevs. This is strictly intended for advanced
188 * pool recovery cases since missing data is almost inevitable. Pools with
189 * missing devices can only be imported read-only for safety reasons, and their
190 * fail-mode will be automatically set to "continue".
191 *
192 * With 1 missing vdev we should be able to import the pool and mount all
193 * datasets. User data that was not modified after the missing device has been
194 * added should be recoverable. This means that snapshots created prior to the
195 * addition of that device should be completely intact.
196 *
197 * With 2 missing vdevs, some datasets may fail to mount since there are
198 * dataset statistics that are stored as regular metadata. Some data might be
199 * recoverable if those vdevs were added recently.
200 *
201 * With 3 or more missing vdevs, the pool is severely damaged and MOS entries
202 * may be missing entirely. Chances of data recovery are very low. Note that
203 * there are also risks of performing an inadvertent rewind as we might be
204 * missing all the vdevs with the latest uberblocks.
205 */
206uint64_t	zfs_max_missing_tvds = 0;
207
208/*
209 * The parameters below are similar to zfs_max_missing_tvds but are only
210 * intended for a preliminary open of the pool with an untrusted config which
211 * might be incomplete or out-dated.
212 *
213 * We are more tolerant for pools opened from a cachefile since we could have
214 * an out-dated cachefile where a device removal was not registered.
215 * We could have set the limit arbitrarily high but in the case where devices
216 * are really missing we would want to return the proper error codes; we chose
217 * SPA_DVAS_PER_BP - 1 so that some copies of the MOS would still be available
218 * and we get a chance to retrieve the trusted config.
219 */
220uint64_t	zfs_max_missing_tvds_cachefile = SPA_DVAS_PER_BP - 1;
221
222/*
223 * In the case where config was assembled by scanning device paths (/dev/dsks
224 * by default) we are less tolerant since all the existing devices should have
225 * been detected and we want spa_load to return the right error codes.
226 */
227uint64_t	zfs_max_missing_tvds_scan = 0;
228
229/*
230 * Debugging aid that pauses spa_sync() towards the end.
231 */
232boolean_t	zfs_pause_spa_sync = B_FALSE;
233
234/*
235 * ==========================================================================
236 * SPA properties routines
237 * ==========================================================================
238 */
239
240/*
241 * Add a (source=src, propname=propval) list to an nvlist.
242 */
243static void
244spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
245    uint64_t intval, zprop_source_t src)
246{
247	const char *propname = zpool_prop_to_name(prop);
248	nvlist_t *propval;
249
250	VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
251	VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
252
253	if (strval != NULL)
254		VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
255	else
256		VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
257
258	VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
259	nvlist_free(propval);
260}
261
262/*
263 * Get property values from the spa configuration.
264 */
265static void
266spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
267{
268	vdev_t *rvd = spa->spa_root_vdev;
269	dsl_pool_t *pool = spa->spa_dsl_pool;
270	uint64_t size, alloc, cap, version;
271	zprop_source_t src = ZPROP_SRC_NONE;
272	spa_config_dirent_t *dp;
273	metaslab_class_t *mc = spa_normal_class(spa);
274
275	ASSERT(MUTEX_HELD(&spa->spa_props_lock));
276
277	if (rvd != NULL) {
278		alloc = metaslab_class_get_alloc(mc);
279		alloc += metaslab_class_get_alloc(spa_special_class(spa));
280		alloc += metaslab_class_get_alloc(spa_dedup_class(spa));
281
282		size = metaslab_class_get_space(mc);
283		size += metaslab_class_get_space(spa_special_class(spa));
284		size += metaslab_class_get_space(spa_dedup_class(spa));
285
286		spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
287		spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
288		spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
289		spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
290		    size - alloc, src);
291		spa_prop_add_list(*nvp, ZPOOL_PROP_CHECKPOINT, NULL,
292		    spa->spa_checkpoint_info.sci_dspace, src);
293
294		spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
295		    metaslab_class_fragmentation(mc), src);
296		spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
297		    metaslab_class_expandable_space(mc), src);
298		spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
299		    (spa_mode(spa) == FREAD), src);
300
301		cap = (size == 0) ? 0 : (alloc * 100 / size);
302		spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
303
304		spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
305		    ddt_get_pool_dedup_ratio(spa), src);
306
307		spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
308		    rvd->vdev_state, src);
309
310		version = spa_version(spa);
311		if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
312			src = ZPROP_SRC_DEFAULT;
313		else
314			src = ZPROP_SRC_LOCAL;
315		spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
316	}
317
318	if (pool != NULL) {
319		/*
320		 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
321		 * when opening pools before this version freedir will be NULL.
322		 */
323		if (pool->dp_free_dir != NULL) {
324			spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
325			    dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
326			    src);
327		} else {
328			spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
329			    NULL, 0, src);
330		}
331
332		if (pool->dp_leak_dir != NULL) {
333			spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
334			    dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
335			    src);
336		} else {
337			spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
338			    NULL, 0, src);
339		}
340	}
341
342	spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
343
344	if (spa->spa_comment != NULL) {
345		spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
346		    0, ZPROP_SRC_LOCAL);
347	}
348
349	if (spa->spa_root != NULL)
350		spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
351		    0, ZPROP_SRC_LOCAL);
352
353	if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
354		spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
355		    MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
356	} else {
357		spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
358		    SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
359	}
360
361	if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE)) {
362		spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
363		    DNODE_MAX_SIZE, ZPROP_SRC_NONE);
364	} else {
365		spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
366		    DNODE_MIN_SIZE, ZPROP_SRC_NONE);
367	}
368
369	if ((dp = list_head(&spa->spa_config_list)) != NULL) {
370		if (dp->scd_path == NULL) {
371			spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
372			    "none", 0, ZPROP_SRC_LOCAL);
373		} else if (strcmp(dp->scd_path, spa_config_path) != 0) {
374			spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
375			    dp->scd_path, 0, ZPROP_SRC_LOCAL);
376		}
377	}
378}
379
380/*
381 * Get zpool property values.
382 */
383int
384spa_prop_get(spa_t *spa, nvlist_t **nvp)
385{
386	objset_t *mos = spa->spa_meta_objset;
387	zap_cursor_t zc;
388	zap_attribute_t za;
389	int err;
390
391	VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
392
393	mutex_enter(&spa->spa_props_lock);
394
395	/*
396	 * Get properties from the spa config.
397	 */
398	spa_prop_get_config(spa, nvp);
399
400	/* If no pool property object, no more prop to get. */
401	if (mos == NULL || spa->spa_pool_props_object == 0) {
402		mutex_exit(&spa->spa_props_lock);
403		return (0);
404	}
405
406	/*
407	 * Get properties from the MOS pool property object.
408	 */
409	for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
410	    (err = zap_cursor_retrieve(&zc, &za)) == 0;
411	    zap_cursor_advance(&zc)) {
412		uint64_t intval = 0;
413		char *strval = NULL;
414		zprop_source_t src = ZPROP_SRC_DEFAULT;
415		zpool_prop_t prop;
416
417		if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
418			continue;
419
420		switch (za.za_integer_length) {
421		case 8:
422			/* integer property */
423			if (za.za_first_integer !=
424			    zpool_prop_default_numeric(prop))
425				src = ZPROP_SRC_LOCAL;
426
427			if (prop == ZPOOL_PROP_BOOTFS) {
428				dsl_pool_t *dp;
429				dsl_dataset_t *ds = NULL;
430
431				dp = spa_get_dsl(spa);
432				dsl_pool_config_enter(dp, FTAG);
433				err = dsl_dataset_hold_obj(dp,
434				    za.za_first_integer, FTAG, &ds);
435				if (err != 0) {
436					dsl_pool_config_exit(dp, FTAG);
437					break;
438				}
439
440				strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
441				    KM_SLEEP);
442				dsl_dataset_name(ds, strval);
443				dsl_dataset_rele(ds, FTAG);
444				dsl_pool_config_exit(dp, FTAG);
445			} else {
446				strval = NULL;
447				intval = za.za_first_integer;
448			}
449
450			spa_prop_add_list(*nvp, prop, strval, intval, src);
451
452			if (strval != NULL)
453				kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
454
455			break;
456
457		case 1:
458			/* string property */
459			strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
460			err = zap_lookup(mos, spa->spa_pool_props_object,
461			    za.za_name, 1, za.za_num_integers, strval);
462			if (err) {
463				kmem_free(strval, za.za_num_integers);
464				break;
465			}
466			spa_prop_add_list(*nvp, prop, strval, 0, src);
467			kmem_free(strval, za.za_num_integers);
468			break;
469
470		default:
471			break;
472		}
473	}
474	zap_cursor_fini(&zc);
475	mutex_exit(&spa->spa_props_lock);
476out:
477	if (err && err != ENOENT) {
478		nvlist_free(*nvp);
479		*nvp = NULL;
480		return (err);
481	}
482
483	return (0);
484}
485
486/*
487 * Validate the given pool properties nvlist and modify the list
488 * for the property values to be set.
489 */
490static int
491spa_prop_validate(spa_t *spa, nvlist_t *props)
492{
493	nvpair_t *elem;
494	int error = 0, reset_bootfs = 0;
495	uint64_t objnum = 0;
496	boolean_t has_feature = B_FALSE;
497
498	elem = NULL;
499	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
500		uint64_t intval;
501		char *strval, *slash, *check, *fname;
502		const char *propname = nvpair_name(elem);
503		zpool_prop_t prop = zpool_name_to_prop(propname);
504
505		switch (prop) {
506		case ZPOOL_PROP_INVAL:
507			if (!zpool_prop_feature(propname)) {
508				error = SET_ERROR(EINVAL);
509				break;
510			}
511
512			/*
513			 * Sanitize the input.
514			 */
515			if (nvpair_type(elem) != DATA_TYPE_UINT64) {
516				error = SET_ERROR(EINVAL);
517				break;
518			}
519
520			if (nvpair_value_uint64(elem, &intval) != 0) {
521				error = SET_ERROR(EINVAL);
522				break;
523			}
524
525			if (intval != 0) {
526				error = SET_ERROR(EINVAL);
527				break;
528			}
529
530			fname = strchr(propname, '@') + 1;
531			if (zfeature_lookup_name(fname, NULL) != 0) {
532				error = SET_ERROR(EINVAL);
533				break;
534			}
535
536			has_feature = B_TRUE;
537			break;
538
539		case ZPOOL_PROP_VERSION:
540			error = nvpair_value_uint64(elem, &intval);
541			if (!error &&
542			    (intval < spa_version(spa) ||
543			    intval > SPA_VERSION_BEFORE_FEATURES ||
544			    has_feature))
545				error = SET_ERROR(EINVAL);
546			break;
547
548		case ZPOOL_PROP_DELEGATION:
549		case ZPOOL_PROP_AUTOREPLACE:
550		case ZPOOL_PROP_LISTSNAPS:
551		case ZPOOL_PROP_AUTOEXPAND:
552			error = nvpair_value_uint64(elem, &intval);
553			if (!error && intval > 1)
554				error = SET_ERROR(EINVAL);
555			break;
556
557		case ZPOOL_PROP_MULTIHOST:
558			error = nvpair_value_uint64(elem, &intval);
559			if (!error && intval > 1)
560				error = SET_ERROR(EINVAL);
561
562			if (!error && !spa_get_hostid())
563				error = SET_ERROR(ENOTSUP);
564
565			break;
566
567		case ZPOOL_PROP_BOOTFS:
568			/*
569			 * If the pool version is less than SPA_VERSION_BOOTFS,
570			 * or the pool is still being created (version == 0),
571			 * the bootfs property cannot be set.
572			 */
573			if (spa_version(spa) < SPA_VERSION_BOOTFS) {
574				error = SET_ERROR(ENOTSUP);
575				break;
576			}
577
578			/*
579			 * Make sure the vdev config is bootable
580			 */
581			if (!vdev_is_bootable(spa->spa_root_vdev)) {
582				error = SET_ERROR(ENOTSUP);
583				break;
584			}
585
586			reset_bootfs = 1;
587
588			error = nvpair_value_string(elem, &strval);
589
590			if (!error) {
591				objset_t *os;
592				uint64_t propval;
593
594				if (strval == NULL || strval[0] == '\0') {
595					objnum = zpool_prop_default_numeric(
596					    ZPOOL_PROP_BOOTFS);
597					break;
598				}
599
600				error = dmu_objset_hold(strval, FTAG, &os);
601				if (error != 0)
602					break;
603
604				/*
605				 * Must be ZPL, and its property settings
606				 * must be supported.
607				 */
608
609				if (dmu_objset_type(os) != DMU_OST_ZFS) {
610					error = SET_ERROR(ENOTSUP);
611				} else if ((error =
612				    dsl_prop_get_int_ds(dmu_objset_ds(os),
613				    zfs_prop_to_name(ZFS_PROP_COMPRESSION),
614				    &propval)) == 0 &&
615				    !BOOTFS_COMPRESS_VALID(propval)) {
616					error = SET_ERROR(ENOTSUP);
617				} else {
618					objnum = dmu_objset_id(os);
619				}
620				dmu_objset_rele(os, FTAG);
621			}
622			break;
623
624		case ZPOOL_PROP_FAILUREMODE:
625			error = nvpair_value_uint64(elem, &intval);
626			if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
627			    intval > ZIO_FAILURE_MODE_PANIC))
628				error = SET_ERROR(EINVAL);
629
630			/*
631			 * This is a special case which only occurs when
632			 * the pool has completely failed. This allows
633			 * the user to change the in-core failmode property
634			 * without syncing it out to disk (I/Os might
635			 * currently be blocked). We do this by returning
636			 * EIO to the caller (spa_prop_set) to trick it
637			 * into thinking we encountered a property validation
638			 * error.
639			 */
640			if (!error && spa_suspended(spa)) {
641				spa->spa_failmode = intval;
642				error = SET_ERROR(EIO);
643			}
644			break;
645
646		case ZPOOL_PROP_CACHEFILE:
647			if ((error = nvpair_value_string(elem, &strval)) != 0)
648				break;
649
650			if (strval[0] == '\0')
651				break;
652
653			if (strcmp(strval, "none") == 0)
654				break;
655
656			if (strval[0] != '/') {
657				error = SET_ERROR(EINVAL);
658				break;
659			}
660
661			slash = strrchr(strval, '/');
662			ASSERT(slash != NULL);
663
664			if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
665			    strcmp(slash, "/..") == 0)
666				error = SET_ERROR(EINVAL);
667			break;
668
669		case ZPOOL_PROP_COMMENT:
670			if ((error = nvpair_value_string(elem, &strval)) != 0)
671				break;
672			for (check = strval; *check != '\0'; check++) {
673				/*
674				 * The kernel doesn't have an easy isprint()
675				 * check.  For this kernel check, we merely
676				 * check ASCII apart from DEL.  Fix this if
677				 * there is an easy-to-use kernel isprint().
678				 */
679				if (*check >= 0x7f) {
680					error = SET_ERROR(EINVAL);
681					break;
682				}
683			}
684			if (strlen(strval) > ZPROP_MAX_COMMENT)
685				error = E2BIG;
686			break;
687
688		case ZPOOL_PROP_DEDUPDITTO:
689			if (spa_version(spa) < SPA_VERSION_DEDUP)
690				error = SET_ERROR(ENOTSUP);
691			else
692				error = nvpair_value_uint64(elem, &intval);
693			if (error == 0 &&
694			    intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
695				error = SET_ERROR(EINVAL);
696			break;
697		}
698
699		if (error)
700			break;
701	}
702
703	if (!error && reset_bootfs) {
704		error = nvlist_remove(props,
705		    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
706
707		if (!error) {
708			error = nvlist_add_uint64(props,
709			    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
710		}
711	}
712
713	return (error);
714}
715
716void
717spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
718{
719	char *cachefile;
720	spa_config_dirent_t *dp;
721
722	if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
723	    &cachefile) != 0)
724		return;
725
726	dp = kmem_alloc(sizeof (spa_config_dirent_t),
727	    KM_SLEEP);
728
729	if (cachefile[0] == '\0')
730		dp->scd_path = spa_strdup(spa_config_path);
731	else if (strcmp(cachefile, "none") == 0)
732		dp->scd_path = NULL;
733	else
734		dp->scd_path = spa_strdup(cachefile);
735
736	list_insert_head(&spa->spa_config_list, dp);
737	if (need_sync)
738		spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
739}
740
741int
742spa_prop_set(spa_t *spa, nvlist_t *nvp)
743{
744	int error;
745	nvpair_t *elem = NULL;
746	boolean_t need_sync = B_FALSE;
747
748	if ((error = spa_prop_validate(spa, nvp)) != 0)
749		return (error);
750
751	while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
752		zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
753
754		if (prop == ZPOOL_PROP_CACHEFILE ||
755		    prop == ZPOOL_PROP_ALTROOT ||
756		    prop == ZPOOL_PROP_READONLY)
757			continue;
758
759		if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
760			uint64_t ver;
761
762			if (prop == ZPOOL_PROP_VERSION) {
763				VERIFY(nvpair_value_uint64(elem, &ver) == 0);
764			} else {
765				ASSERT(zpool_prop_feature(nvpair_name(elem)));
766				ver = SPA_VERSION_FEATURES;
767				need_sync = B_TRUE;
768			}
769
770			/* Save time if the version is already set. */
771			if (ver == spa_version(spa))
772				continue;
773
774			/*
775			 * In addition to the pool directory object, we might
776			 * create the pool properties object, the features for
777			 * read object, the features for write object, or the
778			 * feature descriptions object.
779			 */
780			error = dsl_sync_task(spa->spa_name, NULL,
781			    spa_sync_version, &ver,
782			    6, ZFS_SPACE_CHECK_RESERVED);
783			if (error)
784				return (error);
785			continue;
786		}
787
788		need_sync = B_TRUE;
789		break;
790	}
791
792	if (need_sync) {
793		return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
794		    nvp, 6, ZFS_SPACE_CHECK_RESERVED));
795	}
796
797	return (0);
798}
799
800/*
801 * If the bootfs property value is dsobj, clear it.
802 */
803void
804spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
805{
806	if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
807		VERIFY(zap_remove(spa->spa_meta_objset,
808		    spa->spa_pool_props_object,
809		    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
810		spa->spa_bootfs = 0;
811	}
812}
813
814/*ARGSUSED*/
815static int
816spa_change_guid_check(void *arg, dmu_tx_t *tx)
817{
818	uint64_t *newguid = arg;
819	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
820	vdev_t *rvd = spa->spa_root_vdev;
821	uint64_t vdev_state;
822
823	if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
824		int error = (spa_has_checkpoint(spa)) ?
825		    ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
826		return (SET_ERROR(error));
827	}
828
829	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
830	vdev_state = rvd->vdev_state;
831	spa_config_exit(spa, SCL_STATE, FTAG);
832
833	if (vdev_state != VDEV_STATE_HEALTHY)
834		return (SET_ERROR(ENXIO));
835
836	ASSERT3U(spa_guid(spa), !=, *newguid);
837
838	return (0);
839}
840
841static void
842spa_change_guid_sync(void *arg, dmu_tx_t *tx)
843{
844	uint64_t *newguid = arg;
845	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
846	uint64_t oldguid;
847	vdev_t *rvd = spa->spa_root_vdev;
848
849	oldguid = spa_guid(spa);
850
851	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
852	rvd->vdev_guid = *newguid;
853	rvd->vdev_guid_sum += (*newguid - oldguid);
854	vdev_config_dirty(rvd);
855	spa_config_exit(spa, SCL_STATE, FTAG);
856
857	spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
858	    oldguid, *newguid);
859}
860
861/*
862 * Change the GUID for the pool.  This is done so that we can later
863 * re-import a pool built from a clone of our own vdevs.  We will modify
864 * the root vdev's guid, our own pool guid, and then mark all of our
865 * vdevs dirty.  Note that we must make sure that all our vdevs are
866 * online when we do this, or else any vdevs that weren't present
867 * would be orphaned from our pool.  We are also going to issue a
868 * sysevent to update any watchers.
869 */
870int
871spa_change_guid(spa_t *spa)
872{
873	int error;
874	uint64_t guid;
875
876	mutex_enter(&spa->spa_vdev_top_lock);
877	mutex_enter(&spa_namespace_lock);
878	guid = spa_generate_guid(NULL);
879
880	error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
881	    spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
882
883	if (error == 0) {
884		spa_write_cachefile(spa, B_FALSE, B_TRUE);
885		spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
886	}
887
888	mutex_exit(&spa_namespace_lock);
889	mutex_exit(&spa->spa_vdev_top_lock);
890
891	return (error);
892}
893
894/*
895 * ==========================================================================
896 * SPA state manipulation (open/create/destroy/import/export)
897 * ==========================================================================
898 */
899
900static int
901spa_error_entry_compare(const void *a, const void *b)
902{
903	const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
904	const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
905	int ret;
906
907	ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
908	    sizeof (zbookmark_phys_t));
909
910	return (AVL_ISIGN(ret));
911}
912
913/*
914 * Utility function which retrieves copies of the current logs and
915 * re-initializes them in the process.
916 */
917void
918spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
919{
920	ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
921
922	bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
923	bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
924
925	avl_create(&spa->spa_errlist_scrub,
926	    spa_error_entry_compare, sizeof (spa_error_entry_t),
927	    offsetof(spa_error_entry_t, se_avl));
928	avl_create(&spa->spa_errlist_last,
929	    spa_error_entry_compare, sizeof (spa_error_entry_t),
930	    offsetof(spa_error_entry_t, se_avl));
931}
932
933static void
934spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
935{
936	const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
937	enum zti_modes mode = ztip->zti_mode;
938	uint_t value = ztip->zti_value;
939	uint_t count = ztip->zti_count;
940	spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
941	char name[32];
942	uint_t flags = 0;
943	boolean_t batch = B_FALSE;
944
945	if (mode == ZTI_MODE_NULL) {
946		tqs->stqs_count = 0;
947		tqs->stqs_taskq = NULL;
948		return;
949	}
950
951	ASSERT3U(count, >, 0);
952
953	tqs->stqs_count = count;
954	tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
955
956	switch (mode) {
957	case ZTI_MODE_FIXED:
958		ASSERT3U(value, >=, 1);
959		value = MAX(value, 1);
960		break;
961
962	case ZTI_MODE_BATCH:
963		batch = B_TRUE;
964		flags |= TASKQ_THREADS_CPU_PCT;
965		value = zio_taskq_batch_pct;
966		break;
967
968	default:
969		panic("unrecognized mode for %s_%s taskq (%u:%u) in "
970		    "spa_activate()",
971		    zio_type_name[t], zio_taskq_types[q], mode, value);
972		break;
973	}
974
975	for (uint_t i = 0; i < count; i++) {
976		taskq_t *tq;
977
978		if (count > 1) {
979			(void) snprintf(name, sizeof (name), "%s_%s_%u",
980			    zio_type_name[t], zio_taskq_types[q], i);
981		} else {
982			(void) snprintf(name, sizeof (name), "%s_%s",
983			    zio_type_name[t], zio_taskq_types[q]);
984		}
985
986		if (zio_taskq_sysdc && spa->spa_proc != &p0) {
987			if (batch)
988				flags |= TASKQ_DC_BATCH;
989
990			tq = taskq_create_sysdc(name, value, 50, INT_MAX,
991			    spa->spa_proc, zio_taskq_basedc, flags);
992		} else {
993			pri_t pri = maxclsyspri;
994			/*
995			 * The write issue taskq can be extremely CPU
996			 * intensive.  Run it at slightly lower priority
997			 * than the other taskqs.
998			 */
999			if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1000				pri--;
1001
1002			tq = taskq_create_proc(name, value, pri, 50,
1003			    INT_MAX, spa->spa_proc, flags);
1004		}
1005
1006		tqs->stqs_taskq[i] = tq;
1007	}
1008}
1009
1010static void
1011spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1012{
1013	spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1014
1015	if (tqs->stqs_taskq == NULL) {
1016		ASSERT0(tqs->stqs_count);
1017		return;
1018	}
1019
1020	for (uint_t i = 0; i < tqs->stqs_count; i++) {
1021		ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1022		taskq_destroy(tqs->stqs_taskq[i]);
1023	}
1024
1025	kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1026	tqs->stqs_taskq = NULL;
1027}
1028
1029/*
1030 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1031 * Note that a type may have multiple discrete taskqs to avoid lock contention
1032 * on the taskq itself. In that case we choose which taskq at random by using
1033 * the low bits of gethrtime().
1034 */
1035void
1036spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1037    task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1038{
1039	spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1040	taskq_t *tq;
1041
1042	ASSERT3P(tqs->stqs_taskq, !=, NULL);
1043	ASSERT3U(tqs->stqs_count, !=, 0);
1044
1045	if (tqs->stqs_count == 1) {
1046		tq = tqs->stqs_taskq[0];
1047	} else {
1048		tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1049	}
1050
1051	taskq_dispatch_ent(tq, func, arg, flags, ent);
1052}
1053
1054static void
1055spa_create_zio_taskqs(spa_t *spa)
1056{
1057	for (int t = 0; t < ZIO_TYPES; t++) {
1058		for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1059			spa_taskqs_init(spa, t, q);
1060		}
1061	}
1062}
1063
1064#ifdef _KERNEL
1065static void
1066spa_thread(void *arg)
1067{
1068	callb_cpr_t cprinfo;
1069
1070	spa_t *spa = arg;
1071	user_t *pu = PTOU(curproc);
1072
1073	CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1074	    spa->spa_name);
1075
1076	ASSERT(curproc != &p0);
1077	(void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1078	    "zpool-%s", spa->spa_name);
1079	(void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1080
1081	/* bind this thread to the requested psrset */
1082	if (zio_taskq_psrset_bind != PS_NONE) {
1083		pool_lock();
1084		mutex_enter(&cpu_lock);
1085		mutex_enter(&pidlock);
1086		mutex_enter(&curproc->p_lock);
1087
1088		if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1089		    0, NULL, NULL) == 0)  {
1090			curthread->t_bind_pset = zio_taskq_psrset_bind;
1091		} else {
1092			cmn_err(CE_WARN,
1093			    "Couldn't bind process for zfs pool \"%s\" to "
1094			    "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1095		}
1096
1097		mutex_exit(&curproc->p_lock);
1098		mutex_exit(&pidlock);
1099		mutex_exit(&cpu_lock);
1100		pool_unlock();
1101	}
1102
1103	if (zio_taskq_sysdc) {
1104		sysdc_thread_enter(curthread, 100, 0);
1105	}
1106
1107	spa->spa_proc = curproc;
1108	spa->spa_did = curthread->t_did;
1109
1110	spa_create_zio_taskqs(spa);
1111
1112	mutex_enter(&spa->spa_proc_lock);
1113	ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1114
1115	spa->spa_proc_state = SPA_PROC_ACTIVE;
1116	cv_broadcast(&spa->spa_proc_cv);
1117
1118	CALLB_CPR_SAFE_BEGIN(&cprinfo);
1119	while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1120		cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1121	CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1122
1123	ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1124	spa->spa_proc_state = SPA_PROC_GONE;
1125	spa->spa_proc = &p0;
1126	cv_broadcast(&spa->spa_proc_cv);
1127	CALLB_CPR_EXIT(&cprinfo);	/* drops spa_proc_lock */
1128
1129	mutex_enter(&curproc->p_lock);
1130	lwp_exit();
1131}
1132#endif
1133
1134/*
1135 * Activate an uninitialized pool.
1136 */
1137static void
1138spa_activate(spa_t *spa, int mode)
1139{
1140	ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1141
1142	spa->spa_state = POOL_STATE_ACTIVE;
1143	spa->spa_mode = mode;
1144
1145	spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1146	spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1147	spa->spa_special_class = metaslab_class_create(spa, zfs_metaslab_ops);
1148	spa->spa_dedup_class = metaslab_class_create(spa, zfs_metaslab_ops);
1149
1150	/* Try to create a covering process */
1151	mutex_enter(&spa->spa_proc_lock);
1152	ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1153	ASSERT(spa->spa_proc == &p0);
1154	spa->spa_did = 0;
1155
1156	/* Only create a process if we're going to be around a while. */
1157	if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1158		if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1159		    NULL, 0) == 0) {
1160			spa->spa_proc_state = SPA_PROC_CREATED;
1161			while (spa->spa_proc_state == SPA_PROC_CREATED) {
1162				cv_wait(&spa->spa_proc_cv,
1163				    &spa->spa_proc_lock);
1164			}
1165			ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1166			ASSERT(spa->spa_proc != &p0);
1167			ASSERT(spa->spa_did != 0);
1168		} else {
1169#ifdef _KERNEL
1170			cmn_err(CE_WARN,
1171			    "Couldn't create process for zfs pool \"%s\"\n",
1172			    spa->spa_name);
1173#endif
1174		}
1175	}
1176	mutex_exit(&spa->spa_proc_lock);
1177
1178	/* If we didn't create a process, we need to create our taskqs. */
1179	if (spa->spa_proc == &p0) {
1180		spa_create_zio_taskqs(spa);
1181	}
1182
1183	for (size_t i = 0; i < TXG_SIZE; i++) {
1184		spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL,
1185		    ZIO_FLAG_CANFAIL);
1186	}
1187
1188	list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1189	    offsetof(vdev_t, vdev_config_dirty_node));
1190	list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1191	    offsetof(objset_t, os_evicting_node));
1192	list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1193	    offsetof(vdev_t, vdev_state_dirty_node));
1194
1195	txg_list_create(&spa->spa_vdev_txg_list, spa,
1196	    offsetof(struct vdev, vdev_txg_node));
1197
1198	avl_create(&spa->spa_errlist_scrub,
1199	    spa_error_entry_compare, sizeof (spa_error_entry_t),
1200	    offsetof(spa_error_entry_t, se_avl));
1201	avl_create(&spa->spa_errlist_last,
1202	    spa_error_entry_compare, sizeof (spa_error_entry_t),
1203	    offsetof(spa_error_entry_t, se_avl));
1204}
1205
1206/*
1207 * Opposite of spa_activate().
1208 */
1209static void
1210spa_deactivate(spa_t *spa)
1211{
1212	ASSERT(spa->spa_sync_on == B_FALSE);
1213	ASSERT(spa->spa_dsl_pool == NULL);
1214	ASSERT(spa->spa_root_vdev == NULL);
1215	ASSERT(spa->spa_async_zio_root == NULL);
1216	ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1217
1218	spa_evicting_os_wait(spa);
1219
1220	txg_list_destroy(&spa->spa_vdev_txg_list);
1221
1222	list_destroy(&spa->spa_config_dirty_list);
1223	list_destroy(&spa->spa_evicting_os_list);
1224	list_destroy(&spa->spa_state_dirty_list);
1225
1226	for (int t = 0; t < ZIO_TYPES; t++) {
1227		for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1228			spa_taskqs_fini(spa, t, q);
1229		}
1230	}
1231
1232	for (size_t i = 0; i < TXG_SIZE; i++) {
1233		ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1234		VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1235		spa->spa_txg_zio[i] = NULL;
1236	}
1237
1238	metaslab_class_destroy(spa->spa_normal_class);
1239	spa->spa_normal_class = NULL;
1240
1241	metaslab_class_destroy(spa->spa_log_class);
1242	spa->spa_log_class = NULL;
1243
1244	metaslab_class_destroy(spa->spa_special_class);
1245	spa->spa_special_class = NULL;
1246
1247	metaslab_class_destroy(spa->spa_dedup_class);
1248	spa->spa_dedup_class = NULL;
1249
1250	/*
1251	 * If this was part of an import or the open otherwise failed, we may
1252	 * still have errors left in the queues.  Empty them just in case.
1253	 */
1254	spa_errlog_drain(spa);
1255
1256	avl_destroy(&spa->spa_errlist_scrub);
1257	avl_destroy(&spa->spa_errlist_last);
1258
1259	spa->spa_state = POOL_STATE_UNINITIALIZED;
1260
1261	mutex_enter(&spa->spa_proc_lock);
1262	if (spa->spa_proc_state != SPA_PROC_NONE) {
1263		ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1264		spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1265		cv_broadcast(&spa->spa_proc_cv);
1266		while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1267			ASSERT(spa->spa_proc != &p0);
1268			cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1269		}
1270		ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1271		spa->spa_proc_state = SPA_PROC_NONE;
1272	}
1273	ASSERT(spa->spa_proc == &p0);
1274	mutex_exit(&spa->spa_proc_lock);
1275
1276	/*
1277	 * We want to make sure spa_thread() has actually exited the ZFS
1278	 * module, so that the module can't be unloaded out from underneath
1279	 * it.
1280	 */
1281	if (spa->spa_did != 0) {
1282		thread_join(spa->spa_did);
1283		spa->spa_did = 0;
1284	}
1285}
1286
1287/*
1288 * Verify a pool configuration, and construct the vdev tree appropriately.  This
1289 * will create all the necessary vdevs in the appropriate layout, with each vdev
1290 * in the CLOSED state.  This will prep the pool before open/creation/import.
1291 * All vdev validation is done by the vdev_alloc() routine.
1292 */
1293static int
1294spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1295    uint_t id, int atype)
1296{
1297	nvlist_t **child;
1298	uint_t children;
1299	int error;
1300
1301	if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1302		return (error);
1303
1304	if ((*vdp)->vdev_ops->vdev_op_leaf)
1305		return (0);
1306
1307	error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1308	    &child, &children);
1309
1310	if (error == ENOENT)
1311		return (0);
1312
1313	if (error) {
1314		vdev_free(*vdp);
1315		*vdp = NULL;
1316		return (SET_ERROR(EINVAL));
1317	}
1318
1319	for (int c = 0; c < children; c++) {
1320		vdev_t *vd;
1321		if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1322		    atype)) != 0) {
1323			vdev_free(*vdp);
1324			*vdp = NULL;
1325			return (error);
1326		}
1327	}
1328
1329	ASSERT(*vdp != NULL);
1330
1331	return (0);
1332}
1333
1334/*
1335 * Opposite of spa_load().
1336 */
1337static void
1338spa_unload(spa_t *spa)
1339{
1340	int i;
1341
1342	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1343
1344	spa_load_note(spa, "UNLOADING");
1345
1346	/*
1347	 * Stop async tasks.
1348	 */
1349	spa_async_suspend(spa);
1350
1351	if (spa->spa_root_vdev) {
1352		vdev_initialize_stop_all(spa->spa_root_vdev,
1353		    VDEV_INITIALIZE_ACTIVE);
1354	}
1355
1356	/*
1357	 * Stop syncing.
1358	 */
1359	if (spa->spa_sync_on) {
1360		txg_sync_stop(spa->spa_dsl_pool);
1361		spa->spa_sync_on = B_FALSE;
1362	}
1363
1364	/*
1365	 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1366	 * to call it earlier, before we wait for async i/o to complete.
1367	 * This ensures that there is no async metaslab prefetching, by
1368	 * calling taskq_wait(mg_taskq).
1369	 */
1370	if (spa->spa_root_vdev != NULL) {
1371		spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1372		for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1373			vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1374		spa_config_exit(spa, SCL_ALL, spa);
1375	}
1376
1377	if (spa->spa_mmp.mmp_thread)
1378		mmp_thread_stop(spa);
1379
1380	/*
1381	 * Wait for any outstanding async I/O to complete.
1382	 */
1383	if (spa->spa_async_zio_root != NULL) {
1384		for (int i = 0; i < max_ncpus; i++)
1385			(void) zio_wait(spa->spa_async_zio_root[i]);
1386		kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1387		spa->spa_async_zio_root = NULL;
1388	}
1389
1390	if (spa->spa_vdev_removal != NULL) {
1391		spa_vdev_removal_destroy(spa->spa_vdev_removal);
1392		spa->spa_vdev_removal = NULL;
1393	}
1394
1395	if (spa->spa_condense_zthr != NULL) {
1396		zthr_destroy(spa->spa_condense_zthr);
1397		spa->spa_condense_zthr = NULL;
1398	}
1399
1400	if (spa->spa_checkpoint_discard_zthr != NULL) {
1401		zthr_destroy(spa->spa_checkpoint_discard_zthr);
1402		spa->spa_checkpoint_discard_zthr = NULL;
1403	}
1404
1405	spa_condense_fini(spa);
1406
1407	bpobj_close(&spa->spa_deferred_bpobj);
1408
1409	spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1410
1411	/*
1412	 * Close all vdevs.
1413	 */
1414	if (spa->spa_root_vdev)
1415		vdev_free(spa->spa_root_vdev);
1416	ASSERT(spa->spa_root_vdev == NULL);
1417
1418	/*
1419	 * Close the dsl pool.
1420	 */
1421	if (spa->spa_dsl_pool) {
1422		dsl_pool_close(spa->spa_dsl_pool);
1423		spa->spa_dsl_pool = NULL;
1424		spa->spa_meta_objset = NULL;
1425	}
1426
1427	ddt_unload(spa);
1428
1429	/*
1430	 * Drop and purge level 2 cache
1431	 */
1432	spa_l2cache_drop(spa);
1433
1434	for (i = 0; i < spa->spa_spares.sav_count; i++)
1435		vdev_free(spa->spa_spares.sav_vdevs[i]);
1436	if (spa->spa_spares.sav_vdevs) {
1437		kmem_free(spa->spa_spares.sav_vdevs,
1438		    spa->spa_spares.sav_count * sizeof (void *));
1439		spa->spa_spares.sav_vdevs = NULL;
1440	}
1441	if (spa->spa_spares.sav_config) {
1442		nvlist_free(spa->spa_spares.sav_config);
1443		spa->spa_spares.sav_config = NULL;
1444	}
1445	spa->spa_spares.sav_count = 0;
1446
1447	for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1448		vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1449		vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1450	}
1451	if (spa->spa_l2cache.sav_vdevs) {
1452		kmem_free(spa->spa_l2cache.sav_vdevs,
1453		    spa->spa_l2cache.sav_count * sizeof (void *));
1454		spa->spa_l2cache.sav_vdevs = NULL;
1455	}
1456	if (spa->spa_l2cache.sav_config) {
1457		nvlist_free(spa->spa_l2cache.sav_config);
1458		spa->spa_l2cache.sav_config = NULL;
1459	}
1460	spa->spa_l2cache.sav_count = 0;
1461
1462	spa->spa_async_suspended = 0;
1463
1464	spa->spa_indirect_vdevs_loaded = B_FALSE;
1465
1466	if (spa->spa_comment != NULL) {
1467		spa_strfree(spa->spa_comment);
1468		spa->spa_comment = NULL;
1469	}
1470
1471	spa_config_exit(spa, SCL_ALL, spa);
1472}
1473
1474/*
1475 * Load (or re-load) the current list of vdevs describing the active spares for
1476 * this pool.  When this is called, we have some form of basic information in
1477 * 'spa_spares.sav_config'.  We parse this into vdevs, try to open them, and
1478 * then re-generate a more complete list including status information.
1479 */
1480void
1481spa_load_spares(spa_t *spa)
1482{
1483	nvlist_t **spares;
1484	uint_t nspares;
1485	int i;
1486	vdev_t *vd, *tvd;
1487
1488#ifndef _KERNEL
1489	/*
1490	 * zdb opens both the current state of the pool and the
1491	 * checkpointed state (if present), with a different spa_t.
1492	 *
1493	 * As spare vdevs are shared among open pools, we skip loading
1494	 * them when we load the checkpointed state of the pool.
1495	 */
1496	if (!spa_writeable(spa))
1497		return;
1498#endif
1499
1500	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1501
1502	/*
1503	 * First, close and free any existing spare vdevs.
1504	 */
1505	for (i = 0; i < spa->spa_spares.sav_count; i++) {
1506		vd = spa->spa_spares.sav_vdevs[i];
1507
1508		/* Undo the call to spa_activate() below */
1509		if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1510		    B_FALSE)) != NULL && tvd->vdev_isspare)
1511			spa_spare_remove(tvd);
1512		vdev_close(vd);
1513		vdev_free(vd);
1514	}
1515
1516	if (spa->spa_spares.sav_vdevs)
1517		kmem_free(spa->spa_spares.sav_vdevs,
1518		    spa->spa_spares.sav_count * sizeof (void *));
1519
1520	if (spa->spa_spares.sav_config == NULL)
1521		nspares = 0;
1522	else
1523		VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1524		    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1525
1526	spa->spa_spares.sav_count = (int)nspares;
1527	spa->spa_spares.sav_vdevs = NULL;
1528
1529	if (nspares == 0)
1530		return;
1531
1532	/*
1533	 * Construct the array of vdevs, opening them to get status in the
1534	 * process.   For each spare, there is potentially two different vdev_t
1535	 * structures associated with it: one in the list of spares (used only
1536	 * for basic validation purposes) and one in the active vdev
1537	 * configuration (if it's spared in).  During this phase we open and
1538	 * validate each vdev on the spare list.  If the vdev also exists in the
1539	 * active configuration, then we also mark this vdev as an active spare.
1540	 */
1541	spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1542	    KM_SLEEP);
1543	for (i = 0; i < spa->spa_spares.sav_count; i++) {
1544		VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1545		    VDEV_ALLOC_SPARE) == 0);
1546		ASSERT(vd != NULL);
1547
1548		spa->spa_spares.sav_vdevs[i] = vd;
1549
1550		if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1551		    B_FALSE)) != NULL) {
1552			if (!tvd->vdev_isspare)
1553				spa_spare_add(tvd);
1554
1555			/*
1556			 * We only mark the spare active if we were successfully
1557			 * able to load the vdev.  Otherwise, importing a pool
1558			 * with a bad active spare would result in strange
1559			 * behavior, because multiple pool would think the spare
1560			 * is actively in use.
1561			 *
1562			 * There is a vulnerability here to an equally bizarre
1563			 * circumstance, where a dead active spare is later
1564			 * brought back to life (onlined or otherwise).  Given
1565			 * the rarity of this scenario, and the extra complexity
1566			 * it adds, we ignore the possibility.
1567			 */
1568			if (!vdev_is_dead(tvd))
1569				spa_spare_activate(tvd);
1570		}
1571
1572		vd->vdev_top = vd;
1573		vd->vdev_aux = &spa->spa_spares;
1574
1575		if (vdev_open(vd) != 0)
1576			continue;
1577
1578		if (vdev_validate_aux(vd) == 0)
1579			spa_spare_add(vd);
1580	}
1581
1582	/*
1583	 * Recompute the stashed list of spares, with status information
1584	 * this time.
1585	 */
1586	VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1587	    DATA_TYPE_NVLIST_ARRAY) == 0);
1588
1589	spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1590	    KM_SLEEP);
1591	for (i = 0; i < spa->spa_spares.sav_count; i++)
1592		spares[i] = vdev_config_generate(spa,
1593		    spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1594	VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1595	    ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1596	for (i = 0; i < spa->spa_spares.sav_count; i++)
1597		nvlist_free(spares[i]);
1598	kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1599}
1600
1601/*
1602 * Load (or re-load) the current list of vdevs describing the active l2cache for
1603 * this pool.  When this is called, we have some form of basic information in
1604 * 'spa_l2cache.sav_config'.  We parse this into vdevs, try to open them, and
1605 * then re-generate a more complete list including status information.
1606 * Devices which are already active have their details maintained, and are
1607 * not re-opened.
1608 */
1609void
1610spa_load_l2cache(spa_t *spa)
1611{
1612	nvlist_t **l2cache;
1613	uint_t nl2cache;
1614	int i, j, oldnvdevs;
1615	uint64_t guid;
1616	vdev_t *vd, **oldvdevs, **newvdevs;
1617	spa_aux_vdev_t *sav = &spa->spa_l2cache;
1618
1619#ifndef _KERNEL
1620	/*
1621	 * zdb opens both the current state of the pool and the
1622	 * checkpointed state (if present), with a different spa_t.
1623	 *
1624	 * As L2 caches are part of the ARC which is shared among open
1625	 * pools, we skip loading them when we load the checkpointed
1626	 * state of the pool.
1627	 */
1628	if (!spa_writeable(spa))
1629		return;
1630#endif
1631
1632	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1633
1634	if (sav->sav_config != NULL) {
1635		VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1636		    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1637		newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1638	} else {
1639		nl2cache = 0;
1640		newvdevs = NULL;
1641	}
1642
1643	oldvdevs = sav->sav_vdevs;
1644	oldnvdevs = sav->sav_count;
1645	sav->sav_vdevs = NULL;
1646	sav->sav_count = 0;
1647
1648	/*
1649	 * Process new nvlist of vdevs.
1650	 */
1651	for (i = 0; i < nl2cache; i++) {
1652		VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1653		    &guid) == 0);
1654
1655		newvdevs[i] = NULL;
1656		for (j = 0; j < oldnvdevs; j++) {
1657			vd = oldvdevs[j];
1658			if (vd != NULL && guid == vd->vdev_guid) {
1659				/*
1660				 * Retain previous vdev for add/remove ops.
1661				 */
1662				newvdevs[i] = vd;
1663				oldvdevs[j] = NULL;
1664				break;
1665			}
1666		}
1667
1668		if (newvdevs[i] == NULL) {
1669			/*
1670			 * Create new vdev
1671			 */
1672			VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1673			    VDEV_ALLOC_L2CACHE) == 0);
1674			ASSERT(vd != NULL);
1675			newvdevs[i] = vd;
1676
1677			/*
1678			 * Commit this vdev as an l2cache device,
1679			 * even if it fails to open.
1680			 */
1681			spa_l2cache_add(vd);
1682
1683			vd->vdev_top = vd;
1684			vd->vdev_aux = sav;
1685
1686			spa_l2cache_activate(vd);
1687
1688			if (vdev_open(vd) != 0)
1689				continue;
1690
1691			(void) vdev_validate_aux(vd);
1692
1693			if (!vdev_is_dead(vd))
1694				l2arc_add_vdev(spa, vd);
1695		}
1696	}
1697
1698	/*
1699	 * Purge vdevs that were dropped
1700	 */
1701	for (i = 0; i < oldnvdevs; i++) {
1702		uint64_t pool;
1703
1704		vd = oldvdevs[i];
1705		if (vd != NULL) {
1706			ASSERT(vd->vdev_isl2cache);
1707
1708			if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1709			    pool != 0ULL && l2arc_vdev_present(vd))
1710				l2arc_remove_vdev(vd);
1711			vdev_clear_stats(vd);
1712			vdev_free(vd);
1713		}
1714	}
1715
1716	if (oldvdevs)
1717		kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1718
1719	if (sav->sav_config == NULL)
1720		goto out;
1721
1722	sav->sav_vdevs = newvdevs;
1723	sav->sav_count = (int)nl2cache;
1724
1725	/*
1726	 * Recompute the stashed list of l2cache devices, with status
1727	 * information this time.
1728	 */
1729	VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1730	    DATA_TYPE_NVLIST_ARRAY) == 0);
1731
1732	l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1733	for (i = 0; i < sav->sav_count; i++)
1734		l2cache[i] = vdev_config_generate(spa,
1735		    sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1736	VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1737	    ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1738out:
1739	for (i = 0; i < sav->sav_count; i++)
1740		nvlist_free(l2cache[i]);
1741	if (sav->sav_count)
1742		kmem_free(l2cache, sav->sav_count * sizeof (void *));
1743}
1744
1745static int
1746load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1747{
1748	dmu_buf_t *db;
1749	char *packed = NULL;
1750	size_t nvsize = 0;
1751	int error;
1752	*value = NULL;
1753
1754	error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1755	if (error != 0)
1756		return (error);
1757
1758	nvsize = *(uint64_t *)db->db_data;
1759	dmu_buf_rele(db, FTAG);
1760
1761	packed = kmem_alloc(nvsize, KM_SLEEP);
1762	error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1763	    DMU_READ_PREFETCH);
1764	if (error == 0)
1765		error = nvlist_unpack(packed, nvsize, value, 0);
1766	kmem_free(packed, nvsize);
1767
1768	return (error);
1769}
1770
1771/*
1772 * Concrete top-level vdevs that are not missing and are not logs. At every
1773 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1774 */
1775static uint64_t
1776spa_healthy_core_tvds(spa_t *spa)
1777{
1778	vdev_t *rvd = spa->spa_root_vdev;
1779	uint64_t tvds = 0;
1780
1781	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1782		vdev_t *vd = rvd->vdev_child[i];
1783		if (vd->vdev_islog)
1784			continue;
1785		if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1786			tvds++;
1787	}
1788
1789	return (tvds);
1790}
1791
1792/*
1793 * Checks to see if the given vdev could not be opened, in which case we post a
1794 * sysevent to notify the autoreplace code that the device has been removed.
1795 */
1796static void
1797spa_check_removed(vdev_t *vd)
1798{
1799	for (uint64_t c = 0; c < vd->vdev_children; c++)
1800		spa_check_removed(vd->vdev_child[c]);
1801
1802	if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1803	    vdev_is_concrete(vd)) {
1804		zfs_post_autoreplace(vd->vdev_spa, vd);
1805		spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1806	}
1807}
1808
1809static int
1810spa_check_for_missing_logs(spa_t *spa)
1811{
1812	vdev_t *rvd = spa->spa_root_vdev;
1813
1814	/*
1815	 * If we're doing a normal import, then build up any additional
1816	 * diagnostic information about missing log devices.
1817	 * We'll pass this up to the user for further processing.
1818	 */
1819	if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1820		nvlist_t **child, *nv;
1821		uint64_t idx = 0;
1822
1823		child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1824		    KM_SLEEP);
1825		VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1826
1827		for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1828			vdev_t *tvd = rvd->vdev_child[c];
1829
1830			/*
1831			 * We consider a device as missing only if it failed
1832			 * to open (i.e. offline or faulted is not considered
1833			 * as missing).
1834			 */
1835			if (tvd->vdev_islog &&
1836			    tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1837				child[idx++] = vdev_config_generate(spa, tvd,
1838				    B_FALSE, VDEV_CONFIG_MISSING);
1839			}
1840		}
1841
1842		if (idx > 0) {
1843			fnvlist_add_nvlist_array(nv,
1844			    ZPOOL_CONFIG_CHILDREN, child, idx);
1845			fnvlist_add_nvlist(spa->spa_load_info,
1846			    ZPOOL_CONFIG_MISSING_DEVICES, nv);
1847
1848			for (uint64_t i = 0; i < idx; i++)
1849				nvlist_free(child[i]);
1850		}
1851		nvlist_free(nv);
1852		kmem_free(child, rvd->vdev_children * sizeof (char **));
1853
1854		if (idx > 0) {
1855			spa_load_failed(spa, "some log devices are missing");
1856			vdev_dbgmsg_print_tree(rvd, 2);
1857			return (SET_ERROR(ENXIO));
1858		}
1859	} else {
1860		for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1861			vdev_t *tvd = rvd->vdev_child[c];
1862
1863			if (tvd->vdev_islog &&
1864			    tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1865				spa_set_log_state(spa, SPA_LOG_CLEAR);
1866				spa_load_note(spa, "some log devices are "
1867				    "missing, ZIL is dropped.");
1868				vdev_dbgmsg_print_tree(rvd, 2);
1869				break;
1870			}
1871		}
1872	}
1873
1874	return (0);
1875}
1876
1877/*
1878 * Check for missing log devices
1879 */
1880static boolean_t
1881spa_check_logs(spa_t *spa)
1882{
1883	boolean_t rv = B_FALSE;
1884	dsl_pool_t *dp = spa_get_dsl(spa);
1885
1886	switch (spa->spa_log_state) {
1887	case SPA_LOG_MISSING:
1888		/* need to recheck in case slog has been restored */
1889	case SPA_LOG_UNKNOWN:
1890		rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1891		    zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
1892		if (rv)
1893			spa_set_log_state(spa, SPA_LOG_MISSING);
1894		break;
1895	}
1896	return (rv);
1897}
1898
1899static boolean_t
1900spa_passivate_log(spa_t *spa)
1901{
1902	vdev_t *rvd = spa->spa_root_vdev;
1903	boolean_t slog_found = B_FALSE;
1904
1905	ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1906
1907	if (!spa_has_slogs(spa))
1908		return (B_FALSE);
1909
1910	for (int c = 0; c < rvd->vdev_children; c++) {
1911		vdev_t *tvd = rvd->vdev_child[c];
1912		metaslab_group_t *mg = tvd->vdev_mg;
1913
1914		if (tvd->vdev_islog) {
1915			metaslab_group_passivate(mg);
1916			slog_found = B_TRUE;
1917		}
1918	}
1919
1920	return (slog_found);
1921}
1922
1923static void
1924spa_activate_log(spa_t *spa)
1925{
1926	vdev_t *rvd = spa->spa_root_vdev;
1927
1928	ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1929
1930	for (int c = 0; c < rvd->vdev_children; c++) {
1931		vdev_t *tvd = rvd->vdev_child[c];
1932		metaslab_group_t *mg = tvd->vdev_mg;
1933
1934		if (tvd->vdev_islog)
1935			metaslab_group_activate(mg);
1936	}
1937}
1938
1939int
1940spa_reset_logs(spa_t *spa)
1941{
1942	int error;
1943
1944	error = dmu_objset_find(spa_name(spa), zil_reset,
1945	    NULL, DS_FIND_CHILDREN);
1946	if (error == 0) {
1947		/*
1948		 * We successfully offlined the log device, sync out the
1949		 * current txg so that the "stubby" block can be removed
1950		 * by zil_sync().
1951		 */
1952		txg_wait_synced(spa->spa_dsl_pool, 0);
1953	}
1954	return (error);
1955}
1956
1957static void
1958spa_aux_check_removed(spa_aux_vdev_t *sav)
1959{
1960	for (int i = 0; i < sav->sav_count; i++)
1961		spa_check_removed(sav->sav_vdevs[i]);
1962}
1963
1964void
1965spa_claim_notify(zio_t *zio)
1966{
1967	spa_t *spa = zio->io_spa;
1968
1969	if (zio->io_error)
1970		return;
1971
1972	mutex_enter(&spa->spa_props_lock);	/* any mutex will do */
1973	if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
1974		spa->spa_claim_max_txg = zio->io_bp->blk_birth;
1975	mutex_exit(&spa->spa_props_lock);
1976}
1977
1978typedef struct spa_load_error {
1979	uint64_t	sle_meta_count;
1980	uint64_t	sle_data_count;
1981} spa_load_error_t;
1982
1983static void
1984spa_load_verify_done(zio_t *zio)
1985{
1986	blkptr_t *bp = zio->io_bp;
1987	spa_load_error_t *sle = zio->io_private;
1988	dmu_object_type_t type = BP_GET_TYPE(bp);
1989	int error = zio->io_error;
1990	spa_t *spa = zio->io_spa;
1991
1992	abd_free(zio->io_abd);
1993	if (error) {
1994		if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
1995		    type != DMU_OT_INTENT_LOG)
1996			atomic_inc_64(&sle->sle_meta_count);
1997		else
1998			atomic_inc_64(&sle->sle_data_count);
1999	}
2000
2001	mutex_enter(&spa->spa_scrub_lock);
2002	spa->spa_load_verify_ios--;
2003	cv_broadcast(&spa->spa_scrub_io_cv);
2004	mutex_exit(&spa->spa_scrub_lock);
2005}
2006
2007/*
2008 * Maximum number of concurrent scrub i/os to create while verifying
2009 * a pool while importing it.
2010 */
2011int spa_load_verify_maxinflight = 10000;
2012boolean_t spa_load_verify_metadata = B_TRUE;
2013boolean_t spa_load_verify_data = B_TRUE;
2014
2015/*ARGSUSED*/
2016static int
2017spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2018    const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2019{
2020	if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2021		return (0);
2022	/*
2023	 * Note: normally this routine will not be called if
2024	 * spa_load_verify_metadata is not set.  However, it may be useful
2025	 * to manually set the flag after the traversal has begun.
2026	 */
2027	if (!spa_load_verify_metadata)
2028		return (0);
2029	if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2030		return (0);
2031
2032	zio_t *rio = arg;
2033	size_t size = BP_GET_PSIZE(bp);
2034
2035	mutex_enter(&spa->spa_scrub_lock);
2036	while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
2037		cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2038	spa->spa_load_verify_ios++;
2039	mutex_exit(&spa->spa_scrub_lock);
2040
2041	zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2042	    spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2043	    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2044	    ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2045	return (0);
2046}
2047
2048/* ARGSUSED */
2049int
2050verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2051{
2052	if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2053		return (SET_ERROR(ENAMETOOLONG));
2054
2055	return (0);
2056}
2057
2058static int
2059spa_load_verify(spa_t *spa)
2060{
2061	zio_t *rio;
2062	spa_load_error_t sle = { 0 };
2063	zpool_load_policy_t policy;
2064	boolean_t verify_ok = B_FALSE;
2065	int error = 0;
2066
2067	zpool_get_load_policy(spa->spa_config, &policy);
2068
2069	if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2070		return (0);
2071
2072	dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2073	error = dmu_objset_find_dp(spa->spa_dsl_pool,
2074	    spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2075	    DS_FIND_CHILDREN);
2076	dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2077	if (error != 0)
2078		return (error);
2079
2080	rio = zio_root(spa, NULL, &sle,
2081	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2082
2083	if (spa_load_verify_metadata) {
2084		if (spa->spa_extreme_rewind) {
2085			spa_load_note(spa, "performing a complete scan of the "
2086			    "pool since extreme rewind is on. This may take "
2087			    "a very long time.\n  (spa_load_verify_data=%u, "
2088			    "spa_load_verify_metadata=%u)",
2089			    spa_load_verify_data, spa_load_verify_metadata);
2090		}
2091		error = traverse_pool(spa, spa->spa_verify_min_txg,
2092		    TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2093		    spa_load_verify_cb, rio);
2094	}
2095
2096	(void) zio_wait(rio);
2097
2098	spa->spa_load_meta_errors = sle.sle_meta_count;
2099	spa->spa_load_data_errors = sle.sle_data_count;
2100
2101	if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2102		spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2103		    "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2104		    (u_longlong_t)sle.sle_data_count);
2105	}
2106
2107	if (spa_load_verify_dryrun ||
2108	    (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2109	    sle.sle_data_count <= policy.zlp_maxdata)) {
2110		int64_t loss = 0;
2111
2112		verify_ok = B_TRUE;
2113		spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2114		spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2115
2116		loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2117		VERIFY(nvlist_add_uint64(spa->spa_load_info,
2118		    ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2119		VERIFY(nvlist_add_int64(spa->spa_load_info,
2120		    ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2121		VERIFY(nvlist_add_uint64(spa->spa_load_info,
2122		    ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2123	} else {
2124		spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2125	}
2126
2127	if (spa_load_verify_dryrun)
2128		return (0);
2129
2130	if (error) {
2131		if (error != ENXIO && error != EIO)
2132			error = SET_ERROR(EIO);
2133		return (error);
2134	}
2135
2136	return (verify_ok ? 0 : EIO);
2137}
2138
2139/*
2140 * Find a value in the pool props object.
2141 */
2142static void
2143spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2144{
2145	(void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2146	    zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2147}
2148
2149/*
2150 * Find a value in the pool directory object.
2151 */
2152static int
2153spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2154{
2155	int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2156	    name, sizeof (uint64_t), 1, val);
2157
2158	if (error != 0 && (error != ENOENT || log_enoent)) {
2159		spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2160		    "[error=%d]", name, error);
2161	}
2162
2163	return (error);
2164}
2165
2166static int
2167spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2168{
2169	vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2170	return (SET_ERROR(err));
2171}
2172
2173static void
2174spa_spawn_aux_threads(spa_t *spa)
2175{
2176	ASSERT(spa_writeable(spa));
2177
2178	ASSERT(MUTEX_HELD(&spa_namespace_lock));
2179
2180	spa_start_indirect_condensing_thread(spa);
2181
2182	ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2183	spa->spa_checkpoint_discard_zthr =
2184	    zthr_create(spa_checkpoint_discard_thread_check,
2185	    spa_checkpoint_discard_thread, spa);
2186}
2187
2188/*
2189 * Fix up config after a partly-completed split.  This is done with the
2190 * ZPOOL_CONFIG_SPLIT nvlist.  Both the splitting pool and the split-off
2191 * pool have that entry in their config, but only the splitting one contains
2192 * a list of all the guids of the vdevs that are being split off.
2193 *
2194 * This function determines what to do with that list: either rejoin
2195 * all the disks to the pool, or complete the splitting process.  To attempt
2196 * the rejoin, each disk that is offlined is marked online again, and
2197 * we do a reopen() call.  If the vdev label for every disk that was
2198 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2199 * then we call vdev_split() on each disk, and complete the split.
2200 *
2201 * Otherwise we leave the config alone, with all the vdevs in place in
2202 * the original pool.
2203 */
2204static void
2205spa_try_repair(spa_t *spa, nvlist_t *config)
2206{
2207	uint_t extracted;
2208	uint64_t *glist;
2209	uint_t i, gcount;
2210	nvlist_t *nvl;
2211	vdev_t **vd;
2212	boolean_t attempt_reopen;
2213
2214	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2215		return;
2216
2217	/* check that the config is complete */
2218	if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2219	    &glist, &gcount) != 0)
2220		return;
2221
2222	vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2223
2224	/* attempt to online all the vdevs & validate */
2225	attempt_reopen = B_TRUE;
2226	for (i = 0; i < gcount; i++) {
2227		if (glist[i] == 0)	/* vdev is hole */
2228			continue;
2229
2230		vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2231		if (vd[i] == NULL) {
2232			/*
2233			 * Don't bother attempting to reopen the disks;
2234			 * just do the split.
2235			 */
2236			attempt_reopen = B_FALSE;
2237		} else {
2238			/* attempt to re-online it */
2239			vd[i]->vdev_offline = B_FALSE;
2240		}
2241	}
2242
2243	if (attempt_reopen) {
2244		vdev_reopen(spa->spa_root_vdev);
2245
2246		/* check each device to see what state it's in */
2247		for (extracted = 0, i = 0; i < gcount; i++) {
2248			if (vd[i] != NULL &&
2249			    vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2250				break;
2251			++extracted;
2252		}
2253	}
2254
2255	/*
2256	 * If every disk has been moved to the new pool, or if we never
2257	 * even attempted to look at them, then we split them off for
2258	 * good.
2259	 */
2260	if (!attempt_reopen || gcount == extracted) {
2261		for (i = 0; i < gcount; i++)
2262			if (vd[i] != NULL)
2263				vdev_split(vd[i]);
2264		vdev_reopen(spa->spa_root_vdev);
2265	}
2266
2267	kmem_free(vd, gcount * sizeof (vdev_t *));
2268}
2269
2270static int
2271spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2272{
2273	char *ereport = FM_EREPORT_ZFS_POOL;
2274	int error;
2275
2276	spa->spa_load_state = state;
2277
2278	gethrestime(&spa->spa_loaded_ts);
2279	error = spa_load_impl(spa, type, &ereport);
2280
2281	/*
2282	 * Don't count references from objsets that are already closed
2283	 * and are making their way through the eviction process.
2284	 */
2285	spa_evicting_os_wait(spa);
2286	spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
2287	if (error) {
2288		if (error != EEXIST) {
2289			spa->spa_loaded_ts.tv_sec = 0;
2290			spa->spa_loaded_ts.tv_nsec = 0;
2291		}
2292		if (error != EBADF) {
2293			zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2294		}
2295	}
2296	spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2297	spa->spa_ena = 0;
2298
2299	return (error);
2300}
2301
2302/*
2303 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2304 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2305 * spa's per-vdev ZAP list.
2306 */
2307static uint64_t
2308vdev_count_verify_zaps(vdev_t *vd)
2309{
2310	spa_t *spa = vd->vdev_spa;
2311	uint64_t total = 0;
2312	if (vd->vdev_top_zap != 0) {
2313		total++;
2314		ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2315		    spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2316	}
2317	if (vd->vdev_leaf_zap != 0) {
2318		total++;
2319		ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2320		    spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2321	}
2322
2323	for (uint64_t i = 0; i < vd->vdev_children; i++) {
2324		total += vdev_count_verify_zaps(vd->vdev_child[i]);
2325	}
2326
2327	return (total);
2328}
2329
2330/*
2331 * Determine whether the activity check is required.
2332 */
2333static boolean_t
2334spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
2335    nvlist_t *config)
2336{
2337	uint64_t state = 0;
2338	uint64_t hostid = 0;
2339	uint64_t tryconfig_txg = 0;
2340	uint64_t tryconfig_timestamp = 0;
2341	nvlist_t *nvinfo;
2342
2343	if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2344		nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2345		(void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
2346		    &tryconfig_txg);
2347		(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2348		    &tryconfig_timestamp);
2349	}
2350
2351	(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
2352
2353	/*
2354	 * Disable the MMP activity check - This is used by zdb which
2355	 * is intended to be used on potentially active pools.
2356	 */
2357	if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
2358		return (B_FALSE);
2359
2360	/*
2361	 * Skip the activity check when the MMP feature is disabled.
2362	 */
2363	if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
2364		return (B_FALSE);
2365	/*
2366	 * If the tryconfig_* values are nonzero, they are the results of an
2367	 * earlier tryimport.  If they match the uberblock we just found, then
2368	 * the pool has not changed and we return false so we do not test a
2369	 * second time.
2370	 */
2371	if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
2372	    tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp)
2373		return (B_FALSE);
2374
2375	/*
2376	 * Allow the activity check to be skipped when importing the pool
2377	 * on the same host which last imported it.  Since the hostid from
2378	 * configuration may be stale use the one read from the label.
2379	 */
2380	if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
2381		hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
2382
2383	if (hostid == spa_get_hostid())
2384		return (B_FALSE);
2385
2386	/*
2387	 * Skip the activity test when the pool was cleanly exported.
2388	 */
2389	if (state != POOL_STATE_ACTIVE)
2390		return (B_FALSE);
2391
2392	return (B_TRUE);
2393}
2394
2395/*
2396 * Perform the import activity check.  If the user canceled the import or
2397 * we detected activity then fail.
2398 */
2399static int
2400spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
2401{
2402	uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
2403	uint64_t txg = ub->ub_txg;
2404	uint64_t timestamp = ub->ub_timestamp;
2405	uint64_t import_delay = NANOSEC;
2406	hrtime_t import_expire;
2407	nvlist_t *mmp_label = NULL;
2408	vdev_t *rvd = spa->spa_root_vdev;
2409	kcondvar_t cv;
2410	kmutex_t mtx;
2411	int error = 0;
2412
2413	cv_init(&cv, NULL, CV_DEFAULT, NULL);
2414	mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
2415	mutex_enter(&mtx);
2416
2417	/*
2418	 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
2419	 * during the earlier tryimport.  If the txg recorded there is 0 then
2420	 * the pool is known to be active on another host.
2421	 *
2422	 * Otherwise, the pool might be in use on another node.  Check for
2423	 * changes in the uberblocks on disk if necessary.
2424	 */
2425	if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2426		nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
2427		    ZPOOL_CONFIG_LOAD_INFO);
2428
2429		if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
2430		    fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
2431			vdev_uberblock_load(rvd, ub, &mmp_label);
2432			error = SET_ERROR(EREMOTEIO);
2433			goto out;
2434		}
2435	}
2436
2437	/*
2438	 * Preferentially use the zfs_multihost_interval from the node which
2439	 * last imported the pool.  This value is stored in an MMP uberblock as.
2440	 *
2441	 * ub_mmp_delay * vdev_count_leaves() == zfs_multihost_interval
2442	 */
2443	if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay)
2444		import_delay = MAX(import_delay, import_intervals *
2445		    ub->ub_mmp_delay * MAX(vdev_count_leaves(spa), 1));
2446
2447	/* Apply a floor using the local default values. */
2448	import_delay = MAX(import_delay, import_intervals *
2449	    MSEC2NSEC(MAX(zfs_multihost_interval, MMP_MIN_INTERVAL)));
2450
2451	zfs_dbgmsg("import_delay=%llu ub_mmp_delay=%llu import_intervals=%u "
2452	    "leaves=%u", import_delay, ub->ub_mmp_delay, import_intervals,
2453	    vdev_count_leaves(spa));
2454
2455	/* Add a small random factor in case of simultaneous imports (0-25%) */
2456	import_expire = gethrtime() + import_delay +
2457	    (import_delay * spa_get_random(250) / 1000);
2458
2459	while (gethrtime() < import_expire) {
2460		vdev_uberblock_load(rvd, ub, &mmp_label);
2461
2462		if (txg != ub->ub_txg || timestamp != ub->ub_timestamp) {
2463			error = SET_ERROR(EREMOTEIO);
2464			break;
2465		}
2466
2467		if (mmp_label) {
2468			nvlist_free(mmp_label);
2469			mmp_label = NULL;
2470		}
2471
2472		error = cv_timedwait_sig(&cv, &mtx, ddi_get_lbolt() + hz);
2473		if (error != -1) {
2474			error = SET_ERROR(EINTR);
2475			break;
2476		}
2477		error = 0;
2478	}
2479
2480out:
2481	mutex_exit(&mtx);
2482	mutex_destroy(&mtx);
2483	cv_destroy(&cv);
2484
2485	/*
2486	 * If the pool is determined to be active store the status in the
2487	 * spa->spa_load_info nvlist.  If the remote hostname or hostid are
2488	 * available from configuration read from disk store them as well.
2489	 * This allows 'zpool import' to generate a more useful message.
2490	 *
2491	 * ZPOOL_CONFIG_MMP_STATE    - observed pool status (mandatory)
2492	 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
2493	 * ZPOOL_CONFIG_MMP_HOSTID   - hostid from the active pool
2494	 */
2495	if (error == EREMOTEIO) {
2496		char *hostname = "<unknown>";
2497		uint64_t hostid = 0;
2498
2499		if (mmp_label) {
2500			if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
2501				hostname = fnvlist_lookup_string(mmp_label,
2502				    ZPOOL_CONFIG_HOSTNAME);
2503				fnvlist_add_string(spa->spa_load_info,
2504				    ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
2505			}
2506
2507			if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
2508				hostid = fnvlist_lookup_uint64(mmp_label,
2509				    ZPOOL_CONFIG_HOSTID);
2510				fnvlist_add_uint64(spa->spa_load_info,
2511				    ZPOOL_CONFIG_MMP_HOSTID, hostid);
2512			}
2513		}
2514
2515		fnvlist_add_uint64(spa->spa_load_info,
2516		    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
2517		fnvlist_add_uint64(spa->spa_load_info,
2518		    ZPOOL_CONFIG_MMP_TXG, 0);
2519
2520		error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
2521	}
2522
2523	if (mmp_label)
2524		nvlist_free(mmp_label);
2525
2526	return (error);
2527}
2528
2529static int
2530spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2531{
2532	uint64_t hostid;
2533	char *hostname;
2534	uint64_t myhostid = 0;
2535
2536	if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2537	    ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2538		hostname = fnvlist_lookup_string(mos_config,
2539		    ZPOOL_CONFIG_HOSTNAME);
2540
2541		myhostid = zone_get_hostid(NULL);
2542
2543		if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2544			cmn_err(CE_WARN, "pool '%s' could not be "
2545			    "loaded as it was last accessed by "
2546			    "another system (host: %s hostid: 0x%llx). "
2547			    "See: http://illumos.org/msg/ZFS-8000-EY",
2548			    spa_name(spa), hostname, (u_longlong_t)hostid);
2549			spa_load_failed(spa, "hostid verification failed: pool "
2550			    "last accessed by host: %s (hostid: 0x%llx)",
2551			    hostname, (u_longlong_t)hostid);
2552			return (SET_ERROR(EBADF));
2553		}
2554	}
2555
2556	return (0);
2557}
2558
2559static int
2560spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2561{
2562	int error = 0;
2563	nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2564	int parse;
2565	vdev_t *rvd;
2566	uint64_t pool_guid;
2567	char *comment;
2568
2569	/*
2570	 * Versioning wasn't explicitly added to the label until later, so if
2571	 * it's not present treat it as the initial version.
2572	 */
2573	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2574	    &spa->spa_ubsync.ub_version) != 0)
2575		spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2576
2577	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2578		spa_load_failed(spa, "invalid config provided: '%s' missing",
2579		    ZPOOL_CONFIG_POOL_GUID);
2580		return (SET_ERROR(EINVAL));
2581	}
2582
2583	/*
2584	 * If we are doing an import, ensure that the pool is not already
2585	 * imported by checking if its pool guid already exists in the
2586	 * spa namespace.
2587	 *
2588	 * The only case that we allow an already imported pool to be
2589	 * imported again, is when the pool is checkpointed and we want to
2590	 * look at its checkpointed state from userland tools like zdb.
2591	 */
2592#ifdef _KERNEL
2593	if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2594	    spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2595	    spa_guid_exists(pool_guid, 0)) {
2596#else
2597	if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2598	    spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2599	    spa_guid_exists(pool_guid, 0) &&
2600	    !spa_importing_readonly_checkpoint(spa)) {
2601#endif
2602		spa_load_failed(spa, "a pool with guid %llu is already open",
2603		    (u_longlong_t)pool_guid);
2604		return (SET_ERROR(EEXIST));
2605	}
2606
2607	spa->spa_config_guid = pool_guid;
2608
2609	nvlist_free(spa->spa_load_info);
2610	spa->spa_load_info = fnvlist_alloc();
2611
2612	ASSERT(spa->spa_comment == NULL);
2613	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2614		spa->spa_comment = spa_strdup(comment);
2615
2616	(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2617	    &spa->spa_config_txg);
2618
2619	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2620		spa->spa_config_splitting = fnvlist_dup(nvl);
2621
2622	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2623		spa_load_failed(spa, "invalid config provided: '%s' missing",
2624		    ZPOOL_CONFIG_VDEV_TREE);
2625		return (SET_ERROR(EINVAL));
2626	}
2627
2628	/*
2629	 * Create "The Godfather" zio to hold all async IOs
2630	 */
2631	spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2632	    KM_SLEEP);
2633	for (int i = 0; i < max_ncpus; i++) {
2634		spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2635		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2636		    ZIO_FLAG_GODFATHER);
2637	}
2638
2639	/*
2640	 * Parse the configuration into a vdev tree.  We explicitly set the
2641	 * value that will be returned by spa_version() since parsing the
2642	 * configuration requires knowing the version number.
2643	 */
2644	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2645	parse = (type == SPA_IMPORT_EXISTING ?
2646	    VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2647	error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2648	spa_config_exit(spa, SCL_ALL, FTAG);
2649
2650	if (error != 0) {
2651		spa_load_failed(spa, "unable to parse config [error=%d]",
2652		    error);
2653		return (error);
2654	}
2655
2656	ASSERT(spa->spa_root_vdev == rvd);
2657	ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2658	ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2659
2660	if (type != SPA_IMPORT_ASSEMBLE) {
2661		ASSERT(spa_guid(spa) == pool_guid);
2662	}
2663
2664	return (0);
2665}
2666
2667/*
2668 * Recursively open all vdevs in the vdev tree. This function is called twice:
2669 * first with the untrusted config, then with the trusted config.
2670 */
2671static int
2672spa_ld_open_vdevs(spa_t *spa)
2673{
2674	int error = 0;
2675
2676	/*
2677	 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2678	 * missing/unopenable for the root vdev to be still considered openable.
2679	 */
2680	if (spa->spa_trust_config) {
2681		spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2682	} else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2683		spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2684	} else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2685		spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2686	} else {
2687		spa->spa_missing_tvds_allowed = 0;
2688	}
2689
2690	spa->spa_missing_tvds_allowed =
2691	    MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2692
2693	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2694	error = vdev_open(spa->spa_root_vdev);
2695	spa_config_exit(spa, SCL_ALL, FTAG);
2696
2697	if (spa->spa_missing_tvds != 0) {
2698		spa_load_note(spa, "vdev tree has %lld missing top-level "
2699		    "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2700		if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2701			/*
2702			 * Although theoretically we could allow users to open
2703			 * incomplete pools in RW mode, we'd need to add a lot
2704			 * of extra logic (e.g. adjust pool space to account
2705			 * for missing vdevs).
2706			 * This limitation also prevents users from accidentally
2707			 * opening the pool in RW mode during data recovery and
2708			 * damaging it further.
2709			 */
2710			spa_load_note(spa, "pools with missing top-level "
2711			    "vdevs can only be opened in read-only mode.");
2712			error = SET_ERROR(ENXIO);
2713		} else {
2714			spa_load_note(spa, "current settings allow for maximum "
2715			    "%lld missing top-level vdevs at this stage.",
2716			    (u_longlong_t)spa->spa_missing_tvds_allowed);
2717		}
2718	}
2719	if (error != 0) {
2720		spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2721		    error);
2722	}
2723	if (spa->spa_missing_tvds != 0 || error != 0)
2724		vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2725
2726	return (error);
2727}
2728
2729/*
2730 * We need to validate the vdev labels against the configuration that
2731 * we have in hand. This function is called twice: first with an untrusted
2732 * config, then with a trusted config. The validation is more strict when the
2733 * config is trusted.
2734 */
2735static int
2736spa_ld_validate_vdevs(spa_t *spa)
2737{
2738	int error = 0;
2739	vdev_t *rvd = spa->spa_root_vdev;
2740
2741	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2742	error = vdev_validate(rvd);
2743	spa_config_exit(spa, SCL_ALL, FTAG);
2744
2745	if (error != 0) {
2746		spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2747		return (error);
2748	}
2749
2750	if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2751		spa_load_failed(spa, "cannot open vdev tree after invalidating "
2752		    "some vdevs");
2753		vdev_dbgmsg_print_tree(rvd, 2);
2754		return (SET_ERROR(ENXIO));
2755	}
2756
2757	return (0);
2758}
2759
2760static void
2761spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2762{
2763	spa->spa_state = POOL_STATE_ACTIVE;
2764	spa->spa_ubsync = spa->spa_uberblock;
2765	spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2766	    TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2767	spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2768	    spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2769	spa->spa_claim_max_txg = spa->spa_first_txg;
2770	spa->spa_prev_software_version = ub->ub_software_version;
2771}
2772
2773static int
2774spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2775{
2776	vdev_t *rvd = spa->spa_root_vdev;
2777	nvlist_t *label;
2778	uberblock_t *ub = &spa->spa_uberblock;
2779	boolean_t activity_check = B_FALSE;
2780
2781	/*
2782	 * If we are opening the checkpointed state of the pool by
2783	 * rewinding to it, at this point we will have written the
2784	 * checkpointed uberblock to the vdev labels, so searching
2785	 * the labels will find the right uberblock.  However, if
2786	 * we are opening the checkpointed state read-only, we have
2787	 * not modified the labels. Therefore, we must ignore the
2788	 * labels and continue using the spa_uberblock that was set
2789	 * by spa_ld_checkpoint_rewind.
2790	 *
2791	 * Note that it would be fine to ignore the labels when
2792	 * rewinding (opening writeable) as well. However, if we
2793	 * crash just after writing the labels, we will end up
2794	 * searching the labels. Doing so in the common case means
2795	 * that this code path gets exercised normally, rather than
2796	 * just in the edge case.
2797	 */
2798	if (ub->ub_checkpoint_txg != 0 &&
2799	    spa_importing_readonly_checkpoint(spa)) {
2800		spa_ld_select_uberblock_done(spa, ub);
2801		return (0);
2802	}
2803
2804	/*
2805	 * Find the best uberblock.
2806	 */
2807	vdev_uberblock_load(rvd, ub, &label);
2808
2809	/*
2810	 * If we weren't able to find a single valid uberblock, return failure.
2811	 */
2812	if (ub->ub_txg == 0) {
2813		nvlist_free(label);
2814		spa_load_failed(spa, "no valid uberblock found");
2815		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2816	}
2817
2818	spa_load_note(spa, "using uberblock with txg=%llu",
2819	    (u_longlong_t)ub->ub_txg);
2820
2821	/*
2822	 * For pools which have the multihost property on determine if the
2823	 * pool is truly inactive and can be safely imported.  Prevent
2824	 * hosts which don't have a hostid set from importing the pool.
2825	 */
2826	activity_check = spa_activity_check_required(spa, ub, label,
2827	    spa->spa_config);
2828	if (activity_check) {
2829		if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
2830		    spa_get_hostid() == 0) {
2831			nvlist_free(label);
2832			fnvlist_add_uint64(spa->spa_load_info,
2833			    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
2834			return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
2835		}
2836
2837		int error = spa_activity_check(spa, ub, spa->spa_config);
2838		if (error) {
2839			nvlist_free(label);
2840			return (error);
2841		}
2842
2843		fnvlist_add_uint64(spa->spa_load_info,
2844		    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
2845		fnvlist_add_uint64(spa->spa_load_info,
2846		    ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
2847	}
2848
2849	/*
2850	 * If the pool has an unsupported version we can't open it.
2851	 */
2852	if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2853		nvlist_free(label);
2854		spa_load_failed(spa, "version %llu is not supported",
2855		    (u_longlong_t)ub->ub_version);
2856		return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2857	}
2858
2859	if (ub->ub_version >= SPA_VERSION_FEATURES) {
2860		nvlist_t *features;
2861
2862		/*
2863		 * If we weren't able to find what's necessary for reading the
2864		 * MOS in the label, return failure.
2865		 */
2866		if (label == NULL) {
2867			spa_load_failed(spa, "label config unavailable");
2868			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2869			    ENXIO));
2870		}
2871
2872		if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
2873		    &features) != 0) {
2874			nvlist_free(label);
2875			spa_load_failed(spa, "invalid label: '%s' missing",
2876			    ZPOOL_CONFIG_FEATURES_FOR_READ);
2877			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2878			    ENXIO));
2879		}
2880
2881		/*
2882		 * Update our in-core representation with the definitive values
2883		 * from the label.
2884		 */
2885		nvlist_free(spa->spa_label_features);
2886		VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2887	}
2888
2889	nvlist_free(label);
2890
2891	/*
2892	 * Look through entries in the label nvlist's features_for_read. If
2893	 * there is a feature listed there which we don't understand then we
2894	 * cannot open a pool.
2895	 */
2896	if (ub->ub_version >= SPA_VERSION_FEATURES) {
2897		nvlist_t *unsup_feat;
2898
2899		VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2900		    0);
2901
2902		for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2903		    NULL); nvp != NULL;
2904		    nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2905			if (!zfeature_is_supported(nvpair_name(nvp))) {
2906				VERIFY(nvlist_add_string(unsup_feat,
2907				    nvpair_name(nvp), "") == 0);
2908			}
2909		}
2910
2911		if (!nvlist_empty(unsup_feat)) {
2912			VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2913			    ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2914			nvlist_free(unsup_feat);
2915			spa_load_failed(spa, "some features are unsupported");
2916			return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2917			    ENOTSUP));
2918		}
2919
2920		nvlist_free(unsup_feat);
2921	}
2922
2923	if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2924		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2925		spa_try_repair(spa, spa->spa_config);
2926		spa_config_exit(spa, SCL_ALL, FTAG);
2927		nvlist_free(spa->spa_config_splitting);
2928		spa->spa_config_splitting = NULL;
2929	}
2930
2931	/*
2932	 * Initialize internal SPA structures.
2933	 */
2934	spa_ld_select_uberblock_done(spa, ub);
2935
2936	return (0);
2937}
2938
2939static int
2940spa_ld_open_rootbp(spa_t *spa)
2941{
2942	int error = 0;
2943	vdev_t *rvd = spa->spa_root_vdev;
2944
2945	error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2946	if (error != 0) {
2947		spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
2948		    "[error=%d]", error);
2949		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2950	}
2951	spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2952
2953	return (0);
2954}
2955
2956static int
2957spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
2958    boolean_t reloading)
2959{
2960	vdev_t *mrvd, *rvd = spa->spa_root_vdev;
2961	nvlist_t *nv, *mos_config, *policy;
2962	int error = 0, copy_error;
2963	uint64_t healthy_tvds, healthy_tvds_mos;
2964	uint64_t mos_config_txg;
2965
2966	if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
2967	    != 0)
2968		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2969
2970	/*
2971	 * If we're assembling a pool from a split, the config provided is
2972	 * already trusted so there is nothing to do.
2973	 */
2974	if (type == SPA_IMPORT_ASSEMBLE)
2975		return (0);
2976
2977	healthy_tvds = spa_healthy_core_tvds(spa);
2978
2979	if (load_nvlist(spa, spa->spa_config_object, &mos_config)
2980	    != 0) {
2981		spa_load_failed(spa, "unable to retrieve MOS config");
2982		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2983	}
2984
2985	/*
2986	 * If we are doing an open, pool owner wasn't verified yet, thus do
2987	 * the verification here.
2988	 */
2989	if (spa->spa_load_state == SPA_LOAD_OPEN) {
2990		error = spa_verify_host(spa, mos_config);
2991		if (error != 0) {
2992			nvlist_free(mos_config);
2993			return (error);
2994		}
2995	}
2996
2997	nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
2998
2999	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3000
3001	/*
3002	 * Build a new vdev tree from the trusted config
3003	 */
3004	VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
3005
3006	/*
3007	 * Vdev paths in the MOS may be obsolete. If the untrusted config was
3008	 * obtained by scanning /dev/dsk, then it will have the right vdev
3009	 * paths. We update the trusted MOS config with this information.
3010	 * We first try to copy the paths with vdev_copy_path_strict, which
3011	 * succeeds only when both configs have exactly the same vdev tree.
3012	 * If that fails, we fall back to a more flexible method that has a
3013	 * best effort policy.
3014	 */
3015	copy_error = vdev_copy_path_strict(rvd, mrvd);
3016	if (copy_error != 0 || spa_load_print_vdev_tree) {
3017		spa_load_note(spa, "provided vdev tree:");
3018		vdev_dbgmsg_print_tree(rvd, 2);
3019		spa_load_note(spa, "MOS vdev tree:");
3020		vdev_dbgmsg_print_tree(mrvd, 2);
3021	}
3022	if (copy_error != 0) {
3023		spa_load_note(spa, "vdev_copy_path_strict failed, falling "
3024		    "back to vdev_copy_path_relaxed");
3025		vdev_copy_path_relaxed(rvd, mrvd);
3026	}
3027
3028	vdev_close(rvd);
3029	vdev_free(rvd);
3030	spa->spa_root_vdev = mrvd;
3031	rvd = mrvd;
3032	spa_config_exit(spa, SCL_ALL, FTAG);
3033
3034	/*
3035	 * We will use spa_config if we decide to reload the spa or if spa_load
3036	 * fails and we rewind. We must thus regenerate the config using the
3037	 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
3038	 * pass settings on how to load the pool and is not stored in the MOS.
3039	 * We copy it over to our new, trusted config.
3040	 */
3041	mos_config_txg = fnvlist_lookup_uint64(mos_config,
3042	    ZPOOL_CONFIG_POOL_TXG);
3043	nvlist_free(mos_config);
3044	mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
3045	if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
3046	    &policy) == 0)
3047		fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
3048	spa_config_set(spa, mos_config);
3049	spa->spa_config_source = SPA_CONFIG_SRC_MOS;
3050
3051	/*
3052	 * Now that we got the config from the MOS, we should be more strict
3053	 * in checking blkptrs and can make assumptions about the consistency
3054	 * of the vdev tree. spa_trust_config must be set to true before opening
3055	 * vdevs in order for them to be writeable.
3056	 */
3057	spa->spa_trust_config = B_TRUE;
3058
3059	/*
3060	 * Open and validate the new vdev tree
3061	 */
3062	error = spa_ld_open_vdevs(spa);
3063	if (error != 0)
3064		return (error);
3065
3066	error = spa_ld_validate_vdevs(spa);
3067	if (error != 0)
3068		return (error);
3069
3070	if (copy_error != 0 || spa_load_print_vdev_tree) {
3071		spa_load_note(spa, "final vdev tree:");
3072		vdev_dbgmsg_print_tree(rvd, 2);
3073	}
3074
3075	if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
3076	    !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
3077		/*
3078		 * Sanity check to make sure that we are indeed loading the
3079		 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
3080		 * in the config provided and they happened to be the only ones
3081		 * to have the latest uberblock, we could involuntarily perform
3082		 * an extreme rewind.
3083		 */
3084		healthy_tvds_mos = spa_healthy_core_tvds(spa);
3085		if (healthy_tvds_mos - healthy_tvds >=
3086		    SPA_SYNC_MIN_VDEVS) {
3087			spa_load_note(spa, "config provided misses too many "
3088			    "top-level vdevs compared to MOS (%lld vs %lld). ",
3089			    (u_longlong_t)healthy_tvds,
3090			    (u_longlong_t)healthy_tvds_mos);
3091			spa_load_note(spa, "vdev tree:");
3092			vdev_dbgmsg_print_tree(rvd, 2);
3093			if (reloading) {
3094				spa_load_failed(spa, "config was already "
3095				    "provided from MOS. Aborting.");
3096				return (spa_vdev_err(rvd,
3097				    VDEV_AUX_CORRUPT_DATA, EIO));
3098			}
3099			spa_load_note(spa, "spa must be reloaded using MOS "
3100			    "config");
3101			return (SET_ERROR(EAGAIN));
3102		}
3103	}
3104
3105	error = spa_check_for_missing_logs(spa);
3106	if (error != 0)
3107		return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
3108
3109	if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
3110		spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
3111		    "guid sum (%llu != %llu)",
3112		    (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
3113		    (u_longlong_t)rvd->vdev_guid_sum);
3114		return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
3115		    ENXIO));
3116	}
3117
3118	return (0);
3119}
3120
3121static int
3122spa_ld_open_indirect_vdev_metadata(spa_t *spa)
3123{
3124	int error = 0;
3125	vdev_t *rvd = spa->spa_root_vdev;
3126
3127	/*
3128	 * Everything that we read before spa_remove_init() must be stored
3129	 * on concreted vdevs.  Therefore we do this as early as possible.
3130	 */
3131	error = spa_remove_init(spa);
3132	if (error != 0) {
3133		spa_load_failed(spa, "spa_remove_init failed [error=%d]",
3134		    error);
3135		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3136	}
3137
3138	/*
3139	 * Retrieve information needed to condense indirect vdev mappings.
3140	 */
3141	error = spa_condense_init(spa);
3142	if (error != 0) {
3143		spa_load_failed(spa, "spa_condense_init failed [error=%d]",
3144		    error);
3145		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3146	}
3147
3148	return (0);
3149}
3150
3151static int
3152spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
3153{
3154	int error = 0;
3155	vdev_t *rvd = spa->spa_root_vdev;
3156
3157	if (spa_version(spa) >= SPA_VERSION_FEATURES) {
3158		boolean_t missing_feat_read = B_FALSE;
3159		nvlist_t *unsup_feat, *enabled_feat;
3160
3161		if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
3162		    &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
3163			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3164		}
3165
3166		if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
3167		    &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
3168			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3169		}
3170
3171		if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
3172		    &spa->spa_feat_desc_obj, B_TRUE) != 0) {
3173			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3174		}
3175
3176		enabled_feat = fnvlist_alloc();
3177		unsup_feat = fnvlist_alloc();
3178
3179		if (!spa_features_check(spa, B_FALSE,
3180		    unsup_feat, enabled_feat))
3181			missing_feat_read = B_TRUE;
3182
3183		if (spa_writeable(spa) ||
3184		    spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3185			if (!spa_features_check(spa, B_TRUE,
3186			    unsup_feat, enabled_feat)) {
3187				*missing_feat_writep = B_TRUE;
3188			}
3189		}
3190
3191		fnvlist_add_nvlist(spa->spa_load_info,
3192		    ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3193
3194		if (!nvlist_empty(unsup_feat)) {
3195			fnvlist_add_nvlist(spa->spa_load_info,
3196			    ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3197		}
3198
3199		fnvlist_free(enabled_feat);
3200		fnvlist_free(unsup_feat);
3201
3202		if (!missing_feat_read) {
3203			fnvlist_add_boolean(spa->spa_load_info,
3204			    ZPOOL_CONFIG_CAN_RDONLY);
3205		}
3206
3207		/*
3208		 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3209		 * twofold: to determine whether the pool is available for
3210		 * import in read-write mode and (if it is not) whether the
3211		 * pool is available for import in read-only mode. If the pool
3212		 * is available for import in read-write mode, it is displayed
3213		 * as available in userland; if it is not available for import
3214		 * in read-only mode, it is displayed as unavailable in
3215		 * userland. If the pool is available for import in read-only
3216		 * mode but not read-write mode, it is displayed as unavailable
3217		 * in userland with a special note that the pool is actually
3218		 * available for open in read-only mode.
3219		 *
3220		 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3221		 * missing a feature for write, we must first determine whether
3222		 * the pool can be opened read-only before returning to
3223		 * userland in order to know whether to display the
3224		 * abovementioned note.
3225		 */
3226		if (missing_feat_read || (*missing_feat_writep &&
3227		    spa_writeable(spa))) {
3228			spa_load_failed(spa, "pool uses unsupported features");
3229			return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3230			    ENOTSUP));
3231		}
3232
3233		/*
3234		 * Load refcounts for ZFS features from disk into an in-memory
3235		 * cache during SPA initialization.
3236		 */
3237		for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
3238			uint64_t refcount;
3239
3240			error = feature_get_refcount_from_disk(spa,
3241			    &spa_feature_table[i], &refcount);
3242			if (error == 0) {
3243				spa->spa_feat_refcount_cache[i] = refcount;
3244			} else if (error == ENOTSUP) {
3245				spa->spa_feat_refcount_cache[i] =
3246				    SPA_FEATURE_DISABLED;
3247			} else {
3248				spa_load_failed(spa, "error getting refcount "
3249				    "for feature %s [error=%d]",
3250				    spa_feature_table[i].fi_guid, error);
3251				return (spa_vdev_err(rvd,
3252				    VDEV_AUX_CORRUPT_DATA, EIO));
3253			}
3254		}
3255	}
3256
3257	if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3258		if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
3259		    &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
3260			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3261	}
3262
3263	return (0);
3264}
3265
3266static int
3267spa_ld_load_special_directories(spa_t *spa)
3268{
3269	int error = 0;
3270	vdev_t *rvd = spa->spa_root_vdev;
3271
3272	spa->spa_is_initializing = B_TRUE;
3273	error = dsl_pool_open(spa->spa_dsl_pool);
3274	spa->spa_is_initializing = B_FALSE;
3275	if (error != 0) {
3276		spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3277		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3278	}
3279
3280	return (0);
3281}
3282
3283static int
3284spa_ld_get_props(spa_t *spa)
3285{
3286	int error = 0;
3287	uint64_t obj;
3288	vdev_t *rvd = spa->spa_root_vdev;
3289
3290	/* Grab the secret checksum salt from the MOS. */
3291	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3292	    DMU_POOL_CHECKSUM_SALT, 1,
3293	    sizeof (spa->spa_cksum_salt.zcs_bytes),
3294	    spa->spa_cksum_salt.zcs_bytes);
3295	if (error == ENOENT) {
3296		/* Generate a new salt for subsequent use */
3297		(void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3298		    sizeof (spa->spa_cksum_salt.zcs_bytes));
3299	} else if (error != 0) {
3300		spa_load_failed(spa, "unable to retrieve checksum salt from "
3301		    "MOS [error=%d]", error);
3302		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3303	}
3304
3305	if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3306		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3307	error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3308	if (error != 0) {
3309		spa_load_failed(spa, "error opening deferred-frees bpobj "
3310		    "[error=%d]", error);
3311		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3312	}
3313
3314	/*
3315	 * Load the bit that tells us to use the new accounting function
3316	 * (raid-z deflation).  If we have an older pool, this will not
3317	 * be present.
3318	 */
3319	error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3320	if (error != 0 && error != ENOENT)
3321		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3322
3323	error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3324	    &spa->spa_creation_version, B_FALSE);
3325	if (error != 0 && error != ENOENT)
3326		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3327
3328	/*
3329	 * Load the persistent error log.  If we have an older pool, this will
3330	 * not be present.
3331	 */
3332	error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3333	    B_FALSE);
3334	if (error != 0 && error != ENOENT)
3335		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3336
3337	error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3338	    &spa->spa_errlog_scrub, B_FALSE);
3339	if (error != 0 && error != ENOENT)
3340		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3341
3342	/*
3343	 * Load the history object.  If we have an older pool, this
3344	 * will not be present.
3345	 */
3346	error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3347	if (error != 0 && error != ENOENT)
3348		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3349
3350	/*
3351	 * Load the per-vdev ZAP map. If we have an older pool, this will not
3352	 * be present; in this case, defer its creation to a later time to
3353	 * avoid dirtying the MOS this early / out of sync context. See
3354	 * spa_sync_config_object.
3355	 */
3356
3357	/* The sentinel is only available in the MOS config. */
3358	nvlist_t *mos_config;
3359	if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3360		spa_load_failed(spa, "unable to retrieve MOS config");
3361		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3362	}
3363
3364	error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3365	    &spa->spa_all_vdev_zaps, B_FALSE);
3366
3367	if (error == ENOENT) {
3368		VERIFY(!nvlist_exists(mos_config,
3369		    ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3370		spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3371		ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3372	} else if (error != 0) {
3373		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3374	} else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3375		/*
3376		 * An older version of ZFS overwrote the sentinel value, so
3377		 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3378		 * destruction to later; see spa_sync_config_object.
3379		 */
3380		spa->spa_avz_action = AVZ_ACTION_DESTROY;
3381		/*
3382		 * We're assuming that no vdevs have had their ZAPs created
3383		 * before this. Better be sure of it.
3384		 */
3385		ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3386	}
3387	nvlist_free(mos_config);
3388
3389	spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3390
3391	error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3392	    B_FALSE);
3393	if (error && error != ENOENT)
3394		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3395
3396	if (error == 0) {
3397		uint64_t autoreplace;
3398
3399		spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3400		spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3401		spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3402		spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3403		spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3404		spa_prop_find(spa, ZPOOL_PROP_MULTIHOST, &spa->spa_multihost);
3405		spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3406		    &spa->spa_dedup_ditto);
3407
3408		spa->spa_autoreplace = (autoreplace != 0);
3409	}
3410
3411	/*
3412	 * If we are importing a pool with missing top-level vdevs,
3413	 * we enforce that the pool doesn't panic or get suspended on
3414	 * error since the likelihood of missing data is extremely high.
3415	 */
3416	if (spa->spa_missing_tvds > 0 &&
3417	    spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3418	    spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3419		spa_load_note(spa, "forcing failmode to 'continue' "
3420		    "as some top level vdevs are missing");
3421		spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3422	}
3423
3424	return (0);
3425}
3426
3427static int
3428spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3429{
3430	int error = 0;
3431	vdev_t *rvd = spa->spa_root_vdev;
3432
3433	/*
3434	 * If we're assembling the pool from the split-off vdevs of
3435	 * an existing pool, we don't want to attach the spares & cache
3436	 * devices.
3437	 */
3438
3439	/*
3440	 * Load any hot spares for this pool.
3441	 */
3442	error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3443	    B_FALSE);
3444	if (error != 0 && error != ENOENT)
3445		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3446	if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3447		ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3448		if (load_nvlist(spa, spa->spa_spares.sav_object,
3449		    &spa->spa_spares.sav_config) != 0) {
3450			spa_load_failed(spa, "error loading spares nvlist");
3451			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3452		}
3453
3454		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3455		spa_load_spares(spa);
3456		spa_config_exit(spa, SCL_ALL, FTAG);
3457	} else if (error == 0) {
3458		spa->spa_spares.sav_sync = B_TRUE;
3459	}
3460
3461	/*
3462	 * Load any level 2 ARC devices for this pool.
3463	 */
3464	error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3465	    &spa->spa_l2cache.sav_object, B_FALSE);
3466	if (error != 0 && error != ENOENT)
3467		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3468	if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3469		ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3470		if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3471		    &spa->spa_l2cache.sav_config) != 0) {
3472			spa_load_failed(spa, "error loading l2cache nvlist");
3473			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3474		}
3475
3476		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3477		spa_load_l2cache(spa);
3478		spa_config_exit(spa, SCL_ALL, FTAG);
3479	} else if (error == 0) {
3480		spa->spa_l2cache.sav_sync = B_TRUE;
3481	}
3482
3483	return (0);
3484}
3485
3486static int
3487spa_ld_load_vdev_metadata(spa_t *spa)
3488{
3489	int error = 0;
3490	vdev_t *rvd = spa->spa_root_vdev;
3491
3492	/*
3493	 * If the 'multihost' property is set, then never allow a pool to
3494	 * be imported when the system hostid is zero.  The exception to
3495	 * this rule is zdb which is always allowed to access pools.
3496	 */
3497	if (spa_multihost(spa) && spa_get_hostid() == 0 &&
3498	    (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP) == 0) {
3499		fnvlist_add_uint64(spa->spa_load_info,
3500		    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3501		return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3502	}
3503
3504	/*
3505	 * If the 'autoreplace' property is set, then post a resource notifying
3506	 * the ZFS DE that it should not issue any faults for unopenable
3507	 * devices.  We also iterate over the vdevs, and post a sysevent for any
3508	 * unopenable vdevs so that the normal autoreplace handler can take
3509	 * over.
3510	 */
3511	if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3512		spa_check_removed(spa->spa_root_vdev);
3513		/*
3514		 * For the import case, this is done in spa_import(), because
3515		 * at this point we're using the spare definitions from
3516		 * the MOS config, not necessarily from the userland config.
3517		 */
3518		if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3519			spa_aux_check_removed(&spa->spa_spares);
3520			spa_aux_check_removed(&spa->spa_l2cache);
3521		}
3522	}
3523
3524	/*
3525	 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3526	 */
3527	error = vdev_load(rvd);
3528	if (error != 0) {
3529		spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3530		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3531	}
3532
3533	/*
3534	 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3535	 */
3536	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3537	vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3538	spa_config_exit(spa, SCL_ALL, FTAG);
3539
3540	return (0);
3541}
3542
3543static int
3544spa_ld_load_dedup_tables(spa_t *spa)
3545{
3546	int error = 0;
3547	vdev_t *rvd = spa->spa_root_vdev;
3548
3549	error = ddt_load(spa);
3550	if (error != 0) {
3551		spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3552		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3553	}
3554
3555	return (0);
3556}
3557
3558static int
3559spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3560{
3561	vdev_t *rvd = spa->spa_root_vdev;
3562
3563	if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3564		boolean_t missing = spa_check_logs(spa);
3565		if (missing) {
3566			if (spa->spa_missing_tvds != 0) {
3567				spa_load_note(spa, "spa_check_logs failed "
3568				    "so dropping the logs");
3569			} else {
3570				*ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3571				spa_load_failed(spa, "spa_check_logs failed");
3572				return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3573				    ENXIO));
3574			}
3575		}
3576	}
3577
3578	return (0);
3579}
3580
3581static int
3582spa_ld_verify_pool_data(spa_t *spa)
3583{
3584	int error = 0;
3585	vdev_t *rvd = spa->spa_root_vdev;
3586
3587	/*
3588	 * We've successfully opened the pool, verify that we're ready
3589	 * to start pushing transactions.
3590	 */
3591	if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3592		error = spa_load_verify(spa);
3593		if (error != 0) {
3594			spa_load_failed(spa, "spa_load_verify failed "
3595			    "[error=%d]", error);
3596			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3597			    error));
3598		}
3599	}
3600
3601	return (0);
3602}
3603
3604static void
3605spa_ld_claim_log_blocks(spa_t *spa)
3606{
3607	dmu_tx_t *tx;
3608	dsl_pool_t *dp = spa_get_dsl(spa);
3609
3610	/*
3611	 * Claim log blocks that haven't been committed yet.
3612	 * This must all happen in a single txg.
3613	 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3614	 * invoked from zil_claim_log_block()'s i/o done callback.
3615	 * Price of rollback is that we abandon the log.
3616	 */
3617	spa->spa_claiming = B_TRUE;
3618
3619	tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3620	(void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3621	    zil_claim, tx, DS_FIND_CHILDREN);
3622	dmu_tx_commit(tx);
3623
3624	spa->spa_claiming = B_FALSE;
3625
3626	spa_set_log_state(spa, SPA_LOG_GOOD);
3627}
3628
3629static void
3630spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3631    boolean_t update_config_cache)
3632{
3633	vdev_t *rvd = spa->spa_root_vdev;
3634	int need_update = B_FALSE;
3635
3636	/*
3637	 * If the config cache is stale, or we have uninitialized
3638	 * metaslabs (see spa_vdev_add()), then update the config.
3639	 *
3640	 * If this is a verbatim import, trust the current
3641	 * in-core spa_config and update the disk labels.
3642	 */
3643	if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
3644	    spa->spa_load_state == SPA_LOAD_IMPORT ||
3645	    spa->spa_load_state == SPA_LOAD_RECOVER ||
3646	    (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3647		need_update = B_TRUE;
3648
3649	for (int c = 0; c < rvd->vdev_children; c++)
3650		if (rvd->vdev_child[c]->vdev_ms_array == 0)
3651			need_update = B_TRUE;
3652
3653	/*
3654	 * Update the config cache asychronously in case we're the
3655	 * root pool, in which case the config cache isn't writable yet.
3656	 */
3657	if (need_update)
3658		spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3659}
3660
3661static void
3662spa_ld_prepare_for_reload(spa_t *spa)
3663{
3664	int mode = spa->spa_mode;
3665	int async_suspended = spa->spa_async_suspended;
3666
3667	spa_unload(spa);
3668	spa_deactivate(spa);
3669	spa_activate(spa, mode);
3670
3671	/*
3672	 * We save the value of spa_async_suspended as it gets reset to 0 by
3673	 * spa_unload(). We want to restore it back to the original value before
3674	 * returning as we might be calling spa_async_resume() later.
3675	 */
3676	spa->spa_async_suspended = async_suspended;
3677}
3678
3679static int
3680spa_ld_read_checkpoint_txg(spa_t *spa)
3681{
3682	uberblock_t checkpoint;
3683	int error = 0;
3684
3685	ASSERT0(spa->spa_checkpoint_txg);
3686	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3687
3688	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3689	    DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3690	    sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3691
3692	if (error == ENOENT)
3693		return (0);
3694
3695	if (error != 0)
3696		return (error);
3697
3698	ASSERT3U(checkpoint.ub_txg, !=, 0);
3699	ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3700	ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3701	spa->spa_checkpoint_txg = checkpoint.ub_txg;
3702	spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3703
3704	return (0);
3705}
3706
3707static int
3708spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
3709{
3710	int error = 0;
3711
3712	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3713	ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3714
3715	/*
3716	 * Never trust the config that is provided unless we are assembling
3717	 * a pool following a split.
3718	 * This means don't trust blkptrs and the vdev tree in general. This
3719	 * also effectively puts the spa in read-only mode since
3720	 * spa_writeable() checks for spa_trust_config to be true.
3721	 * We will later load a trusted config from the MOS.
3722	 */
3723	if (type != SPA_IMPORT_ASSEMBLE)
3724		spa->spa_trust_config = B_FALSE;
3725
3726	/*
3727	 * Parse the config provided to create a vdev tree.
3728	 */
3729	error = spa_ld_parse_config(spa, type);
3730	if (error != 0)
3731		return (error);
3732
3733	/*
3734	 * Now that we have the vdev tree, try to open each vdev. This involves
3735	 * opening the underlying physical device, retrieving its geometry and
3736	 * probing the vdev with a dummy I/O. The state of each vdev will be set
3737	 * based on the success of those operations. After this we'll be ready
3738	 * to read from the vdevs.
3739	 */
3740	error = spa_ld_open_vdevs(spa);
3741	if (error != 0)
3742		return (error);
3743
3744	/*
3745	 * Read the label of each vdev and make sure that the GUIDs stored
3746	 * there match the GUIDs in the config provided.
3747	 * If we're assembling a new pool that's been split off from an
3748	 * existing pool, the labels haven't yet been updated so we skip
3749	 * validation for now.
3750	 */
3751	if (type != SPA_IMPORT_ASSEMBLE) {
3752		error = spa_ld_validate_vdevs(spa);
3753		if (error != 0)
3754			return (error);
3755	}
3756
3757	/*
3758	 * Read all vdev labels to find the best uberblock (i.e. latest,
3759	 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3760	 * get the list of features required to read blkptrs in the MOS from
3761	 * the vdev label with the best uberblock and verify that our version
3762	 * of zfs supports them all.
3763	 */
3764	error = spa_ld_select_uberblock(spa, type);
3765	if (error != 0)
3766		return (error);
3767
3768	/*
3769	 * Pass that uberblock to the dsl_pool layer which will open the root
3770	 * blkptr. This blkptr points to the latest version of the MOS and will
3771	 * allow us to read its contents.
3772	 */
3773	error = spa_ld_open_rootbp(spa);
3774	if (error != 0)
3775		return (error);
3776
3777	return (0);
3778}
3779
3780static int
3781spa_ld_checkpoint_rewind(spa_t *spa)
3782{
3783	uberblock_t checkpoint;
3784	int error = 0;
3785
3786	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3787	ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3788
3789	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3790	    DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3791	    sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3792
3793	if (error != 0) {
3794		spa_load_failed(spa, "unable to retrieve checkpointed "
3795		    "uberblock from the MOS config [error=%d]", error);
3796
3797		if (error == ENOENT)
3798			error = ZFS_ERR_NO_CHECKPOINT;
3799
3800		return (error);
3801	}
3802
3803	ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
3804	ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
3805
3806	/*
3807	 * We need to update the txg and timestamp of the checkpointed
3808	 * uberblock to be higher than the latest one. This ensures that
3809	 * the checkpointed uberblock is selected if we were to close and
3810	 * reopen the pool right after we've written it in the vdev labels.
3811	 * (also see block comment in vdev_uberblock_compare)
3812	 */
3813	checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
3814	checkpoint.ub_timestamp = gethrestime_sec();
3815
3816	/*
3817	 * Set current uberblock to be the checkpointed uberblock.
3818	 */
3819	spa->spa_uberblock = checkpoint;
3820
3821	/*
3822	 * If we are doing a normal rewind, then the pool is open for
3823	 * writing and we sync the "updated" checkpointed uberblock to
3824	 * disk. Once this is done, we've basically rewound the whole
3825	 * pool and there is no way back.
3826	 *
3827	 * There are cases when we don't want to attempt and sync the
3828	 * checkpointed uberblock to disk because we are opening a
3829	 * pool as read-only. Specifically, verifying the checkpointed
3830	 * state with zdb, and importing the checkpointed state to get
3831	 * a "preview" of its content.
3832	 */
3833	if (spa_writeable(spa)) {
3834		vdev_t *rvd = spa->spa_root_vdev;
3835
3836		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3837		vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
3838		int svdcount = 0;
3839		int children = rvd->vdev_children;
3840		int c0 = spa_get_random(children);
3841
3842		for (int c = 0; c < children; c++) {
3843			vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
3844
3845			/* Stop when revisiting the first vdev */
3846			if (c > 0 && svd[0] == vd)
3847				break;
3848
3849			if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
3850			    !vdev_is_concrete(vd))
3851				continue;
3852
3853			svd[svdcount++] = vd;
3854			if (svdcount == SPA_SYNC_MIN_VDEVS)
3855				break;
3856		}
3857		error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
3858		if (error == 0)
3859			spa->spa_last_synced_guid = rvd->vdev_guid;
3860		spa_config_exit(spa, SCL_ALL, FTAG);
3861
3862		if (error != 0) {
3863			spa_load_failed(spa, "failed to write checkpointed "
3864			    "uberblock to the vdev labels [error=%d]", error);
3865			return (error);
3866		}
3867	}
3868
3869	return (0);
3870}
3871
3872static int
3873spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
3874    boolean_t *update_config_cache)
3875{
3876	int error;
3877
3878	/*
3879	 * Parse the config for pool, open and validate vdevs,
3880	 * select an uberblock, and use that uberblock to open
3881	 * the MOS.
3882	 */
3883	error = spa_ld_mos_init(spa, type);
3884	if (error != 0)
3885		return (error);
3886
3887	/*
3888	 * Retrieve the trusted config stored in the MOS and use it to create
3889	 * a new, exact version of the vdev tree, then reopen all vdevs.
3890	 */
3891	error = spa_ld_trusted_config(spa, type, B_FALSE);
3892	if (error == EAGAIN) {
3893		if (update_config_cache != NULL)
3894			*update_config_cache = B_TRUE;
3895
3896		/*
3897		 * Redo the loading process with the trusted config if it is
3898		 * too different from the untrusted config.
3899		 */
3900		spa_ld_prepare_for_reload(spa);
3901		spa_load_note(spa, "RELOADING");
3902		error = spa_ld_mos_init(spa, type);
3903		if (error != 0)
3904			return (error);
3905
3906		error = spa_ld_trusted_config(spa, type, B_TRUE);
3907		if (error != 0)
3908			return (error);
3909
3910	} else if (error != 0) {
3911		return (error);
3912	}
3913
3914	return (0);
3915}
3916
3917/*
3918 * Load an existing storage pool, using the config provided. This config
3919 * describes which vdevs are part of the pool and is later validated against
3920 * partial configs present in each vdev's label and an entire copy of the
3921 * config stored in the MOS.
3922 */
3923static int
3924spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
3925{
3926	int error = 0;
3927	boolean_t missing_feat_write = B_FALSE;
3928	boolean_t checkpoint_rewind =
3929	    (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3930	boolean_t update_config_cache = B_FALSE;
3931
3932	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3933	ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3934
3935	spa_load_note(spa, "LOADING");
3936
3937	error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
3938	if (error != 0)
3939		return (error);
3940
3941	/*
3942	 * If we are rewinding to the checkpoint then we need to repeat
3943	 * everything we've done so far in this function but this time
3944	 * selecting the checkpointed uberblock and using that to open
3945	 * the MOS.
3946	 */
3947	if (checkpoint_rewind) {
3948		/*
3949		 * If we are rewinding to the checkpoint update config cache
3950		 * anyway.
3951		 */
3952		update_config_cache = B_TRUE;
3953
3954		/*
3955		 * Extract the checkpointed uberblock from the current MOS
3956		 * and use this as the pool's uberblock from now on. If the
3957		 * pool is imported as writeable we also write the checkpoint
3958		 * uberblock to the labels, making the rewind permanent.
3959		 */
3960		error = spa_ld_checkpoint_rewind(spa);
3961		if (error != 0)
3962			return (error);
3963
3964		/*
3965		 * Redo the loading process process again with the
3966		 * checkpointed uberblock.
3967		 */
3968		spa_ld_prepare_for_reload(spa);
3969		spa_load_note(spa, "LOADING checkpointed uberblock");
3970		error = spa_ld_mos_with_trusted_config(spa, type, NULL);
3971		if (error != 0)
3972			return (error);
3973	}
3974
3975	/*
3976	 * Retrieve the checkpoint txg if the pool has a checkpoint.
3977	 */
3978	error = spa_ld_read_checkpoint_txg(spa);
3979	if (error != 0)
3980		return (error);
3981
3982	/*
3983	 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
3984	 * from the pool and their contents were re-mapped to other vdevs. Note
3985	 * that everything that we read before this step must have been
3986	 * rewritten on concrete vdevs after the last device removal was
3987	 * initiated. Otherwise we could be reading from indirect vdevs before
3988	 * we have loaded their mappings.
3989	 */
3990	error = spa_ld_open_indirect_vdev_metadata(spa);
3991	if (error != 0)
3992		return (error);
3993
3994	/*
3995	 * Retrieve the full list of active features from the MOS and check if
3996	 * they are all supported.
3997	 */
3998	error = spa_ld_check_features(spa, &missing_feat_write);
3999	if (error != 0)
4000		return (error);
4001
4002	/*
4003	 * Load several special directories from the MOS needed by the dsl_pool
4004	 * layer.
4005	 */
4006	error = spa_ld_load_special_directories(spa);
4007	if (error != 0)
4008		return (error);
4009
4010	/*
4011	 * Retrieve pool properties from the MOS.
4012	 */
4013	error = spa_ld_get_props(spa);
4014	if (error != 0)
4015		return (error);
4016
4017	/*
4018	 * Retrieve the list of auxiliary devices - cache devices and spares -
4019	 * and open them.
4020	 */
4021	error = spa_ld_open_aux_vdevs(spa, type);
4022	if (error != 0)
4023		return (error);
4024
4025	/*
4026	 * Load the metadata for all vdevs. Also check if unopenable devices
4027	 * should be autoreplaced.
4028	 */
4029	error = spa_ld_load_vdev_metadata(spa);
4030	if (error != 0)
4031		return (error);
4032
4033	error = spa_ld_load_dedup_tables(spa);
4034	if (error != 0)
4035		return (error);
4036
4037	/*
4038	 * Verify the logs now to make sure we don't have any unexpected errors
4039	 * when we claim log blocks later.
4040	 */
4041	error = spa_ld_verify_logs(spa, type, ereport);
4042	if (error != 0)
4043		return (error);
4044
4045	if (missing_feat_write) {
4046		ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
4047
4048		/*
4049		 * At this point, we know that we can open the pool in
4050		 * read-only mode but not read-write mode. We now have enough
4051		 * information and can return to userland.
4052		 */
4053		return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
4054		    ENOTSUP));
4055	}
4056
4057	/*
4058	 * Traverse the last txgs to make sure the pool was left off in a safe
4059	 * state. When performing an extreme rewind, we verify the whole pool,
4060	 * which can take a very long time.
4061	 */
4062	error = spa_ld_verify_pool_data(spa);
4063	if (error != 0)
4064		return (error);
4065
4066	/*
4067	 * Calculate the deflated space for the pool. This must be done before
4068	 * we write anything to the pool because we'd need to update the space
4069	 * accounting using the deflated sizes.
4070	 */
4071	spa_update_dspace(spa);
4072
4073	/*
4074	 * We have now retrieved all the information we needed to open the
4075	 * pool. If we are importing the pool in read-write mode, a few
4076	 * additional steps must be performed to finish the import.
4077	 */
4078	if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
4079	    spa->spa_load_max_txg == UINT64_MAX)) {
4080		uint64_t config_cache_txg = spa->spa_config_txg;
4081
4082		ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
4083
4084		/*
4085		 * In case of a checkpoint rewind, log the original txg
4086		 * of the checkpointed uberblock.
4087		 */
4088		if (checkpoint_rewind) {
4089			spa_history_log_internal(spa, "checkpoint rewind",
4090			    NULL, "rewound state to txg=%llu",
4091			    (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
4092		}
4093
4094		/*
4095		 * Traverse the ZIL and claim all blocks.
4096		 */
4097		spa_ld_claim_log_blocks(spa);
4098
4099		/*
4100		 * Kick-off the syncing thread.
4101		 */
4102		spa->spa_sync_on = B_TRUE;
4103		txg_sync_start(spa->spa_dsl_pool);
4104		mmp_thread_start(spa);
4105
4106		/*
4107		 * Wait for all claims to sync.  We sync up to the highest
4108		 * claimed log block birth time so that claimed log blocks
4109		 * don't appear to be from the future.  spa_claim_max_txg
4110		 * will have been set for us by ZIL traversal operations
4111		 * performed above.
4112		 */
4113		txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
4114
4115		/*
4116		 * Check if we need to request an update of the config. On the
4117		 * next sync, we would update the config stored in vdev labels
4118		 * and the cachefile (by default /etc/zfs/zpool.cache).
4119		 */
4120		spa_ld_check_for_config_update(spa, config_cache_txg,
4121		    update_config_cache);
4122
4123		/*
4124		 * Check all DTLs to see if anything needs resilvering.
4125		 */
4126		if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
4127		    vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
4128			spa_async_request(spa, SPA_ASYNC_RESILVER);
4129
4130		/*
4131		 * Log the fact that we booted up (so that we can detect if
4132		 * we rebooted in the middle of an operation).
4133		 */
4134		spa_history_log_version(spa, "open");
4135
4136		spa_restart_removal(spa);
4137		spa_spawn_aux_threads(spa);
4138
4139		/*
4140		 * Delete any inconsistent datasets.
4141		 *
4142		 * Note:
4143		 * Since we may be issuing deletes for clones here,
4144		 * we make sure to do so after we've spawned all the
4145		 * auxiliary threads above (from which the livelist
4146		 * deletion zthr is part of).
4147		 */
4148		(void) dmu_objset_find(spa_name(spa),
4149		    dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
4150
4151		/*
4152		 * Clean up any stale temporary dataset userrefs.
4153		 */
4154		dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
4155
4156		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4157		vdev_initialize_restart(spa->spa_root_vdev);
4158		spa_config_exit(spa, SCL_CONFIG, FTAG);
4159	}
4160
4161	spa_load_note(spa, "LOADED");
4162
4163	return (0);
4164}
4165
4166static int
4167spa_load_retry(spa_t *spa, spa_load_state_t state)
4168{
4169	int mode = spa->spa_mode;
4170
4171	spa_unload(spa);
4172	spa_deactivate(spa);
4173
4174	spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
4175
4176	spa_activate(spa, mode);
4177	spa_async_suspend(spa);
4178
4179	spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
4180	    (u_longlong_t)spa->spa_load_max_txg);
4181
4182	return (spa_load(spa, state, SPA_IMPORT_EXISTING));
4183}
4184
4185/*
4186 * If spa_load() fails this function will try loading prior txg's. If
4187 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
4188 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
4189 * function will not rewind the pool and will return the same error as
4190 * spa_load().
4191 */
4192static int
4193spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4194    int rewind_flags)
4195{
4196	nvlist_t *loadinfo = NULL;
4197	nvlist_t *config = NULL;
4198	int load_error, rewind_error;
4199	uint64_t safe_rewind_txg;
4200	uint64_t min_txg;
4201
4202	if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4203		spa->spa_load_max_txg = spa->spa_load_txg;
4204		spa_set_log_state(spa, SPA_LOG_CLEAR);
4205	} else {
4206		spa->spa_load_max_txg = max_request;
4207		if (max_request != UINT64_MAX)
4208			spa->spa_extreme_rewind = B_TRUE;
4209	}
4210
4211	load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
4212	if (load_error == 0)
4213		return (0);
4214	if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4215		/*
4216		 * When attempting checkpoint-rewind on a pool with no
4217		 * checkpoint, we should not attempt to load uberblocks
4218		 * from previous txgs when spa_load fails.
4219		 */
4220		ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4221		return (load_error);
4222	}
4223
4224	if (spa->spa_root_vdev != NULL)
4225		config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4226
4227	spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4228	spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4229
4230	if (rewind_flags & ZPOOL_NEVER_REWIND) {
4231		nvlist_free(config);
4232		return (load_error);
4233	}
4234
4235	if (state == SPA_LOAD_RECOVER) {
4236		/* Price of rolling back is discarding txgs, including log */
4237		spa_set_log_state(spa, SPA_LOG_CLEAR);
4238	} else {
4239		/*
4240		 * If we aren't rolling back save the load info from our first
4241		 * import attempt so that we can restore it after attempting
4242		 * to rewind.
4243		 */
4244		loadinfo = spa->spa_load_info;
4245		spa->spa_load_info = fnvlist_alloc();
4246	}
4247
4248	spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4249	safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4250	min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4251	    TXG_INITIAL : safe_rewind_txg;
4252
4253	/*
4254	 * Continue as long as we're finding errors, we're still within
4255	 * the acceptable rewind range, and we're still finding uberblocks
4256	 */
4257	while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4258	    spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4259		if (spa->spa_load_max_txg < safe_rewind_txg)
4260			spa->spa_extreme_rewind = B_TRUE;
4261		rewind_error = spa_load_retry(spa, state);
4262	}
4263
4264	spa->spa_extreme_rewind = B_FALSE;
4265	spa->spa_load_max_txg = UINT64_MAX;
4266
4267	if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4268		spa_config_set(spa, config);
4269	else
4270		nvlist_free(config);
4271
4272	if (state == SPA_LOAD_RECOVER) {
4273		ASSERT3P(loadinfo, ==, NULL);
4274		return (rewind_error);
4275	} else {
4276		/* Store the rewind info as part of the initial load info */
4277		fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4278		    spa->spa_load_info);
4279
4280		/* Restore the initial load info */
4281		fnvlist_free(spa->spa_load_info);
4282		spa->spa_load_info = loadinfo;
4283
4284		return (load_error);
4285	}
4286}
4287
4288/*
4289 * Pool Open/Import
4290 *
4291 * The import case is identical to an open except that the configuration is sent
4292 * down from userland, instead of grabbed from the configuration cache.  For the
4293 * case of an open, the pool configuration will exist in the
4294 * POOL_STATE_UNINITIALIZED state.
4295 *
4296 * The stats information (gen/count/ustats) is used to gather vdev statistics at
4297 * the same time open the pool, without having to keep around the spa_t in some
4298 * ambiguous state.
4299 */
4300static int
4301spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4302    nvlist_t **config)
4303{
4304	spa_t *spa;
4305	spa_load_state_t state = SPA_LOAD_OPEN;
4306	int error;
4307	int locked = B_FALSE;
4308
4309	*spapp = NULL;
4310
4311	/*
4312	 * As disgusting as this is, we need to support recursive calls to this
4313	 * function because dsl_dir_open() is called during spa_load(), and ends
4314	 * up calling spa_open() again.  The real fix is to figure out how to
4315	 * avoid dsl_dir_open() calling this in the first place.
4316	 */
4317	if (mutex_owner(&spa_namespace_lock) != curthread) {
4318		mutex_enter(&spa_namespace_lock);
4319		locked = B_TRUE;
4320	}
4321
4322	if ((spa = spa_lookup(pool)) == NULL) {
4323		if (locked)
4324			mutex_exit(&spa_namespace_lock);
4325		return (SET_ERROR(ENOENT));
4326	}
4327
4328	if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
4329		zpool_load_policy_t policy;
4330
4331		zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
4332		    &policy);
4333		if (policy.zlp_rewind & ZPOOL_DO_REWIND)
4334			state = SPA_LOAD_RECOVER;
4335
4336		spa_activate(spa, spa_mode_global);
4337
4338		if (state != SPA_LOAD_RECOVER)
4339			spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4340		spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
4341
4342		zfs_dbgmsg("spa_open_common: opening %s", pool);
4343		error = spa_load_best(spa, state, policy.zlp_txg,
4344		    policy.zlp_rewind);
4345
4346		if (error == EBADF) {
4347			/*
4348			 * If vdev_validate() returns failure (indicated by
4349			 * EBADF), it indicates that one of the vdevs indicates
4350			 * that the pool has been exported or destroyed.  If
4351			 * this is the case, the config cache is out of sync and
4352			 * we should remove the pool from the namespace.
4353			 */
4354			spa_unload(spa);
4355			spa_deactivate(spa);
4356			spa_write_cachefile(spa, B_TRUE, B_TRUE);
4357			spa_remove(spa);
4358			if (locked)
4359				mutex_exit(&spa_namespace_lock);
4360			return (SET_ERROR(ENOENT));
4361		}
4362
4363		if (error) {
4364			/*
4365			 * We can't open the pool, but we still have useful
4366			 * information: the state of each vdev after the
4367			 * attempted vdev_open().  Return this to the user.
4368			 */
4369			if (config != NULL && spa->spa_config) {
4370				VERIFY(nvlist_dup(spa->spa_config, config,
4371				    KM_SLEEP) == 0);
4372				VERIFY(nvlist_add_nvlist(*config,
4373				    ZPOOL_CONFIG_LOAD_INFO,
4374				    spa->spa_load_info) == 0);
4375			}
4376			spa_unload(spa);
4377			spa_deactivate(spa);
4378			spa->spa_last_open_failed = error;
4379			if (locked)
4380				mutex_exit(&spa_namespace_lock);
4381			*spapp = NULL;
4382			return (error);
4383		}
4384	}
4385
4386	spa_open_ref(spa, tag);
4387
4388	if (config != NULL)
4389		*config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4390
4391	/*
4392	 * If we've recovered the pool, pass back any information we
4393	 * gathered while doing the load.
4394	 */
4395	if (state == SPA_LOAD_RECOVER) {
4396		VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4397		    spa->spa_load_info) == 0);
4398	}
4399
4400	if (locked) {
4401		spa->spa_last_open_failed = 0;
4402		spa->spa_last_ubsync_txg = 0;
4403		spa->spa_load_txg = 0;
4404		mutex_exit(&spa_namespace_lock);
4405	}
4406
4407	*spapp = spa;
4408
4409	return (0);
4410}
4411
4412int
4413spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4414    nvlist_t **config)
4415{
4416	return (spa_open_common(name, spapp, tag, policy, config));
4417}
4418
4419int
4420spa_open(const char *name, spa_t **spapp, void *tag)
4421{
4422	return (spa_open_common(name, spapp, tag, NULL, NULL));
4423}
4424
4425/*
4426 * Lookup the given spa_t, incrementing the inject count in the process,
4427 * preventing it from being exported or destroyed.
4428 */
4429spa_t *
4430spa_inject_addref(char *name)
4431{
4432	spa_t *spa;
4433
4434	mutex_enter(&spa_namespace_lock);
4435	if ((spa = spa_lookup(name)) == NULL) {
4436		mutex_exit(&spa_namespace_lock);
4437		return (NULL);
4438	}
4439	spa->spa_inject_ref++;
4440	mutex_exit(&spa_namespace_lock);
4441
4442	return (spa);
4443}
4444
4445void
4446spa_inject_delref(spa_t *spa)
4447{
4448	mutex_enter(&spa_namespace_lock);
4449	spa->spa_inject_ref--;
4450	mutex_exit(&spa_namespace_lock);
4451}
4452
4453/*
4454 * Add spares device information to the nvlist.
4455 */
4456static void
4457spa_add_spares(spa_t *spa, nvlist_t *config)
4458{
4459	nvlist_t **spares;
4460	uint_t i, nspares;
4461	nvlist_t *nvroot;
4462	uint64_t guid;
4463	vdev_stat_t *vs;
4464	uint_t vsc;
4465	uint64_t pool;
4466
4467	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4468
4469	if (spa->spa_spares.sav_count == 0)
4470		return;
4471
4472	VERIFY(nvlist_lookup_nvlist(config,
4473	    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4474	VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4475	    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4476	if (nspares != 0) {
4477		VERIFY(nvlist_add_nvlist_array(nvroot,
4478		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4479		VERIFY(nvlist_lookup_nvlist_array(nvroot,
4480		    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4481
4482		/*
4483		 * Go through and find any spares which have since been
4484		 * repurposed as an active spare.  If this is the case, update
4485		 * their status appropriately.
4486		 */
4487		for (i = 0; i < nspares; i++) {
4488			VERIFY(nvlist_lookup_uint64(spares[i],
4489			    ZPOOL_CONFIG_GUID, &guid) == 0);
4490			if (spa_spare_exists(guid, &pool, NULL) &&
4491			    pool != 0ULL) {
4492				VERIFY(nvlist_lookup_uint64_array(
4493				    spares[i], ZPOOL_CONFIG_VDEV_STATS,
4494				    (uint64_t **)&vs, &vsc) == 0);
4495				vs->vs_state = VDEV_STATE_CANT_OPEN;
4496				vs->vs_aux = VDEV_AUX_SPARED;
4497			}
4498		}
4499	}
4500}
4501
4502/*
4503 * Add l2cache device information to the nvlist, including vdev stats.
4504 */
4505static void
4506spa_add_l2cache(spa_t *spa, nvlist_t *config)
4507{
4508	nvlist_t **l2cache;
4509	uint_t i, j, nl2cache;
4510	nvlist_t *nvroot;
4511	uint64_t guid;
4512	vdev_t *vd;
4513	vdev_stat_t *vs;
4514	uint_t vsc;
4515
4516	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4517
4518	if (spa->spa_l2cache.sav_count == 0)
4519		return;
4520
4521	VERIFY(nvlist_lookup_nvlist(config,
4522	    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4523	VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4524	    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4525	if (nl2cache != 0) {
4526		VERIFY(nvlist_add_nvlist_array(nvroot,
4527		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4528		VERIFY(nvlist_lookup_nvlist_array(nvroot,
4529		    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4530
4531		/*
4532		 * Update level 2 cache device stats.
4533		 */
4534
4535		for (i = 0; i < nl2cache; i++) {
4536			VERIFY(nvlist_lookup_uint64(l2cache[i],
4537			    ZPOOL_CONFIG_GUID, &guid) == 0);
4538
4539			vd = NULL;
4540			for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4541				if (guid ==
4542				    spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4543					vd = spa->spa_l2cache.sav_vdevs[j];
4544					break;
4545				}
4546			}
4547			ASSERT(vd != NULL);
4548
4549			VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4550			    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4551			    == 0);
4552			vdev_get_stats(vd, vs);
4553		}
4554	}
4555}
4556
4557static void
4558spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4559{
4560	nvlist_t *features;
4561	zap_cursor_t zc;
4562	zap_attribute_t za;
4563
4564	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4565	VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4566
4567	if (spa->spa_feat_for_read_obj != 0) {
4568		for (zap_cursor_init(&zc, spa->spa_meta_objset,
4569		    spa->spa_feat_for_read_obj);
4570		    zap_cursor_retrieve(&zc, &za) == 0;
4571		    zap_cursor_advance(&zc)) {
4572			ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4573			    za.za_num_integers == 1);
4574			VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4575			    za.za_first_integer));
4576		}
4577		zap_cursor_fini(&zc);
4578	}
4579
4580	if (spa->spa_feat_for_write_obj != 0) {
4581		for (zap_cursor_init(&zc, spa->spa_meta_objset,
4582		    spa->spa_feat_for_write_obj);
4583		    zap_cursor_retrieve(&zc, &za) == 0;
4584		    zap_cursor_advance(&zc)) {
4585			ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4586			    za.za_num_integers == 1);
4587			VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4588			    za.za_first_integer));
4589		}
4590		zap_cursor_fini(&zc);
4591	}
4592
4593	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4594	    features) == 0);
4595	nvlist_free(features);
4596}
4597
4598int
4599spa_get_stats(const char *name, nvlist_t **config,
4600    char *altroot, size_t buflen)
4601{
4602	int error;
4603	spa_t *spa;
4604
4605	*config = NULL;
4606	error = spa_open_common(name, &spa, FTAG, NULL, config);
4607
4608	if (spa != NULL) {
4609		/*
4610		 * This still leaves a window of inconsistency where the spares
4611		 * or l2cache devices could change and the config would be
4612		 * self-inconsistent.
4613		 */
4614		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4615
4616		if (*config != NULL) {
4617			uint64_t loadtimes[2];
4618
4619			loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4620			loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4621			VERIFY(nvlist_add_uint64_array(*config,
4622			    ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4623
4624			VERIFY(nvlist_add_uint64(*config,
4625			    ZPOOL_CONFIG_ERRCOUNT,
4626			    spa_get_errlog_size(spa)) == 0);
4627
4628			if (spa_suspended(spa)) {
4629				VERIFY(nvlist_add_uint64(*config,
4630				    ZPOOL_CONFIG_SUSPENDED,
4631				    spa->spa_failmode) == 0);
4632				VERIFY(nvlist_add_uint64(*config,
4633				    ZPOOL_CONFIG_SUSPENDED_REASON,
4634				    spa->spa_suspended) == 0);
4635			}
4636
4637			spa_add_spares(spa, *config);
4638			spa_add_l2cache(spa, *config);
4639			spa_add_feature_stats(spa, *config);
4640		}
4641	}
4642
4643	/*
4644	 * We want to get the alternate root even for faulted pools, so we cheat
4645	 * and call spa_lookup() directly.
4646	 */
4647	if (altroot) {
4648		if (spa == NULL) {
4649			mutex_enter(&spa_namespace_lock);
4650			spa = spa_lookup(name);
4651			if (spa)
4652				spa_altroot(spa, altroot, buflen);
4653			else
4654				altroot[0] = '\0';
4655			spa = NULL;
4656			mutex_exit(&spa_namespace_lock);
4657		} else {
4658			spa_altroot(spa, altroot, buflen);
4659		}
4660	}
4661
4662	if (spa != NULL) {
4663		spa_config_exit(spa, SCL_CONFIG, FTAG);
4664		spa_close(spa, FTAG);
4665	}
4666
4667	return (error);
4668}
4669
4670/*
4671 * Validate that the auxiliary device array is well formed.  We must have an
4672 * array of nvlists, each which describes a valid leaf vdev.  If this is an
4673 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4674 * specified, as long as they are well-formed.
4675 */
4676static int
4677spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4678    spa_aux_vdev_t *sav, const char *config, uint64_t version,
4679    vdev_labeltype_t label)
4680{
4681	nvlist_t **dev;
4682	uint_t i, ndev;
4683	vdev_t *vd;
4684	int error;
4685
4686	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4687
4688	/*
4689	 * It's acceptable to have no devs specified.
4690	 */
4691	if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4692		return (0);
4693
4694	if (ndev == 0)
4695		return (SET_ERROR(EINVAL));
4696
4697	/*
4698	 * Make sure the pool is formatted with a version that supports this
4699	 * device type.
4700	 */
4701	if (spa_version(spa) < version)
4702		return (SET_ERROR(ENOTSUP));
4703
4704	/*
4705	 * Set the pending device list so we correctly handle device in-use
4706	 * checking.
4707	 */
4708	sav->sav_pending = dev;
4709	sav->sav_npending = ndev;
4710
4711	for (i = 0; i < ndev; i++) {
4712		if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4713		    mode)) != 0)
4714			goto out;
4715
4716		if (!vd->vdev_ops->vdev_op_leaf) {
4717			vdev_free(vd);
4718			error = SET_ERROR(EINVAL);
4719			goto out;
4720		}
4721
4722		vd->vdev_top = vd;
4723
4724		if ((error = vdev_open(vd)) == 0 &&
4725		    (error = vdev_label_init(vd, crtxg, label)) == 0) {
4726			VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4727			    vd->vdev_guid) == 0);
4728		}
4729
4730		vdev_free(vd);
4731
4732		if (error &&
4733		    (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
4734			goto out;
4735		else
4736			error = 0;
4737	}
4738
4739out:
4740	sav->sav_pending = NULL;
4741	sav->sav_npending = 0;
4742	return (error);
4743}
4744
4745static int
4746spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
4747{
4748	int error;
4749
4750	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4751
4752	if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4753	    &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
4754	    VDEV_LABEL_SPARE)) != 0) {
4755		return (error);
4756	}
4757
4758	return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4759	    &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
4760	    VDEV_LABEL_L2CACHE));
4761}
4762
4763static void
4764spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
4765    const char *config)
4766{
4767	int i;
4768
4769	if (sav->sav_config != NULL) {
4770		nvlist_t **olddevs;
4771		uint_t oldndevs;
4772		nvlist_t **newdevs;
4773
4774		/*
4775		 * Generate new dev list by concatentating with the
4776		 * current dev list.
4777		 */
4778		VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
4779		    &olddevs, &oldndevs) == 0);
4780
4781		newdevs = kmem_alloc(sizeof (void *) *
4782		    (ndevs + oldndevs), KM_SLEEP);
4783		for (i = 0; i < oldndevs; i++)
4784			VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
4785			    KM_SLEEP) == 0);
4786		for (i = 0; i < ndevs; i++)
4787			VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
4788			    KM_SLEEP) == 0);
4789
4790		VERIFY(nvlist_remove(sav->sav_config, config,
4791		    DATA_TYPE_NVLIST_ARRAY) == 0);
4792
4793		VERIFY(nvlist_add_nvlist_array(sav->sav_config,
4794		    config, newdevs, ndevs + oldndevs) == 0);
4795		for (i = 0; i < oldndevs + ndevs; i++)
4796			nvlist_free(newdevs[i]);
4797		kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
4798	} else {
4799		/*
4800		 * Generate a new dev list.
4801		 */
4802		VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
4803		    KM_SLEEP) == 0);
4804		VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
4805		    devs, ndevs) == 0);
4806	}
4807}
4808
4809/*
4810 * Stop and drop level 2 ARC devices
4811 */
4812void
4813spa_l2cache_drop(spa_t *spa)
4814{
4815	vdev_t *vd;
4816	int i;
4817	spa_aux_vdev_t *sav = &spa->spa_l2cache;
4818
4819	for (i = 0; i < sav->sav_count; i++) {
4820		uint64_t pool;
4821
4822		vd = sav->sav_vdevs[i];
4823		ASSERT(vd != NULL);
4824
4825		if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
4826		    pool != 0ULL && l2arc_vdev_present(vd))
4827			l2arc_remove_vdev(vd);
4828	}
4829}
4830
4831/*
4832 * Pool Creation
4833 */
4834int
4835spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
4836    nvlist_t *zplprops)
4837{
4838	spa_t *spa;
4839	char *altroot = NULL;
4840	vdev_t *rvd;
4841	dsl_pool_t *dp;
4842	dmu_tx_t *tx;
4843	int error = 0;
4844	uint64_t txg = TXG_INITIAL;
4845	nvlist_t **spares, **l2cache;
4846	uint_t nspares, nl2cache;
4847	uint64_t version, obj;
4848	boolean_t has_features;
4849	char *poolname;
4850	nvlist_t *nvl;
4851
4852	if (props == NULL ||
4853	    nvlist_lookup_string(props,
4854	    zpool_prop_to_name(ZPOOL_PROP_TNAME), &poolname) != 0)
4855		poolname = (char *)pool;
4856
4857	/*
4858	 * If this pool already exists, return failure.
4859	 */
4860	mutex_enter(&spa_namespace_lock);
4861	if (spa_lookup(poolname) != NULL) {
4862		mutex_exit(&spa_namespace_lock);
4863		return (SET_ERROR(EEXIST));
4864	}
4865
4866	/*
4867	 * Allocate a new spa_t structure.
4868	 */
4869	nvl = fnvlist_alloc();
4870	fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
4871	(void) nvlist_lookup_string(props,
4872	    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4873	spa = spa_add(poolname, nvl, altroot);
4874	fnvlist_free(nvl);
4875	spa_activate(spa, spa_mode_global);
4876
4877	if (props && (error = spa_prop_validate(spa, props))) {
4878		spa_deactivate(spa);
4879		spa_remove(spa);
4880		mutex_exit(&spa_namespace_lock);
4881		return (error);
4882	}
4883
4884	/*
4885	 * Temporary pool names should never be written to disk.
4886	 */
4887	if (poolname != pool)
4888		spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
4889
4890	has_features = B_FALSE;
4891	for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
4892	    elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
4893		if (zpool_prop_feature(nvpair_name(elem)))
4894			has_features = B_TRUE;
4895	}
4896
4897	if (has_features || nvlist_lookup_uint64(props,
4898	    zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
4899		version = SPA_VERSION;
4900	}
4901	ASSERT(SPA_VERSION_IS_SUPPORTED(version));
4902
4903	spa->spa_first_txg = txg;
4904	spa->spa_uberblock.ub_txg = txg - 1;
4905	spa->spa_uberblock.ub_version = version;
4906	spa->spa_ubsync = spa->spa_uberblock;
4907	spa->spa_load_state = SPA_LOAD_CREATE;
4908	spa->spa_removing_phys.sr_state = DSS_NONE;
4909	spa->spa_removing_phys.sr_removing_vdev = -1;
4910	spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
4911	spa->spa_indirect_vdevs_loaded = B_TRUE;
4912
4913	/*
4914	 * Create "The Godfather" zio to hold all async IOs
4915	 */
4916	spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
4917	    KM_SLEEP);
4918	for (int i = 0; i < max_ncpus; i++) {
4919		spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
4920		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4921		    ZIO_FLAG_GODFATHER);
4922	}
4923
4924	/*
4925	 * Create the root vdev.
4926	 */
4927	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4928
4929	error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
4930
4931	ASSERT(error != 0 || rvd != NULL);
4932	ASSERT(error != 0 || spa->spa_root_vdev == rvd);
4933
4934	if (error == 0 && !zfs_allocatable_devs(nvroot))
4935		error = SET_ERROR(EINVAL);
4936
4937	if (error == 0 &&
4938	    (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
4939	    (error = spa_validate_aux(spa, nvroot, txg,
4940	    VDEV_ALLOC_ADD)) == 0) {
4941		/*
4942		 * instantiate the metaslab groups (this will dirty the vdevs)
4943		 * we can no longer error exit past this point
4944		 */
4945		for (int c = 0; error == 0 && c < rvd->vdev_children; c++) {
4946			vdev_t *vd = rvd->vdev_child[c];
4947
4948			vdev_metaslab_set_size(vd);
4949			vdev_expand(vd, txg);
4950		}
4951	}
4952
4953	spa_config_exit(spa, SCL_ALL, FTAG);
4954
4955	if (error != 0) {
4956		spa_unload(spa);
4957		spa_deactivate(spa);
4958		spa_remove(spa);
4959		mutex_exit(&spa_namespace_lock);
4960		return (error);
4961	}
4962
4963	/*
4964	 * Get the list of spares, if specified.
4965	 */
4966	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4967	    &spares, &nspares) == 0) {
4968		VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
4969		    KM_SLEEP) == 0);
4970		VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4971		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4972		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4973		spa_load_spares(spa);
4974		spa_config_exit(spa, SCL_ALL, FTAG);
4975		spa->spa_spares.sav_sync = B_TRUE;
4976	}
4977
4978	/*
4979	 * Get the list of level 2 cache devices, if specified.
4980	 */
4981	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4982	    &l2cache, &nl2cache) == 0) {
4983		VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
4984		    NV_UNIQUE_NAME, KM_SLEEP) == 0);
4985		VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4986		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4987		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4988		spa_load_l2cache(spa);
4989		spa_config_exit(spa, SCL_ALL, FTAG);
4990		spa->spa_l2cache.sav_sync = B_TRUE;
4991	}
4992
4993	spa->spa_is_initializing = B_TRUE;
4994	spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
4995	spa->spa_meta_objset = dp->dp_meta_objset;
4996	spa->spa_is_initializing = B_FALSE;
4997
4998	/*
4999	 * Create DDTs (dedup tables).
5000	 */
5001	ddt_create(spa);
5002
5003	spa_update_dspace(spa);
5004
5005	tx = dmu_tx_create_assigned(dp, txg);
5006
5007	/*
5008	 * Create the pool config object.
5009	 */
5010	spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
5011	    DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
5012	    DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
5013
5014	if (zap_add(spa->spa_meta_objset,
5015	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
5016	    sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
5017		cmn_err(CE_PANIC, "failed to add pool config");
5018	}
5019
5020	if (spa_version(spa) >= SPA_VERSION_FEATURES)
5021		spa_feature_create_zap_objects(spa, tx);
5022
5023	if (zap_add(spa->spa_meta_objset,
5024	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
5025	    sizeof (uint64_t), 1, &version, tx) != 0) {
5026		cmn_err(CE_PANIC, "failed to add pool version");
5027	}
5028
5029	/* Newly created pools with the right version are always deflated. */
5030	if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
5031		spa->spa_deflate = TRUE;
5032		if (zap_add(spa->spa_meta_objset,
5033		    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
5034		    sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
5035			cmn_err(CE_PANIC, "failed to add deflate");
5036		}
5037	}
5038
5039	/*
5040	 * Create the deferred-free bpobj.  Turn off compression
5041	 * because sync-to-convergence takes longer if the blocksize
5042	 * keeps changing.
5043	 */
5044	obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
5045	dmu_object_set_compress(spa->spa_meta_objset, obj,
5046	    ZIO_COMPRESS_OFF, tx);
5047	if (zap_add(spa->spa_meta_objset,
5048	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
5049	    sizeof (uint64_t), 1, &obj, tx) != 0) {
5050		cmn_err(CE_PANIC, "failed to add bpobj");
5051	}
5052	VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
5053	    spa->spa_meta_objset, obj));
5054
5055	/*
5056	 * Create the pool's history object.
5057	 */
5058	if (version >= SPA_VERSION_ZPOOL_HISTORY)
5059		spa_history_create_obj(spa, tx);
5060
5061	/*
5062	 * Generate some random noise for salted checksums to operate on.
5063	 */
5064	(void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
5065	    sizeof (spa->spa_cksum_salt.zcs_bytes));
5066
5067	/*
5068	 * Set pool properties.
5069	 */
5070	spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
5071	spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
5072	spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
5073	spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
5074	spa->spa_multihost = zpool_prop_default_numeric(ZPOOL_PROP_MULTIHOST);
5075
5076	if (props != NULL) {
5077		spa_configfile_set(spa, props, B_FALSE);
5078		spa_sync_props(props, tx);
5079	}
5080
5081	dmu_tx_commit(tx);
5082
5083	spa->spa_sync_on = B_TRUE;
5084	txg_sync_start(spa->spa_dsl_pool);
5085	mmp_thread_start(spa);
5086
5087	/*
5088	 * We explicitly wait for the first transaction to complete so that our
5089	 * bean counters are appropriately updated.
5090	 */
5091	txg_wait_synced(spa->spa_dsl_pool, txg);
5092
5093	spa_spawn_aux_threads(spa);
5094
5095	spa_write_cachefile(spa, B_FALSE, B_TRUE);
5096	spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
5097
5098	spa_history_log_version(spa, "create");
5099
5100	/*
5101	 * Don't count references from objsets that are already closed
5102	 * and are making their way through the eviction process.
5103	 */
5104	spa_evicting_os_wait(spa);
5105	spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
5106	spa->spa_load_state = SPA_LOAD_NONE;
5107
5108	mutex_exit(&spa_namespace_lock);
5109
5110	return (0);
5111}
5112
5113#ifdef _KERNEL
5114/*
5115 * Get the root pool information from the root disk, then import the root pool
5116 * during the system boot up time.
5117 */
5118extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
5119
5120static nvlist_t *
5121spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
5122{
5123	nvlist_t *config;
5124	nvlist_t *nvtop, *nvroot;
5125	uint64_t pgid;
5126
5127	if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
5128		return (NULL);
5129
5130	/*
5131	 * Add this top-level vdev to the child array.
5132	 */
5133	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5134	    &nvtop) == 0);
5135	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5136	    &pgid) == 0);
5137	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
5138
5139	/*
5140	 * Put this pool's top-level vdevs into a root vdev.
5141	 */
5142	VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5143	VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5144	    VDEV_TYPE_ROOT) == 0);
5145	VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5146	VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5147	VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5148	    &nvtop, 1) == 0);
5149
5150	/*
5151	 * Replace the existing vdev_tree with the new root vdev in
5152	 * this pool's configuration (remove the old, add the new).
5153	 */
5154	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5155	nvlist_free(nvroot);
5156	return (config);
5157}
5158
5159/*
5160 * Walk the vdev tree and see if we can find a device with "better"
5161 * configuration. A configuration is "better" if the label on that
5162 * device has a more recent txg.
5163 */
5164static void
5165spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
5166{
5167	for (int c = 0; c < vd->vdev_children; c++)
5168		spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
5169
5170	if (vd->vdev_ops->vdev_op_leaf) {
5171		nvlist_t *label;
5172		uint64_t label_txg;
5173
5174		if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
5175		    &label) != 0)
5176			return;
5177
5178		VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
5179		    &label_txg) == 0);
5180
5181		/*
5182		 * Do we have a better boot device?
5183		 */
5184		if (label_txg > *txg) {
5185			*txg = label_txg;
5186			*avd = vd;
5187		}
5188		nvlist_free(label);
5189	}
5190}
5191
5192/*
5193 * Import a root pool.
5194 *
5195 * For x86. devpath_list will consist of devid and/or physpath name of
5196 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
5197 * The GRUB "findroot" command will return the vdev we should boot.
5198 *
5199 * For Sparc, devpath_list consists the physpath name of the booting device
5200 * no matter the rootpool is a single device pool or a mirrored pool.
5201 * e.g.
5202 *	"/pci@1f,0/ide@d/disk@0,0:a"
5203 */
5204int
5205spa_import_rootpool(char *devpath, char *devid)
5206{
5207	spa_t *spa;
5208	vdev_t *rvd, *bvd, *avd = NULL;
5209	nvlist_t *config, *nvtop;
5210	uint64_t guid, txg;
5211	char *pname;
5212	int error;
5213
5214	/*
5215	 * Read the label from the boot device and generate a configuration.
5216	 */
5217	config = spa_generate_rootconf(devpath, devid, &guid);
5218#if defined(_OBP) && defined(_KERNEL)
5219	if (config == NULL) {
5220		if (strstr(devpath, "/iscsi/ssd") != NULL) {
5221			/* iscsi boot */
5222			get_iscsi_bootpath_phy(devpath);
5223			config = spa_generate_rootconf(devpath, devid, &guid);
5224		}
5225	}
5226#endif
5227	if (config == NULL) {
5228		cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
5229		    devpath);
5230		return (SET_ERROR(EIO));
5231	}
5232
5233	VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5234	    &pname) == 0);
5235	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
5236
5237	mutex_enter(&spa_namespace_lock);
5238	if ((spa = spa_lookup(pname)) != NULL) {
5239		/*
5240		 * Remove the existing root pool from the namespace so that we
5241		 * can replace it with the correct config we just read in.
5242		 */
5243		spa_remove(spa);
5244	}
5245
5246	spa = spa_add(pname, config, NULL);
5247	spa->spa_is_root = B_TRUE;
5248	spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5249	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5250	    &spa->spa_ubsync.ub_version) != 0)
5251		spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5252
5253	/*
5254	 * Build up a vdev tree based on the boot device's label config.
5255	 */
5256	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5257	    &nvtop) == 0);
5258	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5259	error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5260	    VDEV_ALLOC_ROOTPOOL);
5261	spa_config_exit(spa, SCL_ALL, FTAG);
5262	if (error) {
5263		mutex_exit(&spa_namespace_lock);
5264		nvlist_free(config);
5265		cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5266		    pname);
5267		return (error);
5268	}
5269
5270	/*
5271	 * Get the boot vdev.
5272	 */
5273	if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
5274		cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
5275		    (u_longlong_t)guid);
5276		error = SET_ERROR(ENOENT);
5277		goto out;
5278	}
5279
5280	/*
5281	 * Determine if there is a better boot device.
5282	 */
5283	avd = bvd;
5284	spa_alt_rootvdev(rvd, &avd, &txg);
5285	if (avd != bvd) {
5286		cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
5287		    "try booting from '%s'", avd->vdev_path);
5288		error = SET_ERROR(EINVAL);
5289		goto out;
5290	}
5291
5292	/*
5293	 * If the boot device is part of a spare vdev then ensure that
5294	 * we're booting off the active spare.
5295	 */
5296	if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
5297	    !bvd->vdev_isspare) {
5298		cmn_err(CE_NOTE, "The boot device is currently spared. Please "
5299		    "try booting from '%s'",
5300		    bvd->vdev_parent->
5301		    vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
5302		error = SET_ERROR(EINVAL);
5303		goto out;
5304	}
5305
5306	error = 0;
5307out:
5308	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5309	vdev_free(rvd);
5310	spa_config_exit(spa, SCL_ALL, FTAG);
5311	mutex_exit(&spa_namespace_lock);
5312
5313	nvlist_free(config);
5314	return (error);
5315}
5316
5317#endif
5318
5319/*
5320 * Import a non-root pool into the system.
5321 */
5322int
5323spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5324{
5325	spa_t *spa;
5326	char *altroot = NULL;
5327	spa_load_state_t state = SPA_LOAD_IMPORT;
5328	zpool_load_policy_t policy;
5329	uint64_t mode = spa_mode_global;
5330	uint64_t readonly = B_FALSE;
5331	int error;
5332	nvlist_t *nvroot;
5333	nvlist_t **spares, **l2cache;
5334	uint_t nspares, nl2cache;
5335
5336	/*
5337	 * If a pool with this name exists, return failure.
5338	 */
5339	mutex_enter(&spa_namespace_lock);
5340	if (spa_lookup(pool) != NULL) {
5341		mutex_exit(&spa_namespace_lock);
5342		return (SET_ERROR(EEXIST));
5343	}
5344
5345	/*
5346	 * Create and initialize the spa structure.
5347	 */
5348	(void) nvlist_lookup_string(props,
5349	    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5350	(void) nvlist_lookup_uint64(props,
5351	    zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5352	if (readonly)
5353		mode = FREAD;
5354	spa = spa_add(pool, config, altroot);
5355	spa->spa_import_flags = flags;
5356
5357	/*
5358	 * Verbatim import - Take a pool and insert it into the namespace
5359	 * as if it had been loaded at boot.
5360	 */
5361	if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5362		if (props != NULL)
5363			spa_configfile_set(spa, props, B_FALSE);
5364
5365		spa_write_cachefile(spa, B_FALSE, B_TRUE);
5366		spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5367		zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5368		mutex_exit(&spa_namespace_lock);
5369		return (0);
5370	}
5371
5372	spa_activate(spa, mode);
5373
5374	/*
5375	 * Don't start async tasks until we know everything is healthy.
5376	 */
5377	spa_async_suspend(spa);
5378
5379	zpool_get_load_policy(config, &policy);
5380	if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5381		state = SPA_LOAD_RECOVER;
5382
5383	spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5384
5385	if (state != SPA_LOAD_RECOVER) {
5386		spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5387		zfs_dbgmsg("spa_import: importing %s", pool);
5388	} else {
5389		zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5390		    "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
5391	}
5392	error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
5393
5394	/*
5395	 * Propagate anything learned while loading the pool and pass it
5396	 * back to caller (i.e. rewind info, missing devices, etc).
5397	 */
5398	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5399	    spa->spa_load_info) == 0);
5400
5401	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5402	/*
5403	 * Toss any existing sparelist, as it doesn't have any validity
5404	 * anymore, and conflicts with spa_has_spare().
5405	 */
5406	if (spa->spa_spares.sav_config) {
5407		nvlist_free(spa->spa_spares.sav_config);
5408		spa->spa_spares.sav_config = NULL;
5409		spa_load_spares(spa);
5410	}
5411	if (spa->spa_l2cache.sav_config) {
5412		nvlist_free(spa->spa_l2cache.sav_config);
5413		spa->spa_l2cache.sav_config = NULL;
5414		spa_load_l2cache(spa);
5415	}
5416
5417	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5418	    &nvroot) == 0);
5419	if (error == 0)
5420		error = spa_validate_aux(spa, nvroot, -1ULL,
5421		    VDEV_ALLOC_SPARE);
5422	if (error == 0)
5423		error = spa_validate_aux(spa, nvroot, -1ULL,
5424		    VDEV_ALLOC_L2CACHE);
5425	spa_config_exit(spa, SCL_ALL, FTAG);
5426
5427	if (props != NULL)
5428		spa_configfile_set(spa, props, B_FALSE);
5429
5430	if (error != 0 || (props && spa_writeable(spa) &&
5431	    (error = spa_prop_set(spa, props)))) {
5432		spa_unload(spa);
5433		spa_deactivate(spa);
5434		spa_remove(spa);
5435		mutex_exit(&spa_namespace_lock);
5436		return (error);
5437	}
5438
5439	spa_async_resume(spa);
5440
5441	/*
5442	 * Override any spares and level 2 cache devices as specified by
5443	 * the user, as these may have correct device names/devids, etc.
5444	 */
5445	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5446	    &spares, &nspares) == 0) {
5447		if (spa->spa_spares.sav_config)
5448			VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5449			    ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5450		else
5451			VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5452			    NV_UNIQUE_NAME, KM_SLEEP) == 0);
5453		VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5454		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5455		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5456		spa_load_spares(spa);
5457		spa_config_exit(spa, SCL_ALL, FTAG);
5458		spa->spa_spares.sav_sync = B_TRUE;
5459	}
5460	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5461	    &l2cache, &nl2cache) == 0) {
5462		if (spa->spa_l2cache.sav_config)
5463			VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5464			    ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5465		else
5466			VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5467			    NV_UNIQUE_NAME, KM_SLEEP) == 0);
5468		VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5469		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5470		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5471		spa_load_l2cache(spa);
5472		spa_config_exit(spa, SCL_ALL, FTAG);
5473		spa->spa_l2cache.sav_sync = B_TRUE;
5474	}
5475
5476	/*
5477	 * Check for any removed devices.
5478	 */
5479	if (spa->spa_autoreplace) {
5480		spa_aux_check_removed(&spa->spa_spares);
5481		spa_aux_check_removed(&spa->spa_l2cache);
5482	}
5483
5484	if (spa_writeable(spa)) {
5485		/*
5486		 * Update the config cache to include the newly-imported pool.
5487		 */
5488		spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5489	}
5490
5491	/*
5492	 * It's possible that the pool was expanded while it was exported.
5493	 * We kick off an async task to handle this for us.
5494	 */
5495	spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5496
5497	spa_history_log_version(spa, "import");
5498
5499	spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5500
5501	mutex_exit(&spa_namespace_lock);
5502
5503	return (0);
5504}
5505
5506nvlist_t *
5507spa_tryimport(nvlist_t *tryconfig)
5508{
5509	nvlist_t *config = NULL;
5510	char *poolname, *cachefile;
5511	spa_t *spa;
5512	uint64_t state;
5513	int error;
5514	zpool_load_policy_t policy;
5515
5516	if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5517		return (NULL);
5518
5519	if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5520		return (NULL);
5521
5522	/*
5523	 * Create and initialize the spa structure.
5524	 */
5525	mutex_enter(&spa_namespace_lock);
5526	spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
5527	spa_activate(spa, FREAD);
5528
5529	/*
5530	 * Rewind pool if a max txg was provided.
5531	 */
5532	zpool_get_load_policy(spa->spa_config, &policy);
5533	if (policy.zlp_txg != UINT64_MAX) {
5534		spa->spa_load_max_txg = policy.zlp_txg;
5535		spa->spa_extreme_rewind = B_TRUE;
5536		zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
5537		    poolname, (longlong_t)policy.zlp_txg);
5538	} else {
5539		zfs_dbgmsg("spa_tryimport: importing %s", poolname);
5540	}
5541
5542	if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
5543	    == 0) {
5544		zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
5545		spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5546	} else {
5547		spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
5548	}
5549
5550	error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
5551
5552	/*
5553	 * If 'tryconfig' was at least parsable, return the current config.
5554	 */
5555	if (spa->spa_root_vdev != NULL) {
5556		config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5557		VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
5558		    poolname) == 0);
5559		VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5560		    state) == 0);
5561		VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
5562		    spa->spa_uberblock.ub_timestamp) == 0);
5563		VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5564		    spa->spa_load_info) == 0);
5565
5566		/*
5567		 * If the bootfs property exists on this pool then we
5568		 * copy it out so that external consumers can tell which
5569		 * pools are bootable.
5570		 */
5571		if ((!error || error == EEXIST) && spa->spa_bootfs) {
5572			char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5573
5574			/*
5575			 * We have to play games with the name since the
5576			 * pool was opened as TRYIMPORT_NAME.
5577			 */
5578			if (dsl_dsobj_to_dsname(spa_name(spa),
5579			    spa->spa_bootfs, tmpname) == 0) {
5580				char *cp;
5581				char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5582
5583				cp = strchr(tmpname, '/');
5584				if (cp == NULL) {
5585					(void) strlcpy(dsname, tmpname,
5586					    MAXPATHLEN);
5587				} else {
5588					(void) snprintf(dsname, MAXPATHLEN,
5589					    "%s/%s", poolname, ++cp);
5590				}
5591				VERIFY(nvlist_add_string(config,
5592				    ZPOOL_CONFIG_BOOTFS, dsname) == 0);
5593				kmem_free(dsname, MAXPATHLEN);
5594			}
5595			kmem_free(tmpname, MAXPATHLEN);
5596		}
5597
5598		/*
5599		 * Add the list of hot spares and level 2 cache devices.
5600		 */
5601		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5602		spa_add_spares(spa, config);
5603		spa_add_l2cache(spa, config);
5604		spa_config_exit(spa, SCL_CONFIG, FTAG);
5605	}
5606
5607	spa_unload(spa);
5608	spa_deactivate(spa);
5609	spa_remove(spa);
5610	mutex_exit(&spa_namespace_lock);
5611
5612	return (config);
5613}
5614
5615/*
5616 * Pool export/destroy
5617 *
5618 * The act of destroying or exporting a pool is very simple.  We make sure there
5619 * is no more pending I/O and any references to the pool are gone.  Then, we
5620 * update the pool state and sync all the labels to disk, removing the
5621 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
5622 * we don't sync the labels or remove the configuration cache.
5623 */
5624static int
5625spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
5626    boolean_t force, boolean_t hardforce)
5627{
5628	spa_t *spa;
5629
5630	if (oldconfig)
5631		*oldconfig = NULL;
5632
5633	if (!(spa_mode_global & FWRITE))
5634		return (SET_ERROR(EROFS));
5635
5636	mutex_enter(&spa_namespace_lock);
5637	if ((spa = spa_lookup(pool)) == NULL) {
5638		mutex_exit(&spa_namespace_lock);
5639		return (SET_ERROR(ENOENT));
5640	}
5641
5642	/*
5643	 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5644	 * reacquire the namespace lock, and see if we can export.
5645	 */
5646	spa_open_ref(spa, FTAG);
5647	mutex_exit(&spa_namespace_lock);
5648	spa_async_suspend(spa);
5649	mutex_enter(&spa_namespace_lock);
5650	spa_close(spa, FTAG);
5651
5652	/*
5653	 * The pool will be in core if it's openable,
5654	 * in which case we can modify its state.
5655	 */
5656	if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
5657
5658		/*
5659		 * Objsets may be open only because they're dirty, so we
5660		 * have to force it to sync before checking spa_refcnt.
5661		 */
5662		txg_wait_synced(spa->spa_dsl_pool, 0);
5663		spa_evicting_os_wait(spa);
5664
5665		/*
5666		 * A pool cannot be exported or destroyed if there are active
5667		 * references.  If we are resetting a pool, allow references by
5668		 * fault injection handlers.
5669		 */
5670		if (!spa_refcount_zero(spa) ||
5671		    (spa->spa_inject_ref != 0 &&
5672		    new_state != POOL_STATE_UNINITIALIZED)) {
5673			spa_async_resume(spa);
5674			mutex_exit(&spa_namespace_lock);
5675			return (SET_ERROR(EBUSY));
5676		}
5677
5678		/*
5679		 * A pool cannot be exported if it has an active shared spare.
5680		 * This is to prevent other pools stealing the active spare
5681		 * from an exported pool. At user's own will, such pool can
5682		 * be forcedly exported.
5683		 */
5684		if (!force && new_state == POOL_STATE_EXPORTED &&
5685		    spa_has_active_shared_spare(spa)) {
5686			spa_async_resume(spa);
5687			mutex_exit(&spa_namespace_lock);
5688			return (SET_ERROR(EXDEV));
5689		}
5690
5691		/*
5692		 * We're about to export or destroy this pool. Make sure
5693		 * we stop all initializtion activity here before we
5694		 * set the spa_final_txg. This will ensure that all
5695		 * dirty data resulting from the initialization is
5696		 * committed to disk before we unload the pool.
5697		 */
5698		if (spa->spa_root_vdev != NULL) {
5699			vdev_initialize_stop_all(spa->spa_root_vdev,
5700			    VDEV_INITIALIZE_ACTIVE);
5701		}
5702
5703		/*
5704		 * We want this to be reflected on every label,
5705		 * so mark them all dirty.  spa_unload() will do the
5706		 * final sync that pushes these changes out.
5707		 */
5708		if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
5709			spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5710			spa->spa_state = new_state;
5711			spa->spa_final_txg = spa_last_synced_txg(spa) +
5712			    TXG_DEFER_SIZE + 1;
5713			vdev_config_dirty(spa->spa_root_vdev);
5714			spa_config_exit(spa, SCL_ALL, FTAG);
5715		}
5716	}
5717
5718	spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
5719
5720	if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
5721		spa_unload(spa);
5722		spa_deactivate(spa);
5723	}
5724
5725	if (oldconfig && spa->spa_config)
5726		VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
5727
5728	if (new_state != POOL_STATE_UNINITIALIZED) {
5729		if (!hardforce)
5730			spa_write_cachefile(spa, B_TRUE, B_TRUE);
5731		spa_remove(spa);
5732	}
5733	mutex_exit(&spa_namespace_lock);
5734
5735	return (0);
5736}
5737
5738/*
5739 * Destroy a storage pool.
5740 */
5741int
5742spa_destroy(char *pool)
5743{
5744	return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
5745	    B_FALSE, B_FALSE));
5746}
5747
5748/*
5749 * Export a storage pool.
5750 */
5751int
5752spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
5753    boolean_t hardforce)
5754{
5755	return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
5756	    force, hardforce));
5757}
5758
5759/*
5760 * Similar to spa_export(), this unloads the spa_t without actually removing it
5761 * from the namespace in any way.
5762 */
5763int
5764spa_reset(char *pool)
5765{
5766	return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
5767	    B_FALSE, B_FALSE));
5768}
5769
5770/*
5771 * ==========================================================================
5772 * Device manipulation
5773 * ==========================================================================
5774 */
5775
5776/*
5777 * Add a device to a storage pool.
5778 */
5779int
5780spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
5781{
5782	uint64_t txg, id;
5783	int error;
5784	vdev_t *rvd = spa->spa_root_vdev;
5785	vdev_t *vd, *tvd;
5786	nvlist_t **spares, **l2cache;
5787	uint_t nspares, nl2cache;
5788
5789	ASSERT(spa_writeable(spa));
5790
5791	txg = spa_vdev_enter(spa);
5792
5793	if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
5794	    VDEV_ALLOC_ADD)) != 0)
5795		return (spa_vdev_exit(spa, NULL, txg, error));
5796
5797	spa->spa_pending_vdev = vd;	/* spa_vdev_exit() will clear this */
5798
5799	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
5800	    &nspares) != 0)
5801		nspares = 0;
5802
5803	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
5804	    &nl2cache) != 0)
5805		nl2cache = 0;
5806
5807	if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
5808		return (spa_vdev_exit(spa, vd, txg, EINVAL));
5809
5810	if (vd->vdev_children != 0 &&
5811	    (error = vdev_create(vd, txg, B_FALSE)) != 0)
5812		return (spa_vdev_exit(spa, vd, txg, error));
5813
5814	/*
5815	 * We must validate the spares and l2cache devices after checking the
5816	 * children.  Otherwise, vdev_inuse() will blindly overwrite the spare.
5817	 */
5818	if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
5819		return (spa_vdev_exit(spa, vd, txg, error));
5820
5821	/*
5822	 * If we are in the middle of a device removal, we can only add
5823	 * devices which match the existing devices in the pool.
5824	 * If we are in the middle of a removal, or have some indirect
5825	 * vdevs, we can not add raidz toplevels.
5826	 */
5827	if (spa->spa_vdev_removal != NULL ||
5828	    spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
5829		for (int c = 0; c < vd->vdev_children; c++) {
5830			tvd = vd->vdev_child[c];
5831			if (spa->spa_vdev_removal != NULL &&
5832			    tvd->vdev_ashift != spa->spa_max_ashift) {
5833				return (spa_vdev_exit(spa, vd, txg, EINVAL));
5834			}
5835			/* Fail if top level vdev is raidz */
5836			if (tvd->vdev_ops == &vdev_raidz_ops) {
5837				return (spa_vdev_exit(spa, vd, txg, EINVAL));
5838			}
5839			/*
5840			 * Need the top level mirror to be
5841			 * a mirror of leaf vdevs only
5842			 */
5843			if (tvd->vdev_ops == &vdev_mirror_ops) {
5844				for (uint64_t cid = 0;
5845				    cid < tvd->vdev_children; cid++) {
5846					vdev_t *cvd = tvd->vdev_child[cid];
5847					if (!cvd->vdev_ops->vdev_op_leaf) {
5848						return (spa_vdev_exit(spa, vd,
5849						    txg, EINVAL));
5850					}
5851				}
5852			}
5853		}
5854	}
5855
5856	for (int c = 0; c < vd->vdev_children; c++) {
5857
5858		/*
5859		 * Set the vdev id to the first hole, if one exists.
5860		 */
5861		for (id = 0; id < rvd->vdev_children; id++) {
5862			if (rvd->vdev_child[id]->vdev_ishole) {
5863				vdev_free(rvd->vdev_child[id]);
5864				break;
5865			}
5866		}
5867		tvd = vd->vdev_child[c];
5868		vdev_remove_child(vd, tvd);
5869		tvd->vdev_id = id;
5870		vdev_add_child(rvd, tvd);
5871		vdev_config_dirty(tvd);
5872	}
5873
5874	if (nspares != 0) {
5875		spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
5876		    ZPOOL_CONFIG_SPARES);
5877		spa_load_spares(spa);
5878		spa->spa_spares.sav_sync = B_TRUE;
5879	}
5880
5881	if (nl2cache != 0) {
5882		spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
5883		    ZPOOL_CONFIG_L2CACHE);
5884		spa_load_l2cache(spa);
5885		spa->spa_l2cache.sav_sync = B_TRUE;
5886	}
5887
5888	/*
5889	 * We have to be careful when adding new vdevs to an existing pool.
5890	 * If other threads start allocating from these vdevs before we
5891	 * sync the config cache, and we lose power, then upon reboot we may
5892	 * fail to open the pool because there are DVAs that the config cache
5893	 * can't translate.  Therefore, we first add the vdevs without
5894	 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
5895	 * and then let spa_config_update() initialize the new metaslabs.
5896	 *
5897	 * spa_load() checks for added-but-not-initialized vdevs, so that
5898	 * if we lose power at any point in this sequence, the remaining
5899	 * steps will be completed the next time we load the pool.
5900	 */
5901	(void) spa_vdev_exit(spa, vd, txg, 0);
5902
5903	mutex_enter(&spa_namespace_lock);
5904	spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5905	spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
5906	mutex_exit(&spa_namespace_lock);
5907
5908	return (0);
5909}
5910
5911/*
5912 * Attach a device to a mirror.  The arguments are the path to any device
5913 * in the mirror, and the nvroot for the new device.  If the path specifies
5914 * a device that is not mirrored, we automatically insert the mirror vdev.
5915 *
5916 * If 'replacing' is specified, the new device is intended to replace the
5917 * existing device; in this case the two devices are made into their own
5918 * mirror using the 'replacing' vdev, which is functionally identical to
5919 * the mirror vdev (it actually reuses all the same ops) but has a few
5920 * extra rules: you can't attach to it after it's been created, and upon
5921 * completion of resilvering, the first disk (the one being replaced)
5922 * is automatically detached.
5923 */
5924int
5925spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
5926{
5927	uint64_t txg, dtl_max_txg;
5928	vdev_t *rvd = spa->spa_root_vdev;
5929	vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
5930	vdev_ops_t *pvops;
5931	char *oldvdpath, *newvdpath;
5932	int newvd_isspare;
5933	int error;
5934
5935	ASSERT(spa_writeable(spa));
5936
5937	txg = spa_vdev_enter(spa);
5938
5939	oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
5940
5941	ASSERT(MUTEX_HELD(&spa_namespace_lock));
5942	if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
5943		error = (spa_has_checkpoint(spa)) ?
5944		    ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
5945		return (spa_vdev_exit(spa, NULL, txg, error));
5946	}
5947
5948	if (spa->spa_vdev_removal != NULL)
5949		return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5950
5951	if (oldvd == NULL)
5952		return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5953
5954	if (!oldvd->vdev_ops->vdev_op_leaf)
5955		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5956
5957	pvd = oldvd->vdev_parent;
5958
5959	if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
5960	    VDEV_ALLOC_ATTACH)) != 0)
5961		return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5962
5963	if (newrootvd->vdev_children != 1)
5964		return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
5965
5966	newvd = newrootvd->vdev_child[0];
5967
5968	if (!newvd->vdev_ops->vdev_op_leaf)
5969		return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
5970
5971	if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
5972		return (spa_vdev_exit(spa, newrootvd, txg, error));
5973
5974	/*
5975	 * Spares can't replace logs
5976	 */
5977	if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
5978		return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5979
5980	if (!replacing) {
5981		/*
5982		 * For attach, the only allowable parent is a mirror or the root
5983		 * vdev.
5984		 */
5985		if (pvd->vdev_ops != &vdev_mirror_ops &&
5986		    pvd->vdev_ops != &vdev_root_ops)
5987			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5988
5989		pvops = &vdev_mirror_ops;
5990	} else {
5991		/*
5992		 * Active hot spares can only be replaced by inactive hot
5993		 * spares.
5994		 */
5995		if (pvd->vdev_ops == &vdev_spare_ops &&
5996		    oldvd->vdev_isspare &&
5997		    !spa_has_spare(spa, newvd->vdev_guid))
5998			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5999
6000		/*
6001		 * If the source is a hot spare, and the parent isn't already a
6002		 * spare, then we want to create a new hot spare.  Otherwise, we
6003		 * want to create a replacing vdev.  The user is not allowed to
6004		 * attach to a spared vdev child unless the 'isspare' state is
6005		 * the same (spare replaces spare, non-spare replaces
6006		 * non-spare).
6007		 */
6008		if (pvd->vdev_ops == &vdev_replacing_ops &&
6009		    spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6010			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6011		} else if (pvd->vdev_ops == &vdev_spare_ops &&
6012		    newvd->vdev_isspare != oldvd->vdev_isspare) {
6013			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6014		}
6015
6016		if (newvd->vdev_isspare)
6017			pvops = &vdev_spare_ops;
6018		else
6019			pvops = &vdev_replacing_ops;
6020	}
6021
6022	/*
6023	 * Make sure the new device is big enough.
6024	 */
6025	if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6026		return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6027
6028	/*
6029	 * The new device cannot have a higher alignment requirement
6030	 * than the top-level vdev.
6031	 */
6032	if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6033		return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6034
6035	/*
6036	 * If this is an in-place replacement, update oldvd's path and devid
6037	 * to make it distinguishable from newvd, and unopenable from now on.
6038	 */
6039	if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6040		spa_strfree(oldvd->vdev_path);
6041		oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6042		    KM_SLEEP);
6043		(void) sprintf(oldvd->vdev_path, "%s/%s",
6044		    newvd->vdev_path, "old");
6045		if (oldvd->vdev_devid != NULL) {
6046			spa_strfree(oldvd->vdev_devid);
6047			oldvd->vdev_devid = NULL;
6048		}
6049	}
6050
6051	/* mark the device being resilvered */
6052	newvd->vdev_resilver_txg = txg;
6053
6054	/*
6055	 * If the parent is not a mirror, or if we're replacing, insert the new
6056	 * mirror/replacing/spare vdev above oldvd.
6057	 */
6058	if (pvd->vdev_ops != pvops)
6059		pvd = vdev_add_parent(oldvd, pvops);
6060
6061	ASSERT(pvd->vdev_top->vdev_parent == rvd);
6062	ASSERT(pvd->vdev_ops == pvops);
6063	ASSERT(oldvd->vdev_parent == pvd);
6064
6065	/*
6066	 * Extract the new device from its root and add it to pvd.
6067	 */
6068	vdev_remove_child(newrootvd, newvd);
6069	newvd->vdev_id = pvd->vdev_children;
6070	newvd->vdev_crtxg = oldvd->vdev_crtxg;
6071	vdev_add_child(pvd, newvd);
6072
6073	tvd = newvd->vdev_top;
6074	ASSERT(pvd->vdev_top == tvd);
6075	ASSERT(tvd->vdev_parent == rvd);
6076
6077	vdev_config_dirty(tvd);
6078
6079	/*
6080	 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6081	 * for any dmu_sync-ed blocks.  It will propagate upward when
6082	 * spa_vdev_exit() calls vdev_dtl_reassess().
6083	 */
6084	dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6085
6086	vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6087	    dtl_max_txg - TXG_INITIAL);
6088
6089	if (newvd->vdev_isspare) {
6090		spa_spare_activate(newvd);
6091		spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6092	}
6093
6094	oldvdpath = spa_strdup(oldvd->vdev_path);
6095	newvdpath = spa_strdup(newvd->vdev_path);
6096	newvd_isspare = newvd->vdev_isspare;
6097
6098	/*
6099	 * Mark newvd's DTL dirty in this txg.
6100	 */
6101	vdev_dirty(tvd, VDD_DTL, newvd, txg);
6102
6103	/*
6104	 * Schedule the resilver to restart in the future. We do this to
6105	 * ensure that dmu_sync-ed blocks have been stitched into the
6106	 * respective datasets.
6107	 */
6108	dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
6109
6110	if (spa->spa_bootfs)
6111		spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6112
6113	spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6114
6115	/*
6116	 * Commit the config
6117	 */
6118	(void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6119
6120	spa_history_log_internal(spa, "vdev attach", NULL,
6121	    "%s vdev=%s %s vdev=%s",
6122	    replacing && newvd_isspare ? "spare in" :
6123	    replacing ? "replace" : "attach", newvdpath,
6124	    replacing ? "for" : "to", oldvdpath);
6125
6126	spa_strfree(oldvdpath);
6127	spa_strfree(newvdpath);
6128
6129	return (0);
6130}
6131
6132/*
6133 * Detach a device from a mirror or replacing vdev.
6134 *
6135 * If 'replace_done' is specified, only detach if the parent
6136 * is a replacing vdev.
6137 */
6138int
6139spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6140{
6141	uint64_t txg;
6142	int error;
6143	vdev_t *rvd = spa->spa_root_vdev;
6144	vdev_t *vd, *pvd, *cvd, *tvd;
6145	boolean_t unspare = B_FALSE;
6146	uint64_t unspare_guid = 0;
6147	char *vdpath;
6148
6149	ASSERT(spa_writeable(spa));
6150
6151	txg = spa_vdev_enter(spa);
6152
6153	vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6154
6155	/*
6156	 * Besides being called directly from the userland through the
6157	 * ioctl interface, spa_vdev_detach() can be potentially called
6158	 * at the end of spa_vdev_resilver_done().
6159	 *
6160	 * In the regular case, when we have a checkpoint this shouldn't
6161	 * happen as we never empty the DTLs of a vdev during the scrub
6162	 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6163	 * should never get here when we have a checkpoint.
6164	 *
6165	 * That said, even in a case when we checkpoint the pool exactly
6166	 * as spa_vdev_resilver_done() calls this function everything
6167	 * should be fine as the resilver will return right away.
6168	 */
6169	ASSERT(MUTEX_HELD(&spa_namespace_lock));
6170	if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6171		error = (spa_has_checkpoint(spa)) ?
6172		    ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6173		return (spa_vdev_exit(spa, NULL, txg, error));
6174	}
6175
6176	if (vd == NULL)
6177		return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6178
6179	if (!vd->vdev_ops->vdev_op_leaf)
6180		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6181
6182	pvd = vd->vdev_parent;
6183
6184	/*
6185	 * If the parent/child relationship is not as expected, don't do it.
6186	 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6187	 * vdev that's replacing B with C.  The user's intent in replacing
6188	 * is to go from M(A,B) to M(A,C).  If the user decides to cancel
6189	 * the replace by detaching C, the expected behavior is to end up
6190	 * M(A,B).  But suppose that right after deciding to detach C,
6191	 * the replacement of B completes.  We would have M(A,C), and then
6192	 * ask to detach C, which would leave us with just A -- not what
6193	 * the user wanted.  To prevent this, we make sure that the
6194	 * parent/child relationship hasn't changed -- in this example,
6195	 * that C's parent is still the replacing vdev R.
6196	 */
6197	if (pvd->vdev_guid != pguid && pguid != 0)
6198		return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6199
6200	/*
6201	 * Only 'replacing' or 'spare' vdevs can be replaced.
6202	 */
6203	if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6204	    pvd->vdev_ops != &vdev_spare_ops)
6205		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6206
6207	ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6208	    spa_version(spa) >= SPA_VERSION_SPARES);
6209
6210	/*
6211	 * Only mirror, replacing, and spare vdevs support detach.
6212	 */
6213	if (pvd->