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