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