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