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