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