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