spa.c revision c4ab0d3f46036e85ad0700125c5a83cc139f55a3
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		ASSERT(!zthr_isrunning(spa->spa_condense_zthr));
1397		zthr_destroy(spa->spa_condense_zthr);
1398		spa->spa_condense_zthr = NULL;
1399	}
1400
1401	if (spa->spa_checkpoint_discard_zthr != NULL) {
1402		ASSERT(!zthr_isrunning(spa->spa_checkpoint_discard_zthr));
1403		zthr_destroy(spa->spa_checkpoint_discard_zthr);
1404		spa->spa_checkpoint_discard_zthr = NULL;
1405	}
1406
1407	spa_condense_fini(spa);
1408
1409	bpobj_close(&spa->spa_deferred_bpobj);
1410
1411	spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1412
1413	/*
1414	 * Close all vdevs.
1415	 */
1416	if (spa->spa_root_vdev)
1417		vdev_free(spa->spa_root_vdev);
1418	ASSERT(spa->spa_root_vdev == NULL);
1419
1420	/*
1421	 * Close the dsl pool.
1422	 */
1423	if (spa->spa_dsl_pool) {
1424		dsl_pool_close(spa->spa_dsl_pool);
1425		spa->spa_dsl_pool = NULL;
1426		spa->spa_meta_objset = NULL;
1427	}
1428
1429	ddt_unload(spa);
1430
1431	/*
1432	 * Drop and purge level 2 cache
1433	 */
1434	spa_l2cache_drop(spa);
1435
1436	for (i = 0; i < spa->spa_spares.sav_count; i++)
1437		vdev_free(spa->spa_spares.sav_vdevs[i]);
1438	if (spa->spa_spares.sav_vdevs) {
1439		kmem_free(spa->spa_spares.sav_vdevs,
1440		    spa->spa_spares.sav_count * sizeof (void *));
1441		spa->spa_spares.sav_vdevs = NULL;
1442	}
1443	if (spa->spa_spares.sav_config) {
1444		nvlist_free(spa->spa_spares.sav_config);
1445		spa->spa_spares.sav_config = NULL;
1446	}
1447	spa->spa_spares.sav_count = 0;
1448
1449	for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1450		vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1451		vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1452	}
1453	if (spa->spa_l2cache.sav_vdevs) {
1454		kmem_free(spa->spa_l2cache.sav_vdevs,
1455		    spa->spa_l2cache.sav_count * sizeof (void *));
1456		spa->spa_l2cache.sav_vdevs = NULL;
1457	}
1458	if (spa->spa_l2cache.sav_config) {
1459		nvlist_free(spa->spa_l2cache.sav_config);
1460		spa->spa_l2cache.sav_config = NULL;
1461	}
1462	spa->spa_l2cache.sav_count = 0;
1463
1464	spa->spa_async_suspended = 0;
1465
1466	spa->spa_indirect_vdevs_loaded = B_FALSE;
1467
1468	if (spa->spa_comment != NULL) {
1469		spa_strfree(spa->spa_comment);
1470		spa->spa_comment = NULL;
1471	}
1472
1473	spa_config_exit(spa, SCL_ALL, spa);
1474}
1475
1476/*
1477 * Load (or re-load) the current list of vdevs describing the active spares for
1478 * this pool.  When this is called, we have some form of basic information in
1479 * 'spa_spares.sav_config'.  We parse this into vdevs, try to open them, and
1480 * then re-generate a more complete list including status information.
1481 */
1482void
1483spa_load_spares(spa_t *spa)
1484{
1485	nvlist_t **spares;
1486	uint_t nspares;
1487	int i;
1488	vdev_t *vd, *tvd;
1489
1490#ifndef _KERNEL
1491	/*
1492	 * zdb opens both the current state of the pool and the
1493	 * checkpointed state (if present), with a different spa_t.
1494	 *
1495	 * As spare vdevs are shared among open pools, we skip loading
1496	 * them when we load the checkpointed state of the pool.
1497	 */
1498	if (!spa_writeable(spa))
1499		return;
1500#endif
1501
1502	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1503
1504	/*
1505	 * First, close and free any existing spare vdevs.
1506	 */
1507	for (i = 0; i < spa->spa_spares.sav_count; i++) {
1508		vd = spa->spa_spares.sav_vdevs[i];
1509
1510		/* Undo the call to spa_activate() below */
1511		if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1512		    B_FALSE)) != NULL && tvd->vdev_isspare)
1513			spa_spare_remove(tvd);
1514		vdev_close(vd);
1515		vdev_free(vd);
1516	}
1517
1518	if (spa->spa_spares.sav_vdevs)
1519		kmem_free(spa->spa_spares.sav_vdevs,
1520		    spa->spa_spares.sav_count * sizeof (void *));
1521
1522	if (spa->spa_spares.sav_config == NULL)
1523		nspares = 0;
1524	else
1525		VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1526		    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1527
1528	spa->spa_spares.sav_count = (int)nspares;
1529	spa->spa_spares.sav_vdevs = NULL;
1530
1531	if (nspares == 0)
1532		return;
1533
1534	/*
1535	 * Construct the array of vdevs, opening them to get status in the
1536	 * process.   For each spare, there is potentially two different vdev_t
1537	 * structures associated with it: one in the list of spares (used only
1538	 * for basic validation purposes) and one in the active vdev
1539	 * configuration (if it's spared in).  During this phase we open and
1540	 * validate each vdev on the spare list.  If the vdev also exists in the
1541	 * active configuration, then we also mark this vdev as an active spare.
1542	 */
1543	spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1544	    KM_SLEEP);
1545	for (i = 0; i < spa->spa_spares.sav_count; i++) {
1546		VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1547		    VDEV_ALLOC_SPARE) == 0);
1548		ASSERT(vd != NULL);
1549
1550		spa->spa_spares.sav_vdevs[i] = vd;
1551
1552		if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1553		    B_FALSE)) != NULL) {
1554			if (!tvd->vdev_isspare)
1555				spa_spare_add(tvd);
1556
1557			/*
1558			 * We only mark the spare active if we were successfully
1559			 * able to load the vdev.  Otherwise, importing a pool
1560			 * with a bad active spare would result in strange
1561			 * behavior, because multiple pool would think the spare
1562			 * is actively in use.
1563			 *
1564			 * There is a vulnerability here to an equally bizarre
1565			 * circumstance, where a dead active spare is later
1566			 * brought back to life (onlined or otherwise).  Given
1567			 * the rarity of this scenario, and the extra complexity
1568			 * it adds, we ignore the possibility.
1569			 */
1570			if (!vdev_is_dead(tvd))
1571				spa_spare_activate(tvd);
1572		}
1573
1574		vd->vdev_top = vd;
1575		vd->vdev_aux = &spa->spa_spares;
1576
1577		if (vdev_open(vd) != 0)
1578			continue;
1579
1580		if (vdev_validate_aux(vd) == 0)
1581			spa_spare_add(vd);
1582	}
1583
1584	/*
1585	 * Recompute the stashed list of spares, with status information
1586	 * this time.
1587	 */
1588	VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1589	    DATA_TYPE_NVLIST_ARRAY) == 0);
1590
1591	spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1592	    KM_SLEEP);
1593	for (i = 0; i < spa->spa_spares.sav_count; i++)
1594		spares[i] = vdev_config_generate(spa,
1595		    spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1596	VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1597	    ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1598	for (i = 0; i < spa->spa_spares.sav_count; i++)
1599		nvlist_free(spares[i]);
1600	kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1601}
1602
1603/*
1604 * Load (or re-load) the current list of vdevs describing the active l2cache for
1605 * this pool.  When this is called, we have some form of basic information in
1606 * 'spa_l2cache.sav_config'.  We parse this into vdevs, try to open them, and
1607 * then re-generate a more complete list including status information.
1608 * Devices which are already active have their details maintained, and are
1609 * not re-opened.
1610 */
1611void
1612spa_load_l2cache(spa_t *spa)
1613{
1614	nvlist_t **l2cache;
1615	uint_t nl2cache;
1616	int i, j, oldnvdevs;
1617	uint64_t guid;
1618	vdev_t *vd, **oldvdevs, **newvdevs;
1619	spa_aux_vdev_t *sav = &spa->spa_l2cache;
1620
1621#ifndef _KERNEL
1622	/*
1623	 * zdb opens both the current state of the pool and the
1624	 * checkpointed state (if present), with a different spa_t.
1625	 *
1626	 * As L2 caches are part of the ARC which is shared among open
1627	 * pools, we skip loading them when we load the checkpointed
1628	 * state of the pool.
1629	 */
1630	if (!spa_writeable(spa))
1631		return;
1632#endif
1633
1634	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1635
1636	if (sav->sav_config != NULL) {
1637		VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1638		    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1639		newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1640	} else {
1641		nl2cache = 0;
1642		newvdevs = NULL;
1643	}
1644
1645	oldvdevs = sav->sav_vdevs;
1646	oldnvdevs = sav->sav_count;
1647	sav->sav_vdevs = NULL;
1648	sav->sav_count = 0;
1649
1650	/*
1651	 * Process new nvlist of vdevs.
1652	 */
1653	for (i = 0; i < nl2cache; i++) {
1654		VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1655		    &guid) == 0);
1656
1657		newvdevs[i] = NULL;
1658		for (j = 0; j < oldnvdevs; j++) {
1659			vd = oldvdevs[j];
1660			if (vd != NULL && guid == vd->vdev_guid) {
1661				/*
1662				 * Retain previous vdev for add/remove ops.
1663				 */
1664				newvdevs[i] = vd;
1665				oldvdevs[j] = NULL;
1666				break;
1667			}
1668		}
1669
1670		if (newvdevs[i] == NULL) {
1671			/*
1672			 * Create new vdev
1673			 */
1674			VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1675			    VDEV_ALLOC_L2CACHE) == 0);
1676			ASSERT(vd != NULL);
1677			newvdevs[i] = vd;
1678
1679			/*
1680			 * Commit this vdev as an l2cache device,
1681			 * even if it fails to open.
1682			 */
1683			spa_l2cache_add(vd);
1684
1685			vd->vdev_top = vd;
1686			vd->vdev_aux = sav;
1687
1688			spa_l2cache_activate(vd);
1689
1690			if (vdev_open(vd) != 0)
1691				continue;
1692
1693			(void) vdev_validate_aux(vd);
1694
1695			if (!vdev_is_dead(vd))
1696				l2arc_add_vdev(spa, vd);
1697		}
1698	}
1699
1700	/*
1701	 * Purge vdevs that were dropped
1702	 */
1703	for (i = 0; i < oldnvdevs; i++) {
1704		uint64_t pool;
1705
1706		vd = oldvdevs[i];
1707		if (vd != NULL) {
1708			ASSERT(vd->vdev_isl2cache);
1709
1710			if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1711			    pool != 0ULL && l2arc_vdev_present(vd))
1712				l2arc_remove_vdev(vd);
1713			vdev_clear_stats(vd);
1714			vdev_free(vd);
1715		}
1716	}
1717
1718	if (oldvdevs)
1719		kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1720
1721	if (sav->sav_config == NULL)
1722		goto out;
1723
1724	sav->sav_vdevs = newvdevs;
1725	sav->sav_count = (int)nl2cache;
1726
1727	/*
1728	 * Recompute the stashed list of l2cache devices, with status
1729	 * information this time.
1730	 */
1731	VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1732	    DATA_TYPE_NVLIST_ARRAY) == 0);
1733
1734	l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1735	for (i = 0; i < sav->sav_count; i++)
1736		l2cache[i] = vdev_config_generate(spa,
1737		    sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1738	VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1739	    ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1740out:
1741	for (i = 0; i < sav->sav_count; i++)
1742		nvlist_free(l2cache[i]);
1743	if (sav->sav_count)
1744		kmem_free(l2cache, sav->sav_count * sizeof (void *));
1745}
1746
1747static int
1748load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1749{
1750	dmu_buf_t *db;
1751	char *packed = NULL;
1752	size_t nvsize = 0;
1753	int error;
1754	*value = NULL;
1755
1756	error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1757	if (error != 0)
1758		return (error);
1759
1760	nvsize = *(uint64_t *)db->db_data;
1761	dmu_buf_rele(db, FTAG);
1762
1763	packed = kmem_alloc(nvsize, KM_SLEEP);
1764	error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1765	    DMU_READ_PREFETCH);
1766	if (error == 0)
1767		error = nvlist_unpack(packed, nvsize, value, 0);
1768	kmem_free(packed, nvsize);
1769
1770	return (error);
1771}
1772
1773/*
1774 * Concrete top-level vdevs that are not missing and are not logs. At every
1775 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1776 */
1777static uint64_t
1778spa_healthy_core_tvds(spa_t *spa)
1779{
1780	vdev_t *rvd = spa->spa_root_vdev;
1781	uint64_t tvds = 0;
1782
1783	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1784		vdev_t *vd = rvd->vdev_child[i];
1785		if (vd->vdev_islog)
1786			continue;
1787		if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1788			tvds++;
1789	}
1790
1791	return (tvds);
1792}
1793
1794/*
1795 * Checks to see if the given vdev could not be opened, in which case we post a
1796 * sysevent to notify the autoreplace code that the device has been removed.
1797 */
1798static void
1799spa_check_removed(vdev_t *vd)
1800{
1801	for (uint64_t c = 0; c < vd->vdev_children; c++)
1802		spa_check_removed(vd->vdev_child[c]);
1803
1804	if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1805	    vdev_is_concrete(vd)) {
1806		zfs_post_autoreplace(vd->vdev_spa, vd);
1807		spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1808	}
1809}
1810
1811static int
1812spa_check_for_missing_logs(spa_t *spa)
1813{
1814	vdev_t *rvd = spa->spa_root_vdev;
1815
1816	/*
1817	 * If we're doing a normal import, then build up any additional
1818	 * diagnostic information about missing log devices.
1819	 * We'll pass this up to the user for further processing.
1820	 */
1821	if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1822		nvlist_t **child, *nv;
1823		uint64_t idx = 0;
1824
1825		child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1826		    KM_SLEEP);
1827		VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1828
1829		for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1830			vdev_t *tvd = rvd->vdev_child[c];
1831
1832			/*
1833			 * We consider a device as missing only if it failed
1834			 * to open (i.e. offline or faulted is not considered
1835			 * as missing).
1836			 */
1837			if (tvd->vdev_islog &&
1838			    tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1839				child[idx++] = vdev_config_generate(spa, tvd,
1840				    B_FALSE, VDEV_CONFIG_MISSING);
1841			}
1842		}
1843
1844		if (idx > 0) {
1845			fnvlist_add_nvlist_array(nv,
1846			    ZPOOL_CONFIG_CHILDREN, child, idx);
1847			fnvlist_add_nvlist(spa->spa_load_info,
1848			    ZPOOL_CONFIG_MISSING_DEVICES, nv);
1849
1850			for (uint64_t i = 0; i < idx; i++)
1851				nvlist_free(child[i]);
1852		}
1853		nvlist_free(nv);
1854		kmem_free(child, rvd->vdev_children * sizeof (char **));
1855
1856		if (idx > 0) {
1857			spa_load_failed(spa, "some log devices are missing");
1858			vdev_dbgmsg_print_tree(rvd, 2);
1859			return (SET_ERROR(ENXIO));
1860		}
1861	} else {
1862		for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1863			vdev_t *tvd = rvd->vdev_child[c];
1864
1865			if (tvd->vdev_islog &&
1866			    tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1867				spa_set_log_state(spa, SPA_LOG_CLEAR);
1868				spa_load_note(spa, "some log devices are "
1869				    "missing, ZIL is dropped.");
1870				vdev_dbgmsg_print_tree(rvd, 2);
1871				break;
1872			}
1873		}
1874	}
1875
1876	return (0);
1877}
1878
1879/*
1880 * Check for missing log devices
1881 */
1882static boolean_t
1883spa_check_logs(spa_t *spa)
1884{
1885	boolean_t rv = B_FALSE;
1886	dsl_pool_t *dp = spa_get_dsl(spa);
1887
1888	switch (spa->spa_log_state) {
1889	case SPA_LOG_MISSING:
1890		/* need to recheck in case slog has been restored */
1891	case SPA_LOG_UNKNOWN:
1892		rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1893		    zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
1894		if (rv)
1895			spa_set_log_state(spa, SPA_LOG_MISSING);
1896		break;
1897	}
1898	return (rv);
1899}
1900
1901static boolean_t
1902spa_passivate_log(spa_t *spa)
1903{
1904	vdev_t *rvd = spa->spa_root_vdev;
1905	boolean_t slog_found = B_FALSE;
1906
1907	ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1908
1909	if (!spa_has_slogs(spa))
1910		return (B_FALSE);
1911
1912	for (int c = 0; c < rvd->vdev_children; c++) {
1913		vdev_t *tvd = rvd->vdev_child[c];
1914		metaslab_group_t *mg = tvd->vdev_mg;
1915
1916		if (tvd->vdev_islog) {
1917			metaslab_group_passivate(mg);
1918			slog_found = B_TRUE;
1919		}
1920	}
1921
1922	return (slog_found);
1923}
1924
1925static void
1926spa_activate_log(spa_t *spa)
1927{
1928	vdev_t *rvd = spa->spa_root_vdev;
1929
1930	ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1931
1932	for (int c = 0; c < rvd->vdev_children; c++) {
1933		vdev_t *tvd = rvd->vdev_child[c];
1934		metaslab_group_t *mg = tvd->vdev_mg;
1935
1936		if (tvd->vdev_islog)
1937			metaslab_group_activate(mg);
1938	}
1939}
1940
1941int
1942spa_reset_logs(spa_t *spa)
1943{
1944	int error;
1945
1946	error = dmu_objset_find(spa_name(spa), zil_reset,
1947	    NULL, DS_FIND_CHILDREN);
1948	if (error == 0) {
1949		/*
1950		 * We successfully offlined the log device, sync out the
1951		 * current txg so that the "stubby" block can be removed
1952		 * by zil_sync().
1953		 */
1954		txg_wait_synced(spa->spa_dsl_pool, 0);
1955	}
1956	return (error);
1957}
1958
1959static void
1960spa_aux_check_removed(spa_aux_vdev_t *sav)
1961{
1962	for (int i = 0; i < sav->sav_count; i++)
1963		spa_check_removed(sav->sav_vdevs[i]);
1964}
1965
1966void
1967spa_claim_notify(zio_t *zio)
1968{
1969	spa_t *spa = zio->io_spa;
1970
1971	if (zio->io_error)
1972		return;
1973
1974	mutex_enter(&spa->spa_props_lock);	/* any mutex will do */
1975	if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
1976		spa->spa_claim_max_txg = zio->io_bp->blk_birth;
1977	mutex_exit(&spa->spa_props_lock);
1978}
1979
1980typedef struct spa_load_error {
1981	uint64_t	sle_meta_count;
1982	uint64_t	sle_data_count;
1983} spa_load_error_t;
1984
1985static void
1986spa_load_verify_done(zio_t *zio)
1987{
1988	blkptr_t *bp = zio->io_bp;
1989	spa_load_error_t *sle = zio->io_private;
1990	dmu_object_type_t type = BP_GET_TYPE(bp);
1991	int error = zio->io_error;
1992	spa_t *spa = zio->io_spa;
1993
1994	abd_free(zio->io_abd);
1995	if (error) {
1996		if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
1997		    type != DMU_OT_INTENT_LOG)
1998			atomic_inc_64(&sle->sle_meta_count);
1999		else
2000			atomic_inc_64(&sle->sle_data_count);
2001	}
2002
2003	mutex_enter(&spa->spa_scrub_lock);
2004	spa->spa_scrub_inflight--;
2005	cv_broadcast(&spa->spa_scrub_io_cv);
2006	mutex_exit(&spa->spa_scrub_lock);
2007}
2008
2009/*
2010 * Maximum number of concurrent scrub i/os to create while verifying
2011 * a pool while importing it.
2012 */
2013int spa_load_verify_maxinflight = 10000;
2014boolean_t spa_load_verify_metadata = B_TRUE;
2015boolean_t spa_load_verify_data = B_TRUE;
2016
2017/*ARGSUSED*/
2018static int
2019spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2020    const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2021{
2022	if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2023		return (0);
2024	/*
2025	 * Note: normally this routine will not be called if
2026	 * spa_load_verify_metadata is not set.  However, it may be useful
2027	 * to manually set the flag after the traversal has begun.
2028	 */
2029	if (!spa_load_verify_metadata)
2030		return (0);
2031	if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2032		return (0);
2033
2034	zio_t *rio = arg;
2035	size_t size = BP_GET_PSIZE(bp);
2036
2037	mutex_enter(&spa->spa_scrub_lock);
2038	while (spa->spa_scrub_inflight >= spa_load_verify_maxinflight)
2039		cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2040	spa->spa_scrub_inflight++;
2041	mutex_exit(&spa->spa_scrub_lock);
2042
2043	zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2044	    spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2045	    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2046	    ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2047	return (0);
2048}
2049
2050/* ARGSUSED */
2051int
2052verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2053{
2054	if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2055		return (SET_ERROR(ENAMETOOLONG));
2056
2057	return (0);
2058}
2059
2060static int
2061spa_load_verify(spa_t *spa)
2062{
2063	zio_t *rio;
2064	spa_load_error_t sle = { 0 };
2065	zpool_load_policy_t policy;
2066	boolean_t verify_ok = B_FALSE;
2067	int error = 0;
2068
2069	zpool_get_load_policy(spa->spa_config, &policy);
2070
2071	if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2072		return (0);
2073
2074	dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2075	error = dmu_objset_find_dp(spa->spa_dsl_pool,
2076	    spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2077	    DS_FIND_CHILDREN);
2078	dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2079	if (error != 0)
2080		return (error);
2081
2082	rio = zio_root(spa, NULL, &sle,
2083	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2084
2085	if (spa_load_verify_metadata) {
2086		if (spa->spa_extreme_rewind) {
2087			spa_load_note(spa, "performing a complete scan of the "
2088			    "pool since extreme rewind is on. This may take "
2089			    "a very long time.\n  (spa_load_verify_data=%u, "
2090			    "spa_load_verify_metadata=%u)",
2091			    spa_load_verify_data, spa_load_verify_metadata);
2092		}
2093		error = traverse_pool(spa, spa->spa_verify_min_txg,
2094		    TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2095		    spa_load_verify_cb, rio);
2096	}
2097
2098	(void) zio_wait(rio);
2099
2100	spa->spa_load_meta_errors = sle.sle_meta_count;
2101	spa->spa_load_data_errors = sle.sle_data_count;
2102
2103	if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2104		spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2105		    "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2106		    (u_longlong_t)sle.sle_data_count);
2107	}
2108
2109	if (spa_load_verify_dryrun ||
2110	    (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2111	    sle.sle_data_count <= policy.zlp_maxdata)) {
2112		int64_t loss = 0;
2113
2114		verify_ok = B_TRUE;
2115		spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2116		spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2117
2118		loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2119		VERIFY(nvlist_add_uint64(spa->spa_load_info,
2120		    ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2121		VERIFY(nvlist_add_int64(spa->spa_load_info,
2122		    ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2123		VERIFY(nvlist_add_uint64(spa->spa_load_info,
2124		    ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2125	} else {
2126		spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2127	}
2128
2129	if (spa_load_verify_dryrun)
2130		return (0);
2131
2132	if (error) {
2133		if (error != ENXIO && error != EIO)
2134			error = SET_ERROR(EIO);
2135		return (error);
2136	}
2137
2138	return (verify_ok ? 0 : EIO);
2139}
2140
2141/*
2142 * Find a value in the pool props object.
2143 */
2144static void
2145spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2146{
2147	(void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2148	    zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2149}
2150
2151/*
2152 * Find a value in the pool directory object.
2153 */
2154static int
2155spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2156{
2157	int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2158	    name, sizeof (uint64_t), 1, val);
2159
2160	if (error != 0 && (error != ENOENT || log_enoent)) {
2161		spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2162		    "[error=%d]", name, error);
2163	}
2164
2165	return (error);
2166}
2167
2168static int
2169spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2170{
2171	vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2172	return (SET_ERROR(err));
2173}
2174
2175static void
2176spa_spawn_aux_threads(spa_t *spa)
2177{
2178	ASSERT(spa_writeable(spa));
2179
2180	ASSERT(MUTEX_HELD(&spa_namespace_lock));
2181
2182	spa_start_indirect_condensing_thread(spa);
2183
2184	ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2185	spa->spa_checkpoint_discard_zthr =
2186	    zthr_create(spa_checkpoint_discard_thread_check,
2187	    spa_checkpoint_discard_thread, spa);
2188}
2189
2190/*
2191 * Fix up config after a partly-completed split.  This is done with the
2192 * ZPOOL_CONFIG_SPLIT nvlist.  Both the splitting pool and the split-off
2193 * pool have that entry in their config, but only the splitting one contains
2194 * a list of all the guids of the vdevs that are being split off.
2195 *
2196 * This function determines what to do with that list: either rejoin
2197 * all the disks to the pool, or complete the splitting process.  To attempt
2198 * the rejoin, each disk that is offlined is marked online again, and
2199 * we do a reopen() call.  If the vdev label for every disk that was
2200 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2201 * then we call vdev_split() on each disk, and complete the split.
2202 *
2203 * Otherwise we leave the config alone, with all the vdevs in place in
2204 * the original pool.
2205 */
2206static void
2207spa_try_repair(spa_t *spa, nvlist_t *config)
2208{
2209	uint_t extracted;
2210	uint64_t *glist;
2211	uint_t i, gcount;
2212	nvlist_t *nvl;
2213	vdev_t **vd;
2214	boolean_t attempt_reopen;
2215
2216	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2217		return;
2218
2219	/* check that the config is complete */
2220	if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2221	    &glist, &gcount) != 0)
2222		return;
2223
2224	vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2225
2226	/* attempt to online all the vdevs & validate */
2227	attempt_reopen = B_TRUE;
2228	for (i = 0; i < gcount; i++) {
2229		if (glist[i] == 0)	/* vdev is hole */
2230			continue;
2231
2232		vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2233		if (vd[i] == NULL) {
2234			/*
2235			 * Don't bother attempting to reopen the disks;
2236			 * just do the split.
2237			 */
2238			attempt_reopen = B_FALSE;
2239		} else {
2240			/* attempt to re-online it */
2241			vd[i]->vdev_offline = B_FALSE;
2242		}
2243	}
2244
2245	if (attempt_reopen) {
2246		vdev_reopen(spa->spa_root_vdev);
2247
2248		/* check each device to see what state it's in */
2249		for (extracted = 0, i = 0; i < gcount; i++) {
2250			if (vd[i] != NULL &&
2251			    vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2252				break;
2253			++extracted;
2254		}
2255	}
2256
2257	/*
2258	 * If every disk has been moved to the new pool, or if we never
2259	 * even attempted to look at them, then we split them off for
2260	 * good.
2261	 */
2262	if (!attempt_reopen || gcount == extracted) {
2263		for (i = 0; i < gcount; i++)
2264			if (vd[i] != NULL)
2265				vdev_split(vd[i]);
2266		vdev_reopen(spa->spa_root_vdev);
2267	}
2268
2269	kmem_free(vd, gcount * sizeof (vdev_t *));
2270}
2271
2272static int
2273spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2274{
2275	char *ereport = FM_EREPORT_ZFS_POOL;
2276	int error;
2277
2278	spa->spa_load_state = state;
2279
2280	gethrestime(&spa->spa_loaded_ts);
2281	error = spa_load_impl(spa, type, &ereport);
2282
2283	/*
2284	 * Don't count references from objsets that are already closed
2285	 * and are making their way through the eviction process.
2286	 */
2287	spa_evicting_os_wait(spa);
2288	spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
2289	if (error) {
2290		if (error != EEXIST) {
2291			spa->spa_loaded_ts.tv_sec = 0;
2292			spa->spa_loaded_ts.tv_nsec = 0;
2293		}
2294		if (error != EBADF) {
2295			zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2296		}
2297	}
2298	spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2299	spa->spa_ena = 0;
2300
2301	return (error);
2302}
2303
2304/*
2305 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2306 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2307 * spa's per-vdev ZAP list.
2308 */
2309static uint64_t
2310vdev_count_verify_zaps(vdev_t *vd)
2311{
2312	spa_t *spa = vd->vdev_spa;
2313	uint64_t total = 0;
2314	if (vd->vdev_top_zap != 0) {
2315		total++;
2316		ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2317		    spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2318	}
2319	if (vd->vdev_leaf_zap != 0) {
2320		total++;
2321		ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2322		    spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2323	}
2324
2325	for (uint64_t i = 0; i < vd->vdev_children; i++) {
2326		total += vdev_count_verify_zaps(vd->vdev_child[i]);
2327	}
2328
2329	return (total);
2330}
2331
2332/*
2333 * Determine whether the activity check is required.
2334 */
2335static boolean_t
2336spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
2337    nvlist_t *config)
2338{
2339	uint64_t state = 0;
2340	uint64_t hostid = 0;
2341	uint64_t tryconfig_txg = 0;
2342	uint64_t tryconfig_timestamp = 0;
2343	nvlist_t *nvinfo;
2344
2345	if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2346		nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2347		(void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
2348		    &tryconfig_txg);
2349		(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2350		    &tryconfig_timestamp);
2351	}
2352
2353	(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
2354
2355	/*
2356	 * Disable the MMP activity check - This is used by zdb which
2357	 * is intended to be used on potentially active pools.
2358	 */
2359	if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
2360		return (B_FALSE);
2361
2362	/*
2363	 * Skip the activity check when the MMP feature is disabled.
2364	 */
2365	if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
2366		return (B_FALSE);
2367	/*
2368	 * If the tryconfig_* values are nonzero, they are the results of an
2369	 * earlier tryimport.  If they match the uberblock we just found, then
2370	 * the pool has not changed and we return false so we do not test a
2371	 * second time.
2372	 */
2373	if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
2374	    tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp)
2375		return (B_FALSE);
2376
2377	/*
2378	 * Allow the activity check to be skipped when importing the pool
2379	 * on the same host which last imported it.  Since the hostid from
2380	 * configuration may be stale use the one read from the label.
2381	 */
2382	if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
2383		hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
2384
2385	if (hostid == spa_get_hostid())
2386		return (B_FALSE);
2387
2388	/*
2389	 * Skip the activity test when the pool was cleanly exported.
2390	 */
2391	if (state != POOL_STATE_ACTIVE)
2392		return (B_FALSE);
2393
2394	return (B_TRUE);
2395}
2396
2397/*
2398 * Perform the import activity check.  If the user canceled the import or
2399 * we detected activity then fail.
2400 */
2401static int
2402spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
2403{
2404	uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
2405	uint64_t txg = ub->ub_txg;
2406	uint64_t timestamp = ub->ub_timestamp;
2407	uint64_t import_delay = NANOSEC;
2408	hrtime_t import_expire;
2409	nvlist_t *mmp_label = NULL;
2410	vdev_t *rvd = spa->spa_root_vdev;
2411	kcondvar_t cv;
2412	kmutex_t mtx;
2413	int error = 0;
2414
2415	cv_init(&cv, NULL, CV_DEFAULT, NULL);
2416	mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
2417	mutex_enter(&mtx);
2418
2419	/*
2420	 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
2421	 * during the earlier tryimport.  If the txg recorded there is 0 then
2422	 * the pool is known to be active on another host.
2423	 *
2424	 * Otherwise, the pool might be in use on another node.  Check for
2425	 * changes in the uberblocks on disk if necessary.
2426	 */
2427	if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2428		nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
2429		    ZPOOL_CONFIG_LOAD_INFO);
2430
2431		if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
2432		    fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
2433			vdev_uberblock_load(rvd, ub, &mmp_label);
2434			error = SET_ERROR(EREMOTEIO);
2435			goto out;
2436		}
2437	}
2438
2439	/*
2440	 * Preferentially use the zfs_multihost_interval from the node which
2441	 * last imported the pool.  This value is stored in an MMP uberblock as.
2442	 *
2443	 * ub_mmp_delay * vdev_count_leaves() == zfs_multihost_interval
2444	 */
2445	if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay)
2446		import_delay = MAX(import_delay, import_intervals *
2447		    ub->ub_mmp_delay * MAX(vdev_count_leaves(spa), 1));
2448
2449	/* Apply a floor using the local default values. */
2450	import_delay = MAX(import_delay, import_intervals *
2451	    MSEC2NSEC(MAX(zfs_multihost_interval, MMP_MIN_INTERVAL)));
2452
2453	zfs_dbgmsg("import_delay=%llu ub_mmp_delay=%llu import_intervals=%u "
2454	    "leaves=%u", import_delay, ub->ub_mmp_delay, import_intervals,
2455	    vdev_count_leaves(spa));
2456
2457	/* Add a small random factor in case of simultaneous imports (0-25%) */
2458	import_expire = gethrtime() + import_delay +
2459	    (import_delay * spa_get_random(250) / 1000);
2460
2461	while (gethrtime() < import_expire) {
2462		vdev_uberblock_load(rvd, ub, &mmp_label);
2463
2464		if (txg != ub->ub_txg || timestamp != ub->ub_timestamp) {
2465			error = SET_ERROR(EREMOTEIO);
2466			break;
2467		}
2468
2469		if (mmp_label) {
2470			nvlist_free(mmp_label);
2471			mmp_label = NULL;
2472		}
2473
2474		error = cv_timedwait_sig(&cv, &mtx, ddi_get_lbolt() + hz);
2475		if (error != -1) {
2476			error = SET_ERROR(EINTR);
2477			break;
2478		}
2479		error = 0;
2480	}
2481
2482out:
2483	mutex_exit(&mtx);
2484	mutex_destroy(&mtx);
2485	cv_destroy(&cv);
2486
2487	/*
2488	 * If the pool is determined to be active store the status in the
2489	 * spa->spa_load_info nvlist.  If the remote hostname or hostid are
2490	 * available from configuration read from disk store them as well.
2491	 * This allows 'zpool import' to generate a more useful message.
2492	 *
2493	 * ZPOOL_CONFIG_MMP_STATE    - observed pool status (mandatory)
2494	 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
2495	 * ZPOOL_CONFIG_MMP_HOSTID   - hostid from the active pool
2496	 */
2497	if (error == EREMOTEIO) {
2498		char *hostname = "<unknown>";
2499		uint64_t hostid = 0;
2500
2501		if (mmp_label) {
2502			if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
2503				hostname = fnvlist_lookup_string(mmp_label,
2504				    ZPOOL_CONFIG_HOSTNAME);
2505				fnvlist_add_string(spa->spa_load_info,
2506				    ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
2507			}
2508
2509			if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
2510				hostid = fnvlist_lookup_uint64(mmp_label,
2511				    ZPOOL_CONFIG_HOSTID);
2512				fnvlist_add_uint64(spa->spa_load_info,
2513				    ZPOOL_CONFIG_MMP_HOSTID, hostid);
2514			}
2515		}
2516
2517		fnvlist_add_uint64(spa->spa_load_info,
2518		    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
2519		fnvlist_add_uint64(spa->spa_load_info,
2520		    ZPOOL_CONFIG_MMP_TXG, 0);
2521
2522		error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
2523	}
2524
2525	if (mmp_label)
2526		nvlist_free(mmp_label);
2527
2528	return (error);
2529}
2530
2531static int
2532spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2533{
2534	uint64_t hostid;
2535	char *hostname;
2536	uint64_t myhostid = 0;
2537
2538	if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2539	    ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2540		hostname = fnvlist_lookup_string(mos_config,
2541		    ZPOOL_CONFIG_HOSTNAME);
2542
2543		myhostid = zone_get_hostid(NULL);
2544
2545		if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2546			cmn_err(CE_WARN, "pool '%s' could not be "
2547			    "loaded as it was last accessed by "
2548			    "another system (host: %s hostid: 0x%llx). "
2549			    "See: http://illumos.org/msg/ZFS-8000-EY",
2550			    spa_name(spa), hostname, (u_longlong_t)hostid);
2551			spa_load_failed(spa, "hostid verification failed: pool "
2552			    "last accessed by host: %s (hostid: 0x%llx)",
2553			    hostname, (u_longlong_t)hostid);
2554			return (SET_ERROR(EBADF));
2555		}
2556	}
2557
2558	return (0);
2559}
2560
2561static int
2562spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2563{
2564	int error = 0;
2565	nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2566	int parse;
2567	vdev_t *rvd;
2568	uint64_t pool_guid;
2569	char *comment;
2570
2571	/*
2572	 * Versioning wasn't explicitly added to the label until later, so if
2573	 * it's not present treat it as the initial version.
2574	 */
2575	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2576	    &spa->spa_ubsync.ub_version) != 0)
2577		spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2578
2579	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2580		spa_load_failed(spa, "invalid config provided: '%s' missing",
2581		    ZPOOL_CONFIG_POOL_GUID);
2582		return (SET_ERROR(EINVAL));
2583	}
2584
2585	/*
2586	 * If we are doing an import, ensure that the pool is not already
2587	 * imported by checking if its pool guid already exists in the
2588	 * spa namespace.
2589	 *
2590	 * The only case that we allow an already imported pool to be
2591	 * imported again, is when the pool is checkpointed and we want to
2592	 * look at its checkpointed state from userland tools like zdb.
2593	 */
2594#ifdef _KERNEL
2595	if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2596	    spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2597	    spa_guid_exists(pool_guid, 0)) {
2598#else
2599	if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2600	    spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2601	    spa_guid_exists(pool_guid, 0) &&
2602	    !spa_importing_readonly_checkpoint(spa)) {
2603#endif
2604		spa_load_failed(spa, "a pool with guid %llu is already open",
2605		    (u_longlong_t)pool_guid);
2606		return (SET_ERROR(EEXIST));
2607	}
2608
2609	spa->spa_config_guid = pool_guid;
2610
2611	nvlist_free(spa->spa_load_info);
2612	spa->spa_load_info = fnvlist_alloc();
2613
2614	ASSERT(spa->spa_comment == NULL);
2615	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2616		spa->spa_comment = spa_strdup(comment);
2617
2618	(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2619	    &spa->spa_config_txg);
2620
2621	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2622		spa->spa_config_splitting = fnvlist_dup(nvl);
2623
2624	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2625		spa_load_failed(spa, "invalid config provided: '%s' missing",
2626		    ZPOOL_CONFIG_VDEV_TREE);
2627		return (SET_ERROR(EINVAL));
2628	}
2629
2630	/*
2631	 * Create "The Godfather" zio to hold all async IOs
2632	 */
2633	spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2634	    KM_SLEEP);
2635	for (int i = 0; i < max_ncpus; i++) {
2636		spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2637		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2638		    ZIO_FLAG_GODFATHER);
2639	}
2640
2641	/*
2642	 * Parse the configuration into a vdev tree.  We explicitly set the
2643	 * value that will be returned by spa_version() since parsing the
2644	 * configuration requires knowing the version number.
2645	 */
2646	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2647	parse = (type == SPA_IMPORT_EXISTING ?
2648	    VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2649	error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2650	spa_config_exit(spa, SCL_ALL, FTAG);
2651
2652	if (error != 0) {
2653		spa_load_failed(spa, "unable to parse config [error=%d]",
2654		    error);
2655		return (error);
2656	}
2657
2658	ASSERT(spa->spa_root_vdev == rvd);
2659	ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2660	ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2661
2662	if (type != SPA_IMPORT_ASSEMBLE) {
2663		ASSERT(spa_guid(spa) == pool_guid);
2664	}
2665
2666	return (0);
2667}
2668
2669/*
2670 * Recursively open all vdevs in the vdev tree. This function is called twice:
2671 * first with the untrusted config, then with the trusted config.
2672 */
2673static int
2674spa_ld_open_vdevs(spa_t *spa)
2675{
2676	int error = 0;
2677
2678	/*
2679	 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2680	 * missing/unopenable for the root vdev to be still considered openable.
2681	 */
2682	if (spa->spa_trust_config) {
2683		spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2684	} else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2685		spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2686	} else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2687		spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2688	} else {
2689		spa->spa_missing_tvds_allowed = 0;
2690	}
2691
2692	spa->spa_missing_tvds_allowed =
2693	    MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2694
2695	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2696	error = vdev_open(spa->spa_root_vdev);
2697	spa_config_exit(spa, SCL_ALL, FTAG);
2698
2699	if (spa->spa_missing_tvds != 0) {
2700		spa_load_note(spa, "vdev tree has %lld missing top-level "
2701		    "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2702		if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2703			/*
2704			 * Although theoretically we could allow users to open
2705			 * incomplete pools in RW mode, we'd need to add a lot
2706			 * of extra logic (e.g. adjust pool space to account
2707			 * for missing vdevs).
2708			 * This limitation also prevents users from accidentally
2709			 * opening the pool in RW mode during data recovery and
2710			 * damaging it further.
2711			 */
2712			spa_load_note(spa, "pools with missing top-level "
2713			    "vdevs can only be opened in read-only mode.");
2714			error = SET_ERROR(ENXIO);
2715		} else {
2716			spa_load_note(spa, "current settings allow for maximum "
2717			    "%lld missing top-level vdevs at this stage.",
2718			    (u_longlong_t)spa->spa_missing_tvds_allowed);
2719		}
2720	}
2721	if (error != 0) {
2722		spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2723		    error);
2724	}
2725	if (spa->spa_missing_tvds != 0 || error != 0)
2726		vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2727
2728	return (error);
2729}
2730
2731/*
2732 * We need to validate the vdev labels against the configuration that
2733 * we have in hand. This function is called twice: first with an untrusted
2734 * config, then with a trusted config. The validation is more strict when the
2735 * config is trusted.
2736 */
2737static int
2738spa_ld_validate_vdevs(spa_t *spa)
2739{
2740	int error = 0;
2741	vdev_t *rvd = spa->spa_root_vdev;
2742
2743	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2744	error = vdev_validate(rvd);
2745	spa_config_exit(spa, SCL_ALL, FTAG);
2746
2747	if (error != 0) {
2748		spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2749		return (error);
2750	}
2751
2752	if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2753		spa_load_failed(spa, "cannot open vdev tree after invalidating "
2754		    "some vdevs");
2755		vdev_dbgmsg_print_tree(rvd, 2);
2756		return (SET_ERROR(ENXIO));
2757	}
2758
2759	return (0);
2760}
2761
2762static void
2763spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2764{
2765	spa->spa_state = POOL_STATE_ACTIVE;
2766	spa->spa_ubsync = spa->spa_uberblock;
2767	spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2768	    TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2769	spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2770	    spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2771	spa->spa_claim_max_txg = spa->spa_first_txg;
2772	spa->spa_prev_software_version = ub->ub_software_version;
2773}
2774
2775static int
2776spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2777{
2778	vdev_t *rvd = spa->spa_root_vdev;
2779	nvlist_t *label;
2780	uberblock_t *ub = &spa->spa_uberblock;
2781	boolean_t activity_check = B_FALSE;
2782
2783	/*
2784	 * If we are opening the checkpointed state of the pool by
2785	 * rewinding to it, at this point we will have written the
2786	 * checkpointed uberblock to the vdev labels, so searching
2787	 * the labels will find the right uberblock.  However, if
2788	 * we are opening the checkpointed state read-only, we have
2789	 * not modified the labels. Therefore, we must ignore the
2790	 * labels and continue using the spa_uberblock that was set
2791	 * by spa_ld_checkpoint_rewind.
2792	 *
2793	 * Note that it would be fine to ignore the labels when
2794	 * rewinding (opening writeable) as well. However, if we
2795	 * crash just after writing the labels, we will end up
2796	 * searching the labels. Doing so in the common case means
2797	 * that this code path gets exercised normally, rather than
2798	 * just in the edge case.
2799	 */
2800	if (ub->ub_checkpoint_txg != 0 &&
2801	    spa_importing_readonly_checkpoint(spa)) {
2802		spa_ld_select_uberblock_done(spa, ub);
2803		return (0);
2804	}
2805
2806	/*
2807	 * Find the best uberblock.
2808	 */
2809	vdev_uberblock_load(rvd, ub, &label);
2810
2811	/*
2812	 * If we weren't able to find a single valid uberblock, return failure.
2813	 */
2814	if (ub->ub_txg == 0) {
2815		nvlist_free(label);
2816		spa_load_failed(spa, "no valid uberblock found");
2817		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2818	}
2819
2820	spa_load_note(spa, "using uberblock with txg=%llu",
2821	    (u_longlong_t)ub->ub_txg);
2822
2823	/*
2824	 * For pools which have the multihost property on determine if the
2825	 * pool is truly inactive and can be safely imported.  Prevent
2826	 * hosts which don't have a hostid set from importing the pool.
2827	 */
2828	activity_check = spa_activity_check_required(spa, ub, label,
2829	    spa->spa_config);
2830	if (activity_check) {
2831		if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
2832		    spa_get_hostid() == 0) {
2833			nvlist_free(label);
2834			fnvlist_add_uint64(spa->spa_load_info,
2835			    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
2836			return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
2837		}
2838
2839		int error = spa_activity_check(spa, ub, spa->spa_config);
2840		if (error) {
2841			nvlist_free(label);
2842			return (error);
2843		}
2844
2845		fnvlist_add_uint64(spa->spa_load_info,
2846		    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
2847		fnvlist_add_uint64(spa->spa_load_info,
2848		    ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
2849	}
2850
2851	/*
2852	 * If the pool has an unsupported version we can't open it.
2853	 */
2854	if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2855		nvlist_free(label);
2856		spa_load_failed(spa, "version %llu is not supported",
2857		    (u_longlong_t)ub->ub_version);
2858		return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2859	}
2860
2861	if (ub->ub_version >= SPA_VERSION_FEATURES) {
2862		nvlist_t *features;
2863
2864		/*
2865		 * If we weren't able to find what's necessary for reading the
2866		 * MOS in the label, return failure.
2867		 */
2868		if (label == NULL) {
2869			spa_load_failed(spa, "label config unavailable");
2870			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2871			    ENXIO));
2872		}
2873
2874		if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
2875		    &features) != 0) {
2876			nvlist_free(label);
2877			spa_load_failed(spa, "invalid label: '%s' missing",
2878			    ZPOOL_CONFIG_FEATURES_FOR_READ);
2879			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2880			    ENXIO));
2881		}
2882
2883		/*
2884		 * Update our in-core representation with the definitive values
2885		 * from the label.
2886		 */
2887		nvlist_free(spa->spa_label_features);
2888		VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2889	}
2890
2891	nvlist_free(label);
2892
2893	/*
2894	 * Look through entries in the label nvlist's features_for_read. If
2895	 * there is a feature listed there which we don't understand then we
2896	 * cannot open a pool.
2897	 */
2898	if (ub->ub_version >= SPA_VERSION_FEATURES) {
2899		nvlist_t *unsup_feat;
2900
2901		VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2902		    0);
2903
2904		for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2905		    NULL); nvp != NULL;
2906		    nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2907			if (!zfeature_is_supported(nvpair_name(nvp))) {
2908				VERIFY(nvlist_add_string(unsup_feat,
2909				    nvpair_name(nvp), "") == 0);
2910			}
2911		}
2912
2913		if (!nvlist_empty(unsup_feat)) {
2914			VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2915			    ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2916			nvlist_free(unsup_feat);
2917			spa_load_failed(spa, "some features are unsupported");
2918			return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2919			    ENOTSUP));
2920		}
2921
2922		nvlist_free(unsup_feat);
2923	}
2924
2925	if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2926		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2927		spa_try_repair(spa, spa->spa_config);
2928		spa_config_exit(spa, SCL_ALL, FTAG);
2929		nvlist_free(spa->spa_config_splitting);
2930		spa->spa_config_splitting = NULL;
2931	}
2932
2933	/*
2934	 * Initialize internal SPA structures.
2935	 */
2936	spa_ld_select_uberblock_done(spa, ub);
2937
2938	return (0);
2939}
2940
2941static int
2942spa_ld_open_rootbp(spa_t *spa)
2943{
2944	int error = 0;
2945	vdev_t *rvd = spa->spa_root_vdev;
2946
2947	error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2948	if (error != 0) {
2949		spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
2950		    "[error=%d]", error);
2951		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2952	}
2953	spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2954
2955	return (0);
2956}
2957
2958static int
2959spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
2960    boolean_t reloading)
2961{
2962	vdev_t *mrvd, *rvd = spa->spa_root_vdev;
2963	nvlist_t *nv, *mos_config, *policy;
2964	int error = 0, copy_error;
2965	uint64_t healthy_tvds, healthy_tvds_mos;
2966	uint64_t mos_config_txg;
2967
2968	if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
2969	    != 0)
2970		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2971
2972	/*
2973	 * If we're assembling a pool from a split, the config provided is
2974	 * already trusted so there is nothing to do.
2975	 */
2976	if (type == SPA_IMPORT_ASSEMBLE)
2977		return (0);
2978
2979	healthy_tvds = spa_healthy_core_tvds(spa);
2980
2981	if (load_nvlist(spa, spa->spa_config_object, &mos_config)
2982	    != 0) {
2983		spa_load_failed(spa, "unable to retrieve MOS config");
2984		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2985	}
2986
2987	/*
2988	 * If we are doing an open, pool owner wasn't verified yet, thus do
2989	 * the verification here.
2990	 */
2991	if (spa->spa_load_state == SPA_LOAD_OPEN) {
2992		error = spa_verify_host(spa, mos_config);
2993		if (error != 0) {
2994			nvlist_free(mos_config);
2995			return (error);
2996		}
2997	}
2998
2999	nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
3000
3001	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3002
3003	/*
3004	 * Build a new vdev tree from the trusted config
3005	 */
3006	VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
3007
3008	/*
3009	 * Vdev paths in the MOS may be obsolete. If the untrusted config was
3010	 * obtained by scanning /dev/dsk, then it will have the right vdev
3011	 * paths. We update the trusted MOS config with this information.
3012	 * We first try to copy the paths with vdev_copy_path_strict, which
3013	 * succeeds only when both configs have exactly the same vdev tree.
3014	 * If that fails, we fall back to a more flexible method that has a
3015	 * best effort policy.
3016	 */
3017	copy_error = vdev_copy_path_strict(rvd, mrvd);
3018	if (copy_error != 0 || spa_load_print_vdev_tree) {
3019		spa_load_note(spa, "provided vdev tree:");
3020		vdev_dbgmsg_print_tree(rvd, 2);
3021		spa_load_note(spa, "MOS vdev tree:");
3022		vdev_dbgmsg_print_tree(mrvd, 2);
3023	}
3024	if (copy_error != 0) {
3025		spa_load_note(spa, "vdev_copy_path_strict failed, falling "
3026		    "back to vdev_copy_path_relaxed");
3027		vdev_copy_path_relaxed(rvd, mrvd);
3028	}
3029
3030	vdev_close(rvd);
3031	vdev_free(rvd);
3032	spa->spa_root_vdev = mrvd;
3033	rvd = mrvd;
3034	spa_config_exit(spa, SCL_ALL, FTAG);
3035
3036	/*
3037	 * We will use spa_config if we decide to reload the spa or if spa_load
3038	 * fails and we rewind. We must thus regenerate the config using the
3039	 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
3040	 * pass settings on how to load the pool and is not stored in the MOS.
3041	 * We copy it over to our new, trusted config.
3042	 */
3043	mos_config_txg = fnvlist_lookup_uint64(mos_config,
3044	    ZPOOL_CONFIG_POOL_TXG);
3045	nvlist_free(mos_config);
3046	mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
3047	if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
3048	    &policy) == 0)
3049		fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
3050	spa_config_set(spa, mos_config);
3051	spa->spa_config_source = SPA_CONFIG_SRC_MOS;
3052
3053	/*
3054	 * Now that we got the config from the MOS, we should be more strict
3055	 * in checking blkptrs and can make assumptions about the consistency
3056	 * of the vdev tree. spa_trust_config must be set to true before opening
3057	 * vdevs in order for them to be writeable.
3058	 */
3059	spa->spa_trust_config = B_TRUE;
3060
3061	/*
3062	 * Open and validate the new vdev tree
3063	 */
3064	error = spa_ld_open_vdevs(spa);
3065	if (error != 0)
3066		return (error);
3067
3068	error = spa_ld_validate_vdevs(spa);
3069	if (error != 0)
3070		return (error);
3071
3072	if (copy_error != 0 || spa_load_print_vdev_tree) {
3073		spa_load_note(spa, "final vdev tree:");
3074		vdev_dbgmsg_print_tree(rvd, 2);
3075	}
3076
3077	if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
3078	    !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
3079		/*
3080		 * Sanity check to make sure that we are indeed loading the
3081		 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
3082		 * in the config provided and they happened to be the only ones
3083		 * to have the latest uberblock, we could involuntarily perform
3084		 * an extreme rewind.
3085		 */
3086		healthy_tvds_mos = spa_healthy_core_tvds(spa);
3087		if (healthy_tvds_mos - healthy_tvds >=
3088		    SPA_SYNC_MIN_VDEVS) {
3089			spa_load_note(spa, "config provided misses too many "
3090			    "top-level vdevs compared to MOS (%lld vs %lld). ",
3091			    (u_longlong_t)healthy_tvds,
3092			    (u_longlong_t)healthy_tvds_mos);
3093			spa_load_note(spa, "vdev tree:");
3094			vdev_dbgmsg_print_tree(rvd, 2);
3095			if (reloading) {
3096				spa_load_failed(spa, "config was already "
3097				    "provided from MOS. Aborting.");
3098				return (spa_vdev_err(rvd,
3099				    VDEV_AUX_CORRUPT_DATA, EIO));
3100			}
3101			spa_load_note(spa, "spa must be reloaded using MOS "
3102			    "config");
3103			return (SET_ERROR(EAGAIN));
3104		}
3105	}
3106
3107	error = spa_check_for_missing_logs(spa);
3108	if (error != 0)
3109		return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
3110
3111	if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
3112		spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
3113		    "guid sum (%llu != %llu)",
3114		    (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
3115		    (u_longlong_t)rvd->vdev_guid_sum);
3116		return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
3117		    ENXIO));
3118	}
3119
3120	return (0);
3121}
3122
3123static int
3124spa_ld_open_indirect_vdev_metadata(spa_t *spa)
3125{
3126	int error = 0;
3127	vdev_t *rvd = spa->spa_root_vdev;
3128
3129	/*
3130	 * Everything that we read before spa_remove_init() must be stored
3131	 * on concreted vdevs.  Therefore we do this as early as possible.
3132	 */
3133	error = spa_remove_init(spa);
3134	if (error != 0) {
3135		spa_load_failed(spa, "spa_remove_init failed [error=%d]",
3136		    error);
3137		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3138	}
3139
3140	/*
3141	 * Retrieve information needed to condense indirect vdev mappings.
3142	 */
3143	error = spa_condense_init(spa);
3144	if (error != 0) {
3145		spa_load_failed(spa, "spa_condense_init failed [error=%d]",
3146		    error);
3147		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3148	}
3149
3150	return (0);
3151}
3152
3153static int
3154spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
3155{
3156	int error = 0;
3157	vdev_t *rvd = spa->spa_root_vdev;
3158
3159	if (spa_version(spa) >= SPA_VERSION_FEATURES) {
3160		boolean_t missing_feat_read = B_FALSE;
3161		nvlist_t *unsup_feat, *enabled_feat;
3162
3163		if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
3164		    &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
3165			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3166		}
3167
3168		if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
3169		    &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
3170			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3171		}
3172
3173		if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
3174		    &spa->spa_feat_desc_obj, B_TRUE) != 0) {
3175			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3176		}
3177
3178		enabled_feat = fnvlist_alloc();
3179		unsup_feat = fnvlist_alloc();
3180
3181		if (!spa_features_check(spa, B_FALSE,
3182		    unsup_feat, enabled_feat))
3183			missing_feat_read = B_TRUE;
3184
3185		if (spa_writeable(spa) ||
3186		    spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3187			if (!spa_features_check(spa, B_TRUE,
3188			    unsup_feat, enabled_feat)) {
3189				*missing_feat_writep = B_TRUE;
3190			}
3191		}
3192
3193		fnvlist_add_nvlist(spa->spa_load_info,
3194		    ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3195
3196		if (!nvlist_empty(unsup_feat)) {
3197			fnvlist_add_nvlist(spa->spa_load_info,
3198			    ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3199		}
3200
3201		fnvlist_free(enabled_feat);
3202		fnvlist_free(unsup_feat);
3203
3204		if (!missing_feat_read) {
3205			fnvlist_add_boolean(spa->spa_load_info,
3206			    ZPOOL_CONFIG_CAN_RDONLY);
3207		}
3208
3209		/*
3210		 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3211		 * twofold: to determine whether the pool is available for
3212		 * import in read-write mode and (if it is not) whether the
3213		 * pool is available for import in read-only mode. If the pool
3214		 * is available for import in read-write mode, it is displayed
3215		 * as available in userland; if it is not available for import
3216		 * in read-only mode, it is displayed as unavailable in
3217		 * userland. If the pool is available for import in read-only
3218		 * mode but not read-write mode, it is displayed as unavailable
3219		 * in userland with a special note that the pool is actually
3220		 * available for open in read-only mode.
3221		 *
3222		 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3223		 * missing a feature for write, we must first determine whether
3224		 * the pool can be opened read-only before returning to
3225		 * userland in order to know whether to display the
3226		 * abovementioned note.
3227		 */
3228		if (missing_feat_read || (*missing_feat_writep &&
3229		    spa_writeable(spa))) {
3230			spa_load_failed(spa, "pool uses unsupported features");
3231			return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3232			    ENOTSUP));
3233		}
3234
3235		/*
3236		 * Load refcounts for ZFS features from disk into an in-memory
3237		 * cache during SPA initialization.
3238		 */
3239		for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
3240			uint64_t refcount;
3241
3242			error = feature_get_refcount_from_disk(spa,
3243			    &spa_feature_table[i], &refcount);
3244			if (error == 0) {
3245				spa->spa_feat_refcount_cache[i] = refcount;
3246			} else if (error == ENOTSUP) {
3247				spa->spa_feat_refcount_cache[i] =
3248				    SPA_FEATURE_DISABLED;
3249			} else {
3250				spa_load_failed(spa, "error getting refcount "
3251				    "for feature %s [error=%d]",
3252				    spa_feature_table[i].fi_guid, error);
3253				return (spa_vdev_err(rvd,
3254				    VDEV_AUX_CORRUPT_DATA, EIO));
3255			}
3256		}
3257	}
3258
3259	if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3260		if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
3261		    &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
3262			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3263	}
3264
3265	return (0);
3266}
3267
3268static int
3269spa_ld_load_special_directories(spa_t *spa)
3270{
3271	int error = 0;
3272	vdev_t *rvd = spa->spa_root_vdev;
3273
3274	spa->spa_is_initializing = B_TRUE;
3275	error = dsl_pool_open(spa->spa_dsl_pool);
3276	spa->spa_is_initializing = B_FALSE;
3277	if (error != 0) {
3278		spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3279		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3280	}
3281
3282	return (0);
3283}
3284
3285static int
3286spa_ld_get_props(spa_t *spa)
3287{
3288	int error = 0;
3289	uint64_t obj;
3290	vdev_t *rvd = spa->spa_root_vdev;
3291
3292	/* Grab the secret checksum salt from the MOS. */
3293	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3294	    DMU_POOL_CHECKSUM_SALT, 1,
3295	    sizeof (spa->spa_cksum_salt.zcs_bytes),
3296	    spa->spa_cksum_salt.zcs_bytes);
3297	if (error == ENOENT) {
3298		/* Generate a new salt for subsequent use */
3299		(void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3300		    sizeof (spa->spa_cksum_salt.zcs_bytes));
3301	} else if (error != 0) {
3302		spa_load_failed(spa, "unable to retrieve checksum salt from "
3303		    "MOS [error=%d]", error);
3304		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3305	}
3306
3307	if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3308		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3309	error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3310	if (error != 0) {
3311		spa_load_failed(spa, "error opening deferred-frees bpobj "
3312		    "[error=%d]", error);
3313		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3314	}
3315
3316	/*
3317	 * Load the bit that tells us to use the new accounting function
3318	 * (raid-z deflation).  If we have an older pool, this will not
3319	 * be present.
3320	 */
3321	error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3322	if (error != 0 && error != ENOENT)
3323		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3324
3325	error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3326	    &spa->spa_creation_version, B_FALSE);
3327	if (error != 0 && error != ENOENT)
3328		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3329
3330	/*
3331	 * Load the persistent error log.  If we have an older pool, this will
3332	 * not be present.
3333	 */
3334	error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3335	    B_FALSE);
3336	if (error != 0 && error != ENOENT)
3337		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3338
3339	error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3340	    &spa->spa_errlog_scrub, B_FALSE);
3341	if (error != 0 && error != ENOENT)
3342		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3343
3344	/*
3345	 * Load the history object.  If we have an older pool, this
3346	 * will not be present.
3347	 */
3348	error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3349	if (error != 0 && error != ENOENT)
3350		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3351
3352	/*
3353	 * Load the per-vdev ZAP map. If we have an older pool, this will not
3354	 * be present; in this case, defer its creation to a later time to
3355	 * avoid dirtying the MOS this early / out of sync context. See
3356	 * spa_sync_config_object.
3357	 */
3358
3359	/* The sentinel is only available in the MOS config. */
3360	nvlist_t *mos_config;
3361	if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3362		spa_load_failed(spa, "unable to retrieve MOS config");
3363		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3364	}
3365
3366	error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3367	    &spa->spa_all_vdev_zaps, B_FALSE);
3368
3369	if (error == ENOENT) {
3370		VERIFY(!nvlist_exists(mos_config,
3371		    ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3372		spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3373		ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3374	} else if (error != 0) {
3375		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3376	} else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3377		/*
3378		 * An older version of ZFS overwrote the sentinel value, so
3379		 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3380		 * destruction to later; see spa_sync_config_object.
3381		 */
3382		spa->spa_avz_action = AVZ_ACTION_DESTROY;
3383		/*
3384		 * We're assuming that no vdevs have had their ZAPs created
3385		 * before this. Better be sure of it.
3386		 */
3387		ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3388	}
3389	nvlist_free(mos_config);
3390
3391	spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3392
3393	error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3394	    B_FALSE);
3395	if (error && error != ENOENT)
3396		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3397
3398	if (error == 0) {
3399		uint64_t autoreplace;
3400
3401		spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3402		spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3403		spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3404		spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3405		spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3406		spa_prop_find(spa, ZPOOL_PROP_MULTIHOST, &spa->spa_multihost);
3407		spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3408		    &spa->spa_dedup_ditto);
3409
3410		spa->spa_autoreplace = (autoreplace != 0);
3411	}
3412
3413	/*
3414	 * If we are importing a pool with missing top-level vdevs,
3415	 * we enforce that the pool doesn't panic or get suspended on
3416	 * error since the likelihood of missing data is extremely high.
3417	 */
3418	if (spa->spa_missing_tvds > 0 &&
3419	    spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3420	    spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3421		spa_load_note(spa, "forcing failmode to 'continue' "
3422		    "as some top level vdevs are missing");
3423		spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3424	}
3425
3426	return (0);
3427}
3428
3429static int
3430spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3431{
3432	int error = 0;
3433	vdev_t *rvd = spa->spa_root_vdev;
3434
3435	/*
3436	 * If we're assembling the pool from the split-off vdevs of
3437	 * an existing pool, we don't want to attach the spares & cache
3438	 * devices.
3439	 */
3440
3441	/*
3442	 * Load any hot spares for this pool.
3443	 */
3444	error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3445	    B_FALSE);
3446	if (error != 0 && error != ENOENT)
3447		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3448	if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3449		ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3450		if (load_nvlist(spa, spa->spa_spares.sav_object,
3451		    &spa->spa_spares.sav_config) != 0) {
3452			spa_load_failed(spa, "error loading spares nvlist");
3453			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3454		}
3455
3456		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3457		spa_load_spares(spa);
3458		spa_config_exit(spa, SCL_ALL, FTAG);
3459	} else if (error == 0) {
3460		spa->spa_spares.sav_sync = B_TRUE;
3461	}
3462
3463	/*
3464	 * Load any level 2 ARC devices for this pool.
3465	 */
3466	error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3467	    &spa->spa_l2cache.sav_object, B_FALSE);
3468	if (error != 0 && error != ENOENT)
3469		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3470	if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3471		ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3472		if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3473		    &spa->spa_l2cache.sav_config) != 0) {
3474			spa_load_failed(spa, "error loading l2cache nvlist");
3475			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3476		}
3477
3478		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3479		spa_load_l2cache(spa);
3480		spa_config_exit(spa, SCL_ALL, FTAG);
3481	} else if (error == 0) {
3482		spa->spa_l2cache.sav_sync = B_TRUE;
3483	}
3484
3485	return (0);
3486}
3487
3488static int
3489spa_ld_load_vdev_metadata(spa_t *spa)
3490{
3491	int error = 0;
3492	vdev_t *rvd = spa->spa_root_vdev;
3493
3494	/*
3495	 * If the 'multihost' property is set, then never allow a pool to
3496	 * be imported when the system hostid is zero.  The exception to
3497	 * this rule is zdb which is always allowed to access pools.
3498	 */
3499	if (spa_multihost(spa) && spa_get_hostid() == 0 &&
3500	    (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP) == 0) {
3501		fnvlist_add_uint64(spa->spa_load_info,
3502		    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3503		return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3504	}
3505
3506	/*
3507	 * If the 'autoreplace' property is set, then post a resource notifying
3508	 * the ZFS DE that it should not issue any faults for unopenable
3509	 * devices.  We also iterate over the vdevs, and post a sysevent for any
3510	 * unopenable vdevs so that the normal autoreplace handler can take
3511	 * over.
3512	 */
3513	if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3514		spa_check_removed(spa->spa_root_vdev);
3515		/*
3516		 * For the import case, this is done in spa_import(), because
3517		 * at this point we're using the spare definitions from
3518		 * the MOS config, not necessarily from the userland config.
3519		 */
3520		if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3521			spa_aux_check_removed(&spa->spa_spares);
3522			spa_aux_check_removed(&spa->spa_l2cache);
3523		}
3524	}
3525
3526	/*
3527	 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3528	 */
3529	error = vdev_load(rvd);
3530	if (error != 0) {
3531		spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3532		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3533	}
3534
3535	/*
3536	 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3537	 */
3538	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3539	vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3540	spa_config_exit(spa, SCL_ALL, FTAG);
3541
3542	return (0);
3543}
3544
3545static int
3546spa_ld_load_dedup_tables(spa_t *spa)
3547{
3548	int error = 0;
3549	vdev_t *rvd = spa->spa_root_vdev;
3550
3551	error = ddt_load(spa);
3552	if (error != 0) {
3553		spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3554		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3555	}
3556
3557	return (0);
3558}
3559
3560static int
3561spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3562{
3563	vdev_t *rvd = spa->spa_root_vdev;
3564
3565	if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3566		boolean_t missing = spa_check_logs(spa);
3567		if (missing) {
3568			if (spa->spa_missing_tvds != 0) {
3569				spa_load_note(spa, "spa_check_logs failed "
3570				    "so dropping the logs");
3571			} else {
3572				*ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3573				spa_load_failed(spa, "spa_check_logs failed");
3574				return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3575				    ENXIO));
3576			}
3577		}
3578	}
3579
3580	return (0);
3581}
3582
3583static int
3584spa_ld_verify_pool_data(spa_t *spa)
3585{
3586	int error = 0;
3587	vdev_t *rvd = spa->spa_root_vdev;
3588
3589	/*
3590	 * We've successfully opened the pool, verify that we're ready
3591	 * to start pushing transactions.
3592	 */
3593	if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3594		error = spa_load_verify(spa);
3595		if (error != 0) {
3596			spa_load_failed(spa, "spa_load_verify failed "
3597			    "[error=%d]", error);
3598			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3599			    error));
3600		}
3601	}
3602
3603	return (0);
3604}
3605
3606static void
3607spa_ld_claim_log_blocks(spa_t *spa)
3608{
3609	dmu_tx_t *tx;
3610	dsl_pool_t *dp = spa_get_dsl(spa);
3611
3612	/*
3613	 * Claim log blocks that haven't been committed yet.
3614	 * This must all happen in a single txg.
3615	 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3616	 * invoked from zil_claim_log_block()'s i/o done callback.
3617	 * Price of rollback is that we abandon the log.
3618	 */
3619	spa->spa_claiming = B_TRUE;
3620
3621	tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3622	(void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3623	    zil_claim, tx, DS_FIND_CHILDREN);
3624	dmu_tx_commit(tx);
3625
3626	spa->spa_claiming = B_FALSE;
3627
3628	spa_set_log_state(spa, SPA_LOG_GOOD);
3629}
3630
3631static void
3632spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3633    boolean_t update_config_cache)
3634{
3635	vdev_t *rvd = spa->spa_root_vdev;
3636	int need_update = B_FALSE;
3637
3638	/*
3639	 * If the config cache is stale, or we have uninitialized
3640	 * metaslabs (see spa_vdev_add()), then update the config.
3641	 *
3642	 * If this is a verbatim import, trust the current
3643	 * in-core spa_config and update the disk labels.
3644	 */
3645	if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
3646	    spa->spa_load_state == SPA_LOAD_IMPORT ||
3647	    spa->spa_load_state == SPA_LOAD_RECOVER ||
3648	    (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3649		need_update = B_TRUE;
3650
3651	for (int c = 0; c < rvd->vdev_children; c++)
3652		if (rvd->vdev_child[c]->vdev_ms_array == 0)
3653			need_update = B_TRUE;
3654
3655	/*
3656	 * Update the config cache asychronously in case we're the
3657	 * root pool, in which case the config cache isn't writable yet.
3658	 */
3659	if (need_update)
3660		spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3661}
3662
3663static void
3664spa_ld_prepare_for_reload(spa_t *spa)
3665{
3666	int mode = spa->spa_mode;
3667	int async_suspended = spa->spa_async_suspended;
3668
3669	spa_unload(spa);
3670	spa_deactivate(spa);
3671	spa_activate(spa, mode);
3672
3673	/*
3674	 * We save the value of spa_async_suspended as it gets reset to 0 by
3675	 * spa_unload(). We want to restore it back to the original value before
3676	 * returning as we might be calling spa_async_resume() later.
3677	 */
3678	spa->spa_async_suspended = async_suspended;
3679}
3680
3681static int
3682spa_ld_read_checkpoint_txg(spa_t *spa)
3683{
3684	uberblock_t checkpoint;
3685	int error = 0;
3686
3687	ASSERT0(spa->spa_checkpoint_txg);
3688	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3689
3690	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3691	    DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3692	    sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3693
3694	if (error == ENOENT)
3695		return (0);
3696
3697	if (error != 0)
3698		return (error);
3699
3700	ASSERT3U(checkpoint.ub_txg, !=, 0);
3701	ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3702	ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3703	spa->spa_checkpoint_txg = checkpoint.ub_txg;
3704	spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3705
3706	return (0);
3707}
3708
3709static int
3710spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
3711{
3712	int error = 0;
3713
3714	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3715	ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3716
3717	/*
3718	 * Never trust the config that is provided unless we are assembling
3719	 * a pool following a split.
3720	 * This means don't trust blkptrs and the vdev tree in general. This
3721	 * also effectively puts the spa in read-only mode since
3722	 * spa_writeable() checks for spa_trust_config to be true.
3723	 * We will later load a trusted config from the MOS.
3724	 */
3725	if (type != SPA_IMPORT_ASSEMBLE)
3726		spa->spa_trust_config = B_FALSE;
3727
3728	/*
3729	 * Parse the config provided to create a vdev tree.
3730	 */
3731	error = spa_ld_parse_config(spa, type);
3732	if (error != 0)
3733		return (error);
3734
3735	/*
3736	 * Now that we have the vdev tree, try to open each vdev. This involves
3737	 * opening the underlying physical device, retrieving its geometry and
3738	 * probing the vdev with a dummy I/O. The state of each vdev will be set
3739	 * based on the success of those operations. After this we'll be ready
3740	 * to read from the vdevs.
3741	 */
3742	error = spa_ld_open_vdevs(spa);
3743	if (error != 0)
3744		return (error);
3745
3746	/*
3747	 * Read the label of each vdev and make sure that the GUIDs stored
3748	 * there match the GUIDs in the config provided.
3749	 * If we're assembling a new pool that's been split off from an
3750	 * existing pool, the labels haven't yet been updated so we skip
3751	 * validation for now.
3752	 */
3753	if (type != SPA_IMPORT_ASSEMBLE) {
3754		error = spa_ld_validate_vdevs(spa);
3755		if (error != 0)
3756			return (error);
3757	}
3758
3759	/*
3760	 * Read all vdev labels to find the best uberblock (i.e. latest,
3761	 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3762	 * get the list of features required to read blkptrs in the MOS from
3763	 * the vdev label with the best uberblock and verify that our version
3764	 * of zfs supports them all.
3765	 */
3766	error = spa_ld_select_uberblock(spa, type);
3767	if (error != 0)
3768		return (error);
3769
3770	/*
3771	 * Pass that uberblock to the dsl_pool layer which will open the root
3772	 * blkptr. This blkptr points to the latest version of the MOS and will
3773	 * allow us to read its contents.
3774	 */
3775	error = spa_ld_open_rootbp(spa);
3776	if (error != 0)
3777		return (error);
3778
3779	return (0);
3780}
3781
3782static int
3783spa_ld_checkpoint_rewind(spa_t *spa)
3784{
3785	uberblock_t checkpoint;
3786	int error = 0;
3787
3788	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3789	ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3790
3791	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3792	    DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3793	    sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3794
3795	if (error != 0) {
3796		spa_load_failed(spa, "unable to retrieve checkpointed "
3797		    "uberblock from the MOS config [error=%d]", error);
3798
3799		if (error == ENOENT)
3800			error = ZFS_ERR_NO_CHECKPOINT;
3801
3802		return (error);
3803	}
3804
3805	ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
3806	ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
3807
3808	/*
3809	 * We need to update the txg and timestamp of the checkpointed
3810	 * uberblock to be higher than the latest one. This ensures that
3811	 * the checkpointed uberblock is selected if we were to close and
3812	 * reopen the pool right after we've written it in the vdev labels.
3813	 * (also see block comment in vdev_uberblock_compare)
3814	 */
3815	checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
3816	checkpoint.ub_timestamp = gethrestime_sec();
3817
3818	/*
3819	 * Set current uberblock to be the checkpointed uberblock.
3820	 */
3821	spa->spa_uberblock = checkpoint;
3822
3823	/*
3824	 * If we are doing a normal rewind, then the pool is open for
3825	 * writing and we sync the "updated" checkpointed uberblock to
3826	 * disk. Once this is done, we've basically rewound the whole
3827	 * pool and there is no way back.
3828	 *
3829	 * There are cases when we don't want to attempt and sync the
3830	 * checkpointed uberblock to disk because we are opening a
3831	 * pool as read-only. Specifically, verifying the checkpointed
3832	 * state with zdb, and importing the checkpointed state to get
3833	 * a "preview" of its content.
3834	 */
3835	if (spa_writeable(spa)) {
3836		vdev_t *rvd = spa->spa_root_vdev;
3837
3838		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3839		vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
3840		int svdcount = 0;
3841		int children = rvd->vdev_children;
3842		int c0 = spa_get_random(children);
3843
3844		for (int c = 0; c < children; c++) {
3845			vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
3846
3847			/* Stop when revisiting the first vdev */
3848			if (c > 0 && svd[0] == vd)
3849				break;
3850
3851			if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
3852			    !vdev_is_concrete(vd))
3853				continue;
3854
3855			svd[svdcount++] = vd;
3856			if (svdcount == SPA_SYNC_MIN_VDEVS)
3857				break;
3858		}
3859		error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
3860		if (error == 0)
3861			spa->spa_last_synced_guid = rvd->vdev_guid;
3862		spa_config_exit(spa, SCL_ALL, FTAG);
3863
3864		if (error != 0) {
3865			spa_load_failed(spa, "failed to write checkpointed "
3866			    "uberblock to the vdev labels [error=%d]", error);
3867			return (error);
3868		}
3869	}
3870
3871	return (0);
3872}
3873
3874static int
3875spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
3876    boolean_t *update_config_cache)
3877{
3878	int error;
3879
3880	/*
3881	 * Parse the config for pool, open and validate vdevs,
3882	 * select an uberblock, and use that uberblock to open
3883	 * the MOS.
3884	 */
3885	error = spa_ld_mos_init(spa, type);
3886	if (error != 0)
3887		return (error);
3888
3889	/*
3890	 * Retrieve the trusted config stored in the MOS and use it to create
3891	 * a new, exact version of the vdev tree, then reopen all vdevs.
3892	 */
3893	error = spa_ld_trusted_config(spa, type, B_FALSE);
3894	if (error == EAGAIN) {
3895		if (update_config_cache != NULL)
3896			*update_config_cache = B_TRUE;
3897
3898		/*
3899		 * Redo the loading process with the trusted config if it is
3900		 * too different from the untrusted config.
3901		 */
3902		spa_ld_prepare_for_reload(spa);
3903		spa_load_note(spa, "RELOADING");
3904		error = spa_ld_mos_init(spa, type);
3905		if (error != 0)
3906			return (error);
3907
3908		error = spa_ld_trusted_config(spa, type, B_TRUE);
3909		if (error != 0)
3910			return (error);
3911
3912	} else if (error != 0) {
3913		return (error);
3914	}
3915
3916	return (0);
3917}
3918
3919/*
3920 * Load an existing storage pool, using the config provided. This config
3921 * describes which vdevs are part of the pool and is later validated against
3922 * partial configs present in each vdev's label and an entire copy of the
3923 * config stored in the MOS.
3924 */
3925static int
3926spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
3927{
3928	int error = 0;
3929	boolean_t missing_feat_write = B_FALSE;
3930	boolean_t checkpoint_rewind =
3931	    (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3932	boolean_t update_config_cache = B_FALSE;
3933
3934	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3935	ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3936
3937	spa_load_note(spa, "LOADING");
3938
3939	error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
3940	if (error != 0)
3941		return (error);
3942
3943	/*
3944	 * If we are rewinding to the checkpoint then we need to repeat
3945	 * everything we've done so far in this function but this time
3946	 * selecting the checkpointed uberblock and using that to open
3947	 * the MOS.
3948	 */
3949	if (checkpoint_rewind) {
3950		/*
3951		 * If we are rewinding to the checkpoint update config cache
3952		 * anyway.
3953		 */
3954		update_config_cache = B_TRUE;
3955
3956		/*
3957		 * Extract the checkpointed uberblock from the current MOS
3958		 * and use this as the pool's uberblock from now on. If the
3959		 * pool is imported as writeable we also write the checkpoint
3960		 * uberblock to the labels, making the rewind permanent.
3961		 */
3962		error = spa_ld_checkpoint_rewind(spa);
3963		if (error != 0)
3964			return (error);
3965
3966		/*
3967		 * Redo the loading process process again with the
3968		 * checkpointed uberblock.
3969		 */
3970		spa_ld_prepare_for_reload(spa);
3971		spa_load_note(spa, "LOADING checkpointed uberblock");
3972		error = spa_ld_mos_with_trusted_config(spa, type, NULL);
3973		if (error != 0)
3974			return (error);
3975	}
3976
3977	/*
3978	 * Retrieve the checkpoint txg if the pool has a checkpoint.
3979	 */
3980	error = spa_ld_read_checkpoint_txg(spa);
3981	if (error != 0)
3982		return (error);
3983
3984	/*
3985	 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
3986	 * from the pool and their contents were re-mapped to other vdevs. Note
3987	 * that everything that we read before this step must have been
3988	 * rewritten on concrete vdevs after the last device removal was
3989	 * initiated. Otherwise we could be reading from indirect vdevs before
3990	 * we have loaded their mappings.
3991	 */
3992	error = spa_ld_open_indirect_vdev_metadata(spa);
3993	if (error != 0)
3994		return (error);
3995
3996	/*
3997	 * Retrieve the full list of active features from the MOS and check if
3998	 * they are all supported.
3999	 */
4000	error = spa_ld_check_features(spa, &missing_feat_write);
4001	if (error != 0)
4002		return (error);
4003
4004	/*
4005	 * Load several special directories from the MOS needed by the dsl_pool
4006	 * layer.
4007	 */
4008	error = spa_ld_load_special_directories(spa);
4009	if (error != 0)
4010		return (error);
4011
4012	/*
4013	 * Retrieve pool properties from the MOS.
4014	 */
4015	error = spa_ld_get_props(spa);
4016	if (error != 0)
4017		return (error);
4018
4019	/*
4020	 * Retrieve the list of auxiliary devices - cache devices and spares -
4021	 * and open them.
4022	 */
4023	error = spa_ld_open_aux_vdevs(spa, type);
4024	if (error != 0)
4025		return (error);
4026
4027	/*
4028	 * Load the metadata for all vdevs. Also check if unopenable devices
4029	 * should be autoreplaced.
4030	 */
4031	error = spa_ld_load_vdev_metadata(spa);
4032	if (error != 0)
4033		return (error);
4034
4035	error = spa_ld_load_dedup_tables(spa);
4036	if (error != 0)
4037		return (error);
4038
4039	/*
4040	 * Verify the logs now to make sure we don't have any unexpected errors
4041	 * when we claim log blocks later.
4042	 */
4043	error = spa_ld_verify_logs(spa, type, ereport);
4044	if (error != 0)
4045		return (error);
4046
4047	if (missing_feat_write) {
4048		ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
4049
4050		/*
4051		 * At this point, we know that we can open the pool in
4052		 * read-only mode but not read-write mode. We now have enough
4053		 * information and can return to userland.
4054		 */
4055		return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
4056		    ENOTSUP));
4057	}
4058
4059	/*
4060	 * Traverse the last txgs to make sure the pool was left off in a safe
4061	 * state. When performing an extreme rewind, we verify the whole pool,
4062	 * which can take a very long time.
4063	 */
4064	error = spa_ld_verify_pool_data(spa);
4065	if (error != 0)
4066		return (error);
4067
4068	/*
4069	 * Calculate the deflated space for the pool. This must be done before
4070	 * we write anything to the pool because we'd need to update the space
4071	 * accounting using the deflated sizes.
4072	 */
4073	spa_update_dspace(spa);
4074
4075	/*
4076	 * We have now retrieved all the information we needed to open the
4077	 * pool. If we are importing the pool in read-write mode, a few
4078	 * additional steps must be performed to finish the import.
4079	 */
4080	if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
4081	    spa->spa_load_max_txg == UINT64_MAX)) {
4082		uint64_t config_cache_txg = spa->spa_config_txg;
4083
4084		ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
4085
4086		/*
4087		 * In case of a checkpoint rewind, log the original txg
4088		 * of the checkpointed uberblock.
4089		 */
4090		if (checkpoint_rewind) {
4091			spa_history_log_internal(spa, "checkpoint rewind",
4092			    NULL, "rewound state to txg=%llu",
4093			    (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
4094		}
4095
4096		/*
4097		 * Traverse the ZIL and claim all blocks.
4098		 */
4099		spa_ld_claim_log_blocks(spa);
4100
4101		/*
4102		 * Kick-off the syncing thread.
4103		 */
4104		spa->spa_sync_on = B_TRUE;
4105		txg_sync_start(spa->spa_dsl_pool);
4106		mmp_thread_start(spa);
4107
4108		/*
4109		 * Wait for all claims to sync.  We sync up to the highest
4110		 * claimed log block birth time so that claimed log blocks
4111		 * don't appear to be from the future.  spa_claim_max_txg
4112		 * will have been set for us by ZIL traversal operations
4113		 * performed above.
4114		 */
4115		txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
4116
4117		/*
4118		 * Check if we need to request an update of the config. On the
4119		 * next sync, we would update the config stored in vdev labels
4120		 * and the cachefile (by default /etc/zfs/zpool.cache).
4121		 */
4122		spa_ld_check_for_config_update(spa, config_cache_txg,
4123		    update_config_cache);
4124
4125		/*
4126		 * Check all DTLs to see if anything needs resilvering.
4127		 */
4128		if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
4129		    vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
4130			spa_async_request(spa, SPA_ASYNC_RESILVER);
4131
4132		/*
4133		 * Log the fact that we booted up (so that we can detect if
4134		 * we rebooted in the middle of an operation).
4135		 */
4136		spa_history_log_version(spa, "open");
4137
4138		spa_restart_removal(spa);
4139		spa_spawn_aux_threads(spa);
4140
4141		/*
4142		 * Delete any inconsistent datasets.
4143		 *
4144		 * Note:
4145		 * Since we may be issuing deletes for clones here,
4146		 * we make sure to do so after we've spawned all the
4147		 * auxiliary threads above (from which the livelist
4148		 * deletion zthr is part of).
4149		 */
4150		(void) dmu_objset_find(spa_name(spa),
4151		    dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
4152
4153		/*
4154		 * Clean up any stale temporary dataset userrefs.
4155		 */
4156		dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
4157
4158		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4159		vdev_initialize_restart(spa->spa_root_vdev);
4160		spa_config_exit(spa, SCL_CONFIG, FTAG);
4161	}
4162
4163	spa_load_note(spa, "LOADED");
4164
4165	return (0);
4166}
4167
4168static int
4169spa_load_retry(spa_t *spa, spa_load_state_t state)
4170{
4171	int mode = spa->spa_mode;
4172
4173	spa_unload(spa);
4174	spa_deactivate(spa);
4175
4176	spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
4177
4178	spa_activate(spa, mode);
4179	spa_async_suspend(spa);
4180
4181	spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
4182	    (u_longlong_t)spa->spa_load_max_txg);
4183
4184	return (spa_load(spa, state, SPA_IMPORT_EXISTING));
4185}
4186
4187/*
4188 * If spa_load() fails this function will try loading prior txg's. If
4189 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
4190 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
4191 * function will not rewind the pool and will return the same error as
4192 * spa_load().
4193 */
4194static int
4195spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4196    int rewind_flags)
4197{
4198	nvlist_t *loadinfo = NULL;
4199	nvlist_t *config = NULL;
4200	int load_error, rewind_error;
4201	uint64_t safe_rewind_txg;
4202	uint64_t min_txg;
4203
4204	if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4205		spa->spa_load_max_txg = spa->spa_load_txg;
4206		spa_set_log_state(spa, SPA_LOG_CLEAR);
4207	} else {
4208		spa->spa_load_max_txg = max_request;
4209		if (max_request != UINT64_MAX)
4210			spa->spa_extreme_rewind = B_TRUE;
4211	}
4212
4213	load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
4214	if (load_error == 0)
4215		return (0);
4216	if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4217		/*
4218		 * When attempting checkpoint-rewind on a pool with no
4219		 * checkpoint, we should not attempt to load uberblocks
4220		 * from previous txgs when spa_load fails.
4221		 */
4222		ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4223		return (load_error);
4224	}
4225
4226	if (spa->spa_root_vdev != NULL)
4227		config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4228
4229	spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4230	spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4231
4232	if (rewind_flags & ZPOOL_NEVER_REWIND) {
4233		nvlist_free(config);
4234		return (load_error);
4235	}
4236
4237	if (state == SPA_LOAD_RECOVER) {
4238		/* Price of rolling back is discarding txgs, including log */
4239		spa_set_log_state(spa, SPA_LOG_CLEAR);
4240	} else {
4241		/*
4242		 * If we aren't rolling back save the load info from our first
4243		 * import attempt so that we can restore it after attempting
4244		 * to rewind.
4245		 */
4246		loadinfo = spa->spa_load_info;
4247		spa->spa_load_info = fnvlist_alloc();
4248	}
4249
4250	spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4251	safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4252	min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4253	    TXG_INITIAL : safe_rewind_txg;
4254
4255	/*
4256	 * Continue as long as we're finding errors, we're still within
4257	 * the acceptable rewind range, and we're still finding uberblocks
4258	 */
4259	while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4260	    spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4261		if (spa->spa_load_max_txg < safe_rewind_txg)
4262			spa->spa_extreme_rewind = B_TRUE;
4263		rewind_error = spa_load_retry(spa, state);
4264	}
4265
4266	spa->spa_extreme_rewind = B_FALSE;
4267	spa->spa_load_max_txg = UINT64_MAX;
4268
4269	if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4270		spa_config_set(spa, config);
4271	else
4272		nvlist_free(config);
4273
4274	if (state == SPA_LOAD_RECOVER) {
4275		ASSERT3P(loadinfo, ==, NULL);
4276		return (rewind_error);
4277	} else {
4278		/* Store the rewind info as part of the initial load info */
4279		fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4280		    spa->spa_load_info);
4281
4282		/* Restore the initial load info */
4283		fnvlist_free(spa->spa_load_info);
4284		spa->spa_load_info = loadinfo;
4285
4286		return (load_error);
4287	}
4288}
4289
4290/*
4291 * Pool Open/Import
4292 *
4293 * The import case is identical to an open except that the configuration is sent
4294 * down from userland, instead of grabbed from the configuration cache.  For the
4295 * case of an open, the pool configuration will exist in the
4296 * POOL_STATE_UNINITIALIZED state.
4297 *
4298 * The stats information (gen/count/ustats) is used to gather vdev statistics at
4299 * the same time open the pool, without having to keep around the spa_t in some
4300 * ambiguous state.
4301 */
4302static int
4303spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4304    nvlist_t **config)
4305{
4306	spa_t *spa;
4307	spa_load_state_t state = SPA_LOAD_OPEN;
4308	int error;
4309	int locked = B_FALSE;
4310
4311	*spapp = NULL;
4312
4313	/*
4314	 * As disgusting as this is, we need to support recursive calls to this
4315	 * function because dsl_dir_open() is called during spa_load(), and ends
4316	 * up calling spa_open() again.  The real fix is to figure out how to
4317	 * avoid dsl_dir_open() calling this in the first place.
4318	 */
4319	if (mutex_owner(&spa_namespace_lock) != curthread) {
4320		mutex_enter(&spa_namespace_lock);
4321		locked = B_TRUE;
4322	}
4323
4324	if ((spa = spa_lookup(pool)) == NULL) {
4325		if (locked)
4326			mutex_exit(&spa_namespace_lock);
4327		return (SET_ERROR(ENOENT));
4328	}
4329
4330	if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
4331		zpool_load_policy_t policy;
4332
4333		zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
4334		    &policy);
4335		if (policy.zlp_rewind & ZPOOL_DO_REWIND)
4336			state = SPA_LOAD_RECOVER;
4337
4338		spa_activate(spa, spa_mode_global);
4339
4340		if (state != SPA_LOAD_RECOVER)
4341			spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4342		spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
4343
4344		zfs_dbgmsg("spa_open_common: opening %s", pool);
4345		error = spa_load_best(spa, state, policy.zlp_txg,
4346		    policy.zlp_rewind);
4347
4348		if (error == EBADF) {
4349			/*
4350			 * If vdev_validate() returns failure (indicated by
4351			 * EBADF), it indicates that one of the vdevs indicates
4352			 * that the pool has been exported or destroyed.  If
4353			 * this is the case, the config cache is out of sync and
4354			 * we should remove the pool from the namespace.
4355			 */
4356			spa_unload(spa);
4357			spa_deactivate(spa);
4358			spa_write_cachefile(spa, B_TRUE, B_TRUE);
4359			spa_remove(spa);
4360			if (locked)
4361				mutex_exit(&spa_namespace_lock);
4362			return (SET_ERROR(ENOENT));
4363		}
4364
4365		if (error) {
4366			/*
4367			 * We can't open the pool, but we still have useful
4368			 * information: the state of each vdev after the
4369			 * attempted vdev_open().  Return this to the user.
4370			 */
4371			if (config != NULL && spa->spa_config) {
4372				VERIFY(nvlist_dup(spa->spa_config, config,
4373				    KM_SLEEP) == 0);
4374				VERIFY(nvlist_add_nvlist(*config,
4375				    ZPOOL_CONFIG_LOAD_INFO,
4376				    spa->spa_load_info) == 0);
4377			}
4378			spa_unload(spa);
4379			spa_deactivate(spa);
4380			spa->spa_last_open_failed = error;
4381			if (locked)
4382				mutex_exit(&spa_namespace_lock);
4383			*spapp = NULL;
4384			return (error);
4385		}
4386	}
4387
4388	spa_open_ref(spa, tag);
4389
4390	if (config != NULL)
4391		*config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4392
4393	/*
4394	 * If we've recovered the pool, pass back any information we
4395	 * gathered while doing the load.
4396	 */
4397	if (state == SPA_LOAD_RECOVER) {
4398		VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4399		    spa->spa_load_info) == 0);
4400	}
4401
4402	if (locked) {
4403		spa->spa_last_open_failed = 0;
4404		spa->spa_last_ubsync_txg = 0;
4405		spa->spa_load_txg = 0;
4406		mutex_exit(&spa_namespace_lock);
4407	}
4408
4409	*spapp = spa;
4410
4411	return (0);
4412}
4413
4414int
4415spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4416    nvlist_t **config)
4417{
4418	return (spa_open_common(name, spapp, tag, policy, config));
4419}
4420
4421int
4422spa_open(const char *name, spa_t **spapp, void *tag)
4423{
4424	return (spa_open_common(name, spapp, tag, NULL, NULL));
4425}
4426
4427/*
4428 * Lookup the given spa_t, incrementing the inject count in the process,
4429 * preventing it from being exported or destroyed.
4430 */
4431spa_t *
4432spa_inject_addref(char *name)
4433{
4434	spa_t *spa;
4435
4436	mutex_enter(&spa_namespace_lock);
4437	if ((spa = spa_lookup(name)) == NULL) {
4438		mutex_exit(&spa_namespace_lock);
4439		return (NULL);
4440	}
4441	spa->spa_inject_ref++;
4442	mutex_exit(&spa_namespace_lock);
4443
4444	return (spa);
4445}
4446
4447void
4448spa_inject_delref(spa_t *spa)
4449{
4450	mutex_enter(&spa_namespace_lock);
4451	spa->spa_inject_ref--;
4452	mutex_exit(&spa_namespace_lock);
4453}
4454
4455/*
4456 * Add spares device information to the nvlist.
4457 */
4458static void
4459spa_add_spares(spa_t *spa, nvlist_t *config)
4460{
4461	nvlist_t **spares;
4462	uint_t i, nspares;
4463	nvlist_t *nvroot;
4464	uint64_t guid;
4465	vdev_stat_t *vs;
4466	uint_t vsc;
4467	uint64_t pool;
4468
4469	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4470
4471	if (spa->spa_spares.sav_count == 0)
4472		return;
4473
4474	VERIFY(nvlist_lookup_nvlist(config,
4475	    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4476	VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4477	    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4478	if (nspares != 0) {
4479		VERIFY(nvlist_add_nvlist_array(nvroot,
4480		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4481		VERIFY(nvlist_lookup_nvlist_array(nvroot,
4482		    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4483
4484		/*
4485		 * Go through and find any spares which have since been
4486		 * repurposed as an active spare.  If this is the case, update
4487		 * their status appropriately.
4488		 */
4489		for (i = 0; i < nspares; i++) {
4490			VERIFY(nvlist_lookup_uint64(spares[i],
4491			    ZPOOL_CONFIG_GUID, &guid) == 0);
4492			if (spa_spare_exists(guid, &pool, NULL) &&
4493			    pool != 0ULL) {
4494				VERIFY(nvlist_lookup_uint64_array(
4495				    spares[i], ZPOOL_CONFIG_VDEV_STATS,
4496				    (uint64_t **)&vs, &vsc) == 0);
4497				vs->vs_state = VDEV_STATE_CANT_OPEN;
4498				vs->vs_aux = VDEV_AUX_SPARED;
4499			}
4500		}
4501	}
4502}
4503
4504/*
4505 * Add l2cache device information to the nvlist, including vdev stats.
4506 */
4507static void
4508spa_add_l2cache(spa_t *spa, nvlist_t *config)
4509{
4510	nvlist_t **l2cache;
4511	uint_t i, j, nl2cache;
4512	nvlist_t *nvroot;
4513	uint64_t guid;
4514	vdev_t *vd;
4515	vdev_stat_t *vs;
4516	uint_t vsc;
4517
4518	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4519
4520	if (spa->spa_l2cache.sav_count == 0)
4521		return;
4522
4523	VERIFY(nvlist_lookup_nvlist(config,
4524	    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4525	VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4526	    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4527	if (nl2cache != 0) {
4528		VERIFY(nvlist_add_nvlist_array(nvroot,
4529		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4530		VERIFY(nvlist_lookup_nvlist_array(nvroot,
4531		    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4532
4533		/*
4534		 * Update level 2 cache device stats.
4535		 */
4536
4537		for (i = 0; i < nl2cache; i++) {
4538			VERIFY(nvlist_lookup_uint64(l2cache[i],
4539			    ZPOOL_CONFIG_GUID, &guid) == 0);
4540
4541			vd = NULL;
4542			for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4543				if (guid ==
4544				    spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4545					vd = spa->spa_l2cache.sav_vdevs[j];
4546					break;
4547				}
4548			}
4549			ASSERT(vd != NULL);
4550
4551			VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4552			    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4553			    == 0);
4554			vdev_get_stats(vd, vs);
4555		}
4556	}
4557}
4558
4559static void
4560spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4561{
4562	nvlist_t *features;
4563	zap_cursor_t zc;
4564	zap_attribute_t za;
4565
4566	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4567	VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4568
4569	if (spa->spa_feat_for_read_obj != 0) {
4570		for (zap_cursor_init(&zc, spa->spa_meta_objset,
4571		    spa->spa_feat_for_read_obj);
4572		    zap_cursor_retrieve(&zc, &za) == 0;
4573		    zap_cursor_advance(&zc)) {
4574			ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4575			    za.za_num_integers == 1);
4576			VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4577			    za.za_first_integer));
4578		}
4579		zap_cursor_fini(&zc);
4580	}
4581
4582	if (spa->spa_feat_for_write_obj != 0) {
4583		for (zap_cursor_init(&zc, spa->spa_meta_objset,
4584		    spa->spa_feat_for_write_obj);
4585		    zap_cursor_retrieve(&zc, &za) == 0;
4586		    zap_cursor_advance(&zc)) {
4587			ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4588			    za.za_num_integers == 1);
4589			VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4590			    za.za_first_integer));
4591		}
4592		zap_cursor_fini(&zc);
4593	}
4594
4595	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4596	    features) == 0);
4597	nvlist_free(features);
4598}
4599
4600int
4601spa_get_stats(const char *name, nvlist_t **config,
4602    char *altroot, size_t buflen)
4603{
4604	int error;
4605	spa_t *spa;
4606
4607	*config = NULL;
4608	error = spa_open_common(name, &spa, FTAG, NULL, config);
4609
4610	if (spa != NULL) {
4611		/*
4612		 * This still leaves a window of inconsistency where the spares
4613		 * or l2cache devices could change and the config would be
4614		 * self-inconsistent.
4615		 */
4616		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4617
4618		if (*config != NULL) {
4619			uint64_t loadtimes[2];
4620
4621			loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4622			loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4623			VERIFY(nvlist_add_uint64_array(*config,
4624			    ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4625
4626			VERIFY(nvlist_add_uint64(*config,
4627			    ZPOOL_CONFIG_ERRCOUNT,
4628			    spa_get_errlog_size(spa)) == 0);
4629
4630			if (spa_suspended(spa)) {
4631				VERIFY(nvlist_add_uint64(*config,
4632				    ZPOOL_CONFIG_SUSPENDED,
4633				    spa->spa_failmode) == 0);
4634				VERIFY(nvlist_add_uint64(*config,
4635				    ZPOOL_CONFIG_SUSPENDED_REASON,
4636				    spa->spa_suspended) == 0);
4637			}
4638
4639			spa_add_spares(spa, *config);
4640			spa_add_l2cache(spa, *config);
4641			spa_add_feature_stats(spa, *config);
4642		}
4643	}
4644
4645	/*
4646	 * We want to get the alternate root even for faulted pools, so we cheat
4647	 * and call spa_lookup() directly.
4648	 */
4649	if (altroot) {
4650		if (spa == NULL) {
4651			mutex_enter(&spa_namespace_lock);
4652			spa = spa_lookup(name);
4653			if (spa)
4654				spa_altroot(spa, altroot, buflen);
4655			else
4656				altroot[0] = '\0';
4657			spa = NULL;
4658			mutex_exit(&spa_namespace_lock);
4659		} else {
4660			spa_altroot(spa, altroot, buflen);
4661		}
4662	}
4663
4664	if (spa != NULL) {
4665		spa_config_exit(spa, SCL_CONFIG, FTAG);
4666		spa_close(spa, FTAG);
4667	}
4668
4669	return (error);
4670}
4671
4672/*
4673 * Validate that the auxiliary device array is well formed.  We must have an
4674 * array of nvlists, each which describes a valid leaf vdev.  If this is an
4675 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4676 * specified, as long as they are well-formed.
4677 */
4678static int
4679spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4680    spa_aux_vdev_t *sav, const char *config, uint64_t version,
4681    vdev_labeltype_t label)
4682{
4683	nvlist_t **dev;
4684	uint_t i, ndev;
4685	vdev_t *vd;
4686	int error;
4687
4688	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4689
4690	/*
4691	 * It's acceptable to have no devs specified.
4692	 */
4693	if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4694		return (0);
4695
4696	if (ndev == 0)
4697		return (SET_ERROR(EINVAL));
4698
4699	/*
4700	 * Make sure the pool is formatted with a version that supports this
4701	 * device type.
4702	 */
4703	if (spa_version(spa) < version)
4704		return (SET_ERROR(ENOTSUP));
4705
4706	/*
4707	 * Set the pending device list so we correctly handle device in-use
4708	 * checking.
4709	 */
4710	sav->sav_pending = dev;
4711	sav->sav_npending = ndev;
4712
4713	for (i = 0; i < ndev; i++) {
4714		if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4715		    mode)) != 0)
4716			goto out;
4717
4718		if (!vd->vdev_ops->vdev_op_leaf) {
4719			vdev_free(vd);
4720			error = SET_ERROR(EINVAL);
4721			goto out;
4722		}
4723
4724		vd->vdev_top = vd;
4725
4726		if ((error = vdev_open(vd)) == 0 &&
4727		    (error = vdev_label_init(vd, crtxg, label)) == 0) {
4728			VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4729			    vd->vdev_guid) == 0);
4730		}
4731
4732		vdev_free(vd);
4733
4734		if (error &&
4735		    (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
4736			goto out;
4737		else
4738			error = 0;
4739	}
4740
4741out:
4742	sav->sav_pending = NULL;
4743	sav->sav_npending = 0;
4744	return (error);
4745}
4746
4747static int
4748spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
4749{
4750	int error;
4751
4752	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4753
4754	if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4755	    &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
4756	    VDEV_LABEL_SPARE)) != 0) {
4757		return (error);
4758	}
4759
4760	return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4761	    &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
4762	    VDEV_LABEL_L2CACHE));
4763}
4764
4765static void
4766spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
4767    const char *config)
4768{
4769	int i;
4770
4771	if (sav->sav_config != NULL) {
4772		nvlist_t **olddevs;
4773		uint_t oldndevs;
4774		nvlist_t **newdevs;
4775
4776		/*
4777		 * Generate new dev list by concatentating with the
4778		 * current dev list.
4779		 */
4780		VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
4781		    &olddevs, &oldndevs) == 0);
4782
4783		newdevs = kmem_alloc(sizeof (void *) *
4784		    (ndevs + oldndevs), KM_SLEEP);
4785		for (i = 0; i < oldndevs; i++)
4786			VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
4787			    KM_SLEEP) == 0);
4788		for (i = 0; i < ndevs; i++)
4789			VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
4790			    KM_SLEEP) == 0);
4791
4792		VERIFY(nvlist_remove(sav->sav_config, config,
4793		    DATA_TYPE_NVLIST_ARRAY) == 0);
4794
4795		VERIFY(nvlist_add_nvlist_array(sav->sav_config,
4796		    config, newdevs, ndevs + oldndevs) == 0);
4797		for (i = 0; i < oldndevs + ndevs; i++)
4798			nvlist_free(newdevs[i]);
4799		kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
4800	} else {
4801		/*
4802		 * Generate a new dev list.
4803		 */
4804		VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
4805		    KM_SLEEP) == 0);
4806		VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
4807		    devs, ndevs) == 0);
4808	}
4809}
4810
4811/*
4812 * Stop and drop level 2 ARC devices
4813 */
4814void
4815spa_l2cache_drop(spa_t *spa)
4816{
4817	vdev_t *vd;
4818	int i;
4819	spa_aux_vdev_t *sav = &spa->spa_l2cache;
4820
4821	for (i = 0; i < sav->sav_count; i++) {
4822		uint64_t pool;
4823
4824		vd = sav->sav_vdevs[i];
4825		ASSERT(vd != NULL);
4826
4827		if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
4828		    pool != 0ULL && l2arc_vdev_present(vd))
4829			l2arc_remove_vdev(vd);
4830	}
4831}
4832
4833/*
4834 * Pool Creation
4835 */
4836int
4837spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
4838    nvlist_t *zplprops)
4839{
4840	spa_t *spa;
4841	char *altroot = NULL;
4842	vdev_t *rvd;
4843	dsl_pool_t *dp;
4844	dmu_tx_t *tx;
4845	int error = 0;
4846	uint64_t txg = TXG_INITIAL;
4847	nvlist_t **spares, **l2cache;
4848	uint_t nspares, nl2cache;
4849	uint64_t version, obj;
4850	boolean_t has_features;
4851	char *poolname;
4852	nvlist_t *nvl;
4853
4854	if (props == NULL ||
4855	    nvlist_lookup_string(props,
4856	    zpool_prop_to_name(ZPOOL_PROP_TNAME), &poolname) != 0)
4857		poolname = (char *)pool;
4858
4859	/*
4860	 * If this pool already exists, return failure.
4861	 */
4862	mutex_enter(&spa_namespace_lock);
4863	if (spa_lookup(poolname) != NULL) {
4864		mutex_exit(&spa_namespace_lock);
4865		return (SET_ERROR(EEXIST));
4866	}
4867
4868	/*
4869	 * Allocate a new spa_t structure.
4870	 */
4871	nvl = fnvlist_alloc();
4872	fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
4873	(void) nvlist_lookup_string(props,
4874	    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4875	spa = spa_add(poolname, nvl, altroot);
4876	fnvlist_free(nvl);
4877	spa_activate(spa, spa_mode_global);
4878
4879	if (props && (error = spa_prop_validate(spa, props))) {
4880		spa_deactivate(spa);
4881		spa_remove(spa);
4882		mutex_exit(&spa_namespace_lock);
4883		return (error);
4884	}
4885
4886	/*
4887	 * Temporary pool names should never be written to disk.
4888	 */
4889	if (poolname != pool)
4890		spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
4891
4892	has_features = B_FALSE;
4893	for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
4894	    elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
4895		if (zpool_prop_feature(nvpair_name(elem)))
4896			has_features = B_TRUE;
4897	}
4898
4899	if (has_features || nvlist_lookup_uint64(props,
4900	    zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
4901		version = SPA_VERSION;
4902	}
4903	ASSERT(SPA_VERSION_IS_SUPPORTED(version));
4904
4905	spa->spa_first_txg = txg;
4906	spa->spa_uberblock.ub_txg = txg - 1;
4907	spa->spa_uberblock.ub_version = version;
4908	spa->spa_ubsync = spa->spa_uberblock;
4909	spa->spa_load_state = SPA_LOAD_CREATE;
4910	spa->spa_removing_phys.sr_state = DSS_NONE;
4911	spa->spa_removing_phys.sr_removing_vdev = -1;
4912	spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
4913	spa->spa_indirect_vdevs_loaded = B_TRUE;
4914
4915	/*
4916	 * Create "The Godfather" zio to hold all async IOs
4917	 */
4918	spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
4919	    KM_SLEEP);
4920	for (int i = 0; i < max_ncpus; i++) {
4921		spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
4922		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4923		    ZIO_FLAG_GODFATHER);
4924	}
4925
4926	/*
4927	 * Create the root vdev.
4928	 */
4929	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4930
4931	error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
4932
4933	ASSERT(error != 0 || rvd != NULL);
4934	ASSERT(error != 0 || spa->spa_root_vdev == rvd);
4935
4936	if (error == 0 && !zfs_allocatable_devs(nvroot))
4937		error = SET_ERROR(EINVAL);
4938
4939	if (error == 0 &&
4940	    (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
4941	    (error = spa_validate_aux(spa, nvroot, txg,
4942	    VDEV_ALLOC_ADD)) == 0) {
4943		/*
4944		 * instantiate the metaslab groups (this will dirty the vdevs)
4945		 * we can no longer error exit past this point
4946		 */
4947		for (int c = 0; error == 0 && c < rvd->vdev_children; c++) {
4948			vdev_t *vd = rvd->vdev_child[c];
4949
4950			vdev_metaslab_set_size(vd);
4951			vdev_expand(vd, txg);
4952		}
4953	}
4954
4955	spa_config_exit(spa, SCL_ALL, FTAG);
4956
4957	if (error != 0) {
4958		spa_unload(spa);
4959		spa_deactivate(spa);
4960		spa_remove(spa);
4961		mutex_exit(&spa_namespace_lock);
4962		return (error);
4963	}
4964
4965	/*
4966	 * Get the list of spares, if specified.
4967	 */
4968	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4969	    &spares, &nspares) == 0) {
4970		VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
4971		    KM_SLEEP) == 0);
4972		VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4973		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4974		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4975		spa_load_spares(spa);
4976		spa_config_exit(spa, SCL_ALL, FTAG);
4977		spa->spa_spares.sav_sync = B_TRUE;
4978	}
4979
4980	/*
4981	 * Get the list of level 2 cache devices, if specified.
4982	 */
4983	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4984	    &l2cache, &nl2cache) == 0) {
4985		VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
4986		    NV_UNIQUE_NAME, KM_SLEEP) == 0);
4987		VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4988		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4989		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4990		spa_load_l2cache(spa);
4991		spa_config_exit(spa, SCL_ALL, FTAG);
4992		spa->spa_l2cache.sav_sync = B_TRUE;
4993	}
4994
4995	spa->spa_is_initializing = B_TRUE;
4996	spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
4997	spa->spa_meta_objset = dp->dp_meta_objset;
4998	spa->spa_is_initializing = B_FALSE;
4999
5000	/*
5001	 * Create DDTs (dedup tables).
5002	 */
5003	ddt_create(spa);
5004
5005	spa_update_dspace(spa);
5006
5007	tx = dmu_tx_create_assigned(dp, txg);
5008
5009	/*
5010	 * Create the pool config object.
5011	 */
5012	spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
5013	    DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
5014	    DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
5015
5016	if (zap_add(spa->spa_meta_objset,
5017	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
5018	    sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
5019		cmn_err(CE_PANIC, "failed to add pool config");
5020	}
5021
5022	if (spa_version(spa) >= SPA_VERSION_FEATURES)
5023		spa_feature_create_zap_objects(spa, tx);
5024
5025	if (zap_add(spa->spa_meta_objset,
5026	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
5027	    sizeof (uint64_t), 1, &version, tx) != 0) {
5028		cmn_err(CE_PANIC, "failed to add pool version");
5029	}
5030
5031	/* Newly created pools with the right version are always deflated. */
5032	if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
5033		spa->spa_deflate = TRUE;
5034		if (zap_add(spa->spa_meta_objset,
5035		    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
5036		    sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
5037			cmn_err(CE_PANIC, "failed to add deflate");
5038		}
5039	}
5040
5041	/*
5042	 * Create the deferred-free bpobj.  Turn off compression
5043	 * because sync-to-convergence takes longer if the blocksize
5044	 * keeps changing.
5045	 */
5046	obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
5047	dmu_object_set_compress(spa->spa_meta_objset, obj,
5048	    ZIO_COMPRESS_OFF, tx);
5049	if (zap_add(spa->spa_meta_objset,
5050	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
5051	    sizeof (uint64_t), 1, &obj, tx) != 0) {
5052		cmn_err(CE_PANIC, "failed to add bpobj");
5053	}
5054	VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
5055	    spa->spa_meta_objset, obj));
5056
5057	/*
5058	 * Create the pool's history object.
5059	 */
5060	if (version >= SPA_VERSION_ZPOOL_HISTORY)
5061		spa_history_create_obj(spa, tx);
5062
5063	/*
5064	 * Generate some random noise for salted checksums to operate on.
5065	 */
5066	(void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
5067	    sizeof (spa->spa_cksum_salt.zcs_bytes));
5068
5069	/*
5070	 * Set pool properties.
5071	 */
5072	spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
5073	spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
5074	spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
5075	spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
5076	spa->spa_multihost = zpool_prop_default_numeric(ZPOOL_PROP_MULTIHOST);
5077
5078	if (props != NULL) {
5079		spa_configfile_set(spa, props, B_FALSE);
5080		spa_sync_props(props, tx);
5081	}
5082
5083	dmu_tx_commit(tx);
5084
5085	spa->spa_sync_on = B_TRUE;
5086	txg_sync_start(spa->spa_dsl_pool);
5087	mmp_thread_start(spa);
5088
5089	/*
5090	 * We explicitly wait for the first transaction to complete so that our
5091	 * bean counters are appropriately updated.
5092	 */
5093	txg_wait_synced(spa->spa_dsl_pool, txg);
5094
5095	spa_spawn_aux_threads(spa);
5096
5097	spa_write_cachefile(spa, B_FALSE, B_TRUE);
5098	spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
5099
5100	spa_history_log_version(spa, "create");
5101
5102	/*
5103	 * Don't count references from objsets that are already closed
5104	 * and are making their way through the eviction process.
5105	 */
5106	spa_evicting_os_wait(spa);
5107	spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
5108	spa->spa_load_state = SPA_LOAD_NONE;
5109
5110	mutex_exit(&spa_namespace_lock);
5111
5112	return (0);
5113}
5114
5115#ifdef _KERNEL
5116/*
5117 * Get the root pool information from the root disk, then import the root pool
5118 * during the system boot up time.
5119 */
5120extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
5121
5122static nvlist_t *
5123spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
5124{
5125	nvlist_t *config;
5126	nvlist_t *nvtop, *nvroot;
5127	uint64_t pgid;
5128
5129	if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
5130		return (NULL);
5131
5132	/*
5133	 * Add this top-level vdev to the child array.
5134	 */
5135	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5136	    &nvtop) == 0);
5137	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5138	    &pgid) == 0);
5139	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
5140
5141	/*
5142	 * Put this pool's top-level vdevs into a root vdev.
5143	 */
5144	VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5145	VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5146	    VDEV_TYPE_ROOT) == 0);
5147	VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5148	VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5149	VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5150	    &nvtop, 1) == 0);
5151
5152	/*
5153	 * Replace the existing vdev_tree with the new root vdev in
5154	 * this pool's configuration (remove the old, add the new).
5155	 */
5156	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5157	nvlist_free(nvroot);
5158	return (config);
5159}
5160
5161/*
5162 * Walk the vdev tree and see if we can find a device with "better"
5163 * configuration. A configuration is "better" if the label on that
5164 * device has a more recent txg.
5165 */
5166static void
5167spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
5168{
5169	for (int c = 0; c < vd->vdev_children; c++)
5170		spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
5171
5172	if (vd->vdev_ops->vdev_op_leaf) {
5173		nvlist_t *label;
5174		uint64_t label_txg;
5175
5176		if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
5177		    &label) != 0)
5178			return;
5179
5180		VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
5181		    &label_txg) == 0);
5182
5183		/*
5184		 * Do we have a better boot device?
5185		 */
5186		if (label_txg > *txg) {
5187			*txg = label_txg;
5188			*avd = vd;
5189		}
5190		nvlist_free(label);
5191	}
5192}
5193
5194/*
5195 * Import a root pool.
5196 *
5197 * For x86. devpath_list will consist of devid and/or physpath name of
5198 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
5199 * The GRUB "findroot" command will return the vdev we should boot.
5200 *
5201 * For Sparc, devpath_list consists the physpath name of the booting device
5202 * no matter the rootpool is a single device pool or a mirrored pool.
5203 * e.g.
5204 *	"/pci@1f,0/ide@d/disk@0,0:a"
5205 */
5206int
5207spa_import_rootpool(char *devpath, char *devid)
5208{
5209	spa_t *spa;
5210	vdev_t *rvd, *bvd, *avd = NULL;
5211	nvlist_t *config, *nvtop;
5212	uint64_t guid, txg;
5213	char *pname;
5214	int error;
5215
5216	/*
5217	 * Read the label from the boot device and generate a configuration.
5218	 */
5219	config = spa_generate_rootconf(devpath, devid, &guid);
5220#if defined(_OBP) && defined(_KERNEL)
5221	if (config == NULL) {
5222		if (strstr(devpath, "/iscsi/ssd") != NULL) {
5223			/* iscsi boot */
5224			get_iscsi_bootpath_phy(devpath);
5225			config = spa_generate_rootconf(devpath, devid, &guid);
5226		}
5227	}
5228#endif
5229	if (config == NULL) {
5230		cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
5231		    devpath);
5232		return (SET_ERROR(EIO));
5233	}
5234
5235	VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5236	    &pname) == 0);
5237	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
5238
5239	mutex_enter(&spa_namespace_lock);
5240	if ((spa = spa_lookup(pname)) != NULL) {
5241		/*
5242		 * Remove the existing root pool from the namespace so that we
5243		 * can replace it with the correct config we just read in.
5244		 */
5245		spa_remove(spa);
5246	}
5247
5248	spa = spa_add(pname, config, NULL);
5249	spa->spa_is_root = B_TRUE;
5250	spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5251	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5252	    &spa->spa_ubsync.ub_version) != 0)
5253		spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5254
5255	/*
5256	 * Build up a vdev tree based on the boot device's label config.
5257	 */
5258	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5259	    &nvtop) == 0);
5260	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5261	error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5262	    VDEV_ALLOC_ROOTPOOL);
5263	spa_config_exit(spa, SCL_ALL, FTAG);
5264	if (error) {
5265		mutex_exit(&spa_namespace_lock);
5266		nvlist_free(config);
5267		cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5268		    pname);
5269		return (error);
5270	}
5271
5272	/*
5273	 * Get the boot vdev.
5274	 */
5275	if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
5276		cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
5277		    (u_longlong_t)guid);
5278		error = SET_ERROR(ENOENT);
5279		goto out;
5280	}
5281
5282	/*
5283	 * Determine if there is a better boot device.
5284	 */
5285	avd = bvd;
5286	spa_alt_rootvdev(rvd, &avd, &txg);
5287	if (avd != bvd) {
5288		cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
5289		    "try booting from '%s'", avd->vdev_path);
5290		error = SET_ERROR(EINVAL);
5291		goto out;
5292	}
5293
5294	/*
5295	 * If the boot device is part of a spare vdev then ensure that
5296	 * we're booting off the active spare.
5297	 */
5298	if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
5299	    !bvd->vdev_isspare) {
5300		cmn_err(CE_NOTE, "The boot device is currently spared. Please "
5301		    "try booting from '%s'",
5302		    bvd->vdev_parent->
5303		    vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
5304		error = SET_ERROR(EINVAL);
5305		goto out;
5306	}
5307
5308	error = 0;
5309out:
5310	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5311	vdev_free(rvd);
5312	spa_config_exit(spa, SCL_ALL, FTAG);
5313	mutex_exit(&spa_namespace_lock);
5314
5315	nvlist_free(config);
5316	return (error);
5317}
5318
5319#endif
5320
5321/*
5322 * Import a non-root pool into the system.
5323 */
5324int
5325spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5326{
5327	spa_t *spa;
5328	char *altroot = NULL;
5329	spa_load_state_t state = SPA_LOAD_IMPORT;
5330	zpool_load_policy_t policy;
5331	uint64_t mode = spa_mode_global;
5332	uint64_t readonly = B_FALSE;
5333	int error;
5334	nvlist_t *nvroot;
5335	nvlist_t **spares, **l2cache;
5336	uint_t nspares, nl2cache;
5337
5338	/*
5339	 * If a pool with this name exists, return failure.
5340	 */
5341	mutex_enter(&spa_namespace_lock);
5342	if (spa_lookup(pool) != NULL) {
5343		mutex_exit(&spa_namespace_lock);
5344		return (SET_ERROR(EEXIST));
5345	}
5346
5347	/*
5348	 * Create and initialize the spa structure.
5349	 */
5350	(void) nvlist_lookup_string(props,
5351	    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5352	(void) nvlist_lookup_uint64(props,
5353	    zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5354	if (readonly)
5355		mode = FREAD;
5356	spa = spa_add(pool, config, altroot);
5357	spa->spa_import_flags = flags;
5358
5359	/*
5360	 * Verbatim import - Take a pool and insert it into the namespace
5361	 * as if it had been loaded at boot.
5362	 */
5363	if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5364		if (props != NULL)
5365			spa_configfile_set(spa, props, B_FALSE);
5366
5367		spa_write_cachefile(spa, B_FALSE, B_TRUE);
5368		spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5369		zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5370		mutex_exit(&spa_namespace_lock);
5371		return (0);
5372	}
5373
5374	spa_activate(spa, mode);
5375
5376	/*
5377	 * Don't start async tasks until we know everything is healthy.
5378	 */
5379	spa_async_suspend(spa);
5380
5381	zpool_get_load_policy(config, &policy);
5382	if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5383		state = SPA_LOAD_RECOVER;
5384
5385	spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5386
5387	if (state != SPA_LOAD_RECOVER) {
5388		spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5389		zfs_dbgmsg("spa_import: importing %s", pool);
5390	} else {
5391		zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5392		    "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
5393	}
5394	error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
5395
5396	/*
5397	 * Propagate anything learned while loading the pool and pass it
5398	 * back to caller (i.e. rewind info, missing devices, etc).
5399	 */
5400	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5401	    spa->spa_load_info) == 0);
5402
5403	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5404	/*
5405	 * Toss any existing sparelist, as it doesn't have any validity
5406	 * anymore, and conflicts with spa_has_spare().
5407	 */
5408	if (spa->spa_spares.sav_config) {
5409		nvlist_free(spa->spa_spares.sav_config);
5410		spa->spa_spares.sav_config = NULL;
5411		spa_load_spares(spa);
5412	}
5413	if (spa->spa_l2cache.sav_config) {
5414		nvlist_free(spa->spa_l2cache.sav_config);
5415		spa->spa_l2cache.sav_config = NULL;
5416		spa_load_l2cache(spa);
5417	}
5418
5419	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5420	    &nvroot) == 0);
5421	if (error == 0)
5422		error = spa_validate_aux(spa, nvroot, -1ULL,
5423		    VDEV_ALLOC_SPARE);
5424	if (error == 0)
5425		error = spa_validate_aux(spa, nvroot, -1ULL,
5426		    VDEV_ALLOC_L2CACHE);
5427	spa_config_exit(spa, SCL_ALL, FTAG);
5428
5429	if (props != NULL)
5430		spa_configfile_set(spa, props, B_FALSE);
5431
5432	if (error != 0 || (props && spa_writeable(spa) &&
5433	    (error = spa_prop_set(spa, props)))) {
5434		spa_unload(spa);
5435		spa_deactivate(spa);
5436		spa_remove(spa);
5437		mutex_exit(&spa_namespace_lock);
5438		return (error);
5439	}
5440
5441	spa_async_resume(spa);
5442
5443	/*
5444	 * Override any spares and level 2 cache devices as specified by
5445	 * the user, as these may have correct device names/devids, etc.
5446	 */
5447	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5448	    &spares, &nspares) == 0) {
5449		if (spa->spa_spares.sav_config)
5450			VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5451			    ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5452		else
5453			VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5454			    NV_UNIQUE_NAME, KM_SLEEP) == 0);
5455		VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5456		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5457		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5458		spa_load_spares(spa);
5459		spa_config_exit(spa, SCL_ALL, FTAG);
5460		spa->spa_spares.sav_sync = B_TRUE;
5461	}
5462	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5463	    &l2cache, &nl2cache) == 0) {
5464		if (spa->spa_l2cache.sav_config)
5465			VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5466			    ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5467		else
5468			VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5469			    NV_UNIQUE_NAME, KM_SLEEP) == 0);
5470		VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5471		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5472		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5473		spa_load_l2cache(spa);
5474		spa_config_exit(spa, SCL_ALL, FTAG);
5475		spa->spa_l2cache.sav_sync = B_TRUE;
5476	}
5477
5478	/*
5479	 * Check for any removed devices.
5480	 */
5481	if (spa->spa_autoreplace) {
5482		spa_aux_check_removed(&spa->spa_spares);
5483		spa_aux_check_removed(&spa->spa_l2cache);
5484	}
5485
5486	if (spa_writeable(spa)) {
5487		/*
5488		 * Update the config cache to include the newly-imported pool.
5489		 */
5490		spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5491	}
5492
5493	/*
5494	 * It's possible that the pool was expanded while it was exported.
5495	 * We kick off an async task to handle this for us.
5496	 */
5497	spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5498
5499	spa_history_log_version(spa, "import");
5500
5501	spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5502
5503	mutex_exit(&spa_namespace_lock);
5504
5505	return (0);
5506}
5507
5508nvlist_t *
5509spa_tryimport(nvlist_t *tryconfig)
5510{
5511	nvlist_t *config = NULL;
5512	char *poolname, *cachefile;
5513	spa_t *spa;
5514	uint64_t state;
5515	int error;
5516	zpool_load_policy_t policy;
5517
5518	if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5519		return (NULL);
5520
5521	if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5522		return (NULL);
5523
5524	/*
5525	 * Create and initialize the spa structure.
5526	 */
5527	mutex_enter(&spa_namespace_lock);
5528	spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
5529	spa_activate(spa, FREAD);
5530
5531	/*
5532	 * Rewind pool if a max txg was provided.
5533	 */
5534	zpool_get_load_policy(spa->spa_config, &policy);
5535	if (policy.zlp_txg != UINT64_MAX) {
5536		spa->spa_load_max_txg = policy.zlp_txg;
5537		spa->spa_extreme_rewind = B_TRUE;
5538		zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
5539		    poolname, (longlong_t)policy.zlp_txg);
5540	} else {
5541		zfs_dbgmsg("spa_tryimport: importing %s", poolname);
5542	}
5543
5544	if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
5545	    == 0) {
5546		zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
5547		spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5548	} else {
5549		spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
5550	}
5551
5552	error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
5553
5554	/*
5555	 * If 'tryconfig' was at least parsable, return the current config.
5556	 */
5557	if (spa->spa_root_vdev != NULL) {
5558		config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5559		VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
5560		    poolname) == 0);
5561		VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5562		    state) == 0);
5563		VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
5564		    spa->spa_uberblock.ub_timestamp) == 0);
5565		VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5566		    spa->spa_load_info) == 0);
5567
5568		/*
5569		 * If the bootfs property exists on this pool then we
5570		 * copy it out so that external consumers can tell which
5571		 * pools are bootable.
5572		 */
5573		if ((!error || error == EEXIST) && spa->spa_bootfs) {
5574			char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5575
5576			/*
5577			 * We have to play games with the name since the
5578			 * pool was opened as TRYIMPORT_NAME.
5579			 */
5580			if (dsl_dsobj_to_dsname(spa_name(spa),
5581			    spa->spa_bootfs, tmpname) == 0) {
5582				char *cp;
5583				char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5584
5585				cp = strchr(tmpname, '/');
5586				if (cp == NULL) {
5587					(void) strlcpy(dsname, tmpname,
5588					    MAXPATHLEN);
5589				} else {
5590					(void) snprintf(dsname, MAXPATHLEN,
5591					    "%s/%s", poolname, ++cp);
5592				}
5593				VERIFY(nvlist_add_string(config,
5594				    ZPOOL_CONFIG_BOOTFS, dsname) == 0);
5595				kmem_free(dsname, MAXPATHLEN);
5596			}
5597			kmem_free(tmpname, MAXPATHLEN);
5598		}
5599
5600		/*
5601		 * Add the list of hot spares and level 2 cache devices.
5602		 */
5603		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5604		spa_add_spares(spa, config);
5605		spa_add_l2cache(spa, config);
5606		spa_config_exit(spa, SCL_CONFIG, FTAG);
5607	}
5608
5609	spa_unload(spa);
5610	spa_deactivate(spa);
5611	spa_remove(spa);
5612	mutex_exit(&spa_namespace_lock);
5613
5614	return (config);
5615}
5616
5617/*
5618 * Pool export/destroy
5619 *
5620 * The act of destroying or exporting a pool is very simple.  We make sure there
5621 * is no more pending I/O and any references to the pool are gone.  Then, we
5622 * update the pool state and sync all the labels to disk, removing the
5623 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
5624 * we don't sync the labels or remove the configuration cache.
5625 */
5626static int
5627spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
5628    boolean_t force, boolean_t hardforce)
5629{
5630	spa_t *spa;
5631
5632	if (oldconfig)
5633		*oldconfig = NULL;
5634
5635	if (!(spa_mode_global & FWRITE))
5636		return (SET_ERROR(EROFS));
5637
5638	mutex_enter(&spa_namespace_lock);
5639	if ((spa = spa_lookup(pool)) == NULL) {
5640		mutex_exit(&spa_namespace_lock);
5641		return (SET_ERROR(ENOENT));
5642	}
5643
5644	/*
5645	 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5646	 * reacquire the namespace lock, and see if we can export.
5647	 */
5648	spa_open_ref(spa, FTAG);
5649	mutex_exit(&spa_namespace_lock);
5650	spa_async_suspend(spa);
5651	mutex_enter(&spa_namespace_lock);
5652	spa_close(spa, FTAG);
5653
5654	/*
5655	 * The pool will be in core if it's openable,
5656	 * in which case we can modify its state.
5657	 */
5658	if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
5659
5660		/*
5661		 * Objsets may be open only because they're dirty, so we
5662		 * have to force it to sync before checking spa_refcnt.
5663		 */
5664		txg_wait_synced(spa->spa_dsl_pool, 0);
5665		spa_evicting_os_wait(spa);
5666
5667		/*
5668		 * A pool cannot be exported or destroyed if there are active
5669		 * references.  If we are resetting a pool, allow references by
5670		 * fault injection handlers.
5671		 */
5672		if (!spa_refcount_zero(spa) ||
5673		    (spa->spa_inject_ref != 0 &&
5674		    new_state != POOL_STATE_UNINITIALIZED)) {
5675			spa_async_resume(spa);
5676			mutex_exit(&spa_namespace_lock);
5677			return (SET_ERROR(EBUSY));
5678		}
5679
5680		/*
5681		 * A pool cannot be exported if it has an active shared spare.
5682		 * This is to prevent other pools stealing the active spare
5683		 * from an exported pool. At user's own will, such pool can
5684		 * be forcedly exported.
5685		 */
5686		if (!force && new_state == POOL_STATE_EXPORTED &&
5687		    spa_has_active_shared_spare(spa)) {
5688			spa_async_resume(spa);
5689			mutex_exit(&spa_namespace_lock);
5690			return (SET_ERROR(EXDEV));
5691		}
5692
5693		/*
5694		 * We're about to export or destroy this pool. Make sure
5695		 * we stop all initializtion activity here before we
5696		 * set the spa_final_txg. This will ensure that all
5697		 * dirty data resulting from the initialization is
5698		 * committed to disk before we unload the pool.
5699		 */
5700		if (spa->spa_root_vdev != NULL) {
5701			vdev_initialize_stop_all(spa->spa_root_vdev,
5702			    VDEV_INITIALIZE_ACTIVE);
5703		}
5704
5705		/*
5706		 * We want this to be reflected on every label,
5707		 * so mark them all dirty.  spa_unload() will do the
5708		 * final sync that pushes these changes out.
5709		 */
5710		if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
5711			spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5712			spa->spa_state = new_state;
5713			spa->spa_final_txg = spa_last_synced_txg(spa) +
5714			    TXG_DEFER_SIZE + 1;
5715			vdev_config_dirty(spa->spa_root_vdev);
5716			spa_config_exit(spa, SCL_ALL, FTAG);
5717		}
5718	}
5719
5720	spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
5721
5722	if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
5723		spa_unload(spa);
5724		spa_deactivate(spa);
5725	}
5726
5727	if (oldconfig && spa->spa_config)
5728		VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
5729
5730	if (new_state != POOL_STATE_UNINITIALIZED) {
5731		if (!hardforce)
5732			spa_write_cachefile(spa, B_TRUE, B_TRUE);
5733		spa_remove(spa);
5734	}
5735	mutex_exit(&spa_namespace_lock);
5736
5737	return (0);
5738}
5739
5740/*
5741 * Destroy a storage pool.
5742 */
5743int
5744spa_destroy(char *pool)
5745{
5746	return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
5747	    B_FALSE, B_FALSE));
5748}
5749
5750/*
5751 * Export a storage pool.
5752 */
5753int
5754spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
5755    boolean_t hardforce)
5756{
5757	return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
5758	    force, hardforce));
5759}
5760
5761/*
5762 * Similar to spa_export(), this unloads the spa_t without actually removing it
5763 * from the namespace in any way.
5764 */
5765int
5766spa_reset(char *pool)
5767{
5768	return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
5769	    B_FALSE, B_FALSE));
5770}
5771
5772/*
5773 * ==========================================================================
5774 * Device manipulation
5775 * ==========================================================================
5776 */
5777
5778/*
5779 * Add a device to a storage pool.
5780 */
5781int
5782spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
5783{
5784	uint64_t txg, id;
5785	int error;
5786	vdev_t *rvd = spa->spa_root_vdev;
5787	vdev_t *vd, *tvd;
5788	nvlist_t **spares, **l2cache;
5789	uint_t nspares, nl2cache;
5790
5791	ASSERT(spa_writeable(spa));
5792
5793	txg = spa_vdev_enter(spa);
5794
5795	if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
5796	    VDEV_ALLOC_ADD)) != 0)
5797		return (spa_vdev_exit(spa, NULL, txg, error));
5798
5799	spa->spa_pending_vdev = vd;	/* spa_vdev_exit() will clear this */
5800
5801	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
5802	    &nspares) != 0)
5803		nspares = 0;
5804
5805	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
5806	    &nl2cache) != 0)
5807		nl2cache = 0;
5808
5809	if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
5810		return (spa_vdev_exit(spa, vd, txg, EINVAL));
5811
5812	if (vd->vdev_children != 0 &&
5813	    (error = vdev_create(vd, txg, B_FALSE)) != 0)
5814		return (spa_vdev_exit(spa, vd, txg, error));
5815
5816	/*
5817	 * We must validate the spares and l2cache devices after checking the
5818	 * children.  Otherwise, vdev_inuse() will blindly overwrite the spare.
5819	 */
5820	if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
5821		return (spa_vdev_exit(spa, vd, txg, error));
5822
5823	/*
5824	 * If we are in the middle of a device removal, we can only add
5825	 * devices which match the existing devices in the pool.
5826	 * If we are in the middle of a removal, or have some indirect
5827	 * vdevs, we can not add raidz toplevels.
5828	 */
5829	if (spa->spa_vdev_removal != NULL ||
5830	    spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
5831		for (int c = 0; c < vd->vdev_children; c++) {
5832			tvd = vd->vdev_child[c];
5833			if (spa->spa_vdev_removal != NULL &&
5834			    tvd->vdev_ashift != spa->spa_max_ashift) {
5835				return (spa_vdev_exit(spa, vd, txg, EINVAL));
5836			}
5837			/* Fail if top level vdev is raidz */
5838			if (tvd->vdev_ops == &vdev_raidz_ops) {
5839				return (spa_vdev_exit(spa, vd, txg, EINVAL));
5840			}
5841			/*
5842			 * Need the top level mirror to be
5843			 * a mirror of leaf vdevs only
5844			 */
5845			if (tvd->vdev_ops == &vdev_mirror_ops) {
5846				for (uint64_t cid = 0;
5847				    cid < tvd->vdev_children; cid++) {
5848					vdev_t *cvd = tvd->vdev_child[cid];
5849					if (!cvd->vdev_ops->vdev_op_leaf) {
5850						return (spa_vdev_exit(spa, vd,
5851						    txg, EINVAL));
5852					}
5853				}
5854			}
5855		}
5856	}
5857
5858	for (int c = 0; c < vd->vdev_children; c++) {
5859
5860		/*
5861		 * Set the vdev id to the first hole, if one exists.
5862		 */
5863		for (id = 0; id < rvd->vdev_children; id++) {
5864			if (rvd->vdev_child[id]->vdev_ishole) {
5865				vdev_free(rvd->vdev_child[id]);
5866				break;
5867			}
5868		}
5869		tvd = vd->vdev_child[c];
5870		vdev_remove_child(vd, tvd);
5871		tvd->vdev_id = id;
5872		vdev_add_child(rvd, tvd);
5873		vdev_config_dirty(tvd);
5874	}
5875
5876	if (nspares != 0) {
5877		spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
5878		    ZPOOL_CONFIG_SPARES);
5879		spa_load_spares(spa);
5880		spa->spa_spares.sav_sync = B_TRUE;
5881	}
5882
5883	if (nl2cache != 0) {
5884		spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
5885		    ZPOOL_CONFIG_L2CACHE);
5886		spa_load_l2cache(spa);
5887		spa->spa_l2cache.sav_sync = B_TRUE;
5888	}
5889
5890	/*
5891	 * We have to be careful when adding new vdevs to an existing pool.
5892	 * If other threads start allocating from these vdevs before we
5893	 * sync the config cache, and we lose power, then upon reboot we may
5894	 * fail to open the pool because there are DVAs that the config cache
5895	 * can't translate.  Therefore, we first add the vdevs without
5896	 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
5897	 * and then let spa_config_update() initialize the new metaslabs.
5898	 *
5899	 * spa_load() checks for added-but-not-initialized vdevs, so that
5900	 * if we lose power at any point in this sequence, the remaining
5901	 * steps will be completed the next time we load the pool.
5902	 */
5903	(void) spa_vdev_exit(spa, vd, txg, 0);
5904
5905	mutex_enter(&spa_namespace_lock);
5906	spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5907	spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
5908	mutex_exit(&spa_namespace_lock);
5909
5910	return (0);
5911}
5912
5913/*
5914 * Attach a device to a mirror.  The arguments are the path to any device
5915 * in the mirror, and the nvroot for the new device.  If the path specifies
5916 * a device that is not mirrored, we automatically insert the mirror vdev.
5917 *
5918 * If 'replacing' is specified, the new device is intended to replace the
5919 * existing device; in this case the two devices are made into their own
5920 * mirror using the 'replacing' vdev, which is functionally identical to
5921 * the mirror vdev (it actually reuses all the same ops) but has a few
5922 * extra rules: you can't attach to it after it's been created, and upon
5923 * completion of resilvering, the first disk (the one being replaced)
5924 * is automatically detached.
5925 */
5926int
5927spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
5928{
5929	uint64_t txg, dtl_max_txg;
5930	vdev_t *rvd = spa->spa_root_vdev;
5931	vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
5932	vdev_ops_t *pvops;
5933	char *oldvdpath, *newvdpath;
5934	int newvd_isspare;
5935	int error;
5936
5937	ASSERT(spa_writeable(spa));
5938
5939	txg = spa_vdev_enter(spa);
5940
5941	oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
5942
5943	ASSERT(MUTEX_HELD(&spa_namespace_lock));
5944	if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
5945		error = (spa_has_checkpoint(spa)) ?
5946		    ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
5947		return (spa_vdev_exit(spa, NULL, txg, error));
5948	}
5949
5950	if (spa->spa_vdev_removal != NULL)
5951		return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5952
5953	if (oldvd == NULL)
5954		return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5955
5956	if (!oldvd->vdev_ops->vdev_op_leaf)
5957		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5958
5959	pvd = oldvd->vdev_parent;
5960
5961	if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
5962	    VDEV_ALLOC_ATTACH)) != 0)
5963		return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5964
5965	if (newrootvd->vdev_children != 1)
5966		return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
5967
5968	newvd = newrootvd->vdev_child[0];
5969
5970	if (!newvd->vdev_ops->vdev_op_leaf)
5971		return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
5972
5973	if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
5974		return (spa_vdev_exit(spa, newrootvd, txg, error));
5975
5976	/*
5977	 * Spares can't replace logs
5978	 */
5979	if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
5980		return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5981
5982	if (!replacing) {
5983		/*
5984		 * For attach, the only allowable parent is a mirror or the root
5985		 * vdev.
5986		 */
5987		if (pvd->vdev_ops != &vdev_mirror_ops &&
5988		    pvd->vdev_ops != &vdev_root_ops)
5989			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5990
5991		pvops = &vdev_mirror_ops;
5992	} else {
5993		/*
5994		 * Active hot spares can only be replaced by inactive hot
5995		 * spares.
5996		 */
5997		if (pvd->vdev_ops == &vdev_spare_ops &&
5998		    oldvd->vdev_isspare &&
5999		    !spa_has_spare(spa, newvd->vdev_guid))
6000			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6001
6002		/*
6003		 * If the source is a hot spare, and the parent isn't already a
6004		 * spare, then we want to create a new hot spare.  Otherwise, we
6005		 * want to create a replacing vdev.  The user is not allowed to
6006		 * attach to a spared vdev child unless the 'isspare' state is
6007		 * the same (spare replaces spare, non-spare replaces
6008		 * non-spare).
6009		 */
6010		if (pvd->vdev_ops == &vdev_replacing_ops &&
6011		    spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6012			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6013		} else if (pvd->vdev_ops == &vdev_spare_ops &&
6014		    newvd->vdev_isspare != oldvd->vdev_isspare) {
6015			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6016		}
6017
6018		if (newvd->vdev_isspare)
6019			pvops = &vdev_spare_ops;
6020		else
6021			pvops = &vdev_replacing_ops;
6022	}
6023
6024	/*
6025	 * Make sure the new device is big enough.
6026	 */
6027	if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6028		return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6029
6030	/*
6031	 * The new device cannot have a higher alignment requirement
6032	 * than the top-level vdev.
6033	 */
6034	if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6035		return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6036
6037	/*
6038	 * If this is an in-place replacement, update oldvd's path and devid
6039	 * to make it distinguishable from newvd, and unopenable from now on.
6040	 */
6041	if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6042		spa_strfree(oldvd->vdev_path);
6043		oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6044		    KM_SLEEP);
6045		(void) sprintf(oldvd->vdev_path, "%s/%s",
6046		    newvd->vdev_path, "old");
6047		if (oldvd->vdev_devid != NULL) {
6048			spa_strfree(oldvd->vdev_devid);
6049			oldvd->vdev_devid = NULL;
6050		}
6051	}
6052
6053	/* mark the device being resilvered */
6054	newvd->vdev_resilver_txg = txg;
6055
6056	/*
6057	 * If the parent is not a mirror, or if we're replacing, insert the new
6058	 * mirror/replacing/spare vdev above oldvd.
6059	 */
6060	if (pvd->vdev_ops != pvops)
6061		pvd = vdev_add_parent(oldvd, pvops);
6062
6063	ASSERT(pvd->vdev_top->vdev_parent == rvd);
6064	ASSERT(pvd->vdev_ops == pvops);
6065	ASSERT(oldvd->vdev_parent == pvd);
6066
6067	/*
6068	 * Extract the new device from its root and add it to pvd.
6069	 */
6070	vdev_remove_child(newrootvd, newvd);
6071	newvd->vdev_id = pvd->vdev_children;
6072	newvd->vdev_crtxg = oldvd->vdev_crtxg;
6073	vdev_add_child(pvd, newvd);
6074
6075	tvd = newvd->vdev_top;
6076	ASSERT(pvd->vdev_top == tvd);
6077	ASSERT(tvd->vdev_parent == rvd);
6078
6079	vdev_config_dirty(tvd);
6080
6081	/*
6082	 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6083	 * for any dmu_sync-ed blocks.  It will propagate upward when
6084	 * spa_vdev_exit() calls vdev_dtl_reassess().
6085	 */
6086	dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6087
6088	vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6089	    dtl_max_txg - TXG_INITIAL);
6090
6091	if (newvd->vdev_isspare) {
6092		spa_spare_activate(newvd);
6093		spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6094	}
6095
6096	oldvdpath = spa_strdup(oldvd->vdev_path);
6097	newvdpath = spa_strdup(newvd->vdev_path);
6098	newvd_isspare = newvd->vdev_isspare;
6099
6100	/*
6101	 * Mark newvd's DTL dirty in this txg.
6102	 */
6103	vdev_dirty(tvd, VDD_DTL, newvd, txg);
6104
6105	/*
6106	 * Schedule the resilver to restart in the future. We do this to
6107	 * ensure that dmu_sync-ed blocks have been stitched into the
6108	 * respective datasets.
6109	 */
6110	dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
6111
6112	if (spa->spa_bootfs)
6113		spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6114
6115	spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6116
6117	/*
6118	 * Commit the config
6119	 */
6120	(void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6121
6122	spa_history_log_internal(spa, "vdev attach", NULL,
6123	    "%s vdev=%s %s vdev=%s",
6124	    replacing && newvd_isspare ? "spare in" :
6125	    replacing ? "replace" : "attach", newvdpath,
6126	    replacing ? "for" : "to", oldvdpath);
6127
6128	spa_strfree(oldvdpath);
6129	spa_strfree(newvdpath);
6130
6131	return (0);
6132}
6133
6134/*
6135 * Detach a device from a mirror or replacing vdev.
6136 *
6137 * If 'replace_done' is specified, only detach if the parent
6138 * is a replacing vdev.
6139 */
6140int
6141spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6142{
6143	uint64_t txg;
6144	int error;
6145	vdev_t *rvd = spa->spa_root_vdev;
6146	vdev_t *vd, *pvd, *cvd, *tvd;
6147	boolean_t unspare = B_FALSE;
6148	uint64_t unspare_guid = 0;
6149	char *vdpath;
6150
6151	ASSERT(spa_writeable(spa));
6152
6153	txg = spa_vdev_enter(spa);
6154
6155	vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6156
6157	/*
6158	 * Besides being called directly from the userland through the
6159	 * ioctl interface, spa_vdev_detach() can be potentially called
6160	 * at the end of spa_vdev_resilver_done().
6161	 *
6162	 * In the regular case, when we have a checkpoint this shouldn't
6163	 * happen as we never empty the DTLs of a vdev during the scrub
6164	 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6165	 * should never get here when we have a checkpoint.
6166	 *
6167	 * That said, even in a case when we checkpoint the pool exactly
6168	 * as spa_vdev_resilver_done() calls this function everything
6169	 * should be fine as the resilver will return right away.
6170	 */
6171	ASSERT(MUTEX_HELD(&spa_namespace_lock));
6172	if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6173		error = (spa_has_checkpoint(spa)) ?
6174		    ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6175		return (spa_vdev_exit(spa, NULL, txg, error));
6176	}
6177
6178	if (vd == NULL)
6179		return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6180
6181	if (!vd->vdev_ops->vdev_op_leaf)
6182		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6183
6184	pvd = vd->vdev_parent;
6185
6186	/*
6187	 * If the parent/child relationship is not as expected, don't do it.
6188	 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6189	 * vdev that's replacing B with C.  The user's intent in replacing
6190	 * is to go from M(A,B) to M(A,C).  If the user decides to cancel
6191	 * the replace by detaching C, the expected behavior is to end up
6192	 * M(A,B).  But suppose that right after deciding to detach C,
6193	 * the replacement of B completes.  We would have M(A,C), and then
6194	 * ask to detach C, which would leave us with just A -- not what
6195	 * the user wanted.  To prevent this, we make sure that the
6196	 * parent/child relationship hasn't changed -- in this example,
6197	 * that C's parent is still the replacing vdev R.
6198	 */
6199	if (pvd->vdev_guid != pguid && pguid != 0)
6200		return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6201
6202	/*
6203	 * Only 'replacing' or 'spare' vdevs can be replaced.
6204	 */
6205	if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6206	    pvd->vdev_ops != &vdev_spare_ops)
6207		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6208
6209	ASSERT(pvd->vdev_ops != &vdev_spare_ops ||