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