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