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