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