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