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