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