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