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