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