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