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