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