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