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