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