xref: /illumos-gate/usr/src/uts/common/fs/zfs/spa.c (revision c4ccc1f9004b70b07e4cdb57641c38ab607306c9)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2019 by Delphix. All rights reserved.
25  * Copyright (c) 2015, Nexenta Systems, Inc.  All rights reserved.
26  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27  * Copyright 2013 Saso Kiselkov. All rights reserved.
28  * Copyright (c) 2014 Integros [integros.com]
29  * Copyright 2016 Toomas Soome <tsoome@me.com>
30  * Copyright 2018 Joyent, Inc.
31  * Copyright (c) 2017, Intel Corporation.
32  * Copyright (c) 2017 Datto Inc.
33  * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
34  */
35 
36 /*
37  * SPA: Storage Pool Allocator
38  *
39  * This file contains all the routines used when modifying on-disk SPA state.
40  * This includes opening, importing, destroying, exporting a pool, and syncing a
41  * pool.
42  */
43 
44 #include <sys/zfs_context.h>
45 #include <sys/fm/fs/zfs.h>
46 #include <sys/spa_impl.h>
47 #include <sys/zio.h>
48 #include <sys/zio_checksum.h>
49 #include <sys/dmu.h>
50 #include <sys/dmu_tx.h>
51 #include <sys/zap.h>
52 #include <sys/zil.h>
53 #include <sys/ddt.h>
54 #include <sys/vdev_impl.h>
55 #include <sys/vdev_removal.h>
56 #include <sys/vdev_indirect_mapping.h>
57 #include <sys/vdev_indirect_births.h>
58 #include <sys/vdev_initialize.h>
59 #include <sys/metaslab.h>
60 #include <sys/metaslab_impl.h>
61 #include <sys/mmp.h>
62 #include <sys/uberblock_impl.h>
63 #include <sys/txg.h>
64 #include <sys/avl.h>
65 #include <sys/bpobj.h>
66 #include <sys/dmu_traverse.h>
67 #include <sys/dmu_objset.h>
68 #include <sys/unique.h>
69 #include <sys/dsl_pool.h>
70 #include <sys/dsl_dataset.h>
71 #include <sys/dsl_dir.h>
72 #include <sys/dsl_prop.h>
73 #include <sys/dsl_synctask.h>
74 #include <sys/fs/zfs.h>
75 #include <sys/arc.h>
76 #include <sys/callb.h>
77 #include <sys/systeminfo.h>
78 #include <sys/spa_boot.h>
79 #include <sys/zfs_ioctl.h>
80 #include <sys/dsl_scan.h>
81 #include <sys/zfeature.h>
82 #include <sys/dsl_destroy.h>
83 #include <sys/abd.h>
84 
85 #ifdef	_KERNEL
86 #include <sys/bootprops.h>
87 #include <sys/callb.h>
88 #include <sys/cpupart.h>
89 #include <sys/pool.h>
90 #include <sys/sysdc.h>
91 #include <sys/zone.h>
92 #endif	/* _KERNEL */
93 
94 #include "zfs_prop.h"
95 #include "zfs_comutil.h"
96 
97 /*
98  * The interval, in seconds, at which failed configuration cache file writes
99  * should be retried.
100  */
101 int zfs_ccw_retry_interval = 300;
102 
103 typedef enum zti_modes {
104 	ZTI_MODE_FIXED,			/* value is # of threads (min 1) */
105 	ZTI_MODE_BATCH,			/* cpu-intensive; value is ignored */
106 	ZTI_MODE_NULL,			/* don't create a taskq */
107 	ZTI_NMODES
108 } zti_modes_t;
109 
110 #define	ZTI_P(n, q)	{ ZTI_MODE_FIXED, (n), (q) }
111 #define	ZTI_BATCH	{ ZTI_MODE_BATCH, 0, 1 }
112 #define	ZTI_NULL	{ ZTI_MODE_NULL, 0, 0 }
113 
114 #define	ZTI_N(n)	ZTI_P(n, 1)
115 #define	ZTI_ONE		ZTI_N(1)
116 
117 typedef struct zio_taskq_info {
118 	zti_modes_t zti_mode;
119 	uint_t zti_value;
120 	uint_t zti_count;
121 } zio_taskq_info_t;
122 
123 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
124 	"issue", "issue_high", "intr", "intr_high"
125 };
126 
127 /*
128  * This table defines the taskq settings for each ZFS I/O type. When
129  * initializing a pool, we use this table to create an appropriately sized
130  * taskq. Some operations are low volume and therefore have a small, static
131  * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
132  * macros. Other operations process a large amount of data; the ZTI_BATCH
133  * macro causes us to create a taskq oriented for throughput. Some operations
134  * are so high frequency and short-lived that the taskq itself can become a a
135  * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
136  * additional degree of parallelism specified by the number of threads per-
137  * taskq and the number of taskqs; when dispatching an event in this case, the
138  * particular taskq is chosen at random.
139  *
140  * The different taskq priorities are to handle the different contexts (issue
141  * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
142  * need to be handled with minimum delay.
143  */
144 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
145 	/* ISSUE	ISSUE_HIGH	INTR		INTR_HIGH */
146 	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* NULL */
147 	{ ZTI_N(8),	ZTI_NULL,	ZTI_P(12, 8),	ZTI_NULL }, /* READ */
148 	{ ZTI_BATCH,	ZTI_N(5),	ZTI_N(8),	ZTI_N(5) }, /* WRITE */
149 	{ ZTI_P(12, 8),	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* FREE */
150 	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* CLAIM */
151 	{ ZTI_ONE,	ZTI_NULL,	ZTI_ONE,	ZTI_NULL }, /* IOCTL */
152 };
153 
154 static void spa_sync_version(void *arg, dmu_tx_t *tx);
155 static void spa_sync_props(void *arg, dmu_tx_t *tx);
156 static boolean_t spa_has_active_shared_spare(spa_t *spa);
157 static int spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport);
158 static void spa_vdev_resilver_done(spa_t *spa);
159 
160 uint_t		zio_taskq_batch_pct = 75;	/* 1 thread per cpu in pset */
161 id_t		zio_taskq_psrset_bind = PS_NONE;
162 boolean_t	zio_taskq_sysdc = B_TRUE;	/* use SDC scheduling class */
163 uint_t		zio_taskq_basedc = 80;		/* base duty cycle */
164 
165 boolean_t	spa_create_process = B_TRUE;	/* no process ==> no sysdc */
166 extern int	zfs_sync_pass_deferred_free;
167 
168 /*
169  * Report any spa_load_verify errors found, but do not fail spa_load.
170  * This is used by zdb to analyze non-idle pools.
171  */
172 boolean_t	spa_load_verify_dryrun = B_FALSE;
173 
174 /*
175  * This (illegal) pool name is used when temporarily importing a spa_t in order
176  * to get the vdev stats associated with the imported devices.
177  */
178 #define	TRYIMPORT_NAME	"$import"
179 
180 /*
181  * For debugging purposes: print out vdev tree during pool import.
182  */
183 boolean_t	spa_load_print_vdev_tree = B_FALSE;
184 
185 /*
186  * A non-zero value for zfs_max_missing_tvds means that we allow importing
187  * pools with missing top-level vdevs. This is strictly intended for advanced
188  * pool recovery cases since missing data is almost inevitable. Pools with
189  * missing devices can only be imported read-only for safety reasons, and their
190  * fail-mode will be automatically set to "continue".
191  *
192  * With 1 missing vdev we should be able to import the pool and mount all
193  * datasets. User data that was not modified after the missing device has been
194  * added should be recoverable. This means that snapshots created prior to the
195  * addition of that device should be completely intact.
196  *
197  * With 2 missing vdevs, some datasets may fail to mount since there are
198  * dataset statistics that are stored as regular metadata. Some data might be
199  * recoverable if those vdevs were added recently.
200  *
201  * With 3 or more missing vdevs, the pool is severely damaged and MOS entries
202  * may be missing entirely. Chances of data recovery are very low. Note that
203  * there are also risks of performing an inadvertent rewind as we might be
204  * missing all the vdevs with the latest uberblocks.
205  */
206 uint64_t	zfs_max_missing_tvds = 0;
207 
208 /*
209  * The parameters below are similar to zfs_max_missing_tvds but are only
210  * intended for a preliminary open of the pool with an untrusted config which
211  * might be incomplete or out-dated.
212  *
213  * We are more tolerant for pools opened from a cachefile since we could have
214  * an out-dated cachefile where a device removal was not registered.
215  * We could have set the limit arbitrarily high but in the case where devices
216  * are really missing we would want to return the proper error codes; we chose
217  * SPA_DVAS_PER_BP - 1 so that some copies of the MOS would still be available
218  * and we get a chance to retrieve the trusted config.
219  */
220 uint64_t	zfs_max_missing_tvds_cachefile = SPA_DVAS_PER_BP - 1;
221 
222 /*
223  * In the case where config was assembled by scanning device paths (/dev/dsks
224  * by default) we are less tolerant since all the existing devices should have
225  * been detected and we want spa_load to return the right error codes.
226  */
227 uint64_t	zfs_max_missing_tvds_scan = 0;
228 
229 /*
230  * Debugging aid that pauses spa_sync() towards the end.
231  */
232 boolean_t	zfs_pause_spa_sync = B_FALSE;
233 
234 /*
235  * ==========================================================================
236  * SPA properties routines
237  * ==========================================================================
238  */
239 
240 /*
241  * Add a (source=src, propname=propval) list to an nvlist.
242  */
243 static void
244 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
245     uint64_t intval, zprop_source_t src)
246 {
247 	const char *propname = zpool_prop_to_name(prop);
248 	nvlist_t *propval;
249 
250 	VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
251 	VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
252 
253 	if (strval != NULL)
254 		VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
255 	else
256 		VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
257 
258 	VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
259 	nvlist_free(propval);
260 }
261 
262 /*
263  * Get property values from the spa configuration.
264  */
265 static void
266 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
267 {
268 	vdev_t *rvd = spa->spa_root_vdev;
269 	dsl_pool_t *pool = spa->spa_dsl_pool;
270 	uint64_t size, alloc, cap, version;
271 	zprop_source_t src = ZPROP_SRC_NONE;
272 	spa_config_dirent_t *dp;
273 	metaslab_class_t *mc = spa_normal_class(spa);
274 
275 	ASSERT(MUTEX_HELD(&spa->spa_props_lock));
276 
277 	if (rvd != NULL) {
278 		alloc = metaslab_class_get_alloc(mc);
279 		alloc += metaslab_class_get_alloc(spa_special_class(spa));
280 		alloc += metaslab_class_get_alloc(spa_dedup_class(spa));
281 
282 		size = metaslab_class_get_space(mc);
283 		size += metaslab_class_get_space(spa_special_class(spa));
284 		size += metaslab_class_get_space(spa_dedup_class(spa));
285 
286 		spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
287 		spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
288 		spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
289 		spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
290 		    size - alloc, src);
291 		spa_prop_add_list(*nvp, ZPOOL_PROP_CHECKPOINT, NULL,
292 		    spa->spa_checkpoint_info.sci_dspace, src);
293 
294 		spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
295 		    metaslab_class_fragmentation(mc), src);
296 		spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
297 		    metaslab_class_expandable_space(mc), src);
298 		spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
299 		    (spa_mode(spa) == FREAD), src);
300 
301 		cap = (size == 0) ? 0 : (alloc * 100 / size);
302 		spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
303 
304 		spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
305 		    ddt_get_pool_dedup_ratio(spa), src);
306 
307 		spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
308 		    rvd->vdev_state, src);
309 
310 		version = spa_version(spa);
311 		if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
312 			src = ZPROP_SRC_DEFAULT;
313 		else
314 			src = ZPROP_SRC_LOCAL;
315 		spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
316 	}
317 
318 	if (pool != NULL) {
319 		/*
320 		 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
321 		 * when opening pools before this version freedir will be NULL.
322 		 */
323 		if (pool->dp_free_dir != NULL) {
324 			spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
325 			    dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
326 			    src);
327 		} else {
328 			spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
329 			    NULL, 0, src);
330 		}
331 
332 		if (pool->dp_leak_dir != NULL) {
333 			spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
334 			    dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
335 			    src);
336 		} else {
337 			spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
338 			    NULL, 0, src);
339 		}
340 	}
341 
342 	spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
343 
344 	if (spa->spa_comment != NULL) {
345 		spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
346 		    0, ZPROP_SRC_LOCAL);
347 	}
348 
349 	if (spa->spa_root != NULL)
350 		spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
351 		    0, ZPROP_SRC_LOCAL);
352 
353 	if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
354 		spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
355 		    MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
356 	} else {
357 		spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
358 		    SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
359 	}
360 
361 	if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE)) {
362 		spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
363 		    DNODE_MAX_SIZE, ZPROP_SRC_NONE);
364 	} else {
365 		spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
366 		    DNODE_MIN_SIZE, ZPROP_SRC_NONE);
367 	}
368 
369 	if ((dp = list_head(&spa->spa_config_list)) != NULL) {
370 		if (dp->scd_path == NULL) {
371 			spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
372 			    "none", 0, ZPROP_SRC_LOCAL);
373 		} else if (strcmp(dp->scd_path, spa_config_path) != 0) {
374 			spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
375 			    dp->scd_path, 0, ZPROP_SRC_LOCAL);
376 		}
377 	}
378 }
379 
380 /*
381  * Get zpool property values.
382  */
383 int
384 spa_prop_get(spa_t *spa, nvlist_t **nvp)
385 {
386 	objset_t *mos = spa->spa_meta_objset;
387 	zap_cursor_t zc;
388 	zap_attribute_t za;
389 	int err;
390 
391 	VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
392 
393 	mutex_enter(&spa->spa_props_lock);
394 
395 	/*
396 	 * Get properties from the spa config.
397 	 */
398 	spa_prop_get_config(spa, nvp);
399 
400 	/* If no pool property object, no more prop to get. */
401 	if (mos == NULL || spa->spa_pool_props_object == 0) {
402 		mutex_exit(&spa->spa_props_lock);
403 		return (0);
404 	}
405 
406 	/*
407 	 * Get properties from the MOS pool property object.
408 	 */
409 	for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
410 	    (err = zap_cursor_retrieve(&zc, &za)) == 0;
411 	    zap_cursor_advance(&zc)) {
412 		uint64_t intval = 0;
413 		char *strval = NULL;
414 		zprop_source_t src = ZPROP_SRC_DEFAULT;
415 		zpool_prop_t prop;
416 
417 		if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
418 			continue;
419 
420 		switch (za.za_integer_length) {
421 		case 8:
422 			/* integer property */
423 			if (za.za_first_integer !=
424 			    zpool_prop_default_numeric(prop))
425 				src = ZPROP_SRC_LOCAL;
426 
427 			if (prop == ZPOOL_PROP_BOOTFS) {
428 				dsl_pool_t *dp;
429 				dsl_dataset_t *ds = NULL;
430 
431 				dp = spa_get_dsl(spa);
432 				dsl_pool_config_enter(dp, FTAG);
433 				err = dsl_dataset_hold_obj(dp,
434 				    za.za_first_integer, FTAG, &ds);
435 				if (err != 0) {
436 					dsl_pool_config_exit(dp, FTAG);
437 					break;
438 				}
439 
440 				strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
441 				    KM_SLEEP);
442 				dsl_dataset_name(ds, strval);
443 				dsl_dataset_rele(ds, FTAG);
444 				dsl_pool_config_exit(dp, FTAG);
445 			} else {
446 				strval = NULL;
447 				intval = za.za_first_integer;
448 			}
449 
450 			spa_prop_add_list(*nvp, prop, strval, intval, src);
451 
452 			if (strval != NULL)
453 				kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
454 
455 			break;
456 
457 		case 1:
458 			/* string property */
459 			strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
460 			err = zap_lookup(mos, spa->spa_pool_props_object,
461 			    za.za_name, 1, za.za_num_integers, strval);
462 			if (err) {
463 				kmem_free(strval, za.za_num_integers);
464 				break;
465 			}
466 			spa_prop_add_list(*nvp, prop, strval, 0, src);
467 			kmem_free(strval, za.za_num_integers);
468 			break;
469 
470 		default:
471 			break;
472 		}
473 	}
474 	zap_cursor_fini(&zc);
475 	mutex_exit(&spa->spa_props_lock);
476 out:
477 	if (err && err != ENOENT) {
478 		nvlist_free(*nvp);
479 		*nvp = NULL;
480 		return (err);
481 	}
482 
483 	return (0);
484 }
485 
486 /*
487  * Validate the given pool properties nvlist and modify the list
488  * for the property values to be set.
489  */
490 static int
491 spa_prop_validate(spa_t *spa, nvlist_t *props)
492 {
493 	nvpair_t *elem;
494 	int error = 0, reset_bootfs = 0;
495 	uint64_t objnum = 0;
496 	boolean_t has_feature = B_FALSE;
497 
498 	elem = NULL;
499 	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
500 		uint64_t intval;
501 		char *strval, *slash, *check, *fname;
502 		const char *propname = nvpair_name(elem);
503 		zpool_prop_t prop = zpool_name_to_prop(propname);
504 
505 		switch (prop) {
506 		case ZPOOL_PROP_INVAL:
507 			if (!zpool_prop_feature(propname)) {
508 				error = SET_ERROR(EINVAL);
509 				break;
510 			}
511 
512 			/*
513 			 * Sanitize the input.
514 			 */
515 			if (nvpair_type(elem) != DATA_TYPE_UINT64) {
516 				error = SET_ERROR(EINVAL);
517 				break;
518 			}
519 
520 			if (nvpair_value_uint64(elem, &intval) != 0) {
521 				error = SET_ERROR(EINVAL);
522 				break;
523 			}
524 
525 			if (intval != 0) {
526 				error = SET_ERROR(EINVAL);
527 				break;
528 			}
529 
530 			fname = strchr(propname, '@') + 1;
531 			if (zfeature_lookup_name(fname, NULL) != 0) {
532 				error = SET_ERROR(EINVAL);
533 				break;
534 			}
535 
536 			has_feature = B_TRUE;
537 			break;
538 
539 		case ZPOOL_PROP_VERSION:
540 			error = nvpair_value_uint64(elem, &intval);
541 			if (!error &&
542 			    (intval < spa_version(spa) ||
543 			    intval > SPA_VERSION_BEFORE_FEATURES ||
544 			    has_feature))
545 				error = SET_ERROR(EINVAL);
546 			break;
547 
548 		case ZPOOL_PROP_DELEGATION:
549 		case ZPOOL_PROP_AUTOREPLACE:
550 		case ZPOOL_PROP_LISTSNAPS:
551 		case ZPOOL_PROP_AUTOEXPAND:
552 			error = nvpair_value_uint64(elem, &intval);
553 			if (!error && intval > 1)
554 				error = SET_ERROR(EINVAL);
555 			break;
556 
557 		case ZPOOL_PROP_MULTIHOST:
558 			error = nvpair_value_uint64(elem, &intval);
559 			if (!error && intval > 1)
560 				error = SET_ERROR(EINVAL);
561 
562 			if (!error && !spa_get_hostid())
563 				error = SET_ERROR(ENOTSUP);
564 
565 			break;
566 
567 		case ZPOOL_PROP_BOOTFS:
568 			/*
569 			 * If the pool version is less than SPA_VERSION_BOOTFS,
570 			 * or the pool is still being created (version == 0),
571 			 * the bootfs property cannot be set.
572 			 */
573 			if (spa_version(spa) < SPA_VERSION_BOOTFS) {
574 				error = SET_ERROR(ENOTSUP);
575 				break;
576 			}
577 
578 			/*
579 			 * Make sure the vdev config is bootable
580 			 */
581 			if (!vdev_is_bootable(spa->spa_root_vdev)) {
582 				error = SET_ERROR(ENOTSUP);
583 				break;
584 			}
585 
586 			reset_bootfs = 1;
587 
588 			error = nvpair_value_string(elem, &strval);
589 
590 			if (!error) {
591 				objset_t *os;
592 				uint64_t propval;
593 
594 				if (strval == NULL || strval[0] == '\0') {
595 					objnum = zpool_prop_default_numeric(
596 					    ZPOOL_PROP_BOOTFS);
597 					break;
598 				}
599 
600 				error = dmu_objset_hold(strval, FTAG, &os);
601 				if (error != 0)
602 					break;
603 
604 				/*
605 				 * Must be ZPL, and its property settings
606 				 * must be supported.
607 				 */
608 
609 				if (dmu_objset_type(os) != DMU_OST_ZFS) {
610 					error = SET_ERROR(ENOTSUP);
611 				} else if ((error =
612 				    dsl_prop_get_int_ds(dmu_objset_ds(os),
613 				    zfs_prop_to_name(ZFS_PROP_COMPRESSION),
614 				    &propval)) == 0 &&
615 				    !BOOTFS_COMPRESS_VALID(propval)) {
616 					error = SET_ERROR(ENOTSUP);
617 				} else {
618 					objnum = dmu_objset_id(os);
619 				}
620 				dmu_objset_rele(os, FTAG);
621 			}
622 			break;
623 
624 		case ZPOOL_PROP_FAILUREMODE:
625 			error = nvpair_value_uint64(elem, &intval);
626 			if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
627 			    intval > ZIO_FAILURE_MODE_PANIC))
628 				error = SET_ERROR(EINVAL);
629 
630 			/*
631 			 * This is a special case which only occurs when
632 			 * the pool has completely failed. This allows
633 			 * the user to change the in-core failmode property
634 			 * without syncing it out to disk (I/Os might
635 			 * currently be blocked). We do this by returning
636 			 * EIO to the caller (spa_prop_set) to trick it
637 			 * into thinking we encountered a property validation
638 			 * error.
639 			 */
640 			if (!error && spa_suspended(spa)) {
641 				spa->spa_failmode = intval;
642 				error = SET_ERROR(EIO);
643 			}
644 			break;
645 
646 		case ZPOOL_PROP_CACHEFILE:
647 			if ((error = nvpair_value_string(elem, &strval)) != 0)
648 				break;
649 
650 			if (strval[0] == '\0')
651 				break;
652 
653 			if (strcmp(strval, "none") == 0)
654 				break;
655 
656 			if (strval[0] != '/') {
657 				error = SET_ERROR(EINVAL);
658 				break;
659 			}
660 
661 			slash = strrchr(strval, '/');
662 			ASSERT(slash != NULL);
663 
664 			if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
665 			    strcmp(slash, "/..") == 0)
666 				error = SET_ERROR(EINVAL);
667 			break;
668 
669 		case ZPOOL_PROP_COMMENT:
670 			if ((error = nvpair_value_string(elem, &strval)) != 0)
671 				break;
672 			for (check = strval; *check != '\0'; check++) {
673 				/*
674 				 * The kernel doesn't have an easy isprint()
675 				 * check.  For this kernel check, we merely
676 				 * check ASCII apart from DEL.  Fix this if
677 				 * there is an easy-to-use kernel isprint().
678 				 */
679 				if (*check >= 0x7f) {
680 					error = SET_ERROR(EINVAL);
681 					break;
682 				}
683 			}
684 			if (strlen(strval) > ZPROP_MAX_COMMENT)
685 				error = E2BIG;
686 			break;
687 
688 		case ZPOOL_PROP_DEDUPDITTO:
689 			if (spa_version(spa) < SPA_VERSION_DEDUP)
690 				error = SET_ERROR(ENOTSUP);
691 			else
692 				error = nvpair_value_uint64(elem, &intval);
693 			if (error == 0 &&
694 			    intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
695 				error = SET_ERROR(EINVAL);
696 			break;
697 		}
698 
699 		if (error)
700 			break;
701 	}
702 
703 	if (!error && reset_bootfs) {
704 		error = nvlist_remove(props,
705 		    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
706 
707 		if (!error) {
708 			error = nvlist_add_uint64(props,
709 			    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
710 		}
711 	}
712 
713 	return (error);
714 }
715 
716 void
717 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
718 {
719 	char *cachefile;
720 	spa_config_dirent_t *dp;
721 
722 	if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
723 	    &cachefile) != 0)
724 		return;
725 
726 	dp = kmem_alloc(sizeof (spa_config_dirent_t),
727 	    KM_SLEEP);
728 
729 	if (cachefile[0] == '\0')
730 		dp->scd_path = spa_strdup(spa_config_path);
731 	else if (strcmp(cachefile, "none") == 0)
732 		dp->scd_path = NULL;
733 	else
734 		dp->scd_path = spa_strdup(cachefile);
735 
736 	list_insert_head(&spa->spa_config_list, dp);
737 	if (need_sync)
738 		spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
739 }
740 
741 int
742 spa_prop_set(spa_t *spa, nvlist_t *nvp)
743 {
744 	int error;
745 	nvpair_t *elem = NULL;
746 	boolean_t need_sync = B_FALSE;
747 
748 	if ((error = spa_prop_validate(spa, nvp)) != 0)
749 		return (error);
750 
751 	while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
752 		zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
753 
754 		if (prop == ZPOOL_PROP_CACHEFILE ||
755 		    prop == ZPOOL_PROP_ALTROOT ||
756 		    prop == ZPOOL_PROP_READONLY)
757 			continue;
758 
759 		if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
760 			uint64_t ver;
761 
762 			if (prop == ZPOOL_PROP_VERSION) {
763 				VERIFY(nvpair_value_uint64(elem, &ver) == 0);
764 			} else {
765 				ASSERT(zpool_prop_feature(nvpair_name(elem)));
766 				ver = SPA_VERSION_FEATURES;
767 				need_sync = B_TRUE;
768 			}
769 
770 			/* Save time if the version is already set. */
771 			if (ver == spa_version(spa))
772 				continue;
773 
774 			/*
775 			 * In addition to the pool directory object, we might
776 			 * create the pool properties object, the features for
777 			 * read object, the features for write object, or the
778 			 * feature descriptions object.
779 			 */
780 			error = dsl_sync_task(spa->spa_name, NULL,
781 			    spa_sync_version, &ver,
782 			    6, ZFS_SPACE_CHECK_RESERVED);
783 			if (error)
784 				return (error);
785 			continue;
786 		}
787 
788 		need_sync = B_TRUE;
789 		break;
790 	}
791 
792 	if (need_sync) {
793 		return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
794 		    nvp, 6, ZFS_SPACE_CHECK_RESERVED));
795 	}
796 
797 	return (0);
798 }
799 
800 /*
801  * If the bootfs property value is dsobj, clear it.
802  */
803 void
804 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
805 {
806 	if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
807 		VERIFY(zap_remove(spa->spa_meta_objset,
808 		    spa->spa_pool_props_object,
809 		    zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
810 		spa->spa_bootfs = 0;
811 	}
812 }
813 
814 /*ARGSUSED*/
815 static int
816 spa_change_guid_check(void *arg, dmu_tx_t *tx)
817 {
818 	uint64_t *newguid = arg;
819 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
820 	vdev_t *rvd = spa->spa_root_vdev;
821 	uint64_t vdev_state;
822 
823 	if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
824 		int error = (spa_has_checkpoint(spa)) ?
825 		    ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
826 		return (SET_ERROR(error));
827 	}
828 
829 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
830 	vdev_state = rvd->vdev_state;
831 	spa_config_exit(spa, SCL_STATE, FTAG);
832 
833 	if (vdev_state != VDEV_STATE_HEALTHY)
834 		return (SET_ERROR(ENXIO));
835 
836 	ASSERT3U(spa_guid(spa), !=, *newguid);
837 
838 	return (0);
839 }
840 
841 static void
842 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
843 {
844 	uint64_t *newguid = arg;
845 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
846 	uint64_t oldguid;
847 	vdev_t *rvd = spa->spa_root_vdev;
848 
849 	oldguid = spa_guid(spa);
850 
851 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
852 	rvd->vdev_guid = *newguid;
853 	rvd->vdev_guid_sum += (*newguid - oldguid);
854 	vdev_config_dirty(rvd);
855 	spa_config_exit(spa, SCL_STATE, FTAG);
856 
857 	spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
858 	    oldguid, *newguid);
859 }
860 
861 /*
862  * Change the GUID for the pool.  This is done so that we can later
863  * re-import a pool built from a clone of our own vdevs.  We will modify
864  * the root vdev's guid, our own pool guid, and then mark all of our
865  * vdevs dirty.  Note that we must make sure that all our vdevs are
866  * online when we do this, or else any vdevs that weren't present
867  * would be orphaned from our pool.  We are also going to issue a
868  * sysevent to update any watchers.
869  */
870 int
871 spa_change_guid(spa_t *spa)
872 {
873 	int error;
874 	uint64_t guid;
875 
876 	mutex_enter(&spa->spa_vdev_top_lock);
877 	mutex_enter(&spa_namespace_lock);
878 	guid = spa_generate_guid(NULL);
879 
880 	error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
881 	    spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
882 
883 	if (error == 0) {
884 		spa_write_cachefile(spa, B_FALSE, B_TRUE);
885 		spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
886 	}
887 
888 	mutex_exit(&spa_namespace_lock);
889 	mutex_exit(&spa->spa_vdev_top_lock);
890 
891 	return (error);
892 }
893 
894 /*
895  * ==========================================================================
896  * SPA state manipulation (open/create/destroy/import/export)
897  * ==========================================================================
898  */
899 
900 static int
901 spa_error_entry_compare(const void *a, const void *b)
902 {
903 	const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
904 	const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
905 	int ret;
906 
907 	ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
908 	    sizeof (zbookmark_phys_t));
909 
910 	return (AVL_ISIGN(ret));
911 }
912 
913 /*
914  * Utility function which retrieves copies of the current logs and
915  * re-initializes them in the process.
916  */
917 void
918 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
919 {
920 	ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
921 
922 	bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
923 	bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
924 
925 	avl_create(&spa->spa_errlist_scrub,
926 	    spa_error_entry_compare, sizeof (spa_error_entry_t),
927 	    offsetof(spa_error_entry_t, se_avl));
928 	avl_create(&spa->spa_errlist_last,
929 	    spa_error_entry_compare, sizeof (spa_error_entry_t),
930 	    offsetof(spa_error_entry_t, se_avl));
931 }
932 
933 static void
934 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
935 {
936 	const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
937 	enum zti_modes mode = ztip->zti_mode;
938 	uint_t value = ztip->zti_value;
939 	uint_t count = ztip->zti_count;
940 	spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
941 	char name[32];
942 	uint_t flags = 0;
943 	boolean_t batch = B_FALSE;
944 
945 	if (mode == ZTI_MODE_NULL) {
946 		tqs->stqs_count = 0;
947 		tqs->stqs_taskq = NULL;
948 		return;
949 	}
950 
951 	ASSERT3U(count, >, 0);
952 
953 	tqs->stqs_count = count;
954 	tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
955 
956 	switch (mode) {
957 	case ZTI_MODE_FIXED:
958 		ASSERT3U(value, >=, 1);
959 		value = MAX(value, 1);
960 		break;
961 
962 	case ZTI_MODE_BATCH:
963 		batch = B_TRUE;
964 		flags |= TASKQ_THREADS_CPU_PCT;
965 		value = zio_taskq_batch_pct;
966 		break;
967 
968 	default:
969 		panic("unrecognized mode for %s_%s taskq (%u:%u) in "
970 		    "spa_activate()",
971 		    zio_type_name[t], zio_taskq_types[q], mode, value);
972 		break;
973 	}
974 
975 	for (uint_t i = 0; i < count; i++) {
976 		taskq_t *tq;
977 
978 		if (count > 1) {
979 			(void) snprintf(name, sizeof (name), "%s_%s_%u",
980 			    zio_type_name[t], zio_taskq_types[q], i);
981 		} else {
982 			(void) snprintf(name, sizeof (name), "%s_%s",
983 			    zio_type_name[t], zio_taskq_types[q]);
984 		}
985 
986 		if (zio_taskq_sysdc && spa->spa_proc != &p0) {
987 			if (batch)
988 				flags |= TASKQ_DC_BATCH;
989 
990 			tq = taskq_create_sysdc(name, value, 50, INT_MAX,
991 			    spa->spa_proc, zio_taskq_basedc, flags);
992 		} else {
993 			pri_t pri = maxclsyspri;
994 			/*
995 			 * The write issue taskq can be extremely CPU
996 			 * intensive.  Run it at slightly lower priority
997 			 * than the other taskqs.
998 			 */
999 			if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1000 				pri--;
1001 
1002 			tq = taskq_create_proc(name, value, pri, 50,
1003 			    INT_MAX, spa->spa_proc, flags);
1004 		}
1005 
1006 		tqs->stqs_taskq[i] = tq;
1007 	}
1008 }
1009 
1010 static void
1011 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1012 {
1013 	spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1014 
1015 	if (tqs->stqs_taskq == NULL) {
1016 		ASSERT0(tqs->stqs_count);
1017 		return;
1018 	}
1019 
1020 	for (uint_t i = 0; i < tqs->stqs_count; i++) {
1021 		ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1022 		taskq_destroy(tqs->stqs_taskq[i]);
1023 	}
1024 
1025 	kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1026 	tqs->stqs_taskq = NULL;
1027 }
1028 
1029 /*
1030  * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1031  * Note that a type may have multiple discrete taskqs to avoid lock contention
1032  * on the taskq itself. In that case we choose which taskq at random by using
1033  * the low bits of gethrtime().
1034  */
1035 void
1036 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1037     task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1038 {
1039 	spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1040 	taskq_t *tq;
1041 
1042 	ASSERT3P(tqs->stqs_taskq, !=, NULL);
1043 	ASSERT3U(tqs->stqs_count, !=, 0);
1044 
1045 	if (tqs->stqs_count == 1) {
1046 		tq = tqs->stqs_taskq[0];
1047 	} else {
1048 		tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1049 	}
1050 
1051 	taskq_dispatch_ent(tq, func, arg, flags, ent);
1052 }
1053 
1054 static void
1055 spa_create_zio_taskqs(spa_t *spa)
1056 {
1057 	for (int t = 0; t < ZIO_TYPES; t++) {
1058 		for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1059 			spa_taskqs_init(spa, t, q);
1060 		}
1061 	}
1062 }
1063 
1064 #ifdef _KERNEL
1065 static void
1066 spa_thread(void *arg)
1067 {
1068 	callb_cpr_t cprinfo;
1069 
1070 	spa_t *spa = arg;
1071 	user_t *pu = PTOU(curproc);
1072 
1073 	CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1074 	    spa->spa_name);
1075 
1076 	ASSERT(curproc != &p0);
1077 	(void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1078 	    "zpool-%s", spa->spa_name);
1079 	(void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1080 
1081 	/* bind this thread to the requested psrset */
1082 	if (zio_taskq_psrset_bind != PS_NONE) {
1083 		pool_lock();
1084 		mutex_enter(&cpu_lock);
1085 		mutex_enter(&pidlock);
1086 		mutex_enter(&curproc->p_lock);
1087 
1088 		if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1089 		    0, NULL, NULL) == 0)  {
1090 			curthread->t_bind_pset = zio_taskq_psrset_bind;
1091 		} else {
1092 			cmn_err(CE_WARN,
1093 			    "Couldn't bind process for zfs pool \"%s\" to "
1094 			    "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1095 		}
1096 
1097 		mutex_exit(&curproc->p_lock);
1098 		mutex_exit(&pidlock);
1099 		mutex_exit(&cpu_lock);
1100 		pool_unlock();
1101 	}
1102 
1103 	if (zio_taskq_sysdc) {
1104 		sysdc_thread_enter(curthread, 100, 0);
1105 	}
1106 
1107 	spa->spa_proc = curproc;
1108 	spa->spa_did = curthread->t_did;
1109 
1110 	spa_create_zio_taskqs(spa);
1111 
1112 	mutex_enter(&spa->spa_proc_lock);
1113 	ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1114 
1115 	spa->spa_proc_state = SPA_PROC_ACTIVE;
1116 	cv_broadcast(&spa->spa_proc_cv);
1117 
1118 	CALLB_CPR_SAFE_BEGIN(&cprinfo);
1119 	while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1120 		cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1121 	CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1122 
1123 	ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1124 	spa->spa_proc_state = SPA_PROC_GONE;
1125 	spa->spa_proc = &p0;
1126 	cv_broadcast(&spa->spa_proc_cv);
1127 	CALLB_CPR_EXIT(&cprinfo);	/* drops spa_proc_lock */
1128 
1129 	mutex_enter(&curproc->p_lock);
1130 	lwp_exit();
1131 }
1132 #endif
1133 
1134 /*
1135  * Activate an uninitialized pool.
1136  */
1137 static void
1138 spa_activate(spa_t *spa, int mode)
1139 {
1140 	ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1141 
1142 	spa->spa_state = POOL_STATE_ACTIVE;
1143 	spa->spa_mode = mode;
1144 
1145 	spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1146 	spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1147 	spa->spa_special_class = metaslab_class_create(spa, zfs_metaslab_ops);
1148 	spa->spa_dedup_class = metaslab_class_create(spa, zfs_metaslab_ops);
1149 
1150 	/* Try to create a covering process */
1151 	mutex_enter(&spa->spa_proc_lock);
1152 	ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1153 	ASSERT(spa->spa_proc == &p0);
1154 	spa->spa_did = 0;
1155 
1156 	/* Only create a process if we're going to be around a while. */
1157 	if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1158 		if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1159 		    NULL, 0) == 0) {
1160 			spa->spa_proc_state = SPA_PROC_CREATED;
1161 			while (spa->spa_proc_state == SPA_PROC_CREATED) {
1162 				cv_wait(&spa->spa_proc_cv,
1163 				    &spa->spa_proc_lock);
1164 			}
1165 			ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1166 			ASSERT(spa->spa_proc != &p0);
1167 			ASSERT(spa->spa_did != 0);
1168 		} else {
1169 #ifdef _KERNEL
1170 			cmn_err(CE_WARN,
1171 			    "Couldn't create process for zfs pool \"%s\"\n",
1172 			    spa->spa_name);
1173 #endif
1174 		}
1175 	}
1176 	mutex_exit(&spa->spa_proc_lock);
1177 
1178 	/* If we didn't create a process, we need to create our taskqs. */
1179 	if (spa->spa_proc == &p0) {
1180 		spa_create_zio_taskqs(spa);
1181 	}
1182 
1183 	for (size_t i = 0; i < TXG_SIZE; i++) {
1184 		spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL,
1185 		    ZIO_FLAG_CANFAIL);
1186 	}
1187 
1188 	list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1189 	    offsetof(vdev_t, vdev_config_dirty_node));
1190 	list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1191 	    offsetof(objset_t, os_evicting_node));
1192 	list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1193 	    offsetof(vdev_t, vdev_state_dirty_node));
1194 
1195 	txg_list_create(&spa->spa_vdev_txg_list, spa,
1196 	    offsetof(struct vdev, vdev_txg_node));
1197 
1198 	avl_create(&spa->spa_errlist_scrub,
1199 	    spa_error_entry_compare, sizeof (spa_error_entry_t),
1200 	    offsetof(spa_error_entry_t, se_avl));
1201 	avl_create(&spa->spa_errlist_last,
1202 	    spa_error_entry_compare, sizeof (spa_error_entry_t),
1203 	    offsetof(spa_error_entry_t, se_avl));
1204 
1205 	spa_keystore_init(&spa->spa_keystore);
1206 }
1207 
1208 /*
1209  * Opposite of spa_activate().
1210  */
1211 static void
1212 spa_deactivate(spa_t *spa)
1213 {
1214 	ASSERT(spa->spa_sync_on == B_FALSE);
1215 	ASSERT(spa->spa_dsl_pool == NULL);
1216 	ASSERT(spa->spa_root_vdev == NULL);
1217 	ASSERT(spa->spa_async_zio_root == NULL);
1218 	ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1219 
1220 	spa_evicting_os_wait(spa);
1221 
1222 	txg_list_destroy(&spa->spa_vdev_txg_list);
1223 
1224 	list_destroy(&spa->spa_config_dirty_list);
1225 	list_destroy(&spa->spa_evicting_os_list);
1226 	list_destroy(&spa->spa_state_dirty_list);
1227 
1228 	for (int t = 0; t < ZIO_TYPES; t++) {
1229 		for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1230 			spa_taskqs_fini(spa, t, q);
1231 		}
1232 	}
1233 
1234 	for (size_t i = 0; i < TXG_SIZE; i++) {
1235 		ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1236 		VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1237 		spa->spa_txg_zio[i] = NULL;
1238 	}
1239 
1240 	metaslab_class_destroy(spa->spa_normal_class);
1241 	spa->spa_normal_class = NULL;
1242 
1243 	metaslab_class_destroy(spa->spa_log_class);
1244 	spa->spa_log_class = NULL;
1245 
1246 	metaslab_class_destroy(spa->spa_special_class);
1247 	spa->spa_special_class = NULL;
1248 
1249 	metaslab_class_destroy(spa->spa_dedup_class);
1250 	spa->spa_dedup_class = NULL;
1251 
1252 	/*
1253 	 * If this was part of an import or the open otherwise failed, we may
1254 	 * still have errors left in the queues.  Empty them just in case.
1255 	 */
1256 	spa_errlog_drain(spa);
1257 	avl_destroy(&spa->spa_errlist_scrub);
1258 	avl_destroy(&spa->spa_errlist_last);
1259 
1260 	spa_keystore_fini(&spa->spa_keystore);
1261 
1262 	spa->spa_state = POOL_STATE_UNINITIALIZED;
1263 
1264 	mutex_enter(&spa->spa_proc_lock);
1265 	if (spa->spa_proc_state != SPA_PROC_NONE) {
1266 		ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1267 		spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1268 		cv_broadcast(&spa->spa_proc_cv);
1269 		while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1270 			ASSERT(spa->spa_proc != &p0);
1271 			cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1272 		}
1273 		ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1274 		spa->spa_proc_state = SPA_PROC_NONE;
1275 	}
1276 	ASSERT(spa->spa_proc == &p0);
1277 	mutex_exit(&spa->spa_proc_lock);
1278 
1279 	/*
1280 	 * We want to make sure spa_thread() has actually exited the ZFS
1281 	 * module, so that the module can't be unloaded out from underneath
1282 	 * it.
1283 	 */
1284 	if (spa->spa_did != 0) {
1285 		thread_join(spa->spa_did);
1286 		spa->spa_did = 0;
1287 	}
1288 }
1289 
1290 /*
1291  * Verify a pool configuration, and construct the vdev tree appropriately.  This
1292  * will create all the necessary vdevs in the appropriate layout, with each vdev
1293  * in the CLOSED state.  This will prep the pool before open/creation/import.
1294  * All vdev validation is done by the vdev_alloc() routine.
1295  */
1296 static int
1297 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1298     uint_t id, int atype)
1299 {
1300 	nvlist_t **child;
1301 	uint_t children;
1302 	int error;
1303 
1304 	if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1305 		return (error);
1306 
1307 	if ((*vdp)->vdev_ops->vdev_op_leaf)
1308 		return (0);
1309 
1310 	error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1311 	    &child, &children);
1312 
1313 	if (error == ENOENT)
1314 		return (0);
1315 
1316 	if (error) {
1317 		vdev_free(*vdp);
1318 		*vdp = NULL;
1319 		return (SET_ERROR(EINVAL));
1320 	}
1321 
1322 	for (int c = 0; c < children; c++) {
1323 		vdev_t *vd;
1324 		if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1325 		    atype)) != 0) {
1326 			vdev_free(*vdp);
1327 			*vdp = NULL;
1328 			return (error);
1329 		}
1330 	}
1331 
1332 	ASSERT(*vdp != NULL);
1333 
1334 	return (0);
1335 }
1336 
1337 /*
1338  * Opposite of spa_load().
1339  */
1340 static void
1341 spa_unload(spa_t *spa)
1342 {
1343 	int i;
1344 
1345 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1346 
1347 	spa_load_note(spa, "UNLOADING");
1348 
1349 	/*
1350 	 * Stop async tasks.
1351 	 */
1352 	spa_async_suspend(spa);
1353 
1354 	if (spa->spa_root_vdev) {
1355 		vdev_initialize_stop_all(spa->spa_root_vdev,
1356 		    VDEV_INITIALIZE_ACTIVE);
1357 	}
1358 
1359 	/*
1360 	 * Stop syncing.
1361 	 */
1362 	if (spa->spa_sync_on) {
1363 		txg_sync_stop(spa->spa_dsl_pool);
1364 		spa->spa_sync_on = B_FALSE;
1365 	}
1366 
1367 	/*
1368 	 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1369 	 * to call it earlier, before we wait for async i/o to complete.
1370 	 * This ensures that there is no async metaslab prefetching, by
1371 	 * calling taskq_wait(mg_taskq).
1372 	 */
1373 	if (spa->spa_root_vdev != NULL) {
1374 		spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1375 		for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1376 			vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1377 		spa_config_exit(spa, SCL_ALL, spa);
1378 	}
1379 
1380 	if (spa->spa_mmp.mmp_thread)
1381 		mmp_thread_stop(spa);
1382 
1383 	/*
1384 	 * Wait for any outstanding async I/O to complete.
1385 	 */
1386 	if (spa->spa_async_zio_root != NULL) {
1387 		for (int i = 0; i < max_ncpus; i++)
1388 			(void) zio_wait(spa->spa_async_zio_root[i]);
1389 		kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1390 		spa->spa_async_zio_root = NULL;
1391 	}
1392 
1393 	if (spa->spa_vdev_removal != NULL) {
1394 		spa_vdev_removal_destroy(spa->spa_vdev_removal);
1395 		spa->spa_vdev_removal = NULL;
1396 	}
1397 
1398 	if (spa->spa_condense_zthr != NULL) {
1399 		zthr_destroy(spa->spa_condense_zthr);
1400 		spa->spa_condense_zthr = NULL;
1401 	}
1402 
1403 	if (spa->spa_checkpoint_discard_zthr != NULL) {
1404 		zthr_destroy(spa->spa_checkpoint_discard_zthr);
1405 		spa->spa_checkpoint_discard_zthr = NULL;
1406 	}
1407 
1408 	spa_condense_fini(spa);
1409 
1410 	bpobj_close(&spa->spa_deferred_bpobj);
1411 
1412 	spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1413 
1414 	/*
1415 	 * Close all vdevs.
1416 	 */
1417 	if (spa->spa_root_vdev)
1418 		vdev_free(spa->spa_root_vdev);
1419 	ASSERT(spa->spa_root_vdev == NULL);
1420 
1421 	/*
1422 	 * Close the dsl pool.
1423 	 */
1424 	if (spa->spa_dsl_pool) {
1425 		dsl_pool_close(spa->spa_dsl_pool);
1426 		spa->spa_dsl_pool = NULL;
1427 		spa->spa_meta_objset = NULL;
1428 	}
1429 
1430 	ddt_unload(spa);
1431 
1432 	/*
1433 	 * Drop and purge level 2 cache
1434 	 */
1435 	spa_l2cache_drop(spa);
1436 
1437 	for (i = 0; i < spa->spa_spares.sav_count; i++)
1438 		vdev_free(spa->spa_spares.sav_vdevs[i]);
1439 	if (spa->spa_spares.sav_vdevs) {
1440 		kmem_free(spa->spa_spares.sav_vdevs,
1441 		    spa->spa_spares.sav_count * sizeof (void *));
1442 		spa->spa_spares.sav_vdevs = NULL;
1443 	}
1444 	if (spa->spa_spares.sav_config) {
1445 		nvlist_free(spa->spa_spares.sav_config);
1446 		spa->spa_spares.sav_config = NULL;
1447 	}
1448 	spa->spa_spares.sav_count = 0;
1449 
1450 	for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1451 		vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1452 		vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1453 	}
1454 	if (spa->spa_l2cache.sav_vdevs) {
1455 		kmem_free(spa->spa_l2cache.sav_vdevs,
1456 		    spa->spa_l2cache.sav_count * sizeof (void *));
1457 		spa->spa_l2cache.sav_vdevs = NULL;
1458 	}
1459 	if (spa->spa_l2cache.sav_config) {
1460 		nvlist_free(spa->spa_l2cache.sav_config);
1461 		spa->spa_l2cache.sav_config = NULL;
1462 	}
1463 	spa->spa_l2cache.sav_count = 0;
1464 
1465 	spa->spa_async_suspended = 0;
1466 
1467 	spa->spa_indirect_vdevs_loaded = B_FALSE;
1468 
1469 	if (spa->spa_comment != NULL) {
1470 		spa_strfree(spa->spa_comment);
1471 		spa->spa_comment = NULL;
1472 	}
1473 
1474 	spa_config_exit(spa, SCL_ALL, spa);
1475 }
1476 
1477 /*
1478  * Load (or re-load) the current list of vdevs describing the active spares for
1479  * this pool.  When this is called, we have some form of basic information in
1480  * 'spa_spares.sav_config'.  We parse this into vdevs, try to open them, and
1481  * then re-generate a more complete list including status information.
1482  */
1483 void
1484 spa_load_spares(spa_t *spa)
1485 {
1486 	nvlist_t **spares;
1487 	uint_t nspares;
1488 	int i;
1489 	vdev_t *vd, *tvd;
1490 
1491 #ifndef _KERNEL
1492 	/*
1493 	 * zdb opens both the current state of the pool and the
1494 	 * checkpointed state (if present), with a different spa_t.
1495 	 *
1496 	 * As spare vdevs are shared among open pools, we skip loading
1497 	 * them when we load the checkpointed state of the pool.
1498 	 */
1499 	if (!spa_writeable(spa))
1500 		return;
1501 #endif
1502 
1503 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1504 
1505 	/*
1506 	 * First, close and free any existing spare vdevs.
1507 	 */
1508 	for (i = 0; i < spa->spa_spares.sav_count; i++) {
1509 		vd = spa->spa_spares.sav_vdevs[i];
1510 
1511 		/* Undo the call to spa_activate() below */
1512 		if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1513 		    B_FALSE)) != NULL && tvd->vdev_isspare)
1514 			spa_spare_remove(tvd);
1515 		vdev_close(vd);
1516 		vdev_free(vd);
1517 	}
1518 
1519 	if (spa->spa_spares.sav_vdevs)
1520 		kmem_free(spa->spa_spares.sav_vdevs,
1521 		    spa->spa_spares.sav_count * sizeof (void *));
1522 
1523 	if (spa->spa_spares.sav_config == NULL)
1524 		nspares = 0;
1525 	else
1526 		VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1527 		    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1528 
1529 	spa->spa_spares.sav_count = (int)nspares;
1530 	spa->spa_spares.sav_vdevs = NULL;
1531 
1532 	if (nspares == 0)
1533 		return;
1534 
1535 	/*
1536 	 * Construct the array of vdevs, opening them to get status in the
1537 	 * process.   For each spare, there is potentially two different vdev_t
1538 	 * structures associated with it: one in the list of spares (used only
1539 	 * for basic validation purposes) and one in the active vdev
1540 	 * configuration (if it's spared in).  During this phase we open and
1541 	 * validate each vdev on the spare list.  If the vdev also exists in the
1542 	 * active configuration, then we also mark this vdev as an active spare.
1543 	 */
1544 	spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1545 	    KM_SLEEP);
1546 	for (i = 0; i < spa->spa_spares.sav_count; i++) {
1547 		VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1548 		    VDEV_ALLOC_SPARE) == 0);
1549 		ASSERT(vd != NULL);
1550 
1551 		spa->spa_spares.sav_vdevs[i] = vd;
1552 
1553 		if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1554 		    B_FALSE)) != NULL) {
1555 			if (!tvd->vdev_isspare)
1556 				spa_spare_add(tvd);
1557 
1558 			/*
1559 			 * We only mark the spare active if we were successfully
1560 			 * able to load the vdev.  Otherwise, importing a pool
1561 			 * with a bad active spare would result in strange
1562 			 * behavior, because multiple pool would think the spare
1563 			 * is actively in use.
1564 			 *
1565 			 * There is a vulnerability here to an equally bizarre
1566 			 * circumstance, where a dead active spare is later
1567 			 * brought back to life (onlined or otherwise).  Given
1568 			 * the rarity of this scenario, and the extra complexity
1569 			 * it adds, we ignore the possibility.
1570 			 */
1571 			if (!vdev_is_dead(tvd))
1572 				spa_spare_activate(tvd);
1573 		}
1574 
1575 		vd->vdev_top = vd;
1576 		vd->vdev_aux = &spa->spa_spares;
1577 
1578 		if (vdev_open(vd) != 0)
1579 			continue;
1580 
1581 		if (vdev_validate_aux(vd) == 0)
1582 			spa_spare_add(vd);
1583 	}
1584 
1585 	/*
1586 	 * Recompute the stashed list of spares, with status information
1587 	 * this time.
1588 	 */
1589 	VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1590 	    DATA_TYPE_NVLIST_ARRAY) == 0);
1591 
1592 	spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1593 	    KM_SLEEP);
1594 	for (i = 0; i < spa->spa_spares.sav_count; i++)
1595 		spares[i] = vdev_config_generate(spa,
1596 		    spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1597 	VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1598 	    ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1599 	for (i = 0; i < spa->spa_spares.sav_count; i++)
1600 		nvlist_free(spares[i]);
1601 	kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1602 }
1603 
1604 /*
1605  * Load (or re-load) the current list of vdevs describing the active l2cache for
1606  * this pool.  When this is called, we have some form of basic information in
1607  * 'spa_l2cache.sav_config'.  We parse this into vdevs, try to open them, and
1608  * then re-generate a more complete list including status information.
1609  * Devices which are already active have their details maintained, and are
1610  * not re-opened.
1611  */
1612 void
1613 spa_load_l2cache(spa_t *spa)
1614 {
1615 	nvlist_t **l2cache;
1616 	uint_t nl2cache;
1617 	int i, j, oldnvdevs;
1618 	uint64_t guid;
1619 	vdev_t *vd, **oldvdevs, **newvdevs;
1620 	spa_aux_vdev_t *sav = &spa->spa_l2cache;
1621 
1622 #ifndef _KERNEL
1623 	/*
1624 	 * zdb opens both the current state of the pool and the
1625 	 * checkpointed state (if present), with a different spa_t.
1626 	 *
1627 	 * As L2 caches are part of the ARC which is shared among open
1628 	 * pools, we skip loading them when we load the checkpointed
1629 	 * state of the pool.
1630 	 */
1631 	if (!spa_writeable(spa))
1632 		return;
1633 #endif
1634 
1635 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1636 
1637 	if (sav->sav_config != NULL) {
1638 		VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1639 		    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1640 		newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1641 	} else {
1642 		nl2cache = 0;
1643 		newvdevs = NULL;
1644 	}
1645 
1646 	oldvdevs = sav->sav_vdevs;
1647 	oldnvdevs = sav->sav_count;
1648 	sav->sav_vdevs = NULL;
1649 	sav->sav_count = 0;
1650 
1651 	/*
1652 	 * Process new nvlist of vdevs.
1653 	 */
1654 	for (i = 0; i < nl2cache; i++) {
1655 		VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1656 		    &guid) == 0);
1657 
1658 		newvdevs[i] = NULL;
1659 		for (j = 0; j < oldnvdevs; j++) {
1660 			vd = oldvdevs[j];
1661 			if (vd != NULL && guid == vd->vdev_guid) {
1662 				/*
1663 				 * Retain previous vdev for add/remove ops.
1664 				 */
1665 				newvdevs[i] = vd;
1666 				oldvdevs[j] = NULL;
1667 				break;
1668 			}
1669 		}
1670 
1671 		if (newvdevs[i] == NULL) {
1672 			/*
1673 			 * Create new vdev
1674 			 */
1675 			VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1676 			    VDEV_ALLOC_L2CACHE) == 0);
1677 			ASSERT(vd != NULL);
1678 			newvdevs[i] = vd;
1679 
1680 			/*
1681 			 * Commit this vdev as an l2cache device,
1682 			 * even if it fails to open.
1683 			 */
1684 			spa_l2cache_add(vd);
1685 
1686 			vd->vdev_top = vd;
1687 			vd->vdev_aux = sav;
1688 
1689 			spa_l2cache_activate(vd);
1690 
1691 			if (vdev_open(vd) != 0)
1692 				continue;
1693 
1694 			(void) vdev_validate_aux(vd);
1695 
1696 			if (!vdev_is_dead(vd))
1697 				l2arc_add_vdev(spa, vd);
1698 		}
1699 	}
1700 
1701 	/*
1702 	 * Purge vdevs that were dropped
1703 	 */
1704 	for (i = 0; i < oldnvdevs; i++) {
1705 		uint64_t pool;
1706 
1707 		vd = oldvdevs[i];
1708 		if (vd != NULL) {
1709 			ASSERT(vd->vdev_isl2cache);
1710 
1711 			if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1712 			    pool != 0ULL && l2arc_vdev_present(vd))
1713 				l2arc_remove_vdev(vd);
1714 			vdev_clear_stats(vd);
1715 			vdev_free(vd);
1716 		}
1717 	}
1718 
1719 	if (oldvdevs)
1720 		kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1721 
1722 	if (sav->sav_config == NULL)
1723 		goto out;
1724 
1725 	sav->sav_vdevs = newvdevs;
1726 	sav->sav_count = (int)nl2cache;
1727 
1728 	/*
1729 	 * Recompute the stashed list of l2cache devices, with status
1730 	 * information this time.
1731 	 */
1732 	VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1733 	    DATA_TYPE_NVLIST_ARRAY) == 0);
1734 
1735 	l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1736 	for (i = 0; i < sav->sav_count; i++)
1737 		l2cache[i] = vdev_config_generate(spa,
1738 		    sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1739 	VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1740 	    ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1741 out:
1742 	for (i = 0; i < sav->sav_count; i++)
1743 		nvlist_free(l2cache[i]);
1744 	if (sav->sav_count)
1745 		kmem_free(l2cache, sav->sav_count * sizeof (void *));
1746 }
1747 
1748 static int
1749 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1750 {
1751 	dmu_buf_t *db;
1752 	char *packed = NULL;
1753 	size_t nvsize = 0;
1754 	int error;
1755 	*value = NULL;
1756 
1757 	error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1758 	if (error != 0)
1759 		return (error);
1760 
1761 	nvsize = *(uint64_t *)db->db_data;
1762 	dmu_buf_rele(db, FTAG);
1763 
1764 	packed = kmem_alloc(nvsize, KM_SLEEP);
1765 	error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1766 	    DMU_READ_PREFETCH);
1767 	if (error == 0)
1768 		error = nvlist_unpack(packed, nvsize, value, 0);
1769 	kmem_free(packed, nvsize);
1770 
1771 	return (error);
1772 }
1773 
1774 /*
1775  * Concrete top-level vdevs that are not missing and are not logs. At every
1776  * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1777  */
1778 static uint64_t
1779 spa_healthy_core_tvds(spa_t *spa)
1780 {
1781 	vdev_t *rvd = spa->spa_root_vdev;
1782 	uint64_t tvds = 0;
1783 
1784 	for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1785 		vdev_t *vd = rvd->vdev_child[i];
1786 		if (vd->vdev_islog)
1787 			continue;
1788 		if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1789 			tvds++;
1790 	}
1791 
1792 	return (tvds);
1793 }
1794 
1795 /*
1796  * Checks to see if the given vdev could not be opened, in which case we post a
1797  * sysevent to notify the autoreplace code that the device has been removed.
1798  */
1799 static void
1800 spa_check_removed(vdev_t *vd)
1801 {
1802 	for (uint64_t c = 0; c < vd->vdev_children; c++)
1803 		spa_check_removed(vd->vdev_child[c]);
1804 
1805 	if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1806 	    vdev_is_concrete(vd)) {
1807 		zfs_post_autoreplace(vd->vdev_spa, vd);
1808 		spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1809 	}
1810 }
1811 
1812 static int
1813 spa_check_for_missing_logs(spa_t *spa)
1814 {
1815 	vdev_t *rvd = spa->spa_root_vdev;
1816 
1817 	/*
1818 	 * If we're doing a normal import, then build up any additional
1819 	 * diagnostic information about missing log devices.
1820 	 * We'll pass this up to the user for further processing.
1821 	 */
1822 	if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1823 		nvlist_t **child, *nv;
1824 		uint64_t idx = 0;
1825 
1826 		child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1827 		    KM_SLEEP);
1828 		VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1829 
1830 		for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1831 			vdev_t *tvd = rvd->vdev_child[c];
1832 
1833 			/*
1834 			 * We consider a device as missing only if it failed
1835 			 * to open (i.e. offline or faulted is not considered
1836 			 * as missing).
1837 			 */
1838 			if (tvd->vdev_islog &&
1839 			    tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1840 				child[idx++] = vdev_config_generate(spa, tvd,
1841 				    B_FALSE, VDEV_CONFIG_MISSING);
1842 			}
1843 		}
1844 
1845 		if (idx > 0) {
1846 			fnvlist_add_nvlist_array(nv,
1847 			    ZPOOL_CONFIG_CHILDREN, child, idx);
1848 			fnvlist_add_nvlist(spa->spa_load_info,
1849 			    ZPOOL_CONFIG_MISSING_DEVICES, nv);
1850 
1851 			for (uint64_t i = 0; i < idx; i++)
1852 				nvlist_free(child[i]);
1853 		}
1854 		nvlist_free(nv);
1855 		kmem_free(child, rvd->vdev_children * sizeof (char **));
1856 
1857 		if (idx > 0) {
1858 			spa_load_failed(spa, "some log devices are missing");
1859 			vdev_dbgmsg_print_tree(rvd, 2);
1860 			return (SET_ERROR(ENXIO));
1861 		}
1862 	} else {
1863 		for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1864 			vdev_t *tvd = rvd->vdev_child[c];
1865 
1866 			if (tvd->vdev_islog &&
1867 			    tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1868 				spa_set_log_state(spa, SPA_LOG_CLEAR);
1869 				spa_load_note(spa, "some log devices are "
1870 				    "missing, ZIL is dropped.");
1871 				vdev_dbgmsg_print_tree(rvd, 2);
1872 				break;
1873 			}
1874 		}
1875 	}
1876 
1877 	return (0);
1878 }
1879 
1880 /*
1881  * Check for missing log devices
1882  */
1883 static boolean_t
1884 spa_check_logs(spa_t *spa)
1885 {
1886 	boolean_t rv = B_FALSE;
1887 	dsl_pool_t *dp = spa_get_dsl(spa);
1888 
1889 	switch (spa->spa_log_state) {
1890 	case SPA_LOG_MISSING:
1891 		/* need to recheck in case slog has been restored */
1892 	case SPA_LOG_UNKNOWN:
1893 		rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1894 		    zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
1895 		if (rv)
1896 			spa_set_log_state(spa, SPA_LOG_MISSING);
1897 		break;
1898 	}
1899 	return (rv);
1900 }
1901 
1902 static boolean_t
1903 spa_passivate_log(spa_t *spa)
1904 {
1905 	vdev_t *rvd = spa->spa_root_vdev;
1906 	boolean_t slog_found = B_FALSE;
1907 
1908 	ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1909 
1910 	if (!spa_has_slogs(spa))
1911 		return (B_FALSE);
1912 
1913 	for (int c = 0; c < rvd->vdev_children; c++) {
1914 		vdev_t *tvd = rvd->vdev_child[c];
1915 		metaslab_group_t *mg = tvd->vdev_mg;
1916 
1917 		if (tvd->vdev_islog) {
1918 			metaslab_group_passivate(mg);
1919 			slog_found = B_TRUE;
1920 		}
1921 	}
1922 
1923 	return (slog_found);
1924 }
1925 
1926 static void
1927 spa_activate_log(spa_t *spa)
1928 {
1929 	vdev_t *rvd = spa->spa_root_vdev;
1930 
1931 	ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1932 
1933 	for (int c = 0; c < rvd->vdev_children; c++) {
1934 		vdev_t *tvd = rvd->vdev_child[c];
1935 		metaslab_group_t *mg = tvd->vdev_mg;
1936 
1937 		if (tvd->vdev_islog)
1938 			metaslab_group_activate(mg);
1939 	}
1940 }
1941 
1942 int
1943 spa_reset_logs(spa_t *spa)
1944 {
1945 	int error;
1946 
1947 	error = dmu_objset_find(spa_name(spa), zil_reset,
1948 	    NULL, DS_FIND_CHILDREN);
1949 	if (error == 0) {
1950 		/*
1951 		 * We successfully offlined the log device, sync out the
1952 		 * current txg so that the "stubby" block can be removed
1953 		 * by zil_sync().
1954 		 */
1955 		txg_wait_synced(spa->spa_dsl_pool, 0);
1956 	}
1957 	return (error);
1958 }
1959 
1960 static void
1961 spa_aux_check_removed(spa_aux_vdev_t *sav)
1962 {
1963 	for (int i = 0; i < sav->sav_count; i++)
1964 		spa_check_removed(sav->sav_vdevs[i]);
1965 }
1966 
1967 void
1968 spa_claim_notify(zio_t *zio)
1969 {
1970 	spa_t *spa = zio->io_spa;
1971 
1972 	if (zio->io_error)
1973 		return;
1974 
1975 	mutex_enter(&spa->spa_props_lock);	/* any mutex will do */
1976 	if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
1977 		spa->spa_claim_max_txg = zio->io_bp->blk_birth;
1978 	mutex_exit(&spa->spa_props_lock);
1979 }
1980 
1981 typedef struct spa_load_error {
1982 	uint64_t	sle_meta_count;
1983 	uint64_t	sle_data_count;
1984 } spa_load_error_t;
1985 
1986 static void
1987 spa_load_verify_done(zio_t *zio)
1988 {
1989 	blkptr_t *bp = zio->io_bp;
1990 	spa_load_error_t *sle = zio->io_private;
1991 	dmu_object_type_t type = BP_GET_TYPE(bp);
1992 	int error = zio->io_error;
1993 	spa_t *spa = zio->io_spa;
1994 
1995 	abd_free(zio->io_abd);
1996 	if (error) {
1997 		if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
1998 		    type != DMU_OT_INTENT_LOG)
1999 			atomic_inc_64(&sle->sle_meta_count);
2000 		else
2001 			atomic_inc_64(&sle->sle_data_count);
2002 	}
2003 
2004 	mutex_enter(&spa->spa_scrub_lock);
2005 	spa->spa_load_verify_ios--;
2006 	cv_broadcast(&spa->spa_scrub_io_cv);
2007 	mutex_exit(&spa->spa_scrub_lock);
2008 }
2009 
2010 /*
2011  * Maximum number of concurrent scrub i/os to create while verifying
2012  * a pool while importing it.
2013  */
2014 int spa_load_verify_maxinflight = 10000;
2015 boolean_t spa_load_verify_metadata = B_TRUE;
2016 boolean_t spa_load_verify_data = B_TRUE;
2017 
2018 /*ARGSUSED*/
2019 static int
2020 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2021     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2022 {
2023 	if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2024 		return (0);
2025 	/*
2026 	 * Note: normally this routine will not be called if
2027 	 * spa_load_verify_metadata is not set.  However, it may be useful
2028 	 * to manually set the flag after the traversal has begun.
2029 	 */
2030 	if (!spa_load_verify_metadata)
2031 		return (0);
2032 	if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2033 		return (0);
2034 
2035 	zio_t *rio = arg;
2036 	size_t size = BP_GET_PSIZE(bp);
2037 
2038 	mutex_enter(&spa->spa_scrub_lock);
2039 	while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
2040 		cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2041 	spa->spa_load_verify_ios++;
2042 	mutex_exit(&spa->spa_scrub_lock);
2043 
2044 	zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2045 	    spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2046 	    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2047 	    ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2048 	return (0);
2049 }
2050 
2051 /* ARGSUSED */
2052 int
2053 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2054 {
2055 	if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2056 		return (SET_ERROR(ENAMETOOLONG));
2057 
2058 	return (0);
2059 }
2060 
2061 static int
2062 spa_load_verify(spa_t *spa)
2063 {
2064 	zio_t *rio;
2065 	spa_load_error_t sle = { 0 };
2066 	zpool_load_policy_t policy;
2067 	boolean_t verify_ok = B_FALSE;
2068 	int error = 0;
2069 
2070 	zpool_get_load_policy(spa->spa_config, &policy);
2071 
2072 	if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2073 		return (0);
2074 
2075 	dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2076 	error = dmu_objset_find_dp(spa->spa_dsl_pool,
2077 	    spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2078 	    DS_FIND_CHILDREN);
2079 	dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2080 	if (error != 0)
2081 		return (error);
2082 
2083 	rio = zio_root(spa, NULL, &sle,
2084 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2085 
2086 	if (spa_load_verify_metadata) {
2087 		if (spa->spa_extreme_rewind) {
2088 			spa_load_note(spa, "performing a complete scan of the "
2089 			    "pool since extreme rewind is on. This may take "
2090 			    "a very long time.\n  (spa_load_verify_data=%u, "
2091 			    "spa_load_verify_metadata=%u)",
2092 			    spa_load_verify_data, spa_load_verify_metadata);
2093 		}
2094 		error = traverse_pool(spa, spa->spa_verify_min_txg,
2095 		    TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
2096 		    TRAVERSE_NO_DECRYPT, spa_load_verify_cb, rio);
2097 	}
2098 
2099 	(void) zio_wait(rio);
2100 
2101 	spa->spa_load_meta_errors = sle.sle_meta_count;
2102 	spa->spa_load_data_errors = sle.sle_data_count;
2103 
2104 	if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2105 		spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2106 		    "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2107 		    (u_longlong_t)sle.sle_data_count);
2108 	}
2109 
2110 	if (spa_load_verify_dryrun ||
2111 	    (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2112 	    sle.sle_data_count <= policy.zlp_maxdata)) {
2113 		int64_t loss = 0;
2114 
2115 		verify_ok = B_TRUE;
2116 		spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2117 		spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2118 
2119 		loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2120 		VERIFY(nvlist_add_uint64(spa->spa_load_info,
2121 		    ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2122 		VERIFY(nvlist_add_int64(spa->spa_load_info,
2123 		    ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2124 		VERIFY(nvlist_add_uint64(spa->spa_load_info,
2125 		    ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2126 	} else {
2127 		spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2128 	}
2129 
2130 	if (spa_load_verify_dryrun)
2131 		return (0);
2132 
2133 	if (error) {
2134 		if (error != ENXIO && error != EIO)
2135 			error = SET_ERROR(EIO);
2136 		return (error);
2137 	}
2138 
2139 	return (verify_ok ? 0 : EIO);
2140 }
2141 
2142 /*
2143  * Find a value in the pool props object.
2144  */
2145 static void
2146 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2147 {
2148 	(void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2149 	    zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2150 }
2151 
2152 /*
2153  * Find a value in the pool directory object.
2154  */
2155 static int
2156 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2157 {
2158 	int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2159 	    name, sizeof (uint64_t), 1, val);
2160 
2161 	if (error != 0 && (error != ENOENT || log_enoent)) {
2162 		spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2163 		    "[error=%d]", name, error);
2164 	}
2165 
2166 	return (error);
2167 }
2168 
2169 static int
2170 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2171 {
2172 	vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2173 	return (SET_ERROR(err));
2174 }
2175 
2176 static void
2177 spa_spawn_aux_threads(spa_t *spa)
2178 {
2179 	ASSERT(spa_writeable(spa));
2180 
2181 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
2182 
2183 	spa_start_indirect_condensing_thread(spa);
2184 
2185 	ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2186 	spa->spa_checkpoint_discard_zthr =
2187 	    zthr_create(spa_checkpoint_discard_thread_check,
2188 	    spa_checkpoint_discard_thread, spa);
2189 }
2190 
2191 /*
2192  * Fix up config after a partly-completed split.  This is done with the
2193  * ZPOOL_CONFIG_SPLIT nvlist.  Both the splitting pool and the split-off
2194  * pool have that entry in their config, but only the splitting one contains
2195  * a list of all the guids of the vdevs that are being split off.
2196  *
2197  * This function determines what to do with that list: either rejoin
2198  * all the disks to the pool, or complete the splitting process.  To attempt
2199  * the rejoin, each disk that is offlined is marked online again, and
2200  * we do a reopen() call.  If the vdev label for every disk that was
2201  * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2202  * then we call vdev_split() on each disk, and complete the split.
2203  *
2204  * Otherwise we leave the config alone, with all the vdevs in place in
2205  * the original pool.
2206  */
2207 static void
2208 spa_try_repair(spa_t *spa, nvlist_t *config)
2209 {
2210 	uint_t extracted;
2211 	uint64_t *glist;
2212 	uint_t i, gcount;
2213 	nvlist_t *nvl;
2214 	vdev_t **vd;
2215 	boolean_t attempt_reopen;
2216 
2217 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2218 		return;
2219 
2220 	/* check that the config is complete */
2221 	if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2222 	    &glist, &gcount) != 0)
2223 		return;
2224 
2225 	vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2226 
2227 	/* attempt to online all the vdevs & validate */
2228 	attempt_reopen = B_TRUE;
2229 	for (i = 0; i < gcount; i++) {
2230 		if (glist[i] == 0)	/* vdev is hole */
2231 			continue;
2232 
2233 		vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2234 		if (vd[i] == NULL) {
2235 			/*
2236 			 * Don't bother attempting to reopen the disks;
2237 			 * just do the split.
2238 			 */
2239 			attempt_reopen = B_FALSE;
2240 		} else {
2241 			/* attempt to re-online it */
2242 			vd[i]->vdev_offline = B_FALSE;
2243 		}
2244 	}
2245 
2246 	if (attempt_reopen) {
2247 		vdev_reopen(spa->spa_root_vdev);
2248 
2249 		/* check each device to see what state it's in */
2250 		for (extracted = 0, i = 0; i < gcount; i++) {
2251 			if (vd[i] != NULL &&
2252 			    vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2253 				break;
2254 			++extracted;
2255 		}
2256 	}
2257 
2258 	/*
2259 	 * If every disk has been moved to the new pool, or if we never
2260 	 * even attempted to look at them, then we split them off for
2261 	 * good.
2262 	 */
2263 	if (!attempt_reopen || gcount == extracted) {
2264 		for (i = 0; i < gcount; i++)
2265 			if (vd[i] != NULL)
2266 				vdev_split(vd[i]);
2267 		vdev_reopen(spa->spa_root_vdev);
2268 	}
2269 
2270 	kmem_free(vd, gcount * sizeof (vdev_t *));
2271 }
2272 
2273 static int
2274 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2275 {
2276 	char *ereport = FM_EREPORT_ZFS_POOL;
2277 	int error;
2278 
2279 	spa->spa_load_state = state;
2280 
2281 	gethrestime(&spa->spa_loaded_ts);
2282 	error = spa_load_impl(spa, type, &ereport);
2283 
2284 	/*
2285 	 * Don't count references from objsets that are already closed
2286 	 * and are making their way through the eviction process.
2287 	 */
2288 	spa_evicting_os_wait(spa);
2289 	spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
2290 	if (error) {
2291 		if (error != EEXIST) {
2292 			spa->spa_loaded_ts.tv_sec = 0;
2293 			spa->spa_loaded_ts.tv_nsec = 0;
2294 		}
2295 		if (error != EBADF) {
2296 			zfs_ereport_post(ereport, spa, NULL, NULL, NULL, 0, 0);
2297 		}
2298 	}
2299 	spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2300 	spa->spa_ena = 0;
2301 
2302 	return (error);
2303 }
2304 
2305 /*
2306  * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2307  * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2308  * spa's per-vdev ZAP list.
2309  */
2310 static uint64_t
2311 vdev_count_verify_zaps(vdev_t *vd)
2312 {
2313 	spa_t *spa = vd->vdev_spa;
2314 	uint64_t total = 0;
2315 	if (vd->vdev_top_zap != 0) {
2316 		total++;
2317 		ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2318 		    spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2319 	}
2320 	if (vd->vdev_leaf_zap != 0) {
2321 		total++;
2322 		ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2323 		    spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2324 	}
2325 
2326 	for (uint64_t i = 0; i < vd->vdev_children; i++) {
2327 		total += vdev_count_verify_zaps(vd->vdev_child[i]);
2328 	}
2329 
2330 	return (total);
2331 }
2332 
2333 /*
2334  * Determine whether the activity check is required.
2335  */
2336 static boolean_t
2337 spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
2338     nvlist_t *config)
2339 {
2340 	uint64_t state = 0;
2341 	uint64_t hostid = 0;
2342 	uint64_t tryconfig_txg = 0;
2343 	uint64_t tryconfig_timestamp = 0;
2344 	nvlist_t *nvinfo;
2345 
2346 	if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2347 		nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2348 		(void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
2349 		    &tryconfig_txg);
2350 		(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2351 		    &tryconfig_timestamp);
2352 	}
2353 
2354 	(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
2355 
2356 	/*
2357 	 * Disable the MMP activity check - This is used by zdb which
2358 	 * is intended to be used on potentially active pools.
2359 	 */
2360 	if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
2361 		return (B_FALSE);
2362 
2363 	/*
2364 	 * Skip the activity check when the MMP feature is disabled.
2365 	 */
2366 	if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
2367 		return (B_FALSE);
2368 	/*
2369 	 * If the tryconfig_* values are nonzero, they are the results of an
2370 	 * earlier tryimport.  If they match the uberblock we just found, then
2371 	 * the pool has not changed and we return false so we do not test a
2372 	 * second time.
2373 	 */
2374 	if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
2375 	    tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp)
2376 		return (B_FALSE);
2377 
2378 	/*
2379 	 * Allow the activity check to be skipped when importing the pool
2380 	 * on the same host which last imported it.  Since the hostid from
2381 	 * configuration may be stale use the one read from the label.
2382 	 */
2383 	if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
2384 		hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
2385 
2386 	if (hostid == spa_get_hostid())
2387 		return (B_FALSE);
2388 
2389 	/*
2390 	 * Skip the activity test when the pool was cleanly exported.
2391 	 */
2392 	if (state != POOL_STATE_ACTIVE)
2393 		return (B_FALSE);
2394 
2395 	return (B_TRUE);
2396 }
2397 
2398 /*
2399  * Perform the import activity check.  If the user canceled the import or
2400  * we detected activity then fail.
2401  */
2402 static int
2403 spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
2404 {
2405 	uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
2406 	uint64_t txg = ub->ub_txg;
2407 	uint64_t timestamp = ub->ub_timestamp;
2408 	uint64_t import_delay = NANOSEC;
2409 	hrtime_t import_expire;
2410 	nvlist_t *mmp_label = NULL;
2411 	vdev_t *rvd = spa->spa_root_vdev;
2412 	kcondvar_t cv;
2413 	kmutex_t mtx;
2414 	int error = 0;
2415 
2416 	cv_init(&cv, NULL, CV_DEFAULT, NULL);
2417 	mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
2418 	mutex_enter(&mtx);
2419 
2420 	/*
2421 	 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
2422 	 * during the earlier tryimport.  If the txg recorded there is 0 then
2423 	 * the pool is known to be active on another host.
2424 	 *
2425 	 * Otherwise, the pool might be in use on another node.  Check for
2426 	 * changes in the uberblocks on disk if necessary.
2427 	 */
2428 	if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2429 		nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
2430 		    ZPOOL_CONFIG_LOAD_INFO);
2431 
2432 		if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
2433 		    fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
2434 			vdev_uberblock_load(rvd, ub, &mmp_label);
2435 			error = SET_ERROR(EREMOTEIO);
2436 			goto out;
2437 		}
2438 	}
2439 
2440 	/*
2441 	 * Preferentially use the zfs_multihost_interval from the node which
2442 	 * last imported the pool.  This value is stored in an MMP uberblock as.
2443 	 *
2444 	 * ub_mmp_delay * vdev_count_leaves() == zfs_multihost_interval
2445 	 */
2446 	if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay)
2447 		import_delay = MAX(import_delay, import_intervals *
2448 		    ub->ub_mmp_delay * MAX(vdev_count_leaves(spa), 1));
2449 
2450 	/* Apply a floor using the local default values. */
2451 	import_delay = MAX(import_delay, import_intervals *
2452 	    MSEC2NSEC(MAX(zfs_multihost_interval, MMP_MIN_INTERVAL)));
2453 
2454 	zfs_dbgmsg("import_delay=%llu ub_mmp_delay=%llu import_intervals=%u "
2455 	    "leaves=%u", import_delay, ub->ub_mmp_delay, import_intervals,
2456 	    vdev_count_leaves(spa));
2457 
2458 	/* Add a small random factor in case of simultaneous imports (0-25%) */
2459 	import_expire = gethrtime() + import_delay +
2460 	    (import_delay * spa_get_random(250) / 1000);
2461 
2462 	while (gethrtime() < import_expire) {
2463 		vdev_uberblock_load(rvd, ub, &mmp_label);
2464 
2465 		if (txg != ub->ub_txg || timestamp != ub->ub_timestamp) {
2466 			error = SET_ERROR(EREMOTEIO);
2467 			break;
2468 		}
2469 
2470 		if (mmp_label) {
2471 			nvlist_free(mmp_label);
2472 			mmp_label = NULL;
2473 		}
2474 
2475 		error = cv_timedwait_sig(&cv, &mtx, ddi_get_lbolt() + hz);
2476 		if (error != -1) {
2477 			error = SET_ERROR(EINTR);
2478 			break;
2479 		}
2480 		error = 0;
2481 	}
2482 
2483 out:
2484 	mutex_exit(&mtx);
2485 	mutex_destroy(&mtx);
2486 	cv_destroy(&cv);
2487 
2488 	/*
2489 	 * If the pool is determined to be active store the status in the
2490 	 * spa->spa_load_info nvlist.  If the remote hostname or hostid are
2491 	 * available from configuration read from disk store them as well.
2492 	 * This allows 'zpool import' to generate a more useful message.
2493 	 *
2494 	 * ZPOOL_CONFIG_MMP_STATE    - observed pool status (mandatory)
2495 	 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
2496 	 * ZPOOL_CONFIG_MMP_HOSTID   - hostid from the active pool
2497 	 */
2498 	if (error == EREMOTEIO) {
2499 		char *hostname = "<unknown>";
2500 		uint64_t hostid = 0;
2501 
2502 		if (mmp_label) {
2503 			if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
2504 				hostname = fnvlist_lookup_string(mmp_label,
2505 				    ZPOOL_CONFIG_HOSTNAME);
2506 				fnvlist_add_string(spa->spa_load_info,
2507 				    ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
2508 			}
2509 
2510 			if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
2511 				hostid = fnvlist_lookup_uint64(mmp_label,
2512 				    ZPOOL_CONFIG_HOSTID);
2513 				fnvlist_add_uint64(spa->spa_load_info,
2514 				    ZPOOL_CONFIG_MMP_HOSTID, hostid);
2515 			}
2516 		}
2517 
2518 		fnvlist_add_uint64(spa->spa_load_info,
2519 		    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
2520 		fnvlist_add_uint64(spa->spa_load_info,
2521 		    ZPOOL_CONFIG_MMP_TXG, 0);
2522 
2523 		error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
2524 	}
2525 
2526 	if (mmp_label)
2527 		nvlist_free(mmp_label);
2528 
2529 	return (error);
2530 }
2531 
2532 static int
2533 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2534 {
2535 	uint64_t hostid;
2536 	char *hostname;
2537 	uint64_t myhostid = 0;
2538 
2539 	if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2540 	    ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2541 		hostname = fnvlist_lookup_string(mos_config,
2542 		    ZPOOL_CONFIG_HOSTNAME);
2543 
2544 		myhostid = zone_get_hostid(NULL);
2545 
2546 		if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2547 			cmn_err(CE_WARN, "pool '%s' could not be "
2548 			    "loaded as it was last accessed by "
2549 			    "another system (host: %s hostid: 0x%llx). "
2550 			    "See: http://illumos.org/msg/ZFS-8000-EY",
2551 			    spa_name(spa), hostname, (u_longlong_t)hostid);
2552 			spa_load_failed(spa, "hostid verification failed: pool "
2553 			    "last accessed by host: %s (hostid: 0x%llx)",
2554 			    hostname, (u_longlong_t)hostid);
2555 			return (SET_ERROR(EBADF));
2556 		}
2557 	}
2558 
2559 	return (0);
2560 }
2561 
2562 static int
2563 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2564 {
2565 	int error = 0;
2566 	nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2567 	int parse;
2568 	vdev_t *rvd;
2569 	uint64_t pool_guid;
2570 	char *comment;
2571 
2572 	/*
2573 	 * Versioning wasn't explicitly added to the label until later, so if
2574 	 * it's not present treat it as the initial version.
2575 	 */
2576 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2577 	    &spa->spa_ubsync.ub_version) != 0)
2578 		spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2579 
2580 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2581 		spa_load_failed(spa, "invalid config provided: '%s' missing",
2582 		    ZPOOL_CONFIG_POOL_GUID);
2583 		return (SET_ERROR(EINVAL));
2584 	}
2585 
2586 	/*
2587 	 * If we are doing an import, ensure that the pool is not already
2588 	 * imported by checking if its pool guid already exists in the
2589 	 * spa namespace.
2590 	 *
2591 	 * The only case that we allow an already imported pool to be
2592 	 * imported again, is when the pool is checkpointed and we want to
2593 	 * look at its checkpointed state from userland tools like zdb.
2594 	 */
2595 #ifdef _KERNEL
2596 	if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2597 	    spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2598 	    spa_guid_exists(pool_guid, 0)) {
2599 #else
2600 	if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2601 	    spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2602 	    spa_guid_exists(pool_guid, 0) &&
2603 	    !spa_importing_readonly_checkpoint(spa)) {
2604 #endif
2605 		spa_load_failed(spa, "a pool with guid %llu is already open",
2606 		    (u_longlong_t)pool_guid);
2607 		return (SET_ERROR(EEXIST));
2608 	}
2609 
2610 	spa->spa_config_guid = pool_guid;
2611 
2612 	nvlist_free(spa->spa_load_info);
2613 	spa->spa_load_info = fnvlist_alloc();
2614 
2615 	ASSERT(spa->spa_comment == NULL);
2616 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2617 		spa->spa_comment = spa_strdup(comment);
2618 
2619 	(void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2620 	    &spa->spa_config_txg);
2621 
2622 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2623 		spa->spa_config_splitting = fnvlist_dup(nvl);
2624 
2625 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2626 		spa_load_failed(spa, "invalid config provided: '%s' missing",
2627 		    ZPOOL_CONFIG_VDEV_TREE);
2628 		return (SET_ERROR(EINVAL));
2629 	}
2630 
2631 	/*
2632 	 * Create "The Godfather" zio to hold all async IOs
2633 	 */
2634 	spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2635 	    KM_SLEEP);
2636 	for (int i = 0; i < max_ncpus; i++) {
2637 		spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2638 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2639 		    ZIO_FLAG_GODFATHER);
2640 	}
2641 
2642 	/*
2643 	 * Parse the configuration into a vdev tree.  We explicitly set the
2644 	 * value that will be returned by spa_version() since parsing the
2645 	 * configuration requires knowing the version number.
2646 	 */
2647 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2648 	parse = (type == SPA_IMPORT_EXISTING ?
2649 	    VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2650 	error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2651 	spa_config_exit(spa, SCL_ALL, FTAG);
2652 
2653 	if (error != 0) {
2654 		spa_load_failed(spa, "unable to parse config [error=%d]",
2655 		    error);
2656 		return (error);
2657 	}
2658 
2659 	ASSERT(spa->spa_root_vdev == rvd);
2660 	ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2661 	ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2662 
2663 	if (type != SPA_IMPORT_ASSEMBLE) {
2664 		ASSERT(spa_guid(spa) == pool_guid);
2665 	}
2666 
2667 	return (0);
2668 }
2669 
2670 /*
2671  * Recursively open all vdevs in the vdev tree. This function is called twice:
2672  * first with the untrusted config, then with the trusted config.
2673  */
2674 static int
2675 spa_ld_open_vdevs(spa_t *spa)
2676 {
2677 	int error = 0;
2678 
2679 	/*
2680 	 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2681 	 * missing/unopenable for the root vdev to be still considered openable.
2682 	 */
2683 	if (spa->spa_trust_config) {
2684 		spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2685 	} else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2686 		spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2687 	} else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2688 		spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2689 	} else {
2690 		spa->spa_missing_tvds_allowed = 0;
2691 	}
2692 
2693 	spa->spa_missing_tvds_allowed =
2694 	    MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2695 
2696 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2697 	error = vdev_open(spa->spa_root_vdev);
2698 	spa_config_exit(spa, SCL_ALL, FTAG);
2699 
2700 	if (spa->spa_missing_tvds != 0) {
2701 		spa_load_note(spa, "vdev tree has %lld missing top-level "
2702 		    "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2703 		if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2704 			/*
2705 			 * Although theoretically we could allow users to open
2706 			 * incomplete pools in RW mode, we'd need to add a lot
2707 			 * of extra logic (e.g. adjust pool space to account
2708 			 * for missing vdevs).
2709 			 * This limitation also prevents users from accidentally
2710 			 * opening the pool in RW mode during data recovery and
2711 			 * damaging it further.
2712 			 */
2713 			spa_load_note(spa, "pools with missing top-level "
2714 			    "vdevs can only be opened in read-only mode.");
2715 			error = SET_ERROR(ENXIO);
2716 		} else {
2717 			spa_load_note(spa, "current settings allow for maximum "
2718 			    "%lld missing top-level vdevs at this stage.",
2719 			    (u_longlong_t)spa->spa_missing_tvds_allowed);
2720 		}
2721 	}
2722 	if (error != 0) {
2723 		spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2724 		    error);
2725 	}
2726 	if (spa->spa_missing_tvds != 0 || error != 0)
2727 		vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2728 
2729 	return (error);
2730 }
2731 
2732 /*
2733  * We need to validate the vdev labels against the configuration that
2734  * we have in hand. This function is called twice: first with an untrusted
2735  * config, then with a trusted config. The validation is more strict when the
2736  * config is trusted.
2737  */
2738 static int
2739 spa_ld_validate_vdevs(spa_t *spa)
2740 {
2741 	int error = 0;
2742 	vdev_t *rvd = spa->spa_root_vdev;
2743 
2744 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2745 	error = vdev_validate(rvd);
2746 	spa_config_exit(spa, SCL_ALL, FTAG);
2747 
2748 	if (error != 0) {
2749 		spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2750 		return (error);
2751 	}
2752 
2753 	if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2754 		spa_load_failed(spa, "cannot open vdev tree after invalidating "
2755 		    "some vdevs");
2756 		vdev_dbgmsg_print_tree(rvd, 2);
2757 		return (SET_ERROR(ENXIO));
2758 	}
2759 
2760 	return (0);
2761 }
2762 
2763 static void
2764 spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2765 {
2766 	spa->spa_state = POOL_STATE_ACTIVE;
2767 	spa->spa_ubsync = spa->spa_uberblock;
2768 	spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2769 	    TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2770 	spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2771 	    spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2772 	spa->spa_claim_max_txg = spa->spa_first_txg;
2773 	spa->spa_prev_software_version = ub->ub_software_version;
2774 }
2775 
2776 static int
2777 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2778 {
2779 	vdev_t *rvd = spa->spa_root_vdev;
2780 	nvlist_t *label;
2781 	uberblock_t *ub = &spa->spa_uberblock;
2782 	boolean_t activity_check = B_FALSE;
2783 
2784 	/*
2785 	 * If we are opening the checkpointed state of the pool by
2786 	 * rewinding to it, at this point we will have written the
2787 	 * checkpointed uberblock to the vdev labels, so searching
2788 	 * the labels will find the right uberblock.  However, if
2789 	 * we are opening the checkpointed state read-only, we have
2790 	 * not modified the labels. Therefore, we must ignore the
2791 	 * labels and continue using the spa_uberblock that was set
2792 	 * by spa_ld_checkpoint_rewind.
2793 	 *
2794 	 * Note that it would be fine to ignore the labels when
2795 	 * rewinding (opening writeable) as well. However, if we
2796 	 * crash just after writing the labels, we will end up
2797 	 * searching the labels. Doing so in the common case means
2798 	 * that this code path gets exercised normally, rather than
2799 	 * just in the edge case.
2800 	 */
2801 	if (ub->ub_checkpoint_txg != 0 &&
2802 	    spa_importing_readonly_checkpoint(spa)) {
2803 		spa_ld_select_uberblock_done(spa, ub);
2804 		return (0);
2805 	}
2806 
2807 	/*
2808 	 * Find the best uberblock.
2809 	 */
2810 	vdev_uberblock_load(rvd, ub, &label);
2811 
2812 	/*
2813 	 * If we weren't able to find a single valid uberblock, return failure.
2814 	 */
2815 	if (ub->ub_txg == 0) {
2816 		nvlist_free(label);
2817 		spa_load_failed(spa, "no valid uberblock found");
2818 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2819 	}
2820 
2821 	spa_load_note(spa, "using uberblock with txg=%llu",
2822 	    (u_longlong_t)ub->ub_txg);
2823 
2824 	/*
2825 	 * For pools which have the multihost property on determine if the
2826 	 * pool is truly inactive and can be safely imported.  Prevent
2827 	 * hosts which don't have a hostid set from importing the pool.
2828 	 */
2829 	activity_check = spa_activity_check_required(spa, ub, label,
2830 	    spa->spa_config);
2831 	if (activity_check) {
2832 		if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
2833 		    spa_get_hostid() == 0) {
2834 			nvlist_free(label);
2835 			fnvlist_add_uint64(spa->spa_load_info,
2836 			    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
2837 			return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
2838 		}
2839 
2840 		int error = spa_activity_check(spa, ub, spa->spa_config);
2841 		if (error) {
2842 			nvlist_free(label);
2843 			return (error);
2844 		}
2845 
2846 		fnvlist_add_uint64(spa->spa_load_info,
2847 		    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
2848 		fnvlist_add_uint64(spa->spa_load_info,
2849 		    ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
2850 	}
2851 
2852 	/*
2853 	 * If the pool has an unsupported version we can't open it.
2854 	 */
2855 	if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2856 		nvlist_free(label);
2857 		spa_load_failed(spa, "version %llu is not supported",
2858 		    (u_longlong_t)ub->ub_version);
2859 		return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2860 	}
2861 
2862 	if (ub->ub_version >= SPA_VERSION_FEATURES) {
2863 		nvlist_t *features;
2864 
2865 		/*
2866 		 * If we weren't able to find what's necessary for reading the
2867 		 * MOS in the label, return failure.
2868 		 */
2869 		if (label == NULL) {
2870 			spa_load_failed(spa, "label config unavailable");
2871 			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2872 			    ENXIO));
2873 		}
2874 
2875 		if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
2876 		    &features) != 0) {
2877 			nvlist_free(label);
2878 			spa_load_failed(spa, "invalid label: '%s' missing",
2879 			    ZPOOL_CONFIG_FEATURES_FOR_READ);
2880 			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2881 			    ENXIO));
2882 		}
2883 
2884 		/*
2885 		 * Update our in-core representation with the definitive values
2886 		 * from the label.
2887 		 */
2888 		nvlist_free(spa->spa_label_features);
2889 		VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2890 	}
2891 
2892 	nvlist_free(label);
2893 
2894 	/*
2895 	 * Look through entries in the label nvlist's features_for_read. If
2896 	 * there is a feature listed there which we don't understand then we
2897 	 * cannot open a pool.
2898 	 */
2899 	if (ub->ub_version >= SPA_VERSION_FEATURES) {
2900 		nvlist_t *unsup_feat;
2901 
2902 		VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2903 		    0);
2904 
2905 		for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2906 		    NULL); nvp != NULL;
2907 		    nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2908 			if (!zfeature_is_supported(nvpair_name(nvp))) {
2909 				VERIFY(nvlist_add_string(unsup_feat,
2910 				    nvpair_name(nvp), "") == 0);
2911 			}
2912 		}
2913 
2914 		if (!nvlist_empty(unsup_feat)) {
2915 			VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2916 			    ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2917 			nvlist_free(unsup_feat);
2918 			spa_load_failed(spa, "some features are unsupported");
2919 			return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2920 			    ENOTSUP));
2921 		}
2922 
2923 		nvlist_free(unsup_feat);
2924 	}
2925 
2926 	if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2927 		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2928 		spa_try_repair(spa, spa->spa_config);
2929 		spa_config_exit(spa, SCL_ALL, FTAG);
2930 		nvlist_free(spa->spa_config_splitting);
2931 		spa->spa_config_splitting = NULL;
2932 	}
2933 
2934 	/*
2935 	 * Initialize internal SPA structures.
2936 	 */
2937 	spa_ld_select_uberblock_done(spa, ub);
2938 
2939 	return (0);
2940 }
2941 
2942 static int
2943 spa_ld_open_rootbp(spa_t *spa)
2944 {
2945 	int error = 0;
2946 	vdev_t *rvd = spa->spa_root_vdev;
2947 
2948 	error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2949 	if (error != 0) {
2950 		spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
2951 		    "[error=%d]", error);
2952 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2953 	}
2954 	spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2955 
2956 	return (0);
2957 }
2958 
2959 static int
2960 spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
2961     boolean_t reloading)
2962 {
2963 	vdev_t *mrvd, *rvd = spa->spa_root_vdev;
2964 	nvlist_t *nv, *mos_config, *policy;
2965 	int error = 0, copy_error;
2966 	uint64_t healthy_tvds, healthy_tvds_mos;
2967 	uint64_t mos_config_txg;
2968 
2969 	if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
2970 	    != 0)
2971 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2972 
2973 	/*
2974 	 * If we're assembling a pool from a split, the config provided is
2975 	 * already trusted so there is nothing to do.
2976 	 */
2977 	if (type == SPA_IMPORT_ASSEMBLE)
2978 		return (0);
2979 
2980 	healthy_tvds = spa_healthy_core_tvds(spa);
2981 
2982 	if (load_nvlist(spa, spa->spa_config_object, &mos_config)
2983 	    != 0) {
2984 		spa_load_failed(spa, "unable to retrieve MOS config");
2985 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2986 	}
2987 
2988 	/*
2989 	 * If we are doing an open, pool owner wasn't verified yet, thus do
2990 	 * the verification here.
2991 	 */
2992 	if (spa->spa_load_state == SPA_LOAD_OPEN) {
2993 		error = spa_verify_host(spa, mos_config);
2994 		if (error != 0) {
2995 			nvlist_free(mos_config);
2996 			return (error);
2997 		}
2998 	}
2999 
3000 	nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
3001 
3002 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3003 
3004 	/*
3005 	 * Build a new vdev tree from the trusted config
3006 	 */
3007 	VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
3008 
3009 	/*
3010 	 * Vdev paths in the MOS may be obsolete. If the untrusted config was
3011 	 * obtained by scanning /dev/dsk, then it will have the right vdev
3012 	 * paths. We update the trusted MOS config with this information.
3013 	 * We first try to copy the paths with vdev_copy_path_strict, which
3014 	 * succeeds only when both configs have exactly the same vdev tree.
3015 	 * If that fails, we fall back to a more flexible method that has a
3016 	 * best effort policy.
3017 	 */
3018 	copy_error = vdev_copy_path_strict(rvd, mrvd);
3019 	if (copy_error != 0 || spa_load_print_vdev_tree) {
3020 		spa_load_note(spa, "provided vdev tree:");
3021 		vdev_dbgmsg_print_tree(rvd, 2);
3022 		spa_load_note(spa, "MOS vdev tree:");
3023 		vdev_dbgmsg_print_tree(mrvd, 2);
3024 	}
3025 	if (copy_error != 0) {
3026 		spa_load_note(spa, "vdev_copy_path_strict failed, falling "
3027 		    "back to vdev_copy_path_relaxed");
3028 		vdev_copy_path_relaxed(rvd, mrvd);
3029 	}
3030 
3031 	vdev_close(rvd);
3032 	vdev_free(rvd);
3033 	spa->spa_root_vdev = mrvd;
3034 	rvd = mrvd;
3035 	spa_config_exit(spa, SCL_ALL, FTAG);
3036 
3037 	/*
3038 	 * We will use spa_config if we decide to reload the spa or if spa_load
3039 	 * fails and we rewind. We must thus regenerate the config using the
3040 	 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
3041 	 * pass settings on how to load the pool and is not stored in the MOS.
3042 	 * We copy it over to our new, trusted config.
3043 	 */
3044 	mos_config_txg = fnvlist_lookup_uint64(mos_config,
3045 	    ZPOOL_CONFIG_POOL_TXG);
3046 	nvlist_free(mos_config);
3047 	mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
3048 	if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
3049 	    &policy) == 0)
3050 		fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
3051 	spa_config_set(spa, mos_config);
3052 	spa->spa_config_source = SPA_CONFIG_SRC_MOS;
3053 
3054 	/*
3055 	 * Now that we got the config from the MOS, we should be more strict
3056 	 * in checking blkptrs and can make assumptions about the consistency
3057 	 * of the vdev tree. spa_trust_config must be set to true before opening
3058 	 * vdevs in order for them to be writeable.
3059 	 */
3060 	spa->spa_trust_config = B_TRUE;
3061 
3062 	/*
3063 	 * Open and validate the new vdev tree
3064 	 */
3065 	error = spa_ld_open_vdevs(spa);
3066 	if (error != 0)
3067 		return (error);
3068 
3069 	error = spa_ld_validate_vdevs(spa);
3070 	if (error != 0)
3071 		return (error);
3072 
3073 	if (copy_error != 0 || spa_load_print_vdev_tree) {
3074 		spa_load_note(spa, "final vdev tree:");
3075 		vdev_dbgmsg_print_tree(rvd, 2);
3076 	}
3077 
3078 	if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
3079 	    !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
3080 		/*
3081 		 * Sanity check to make sure that we are indeed loading the
3082 		 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
3083 		 * in the config provided and they happened to be the only ones
3084 		 * to have the latest uberblock, we could involuntarily perform
3085 		 * an extreme rewind.
3086 		 */
3087 		healthy_tvds_mos = spa_healthy_core_tvds(spa);
3088 		if (healthy_tvds_mos - healthy_tvds >=
3089 		    SPA_SYNC_MIN_VDEVS) {
3090 			spa_load_note(spa, "config provided misses too many "
3091 			    "top-level vdevs compared to MOS (%lld vs %lld). ",
3092 			    (u_longlong_t)healthy_tvds,
3093 			    (u_longlong_t)healthy_tvds_mos);
3094 			spa_load_note(spa, "vdev tree:");
3095 			vdev_dbgmsg_print_tree(rvd, 2);
3096 			if (reloading) {
3097 				spa_load_failed(spa, "config was already "
3098 				    "provided from MOS. Aborting.");
3099 				return (spa_vdev_err(rvd,
3100 				    VDEV_AUX_CORRUPT_DATA, EIO));
3101 			}
3102 			spa_load_note(spa, "spa must be reloaded using MOS "
3103 			    "config");
3104 			return (SET_ERROR(EAGAIN));
3105 		}
3106 	}
3107 
3108 	error = spa_check_for_missing_logs(spa);
3109 	if (error != 0)
3110 		return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
3111 
3112 	if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
3113 		spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
3114 		    "guid sum (%llu != %llu)",
3115 		    (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
3116 		    (u_longlong_t)rvd->vdev_guid_sum);
3117 		return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
3118 		    ENXIO));
3119 	}
3120 
3121 	return (0);
3122 }
3123 
3124 static int
3125 spa_ld_open_indirect_vdev_metadata(spa_t *spa)
3126 {
3127 	int error = 0;
3128 	vdev_t *rvd = spa->spa_root_vdev;
3129 
3130 	/*
3131 	 * Everything that we read before spa_remove_init() must be stored
3132 	 * on concreted vdevs.  Therefore we do this as early as possible.
3133 	 */
3134 	error = spa_remove_init(spa);
3135 	if (error != 0) {
3136 		spa_load_failed(spa, "spa_remove_init failed [error=%d]",
3137 		    error);
3138 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3139 	}
3140 
3141 	/*
3142 	 * Retrieve information needed to condense indirect vdev mappings.
3143 	 */
3144 	error = spa_condense_init(spa);
3145 	if (error != 0) {
3146 		spa_load_failed(spa, "spa_condense_init failed [error=%d]",
3147 		    error);
3148 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3149 	}
3150 
3151 	return (0);
3152 }
3153 
3154 static int
3155 spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
3156 {
3157 	int error = 0;
3158 	vdev_t *rvd = spa->spa_root_vdev;
3159 
3160 	if (spa_version(spa) >= SPA_VERSION_FEATURES) {
3161 		boolean_t missing_feat_read = B_FALSE;
3162 		nvlist_t *unsup_feat, *enabled_feat;
3163 
3164 		if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
3165 		    &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
3166 			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3167 		}
3168 
3169 		if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
3170 		    &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
3171 			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3172 		}
3173 
3174 		if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
3175 		    &spa->spa_feat_desc_obj, B_TRUE) != 0) {
3176 			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3177 		}
3178 
3179 		enabled_feat = fnvlist_alloc();
3180 		unsup_feat = fnvlist_alloc();
3181 
3182 		if (!spa_features_check(spa, B_FALSE,
3183 		    unsup_feat, enabled_feat))
3184 			missing_feat_read = B_TRUE;
3185 
3186 		if (spa_writeable(spa) ||
3187 		    spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3188 			if (!spa_features_check(spa, B_TRUE,
3189 			    unsup_feat, enabled_feat)) {
3190 				*missing_feat_writep = B_TRUE;
3191 			}
3192 		}
3193 
3194 		fnvlist_add_nvlist(spa->spa_load_info,
3195 		    ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3196 
3197 		if (!nvlist_empty(unsup_feat)) {
3198 			fnvlist_add_nvlist(spa->spa_load_info,
3199 			    ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3200 		}
3201 
3202 		fnvlist_free(enabled_feat);
3203 		fnvlist_free(unsup_feat);
3204 
3205 		if (!missing_feat_read) {
3206 			fnvlist_add_boolean(spa->spa_load_info,
3207 			    ZPOOL_CONFIG_CAN_RDONLY);
3208 		}
3209 
3210 		/*
3211 		 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3212 		 * twofold: to determine whether the pool is available for
3213 		 * import in read-write mode and (if it is not) whether the
3214 		 * pool is available for import in read-only mode. If the pool
3215 		 * is available for import in read-write mode, it is displayed
3216 		 * as available in userland; if it is not available for import
3217 		 * in read-only mode, it is displayed as unavailable in
3218 		 * userland. If the pool is available for import in read-only
3219 		 * mode but not read-write mode, it is displayed as unavailable
3220 		 * in userland with a special note that the pool is actually
3221 		 * available for open in read-only mode.
3222 		 *
3223 		 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3224 		 * missing a feature for write, we must first determine whether
3225 		 * the pool can be opened read-only before returning to
3226 		 * userland in order to know whether to display the
3227 		 * abovementioned note.
3228 		 */
3229 		if (missing_feat_read || (*missing_feat_writep &&
3230 		    spa_writeable(spa))) {
3231 			spa_load_failed(spa, "pool uses unsupported features");
3232 			return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3233 			    ENOTSUP));
3234 		}
3235 
3236 		/*
3237 		 * Load refcounts for ZFS features from disk into an in-memory
3238 		 * cache during SPA initialization.
3239 		 */
3240 		for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
3241 			uint64_t refcount;
3242 
3243 			error = feature_get_refcount_from_disk(spa,
3244 			    &spa_feature_table[i], &refcount);
3245 			if (error == 0) {
3246 				spa->spa_feat_refcount_cache[i] = refcount;
3247 			} else if (error == ENOTSUP) {
3248 				spa->spa_feat_refcount_cache[i] =
3249 				    SPA_FEATURE_DISABLED;
3250 			} else {
3251 				spa_load_failed(spa, "error getting refcount "
3252 				    "for feature %s [error=%d]",
3253 				    spa_feature_table[i].fi_guid, error);
3254 				return (spa_vdev_err(rvd,
3255 				    VDEV_AUX_CORRUPT_DATA, EIO));
3256 			}
3257 		}
3258 	}
3259 
3260 	if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3261 		if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
3262 		    &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
3263 			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3264 	}
3265 
3266 	/*
3267 	 * Encryption was added before bookmark_v2, even though bookmark_v2
3268 	 * is now a dependency. If this pool has encryption enabled without
3269 	 * bookmark_v2, trigger an errata message.
3270 	 */
3271 	if (spa_feature_is_enabled(spa, SPA_FEATURE_ENCRYPTION) &&
3272 	    !spa_feature_is_enabled(spa, SPA_FEATURE_BOOKMARK_V2)) {
3273 		spa->spa_errata = ZPOOL_ERRATA_ZOL_8308_ENCRYPTION;
3274 	}
3275 
3276 	return (0);
3277 }
3278 
3279 static int
3280 spa_ld_load_special_directories(spa_t *spa)
3281 {
3282 	int error = 0;
3283 	vdev_t *rvd = spa->spa_root_vdev;
3284 
3285 	spa->spa_is_initializing = B_TRUE;
3286 	error = dsl_pool_open(spa->spa_dsl_pool);
3287 	spa->spa_is_initializing = B_FALSE;
3288 	if (error != 0) {
3289 		spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3290 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3291 	}
3292 
3293 	return (0);
3294 }
3295 
3296 static int
3297 spa_ld_get_props(spa_t *spa)
3298 {
3299 	int error = 0;
3300 	uint64_t obj;
3301 	vdev_t *rvd = spa->spa_root_vdev;
3302 
3303 	/* Grab the secret checksum salt from the MOS. */
3304 	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3305 	    DMU_POOL_CHECKSUM_SALT, 1,
3306 	    sizeof (spa->spa_cksum_salt.zcs_bytes),
3307 	    spa->spa_cksum_salt.zcs_bytes);
3308 	if (error == ENOENT) {
3309 		/* Generate a new salt for subsequent use */
3310 		(void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3311 		    sizeof (spa->spa_cksum_salt.zcs_bytes));
3312 	} else if (error != 0) {
3313 		spa_load_failed(spa, "unable to retrieve checksum salt from "
3314 		    "MOS [error=%d]", error);
3315 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3316 	}
3317 
3318 	if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3319 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3320 	error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3321 	if (error != 0) {
3322 		spa_load_failed(spa, "error opening deferred-frees bpobj "
3323 		    "[error=%d]", error);
3324 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3325 	}
3326 
3327 	/*
3328 	 * Load the bit that tells us to use the new accounting function
3329 	 * (raid-z deflation).  If we have an older pool, this will not
3330 	 * be present.
3331 	 */
3332 	error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3333 	if (error != 0 && error != ENOENT)
3334 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3335 
3336 	error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3337 	    &spa->spa_creation_version, B_FALSE);
3338 	if (error != 0 && error != ENOENT)
3339 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3340 
3341 	/*
3342 	 * Load the persistent error log.  If we have an older pool, this will
3343 	 * not be present.
3344 	 */
3345 	error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3346 	    B_FALSE);
3347 	if (error != 0 && error != ENOENT)
3348 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3349 
3350 	error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3351 	    &spa->spa_errlog_scrub, B_FALSE);
3352 	if (error != 0 && error != ENOENT)
3353 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3354 
3355 	/*
3356 	 * Load the history object.  If we have an older pool, this
3357 	 * will not be present.
3358 	 */
3359 	error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3360 	if (error != 0 && error != ENOENT)
3361 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3362 
3363 	/*
3364 	 * Load the per-vdev ZAP map. If we have an older pool, this will not
3365 	 * be present; in this case, defer its creation to a later time to
3366 	 * avoid dirtying the MOS this early / out of sync context. See
3367 	 * spa_sync_config_object.
3368 	 */
3369 
3370 	/* The sentinel is only available in the MOS config. */
3371 	nvlist_t *mos_config;
3372 	if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3373 		spa_load_failed(spa, "unable to retrieve MOS config");
3374 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3375 	}
3376 
3377 	error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3378 	    &spa->spa_all_vdev_zaps, B_FALSE);
3379 
3380 	if (error == ENOENT) {
3381 		VERIFY(!nvlist_exists(mos_config,
3382 		    ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3383 		spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3384 		ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3385 	} else if (error != 0) {
3386 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3387 	} else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3388 		/*
3389 		 * An older version of ZFS overwrote the sentinel value, so
3390 		 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3391 		 * destruction to later; see spa_sync_config_object.
3392 		 */
3393 		spa->spa_avz_action = AVZ_ACTION_DESTROY;
3394 		/*
3395 		 * We're assuming that no vdevs have had their ZAPs created
3396 		 * before this. Better be sure of it.
3397 		 */
3398 		ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3399 	}
3400 	nvlist_free(mos_config);
3401 
3402 	spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3403 
3404 	error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3405 	    B_FALSE);
3406 	if (error && error != ENOENT)
3407 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3408 
3409 	if (error == 0) {
3410 		uint64_t autoreplace;
3411 
3412 		spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3413 		spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3414 		spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3415 		spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3416 		spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3417 		spa_prop_find(spa, ZPOOL_PROP_MULTIHOST, &spa->spa_multihost);
3418 		spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3419 		    &spa->spa_dedup_ditto);
3420 
3421 		spa->spa_autoreplace = (autoreplace != 0);
3422 	}
3423 
3424 	/*
3425 	 * If we are importing a pool with missing top-level vdevs,
3426 	 * we enforce that the pool doesn't panic or get suspended on
3427 	 * error since the likelihood of missing data is extremely high.
3428 	 */
3429 	if (spa->spa_missing_tvds > 0 &&
3430 	    spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3431 	    spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3432 		spa_load_note(spa, "forcing failmode to 'continue' "
3433 		    "as some top level vdevs are missing");
3434 		spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3435 	}
3436 
3437 	return (0);
3438 }
3439 
3440 static int
3441 spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3442 {
3443 	int error = 0;
3444 	vdev_t *rvd = spa->spa_root_vdev;
3445 
3446 	/*
3447 	 * If we're assembling the pool from the split-off vdevs of
3448 	 * an existing pool, we don't want to attach the spares & cache
3449 	 * devices.
3450 	 */
3451 
3452 	/*
3453 	 * Load any hot spares for this pool.
3454 	 */
3455 	error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3456 	    B_FALSE);
3457 	if (error != 0 && error != ENOENT)
3458 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3459 	if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3460 		ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3461 		if (load_nvlist(spa, spa->spa_spares.sav_object,
3462 		    &spa->spa_spares.sav_config) != 0) {
3463 			spa_load_failed(spa, "error loading spares nvlist");
3464 			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3465 		}
3466 
3467 		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3468 		spa_load_spares(spa);
3469 		spa_config_exit(spa, SCL_ALL, FTAG);
3470 	} else if (error == 0) {
3471 		spa->spa_spares.sav_sync = B_TRUE;
3472 	}
3473 
3474 	/*
3475 	 * Load any level 2 ARC devices for this pool.
3476 	 */
3477 	error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3478 	    &spa->spa_l2cache.sav_object, B_FALSE);
3479 	if (error != 0 && error != ENOENT)
3480 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3481 	if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3482 		ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3483 		if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3484 		    &spa->spa_l2cache.sav_config) != 0) {
3485 			spa_load_failed(spa, "error loading l2cache nvlist");
3486 			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3487 		}
3488 
3489 		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3490 		spa_load_l2cache(spa);
3491 		spa_config_exit(spa, SCL_ALL, FTAG);
3492 	} else if (error == 0) {
3493 		spa->spa_l2cache.sav_sync = B_TRUE;
3494 	}
3495 
3496 	return (0);
3497 }
3498 
3499 static int
3500 spa_ld_load_vdev_metadata(spa_t *spa)
3501 {
3502 	int error = 0;
3503 	vdev_t *rvd = spa->spa_root_vdev;
3504 
3505 	/*
3506 	 * If the 'multihost' property is set, then never allow a pool to
3507 	 * be imported when the system hostid is zero.  The exception to
3508 	 * this rule is zdb which is always allowed to access pools.
3509 	 */
3510 	if (spa_multihost(spa) && spa_get_hostid() == 0 &&
3511 	    (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP) == 0) {
3512 		fnvlist_add_uint64(spa->spa_load_info,
3513 		    ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3514 		return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3515 	}
3516 
3517 	/*
3518 	 * If the 'autoreplace' property is set, then post a resource notifying
3519 	 * the ZFS DE that it should not issue any faults for unopenable
3520 	 * devices.  We also iterate over the vdevs, and post a sysevent for any
3521 	 * unopenable vdevs so that the normal autoreplace handler can take
3522 	 * over.
3523 	 */
3524 	if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3525 		spa_check_removed(spa->spa_root_vdev);
3526 		/*
3527 		 * For the import case, this is done in spa_import(), because
3528 		 * at this point we're using the spare definitions from
3529 		 * the MOS config, not necessarily from the userland config.
3530 		 */
3531 		if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3532 			spa_aux_check_removed(&spa->spa_spares);
3533 			spa_aux_check_removed(&spa->spa_l2cache);
3534 		}
3535 	}
3536 
3537 	/*
3538 	 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3539 	 */
3540 	error = vdev_load(rvd);
3541 	if (error != 0) {
3542 		spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3543 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3544 	}
3545 
3546 	/*
3547 	 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3548 	 */
3549 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3550 	vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3551 	spa_config_exit(spa, SCL_ALL, FTAG);
3552 
3553 	return (0);
3554 }
3555 
3556 static int
3557 spa_ld_load_dedup_tables(spa_t *spa)
3558 {
3559 	int error = 0;
3560 	vdev_t *rvd = spa->spa_root_vdev;
3561 
3562 	error = ddt_load(spa);
3563 	if (error != 0) {
3564 		spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3565 		return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3566 	}
3567 
3568 	return (0);
3569 }
3570 
3571 static int
3572 spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3573 {
3574 	vdev_t *rvd = spa->spa_root_vdev;
3575 
3576 	if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3577 		boolean_t missing = spa_check_logs(spa);
3578 		if (missing) {
3579 			if (spa->spa_missing_tvds != 0) {
3580 				spa_load_note(spa, "spa_check_logs failed "
3581 				    "so dropping the logs");
3582 			} else {
3583 				*ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3584 				spa_load_failed(spa, "spa_check_logs failed");
3585 				return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3586 				    ENXIO));
3587 			}
3588 		}
3589 	}
3590 
3591 	return (0);
3592 }
3593 
3594 static int
3595 spa_ld_verify_pool_data(spa_t *spa)
3596 {
3597 	int error = 0;
3598 	vdev_t *rvd = spa->spa_root_vdev;
3599 
3600 	/*
3601 	 * We've successfully opened the pool, verify that we're ready
3602 	 * to start pushing transactions.
3603 	 */
3604 	if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3605 		error = spa_load_verify(spa);
3606 		if (error != 0) {
3607 			spa_load_failed(spa, "spa_load_verify failed "
3608 			    "[error=%d]", error);
3609 			return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3610 			    error));
3611 		}
3612 	}
3613 
3614 	return (0);
3615 }
3616 
3617 static void
3618 spa_ld_claim_log_blocks(spa_t *spa)
3619 {
3620 	dmu_tx_t *tx;
3621 	dsl_pool_t *dp = spa_get_dsl(spa);
3622 
3623 	/*
3624 	 * Claim log blocks that haven't been committed yet.
3625 	 * This must all happen in a single txg.
3626 	 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3627 	 * invoked from zil_claim_log_block()'s i/o done callback.
3628 	 * Price of rollback is that we abandon the log.
3629 	 */
3630 	spa->spa_claiming = B_TRUE;
3631 
3632 	tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3633 	(void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3634 	    zil_claim, tx, DS_FIND_CHILDREN);
3635 	dmu_tx_commit(tx);
3636 
3637 	spa->spa_claiming = B_FALSE;
3638 
3639 	spa_set_log_state(spa, SPA_LOG_GOOD);
3640 }
3641 
3642 static void
3643 spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3644     boolean_t update_config_cache)
3645 {
3646 	vdev_t *rvd = spa->spa_root_vdev;
3647 	int need_update = B_FALSE;
3648 
3649 	/*
3650 	 * If the config cache is stale, or we have uninitialized
3651 	 * metaslabs (see spa_vdev_add()), then update the config.
3652 	 *
3653 	 * If this is a verbatim import, trust the current
3654 	 * in-core spa_config and update the disk labels.
3655 	 */
3656 	if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
3657 	    spa->spa_load_state == SPA_LOAD_IMPORT ||
3658 	    spa->spa_load_state == SPA_LOAD_RECOVER ||
3659 	    (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3660 		need_update = B_TRUE;
3661 
3662 	for (int c = 0; c < rvd->vdev_children; c++)
3663 		if (rvd->vdev_child[c]->vdev_ms_array == 0)
3664 			need_update = B_TRUE;
3665 
3666 	/*
3667 	 * Update the config cache asychronously in case we're the
3668 	 * root pool, in which case the config cache isn't writable yet.
3669 	 */
3670 	if (need_update)
3671 		spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3672 }
3673 
3674 static void
3675 spa_ld_prepare_for_reload(spa_t *spa)
3676 {
3677 	int mode = spa->spa_mode;
3678 	int async_suspended = spa->spa_async_suspended;
3679 
3680 	spa_unload(spa);
3681 	spa_deactivate(spa);
3682 	spa_activate(spa, mode);
3683 
3684 	/*
3685 	 * We save the value of spa_async_suspended as it gets reset to 0 by
3686 	 * spa_unload(). We want to restore it back to the original value before
3687 	 * returning as we might be calling spa_async_resume() later.
3688 	 */
3689 	spa->spa_async_suspended = async_suspended;
3690 }
3691 
3692 static int
3693 spa_ld_read_checkpoint_txg(spa_t *spa)
3694 {
3695 	uberblock_t checkpoint;
3696 	int error = 0;
3697 
3698 	ASSERT0(spa->spa_checkpoint_txg);
3699 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3700 
3701 	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3702 	    DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3703 	    sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3704 
3705 	if (error == ENOENT)
3706 		return (0);
3707 
3708 	if (error != 0)
3709 		return (error);
3710 
3711 	ASSERT3U(checkpoint.ub_txg, !=, 0);
3712 	ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3713 	ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3714 	spa->spa_checkpoint_txg = checkpoint.ub_txg;
3715 	spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3716 
3717 	return (0);
3718 }
3719 
3720 static int
3721 spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
3722 {
3723 	int error = 0;
3724 
3725 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3726 	ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3727 
3728 	/*
3729 	 * Never trust the config that is provided unless we are assembling
3730 	 * a pool following a split.
3731 	 * This means don't trust blkptrs and the vdev tree in general. This
3732 	 * also effectively puts the spa in read-only mode since
3733 	 * spa_writeable() checks for spa_trust_config to be true.
3734 	 * We will later load a trusted config from the MOS.
3735 	 */
3736 	if (type != SPA_IMPORT_ASSEMBLE)
3737 		spa->spa_trust_config = B_FALSE;
3738 
3739 	/*
3740 	 * Parse the config provided to create a vdev tree.
3741 	 */
3742 	error = spa_ld_parse_config(spa, type);
3743 	if (error != 0)
3744 		return (error);
3745 
3746 	/*
3747 	 * Now that we have the vdev tree, try to open each vdev. This involves
3748 	 * opening the underlying physical device, retrieving its geometry and
3749 	 * probing the vdev with a dummy I/O. The state of each vdev will be set
3750 	 * based on the success of those operations. After this we'll be ready
3751 	 * to read from the vdevs.
3752 	 */
3753 	error = spa_ld_open_vdevs(spa);
3754 	if (error != 0)
3755 		return (error);
3756 
3757 	/*
3758 	 * Read the label of each vdev and make sure that the GUIDs stored
3759 	 * there match the GUIDs in the config provided.
3760 	 * If we're assembling a new pool that's been split off from an
3761 	 * existing pool, the labels haven't yet been updated so we skip
3762 	 * validation for now.
3763 	 */
3764 	if (type != SPA_IMPORT_ASSEMBLE) {
3765 		error = spa_ld_validate_vdevs(spa);
3766 		if (error != 0)
3767 			return (error);
3768 	}
3769 
3770 	/*
3771 	 * Read all vdev labels to find the best uberblock (i.e. latest,
3772 	 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3773 	 * get the list of features required to read blkptrs in the MOS from
3774 	 * the vdev label with the best uberblock and verify that our version
3775 	 * of zfs supports them all.
3776 	 */
3777 	error = spa_ld_select_uberblock(spa, type);
3778 	if (error != 0)
3779 		return (error);
3780 
3781 	/*
3782 	 * Pass that uberblock to the dsl_pool layer which will open the root
3783 	 * blkptr. This blkptr points to the latest version of the MOS and will
3784 	 * allow us to read its contents.
3785 	 */
3786 	error = spa_ld_open_rootbp(spa);
3787 	if (error != 0)
3788 		return (error);
3789 
3790 	return (0);
3791 }
3792 
3793 static int
3794 spa_ld_checkpoint_rewind(spa_t *spa)
3795 {
3796 	uberblock_t checkpoint;
3797 	int error = 0;
3798 
3799 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3800 	ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3801 
3802 	error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3803 	    DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3804 	    sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3805 
3806 	if (error != 0) {
3807 		spa_load_failed(spa, "unable to retrieve checkpointed "
3808 		    "uberblock from the MOS config [error=%d]", error);
3809 
3810 		if (error == ENOENT)
3811 			error = ZFS_ERR_NO_CHECKPOINT;
3812 
3813 		return (error);
3814 	}
3815 
3816 	ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
3817 	ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
3818 
3819 	/*
3820 	 * We need to update the txg and timestamp of the checkpointed
3821 	 * uberblock to be higher than the latest one. This ensures that
3822 	 * the checkpointed uberblock is selected if we were to close and
3823 	 * reopen the pool right after we've written it in the vdev labels.
3824 	 * (also see block comment in vdev_uberblock_compare)
3825 	 */
3826 	checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
3827 	checkpoint.ub_timestamp = gethrestime_sec();
3828 
3829 	/*
3830 	 * Set current uberblock to be the checkpointed uberblock.
3831 	 */
3832 	spa->spa_uberblock = checkpoint;
3833 
3834 	/*
3835 	 * If we are doing a normal rewind, then the pool is open for
3836 	 * writing and we sync the "updated" checkpointed uberblock to
3837 	 * disk. Once this is done, we've basically rewound the whole
3838 	 * pool and there is no way back.
3839 	 *
3840 	 * There are cases when we don't want to attempt and sync the
3841 	 * checkpointed uberblock to disk because we are opening a
3842 	 * pool as read-only. Specifically, verifying the checkpointed
3843 	 * state with zdb, and importing the checkpointed state to get
3844 	 * a "preview" of its content.
3845 	 */
3846 	if (spa_writeable(spa)) {
3847 		vdev_t *rvd = spa->spa_root_vdev;
3848 
3849 		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3850 		vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
3851 		int svdcount = 0;
3852 		int children = rvd->vdev_children;
3853 		int c0 = spa_get_random(children);
3854 
3855 		for (int c = 0; c < children; c++) {
3856 			vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
3857 
3858 			/* Stop when revisiting the first vdev */
3859 			if (c > 0 && svd[0] == vd)
3860 				break;
3861 
3862 			if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
3863 			    !vdev_is_concrete(vd))
3864 				continue;
3865 
3866 			svd[svdcount++] = vd;
3867 			if (svdcount == SPA_SYNC_MIN_VDEVS)
3868 				break;
3869 		}
3870 		error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
3871 		if (error == 0)
3872 			spa->spa_last_synced_guid = rvd->vdev_guid;
3873 		spa_config_exit(spa, SCL_ALL, FTAG);
3874 
3875 		if (error != 0) {
3876 			spa_load_failed(spa, "failed to write checkpointed "
3877 			    "uberblock to the vdev labels [error=%d]", error);
3878 			return (error);
3879 		}
3880 	}
3881 
3882 	return (0);
3883 }
3884 
3885 static int
3886 spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
3887     boolean_t *update_config_cache)
3888 {
3889 	int error;
3890 
3891 	/*
3892 	 * Parse the config for pool, open and validate vdevs,
3893 	 * select an uberblock, and use that uberblock to open
3894 	 * the MOS.
3895 	 */
3896 	error = spa_ld_mos_init(spa, type);
3897 	if (error != 0)
3898 		return (error);
3899 
3900 	/*
3901 	 * Retrieve the trusted config stored in the MOS and use it to create
3902 	 * a new, exact version of the vdev tree, then reopen all vdevs.
3903 	 */
3904 	error = spa_ld_trusted_config(spa, type, B_FALSE);
3905 	if (error == EAGAIN) {
3906 		if (update_config_cache != NULL)
3907 			*update_config_cache = B_TRUE;
3908 
3909 		/*
3910 		 * Redo the loading process with the trusted config if it is
3911 		 * too different from the untrusted config.
3912 		 */
3913 		spa_ld_prepare_for_reload(spa);
3914 		spa_load_note(spa, "RELOADING");
3915 		error = spa_ld_mos_init(spa, type);
3916 		if (error != 0)
3917 			return (error);
3918 
3919 		error = spa_ld_trusted_config(spa, type, B_TRUE);
3920 		if (error != 0)
3921 			return (error);
3922 
3923 	} else if (error != 0) {
3924 		return (error);
3925 	}
3926 
3927 	return (0);
3928 }
3929 
3930 /*
3931  * Load an existing storage pool, using the config provided. This config
3932  * describes which vdevs are part of the pool and is later validated against
3933  * partial configs present in each vdev's label and an entire copy of the
3934  * config stored in the MOS.
3935  */
3936 static int
3937 spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
3938 {
3939 	int error = 0;
3940 	boolean_t missing_feat_write = B_FALSE;
3941 	boolean_t checkpoint_rewind =
3942 	    (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3943 	boolean_t update_config_cache = B_FALSE;
3944 
3945 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
3946 	ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3947 
3948 	spa_load_note(spa, "LOADING");
3949 
3950 	error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
3951 	if (error != 0)
3952 		return (error);
3953 
3954 	/*
3955 	 * If we are rewinding to the checkpoint then we need to repeat
3956 	 * everything we've done so far in this function but this time
3957 	 * selecting the checkpointed uberblock and using that to open
3958 	 * the MOS.
3959 	 */
3960 	if (checkpoint_rewind) {
3961 		/*
3962 		 * If we are rewinding to the checkpoint update config cache
3963 		 * anyway.
3964 		 */
3965 		update_config_cache = B_TRUE;
3966 
3967 		/*
3968 		 * Extract the checkpointed uberblock from the current MOS
3969 		 * and use this as the pool's uberblock from now on. If the
3970 		 * pool is imported as writeable we also write the checkpoint
3971 		 * uberblock to the labels, making the rewind permanent.
3972 		 */
3973 		error = spa_ld_checkpoint_rewind(spa);
3974 		if (error != 0)
3975 			return (error);
3976 
3977 		/*
3978 		 * Redo the loading process process again with the
3979 		 * checkpointed uberblock.
3980 		 */
3981 		spa_ld_prepare_for_reload(spa);
3982 		spa_load_note(spa, "LOADING checkpointed uberblock");
3983 		error = spa_ld_mos_with_trusted_config(spa, type, NULL);
3984 		if (error != 0)
3985 			return (error);
3986 	}
3987 
3988 	/*
3989 	 * Retrieve the checkpoint txg if the pool has a checkpoint.
3990 	 */
3991 	error = spa_ld_read_checkpoint_txg(spa);
3992 	if (error != 0)
3993 		return (error);
3994 
3995 	/*
3996 	 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
3997 	 * from the pool and their contents were re-mapped to other vdevs. Note
3998 	 * that everything that we read before this step must have been
3999 	 * rewritten on concrete vdevs after the last device removal was
4000 	 * initiated. Otherwise we could be reading from indirect vdevs before
4001 	 * we have loaded their mappings.
4002 	 */
4003 	error = spa_ld_open_indirect_vdev_metadata(spa);
4004 	if (error != 0)
4005 		return (error);
4006 
4007 	/*
4008 	 * Retrieve the full list of active features from the MOS and check if
4009 	 * they are all supported.
4010 	 */
4011 	error = spa_ld_check_features(spa, &missing_feat_write);
4012 	if (error != 0)
4013 		return (error);
4014 
4015 	/*
4016 	 * Load several special directories from the MOS needed by the dsl_pool
4017 	 * layer.
4018 	 */
4019 	error = spa_ld_load_special_directories(spa);
4020 	if (error != 0)
4021 		return (error);
4022 
4023 	/*
4024 	 * Retrieve pool properties from the MOS.
4025 	 */
4026 	error = spa_ld_get_props(spa);
4027 	if (error != 0)
4028 		return (error);
4029 
4030 	/*
4031 	 * Retrieve the list of auxiliary devices - cache devices and spares -
4032 	 * and open them.
4033 	 */
4034 	error = spa_ld_open_aux_vdevs(spa, type);
4035 	if (error != 0)
4036 		return (error);
4037 
4038 	/*
4039 	 * Load the metadata for all vdevs. Also check if unopenable devices
4040 	 * should be autoreplaced.
4041 	 */
4042 	error = spa_ld_load_vdev_metadata(spa);
4043 	if (error != 0)
4044 		return (error);
4045 
4046 	error = spa_ld_load_dedup_tables(spa);
4047 	if (error != 0)
4048 		return (error);
4049 
4050 	/*
4051 	 * Verify the logs now to make sure we don't have any unexpected errors
4052 	 * when we claim log blocks later.
4053 	 */
4054 	error = spa_ld_verify_logs(spa, type, ereport);
4055 	if (error != 0)
4056 		return (error);
4057 
4058 	if (missing_feat_write) {
4059 		ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
4060 
4061 		/*
4062 		 * At this point, we know that we can open the pool in
4063 		 * read-only mode but not read-write mode. We now have enough
4064 		 * information and can return to userland.
4065 		 */
4066 		return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
4067 		    ENOTSUP));
4068 	}
4069 
4070 	/*
4071 	 * Traverse the last txgs to make sure the pool was left off in a safe
4072 	 * state. When performing an extreme rewind, we verify the whole pool,
4073 	 * which can take a very long time.
4074 	 */
4075 	error = spa_ld_verify_pool_data(spa);
4076 	if (error != 0)
4077 		return (error);
4078 
4079 	/*
4080 	 * Calculate the deflated space for the pool. This must be done before
4081 	 * we write anything to the pool because we'd need to update the space
4082 	 * accounting using the deflated sizes.
4083 	 */
4084 	spa_update_dspace(spa);
4085 
4086 	/*
4087 	 * We have now retrieved all the information we needed to open the
4088 	 * pool. If we are importing the pool in read-write mode, a few
4089 	 * additional steps must be performed to finish the import.
4090 	 */
4091 	if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
4092 	    spa->spa_load_max_txg == UINT64_MAX)) {
4093 		uint64_t config_cache_txg = spa->spa_config_txg;
4094 
4095 		ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
4096 
4097 		/*
4098 		 * In case of a checkpoint rewind, log the original txg
4099 		 * of the checkpointed uberblock.
4100 		 */
4101 		if (checkpoint_rewind) {
4102 			spa_history_log_internal(spa, "checkpoint rewind",
4103 			    NULL, "rewound state to txg=%llu",
4104 			    (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
4105 		}
4106 
4107 		/*
4108 		 * Traverse the ZIL and claim all blocks.
4109 		 */
4110 		spa_ld_claim_log_blocks(spa);
4111 
4112 		/*
4113 		 * Kick-off the syncing thread.
4114 		 */
4115 		spa->spa_sync_on = B_TRUE;
4116 		txg_sync_start(spa->spa_dsl_pool);
4117 		mmp_thread_start(spa);
4118 
4119 		/*
4120 		 * Wait for all claims to sync.  We sync up to the highest
4121 		 * claimed log block birth time so that claimed log blocks
4122 		 * don't appear to be from the future.  spa_claim_max_txg
4123 		 * will have been set for us by ZIL traversal operations
4124 		 * performed above.
4125 		 */
4126 		txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
4127 
4128 		/*
4129 		 * Check if we need to request an update of the config. On the
4130 		 * next sync, we would update the config stored in vdev labels
4131 		 * and the cachefile (by default /etc/zfs/zpool.cache).
4132 		 */
4133 		spa_ld_check_for_config_update(spa, config_cache_txg,
4134 		    update_config_cache);
4135 
4136 		/*
4137 		 * Check all DTLs to see if anything needs resilvering.
4138 		 */
4139 		if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
4140 		    vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
4141 			spa_async_request(spa, SPA_ASYNC_RESILVER);
4142 
4143 		/*
4144 		 * Log the fact that we booted up (so that we can detect if
4145 		 * we rebooted in the middle of an operation).
4146 		 */
4147 		spa_history_log_version(spa, "open");
4148 
4149 		spa_restart_removal(spa);
4150 		spa_spawn_aux_threads(spa);
4151 
4152 		/*
4153 		 * Delete any inconsistent datasets.
4154 		 *
4155 		 * Note:
4156 		 * Since we may be issuing deletes for clones here,
4157 		 * we make sure to do so after we've spawned all the
4158 		 * auxiliary threads above (from which the livelist
4159 		 * deletion zthr is part of).
4160 		 */
4161 		(void) dmu_objset_find(spa_name(spa),
4162 		    dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
4163 
4164 		/*
4165 		 * Clean up any stale temporary dataset userrefs.
4166 		 */
4167 		dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
4168 
4169 		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4170 		vdev_initialize_restart(spa->spa_root_vdev);
4171 		spa_config_exit(spa, SCL_CONFIG, FTAG);
4172 	}
4173 
4174 	spa_load_note(spa, "LOADED");
4175 
4176 	return (0);
4177 }
4178 
4179 static int
4180 spa_load_retry(spa_t *spa, spa_load_state_t state)
4181 {
4182 	int mode = spa->spa_mode;
4183 
4184 	spa_unload(spa);
4185 	spa_deactivate(spa);
4186 
4187 	spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
4188 
4189 	spa_activate(spa, mode);
4190 	spa_async_suspend(spa);
4191 
4192 	spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
4193 	    (u_longlong_t)spa->spa_load_max_txg);
4194 
4195 	return (spa_load(spa, state, SPA_IMPORT_EXISTING));
4196 }
4197 
4198 /*
4199  * If spa_load() fails this function will try loading prior txg's. If
4200  * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
4201  * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
4202  * function will not rewind the pool and will return the same error as
4203  * spa_load().
4204  */
4205 static int
4206 spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4207     int rewind_flags)
4208 {
4209 	nvlist_t *loadinfo = NULL;
4210 	nvlist_t *config = NULL;
4211 	int load_error, rewind_error;
4212 	uint64_t safe_rewind_txg;
4213 	uint64_t min_txg;
4214 
4215 	if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4216 		spa->spa_load_max_txg = spa->spa_load_txg;
4217 		spa_set_log_state(spa, SPA_LOG_CLEAR);
4218 	} else {
4219 		spa->spa_load_max_txg = max_request;
4220 		if (max_request != UINT64_MAX)
4221 			spa->spa_extreme_rewind = B_TRUE;
4222 	}
4223 
4224 	load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
4225 	if (load_error == 0)
4226 		return (0);
4227 	if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4228 		/*
4229 		 * When attempting checkpoint-rewind on a pool with no
4230 		 * checkpoint, we should not attempt to load uberblocks
4231 		 * from previous txgs when spa_load fails.
4232 		 */
4233 		ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4234 		return (load_error);
4235 	}
4236 
4237 	if (spa->spa_root_vdev != NULL)
4238 		config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4239 
4240 	spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4241 	spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4242 
4243 	if (rewind_flags & ZPOOL_NEVER_REWIND) {
4244 		nvlist_free(config);
4245 		return (load_error);
4246 	}
4247 
4248 	if (state == SPA_LOAD_RECOVER) {
4249 		/* Price of rolling back is discarding txgs, including log */
4250 		spa_set_log_state(spa, SPA_LOG_CLEAR);
4251 	} else {
4252 		/*
4253 		 * If we aren't rolling back save the load info from our first
4254 		 * import attempt so that we can restore it after attempting
4255 		 * to rewind.
4256 		 */
4257 		loadinfo = spa->spa_load_info;
4258 		spa->spa_load_info = fnvlist_alloc();
4259 	}
4260 
4261 	spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4262 	safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4263 	min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4264 	    TXG_INITIAL : safe_rewind_txg;
4265 
4266 	/*
4267 	 * Continue as long as we're finding errors, we're still within
4268 	 * the acceptable rewind range, and we're still finding uberblocks
4269 	 */
4270 	while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4271 	    spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4272 		if (spa->spa_load_max_txg < safe_rewind_txg)
4273 			spa->spa_extreme_rewind = B_TRUE;
4274 		rewind_error = spa_load_retry(spa, state);
4275 	}
4276 
4277 	spa->spa_extreme_rewind = B_FALSE;
4278 	spa->spa_load_max_txg = UINT64_MAX;
4279 
4280 	if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4281 		spa_config_set(spa, config);
4282 	else
4283 		nvlist_free(config);
4284 
4285 	if (state == SPA_LOAD_RECOVER) {
4286 		ASSERT3P(loadinfo, ==, NULL);
4287 		return (rewind_error);
4288 	} else {
4289 		/* Store the rewind info as part of the initial load info */
4290 		fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4291 		    spa->spa_load_info);
4292 
4293 		/* Restore the initial load info */
4294 		fnvlist_free(spa->spa_load_info);
4295 		spa->spa_load_info = loadinfo;
4296 
4297 		return (load_error);
4298 	}
4299 }
4300 
4301 /*
4302  * Pool Open/Import
4303  *
4304  * The import case is identical to an open except that the configuration is sent
4305  * down from userland, instead of grabbed from the configuration cache.  For the
4306  * case of an open, the pool configuration will exist in the
4307  * POOL_STATE_UNINITIALIZED state.
4308  *
4309  * The stats information (gen/count/ustats) is used to gather vdev statistics at
4310  * the same time open the pool, without having to keep around the spa_t in some
4311  * ambiguous state.
4312  */
4313 static int
4314 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4315     nvlist_t **config)
4316 {
4317 	spa_t *spa;
4318 	spa_load_state_t state = SPA_LOAD_OPEN;
4319 	int error;
4320 	int locked = B_FALSE;
4321 
4322 	*spapp = NULL;
4323 
4324 	/*
4325 	 * As disgusting as this is, we need to support recursive calls to this
4326 	 * function because dsl_dir_open() is called during spa_load(), and ends
4327 	 * up calling spa_open() again.  The real fix is to figure out how to
4328 	 * avoid dsl_dir_open() calling this in the first place.
4329 	 */
4330 	if (mutex_owner(&spa_namespace_lock) != curthread) {
4331 		mutex_enter(&spa_namespace_lock);
4332 		locked = B_TRUE;
4333 	}
4334 
4335 	if ((spa = spa_lookup(pool)) == NULL) {
4336 		if (locked)
4337 			mutex_exit(&spa_namespace_lock);
4338 		return (SET_ERROR(ENOENT));
4339 	}
4340 
4341 	if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
4342 		zpool_load_policy_t policy;
4343 
4344 		zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
4345 		    &policy);
4346 		if (policy.zlp_rewind & ZPOOL_DO_REWIND)
4347 			state = SPA_LOAD_RECOVER;
4348 
4349 		spa_activate(spa, spa_mode_global);
4350 
4351 		if (state != SPA_LOAD_RECOVER)
4352 			spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4353 		spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
4354 
4355 		zfs_dbgmsg("spa_open_common: opening %s", pool);
4356 		error = spa_load_best(spa, state, policy.zlp_txg,
4357 		    policy.zlp_rewind);
4358 
4359 		if (error == EBADF) {
4360 			/*
4361 			 * If vdev_validate() returns failure (indicated by
4362 			 * EBADF), it indicates that one of the vdevs indicates
4363 			 * that the pool has been exported or destroyed.  If
4364 			 * this is the case, the config cache is out of sync and
4365 			 * we should remove the pool from the namespace.
4366 			 */
4367 			spa_unload(spa);
4368 			spa_deactivate(spa);
4369 			spa_write_cachefile(spa, B_TRUE, B_TRUE);
4370 			spa_remove(spa);
4371 			if (locked)
4372 				mutex_exit(&spa_namespace_lock);
4373 			return (SET_ERROR(ENOENT));
4374 		}
4375 
4376 		if (error) {
4377 			/*
4378 			 * We can't open the pool, but we still have useful
4379 			 * information: the state of each vdev after the
4380 			 * attempted vdev_open().  Return this to the user.
4381 			 */
4382 			if (config != NULL && spa->spa_config) {
4383 				VERIFY(nvlist_dup(spa->spa_config, config,
4384 				    KM_SLEEP) == 0);
4385 				VERIFY(nvlist_add_nvlist(*config,
4386 				    ZPOOL_CONFIG_LOAD_INFO,
4387 				    spa->spa_load_info) == 0);
4388 			}
4389 			spa_unload(spa);
4390 			spa_deactivate(spa);
4391 			spa->spa_last_open_failed = error;
4392 			if (locked)
4393 				mutex_exit(&spa_namespace_lock);
4394 			*spapp = NULL;
4395 			return (error);
4396 		}
4397 	}
4398 
4399 	spa_open_ref(spa, tag);
4400 
4401 	if (config != NULL)
4402 		*config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4403 
4404 	/*
4405 	 * If we've recovered the pool, pass back any information we
4406 	 * gathered while doing the load.
4407 	 */
4408 	if (state == SPA_LOAD_RECOVER) {
4409 		VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4410 		    spa->spa_load_info) == 0);
4411 	}
4412 
4413 	if (locked) {
4414 		spa->spa_last_open_failed = 0;
4415 		spa->spa_last_ubsync_txg = 0;
4416 		spa->spa_load_txg = 0;
4417 		mutex_exit(&spa_namespace_lock);
4418 	}
4419 
4420 	*spapp = spa;
4421 
4422 	return (0);
4423 }
4424 
4425 int
4426 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4427     nvlist_t **config)
4428 {
4429 	return (spa_open_common(name, spapp, tag, policy, config));
4430 }
4431 
4432 int
4433 spa_open(const char *name, spa_t **spapp, void *tag)
4434 {
4435 	return (spa_open_common(name, spapp, tag, NULL, NULL));
4436 }
4437 
4438 /*
4439  * Lookup the given spa_t, incrementing the inject count in the process,
4440  * preventing it from being exported or destroyed.
4441  */
4442 spa_t *
4443 spa_inject_addref(char *name)
4444 {
4445 	spa_t *spa;
4446 
4447 	mutex_enter(&spa_namespace_lock);
4448 	if ((spa = spa_lookup(name)) == NULL) {
4449 		mutex_exit(&spa_namespace_lock);
4450 		return (NULL);
4451 	}
4452 	spa->spa_inject_ref++;
4453 	mutex_exit(&spa_namespace_lock);
4454 
4455 	return (spa);
4456 }
4457 
4458 void
4459 spa_inject_delref(spa_t *spa)
4460 {
4461 	mutex_enter(&spa_namespace_lock);
4462 	spa->spa_inject_ref--;
4463 	mutex_exit(&spa_namespace_lock);
4464 }
4465 
4466 /*
4467  * Add spares device information to the nvlist.
4468  */
4469 static void
4470 spa_add_spares(spa_t *spa, nvlist_t *config)
4471 {
4472 	nvlist_t **spares;
4473 	uint_t i, nspares;
4474 	nvlist_t *nvroot;
4475 	uint64_t guid;
4476 	vdev_stat_t *vs;
4477 	uint_t vsc;
4478 	uint64_t pool;
4479 
4480 	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4481 
4482 	if (spa->spa_spares.sav_count == 0)
4483 		return;
4484 
4485 	VERIFY(nvlist_lookup_nvlist(config,
4486 	    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4487 	VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4488 	    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4489 	if (nspares != 0) {
4490 		VERIFY(nvlist_add_nvlist_array(nvroot,
4491 		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4492 		VERIFY(nvlist_lookup_nvlist_array(nvroot,
4493 		    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4494 
4495 		/*
4496 		 * Go through and find any spares which have since been
4497 		 * repurposed as an active spare.  If this is the case, update
4498 		 * their status appropriately.
4499 		 */
4500 		for (i = 0; i < nspares; i++) {
4501 			VERIFY(nvlist_lookup_uint64(spares[i],
4502 			    ZPOOL_CONFIG_GUID, &guid) == 0);
4503 			if (spa_spare_exists(guid, &pool, NULL) &&
4504 			    pool != 0ULL) {
4505 				VERIFY(nvlist_lookup_uint64_array(
4506 				    spares[i], ZPOOL_CONFIG_VDEV_STATS,
4507 				    (uint64_t **)&vs, &vsc) == 0);
4508 				vs->vs_state = VDEV_STATE_CANT_OPEN;
4509 				vs->vs_aux = VDEV_AUX_SPARED;
4510 			}
4511 		}
4512 	}
4513 }
4514 
4515 /*
4516  * Add l2cache device information to the nvlist, including vdev stats.
4517  */
4518 static void
4519 spa_add_l2cache(spa_t *spa, nvlist_t *config)
4520 {
4521 	nvlist_t **l2cache;
4522 	uint_t i, j, nl2cache;
4523 	nvlist_t *nvroot;
4524 	uint64_t guid;
4525 	vdev_t *vd;
4526 	vdev_stat_t *vs;
4527 	uint_t vsc;
4528 
4529 	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4530 
4531 	if (spa->spa_l2cache.sav_count == 0)
4532 		return;
4533 
4534 	VERIFY(nvlist_lookup_nvlist(config,
4535 	    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4536 	VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4537 	    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4538 	if (nl2cache != 0) {
4539 		VERIFY(nvlist_add_nvlist_array(nvroot,
4540 		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4541 		VERIFY(nvlist_lookup_nvlist_array(nvroot,
4542 		    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4543 
4544 		/*
4545 		 * Update level 2 cache device stats.
4546 		 */
4547 
4548 		for (i = 0; i < nl2cache; i++) {
4549 			VERIFY(nvlist_lookup_uint64(l2cache[i],
4550 			    ZPOOL_CONFIG_GUID, &guid) == 0);
4551 
4552 			vd = NULL;
4553 			for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4554 				if (guid ==
4555 				    spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4556 					vd = spa->spa_l2cache.sav_vdevs[j];
4557 					break;
4558 				}
4559 			}
4560 			ASSERT(vd != NULL);
4561 
4562 			VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4563 			    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4564 			    == 0);
4565 			vdev_get_stats(vd, vs);
4566 		}
4567 	}
4568 }
4569 
4570 static void
4571 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4572 {
4573 	nvlist_t *features;
4574 	zap_cursor_t zc;
4575 	zap_attribute_t za;
4576 
4577 	ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4578 	VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4579 
4580 	if (spa->spa_feat_for_read_obj != 0) {
4581 		for (zap_cursor_init(&zc, spa->spa_meta_objset,
4582 		    spa->spa_feat_for_read_obj);
4583 		    zap_cursor_retrieve(&zc, &za) == 0;
4584 		    zap_cursor_advance(&zc)) {
4585 			ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4586 			    za.za_num_integers == 1);
4587 			VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4588 			    za.za_first_integer));
4589 		}
4590 		zap_cursor_fini(&zc);
4591 	}
4592 
4593 	if (spa->spa_feat_for_write_obj != 0) {
4594 		for (zap_cursor_init(&zc, spa->spa_meta_objset,
4595 		    spa->spa_feat_for_write_obj);
4596 		    zap_cursor_retrieve(&zc, &za) == 0;
4597 		    zap_cursor_advance(&zc)) {
4598 			ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4599 			    za.za_num_integers == 1);
4600 			VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4601 			    za.za_first_integer));
4602 		}
4603 		zap_cursor_fini(&zc);
4604 	}
4605 
4606 	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4607 	    features) == 0);
4608 	nvlist_free(features);
4609 }
4610 
4611 int
4612 spa_get_stats(const char *name, nvlist_t **config,
4613     char *altroot, size_t buflen)
4614 {
4615 	int error;
4616 	spa_t *spa;
4617 
4618 	*config = NULL;
4619 	error = spa_open_common(name, &spa, FTAG, NULL, config);
4620 
4621 	if (spa != NULL) {
4622 		/*
4623 		 * This still leaves a window of inconsistency where the spares
4624 		 * or l2cache devices could change and the config would be
4625 		 * self-inconsistent.
4626 		 */
4627 		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4628 
4629 		if (*config != NULL) {
4630 			uint64_t loadtimes[2];
4631 
4632 			loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4633 			loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4634 			VERIFY(nvlist_add_uint64_array(*config,
4635 			    ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4636 
4637 			VERIFY(nvlist_add_uint64(*config,
4638 			    ZPOOL_CONFIG_ERRCOUNT,
4639 			    spa_get_errlog_size(spa)) == 0);
4640 
4641 			if (spa_suspended(spa)) {
4642 				VERIFY(nvlist_add_uint64(*config,
4643 				    ZPOOL_CONFIG_SUSPENDED,
4644 				    spa->spa_failmode) == 0);
4645 				VERIFY(nvlist_add_uint64(*config,
4646 				    ZPOOL_CONFIG_SUSPENDED_REASON,
4647 				    spa->spa_suspended) == 0);
4648 			}
4649 
4650 			spa_add_spares(spa, *config);
4651 			spa_add_l2cache(spa, *config);
4652 			spa_add_feature_stats(spa, *config);
4653 		}
4654 	}
4655 
4656 	/*
4657 	 * We want to get the alternate root even for faulted pools, so we cheat
4658 	 * and call spa_lookup() directly.
4659 	 */
4660 	if (altroot) {
4661 		if (spa == NULL) {
4662 			mutex_enter(&spa_namespace_lock);
4663 			spa = spa_lookup(name);
4664 			if (spa)
4665 				spa_altroot(spa, altroot, buflen);
4666 			else
4667 				altroot[0] = '\0';
4668 			spa = NULL;
4669 			mutex_exit(&spa_namespace_lock);
4670 		} else {
4671 			spa_altroot(spa, altroot, buflen);
4672 		}
4673 	}
4674 
4675 	if (spa != NULL) {
4676 		spa_config_exit(spa, SCL_CONFIG, FTAG);
4677 		spa_close(spa, FTAG);
4678 	}
4679 
4680 	return (error);
4681 }
4682 
4683 /*
4684  * Validate that the auxiliary device array is well formed.  We must have an
4685  * array of nvlists, each which describes a valid leaf vdev.  If this is an
4686  * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4687  * specified, as long as they are well-formed.
4688  */
4689 static int
4690 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4691     spa_aux_vdev_t *sav, const char *config, uint64_t version,
4692     vdev_labeltype_t label)
4693 {
4694 	nvlist_t **dev;
4695 	uint_t i, ndev;
4696 	vdev_t *vd;
4697 	int error;
4698 
4699 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4700 
4701 	/*
4702 	 * It's acceptable to have no devs specified.
4703 	 */
4704 	if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4705 		return (0);
4706 
4707 	if (ndev == 0)
4708 		return (SET_ERROR(EINVAL));
4709 
4710 	/*
4711 	 * Make sure the pool is formatted with a version that supports this
4712 	 * device type.
4713 	 */
4714 	if (spa_version(spa) < version)
4715 		return (SET_ERROR(ENOTSUP));
4716 
4717 	/*
4718 	 * Set the pending device list so we correctly handle device in-use
4719 	 * checking.
4720 	 */
4721 	sav->sav_pending = dev;
4722 	sav->sav_npending = ndev;
4723 
4724 	for (i = 0; i < ndev; i++) {
4725 		if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4726 		    mode)) != 0)
4727 			goto out;
4728 
4729 		if (!vd->vdev_ops->vdev_op_leaf) {
4730 			vdev_free(vd);
4731 			error = SET_ERROR(EINVAL);
4732 			goto out;
4733 		}
4734 
4735 		vd->vdev_top = vd;
4736 
4737 		if ((error = vdev_open(vd)) == 0 &&
4738 		    (error = vdev_label_init(vd, crtxg, label)) == 0) {
4739 			VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4740 			    vd->vdev_guid) == 0);
4741 		}
4742 
4743 		vdev_free(vd);
4744 
4745 		if (error &&
4746 		    (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
4747 			goto out;
4748 		else
4749 			error = 0;
4750 	}
4751 
4752 out:
4753 	sav->sav_pending = NULL;
4754 	sav->sav_npending = 0;
4755 	return (error);
4756 }
4757 
4758 static int
4759 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
4760 {
4761 	int error;
4762 
4763 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4764 
4765 	if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4766 	    &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
4767 	    VDEV_LABEL_SPARE)) != 0) {
4768 		return (error);
4769 	}
4770 
4771 	return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4772 	    &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
4773 	    VDEV_LABEL_L2CACHE));
4774 }
4775 
4776 static void
4777 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
4778     const char *config)
4779 {
4780 	int i;
4781 
4782 	if (sav->sav_config != NULL) {
4783 		nvlist_t **olddevs;
4784 		uint_t oldndevs;
4785 		nvlist_t **newdevs;
4786 
4787 		/*
4788 		 * Generate new dev list by concatentating with the
4789 		 * current dev list.
4790 		 */
4791 		VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
4792 		    &olddevs, &oldndevs) == 0);
4793 
4794 		newdevs = kmem_alloc(sizeof (void *) *
4795 		    (ndevs + oldndevs), KM_SLEEP);
4796 		for (i = 0; i < oldndevs; i++)
4797 			VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
4798 			    KM_SLEEP) == 0);
4799 		for (i = 0; i < ndevs; i++)
4800 			VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
4801 			    KM_SLEEP) == 0);
4802 
4803 		VERIFY(nvlist_remove(sav->sav_config, config,
4804 		    DATA_TYPE_NVLIST_ARRAY) == 0);
4805 
4806 		VERIFY(nvlist_add_nvlist_array(sav->sav_config,
4807 		    config, newdevs, ndevs + oldndevs) == 0);
4808 		for (i = 0; i < oldndevs + ndevs; i++)
4809 			nvlist_free(newdevs[i]);
4810 		kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
4811 	} else {
4812 		/*
4813 		 * Generate a new dev list.
4814 		 */
4815 		VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
4816 		    KM_SLEEP) == 0);
4817 		VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
4818 		    devs, ndevs) == 0);
4819 	}
4820 }
4821 
4822 /*
4823  * Stop and drop level 2 ARC devices
4824  */
4825 void
4826 spa_l2cache_drop(spa_t *spa)
4827 {
4828 	vdev_t *vd;
4829 	int i;
4830 	spa_aux_vdev_t *sav = &spa->spa_l2cache;
4831 
4832 	for (i = 0; i < sav->sav_count; i++) {
4833 		uint64_t pool;
4834 
4835 		vd = sav->sav_vdevs[i];
4836 		ASSERT(vd != NULL);
4837 
4838 		if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
4839 		    pool != 0ULL && l2arc_vdev_present(vd))
4840 			l2arc_remove_vdev(vd);
4841 	}
4842 }
4843 
4844 /*
4845  * Verify encryption parameters for spa creation. If we are encrypting, we must
4846  * have the encryption feature flag enabled.
4847  */
4848 static int
4849 spa_create_check_encryption_params(dsl_crypto_params_t *dcp,
4850     boolean_t has_encryption)
4851 {
4852 	if (dcp->cp_crypt != ZIO_CRYPT_OFF &&
4853 	    dcp->cp_crypt != ZIO_CRYPT_INHERIT &&
4854 	    !has_encryption)
4855 		return (SET_ERROR(ENOTSUP));
4856 
4857 	return (dmu_objset_create_crypt_check(NULL, dcp, NULL));
4858 }
4859 
4860 /*
4861  * Pool Creation
4862  */
4863 int
4864 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
4865     nvlist_t *zplprops, dsl_crypto_params_t *dcp)
4866 {
4867 	spa_t *spa;
4868 	char *altroot = NULL;
4869 	vdev_t *rvd;
4870 	dsl_pool_t *dp;
4871 	dmu_tx_t *tx;
4872 	int error = 0;
4873 	uint64_t txg = TXG_INITIAL;
4874 	nvlist_t **spares, **l2cache;
4875 	uint_t nspares, nl2cache;
4876 	uint64_t version, obj;
4877 	boolean_t has_features;
4878 	char *poolname;
4879 	nvlist_t *nvl;
4880 	boolean_t has_encryption;
4881 	spa_feature_t feat;
4882 	char *feat_name;
4883 
4884 	if (props == NULL ||
4885 	    nvlist_lookup_string(props,
4886 	    zpool_prop_to_name(ZPOOL_PROP_TNAME), &poolname) != 0)
4887 		poolname = (char *)pool;
4888 
4889 	/*
4890 	 * If this pool already exists, return failure.
4891 	 */
4892 	mutex_enter(&spa_namespace_lock);
4893 	if (spa_lookup(poolname) != NULL) {
4894 		mutex_exit(&spa_namespace_lock);
4895 		return (SET_ERROR(EEXIST));
4896 	}
4897 
4898 	/*
4899 	 * Allocate a new spa_t structure.
4900 	 */
4901 	nvl = fnvlist_alloc();
4902 	fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
4903 	(void) nvlist_lookup_string(props,
4904 	    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4905 	spa = spa_add(poolname, nvl, altroot);
4906 	fnvlist_free(nvl);
4907 	spa_activate(spa, spa_mode_global);
4908 
4909 	if (props && (error = spa_prop_validate(spa, props))) {
4910 		spa_deactivate(spa);
4911 		spa_remove(spa);
4912 		mutex_exit(&spa_namespace_lock);
4913 		return (error);
4914 	}
4915 
4916 	/*
4917 	 * Temporary pool names should never be written to disk.
4918 	 */
4919 	if (poolname != pool)
4920 		spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
4921 
4922 	has_features = B_FALSE;
4923 	has_encryption = B_FALSE;
4924 	for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
4925 	    elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
4926 		if (zpool_prop_feature(nvpair_name(elem))) {
4927 			has_features = B_TRUE;
4928 			feat_name = strchr(nvpair_name(elem), '@') + 1;
4929 			VERIFY0(zfeature_lookup_name(feat_name, &feat));
4930 			if (feat == SPA_FEATURE_ENCRYPTION)
4931 				has_encryption = B_TRUE;
4932 		}
4933 	}
4934 
4935 	/* verify encryption params, if they were provided */
4936 	if (dcp != NULL) {
4937 		error = spa_create_check_encryption_params(dcp, has_encryption);
4938 		if (error != 0) {
4939 			spa_deactivate(spa);
4940 			spa_remove(spa);
4941 			mutex_exit(&spa_namespace_lock);
4942 			return (error);
4943 		}
4944 	}
4945 
4946 	if (has_features || nvlist_lookup_uint64(props,
4947 	    zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
4948 		version = SPA_VERSION;
4949 	}
4950 	ASSERT(SPA_VERSION_IS_SUPPORTED(version));
4951 
4952 	spa->spa_first_txg = txg;
4953 	spa->spa_uberblock.ub_txg = txg - 1;
4954 	spa->spa_uberblock.ub_version = version;
4955 	spa->spa_ubsync = spa->spa_uberblock;
4956 	spa->spa_load_state = SPA_LOAD_CREATE;
4957 	spa->spa_removing_phys.sr_state = DSS_NONE;
4958 	spa->spa_removing_phys.sr_removing_vdev = -1;
4959 	spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
4960 	spa->spa_indirect_vdevs_loaded = B_TRUE;
4961 
4962 	/*
4963 	 * Create "The Godfather" zio to hold all async IOs
4964 	 */
4965 	spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
4966 	    KM_SLEEP);
4967 	for (int i = 0; i < max_ncpus; i++) {
4968 		spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
4969 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4970 		    ZIO_FLAG_GODFATHER);
4971 	}
4972 
4973 	/*
4974 	 * Create the root vdev.
4975 	 */
4976 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4977 
4978 	error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
4979 
4980 	ASSERT(error != 0 || rvd != NULL);
4981 	ASSERT(error != 0 || spa->spa_root_vdev == rvd);
4982 
4983 	if (error == 0 && !zfs_allocatable_devs(nvroot))
4984 		error = SET_ERROR(EINVAL);
4985 
4986 	if (error == 0 &&
4987 	    (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
4988 	    (error = spa_validate_aux(spa, nvroot, txg,
4989 	    VDEV_ALLOC_ADD)) == 0) {
4990 		/*
4991 		 * instantiate the metaslab groups (this will dirty the vdevs)
4992 		 * we can no longer error exit past this point
4993 		 */
4994 		for (int c = 0; error == 0 && c < rvd->vdev_children; c++) {
4995 			vdev_t *vd = rvd->vdev_child[c];
4996 
4997 			vdev_metaslab_set_size(vd);
4998 			vdev_expand(vd, txg);
4999 		}
5000 	}
5001 
5002 	spa_config_exit(spa, SCL_ALL, FTAG);
5003 
5004 	if (error != 0) {
5005 		spa_unload(spa);
5006 		spa_deactivate(spa);
5007 		spa_remove(spa);
5008 		mutex_exit(&spa_namespace_lock);
5009 		return (error);
5010 	}
5011 
5012 	/*
5013 	 * Get the list of spares, if specified.
5014 	 */
5015 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5016 	    &spares, &nspares) == 0) {
5017 		VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
5018 		    KM_SLEEP) == 0);
5019 		VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5020 		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5021 		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5022 		spa_load_spares(spa);
5023 		spa_config_exit(spa, SCL_ALL, FTAG);
5024 		spa->spa_spares.sav_sync = B_TRUE;
5025 	}
5026 
5027 	/*
5028 	 * Get the list of level 2 cache devices, if specified.
5029 	 */
5030 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5031 	    &l2cache, &nl2cache) == 0) {
5032 		VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5033 		    NV_UNIQUE_NAME, KM_SLEEP) == 0);
5034 		VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5035 		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5036 		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5037 		spa_load_l2cache(spa);
5038 		spa_config_exit(spa, SCL_ALL, FTAG);
5039 		spa->spa_l2cache.sav_sync = B_TRUE;
5040 	}
5041 
5042 	spa->spa_is_initializing = B_TRUE;
5043 	spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, dcp, txg);
5044 	spa->spa_is_initializing = B_FALSE;
5045 
5046 	/*
5047 	 * Create DDTs (dedup tables).
5048 	 */
5049 	ddt_create(spa);
5050 
5051 	spa_update_dspace(spa);
5052 
5053 	tx = dmu_tx_create_assigned(dp, txg);
5054 
5055 	/*
5056 	 * Create the pool config object.
5057 	 */
5058 	spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
5059 	    DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
5060 	    DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
5061 
5062 	if (zap_add(spa->spa_meta_objset,
5063 	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
5064 	    sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
5065 		cmn_err(CE_PANIC, "failed to add pool config");
5066 	}
5067 
5068 	if (zap_add(spa->spa_meta_objset,
5069 	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
5070 	    sizeof (uint64_t), 1, &version, tx) != 0) {
5071 		cmn_err(CE_PANIC, "failed to add pool version");
5072 	}
5073 
5074 	/* Newly created pools with the right version are always deflated. */
5075 	if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
5076 		spa->spa_deflate = TRUE;
5077 		if (zap_add(spa->spa_meta_objset,
5078 		    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
5079 		    sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
5080 			cmn_err(CE_PANIC, "failed to add deflate");
5081 		}
5082 	}
5083 
5084 	/*
5085 	 * Create the deferred-free bpobj.  Turn off compression
5086 	 * because sync-to-convergence takes longer if the blocksize
5087 	 * keeps changing.
5088 	 */
5089 	obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
5090 	dmu_object_set_compress(spa->spa_meta_objset, obj,
5091 	    ZIO_COMPRESS_OFF, tx);
5092 	if (zap_add(spa->spa_meta_objset,
5093 	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
5094 	    sizeof (uint64_t), 1, &obj, tx) != 0) {
5095 		cmn_err(CE_PANIC, "failed to add bpobj");
5096 	}
5097 	VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
5098 	    spa->spa_meta_objset, obj));
5099 
5100 	/*
5101 	 * Create the pool's history object.
5102 	 */
5103 	if (version >= SPA_VERSION_ZPOOL_HISTORY)
5104 		spa_history_create_obj(spa, tx);
5105 
5106 	/*
5107 	 * Generate some random noise for salted checksums to operate on.
5108 	 */
5109 	(void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
5110 	    sizeof (spa->spa_cksum_salt.zcs_bytes));
5111 
5112 	/*
5113 	 * Set pool properties.
5114 	 */
5115 	spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
5116 	spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
5117 	spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
5118 	spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
5119 	spa->spa_multihost = zpool_prop_default_numeric(ZPOOL_PROP_MULTIHOST);
5120 
5121 	if (props != NULL) {
5122 		spa_configfile_set(spa, props, B_FALSE);
5123 		spa_sync_props(props, tx);
5124 	}
5125 
5126 	dmu_tx_commit(tx);
5127 
5128 	spa->spa_sync_on = B_TRUE;
5129 	txg_sync_start(spa->spa_dsl_pool);
5130 	mmp_thread_start(spa);
5131 
5132 	/*
5133 	 * We explicitly wait for the first transaction to complete so that our
5134 	 * bean counters are appropriately updated.
5135 	 */
5136 	txg_wait_synced(spa->spa_dsl_pool, txg);
5137 
5138 	spa_spawn_aux_threads(spa);
5139 
5140 	spa_write_cachefile(spa, B_FALSE, B_TRUE);
5141 	spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
5142 
5143 	spa_history_log_version(spa, "create");
5144 
5145 	/*
5146 	 * Don't count references from objsets that are already closed
5147 	 * and are making their way through the eviction process.
5148 	 */
5149 	spa_evicting_os_wait(spa);
5150 	spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
5151 	spa->spa_load_state = SPA_LOAD_NONE;
5152 
5153 	mutex_exit(&spa_namespace_lock);
5154 
5155 	return (0);
5156 }
5157 
5158 #ifdef _KERNEL
5159 /*
5160  * Get the root pool information from the root disk, then import the root pool
5161  * during the system boot up time.
5162  */
5163 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
5164 
5165 static nvlist_t *
5166 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
5167 {
5168 	nvlist_t *config;
5169 	nvlist_t *nvtop, *nvroot;
5170 	uint64_t pgid;
5171 
5172 	if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
5173 		return (NULL);
5174 
5175 	/*
5176 	 * Add this top-level vdev to the child array.
5177 	 */
5178 	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5179 	    &nvtop) == 0);
5180 	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5181 	    &pgid) == 0);
5182 	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
5183 
5184 	/*
5185 	 * Put this pool's top-level vdevs into a root vdev.
5186 	 */
5187 	VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5188 	VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5189 	    VDEV_TYPE_ROOT) == 0);
5190 	VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5191 	VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5192 	VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5193 	    &nvtop, 1) == 0);
5194 
5195 	/*
5196 	 * Replace the existing vdev_tree with the new root vdev in
5197 	 * this pool's configuration (remove the old, add the new).
5198 	 */
5199 	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5200 	nvlist_free(nvroot);
5201 	return (config);
5202 }
5203 
5204 /*
5205  * Walk the vdev tree and see if we can find a device with "better"
5206  * configuration. A configuration is "better" if the label on that
5207  * device has a more recent txg.
5208  */
5209 static void
5210 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
5211 {
5212 	for (int c = 0; c < vd->vdev_children; c++)
5213 		spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
5214 
5215 	if (vd->vdev_ops->vdev_op_leaf) {
5216 		nvlist_t *label;
5217 		uint64_t label_txg;
5218 
5219 		if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
5220 		    &label) != 0)
5221 			return;
5222 
5223 		VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
5224 		    &label_txg) == 0);
5225 
5226 		/*
5227 		 * Do we have a better boot device?
5228 		 */
5229 		if (label_txg > *txg) {
5230 			*txg = label_txg;
5231 			*avd = vd;
5232 		}
5233 		nvlist_free(label);
5234 	}
5235 }
5236 
5237 /*
5238  * Import a root pool.
5239  *
5240  * For x86. devpath_list will consist of devid and/or physpath name of
5241  * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
5242  * The GRUB "findroot" command will return the vdev we should boot.
5243  *
5244  * For Sparc, devpath_list consists the physpath name of the booting device
5245  * no matter the rootpool is a single device pool or a mirrored pool.
5246  * e.g.
5247  *	"/pci@1f,0/ide@d/disk@0,0:a"
5248  */
5249 int
5250 spa_import_rootpool(char *devpath, char *devid)
5251 {
5252 	spa_t *spa;
5253 	vdev_t *rvd, *bvd, *avd = NULL;
5254 	nvlist_t *config, *nvtop;
5255 	uint64_t guid, txg;
5256 	char *pname;
5257 	int error;
5258 
5259 	/*
5260 	 * Read the label from the boot device and generate a configuration.
5261 	 */
5262 	config = spa_generate_rootconf(devpath, devid, &guid);
5263 #if defined(_OBP) && defined(_KERNEL)
5264 	if (config == NULL) {
5265 		if (strstr(devpath, "/iscsi/ssd") != NULL) {
5266 			/* iscsi boot */
5267 			get_iscsi_bootpath_phy(devpath);
5268 			config = spa_generate_rootconf(devpath, devid, &guid);
5269 		}
5270 	}
5271 #endif
5272 	if (config == NULL) {
5273 		cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
5274 		    devpath);
5275 		return (SET_ERROR(EIO));
5276 	}
5277 
5278 	VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5279 	    &pname) == 0);
5280 	VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
5281 
5282 	mutex_enter(&spa_namespace_lock);
5283 	if ((spa = spa_lookup(pname)) != NULL) {
5284 		/*
5285 		 * Remove the existing root pool from the namespace so that we
5286 		 * can replace it with the correct config we just read in.
5287 		 */
5288 		spa_remove(spa);
5289 	}
5290 
5291 	spa = spa_add(pname, config, NULL);
5292 	spa->spa_is_root = B_TRUE;
5293 	spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5294 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5295 	    &spa->spa_ubsync.ub_version) != 0)
5296 		spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5297 
5298 	/*
5299 	 * Build up a vdev tree based on the boot device's label config.
5300 	 */
5301 	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5302 	    &nvtop) == 0);
5303 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5304 	error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5305 	    VDEV_ALLOC_ROOTPOOL);
5306 	spa_config_exit(spa, SCL_ALL, FTAG);
5307 	if (error) {
5308 		mutex_exit(&spa_namespace_lock);
5309 		nvlist_free(config);
5310 		cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5311 		    pname);
5312 		return (error);
5313 	}
5314 
5315 	/*
5316 	 * Get the boot vdev.
5317 	 */
5318 	if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
5319 		cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
5320 		    (u_longlong_t)guid);
5321 		error = SET_ERROR(ENOENT);
5322 		goto out;
5323 	}
5324 
5325 	/*
5326 	 * Determine if there is a better boot device.
5327 	 */
5328 	avd = bvd;
5329 	spa_alt_rootvdev(rvd, &avd, &txg);
5330 	if (avd != bvd) {
5331 		cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
5332 		    "try booting from '%s'", avd->vdev_path);
5333 		error = SET_ERROR(EINVAL);
5334 		goto out;
5335 	}
5336 
5337 	/*
5338 	 * If the boot device is part of a spare vdev then ensure that
5339 	 * we're booting off the active spare.
5340 	 */
5341 	if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
5342 	    !bvd->vdev_isspare) {
5343 		cmn_err(CE_NOTE, "The boot device is currently spared. Please "
5344 		    "try booting from '%s'",
5345 		    bvd->vdev_parent->
5346 		    vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
5347 		error = SET_ERROR(EINVAL);
5348 		goto out;
5349 	}
5350 
5351 	error = 0;
5352 out:
5353 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5354 	vdev_free(rvd);
5355 	spa_config_exit(spa, SCL_ALL, FTAG);
5356 	mutex_exit(&spa_namespace_lock);
5357 
5358 	nvlist_free(config);
5359 	return (error);
5360 }
5361 
5362 #endif
5363 
5364 /*
5365  * Import a non-root pool into the system.
5366  */
5367 int
5368 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5369 {
5370 	spa_t *spa;
5371 	char *altroot = NULL;
5372 	spa_load_state_t state = SPA_LOAD_IMPORT;
5373 	zpool_load_policy_t policy;
5374 	uint64_t mode = spa_mode_global;
5375 	uint64_t readonly = B_FALSE;
5376 	int error;
5377 	nvlist_t *nvroot;
5378 	nvlist_t **spares, **l2cache;
5379 	uint_t nspares, nl2cache;
5380 
5381 	/*
5382 	 * If a pool with this name exists, return failure.
5383 	 */
5384 	mutex_enter(&spa_namespace_lock);
5385 	if (spa_lookup(pool) != NULL) {
5386 		mutex_exit(&spa_namespace_lock);
5387 		return (SET_ERROR(EEXIST));
5388 	}
5389 
5390 	/*
5391 	 * Create and initialize the spa structure.
5392 	 */
5393 	(void) nvlist_lookup_string(props,
5394 	    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5395 	(void) nvlist_lookup_uint64(props,
5396 	    zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5397 	if (readonly)
5398 		mode = FREAD;
5399 	spa = spa_add(pool, config, altroot);
5400 	spa->spa_import_flags = flags;
5401 
5402 	/*
5403 	 * Verbatim import - Take a pool and insert it into the namespace
5404 	 * as if it had been loaded at boot.
5405 	 */
5406 	if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5407 		if (props != NULL)
5408 			spa_configfile_set(spa, props, B_FALSE);
5409 
5410 		spa_write_cachefile(spa, B_FALSE, B_TRUE);
5411 		spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5412 		zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5413 		mutex_exit(&spa_namespace_lock);
5414 		return (0);
5415 	}
5416 
5417 	spa_activate(spa, mode);
5418 
5419 	/*
5420 	 * Don't start async tasks until we know everything is healthy.
5421 	 */
5422 	spa_async_suspend(spa);
5423 
5424 	zpool_get_load_policy(config, &policy);
5425 	if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5426 		state = SPA_LOAD_RECOVER;
5427 
5428 	spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5429 
5430 	if (state != SPA_LOAD_RECOVER) {
5431 		spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5432 		zfs_dbgmsg("spa_import: importing %s", pool);
5433 	} else {
5434 		zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5435 		    "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
5436 	}
5437 	error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
5438 
5439 	/*
5440 	 * Propagate anything learned while loading the pool and pass it
5441 	 * back to caller (i.e. rewind info, missing devices, etc).
5442 	 */
5443 	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5444 	    spa->spa_load_info) == 0);
5445 
5446 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5447 	/*
5448 	 * Toss any existing sparelist, as it doesn't have any validity
5449 	 * anymore, and conflicts with spa_has_spare().
5450 	 */
5451 	if (spa->spa_spares.sav_config) {
5452 		nvlist_free(spa->spa_spares.sav_config);
5453 		spa->spa_spares.sav_config = NULL;
5454 		spa_load_spares(spa);
5455 	}
5456 	if (spa->spa_l2cache.sav_config) {
5457 		nvlist_free(spa->spa_l2cache.sav_config);
5458 		spa->spa_l2cache.sav_config = NULL;
5459 		spa_load_l2cache(spa);
5460 	}
5461 
5462 	VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5463 	    &nvroot) == 0);
5464 	if (error == 0)
5465 		error = spa_validate_aux(spa, nvroot, -1ULL,
5466 		    VDEV_ALLOC_SPARE);
5467 	if (error == 0)
5468 		error = spa_validate_aux(spa, nvroot, -1ULL,
5469 		    VDEV_ALLOC_L2CACHE);
5470 	spa_config_exit(spa, SCL_ALL, FTAG);
5471 
5472 	if (props != NULL)
5473 		spa_configfile_set(spa, props, B_FALSE);
5474 
5475 	if (error != 0 || (props && spa_writeable(spa) &&
5476 	    (error = spa_prop_set(spa, props)))) {
5477 		spa_unload(spa);
5478 		spa_deactivate(spa);
5479 		spa_remove(spa);
5480 		mutex_exit(&spa_namespace_lock);
5481 		return (error);
5482 	}
5483 
5484 	spa_async_resume(spa);
5485 
5486 	/*
5487 	 * Override any spares and level 2 cache devices as specified by
5488 	 * the user, as these may have correct device names/devids, etc.
5489 	 */
5490 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5491 	    &spares, &nspares) == 0) {
5492 		if (spa->spa_spares.sav_config)
5493 			VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5494 			    ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5495 		else
5496 			VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5497 			    NV_UNIQUE_NAME, KM_SLEEP) == 0);
5498 		VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5499 		    ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5500 		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5501 		spa_load_spares(spa);
5502 		spa_config_exit(spa, SCL_ALL, FTAG);
5503 		spa->spa_spares.sav_sync = B_TRUE;
5504 	}
5505 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5506 	    &l2cache, &nl2cache) == 0) {
5507 		if (spa->spa_l2cache.sav_config)
5508 			VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5509 			    ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5510 		else
5511 			VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5512 			    NV_UNIQUE_NAME, KM_SLEEP) == 0);
5513 		VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5514 		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5515 		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5516 		spa_load_l2cache(spa);
5517 		spa_config_exit(spa, SCL_ALL, FTAG);
5518 		spa->spa_l2cache.sav_sync = B_TRUE;
5519 	}
5520 
5521 	/*
5522 	 * Check for any removed devices.
5523 	 */
5524 	if (spa->spa_autoreplace) {
5525 		spa_aux_check_removed(&spa->spa_spares);
5526 		spa_aux_check_removed(&spa->spa_l2cache);
5527 	}
5528 
5529 	if (spa_writeable(spa)) {
5530 		/*
5531 		 * Update the config cache to include the newly-imported pool.
5532 		 */
5533 		spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5534 	}
5535 
5536 	/*
5537 	 * It's possible that the pool was expanded while it was exported.
5538 	 * We kick off an async task to handle this for us.
5539 	 */
5540 	spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5541 
5542 	spa_history_log_version(spa, "import");
5543 
5544 	spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5545 
5546 	mutex_exit(&spa_namespace_lock);
5547 
5548 	return (0);
5549 }
5550 
5551 nvlist_t *
5552 spa_tryimport(nvlist_t *tryconfig)
5553 {
5554 	nvlist_t *config = NULL;
5555 	char *poolname, *cachefile;
5556 	spa_t *spa;
5557 	uint64_t state;
5558 	int error;
5559 	zpool_load_policy_t policy;
5560 
5561 	if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5562 		return (NULL);
5563 
5564 	if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5565 		return (NULL);
5566 
5567 	/*
5568 	 * Create and initialize the spa structure.
5569 	 */
5570 	mutex_enter(&spa_namespace_lock);
5571 	spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
5572 	spa_activate(spa, FREAD);
5573 
5574 	/*
5575 	 * Rewind pool if a max txg was provided.
5576 	 */
5577 	zpool_get_load_policy(spa->spa_config, &policy);
5578 	if (policy.zlp_txg != UINT64_MAX) {
5579 		spa->spa_load_max_txg = policy.zlp_txg;
5580 		spa->spa_extreme_rewind = B_TRUE;
5581 		zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
5582 		    poolname, (longlong_t)policy.zlp_txg);
5583 	} else {
5584 		zfs_dbgmsg("spa_tryimport: importing %s", poolname);
5585 	}
5586 
5587 	if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
5588 	    == 0) {
5589 		zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
5590 		spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5591 	} else {
5592 		spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
5593 	}
5594 
5595 	error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
5596 
5597 	/*
5598 	 * If 'tryconfig' was at least parsable, return the current config.
5599 	 */
5600 	if (spa->spa_root_vdev != NULL) {
5601 		config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5602 		VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
5603 		    poolname) == 0);
5604 		VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5605 		    state) == 0);
5606 		VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
5607 		    spa->spa_uberblock.ub_timestamp) == 0);
5608 		VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5609 		    spa->spa_load_info) == 0);
5610 
5611 		/*
5612 		 * If the bootfs property exists on this pool then we
5613 		 * copy it out so that external consumers can tell which
5614 		 * pools are bootable.
5615 		 */
5616 		if ((!error || error == EEXIST) && spa->spa_bootfs) {
5617 			char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5618 
5619 			/*
5620 			 * We have to play games with the name since the
5621 			 * pool was opened as TRYIMPORT_NAME.
5622 			 */
5623 			if (dsl_dsobj_to_dsname(spa_name(spa),
5624 			    spa->spa_bootfs, tmpname) == 0) {
5625 				char *cp;
5626 				char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5627 
5628 				cp = strchr(tmpname, '/');
5629 				if (cp == NULL) {
5630 					(void) strlcpy(dsname, tmpname,
5631 					    MAXPATHLEN);
5632 				} else {
5633 					(void) snprintf(dsname, MAXPATHLEN,
5634 					    "%s/%s", poolname, ++cp);
5635 				}
5636 				VERIFY(nvlist_add_string(config,
5637 				    ZPOOL_CONFIG_BOOTFS, dsname) == 0);
5638 				kmem_free(dsname, MAXPATHLEN);
5639 			}
5640 			kmem_free(tmpname, MAXPATHLEN);
5641 		}
5642 
5643 		/*
5644 		 * Add the list of hot spares and level 2 cache devices.
5645 		 */
5646 		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5647 		spa_add_spares(spa, config);
5648 		spa_add_l2cache(spa, config);
5649 		spa_config_exit(spa, SCL_CONFIG, FTAG);
5650 	}
5651 
5652 	spa_unload(spa);
5653 	spa_deactivate(spa);
5654 	spa_remove(spa);
5655 	mutex_exit(&spa_namespace_lock);
5656 
5657 	return (config);
5658 }
5659 
5660 /*
5661  * Pool export/destroy
5662  *
5663  * The act of destroying or exporting a pool is very simple.  We make sure there
5664  * is no more pending I/O and any references to the pool are gone.  Then, we
5665  * update the pool state and sync all the labels to disk, removing the
5666  * configuration from the cache afterwards. If the 'hardforce' flag is set, then
5667  * we don't sync the labels or remove the configuration cache.
5668  */
5669 static int
5670 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
5671     boolean_t force, boolean_t hardforce)
5672 {
5673 	spa_t *spa;
5674 
5675 	if (oldconfig)
5676 		*oldconfig = NULL;
5677 
5678 	if (!(spa_mode_global & FWRITE))
5679 		return (SET_ERROR(EROFS));
5680 
5681 	mutex_enter(&spa_namespace_lock);
5682 	if ((spa = spa_lookup(pool)) == NULL) {
5683 		mutex_exit(&spa_namespace_lock);
5684 		return (SET_ERROR(ENOENT));
5685 	}
5686 
5687 	/*
5688 	 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5689 	 * reacquire the namespace lock, and see if we can export.
5690 	 */
5691 	spa_open_ref(spa, FTAG);
5692 	mutex_exit(&spa_namespace_lock);
5693 	spa_async_suspend(spa);
5694 	mutex_enter(&spa_namespace_lock);
5695 	spa_close(spa, FTAG);
5696 
5697 	/*
5698 	 * The pool will be in core if it's openable,
5699 	 * in which case we can modify its state.
5700 	 */
5701 	if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
5702 
5703 		/*
5704 		 * Objsets may be open only because they're dirty, so we
5705 		 * have to force it to sync before checking spa_refcnt.
5706 		 */
5707 		txg_wait_synced(spa->spa_dsl_pool, 0);
5708 		spa_evicting_os_wait(spa);
5709 
5710 		/*
5711 		 * A pool cannot be exported or destroyed if there are active
5712 		 * references.  If we are resetting a pool, allow references by
5713 		 * fault injection handlers.
5714 		 */
5715 		if (!spa_refcount_zero(spa) ||
5716 		    (spa->spa_inject_ref != 0 &&
5717 		    new_state != POOL_STATE_UNINITIALIZED)) {
5718 			spa_async_resume(spa);
5719 			mutex_exit(&spa_namespace_lock);
5720 			return (SET_ERROR(EBUSY));
5721 		}
5722 
5723 		/*
5724 		 * A pool cannot be exported if it has an active shared spare.
5725 		 * This is to prevent other pools stealing the active spare
5726 		 * from an exported pool. At user's own will, such pool can
5727 		 * be forcedly exported.
5728 		 */
5729 		if (!force && new_state == POOL_STATE_EXPORTED &&
5730 		    spa_has_active_shared_spare(spa)) {
5731 			spa_async_resume(spa);
5732 			mutex_exit(&spa_namespace_lock);
5733 			return (SET_ERROR(EXDEV));
5734 		}
5735 
5736 		/*
5737 		 * We're about to export or destroy this pool. Make sure
5738 		 * we stop all initializtion activity here before we
5739 		 * set the spa_final_txg. This will ensure that all
5740 		 * dirty data resulting from the initialization is
5741 		 * committed to disk before we unload the pool.
5742 		 */
5743 		if (spa->spa_root_vdev != NULL) {
5744 			vdev_initialize_stop_all(spa->spa_root_vdev,
5745 			    VDEV_INITIALIZE_ACTIVE);
5746 		}
5747 
5748 		/*
5749 		 * We want this to be reflected on every label,
5750 		 * so mark them all dirty.  spa_unload() will do the
5751 		 * final sync that pushes these changes out.
5752 		 */
5753 		if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
5754 			spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5755 			spa->spa_state = new_state;
5756 			spa->spa_final_txg = spa_last_synced_txg(spa) +
5757 			    TXG_DEFER_SIZE + 1;
5758 			vdev_config_dirty(spa->spa_root_vdev);
5759 			spa_config_exit(spa, SCL_ALL, FTAG);
5760 		}
5761 	}
5762 
5763 	spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
5764 
5765 	if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
5766 		spa_unload(spa);
5767 		spa_deactivate(spa);
5768 	}
5769 
5770 	if (oldconfig && spa->spa_config)
5771 		VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
5772 
5773 	if (new_state != POOL_STATE_UNINITIALIZED) {
5774 		if (!hardforce)
5775 			spa_write_cachefile(spa, B_TRUE, B_TRUE);
5776 		spa_remove(spa);
5777 	}
5778 	mutex_exit(&spa_namespace_lock);
5779 
5780 	return (0);
5781 }
5782 
5783 /*
5784  * Destroy a storage pool.
5785  */
5786 int
5787 spa_destroy(char *pool)
5788 {
5789 	return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
5790 	    B_FALSE, B_FALSE));
5791 }
5792 
5793 /*
5794  * Export a storage pool.
5795  */
5796 int
5797 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
5798     boolean_t hardforce)
5799 {
5800 	return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
5801 	    force, hardforce));
5802 }
5803 
5804 /*
5805  * Similar to spa_export(), this unloads the spa_t without actually removing it
5806  * from the namespace in any way.
5807  */
5808 int
5809 spa_reset(char *pool)
5810 {
5811 	return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
5812 	    B_FALSE, B_FALSE));
5813 }
5814 
5815 /*
5816  * ==========================================================================
5817  * Device manipulation
5818  * ==========================================================================
5819  */
5820 
5821 /*
5822  * Add a device to a storage pool.
5823  */
5824 int
5825 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
5826 {
5827 	uint64_t txg, id;
5828 	int error;
5829 	vdev_t *rvd = spa->spa_root_vdev;
5830 	vdev_t *vd, *tvd;
5831 	nvlist_t **spares, **l2cache;
5832 	uint_t nspares, nl2cache;
5833 
5834 	ASSERT(spa_writeable(spa));
5835 
5836 	txg = spa_vdev_enter(spa);
5837 
5838 	if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
5839 	    VDEV_ALLOC_ADD)) != 0)
5840 		return (spa_vdev_exit(spa, NULL, txg, error));
5841 
5842 	spa->spa_pending_vdev = vd;	/* spa_vdev_exit() will clear this */
5843 
5844 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
5845 	    &nspares) != 0)
5846 		nspares = 0;
5847 
5848 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
5849 	    &nl2cache) != 0)
5850 		nl2cache = 0;
5851 
5852 	if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
5853 		return (spa_vdev_exit(spa, vd, txg, EINVAL));
5854 
5855 	if (vd->vdev_children != 0 &&
5856 	    (error = vdev_create(vd, txg, B_FALSE)) != 0)
5857 		return (spa_vdev_exit(spa, vd, txg, error));
5858 
5859 	/*
5860 	 * We must validate the spares and l2cache devices after checking the
5861 	 * children.  Otherwise, vdev_inuse() will blindly overwrite the spare.
5862 	 */
5863 	if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
5864 		return (spa_vdev_exit(spa, vd, txg, error));
5865 
5866 	/*
5867 	 * If we are in the middle of a device removal, we can only add
5868 	 * devices which match the existing devices in the pool.
5869 	 * If we are in the middle of a removal, or have some indirect
5870 	 * vdevs, we can not add raidz toplevels.
5871 	 */
5872 	if (spa->spa_vdev_removal != NULL ||
5873 	    spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
5874 		for (int c = 0; c < vd->vdev_children; c++) {
5875 			tvd = vd->vdev_child[c];
5876 			if (spa->spa_vdev_removal != NULL &&
5877 			    tvd->vdev_ashift != spa->spa_max_ashift) {
5878 				return (spa_vdev_exit(spa, vd, txg, EINVAL));
5879 			}
5880 			/* Fail if top level vdev is raidz */
5881 			if (tvd->vdev_ops == &vdev_raidz_ops) {
5882 				return (spa_vdev_exit(spa, vd, txg, EINVAL));
5883 			}
5884 			/*
5885 			 * Need the top level mirror to be
5886 			 * a mirror of leaf vdevs only
5887 			 */
5888 			if (tvd->vdev_ops == &vdev_mirror_ops) {
5889 				for (uint64_t cid = 0;
5890 				    cid < tvd->vdev_children; cid++) {
5891 					vdev_t *cvd = tvd->vdev_child[cid];
5892 					if (!cvd->vdev_ops->vdev_op_leaf) {
5893 						return (spa_vdev_exit(spa, vd,
5894 						    txg, EINVAL));
5895 					}
5896 				}
5897 			}
5898 		}
5899 	}
5900 
5901 	for (int c = 0; c < vd->vdev_children; c++) {
5902 
5903 		/*
5904 		 * Set the vdev id to the first hole, if one exists.
5905 		 */
5906 		for (id = 0; id < rvd->vdev_children; id++) {
5907 			if (rvd->vdev_child[id]->vdev_ishole) {
5908 				vdev_free(rvd->vdev_child[id]);
5909 				break;
5910 			}
5911 		}
5912 		tvd = vd->vdev_child[c];
5913 		vdev_remove_child(vd, tvd);
5914 		tvd->vdev_id = id;
5915 		vdev_add_child(rvd, tvd);
5916 		vdev_config_dirty(tvd);
5917 	}
5918 
5919 	if (nspares != 0) {
5920 		spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
5921 		    ZPOOL_CONFIG_SPARES);
5922 		spa_load_spares(spa);
5923 		spa->spa_spares.sav_sync = B_TRUE;
5924 	}
5925 
5926 	if (nl2cache != 0) {
5927 		spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
5928 		    ZPOOL_CONFIG_L2CACHE);
5929 		spa_load_l2cache(spa);
5930 		spa->spa_l2cache.sav_sync = B_TRUE;
5931 	}
5932 
5933 	/*
5934 	 * We have to be careful when adding new vdevs to an existing pool.
5935 	 * If other threads start allocating from these vdevs before we
5936 	 * sync the config cache, and we lose power, then upon reboot we may
5937 	 * fail to open the pool because there are DVAs that the config cache
5938 	 * can't translate.  Therefore, we first add the vdevs without
5939 	 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
5940 	 * and then let spa_config_update() initialize the new metaslabs.
5941 	 *
5942 	 * spa_load() checks for added-but-not-initialized vdevs, so that
5943 	 * if we lose power at any point in this sequence, the remaining
5944 	 * steps will be completed the next time we load the pool.
5945 	 */
5946 	(void) spa_vdev_exit(spa, vd, txg, 0);
5947 
5948 	mutex_enter(&spa_namespace_lock);
5949 	spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5950 	spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
5951 	mutex_exit(&spa_namespace_lock);
5952 
5953 	return (0);
5954 }
5955 
5956 /*
5957  * Attach a device to a mirror.  The arguments are the path to any device
5958  * in the mirror, and the nvroot for the new device.  If the path specifies
5959  * a device that is not mirrored, we automatically insert the mirror vdev.
5960  *
5961  * If 'replacing' is specified, the new device is intended to replace the
5962  * existing device; in this case the two devices are made into their own
5963  * mirror using the 'replacing' vdev, which is functionally identical to
5964  * the mirror vdev (it actually reuses all the same ops) but has a few
5965  * extra rules: you can't attach to it after it's been created, and upon
5966  * completion of resilvering, the first disk (the one being replaced)
5967  * is automatically detached.
5968  */
5969 int
5970 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
5971 {
5972 	uint64_t txg, dtl_max_txg;
5973 	vdev_t *rvd = spa->spa_root_vdev;
5974 	vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
5975 	vdev_ops_t *pvops;
5976 	char *oldvdpath, *newvdpath;
5977 	int newvd_isspare;
5978 	int error;
5979 
5980 	ASSERT(spa_writeable(spa));
5981 
5982 	txg = spa_vdev_enter(spa);
5983 
5984 	oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
5985 
5986 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
5987 	if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
5988 		error = (spa_has_checkpoint(spa)) ?
5989 		    ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
5990 		return (spa_vdev_exit(spa, NULL, txg, error));
5991 	}
5992 
5993 	if (spa->spa_vdev_removal != NULL)
5994 		return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5995 
5996 	if (oldvd == NULL)
5997 		return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5998 
5999 	if (!oldvd->vdev_ops->vdev_op_leaf)
6000 		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6001 
6002 	pvd = oldvd->vdev_parent;
6003 
6004 	if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
6005 	    VDEV_ALLOC_ATTACH)) != 0)
6006 		return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6007 
6008 	if (newrootvd->vdev_children != 1)
6009 		return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6010 
6011 	newvd = newrootvd->vdev_child[0];
6012 
6013 	if (!newvd->vdev_ops->vdev_op_leaf)
6014 		return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6015 
6016 	if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
6017 		return (spa_vdev_exit(spa, newrootvd, txg, error));
6018 
6019 	/*
6020 	 * Spares can't replace logs
6021 	 */
6022 	if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
6023 		return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6024 
6025 	if (!replacing) {
6026 		/*
6027 		 * For attach, the only allowable parent is a mirror or the root
6028 		 * vdev.
6029 		 */
6030 		if (pvd->vdev_ops != &vdev_mirror_ops &&
6031 		    pvd->vdev_ops != &vdev_root_ops)
6032 			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6033 
6034 		pvops = &vdev_mirror_ops;
6035 	} else {
6036 		/*
6037 		 * Active hot spares can only be replaced by inactive hot
6038 		 * spares.
6039 		 */
6040 		if (pvd->vdev_ops == &vdev_spare_ops &&
6041 		    oldvd->vdev_isspare &&
6042 		    !spa_has_spare(spa, newvd->vdev_guid))
6043 			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6044 
6045 		/*
6046 		 * If the source is a hot spare, and the parent isn't already a
6047 		 * spare, then we want to create a new hot spare.  Otherwise, we
6048 		 * want to create a replacing vdev.  The user is not allowed to
6049 		 * attach to a spared vdev child unless the 'isspare' state is
6050 		 * the same (spare replaces spare, non-spare replaces
6051 		 * non-spare).
6052 		 */
6053 		if (pvd->vdev_ops == &vdev_replacing_ops &&
6054 		    spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6055 			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6056 		} else if (pvd->vdev_ops == &vdev_spare_ops &&
6057 		    newvd->vdev_isspare != oldvd->vdev_isspare) {
6058 			return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6059 		}
6060 
6061 		if (newvd->vdev_isspare)
6062 			pvops = &vdev_spare_ops;
6063 		else
6064 			pvops = &vdev_replacing_ops;
6065 	}
6066 
6067 	/*
6068 	 * Make sure the new device is big enough.
6069 	 */
6070 	if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6071 		return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6072 
6073 	/*
6074 	 * The new device cannot have a higher alignment requirement
6075 	 * than the top-level vdev.
6076 	 */
6077 	if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6078 		return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6079 
6080 	/*
6081 	 * If this is an in-place replacement, update oldvd's path and devid
6082 	 * to make it distinguishable from newvd, and unopenable from now on.
6083 	 */
6084 	if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6085 		spa_strfree(oldvd->vdev_path);
6086 		oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6087 		    KM_SLEEP);
6088 		(void) sprintf(oldvd->vdev_path, "%s/%s",
6089 		    newvd->vdev_path, "old");
6090 		if (oldvd->vdev_devid != NULL) {
6091 			spa_strfree(oldvd->vdev_devid);
6092 			oldvd->vdev_devid = NULL;
6093 		}
6094 	}
6095 
6096 	/* mark the device being resilvered */
6097 	newvd->vdev_resilver_txg = txg;
6098 
6099 	/*
6100 	 * If the parent is not a mirror, or if we're replacing, insert the new
6101 	 * mirror/replacing/spare vdev above oldvd.
6102 	 */
6103 	if (pvd->vdev_ops != pvops)
6104 		pvd = vdev_add_parent(oldvd, pvops);
6105 
6106 	ASSERT(pvd->vdev_top->vdev_parent == rvd);
6107 	ASSERT(pvd->vdev_ops == pvops);
6108 	ASSERT(oldvd->vdev_parent == pvd);
6109 
6110 	/*
6111 	 * Extract the new device from its root and add it to pvd.
6112 	 */
6113 	vdev_remove_child(newrootvd, newvd);
6114 	newvd->vdev_id = pvd->vdev_children;
6115 	newvd->vdev_crtxg = oldvd->vdev_crtxg;
6116 	vdev_add_child(pvd, newvd);
6117 
6118 	tvd = newvd->vdev_top;
6119 	ASSERT(pvd->vdev_top == tvd);
6120 	ASSERT(tvd->vdev_parent == rvd);
6121 
6122 	vdev_config_dirty(tvd);
6123 
6124 	/*
6125 	 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6126 	 * for any dmu_sync-ed blocks.  It will propagate upward when
6127 	 * spa_vdev_exit() calls vdev_dtl_reassess().
6128 	 */
6129 	dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6130 
6131 	vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6132 	    dtl_max_txg - TXG_INITIAL);
6133 
6134 	if (newvd->vdev_isspare) {
6135 		spa_spare_activate(newvd);
6136 		spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6137 	}
6138 
6139 	oldvdpath = spa_strdup(oldvd->vdev_path);
6140 	newvdpath = spa_strdup(newvd->vdev_path);
6141 	newvd_isspare = newvd->vdev_isspare;
6142 
6143 	/*
6144 	 * Mark newvd's DTL dirty in this txg.
6145 	 */
6146 	vdev_dirty(tvd, VDD_DTL, newvd, txg);
6147 
6148 	/*
6149 	 * Schedule the resilver to restart in the future. We do this to
6150 	 * ensure that dmu_sync-ed blocks have been stitched into the
6151 	 * respective datasets. We do not do this if resilvers have been
6152 	 * deferred.
6153 	 */
6154 	if (dsl_scan_resilvering(spa_get_dsl(spa)) &&
6155 	    spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER))
6156 		vdev_set_deferred_resilver(spa, newvd);
6157 	else
6158 		dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
6159 
6160 	if (spa->spa_bootfs)
6161 		spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6162 
6163 	spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6164 
6165 	/*
6166 	 * Commit the config
6167 	 */
6168 	(void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6169 
6170 	spa_history_log_internal(spa, "vdev attach", NULL,
6171 	    "%s vdev=%s %s vdev=%s",
6172 	    replacing && newvd_isspare ? "spare in" :
6173 	    replacing ? "replace" : "attach", newvdpath,
6174 	    replacing ? "for" : "to", oldvdpath);
6175 
6176 	spa_strfree(oldvdpath);
6177 	spa_strfree(newvdpath);
6178 
6179 	return (0);
6180 }
6181 
6182 /*
6183  * Detach a device from a mirror or replacing vdev.
6184  *
6185  * If 'replace_done' is specified, only detach if the parent
6186  * is a replacing vdev.
6187  */
6188 int
6189 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6190 {
6191 	uint64_t txg;
6192 	int error;
6193 	vdev_t *rvd = spa->spa_root_vdev;
6194 	vdev_t *vd, *pvd, *cvd, *tvd;
6195 	boolean_t unspare = B_FALSE;
6196 	uint64_t unspare_guid = 0;
6197 	char *vdpath;
6198 
6199 	ASSERT(spa_writeable(spa));
6200 
6201 	txg = spa_vdev_enter(spa);
6202 
6203 	vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6204 
6205 	/*
6206 	 * Besides being called directly from the userland through the
6207 	 * ioctl interface, spa_vdev_detach() can be potentially called
6208 	 * at the end of spa_vdev_resilver_done().
6209 	 *
6210 	 * In the regular case, when we have a checkpoint this shouldn't
6211 	 * happen as we never empty the DTLs of a vdev during the scrub
6212 	 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6213 	 * should never get here when we have a checkpoint.
6214 	 *
6215 	 * That said, even in a case when we checkpoint the pool exactly
6216 	 * as spa_vdev_resilver_done() calls this function everything
6217 	 * should be fine as the resilver will return right away.
6218 	 */
6219 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
6220 	if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6221 		error = (spa_has_checkpoint(spa)) ?
6222 		    ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6223 		return (spa_vdev_exit(spa, NULL, txg, error));
6224 	}
6225 
6226 	if (vd == NULL)
6227 		return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6228 
6229 	if (!vd->vdev_ops->vdev_op_leaf)
6230 		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6231 
6232 	pvd = vd->vdev_parent;
6233 
6234 	/*
6235 	 * If the parent/child relationship is not as expected, don't do it.
6236 	 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6237 	 * vdev that's replacing B with C.  The user's intent in replacing
6238 	 * is to go from M(A,B) to M(A,C).  If the user decides to cancel
6239 	 * the replace by detaching C, the expected behavior is to end up
6240 	 * M(A,B).  But suppose that right after deciding to detach C,
6241 	 * the replacement of B completes.  We would have M(A,C), and then
6242 	 * ask to detach C, which would leave us with just A -- not what
6243 	 * the user wanted.  To prevent this, we make sure that the
6244 	 * parent/child relationship hasn't changed -- in this example,
6245 	 * that C's parent is still the replacing vdev R.
6246 	 */
6247 	if (pvd->vdev_guid != pguid && pguid != 0)
6248 		return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6249 
6250 	/*
6251 	 * Only 'replacing' or 'spare' vdevs can be replaced.
6252 	 */
6253 	if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6254 	    pvd->vdev_ops != &vdev_spare_ops)
6255 		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6256 
6257 	ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6258 	    spa_version(spa) >= SPA_VERSION_SPARES);
6259 
6260 	/*
6261 	 * Only mirror, replacing, and spare vdevs support detach.
6262 	 */
6263 	if (pvd->vdev_ops != &vdev_replacing_ops &&
6264 	    pvd->vdev_ops != &vdev_mirror_ops &&
6265 	    pvd->vdev_ops != &vdev_spare_ops)
6266 		return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6267 
6268 	/*
6269 	 * If this device has the only valid copy of some data,
6270 	 * we cannot safely detach it.
6271 	 */
6272 	if (vdev_dtl_required(vd))
6273 		return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6274 
6275 	ASSERT(pvd->vdev_children >= 2);
6276 
6277 	/*
6278 	 * If we are detaching the second disk from a replacing vdev, then
6279 	 * check to see if we changed the original vdev's path to have "/old"
6280 	 * at the end in spa_vdev_attach().  If so, undo that change now.
6281 	 */
6282 	if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
6283 	    vd->vdev_path != NULL) {
6284 		size_t len = strlen(vd->vdev_path);
6285 
6286 		for (int c = 0; c < pvd->vdev_children; c++) {
6287 			cvd = pvd->vdev_child[c];
6288 
6289 			if (cvd == vd || cvd->vdev_path == NULL)
6290 				continue;
6291 
6292 			if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
6293 			    strcmp(cvd->vdev_path + len, "/old") == 0) {
6294 				spa_strfree(cvd->vdev_path);
6295 				cvd->vdev_path = spa_strdup(vd->vdev_path);
6296 				break;
6297 			}
6298 		}
6299 	}
6300 
6301 	/*
6302 	 * If we are detaching the original disk from a spare, then it implies
6303 	 * that the spare should become a real disk, and be removed from the
6304 	 * active spare list for the pool.
6305 	 */
6306 	if (pvd->vdev_ops == &vdev_spare_ops &&
6307 	    vd->vdev_id == 0 &&
6308 	    pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
6309 		unspare = B_TRUE;
6310 
6311 	/*
6312 	 * Erase the disk labels so the disk can be used for other things.
6313 	 * This must be done after all other error cases are handled,
6314 	 * but before we disembowel vd (so we can still do I/O to it).
6315 	 * But if we can't do it, don't treat the error as fatal --
6316 	 * it may be that the unwritability of the disk is the reason
6317 	 * it's being detached!
6318 	 */
6319 	error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
6320 
6321 	/*
6322 	 * Remove vd from its parent and compact the parent's children.
6323 	 */
6324 	vdev_remove_child(pvd, vd);
6325 	vdev_compact_children(pvd);
6326 
6327 	/*
6328 	 * Remember one of the remaining children so we can get tvd below.
6329 	 */
6330 	cvd = pvd->vdev_child[pvd->vdev_children - 1];
6331 
6332 	/*
6333 	 * If we need to remove the remaining child from the list of hot spares,
6334 	 * do it now, marking the vdev as no longer a spare in the process.
6335 	 * We must do this before vdev_remove_parent(), because that can
6336 	 * change the GUID if it creates a new toplevel GUID.  For a similar
6337 	 * reason, we must remove the spare now, in the same txg as the detach;
6338 	 * otherwise someone could attach a new sibling, change the GUID, and
6339 	 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
6340 	 */
6341 	if (unspare) {
6342 		ASSERT(cvd->vdev_isspare);
6343 		spa_spare_remove(cvd);
6344 		unspare_guid = cvd->vdev_guid;
6345 		(void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
6346 		cvd->vdev_unspare = B_TRUE;
6347 	}
6348 
6349 	/*
6350 	 * If the parent mirror/replacing vdev only has one child,
6351 	 * the parent is no longer needed.  Remove it from the tree.
6352 	 */
6353 	if (pvd->vdev_children == 1) {
6354 		if (pvd->vdev_ops == &vdev_spare_ops)
6355 			cvd->vdev_unspare = B_FALSE;
6356 		vdev_remove_parent(cvd);
6357 	}
6358 
6359 
6360 	/*
6361 	 * We don't set tvd until now because the parent we just removed
6362 	 * may have been the previous top-level vdev.
6363 	 */
6364 	tvd = cvd->vdev_top;
6365 	ASSERT(tvd->vdev_parent == rvd);
6366 
6367 	/*
6368 	 * Reevaluate the parent vdev state.
6369 	 */
6370 	vdev_propagate_state(cvd);
6371 
6372 	/*
6373 	 * If the 'autoexpand' property is set on the pool then automatically
6374 	 * try to expand the size of the pool. For example if the device we
6375 	 * just detached was smaller than the others, it may be possible to
6376 	 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
6377 	 * first so that we can obtain the updated sizes of the leaf vdevs.
6378 	 */
6379 	if (spa->spa_autoexpand) {
6380 		vdev_reopen(tvd);
6381 		vdev_expand(tvd, txg);
6382 	}
6383 
6384 	vdev_config_dirty(tvd);
6385 
6386 	/*
6387 	 * Mark vd's DTL as dirty in this txg.  vdev_dtl_sync() will see that
6388 	 * vd->vdev_detached is set and free vd's DTL object in syncing context.
6389 	 * But first make sure we're not on any *other* txg's DTL list, to
6390 	 * prevent vd from being accessed after it's freed.
6391 	 */
6392 	vdpath = spa_strdup(vd->vdev_path);
6393 	for (int t = 0; t < TXG_SIZE; t++)
6394 		(void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
6395 	vd->vdev_detached = B_TRUE;
6396 	vdev_dirty(tvd, VDD_DTL, vd, txg);
6397 
6398 	spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
6399 
6400 	/* hang on to the spa before we release the lock */
6401 	spa_open_ref(spa, FTAG);
6402 
6403 	error = spa_vdev_exit(spa, vd, txg, 0);
6404 
6405 	spa_history_log_internal(spa, "detach", NULL,
6406 	    "vdev=%s", vdpath);
6407 	spa_strfree(vdpath);
6408 
6409 	/*
6410 	 * If this was the removal of the original device in a hot spare vdev,
6411 	 * then we want to go through and remove the device from the hot spare
6412 	 * list of every other pool.
6413 	 */
6414 	if (unspare) {
6415 		spa_t *altspa = NULL;
6416 
6417 		mutex_enter(&spa_namespace_lock);
6418 		while ((altspa = spa_next(altspa)) != NULL) {
6419 			if (altspa->spa_state != POOL_STATE_ACTIVE ||
6420 			    altspa == spa)
6421 				continue;
6422 
6423 			spa_open_ref(altspa, FTAG);
6424 			mutex_exit(&spa_namespace_lock);
6425 			(void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
6426 			mutex_enter(&spa_namespace_lock);
6427 			spa_close(altspa, FTAG);
6428 		}
6429 		mutex_exit(&spa_namespace_lock);
6430 
6431 		/* search the rest of the vdevs for spares to remove */
6432 		spa_vdev_resilver_done(spa);
6433 	}
6434 
6435 	/* all done with the spa; OK to release */
6436 	mutex_enter(&spa_namespace_lock);
6437 	spa_close(spa, FTAG);
6438 	mutex_exit(&spa_namespace_lock);
6439 
6440 	return (error);
6441 }
6442 
6443 int
6444 spa_vdev_initialize(spa_t *spa, uint64_t guid, uint64_t cmd_type)
6445 {
6446 	/*
6447 	 * We hold the namespace lock through the whole function
6448 	 * to prevent any changes to the pool while we're starting or
6449 	 * stopping initialization. The config and state locks are held so that
6450 	 * we can properly assess the vdev state before we commit to
6451 	 * the initializing operation.
6452 	 */
6453 	mutex_enter(&spa_namespace_lock);
6454 	spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6455 
6456 	/* Look up vdev and ensure it's a leaf. */
6457 	vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6458 	if (vd == NULL || vd->vdev_detached) {
6459 		spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6460 		mutex_exit(&spa_namespace_lock);
6461 		return (SET_ERROR(ENODEV));
6462 	} else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6463 		spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6464 		mutex_exit(&spa_namespace_lock);
6465 		return (SET_ERROR(EINVAL));
6466 	} else if (!vdev_writeable(vd)) {
6467 		spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6468 		mutex_exit(&spa_namespace_lock);
6469 		return (SET_ERROR(EROFS));
6470 	}
6471 	mutex_enter(&vd->vdev_initialize_lock);
6472 	spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6473 
6474 	/*
6475 	 * When we activate an initialize action we check to see
6476 	 * if the vdev_initialize_thread is NULL. We do this instead
6477 	 * of using the vdev_initialize_state since there might be
6478 	 * a previous initialization process which has completed but
6479 	 * the thread is not exited.
6480 	 */
6481 	if (cmd_type == POOL_INITIALIZE_DO &&
6482 	    (vd->vdev_initialize_thread != NULL ||
6483 	    vd->vdev_top->vdev_removing)) {
6484 		mutex_exit(&vd->vdev_initialize_lock);
6485 		mutex_exit(&spa_namespace_lock);
6486 		return (SET_ERROR(EBUSY));
6487 	} else if (cmd_type == POOL_INITIALIZE_CANCEL &&
6488 	    (vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE &&
6489 	    vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED)) {
6490 		mutex_exit(&vd->vdev_initialize_lock);
6491 		mutex_exit(&spa_namespace_lock);
6492 		return (SET_ERROR(ESRCH));
6493 	} else if (cmd_type == POOL_INITIALIZE_SUSPEND &&
6494 	    vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE) {
6495 		mutex_exit(&vd->vdev_initialize_lock);
6496 		mutex_exit(&spa_namespace_lock);
6497 		return (SET_ERROR(ESRCH));
6498 	}
6499 
6500 	switch (cmd_type) {
6501 	case POOL_INITIALIZE_DO:
6502 		vdev_initialize(vd);
6503 		break;
6504 	case POOL_INITIALIZE_CANCEL:
6505 		vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED);
6506 		break;
6507 	case POOL_INITIALIZE_SUSPEND:
6508 		vdev_initialize_stop(vd, VDEV_INITIALIZE_SUSPENDED);
6509 		break;
6510 	default:
6511 		panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6512 	}
6513 	mutex_exit(&vd->vdev_initialize_lock);
6514 
6515 	/* Sync out the initializing state */
6516 	txg_wait_synced(spa->spa_dsl_pool, 0);
6517 	mutex_exit(&spa_namespace_lock);
6518 
6519 	return (0);
6520 }
6521 
6522 
6523 /*
6524  * Split a set of devices from their mirrors, and create a new pool from them.
6525  */
6526 int
6527 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6528     nvlist_t *props, boolean_t exp)
6529 {
6530 	int error = 0;
6531 	uint64_t txg, *glist;
6532 	spa_t *newspa;
6533 	uint_t c, children, lastlog;
6534 	nvlist_t **child, *nvl, *tmp;
6535 	dmu_tx_t *tx;
6536 	char *altroot = NULL;
6537 	vdev_t *rvd, **vml = NULL;			/* vdev modify list */
6538 	boolean_t activate_slog;
6539 
6540 	ASSERT(spa_writeable(spa));
6541 
6542 	txg = spa_vdev_enter(spa);
6543 
6544 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
6545 	if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6546 		error = (spa_has_checkpoint(spa)) ?
6547 		    ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6548 		return (spa_vdev_exit(spa, NULL, txg, error));
6549 	}
6550 
6551 	/* clear the log and flush everything up to now */
6552 	activate_slog = spa_passivate_log(spa);
6553 	(void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6554 	error = spa_reset_logs(spa);
6555 	txg = spa_vdev_config_enter(spa);
6556 
6557 	if (activate_slog)
6558 		spa_activate_log(spa);
6559 
6560 	if (error != 0)
6561 		return (spa_vdev_exit(spa, NULL, txg, error));
6562 
6563 	/* check new spa name before going any further */
6564 	if (spa_lookup(newname) != NULL)
6565 		return (spa_vdev_exit(spa, NULL, txg, EEXIST));
6566 
6567 	/*
6568 	 * scan through all the children to ensure they're all mirrors
6569 	 */
6570 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
6571 	    nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
6572 	    &children) != 0)
6573 		return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6574 
6575 	/* first, check to ensure we've got the right child count */
6576 	rvd = spa->spa_root_vdev;
6577 	lastlog = 0;
6578 	for (c = 0; c < rvd->vdev_children; c++) {
6579 		vdev_t *vd = rvd->vdev_child[c];
6580 
6581 		/* don't count the holes & logs as children */
6582 		if (vd->vdev_islog || !vdev_is_concrete(vd)) {
6583 			if (lastlog == 0)
6584 				lastlog = c;
6585 			continue;
6586 		}
6587 
6588 		lastlog = 0;
6589 	}
6590 	if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
6591 		return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6592 
6593 	/* next, ensure no spare or cache devices are part of the split */
6594 	if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
6595 	    nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
6596 		return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6597 
6598 	vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
6599 	glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
6600 
6601 	/* then, loop over each vdev and validate it */
6602 	for (c = 0; c < children; c++) {
6603 		uint64_t is_hole = 0;
6604 
6605 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
6606 		    &is_hole);
6607 
6608 		if (is_hole != 0) {
6609 			if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
6610 			    spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
6611 				continue;
6612 			} else {
6613 				error = SET_ERROR(EINVAL);
6614 				break;
6615 			}
6616 		}
6617 
6618 		/* which disk is going to be split? */
6619 		if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
6620 		    &glist[c]) != 0) {
6621 			error = SET_ERROR(EINVAL);
6622 			break;
6623 		}
6624 
6625 		/* look it up in the spa */
6626 		vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
6627 		if (vml[c] == NULL) {
6628 			error = SET_ERROR(ENODEV);
6629 			break;
6630 		}
6631 
6632 		/* make sure there's nothing stopping the split */
6633 		if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
6634 		    vml[c]->vdev_islog ||
6635 		    !vdev_is_concrete(vml[c]) ||
6636 		    vml[c]->vdev_isspare ||
6637 		    vml[c]->vdev_isl2cache ||
6638 		    !vdev_writeable(vml[c]) ||
6639 		    vml[c]->vdev_children != 0 ||
6640 		    vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
6641 		    c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
6642 			error = SET_ERROR(EINVAL);
6643 			break;
6644 		}
6645 
6646 		if (vdev_dtl_required(vml[c])) {
6647 			error = SET_ERROR(EBUSY);
6648 			break;
6649 		}
6650 
6651 		/* we need certain info from the top level */
6652 		VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
6653 		    vml[c]->vdev_top->vdev_ms_array) == 0);
6654 		VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
6655 		    vml[c]->vdev_top->vdev_ms_shift) == 0);
6656 		VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
6657 		    vml[c]->vdev_top->vdev_asize) == 0);
6658 		VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
6659 		    vml[c]->vdev_top->vdev_ashift) == 0);
6660 
6661 		/* transfer per-vdev ZAPs */
6662 		ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
6663 		VERIFY0(nvlist_add_uint64(child[c],
6664 		    ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
6665 
6666 		ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
6667 		VERIFY0(nvlist_add_uint64(child[c],
6668 		    ZPOOL_CONFIG_VDEV_TOP_ZAP,
6669 		    vml[c]->vdev_parent->vdev_top_zap));
6670 	}
6671 
6672 	if (error != 0) {
6673 		kmem_free(vml, children * sizeof (vdev_t *));
6674 		kmem_free(glist, children * sizeof (uint64_t));
6675 		return (spa_vdev_exit(spa, NULL, txg, error));
6676 	}
6677 
6678 	/* stop writers from using the disks */
6679 	for (c = 0; c < children; c++) {
6680 		if (vml[c] != NULL)
6681 			vml[c]->vdev_offline = B_TRUE;
6682 	}
6683 	vdev_reopen(spa->spa_root_vdev);
6684 
6685 	/*
6686 	 * Temporarily record the splitting vdevs in the spa config.  This
6687 	 * will disappear once the config is regenerated.
6688 	 */
6689 	VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6690 	VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
6691 	    glist, children) == 0);
6692 	kmem_free(glist, children * sizeof (uint64_t));
6693 
6694 	mutex_enter(&spa->spa_props_lock);
6695 	VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
6696 	    nvl) == 0);
6697 	mutex_exit(&spa->spa_props_lock);
6698 	spa->spa_config_splitting = nvl;
6699 	vdev_config_dirty(spa->spa_root_vdev);
6700 
6701 	/* configure and create the new pool */
6702 	VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
6703 	VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6704 	    exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
6705 	VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6706 	    spa_version(spa)) == 0);
6707 	VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
6708 	    spa->spa_config_txg) == 0);
6709 	VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
6710 	    spa_generate_guid(NULL)) == 0);
6711 	VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
6712 	(void) nvlist_lookup_string(props,
6713 	    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
6714 
6715 	/* add the new pool to the namespace */
6716 	newspa = spa_add(newname, config, altroot);
6717 	newspa->spa_avz_action = AVZ_ACTION_REBUILD;
6718 	newspa->spa_config_txg = spa->spa_config_txg;
6719 	spa_set_log_state(newspa, SPA_LOG_CLEAR);
6720 
6721 	/* release the spa config lock, retaining the namespace lock */
6722 	spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6723 
6724 	if (zio_injection_enabled)
6725 		zio_handle_panic_injection(spa, FTAG, 1);
6726 
6727 	spa_activate(newspa, spa_mode_global);
6728 	spa_async_suspend(newspa);
6729 
6730 	for (c = 0; c < children; c++) {
6731 		if (vml[c] != NULL) {
6732 			/*
6733 			 * Temporarily stop the initializing activity. We set
6734 			 * the state to ACTIVE so that we know to resume
6735 			 * the initializing once the split has completed.
6736 			 */
6737 			mutex_enter(&vml[c]->vdev_initialize_lock);
6738 			vdev_initialize_stop(vml[c], VDEV_INITIALIZE_ACTIVE);
6739 			mutex_exit(&vml[c]->vdev_initialize_lock);
6740 		}
6741 	}
6742 
6743 	newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
6744 
6745 	/* create the new pool from the disks of the original pool */
6746 	error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
6747 	if (error)
6748 		goto out;
6749 
6750 	/* if that worked, generate a real config for the new pool */
6751 	if (newspa->spa_root_vdev != NULL) {
6752 		VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
6753 		    NV_UNIQUE_NAME, KM_SLEEP) == 0);
6754 		VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
6755 		    ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
6756 		spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
6757 		    B_TRUE));
6758 	}
6759 
6760 	/* set the props */
6761 	if (props != NULL) {
6762 		spa_configfile_set(newspa, props, B_FALSE);
6763 		error = spa_prop_set(newspa, props);
6764 		if (error)
6765 			goto out;
6766 	}
6767 
6768 	/* flush everything */
6769 	txg = spa_vdev_config_enter(newspa);
6770 	vdev_config_dirty(newspa->spa_root_vdev);
6771 	(void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
6772 
6773 	if (zio_injection_enabled)
6774 		zio_handle_panic_injection(spa, FTAG, 2);
6775 
6776 	spa_async_resume(newspa);
6777 
6778 	/* finally, update the original pool's config */
6779 	txg = spa_vdev_config_enter(spa);
6780 	tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
6781 	error = dmu_tx_assign(tx, TXG_WAIT);
6782 	if (error != 0)
6783 		dmu_tx_abort(tx);
6784 	for (c = 0; c < children; c++) {
6785 		if (vml[c] != NULL) {
6786 			vdev_split(vml[c]);
6787 			if (error == 0)
6788 				spa_history_log_internal(spa, "detach", tx,
6789 				    "vdev=%s", vml[c]->vdev_path);
6790 
6791 			vdev_free(vml[c]);
6792 		}
6793 	}
6794 	spa->spa_avz_action = AVZ_ACTION_REBUILD;
6795 	vdev_config_dirty(spa->spa_root_vdev);
6796 	spa->spa_config_splitting = NULL;
6797 	nvlist_free(nvl);
6798 	if (error == 0)
6799 		dmu_tx_commit(tx);
6800 	(void) spa_vdev_exit(spa, NULL, txg, 0);
6801 
6802 	if (zio_injection_enabled)
6803 		zio_handle_panic_injection(spa, FTAG, 3);
6804 
6805 	/* split is complete; log a history record */
6806 	spa_history_log_internal(newspa, "split", NULL,
6807 	    "from pool %s", spa_name(spa));
6808 
6809 	kmem_free(vml, children * sizeof (vdev_t *));
6810 
6811 	/* if we're not going to mount the filesystems in userland, export */
6812 	if (exp)
6813 		error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
6814 		    B_FALSE, B_FALSE);
6815 
6816 	return (error);
6817 
6818 out:
6819 	spa_unload(newspa);
6820 	spa_deactivate(newspa);
6821 	spa_remove(newspa);
6822 
6823 	txg = spa_vdev_config_enter(spa);
6824 
6825 	/* re-online all offlined disks */
6826 	for (c = 0; c < children; c++) {
6827 		if (vml[c] != NULL)
6828 			vml[c]->vdev_offline = B_FALSE;
6829 	}
6830 
6831 	/* restart initializing disks as necessary */
6832 	spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
6833 
6834 	vdev_reopen(spa->spa_root_vdev);
6835 
6836 	nvlist_free(spa->spa_config_splitting);
6837 	spa->spa_config_splitting = NULL;
6838 	(void) spa_vdev_exit(spa, NULL, txg, error);
6839 
6840 	kmem_free(vml, children * sizeof (vdev_t *));
6841 	return (error);
6842 }
6843 
6844 /*
6845  * Find any device that's done replacing, or a vdev marked 'unspare' that's
6846  * currently spared, so we can detach it.
6847  */
6848 static vdev_t *
6849 spa_vdev_resilver_done_hunt(vdev_t *vd)
6850 {
6851 	vdev_t *newvd, *oldvd;
6852 
6853 	for (int c = 0; c < vd->vdev_children; c++) {
6854 		oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
6855 		if (oldvd != NULL)
6856 			return (oldvd);
6857 	}
6858 
6859 	/*
6860 	 * Check for a completed replacement.  We always consider the first
6861 	 * vdev in the list to be the oldest vdev, and the last one to be
6862 	 * the newest (see spa_vdev_attach() for how that works).  In
6863 	 * the case where the newest vdev is faulted, we will not automatically
6864 	 * remove it after a resilver completes.  This is OK as it will require
6865 	 * user intervention to determine which disk the admin wishes to keep.
6866 	 */
6867 	if (vd->vdev_ops == &vdev_replacing_ops) {
6868 		ASSERT(vd->vdev_children > 1);
6869 
6870 		newvd = vd->vdev_child[vd->vdev_children - 1];
6871 		oldvd = vd->vdev_child[0];
6872 
6873 		if (vdev_dtl_empty(newvd, DTL_MISSING) &&
6874 		    vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6875 		    !vdev_dtl_required(oldvd))
6876 			return (oldvd);
6877 	}
6878 
6879 	/*
6880 	 * Check for a completed resilver with the 'unspare' flag set.
6881 	 * Also potentially update faulted state.
6882 	 */
6883 	if (vd->vdev_ops == &vdev_spare_ops) {
6884 		vdev_t *first = vd->vdev_child[0];
6885 		vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
6886 
6887 		if (last->vdev_unspare) {
6888 			oldvd = first;
6889 			newvd = last;
6890 		} else if (first->vdev_unspare) {
6891 			oldvd = last;
6892 			newvd = first;
6893 		} else {
6894 			oldvd = NULL;
6895 		}
6896 
6897 		if (oldvd != NULL &&
6898 		    vdev_dtl_empty(newvd, DTL_MISSING) &&
6899 		    vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6900 		    !vdev_dtl_required(oldvd))
6901 			return (oldvd);
6902 
6903 		vdev_propagate_state(vd);
6904 
6905 		/*
6906 		 * If there are more than two spares attached to a disk,
6907 		 * and those spares are not required, then we want to
6908 		 * attempt to free them up now so that they can be used
6909 		 * by other pools.  Once we're back down to a single
6910 		 * disk+spare, we stop removing them.
6911 		 */
6912 		if (vd->vdev_children > 2) {
6913 			newvd = vd->vdev_child[1];
6914 
6915 			if (newvd->vdev_isspare && last->vdev_isspare &&
6916 			    vdev_dtl_empty(last, DTL_MISSING) &&
6917 			    vdev_dtl_empty(last, DTL_OUTAGE) &&
6918 			    !vdev_dtl_required(newvd))
6919 				return (newvd);
6920 		}
6921 	}
6922 
6923 	return (NULL);
6924 }
6925 
6926 static void
6927 spa_vdev_resilver_done(spa_t *spa)
6928 {
6929 	vdev_t *vd, *pvd, *ppvd;
6930 	uint64_t guid, sguid, pguid, ppguid;
6931 
6932 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6933 
6934 	while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
6935 		pvd = vd->vdev_parent;
6936 		ppvd = pvd->vdev_parent;
6937 		guid = vd->vdev_guid;
6938 		pguid = pvd->vdev_guid;
6939 		ppguid = ppvd->vdev_guid;
6940 		sguid = 0;
6941 		/*
6942 		 * If we have just finished replacing a hot spared device, then
6943 		 * we need to detach the parent's first child (the original hot
6944 		 * spare) as well.
6945 		 */
6946 		if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
6947 		    ppvd->vdev_children == 2) {
6948 			ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
6949 			sguid = ppvd->vdev_child[1]->vdev_guid;
6950 		}
6951 		ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
6952 
6953 		spa_config_exit(spa, SCL_ALL, FTAG);
6954 		if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
6955 			return;
6956 		if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
6957 			return;
6958 		spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6959 	}
6960 
6961 	spa_config_exit(spa, SCL_ALL, FTAG);
6962 }
6963 
6964 /*
6965  * Update the stored path or FRU for this vdev.
6966  */
6967 int
6968 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
6969     boolean_t ispath)
6970 {
6971 	vdev_t *vd;
6972 	boolean_t sync = B_FALSE;
6973 
6974 	ASSERT(spa_writeable(spa));
6975 
6976 	spa_vdev_state_enter(spa, SCL_ALL);
6977 
6978 	if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
6979 		return (spa_vdev_state_exit(spa, NULL, ENOENT));
6980 
6981 	if (!vd->vdev_ops->vdev_op_leaf)
6982 		return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
6983 
6984 	if (ispath) {
6985 		if (strcmp(value, vd->vdev_path) != 0) {
6986 			spa_strfree(vd->vdev_path);
6987 			vd->vdev_path = spa_strdup(value);
6988 			sync = B_TRUE;
6989 		}
6990 	} else {
6991 		if (vd->vdev_fru == NULL) {
6992 			vd->vdev_fru = spa_strdup(value);
6993 			sync = B_TRUE;
6994 		} else if (strcmp(value, vd->vdev_fru) != 0) {
6995 			spa_strfree(vd->vdev_fru);
6996 			vd->vdev_fru = spa_strdup(value);
6997 			sync = B_TRUE;
6998 		}
6999 	}
7000 
7001 	return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
7002 }
7003 
7004 int
7005 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
7006 {
7007 	return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
7008 }
7009 
7010 int
7011 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
7012 {
7013 	return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
7014 }
7015 
7016 /*
7017  * ==========================================================================
7018  * SPA Scanning
7019  * ==========================================================================
7020  */
7021 int
7022 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
7023 {
7024 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7025 
7026 	if (dsl_scan_resilvering(spa->spa_dsl_pool))
7027 		return (SET_ERROR(EBUSY));
7028 
7029 	return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
7030 }
7031 
7032 int
7033 spa_scan_stop(spa_t *spa)
7034 {
7035 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7036 	if (dsl_scan_resilvering(spa->spa_dsl_pool))
7037 		return (SET_ERROR(EBUSY));
7038 	return (dsl_scan_cancel(spa->spa_dsl_pool));
7039 }
7040 
7041 int
7042 spa_scan(spa_t *spa, pool_scan_func_t func)
7043 {
7044 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7045 
7046 	if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
7047 		return (SET_ERROR(ENOTSUP));
7048 
7049 	if (func == POOL_SCAN_RESILVER &&
7050 	    !spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER))
7051 		return (SET_ERROR(ENOTSUP));
7052 
7053 	/*
7054 	 * If a resilver was requested, but there is no DTL on a
7055 	 * writeable leaf device, we have nothing to do.
7056 	 */
7057 	if (func == POOL_SCAN_RESILVER &&
7058 	    !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
7059 		spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
7060 		return (0);
7061 	}
7062 
7063 	return (dsl_scan(spa->spa_dsl_pool, func));
7064 }
7065 
7066 /*
7067  * ==========================================================================
7068  * SPA async task processing
7069  * ==========================================================================
7070  */
7071 
7072 static void
7073 spa_async_remove(spa_t *spa, vdev_t *vd)
7074 {
7075 	if (vd->vdev_remove_wanted) {
7076 		vd->vdev_remove_wanted = B_FALSE;
7077 		vd->vdev_delayed_close = B_FALSE;
7078 		vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
7079 
7080 		/*
7081 		 * We want to clear the stats, but we don't want to do a full
7082 		 * vdev_clear() as that will cause us to throw away
7083 		 * degraded/faulted state as well as attempt to reopen the
7084 		 * device, all of which is a waste.
7085 		 */
7086 		vd->vdev_stat.vs_read_errors = 0;
7087 		vd->vdev_stat.vs_write_errors = 0;
7088 		vd->vdev_stat.vs_checksum_errors = 0;
7089 
7090 		vdev_state_dirty(vd->vdev_top);
7091 	}
7092 
7093 	for (int c = 0; c < vd->vdev_children; c++)
7094 		spa_async_remove(spa, vd->vdev_child[c]);
7095 }
7096 
7097 static void
7098 spa_async_probe(spa_t *spa, vdev_t *vd)
7099 {
7100 	if (vd->vdev_probe_wanted) {
7101 		vd->vdev_probe_wanted = B_FALSE;
7102 		vdev_reopen(vd);	/* vdev_open() does the actual probe */
7103 	}
7104 
7105 	for (int c = 0; c < vd->vdev_children; c++)
7106 		spa_async_probe(spa, vd->vdev_child[c]);
7107 }
7108 
7109 static void
7110 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
7111 {
7112 	sysevent_id_t eid;
7113 	nvlist_t *attr;
7114 	char *physpath;
7115 
7116 	if (!spa->spa_autoexpand)
7117 		return;
7118 
7119 	for (int c = 0; c < vd->vdev_children; c++) {
7120 		vdev_t *cvd = vd->vdev_child[c];
7121 		spa_async_autoexpand(spa, cvd);
7122 	}
7123 
7124 	if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
7125 		return;
7126 
7127 	physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
7128 	(void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
7129 
7130 	VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7131 	VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
7132 
7133 	(void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
7134 	    ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
7135 
7136 	nvlist_free(attr);
7137 	kmem_free(physpath, MAXPATHLEN);
7138 }
7139 
7140 static void
7141 spa_async_thread(void *arg)
7142 {
7143 	spa_t *spa = (spa_t *)arg;
7144 	dsl_pool_t *dp = spa->spa_dsl_pool;
7145 	int tasks;
7146 
7147 	ASSERT(spa->spa_sync_on);
7148 
7149 	mutex_enter(&spa->spa_async_lock);
7150 	tasks = spa->spa_async_tasks;
7151 	spa->spa_async_tasks = 0;
7152 	mutex_exit(&spa->spa_async_lock);
7153 
7154 	/*
7155 	 * See if the config needs to be updated.
7156 	 */
7157 	if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
7158 		uint64_t old_space, new_space;
7159 
7160 		mutex_enter(&spa_namespace_lock);
7161 		old_space = metaslab_class_get_space(spa_normal_class(spa));
7162 		old_space += metaslab_class_get_space(spa_special_class(spa));
7163 		old_space += metaslab_class_get_space(spa_dedup_class(spa));
7164 
7165 		spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
7166 
7167 		new_space = metaslab_class_get_space(spa_normal_class(spa));
7168 		new_space += metaslab_class_get_space(spa_special_class(spa));
7169 		new_space += metaslab_class_get_space(spa_dedup_class(spa));
7170 		mutex_exit(&spa_namespace_lock);
7171 
7172 		/*
7173 		 * If the pool grew as a result of the config update,
7174 		 * then log an internal history event.
7175 		 */
7176 		if (new_space != old_space) {
7177 			spa_history_log_internal(spa, "vdev online", NULL,
7178 			    "pool '%s' size: %llu(+%llu)",
7179 			    spa_name(spa), new_space, new_space - old_space);
7180 		}
7181 	}
7182 
7183 	/*
7184 	 * See if any devices need to be marked REMOVED.
7185 	 */
7186 	if (tasks & SPA_ASYNC_REMOVE) {
7187 		spa_vdev_state_enter(spa, SCL_NONE);
7188 		spa_async_remove(spa, spa->spa_root_vdev);
7189 		for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
7190 			spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
7191 		for (int i = 0; i < spa->spa_spares.sav_count; i++)
7192 			spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
7193 		(void) spa_vdev_state_exit(spa, NULL, 0);
7194 	}
7195 
7196 	if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
7197 		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7198 		spa_async_autoexpand(spa, spa->spa_root_vdev);
7199 		spa_config_exit(spa, SCL_CONFIG, FTAG);
7200 	}
7201 
7202 	/*
7203 	 * See if any devices need to be probed.
7204 	 */
7205 	if (tasks & SPA_ASYNC_PROBE) {
7206 		spa_vdev_state_enter(spa, SCL_NONE);
7207 		spa_async_probe(spa, spa->spa_root_vdev);
7208 		(void) spa_vdev_state_exit(spa, NULL, 0);
7209 	}
7210 
7211 	/*
7212 	 * If any devices are done replacing, detach them.
7213 	 */
7214 	if (tasks & SPA_ASYNC_RESILVER_DONE)
7215 		spa_vdev_resilver_done(spa);
7216 
7217 	/*
7218 	 * Kick off a resilver.
7219 	 */
7220 	if (tasks & SPA_ASYNC_RESILVER &&
7221 	    (!dsl_scan_resilvering(dp) ||
7222 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_RESILVER_DEFER)))
7223 		dsl_resilver_restart(dp, 0);
7224 
7225 	if (tasks & SPA_ASYNC_INITIALIZE_RESTART) {
7226 		mutex_enter(&spa_namespace_lock);
7227 		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7228 		vdev_initialize_restart(spa->spa_root_vdev);
7229 		spa_config_exit(spa, SCL_CONFIG, FTAG);
7230 		mutex_exit(&spa_namespace_lock);
7231 	}
7232 
7233 	/*
7234 	 * Let the world know that we're done.
7235 	 */
7236 	mutex_enter(&spa->spa_async_lock);
7237 	spa->spa_async_thread = NULL;
7238 	cv_broadcast(&spa->spa_async_cv);
7239 	mutex_exit(&spa->spa_async_lock);
7240 	thread_exit();
7241 }
7242 
7243 void
7244 spa_async_suspend(spa_t *spa)
7245 {
7246 	mutex_enter(&spa->spa_async_lock);
7247 	spa->spa_async_suspended++;
7248 	while (spa->spa_async_thread != NULL)
7249 		cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
7250 	mutex_exit(&spa->spa_async_lock);
7251 
7252 	spa_vdev_remove_suspend(spa);
7253 
7254 	zthr_t *condense_thread = spa->spa_condense_zthr;
7255 	if (condense_thread != NULL)
7256 		zthr_cancel(condense_thread);
7257 
7258 	zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7259 	if (discard_thread != NULL)
7260 		zthr_cancel(discard_thread);
7261 }
7262 
7263 void
7264 spa_async_resume(spa_t *spa)
7265 {
7266 	mutex_enter(&spa->spa_async_lock);
7267 	ASSERT(spa->spa_async_suspended != 0);
7268 	spa->spa_async_suspended--;
7269 	mutex_exit(&spa->spa_async_lock);
7270 	spa_restart_removal(spa);
7271 
7272 	zthr_t *condense_thread = spa->spa_condense_zthr;
7273 	if (condense_thread != NULL)
7274 		zthr_resume(condense_thread);
7275 
7276 	zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7277 	if (discard_thread != NULL)
7278 		zthr_resume(discard_thread);
7279 }
7280 
7281 static boolean_t
7282 spa_async_tasks_pending(spa_t *spa)
7283 {
7284 	uint_t non_config_tasks;
7285 	uint_t config_task;
7286 	boolean_t config_task_suspended;
7287 
7288 	non_config_tasks = spa->spa_async_tasks & ~SPA_ASYNC_CONFIG_UPDATE;
7289 	config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
7290 	if (spa->spa_ccw_fail_time == 0) {
7291 		config_task_suspended = B_FALSE;
7292 	} else {
7293 		config_task_suspended =
7294 		    (gethrtime() - spa->spa_ccw_fail_time) <
7295 		    (zfs_ccw_retry_interval * NANOSEC);
7296 	}
7297 
7298 	return (non_config_tasks || (config_task && !config_task_suspended));
7299 }
7300 
7301 static void
7302 spa_async_dispatch(spa_t *spa)
7303 {
7304 	mutex_enter(&spa->spa_async_lock);
7305 	if (spa_async_tasks_pending(spa) &&
7306 	    !spa->spa_async_suspended &&
7307 	    spa->spa_async_thread == NULL &&
7308 	    rootdir != NULL)
7309 		spa->spa_async_thread = thread_create(NULL, 0,
7310 		    spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
7311 	mutex_exit(&spa->spa_async_lock);
7312 }
7313 
7314 void
7315 spa_async_request(spa_t *spa, int task)
7316 {
7317 	zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
7318 	mutex_enter(&spa->spa_async_lock);
7319 	spa->spa_async_tasks |= task;
7320 	mutex_exit(&spa->spa_async_lock);
7321 }
7322 
7323 /*
7324  * ==========================================================================
7325  * SPA syncing routines
7326  * ==========================================================================
7327  */
7328 
7329 static int
7330 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7331 {
7332 	bpobj_t *bpo = arg;
7333 	bpobj_enqueue(bpo, bp, tx);
7334 	return (0);
7335 }
7336 
7337 static int
7338 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7339 {
7340 	zio_t *zio = arg;
7341 
7342 	zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
7343 	    zio->io_flags));
7344 	return (0);
7345 }
7346 
7347 /*
7348  * Note: this simple function is not inlined to make it easier to dtrace the
7349  * amount of time spent syncing frees.
7350  */
7351 static void
7352 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
7353 {
7354 	zio_t *zio = zio_root(spa, NULL, NULL, 0);
7355 	bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
7356 	VERIFY(zio_wait(zio) == 0);
7357 }
7358 
7359 /*
7360  * Note: this simple function is not inlined to make it easier to dtrace the
7361  * amount of time spent syncing deferred frees.
7362  */
7363 static void
7364 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
7365 {
7366 	if (spa_sync_pass(spa) != 1)
7367 		return;
7368 
7369 	zio_t *zio = zio_root(spa, NULL, NULL, 0);
7370 	VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
7371 	    spa_free_sync_cb, zio, tx), ==, 0);
7372 	VERIFY0(zio_wait(zio));
7373 }
7374 
7375 
7376 static void
7377 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
7378 {
7379 	char *packed = NULL;
7380 	size_t bufsize;
7381 	size_t nvsize = 0;
7382 	dmu_buf_t *db;
7383 
7384 	VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
7385 
7386 	/*
7387 	 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
7388 	 * information.  This avoids the dmu_buf_will_dirty() path and
7389 	 * saves us a pre-read to get data we don't actually care about.
7390 	 */
7391 	bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
7392 	packed = kmem_alloc(bufsize, KM_SLEEP);
7393 
7394 	VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
7395 	    KM_SLEEP) == 0);
7396 	bzero(packed + nvsize, bufsize - nvsize);
7397 
7398 	dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
7399 
7400 	kmem_free(packed, bufsize);
7401 
7402 	VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
7403 	dmu_buf_will_dirty(db, tx);
7404 	*(uint64_t *)db->db_data = nvsize;
7405 	dmu_buf_rele(db, FTAG);
7406 }
7407 
7408 static void
7409 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
7410     const char *config, const char *entry)
7411 {
7412 	nvlist_t *nvroot;
7413 	nvlist_t **list;
7414 	int i;
7415 
7416 	if (!sav->sav_sync)
7417 		return;
7418 
7419 	/*
7420 	 * Update the MOS nvlist describing the list of available devices.
7421 	 * spa_validate_aux() will have already made sure this nvlist is
7422 	 * valid and the vdevs are labeled appropriately.
7423 	 */
7424 	if (sav->sav_object == 0) {
7425 		sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
7426 		    DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
7427 		    sizeof (uint64_t), tx);
7428 		VERIFY(zap_update(spa->spa_meta_objset,
7429 		    DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
7430 		    &sav->sav_object, tx) == 0);
7431 	}
7432 
7433 	VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7434 	if (sav->sav_count == 0) {
7435 		VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
7436 	} else {
7437 		list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
7438 		for (i = 0; i < sav->sav_count; i++)
7439 			list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
7440 			    B_FALSE, VDEV_CONFIG_L2CACHE);
7441 		VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
7442 		    sav->sav_count) == 0);
7443 		for (i = 0; i < sav->sav_count; i++)
7444 			nvlist_free(list[i]);
7445 		kmem_free(list, sav->sav_count * sizeof (void *));
7446 	}
7447 
7448 	spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
7449 	nvlist_free(nvroot);
7450 
7451 	sav->sav_sync = B_FALSE;
7452 }
7453 
7454 /*
7455  * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
7456  * The all-vdev ZAP must be empty.
7457  */
7458 static void
7459 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
7460 {
7461 	spa_t *spa = vd->vdev_spa;
7462 	if (vd->vdev_top_zap != 0) {
7463 		VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7464 		    vd->vdev_top_zap, tx));
7465 	}
7466 	if (vd->vdev_leaf_zap != 0) {
7467 		VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7468 		    vd->vdev_leaf_zap, tx));
7469 	}
7470 	for (uint64_t i = 0; i < vd->vdev_children; i++) {
7471 		spa_avz_build(vd->vdev_child[i], avz, tx);
7472 	}
7473 }
7474 
7475 static void
7476 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
7477 {
7478 	nvlist_t *config;
7479 
7480 	/*
7481 	 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
7482 	 * its config may not be dirty but we still need to build per-vdev ZAPs.
7483 	 * Similarly, if the pool is being assembled (e.g. after a split), we
7484 	 * need to rebuild the AVZ although the config may not be dirty.
7485 	 */
7486 	if (list_is_empty(&spa->spa_config_dirty_list) &&
7487 	    spa->spa_avz_action == AVZ_ACTION_NONE)
7488 		return;
7489 
7490 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7491 
7492 	ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
7493 	    spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
7494 	    spa->spa_all_vdev_zaps != 0);
7495 
7496 	if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
7497 		/* Make and build the new AVZ */
7498 		uint64_t new_avz = zap_create(spa->spa_meta_objset,
7499 		    DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7500 		spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7501 
7502 		/* Diff old AVZ with new one */
7503 		zap_cursor_t zc;
7504 		zap_attribute_t za;
7505 
7506 		for (zap_cursor_init(&zc, spa->spa_meta_objset,
7507 		    spa->spa_all_vdev_zaps);
7508 		    zap_cursor_retrieve(&zc, &za) == 0;
7509 		    zap_cursor_advance(&zc)) {
7510 			uint64_t vdzap = za.za_first_integer;
7511 			if (zap_lookup_int(spa->spa_meta_objset, new_avz,
7512 			    vdzap) == ENOENT) {
7513 				/*
7514 				 * ZAP is listed in old AVZ but not in new one;
7515 				 * destroy it
7516 				 */
7517 				VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
7518 				    tx));
7519 			}
7520 		}
7521 
7522 		zap_cursor_fini(&zc);
7523 
7524 		/* Destroy the old AVZ */
7525 		VERIFY0(zap_destroy(spa->spa_meta_objset,
7526 		    spa->spa_all_vdev_zaps, tx));
7527 
7528 		/* Replace the old AVZ in the dir obj with the new one */
7529 		VERIFY0(zap_update(spa->spa_meta_objset,
7530 		    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
7531 		    sizeof (new_avz), 1, &new_avz, tx));
7532 
7533 		spa->spa_all_vdev_zaps = new_avz;
7534 	} else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
7535 		zap_cursor_t zc;
7536 		zap_attribute_t za;
7537 
7538 		/* Walk through the AVZ and destroy all listed ZAPs */
7539 		for (zap_cursor_init(&zc, spa->spa_meta_objset,
7540 		    spa->spa_all_vdev_zaps);
7541 		    zap_cursor_retrieve(&zc, &za) == 0;
7542 		    zap_cursor_advance(&zc)) {
7543 			uint64_t zap = za.za_first_integer;
7544 			VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
7545 		}
7546 
7547 		zap_cursor_fini(&zc);
7548 
7549 		/* Destroy and unlink the AVZ itself */
7550 		VERIFY0(zap_destroy(spa->spa_meta_objset,
7551 		    spa->spa_all_vdev_zaps, tx));
7552 		VERIFY0(zap_remove(spa->spa_meta_objset,
7553 		    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
7554 		spa->spa_all_vdev_zaps = 0;
7555 	}
7556 
7557 	if (spa->spa_all_vdev_zaps == 0) {
7558 		spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
7559 		    DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
7560 		    DMU_POOL_VDEV_ZAP_MAP, tx);
7561 	}
7562 	spa->spa_avz_action = AVZ_ACTION_NONE;
7563 
7564 	/* Create ZAPs for vdevs that don't have them. */
7565 	vdev_construct_zaps(spa->spa_root_vdev, tx);
7566 
7567 	config = spa_config_generate(spa, spa->spa_root_vdev,
7568 	    dmu_tx_get_txg(tx), B_FALSE);
7569 
7570 	/*
7571 	 * If we're upgrading the spa version then make sure that
7572 	 * the config object gets updated with the correct version.
7573 	 */
7574 	if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
7575 		fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7576 		    spa->spa_uberblock.ub_version);
7577 
7578 	spa_config_exit(spa, SCL_STATE, FTAG);
7579 
7580 	nvlist_free(spa->spa_config_syncing);
7581 	spa->spa_config_syncing = config;
7582 
7583 	spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
7584 }
7585 
7586 static void
7587 spa_sync_version(void *arg, dmu_tx_t *tx)
7588 {
7589 	uint64_t *versionp = arg;
7590 	uint64_t version = *versionp;
7591 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7592 
7593 	/*
7594 	 * Setting the version is special cased when first creating the pool.
7595 	 */
7596 	ASSERT(tx->tx_txg != TXG_INITIAL);
7597 
7598 	ASSERT(SPA_VERSION_IS_SUPPORTED(version));
7599 	ASSERT(version >= spa_version(spa));
7600 
7601 	spa->spa_uberblock.ub_version = version;
7602 	vdev_config_dirty(spa->spa_root_vdev);
7603 	spa_history_log_internal(spa, "set", tx, "version=%lld", version);
7604 }
7605 
7606 /*
7607  * Set zpool properties.
7608  */
7609 static void
7610 spa_sync_props(void *arg, dmu_tx_t *tx)
7611 {
7612 	nvlist_t *nvp = arg;
7613 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7614 	objset_t *mos = spa->spa_meta_objset;
7615 	nvpair_t *elem = NULL;
7616 
7617 	mutex_enter(&spa->spa_props_lock);
7618 
7619 	while ((elem = nvlist_next_nvpair(nvp, elem))) {
7620 		uint64_t intval;
7621 		char *strval, *fname;
7622 		zpool_prop_t prop;
7623 		const char *propname;
7624 		zprop_type_t proptype;
7625 		spa_feature_t fid;
7626 
7627 		switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
7628 		case ZPOOL_PROP_INVAL:
7629 			/*
7630 			 * We checked this earlier in spa_prop_validate().
7631 			 */
7632 			ASSERT(zpool_prop_feature(nvpair_name(elem)));
7633 
7634 			fname = strchr(nvpair_name(elem), '@') + 1;
7635 			VERIFY0(zfeature_lookup_name(fname, &fid));
7636 
7637 			spa_feature_enable(spa, fid, tx);
7638 			spa_history_log_internal(spa, "set", tx,
7639 			    "%s=enabled", nvpair_name(elem));
7640 			break;
7641 
7642 		case ZPOOL_PROP_VERSION:
7643 			intval = fnvpair_value_uint64(elem);
7644 			/*
7645 			 * The version is synced seperatly before other
7646 			 * properties and should be correct by now.
7647 			 */
7648 			ASSERT3U(spa_version(spa), >=, intval);
7649 			break;
7650 
7651 		case ZPOOL_PROP_ALTROOT:
7652 			/*
7653 			 * 'altroot' is a non-persistent property. It should
7654 			 * have been set temporarily at creation or import time.
7655 			 */
7656 			ASSERT(spa->spa_root != NULL);
7657 			break;
7658 
7659 		case ZPOOL_PROP_READONLY:
7660 		case ZPOOL_PROP_CACHEFILE:
7661 			/*
7662 			 * 'readonly' and 'cachefile' are also non-persisitent
7663 			 * properties.
7664 			 */
7665 			break;
7666 		case ZPOOL_PROP_COMMENT:
7667 			strval = fnvpair_value_string(elem);
7668 			if (spa->spa_comment != NULL)
7669 				spa_strfree(spa->spa_comment);
7670 			spa->spa_comment = spa_strdup(strval);
7671 			/*
7672 			 * We need to dirty the configuration on all the vdevs
7673 			 * so that their labels get updated.  It's unnecessary
7674 			 * to do this for pool creation since the vdev's
7675 			 * configuratoin has already been dirtied.
7676 			 */
7677 			if (tx->tx_txg != TXG_INITIAL)
7678 				vdev_config_dirty(spa->spa_root_vdev);
7679 			spa_history_log_internal(spa, "set", tx,
7680 			    "%s=%s", nvpair_name(elem), strval);
7681 			break;
7682 		default:
7683 			/*
7684 			 * Set pool property values in the poolprops mos object.
7685 			 */
7686 			if (spa->spa_pool_props_object == 0) {
7687 				spa->spa_pool_props_object =
7688 				    zap_create_link(mos, DMU_OT_POOL_PROPS,
7689 				    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
7690 				    tx);
7691 			}
7692 
7693 			/* normalize the property name */
7694 			propname = zpool_prop_to_name(prop);
7695 			proptype = zpool_prop_get_type(prop);
7696 
7697 			if (nvpair_type(elem) == DATA_TYPE_STRING) {
7698 				ASSERT(proptype == PROP_TYPE_STRING);
7699 				strval = fnvpair_value_string(elem);
7700 				VERIFY0(zap_update(mos,
7701 				    spa->spa_pool_props_object, propname,
7702 				    1, strlen(strval) + 1, strval, tx));
7703 				spa_history_log_internal(spa, "set", tx,
7704 				    "%s=%s", nvpair_name(elem), strval);
7705 			} else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
7706 				intval = fnvpair_value_uint64(elem);
7707 
7708 				if (proptype == PROP_TYPE_INDEX) {
7709 					const char *unused;
7710 					VERIFY0(zpool_prop_index_to_string(
7711 					    prop, intval, &unused));
7712 				}
7713 				VERIFY0(zap_update(mos,
7714 				    spa->spa_pool_props_object, propname,
7715 				    8, 1, &intval, tx));
7716 				spa_history_log_internal(spa, "set", tx,
7717 				    "%s=%lld", nvpair_name(elem), intval);
7718 			} else {
7719 				ASSERT(0); /* not allowed */
7720 			}
7721 
7722 			switch (prop) {
7723 			case ZPOOL_PROP_DELEGATION:
7724 				spa->spa_delegation = intval;
7725 				break;
7726 			case ZPOOL_PROP_BOOTFS:
7727 				spa->spa_bootfs = intval;
7728 				break;
7729 			case ZPOOL_PROP_FAILUREMODE:
7730 				spa->spa_failmode = intval;
7731 				break;
7732 			case ZPOOL_PROP_AUTOEXPAND:
7733 				spa->spa_autoexpand = intval;
7734 				if (tx->tx_txg != TXG_INITIAL)
7735 					spa_async_request(spa,
7736 					    SPA_ASYNC_AUTOEXPAND);
7737 				break;
7738 			case ZPOOL_PROP_MULTIHOST:
7739 				spa->spa_multihost = intval;
7740 				break;
7741 			case ZPOOL_PROP_DEDUPDITTO:
7742 				spa->spa_dedup_ditto = intval;
7743 				break;
7744 			default:
7745 				break;
7746 			}
7747 		}
7748 
7749 	}
7750 
7751 	mutex_exit(&spa->spa_props_lock);
7752 }
7753 
7754 /*
7755  * Perform one-time upgrade on-disk changes.  spa_version() does not
7756  * reflect the new version this txg, so there must be no changes this
7757  * txg to anything that the upgrade code depends on after it executes.
7758  * Therefore this must be called after dsl_pool_sync() does the sync
7759  * tasks.
7760  */
7761 static void
7762 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
7763 {
7764 	if (spa_sync_pass(spa) != 1)
7765 		return;
7766 
7767 	dsl_pool_t *dp = spa->spa_dsl_pool;
7768 	rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
7769 
7770 	if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
7771 	    spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
7772 		dsl_pool_create_origin(dp, tx);
7773 
7774 		/* Keeping the origin open increases spa_minref */
7775 		spa->spa_minref += 3;
7776 	}
7777 
7778 	if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
7779 	    spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
7780 		dsl_pool_upgrade_clones(dp, tx);
7781 	}
7782 
7783 	if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
7784 	    spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
7785 		dsl_pool_upgrade_dir_clones(dp, tx);
7786 
7787 		/* Keeping the freedir open increases spa_minref */
7788 		spa->spa_minref += 3;
7789 	}
7790 
7791 	if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
7792 	    spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7793 		spa_feature_create_zap_objects(spa, tx);
7794 	}
7795 
7796 	/*
7797 	 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
7798 	 * when possibility to use lz4 compression for metadata was added
7799 	 * Old pools that have this feature enabled must be upgraded to have
7800 	 * this feature active
7801 	 */
7802 	if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7803 		boolean_t lz4_en = spa_feature_is_enabled(spa,
7804 		    SPA_FEATURE_LZ4_COMPRESS);
7805 		boolean_t lz4_ac = spa_feature_is_active(spa,
7806 		    SPA_FEATURE_LZ4_COMPRESS);
7807 
7808 		if (lz4_en && !lz4_ac)
7809 			spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
7810 	}
7811 
7812 	/*
7813 	 * If we haven't written the salt, do so now.  Note that the
7814 	 * feature may not be activated yet, but that's fine since
7815 	 * the presence of this ZAP entry is backwards compatible.
7816 	 */
7817 	if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7818 	    DMU_POOL_CHECKSUM_SALT) == ENOENT) {
7819 		VERIFY0(zap_add(spa->spa_meta_objset,
7820 		    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
7821 		    sizeof (spa->spa_cksum_salt.zcs_bytes),
7822 		    spa->spa_cksum_salt.zcs_bytes, tx));
7823 	}
7824 
7825 	rrw_exit(&dp->dp_config_rwlock, FTAG);
7826 }
7827 
7828 static void
7829 vdev_indirect_state_sync_verify(vdev_t *vd)
7830 {
7831 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
7832 	vdev_indirect_births_t *vib = vd->vdev_indirect_births;
7833 
7834 	if (vd->vdev_ops == &vdev_indirect_ops) {
7835 		ASSERT(vim != NULL);
7836 		ASSERT(vib != NULL);
7837 	}
7838 
7839 	if (vdev_obsolete_sm_object(vd) != 0) {
7840 		ASSERT(vd->vdev_obsolete_sm != NULL);
7841 		ASSERT(vd->vdev_removing ||
7842 		    vd->vdev_ops == &vdev_indirect_ops);
7843 		ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
7844 		ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
7845 
7846 		ASSERT3U(vdev_obsolete_sm_object(vd), ==,
7847 		    space_map_object(vd->vdev_obsolete_sm));
7848 		ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
7849 		    space_map_allocated(vd->vdev_obsolete_sm));
7850 	}
7851 	ASSERT(vd->vdev_obsolete_segments != NULL);
7852 
7853 	/*
7854 	 * Since frees / remaps to an indirect vdev can only
7855 	 * happen in syncing context, the obsolete segments
7856 	 * tree must be empty when we start syncing.
7857 	 */
7858 	ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
7859 }
7860 
7861 /*
7862  * Set the top-level vdev's max queue depth. Evaluate each top-level's
7863  * async write queue depth in case it changed. The max queue depth will
7864  * not change in the middle of syncing out this txg.
7865  */
7866 static void
7867 spa_sync_adjust_vdev_max_queue_depth(spa_t *spa)
7868 {
7869 	ASSERT(spa_writeable(spa));
7870 
7871 	vdev_t *rvd = spa->spa_root_vdev;
7872 	uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
7873 	    zfs_vdev_queue_depth_pct / 100;
7874 	metaslab_class_t *normal = spa_normal_class(spa);
7875 	metaslab_class_t *special = spa_special_class(spa);
7876 	metaslab_class_t *dedup = spa_dedup_class(spa);
7877 
7878 	uint64_t slots_per_allocator = 0;
7879 	for (int c = 0; c < rvd->vdev_children; c++) {
7880 		vdev_t *tvd = rvd->vdev_child[c];
7881 
7882 		metaslab_group_t *mg = tvd->vdev_mg;
7883 		if (mg == NULL || !metaslab_group_initialized(mg))
7884 			continue;
7885 
7886 		metaslab_class_t *mc = mg->mg_class;
7887 		if (mc != normal && mc != special && mc != dedup)
7888 			continue;
7889 
7890 		/*
7891 		 * It is safe to do a lock-free check here because only async
7892 		 * allocations look at mg_max_alloc_queue_depth, and async
7893 		 * allocations all happen from spa_sync().
7894 		 */
7895 		for (int i = 0; i < spa->spa_alloc_count; i++)
7896 			ASSERT0(zfs_refcount_count(
7897 			    &(mg->mg_alloc_queue_depth[i])));
7898 		mg->mg_max_alloc_queue_depth = max_queue_depth;
7899 
7900 		for (int i = 0; i < spa->spa_alloc_count; i++) {
7901 			mg->mg_cur_max_alloc_queue_depth[i] =
7902 			    zfs_vdev_def_queue_depth;
7903 		}
7904 		slots_per_allocator += zfs_vdev_def_queue_depth;
7905 	}
7906 
7907 	for (int i = 0; i < spa->spa_alloc_count; i++) {
7908 		ASSERT0(zfs_refcount_count(&normal->mc_alloc_slots[i]));
7909 		ASSERT0(zfs_refcount_count(&special->mc_alloc_slots[i]));
7910 		ASSERT0(zfs_refcount_count(&dedup->mc_alloc_slots[i]));
7911 		normal->mc_alloc_max_slots[i] = slots_per_allocator;
7912 		special->mc_alloc_max_slots[i] = slots_per_allocator;
7913 		dedup->mc_alloc_max_slots[i] = slots_per_allocator;
7914 	}
7915 	normal->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
7916 	special->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
7917 	dedup->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
7918 }
7919 
7920 static void
7921 spa_sync_condense_indirect(spa_t *spa, dmu_tx_t *tx)
7922 {
7923 	ASSERT(spa_writeable(spa));
7924 
7925 	vdev_t *rvd = spa->spa_root_vdev;
7926 	for (int c = 0; c < rvd->vdev_children; c++) {
7927 		vdev_t *vd = rvd->vdev_child[c];
7928 		vdev_indirect_state_sync_verify(vd);
7929 
7930 		if (vdev_indirect_should_condense(vd)) {
7931 			spa_condense_indirect_start_sync(vd, tx);
7932 			break;
7933 		}
7934 	}
7935 }
7936 
7937 static void
7938 spa_sync_iterate_to_convergence(spa_t *spa, dmu_tx_t *tx)
7939 {
7940 	objset_t *mos = spa->spa_meta_objset;
7941 	dsl_pool_t *dp = spa->spa_dsl_pool;
7942 	uint64_t txg = tx->tx_txg;
7943 	bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
7944 
7945 	do {
7946 		int pass = ++spa->spa_sync_pass;
7947 
7948 		spa_sync_config_object(spa, tx);
7949 		spa_sync_aux_dev(spa, &spa->spa_spares, tx,
7950 		    ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
7951 		spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
7952 		    ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
7953 		spa_errlog_sync(spa, txg);
7954 		dsl_pool_sync(dp, txg);
7955 
7956 		if (pass < zfs_sync_pass_deferred_free) {
7957 			spa_sync_frees(spa, free_bpl, tx);
7958 		} else {
7959 			/*
7960 			 * We can not defer frees in pass 1, because
7961 			 * we sync the deferred frees later in pass 1.
7962 			 */
7963 			ASSERT3U(pass, >, 1);
7964 			bplist_iterate(free_bpl, bpobj_enqueue_cb,
7965 			    &spa->spa_deferred_bpobj, tx);
7966 		}
7967 
7968 		ddt_sync(spa, txg);
7969 		dsl_scan_sync(dp, tx);
7970 		svr_sync(spa, tx);
7971 		spa_sync_upgrades(spa, tx);
7972 
7973 		vdev_t *vd = NULL;
7974 		while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
7975 		    != NULL)
7976 			vdev_sync(vd, txg);
7977 
7978 		/*
7979 		 * Note: We need to check if the MOS is dirty because we could
7980 		 * have marked the MOS dirty without updating the uberblock
7981 		 * (e.g. if we have sync tasks but no dirty user data). We need
7982 		 * to check the uberblock's rootbp because it is updated if we
7983 		 * have synced out dirty data (though in this case the MOS will
7984 		 * most likely also be dirty due to second order effects, we
7985 		 * don't want to rely on that here).
7986 		 */
7987 		if (pass == 1 &&
7988 		    spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
7989 		    !dmu_objset_is_dirty(mos, txg)) {
7990 			/*
7991 			 * Nothing changed on the first pass, therefore this
7992 			 * TXG is a no-op. Avoid syncing deferred frees, so
7993 			 * that we can keep this TXG as a no-op.
7994 			 */
7995 			ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
7996 			ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
7997 			ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
7998 			ASSERT(txg_list_empty(&dp->dp_early_sync_tasks, txg));
7999 			break;
8000 		}
8001 
8002 		spa_sync_deferred_frees(spa, tx);
8003 	} while (dmu_objset_is_dirty(mos, txg));
8004 }
8005 
8006 /*
8007  * Rewrite the vdev configuration (which includes the uberblock) to
8008  * commit the transaction group.
8009  *
8010  * If there are no dirty vdevs, we sync the uberblock to a few random
8011  * top-level vdevs that are known to be visible in the config cache
8012  * (see spa_vdev_add() for a complete description). If there *are* dirty
8013  * vdevs, sync the uberblock to all vdevs.
8014  */
8015 static void
8016 spa_sync_rewrite_vdev_config(spa_t *spa, dmu_tx_t *tx)
8017 {
8018 	vdev_t *rvd = spa->spa_root_vdev;
8019 	uint64_t txg = tx->tx_txg;
8020 
8021 	for (;;) {
8022 		int error = 0;
8023 
8024 		/*
8025 		 * We hold SCL_STATE to prevent vdev open/close/etc.
8026 		 * while we're attempting to write the vdev labels.
8027 		 */
8028 		spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8029 
8030 		if (list_is_empty(&spa->spa_config_dirty_list)) {
8031 			vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
8032 			int svdcount = 0;
8033 			int children = rvd->vdev_children;
8034 			int c0 = spa_get_random(children);
8035 
8036 			for (int c = 0; c < children; c++) {
8037 				vdev_t *vd =
8038 				    rvd->vdev_child[(c0 + c) % children];
8039 
8040 				/* Stop when revisiting the first vdev */
8041 				if (c > 0 && svd[0] == vd)
8042 					break;
8043 
8044 				if (vd->vdev_ms_array == 0 ||
8045 				    vd->vdev_islog ||
8046 				    !vdev_is_concrete(vd))
8047 					continue;
8048 
8049 				svd[svdcount++] = vd;
8050 				if (svdcount == SPA_SYNC_MIN_VDEVS)
8051 					break;
8052 			}
8053 			error = vdev_config_sync(svd, svdcount, txg);
8054 		} else {
8055 			error = vdev_config_sync(rvd->vdev_child,
8056 			    rvd->vdev_children, txg);
8057 		}
8058 
8059 		if (error == 0)
8060 			spa->spa_last_synced_guid = rvd->vdev_guid;
8061 
8062 		spa_config_exit(spa, SCL_STATE, FTAG);
8063 
8064 		if (error == 0)
8065 			break;
8066 		zio_suspend(spa, NULL, ZIO_SUSPEND_IOERR);
8067 		zio_resume_wait(spa);
8068 	}
8069 }
8070 
8071 /*
8072  * Sync the specified transaction group.  New blocks may be dirtied as
8073  * part of the process, so we iterate until it converges.
8074  */
8075 void
8076 spa_sync(spa_t *spa, uint64_t txg)
8077 {
8078 	vdev_t *vd = NULL;
8079 
8080 	VERIFY(spa_writeable(spa));
8081 
8082 	/*
8083 	 * Wait for i/os issued in open context that need to complete
8084 	 * before this txg syncs.
8085 	 */
8086 	(void) zio_wait(spa->spa_txg_zio[txg & TXG_MASK]);
8087 	spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL,
8088 	    ZIO_FLAG_CANFAIL);
8089 
8090 	/*
8091 	 * Lock out configuration changes.
8092 	 */
8093 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8094 
8095 	spa->spa_syncing_txg = txg;
8096 	spa->spa_sync_pass = 0;
8097 
8098 	for (int i = 0; i < spa->spa_alloc_count; i++) {
8099 		mutex_enter(&spa->spa_alloc_locks[i]);
8100 		VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8101 		mutex_exit(&spa->spa_alloc_locks[i]);
8102 	}
8103 
8104 	/*
8105 	 * If there are any pending vdev state changes, convert them
8106 	 * into config changes that go out with this transaction group.
8107 	 */
8108 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8109 	while (list_head(&spa->spa_state_dirty_list) != NULL) {
8110 		/*
8111 		 * We need the write lock here because, for aux vdevs,
8112 		 * calling vdev_config_dirty() modifies sav_config.
8113 		 * This is ugly and will become unnecessary when we
8114 		 * eliminate the aux vdev wart by integrating all vdevs
8115 		 * into the root vdev tree.
8116 		 */
8117 		spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8118 		spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
8119 		while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
8120 			vdev_state_clean(vd);
8121 			vdev_config_dirty(vd);
8122 		}
8123 		spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8124 		spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
8125 	}
8126 	spa_config_exit(spa, SCL_STATE, FTAG);
8127 
8128 	dsl_pool_t *dp = spa->spa_dsl_pool;
8129 	dmu_tx_t *tx = dmu_tx_create_assigned(dp, txg);
8130 
8131 	spa->spa_sync_starttime = gethrtime();
8132 	VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
8133 	    spa->spa_sync_starttime + spa->spa_deadman_synctime));
8134 
8135 	/*
8136 	 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
8137 	 * set spa_deflate if we have no raid-z vdevs.
8138 	 */
8139 	if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
8140 	    spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
8141 		vdev_t *rvd = spa->spa_root_vdev;
8142 
8143 		int i;
8144 		for (i = 0; i < rvd->vdev_children; i++) {
8145 			vd = rvd->vdev_child[i];
8146 			if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
8147 				break;
8148 		}
8149 		if (i == rvd->vdev_children) {
8150 			spa->spa_deflate = TRUE;
8151 			VERIFY0(zap_add(spa->spa_meta_objset,
8152 			    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
8153 			    sizeof (uint64_t), 1, &spa->spa_deflate, tx));
8154 		}
8155 	}
8156 
8157 	spa_sync_adjust_vdev_max_queue_depth(spa);
8158 
8159 	spa_sync_condense_indirect(spa, tx);
8160 
8161 	spa_sync_iterate_to_convergence(spa, tx);
8162 
8163 #ifdef ZFS_DEBUG
8164 	if (!list_is_empty(&spa->spa_config_dirty_list)) {
8165 		/*
8166 		 * Make sure that the number of ZAPs for all the vdevs matches
8167 		 * the number of ZAPs in the per-vdev ZAP list. This only gets
8168 		 * called if the config is dirty; otherwise there may be
8169 		 * outstanding AVZ operations that weren't completed in
8170 		 * spa_sync_config_object.
8171 		 */
8172 		uint64_t all_vdev_zap_entry_count;
8173 		ASSERT0(zap_count(spa->spa_meta_objset,
8174 		    spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
8175 		ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
8176 		    all_vdev_zap_entry_count);
8177 	}
8178 #endif
8179 
8180 	if (spa->spa_vdev_removal != NULL) {
8181 		ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
8182 	}
8183 
8184 	spa_sync_rewrite_vdev_config(spa, tx);
8185 	dmu_tx_commit(tx);
8186 
8187 	VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
8188 
8189 	/*
8190 	 * Clear the dirty config list.
8191 	 */
8192 	while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
8193 		vdev_config_clean(vd);
8194 
8195 	/*
8196 	 * Now that the new config has synced transactionally,
8197 	 * let it become visible to the config cache.
8198 	 */
8199 	if (spa->spa_config_syncing != NULL) {
8200 		spa_config_set(spa, spa->spa_config_syncing);
8201 		spa->spa_config_txg = txg;
8202 		spa->spa_config_syncing = NULL;
8203 	}
8204 
8205 	dsl_pool_sync_done(dp, txg);
8206 
8207 	for (int i = 0; i < spa->spa_alloc_count; i++) {
8208 		mutex_enter(&spa->spa_alloc_locks[i]);
8209 		VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8210 		mutex_exit(&spa->spa_alloc_locks[i]);
8211 	}
8212 
8213 	/*
8214 	 * Update usable space statistics.
8215 	 */
8216 	while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
8217 	    != NULL)
8218 		vdev_sync_done(vd, txg);
8219 
8220 	spa_update_dspace(spa);
8221 
8222 	/*
8223 	 * It had better be the case that we didn't dirty anything
8224 	 * since vdev_config_sync().
8225 	 */
8226 	ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8227 	ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8228 	ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
8229 
8230 	while (zfs_pause_spa_sync)
8231 		delay(1);
8232 
8233 	spa->spa_sync_pass = 0;
8234 
8235 	/*
8236 	 * Update the last synced uberblock here. We want to do this at
8237 	 * the end of spa_sync() so that consumers of spa_last_synced_txg()
8238 	 * will be guaranteed that all the processing associated with
8239 	 * that txg has been completed.
8240 	 */
8241 	spa->spa_ubsync = spa->spa_uberblock;
8242 	spa_config_exit(spa, SCL_CONFIG, FTAG);
8243 
8244 	spa_handle_ignored_writes(spa);
8245 
8246 	/*
8247 	 * If any async tasks have been requested, kick them off.
8248 	 */
8249 	spa_async_dispatch(spa);
8250 }
8251 
8252 /*
8253  * Sync all pools.  We don't want to hold the namespace lock across these
8254  * operations, so we take a reference on the spa_t and drop the lock during the
8255  * sync.
8256  */
8257 void
8258 spa_sync_allpools(void)
8259 {
8260 	spa_t *spa = NULL;
8261 	mutex_enter(&spa_namespace_lock);
8262 	while ((spa = spa_next(spa)) != NULL) {
8263 		if (spa_state(spa) != POOL_STATE_ACTIVE ||
8264 		    !spa_writeable(spa) || spa_suspended(spa))
8265 			continue;
8266 		spa_open_ref(spa, FTAG);
8267 		mutex_exit(&spa_namespace_lock);
8268 		txg_wait_synced(spa_get_dsl(spa), 0);
8269 		mutex_enter(&spa_namespace_lock);
8270 		spa_close(spa, FTAG);
8271 	}
8272 	mutex_exit(&spa_namespace_lock);
8273 }
8274 
8275 /*
8276  * ==========================================================================
8277  * Miscellaneous routines
8278  * ==========================================================================
8279  */
8280 
8281 /*
8282  * Remove all pools in the system.
8283  */
8284 void
8285 spa_evict_all(void)
8286 {
8287 	spa_t *spa;
8288 
8289 	/*
8290 	 * Remove all cached state.  All pools should be closed now,
8291 	 * so every spa in the AVL tree should be unreferenced.
8292 	 */
8293 	mutex_enter(&spa_namespace_lock);
8294 	while ((spa = spa_next(NULL)) != NULL) {
8295 		/*
8296 		 * Stop async tasks.  The async thread may need to detach
8297 		 * a device that's been replaced, which requires grabbing
8298 		 * spa_namespace_lock, so we must drop it here.
8299 		 */
8300 		spa_open_ref(spa, FTAG);
8301 		mutex_exit(&spa_namespace_lock);
8302 		spa_async_suspend(spa);
8303 		mutex_enter(&spa_namespace_lock);
8304 		spa_close(spa, FTAG);
8305 
8306 		if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
8307 			spa_unload(spa);
8308 			spa_deactivate(spa);
8309 		}
8310 		spa_remove(spa);
8311 	}
8312 	mutex_exit(&spa_namespace_lock);
8313 }
8314 
8315 vdev_t *
8316 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
8317 {
8318 	vdev_t *vd;
8319 	int i;
8320 
8321 	if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
8322 		return (vd);
8323 
8324 	if (aux) {
8325 		for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
8326 			vd = spa->spa_l2cache.sav_vdevs[i];
8327 			if (vd->vdev_guid == guid)
8328 				return (vd);
8329 		}
8330 
8331 		for (i = 0; i < spa->spa_spares.sav_count; i++) {
8332 			vd = spa->spa_spares.sav_vdevs[i];
8333 			if (vd->vdev_guid == guid)
8334 				return (vd);
8335 		}
8336 	}
8337 
8338 	return (NULL);
8339 }
8340 
8341 void
8342 spa_upgrade(spa_t *spa, uint64_t version)
8343 {
8344 	ASSERT(spa_writeable(spa));
8345 
8346 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
8347 
8348 	/*
8349 	 * This should only be called for a non-faulted pool, and since a
8350 	 * future version would result in an unopenable pool, this shouldn't be
8351 	 * possible.
8352 	 */
8353 	ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
8354 	ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
8355 
8356 	spa->spa_uberblock.ub_version = version;
8357 	vdev_config_dirty(spa->spa_root_vdev);
8358 
8359 	spa_config_exit(spa, SCL_ALL, FTAG);
8360 
8361 	txg_wait_synced(spa_get_dsl(spa), 0);
8362 }
8363 
8364 boolean_t
8365 spa_has_spare(spa_t *spa, uint64_t guid)
8366 {
8367 	int i;
8368 	uint64_t spareguid;
8369 	spa_aux_vdev_t *sav = &spa->spa_spares;
8370 
8371 	for (i = 0; i < sav->sav_count; i++)
8372 		if (sav->sav_vdevs[i]->vdev_guid == guid)
8373 			return (B_TRUE);
8374 
8375 	for (i = 0; i < sav->sav_npending; i++) {
8376 		if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
8377 		    &spareguid) == 0 && spareguid == guid)
8378 			return (B_TRUE);
8379 	}
8380 
8381 	return (B_FALSE);
8382 }
8383 
8384 /*
8385  * Check if a pool has an active shared spare device.
8386  * Note: reference count of an active spare is 2, as a spare and as a replace
8387  */
8388 static boolean_t
8389 spa_has_active_shared_spare(spa_t *spa)
8390 {
8391 	int i, refcnt;
8392 	uint64_t pool;
8393 	spa_aux_vdev_t *sav = &spa->spa_spares;
8394 
8395 	for (i = 0; i < sav->sav_count; i++) {
8396 		if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
8397 		    &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
8398 		    refcnt > 2)
8399 			return (B_TRUE);
8400 	}
8401 
8402 	return (B_FALSE);
8403 }
8404 
8405 sysevent_t *
8406 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8407 {
8408 	sysevent_t		*ev = NULL;
8409 #ifdef _KERNEL
8410 	sysevent_attr_list_t	*attr = NULL;
8411 	sysevent_value_t	value;
8412 
8413 	ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
8414 	    SE_SLEEP);
8415 	ASSERT(ev != NULL);
8416 
8417 	value.value_type = SE_DATA_TYPE_STRING;
8418 	value.value.sv_string = spa_name(spa);
8419 	if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
8420 		goto done;
8421 
8422 	value.value_type = SE_DATA_TYPE_UINT64;
8423 	value.value.sv_uint64 = spa_guid(spa);
8424 	if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
8425 		goto done;
8426 
8427 	if (vd) {
8428 		value.value_type = SE_DATA_TYPE_UINT64;
8429 		value.value.sv_uint64 = vd->vdev_guid;
8430 		if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
8431 		    SE_SLEEP) != 0)
8432 			goto done;
8433 
8434 		if (vd->vdev_path) {
8435 			value.value_type = SE_DATA_TYPE_STRING;
8436 			value.value.sv_string = vd->vdev_path;
8437 			if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
8438 			    &value, SE_SLEEP) != 0)
8439 				goto done;
8440 		}
8441 	}
8442 
8443 	if (hist_nvl != NULL) {
8444 		fnvlist_merge((nvlist_t *)attr, hist_nvl);
8445 	}
8446 
8447 	if (sysevent_attach_attributes(ev, attr) != 0)
8448 		goto done;
8449 	attr = NULL;
8450 
8451 done:
8452 	if (attr)
8453 		sysevent_free_attr(attr);
8454 
8455 #endif
8456 	return (ev);
8457 }
8458 
8459 void
8460 spa_event_post(sysevent_t *ev)
8461 {
8462 #ifdef _KERNEL
8463 	sysevent_id_t		eid;
8464 
8465 	(void) log_sysevent(ev, SE_SLEEP, &eid);
8466 	sysevent_free(ev);
8467 #endif
8468 }
8469 
8470 void
8471 spa_event_discard(sysevent_t *ev)
8472 {
8473 #ifdef _KERNEL
8474 	sysevent_free(ev);
8475 #endif
8476 }
8477 
8478 /*
8479  * Post a sysevent corresponding to the given event.  The 'name' must be one of
8480  * the event definitions in sys/sysevent/eventdefs.h.  The payload will be
8481  * filled in from the spa and (optionally) the vdev and history nvl.  This
8482  * doesn't do anything in the userland libzpool, as we don't want consumers to
8483  * misinterpret ztest or zdb as real changes.
8484  */
8485 void
8486 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8487 {
8488 	spa_event_post(spa_event_create(spa, vd, hist_nvl, name));
8489 }
8490