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