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