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