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