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