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