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