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