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