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