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