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