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