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