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