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