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