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