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