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