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