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.
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.
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]
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25 * Copyright (c) 2015, Nexenta Systems, Inc. All rights reserved.
26 * Copyright (c) 2013 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
27 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28 * Copyright 2013 Saso Kiselkov. All rights reserved.
29 * Copyright (c) 2014 Integros [integros.com]
30 * Copyright 2016 Toomas Soome <tsoome@me.com>
31 * Copyright 2018 Joyent, Inc.
32 * Copyright (c) 2017 Datto Inc.
33 * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
37 * SPA: Storage Pool Allocator
39 * This file contains all the routines used when modifying on-disk SPA state.
40 * This includes opening, importing, destroying, exporting a pool, and syncing a
44 #include <sys/zfs_context.h>
45 #include <sys/fm/fs/zfs.h>
46 #include <sys/spa_impl.h>
48 #include <sys/zio_checksum.h>
50 #include <sys/dmu_tx.h>
54 #include <sys/vdev_impl.h>
55 #include <sys/vdev_removal.h>
56 #include <sys/vdev_indirect_mapping.h>
57 #include <sys/vdev_indirect_births.h>
58 #include <sys/vdev_initialize.h>
59 #include <sys/metaslab.h>
60 #include <sys/metaslab_impl.h>
61 #include <sys/uberblock_impl.h>
64 #include <sys/bpobj.h>
65 #include <sys/dmu_traverse.h>
66 #include <sys/dmu_objset.h>
67 #include <sys/unique.h>
68 #include <sys/dsl_pool.h>
69 #include <sys/dsl_dataset.h>
70 #include <sys/dsl_dir.h>
71 #include <sys/dsl_prop.h>
72 #include <sys/dsl_synctask.h>
73 #include <sys/fs/zfs.h>
75 #include <sys/callb.h>
76 #include <sys/spa_boot.h>
77 #include <sys/zfs_ioctl.h>
78 #include <sys/dsl_scan.h>
79 #include <sys/dmu_send.h>
80 #include <sys/dsl_destroy.h>
81 #include <sys/dsl_userhold.h>
82 #include <sys/zfeature.h>
84 #include <sys/trim_map.h>
88 #include <sys/callb.h>
89 #include <sys/cpupart.h>
94 #include "zfs_comutil.h"
96 /* Check hostid on import? */
97 static int check_hostid = 1;
100 * The interval, in seconds, at which failed configuration cache file writes
103 int zfs_ccw_retry_interval = 300;
105 SYSCTL_DECL(_vfs_zfs);
106 SYSCTL_INT(_vfs_zfs, OID_AUTO, check_hostid, CTLFLAG_RWTUN, &check_hostid, 0,
107 "Check hostid on import?");
108 TUNABLE_INT("vfs.zfs.ccw_retry_interval", &zfs_ccw_retry_interval);
109 SYSCTL_INT(_vfs_zfs, OID_AUTO, ccw_retry_interval, CTLFLAG_RW,
110 &zfs_ccw_retry_interval, 0,
111 "Configuration cache file write, retry after failure, interval (seconds)");
113 typedef enum zti_modes {
114 ZTI_MODE_FIXED, /* value is # of threads (min 1) */
115 ZTI_MODE_BATCH, /* cpu-intensive; value is ignored */
116 ZTI_MODE_NULL, /* don't create a taskq */
120 #define ZTI_P(n, q) { ZTI_MODE_FIXED, (n), (q) }
121 #define ZTI_BATCH { ZTI_MODE_BATCH, 0, 1 }
122 #define ZTI_NULL { ZTI_MODE_NULL, 0, 0 }
124 #define ZTI_N(n) ZTI_P(n, 1)
125 #define ZTI_ONE ZTI_N(1)
127 typedef struct zio_taskq_info {
128 zti_modes_t zti_mode;
133 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
134 "issue", "issue_high", "intr", "intr_high"
138 * This table defines the taskq settings for each ZFS I/O type. When
139 * initializing a pool, we use this table to create an appropriately sized
140 * taskq. Some operations are low volume and therefore have a small, static
141 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
142 * macros. Other operations process a large amount of data; the ZTI_BATCH
143 * macro causes us to create a taskq oriented for throughput. Some operations
144 * are so high frequency and short-lived that the taskq itself can become a a
145 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
146 * additional degree of parallelism specified by the number of threads per-
147 * taskq and the number of taskqs; when dispatching an event in this case, the
148 * particular taskq is chosen at random.
150 * The different taskq priorities are to handle the different contexts (issue
151 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
152 * need to be handled with minimum delay.
154 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
155 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
156 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* NULL */
157 { ZTI_N(8), ZTI_NULL, ZTI_P(12, 8), ZTI_NULL }, /* READ */
158 { ZTI_BATCH, ZTI_N(5), ZTI_N(8), ZTI_N(5) }, /* WRITE */
159 { ZTI_P(12, 8), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* FREE */
160 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* CLAIM */
161 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* IOCTL */
164 static void spa_sync_version(void *arg, dmu_tx_t *tx);
165 static void spa_sync_props(void *arg, dmu_tx_t *tx);
166 static boolean_t spa_has_active_shared_spare(spa_t *spa);
167 static int spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport);
168 static void spa_vdev_resilver_done(spa_t *spa);
170 uint_t zio_taskq_batch_pct = 75; /* 1 thread per cpu in pset */
172 id_t zio_taskq_psrset_bind = PS_NONE;
175 boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
176 uint_t zio_taskq_basedc = 80; /* base duty cycle */
179 boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
180 extern int zfs_sync_pass_deferred_free;
183 * Report any spa_load_verify errors found, but do not fail spa_load.
184 * This is used by zdb to analyze non-idle pools.
186 boolean_t spa_load_verify_dryrun = B_FALSE;
189 * This (illegal) pool name is used when temporarily importing a spa_t in order
190 * to get the vdev stats associated with the imported devices.
192 #define TRYIMPORT_NAME "$import"
195 * For debugging purposes: print out vdev tree during pool import.
197 int spa_load_print_vdev_tree = B_FALSE;
200 * A non-zero value for zfs_max_missing_tvds means that we allow importing
201 * pools with missing top-level vdevs. This is strictly intended for advanced
202 * pool recovery cases since missing data is almost inevitable. Pools with
203 * missing devices can only be imported read-only for safety reasons, and their
204 * fail-mode will be automatically set to "continue".
206 * With 1 missing vdev we should be able to import the pool and mount all
207 * datasets. User data that was not modified after the missing device has been
208 * added should be recoverable. This means that snapshots created prior to the
209 * addition of that device should be completely intact.
211 * With 2 missing vdevs, some datasets may fail to mount since there are
212 * dataset statistics that are stored as regular metadata. Some data might be
213 * recoverable if those vdevs were added recently.
215 * With 3 or more missing vdevs, the pool is severely damaged and MOS entries
216 * may be missing entirely. Chances of data recovery are very low. Note that
217 * there are also risks of performing an inadvertent rewind as we might be
218 * missing all the vdevs with the latest uberblocks.
220 uint64_t zfs_max_missing_tvds = 0;
223 * The parameters below are similar to zfs_max_missing_tvds but are only
224 * intended for a preliminary open of the pool with an untrusted config which
225 * might be incomplete or out-dated.
227 * We are more tolerant for pools opened from a cachefile since we could have
228 * an out-dated cachefile where a device removal was not registered.
229 * We could have set the limit arbitrarily high but in the case where devices
230 * are really missing we would want to return the proper error codes; we chose
231 * SPA_DVAS_PER_BP - 1 so that some copies of the MOS would still be available
232 * and we get a chance to retrieve the trusted config.
234 uint64_t zfs_max_missing_tvds_cachefile = SPA_DVAS_PER_BP - 1;
237 * In the case where config was assembled by scanning device paths (/dev/dsks
238 * by default) we are less tolerant since all the existing devices should have
239 * been detected and we want spa_load to return the right error codes.
241 uint64_t zfs_max_missing_tvds_scan = 0;
244 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_print_vdev_tree, CTLFLAG_RWTUN,
245 &spa_load_print_vdev_tree, 0,
246 "print out vdev tree during pool import");
247 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds, CTLFLAG_RWTUN,
248 &zfs_max_missing_tvds, 0,
249 "allow importing pools with missing top-level vdevs");
250 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_cachefile, CTLFLAG_RWTUN,
251 &zfs_max_missing_tvds_cachefile, 0,
252 "allow importing pools with missing top-level vdevs in cache file");
253 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_scan, CTLFLAG_RWTUN,
254 &zfs_max_missing_tvds_scan, 0,
255 "allow importing pools with missing top-level vdevs during scan");
258 * Debugging aid that pauses spa_sync() towards the end.
260 boolean_t zfs_pause_spa_sync = B_FALSE;
263 * ==========================================================================
264 * SPA properties routines
265 * ==========================================================================
269 * Add a (source=src, propname=propval) list to an nvlist.
272 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
273 uint64_t intval, zprop_source_t src)
275 const char *propname = zpool_prop_to_name(prop);
278 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
279 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
282 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
284 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
286 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
287 nvlist_free(propval);
291 * Get property values from the spa configuration.
294 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
296 vdev_t *rvd = spa->spa_root_vdev;
297 dsl_pool_t *pool = spa->spa_dsl_pool;
298 uint64_t size, alloc, cap, version;
299 zprop_source_t src = ZPROP_SRC_NONE;
300 spa_config_dirent_t *dp;
301 metaslab_class_t *mc = spa_normal_class(spa);
303 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
306 alloc = metaslab_class_get_alloc(spa_normal_class(spa));
307 size = metaslab_class_get_space(spa_normal_class(spa));
308 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
309 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
310 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
311 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
313 spa_prop_add_list(*nvp, ZPOOL_PROP_CHECKPOINT, NULL,
314 spa->spa_checkpoint_info.sci_dspace, src);
316 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
317 metaslab_class_fragmentation(mc), src);
318 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
319 metaslab_class_expandable_space(mc), src);
320 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
321 (spa_mode(spa) == FREAD), src);
323 cap = (size == 0) ? 0 : (alloc * 100 / size);
324 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
326 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
327 ddt_get_pool_dedup_ratio(spa), src);
329 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
330 rvd->vdev_state, src);
332 version = spa_version(spa);
333 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
334 src = ZPROP_SRC_DEFAULT;
336 src = ZPROP_SRC_LOCAL;
337 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
342 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
343 * when opening pools before this version freedir will be NULL.
345 if (pool->dp_free_dir != NULL) {
346 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
347 dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
350 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
354 if (pool->dp_leak_dir != NULL) {
355 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
356 dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
359 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
364 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
366 if (spa->spa_comment != NULL) {
367 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
371 if (spa->spa_root != NULL)
372 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
375 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
376 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
377 MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
379 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
380 SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
383 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE)) {
384 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
385 DNODE_MAX_SIZE, ZPROP_SRC_NONE);
387 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
388 DNODE_MIN_SIZE, ZPROP_SRC_NONE);
391 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
392 if (dp->scd_path == NULL) {
393 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
394 "none", 0, ZPROP_SRC_LOCAL);
395 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
396 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
397 dp->scd_path, 0, ZPROP_SRC_LOCAL);
403 * Get zpool property values.
406 spa_prop_get(spa_t *spa, nvlist_t **nvp)
408 objset_t *mos = spa->spa_meta_objset;
413 VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
415 mutex_enter(&spa->spa_props_lock);
418 * Get properties from the spa config.
420 spa_prop_get_config(spa, nvp);
422 /* If no pool property object, no more prop to get. */
423 if (mos == NULL || spa->spa_pool_props_object == 0) {
424 mutex_exit(&spa->spa_props_lock);
429 * Get properties from the MOS pool property object.
431 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
432 (err = zap_cursor_retrieve(&zc, &za)) == 0;
433 zap_cursor_advance(&zc)) {
436 zprop_source_t src = ZPROP_SRC_DEFAULT;
439 if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
442 switch (za.za_integer_length) {
444 /* integer property */
445 if (za.za_first_integer !=
446 zpool_prop_default_numeric(prop))
447 src = ZPROP_SRC_LOCAL;
449 if (prop == ZPOOL_PROP_BOOTFS) {
451 dsl_dataset_t *ds = NULL;
453 dp = spa_get_dsl(spa);
454 dsl_pool_config_enter(dp, FTAG);
455 err = dsl_dataset_hold_obj(dp,
456 za.za_first_integer, FTAG, &ds);
458 dsl_pool_config_exit(dp, FTAG);
462 strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
464 dsl_dataset_name(ds, strval);
465 dsl_dataset_rele(ds, FTAG);
466 dsl_pool_config_exit(dp, FTAG);
469 intval = za.za_first_integer;
472 spa_prop_add_list(*nvp, prop, strval, intval, src);
475 kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
480 /* string property */
481 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
482 err = zap_lookup(mos, spa->spa_pool_props_object,
483 za.za_name, 1, za.za_num_integers, strval);
485 kmem_free(strval, za.za_num_integers);
488 spa_prop_add_list(*nvp, prop, strval, 0, src);
489 kmem_free(strval, za.za_num_integers);
496 zap_cursor_fini(&zc);
497 mutex_exit(&spa->spa_props_lock);
499 if (err && err != ENOENT) {
509 * Validate the given pool properties nvlist and modify the list
510 * for the property values to be set.
513 spa_prop_validate(spa_t *spa, nvlist_t *props)
516 int error = 0, reset_bootfs = 0;
518 boolean_t has_feature = B_FALSE;
521 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
523 char *strval, *slash, *check, *fname;
524 const char *propname = nvpair_name(elem);
525 zpool_prop_t prop = zpool_name_to_prop(propname);
528 case ZPOOL_PROP_INVAL:
529 if (!zpool_prop_feature(propname)) {
530 error = SET_ERROR(EINVAL);
535 * Sanitize the input.
537 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
538 error = SET_ERROR(EINVAL);
542 if (nvpair_value_uint64(elem, &intval) != 0) {
543 error = SET_ERROR(EINVAL);
548 error = SET_ERROR(EINVAL);
552 fname = strchr(propname, '@') + 1;
553 if (zfeature_lookup_name(fname, NULL) != 0) {
554 error = SET_ERROR(EINVAL);
558 has_feature = B_TRUE;
561 case ZPOOL_PROP_VERSION:
562 error = nvpair_value_uint64(elem, &intval);
564 (intval < spa_version(spa) ||
565 intval > SPA_VERSION_BEFORE_FEATURES ||
567 error = SET_ERROR(EINVAL);
570 case ZPOOL_PROP_DELEGATION:
571 case ZPOOL_PROP_AUTOREPLACE:
572 case ZPOOL_PROP_LISTSNAPS:
573 case ZPOOL_PROP_AUTOEXPAND:
574 error = nvpair_value_uint64(elem, &intval);
575 if (!error && intval > 1)
576 error = SET_ERROR(EINVAL);
579 case ZPOOL_PROP_BOOTFS:
581 * If the pool version is less than SPA_VERSION_BOOTFS,
582 * or the pool is still being created (version == 0),
583 * the bootfs property cannot be set.
585 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
586 error = SET_ERROR(ENOTSUP);
591 * Make sure the vdev config is bootable
593 if (!vdev_is_bootable(spa->spa_root_vdev)) {
594 error = SET_ERROR(ENOTSUP);
600 error = nvpair_value_string(elem, &strval);
606 if (strval == NULL || strval[0] == '\0') {
607 objnum = zpool_prop_default_numeric(
612 error = dmu_objset_hold(strval, FTAG, &os);
617 * Must be ZPL, and its property settings
621 if (dmu_objset_type(os) != DMU_OST_ZFS) {
622 error = SET_ERROR(ENOTSUP);
624 dsl_prop_get_int_ds(dmu_objset_ds(os),
625 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
627 !BOOTFS_COMPRESS_VALID(propval)) {
628 error = SET_ERROR(ENOTSUP);
630 objnum = dmu_objset_id(os);
632 dmu_objset_rele(os, FTAG);
636 case ZPOOL_PROP_FAILUREMODE:
637 error = nvpair_value_uint64(elem, &intval);
638 if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
639 intval > ZIO_FAILURE_MODE_PANIC))
640 error = SET_ERROR(EINVAL);
643 * This is a special case which only occurs when
644 * the pool has completely failed. This allows
645 * the user to change the in-core failmode property
646 * without syncing it out to disk (I/Os might
647 * currently be blocked). We do this by returning
648 * EIO to the caller (spa_prop_set) to trick it
649 * into thinking we encountered a property validation
652 if (!error && spa_suspended(spa)) {
653 spa->spa_failmode = intval;
654 error = SET_ERROR(EIO);
658 case ZPOOL_PROP_CACHEFILE:
659 if ((error = nvpair_value_string(elem, &strval)) != 0)
662 if (strval[0] == '\0')
665 if (strcmp(strval, "none") == 0)
668 if (strval[0] != '/') {
669 error = SET_ERROR(EINVAL);
673 slash = strrchr(strval, '/');
674 ASSERT(slash != NULL);
676 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
677 strcmp(slash, "/..") == 0)
678 error = SET_ERROR(EINVAL);
681 case ZPOOL_PROP_COMMENT:
682 if ((error = nvpair_value_string(elem, &strval)) != 0)
684 for (check = strval; *check != '\0'; check++) {
686 * The kernel doesn't have an easy isprint()
687 * check. For this kernel check, we merely
688 * check ASCII apart from DEL. Fix this if
689 * there is an easy-to-use kernel isprint().
691 if (*check >= 0x7f) {
692 error = SET_ERROR(EINVAL);
696 if (strlen(strval) > ZPROP_MAX_COMMENT)
700 case ZPOOL_PROP_DEDUPDITTO:
701 if (spa_version(spa) < SPA_VERSION_DEDUP)
702 error = SET_ERROR(ENOTSUP);
704 error = nvpair_value_uint64(elem, &intval);
706 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
707 error = SET_ERROR(EINVAL);
715 if (!error && reset_bootfs) {
716 error = nvlist_remove(props,
717 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
720 error = nvlist_add_uint64(props,
721 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
729 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
732 spa_config_dirent_t *dp;
734 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
738 dp = kmem_alloc(sizeof (spa_config_dirent_t),
741 if (cachefile[0] == '\0')
742 dp->scd_path = spa_strdup(spa_config_path);
743 else if (strcmp(cachefile, "none") == 0)
746 dp->scd_path = spa_strdup(cachefile);
748 list_insert_head(&spa->spa_config_list, dp);
750 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
754 spa_prop_set(spa_t *spa, nvlist_t *nvp)
757 nvpair_t *elem = NULL;
758 boolean_t need_sync = B_FALSE;
760 if ((error = spa_prop_validate(spa, nvp)) != 0)
763 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
764 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
766 if (prop == ZPOOL_PROP_CACHEFILE ||
767 prop == ZPOOL_PROP_ALTROOT ||
768 prop == ZPOOL_PROP_READONLY)
771 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
774 if (prop == ZPOOL_PROP_VERSION) {
775 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
777 ASSERT(zpool_prop_feature(nvpair_name(elem)));
778 ver = SPA_VERSION_FEATURES;
782 /* Save time if the version is already set. */
783 if (ver == spa_version(spa))
787 * In addition to the pool directory object, we might
788 * create the pool properties object, the features for
789 * read object, the features for write object, or the
790 * feature descriptions object.
792 error = dsl_sync_task(spa->spa_name, NULL,
793 spa_sync_version, &ver,
794 6, ZFS_SPACE_CHECK_RESERVED);
805 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
806 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
813 * If the bootfs property value is dsobj, clear it.
816 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
818 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
819 VERIFY(zap_remove(spa->spa_meta_objset,
820 spa->spa_pool_props_object,
821 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
828 spa_change_guid_check(void *arg, dmu_tx_t *tx)
830 uint64_t *newguid = arg;
831 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
832 vdev_t *rvd = spa->spa_root_vdev;
835 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
836 int error = (spa_has_checkpoint(spa)) ?
837 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
838 return (SET_ERROR(error));
841 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
842 vdev_state = rvd->vdev_state;
843 spa_config_exit(spa, SCL_STATE, FTAG);
845 if (vdev_state != VDEV_STATE_HEALTHY)
846 return (SET_ERROR(ENXIO));
848 ASSERT3U(spa_guid(spa), !=, *newguid);
854 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
856 uint64_t *newguid = arg;
857 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
859 vdev_t *rvd = spa->spa_root_vdev;
861 oldguid = spa_guid(spa);
863 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
864 rvd->vdev_guid = *newguid;
865 rvd->vdev_guid_sum += (*newguid - oldguid);
866 vdev_config_dirty(rvd);
867 spa_config_exit(spa, SCL_STATE, FTAG);
869 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
874 * Change the GUID for the pool. This is done so that we can later
875 * re-import a pool built from a clone of our own vdevs. We will modify
876 * the root vdev's guid, our own pool guid, and then mark all of our
877 * vdevs dirty. Note that we must make sure that all our vdevs are
878 * online when we do this, or else any vdevs that weren't present
879 * would be orphaned from our pool. We are also going to issue a
880 * sysevent to update any watchers.
883 spa_change_guid(spa_t *spa)
888 mutex_enter(&spa->spa_vdev_top_lock);
889 mutex_enter(&spa_namespace_lock);
890 guid = spa_generate_guid(NULL);
892 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
893 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
896 spa_write_cachefile(spa, B_FALSE, B_TRUE);
897 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
900 mutex_exit(&spa_namespace_lock);
901 mutex_exit(&spa->spa_vdev_top_lock);
907 * ==========================================================================
908 * SPA state manipulation (open/create/destroy/import/export)
909 * ==========================================================================
913 spa_error_entry_compare(const void *a, const void *b)
915 const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
916 const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
919 ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
920 sizeof (zbookmark_phys_t));
922 return (AVL_ISIGN(ret));
926 * Utility function which retrieves copies of the current logs and
927 * re-initializes them in the process.
930 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
932 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
934 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
935 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
937 avl_create(&spa->spa_errlist_scrub,
938 spa_error_entry_compare, sizeof (spa_error_entry_t),
939 offsetof(spa_error_entry_t, se_avl));
940 avl_create(&spa->spa_errlist_last,
941 spa_error_entry_compare, sizeof (spa_error_entry_t),
942 offsetof(spa_error_entry_t, se_avl));
946 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
948 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
949 enum zti_modes mode = ztip->zti_mode;
950 uint_t value = ztip->zti_value;
951 uint_t count = ztip->zti_count;
952 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
955 boolean_t batch = B_FALSE;
957 if (mode == ZTI_MODE_NULL) {
959 tqs->stqs_taskq = NULL;
963 ASSERT3U(count, >, 0);
965 tqs->stqs_count = count;
966 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
970 ASSERT3U(value, >=, 1);
971 value = MAX(value, 1);
976 flags |= TASKQ_THREADS_CPU_PCT;
977 value = zio_taskq_batch_pct;
981 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
983 zio_type_name[t], zio_taskq_types[q], mode, value);
987 for (uint_t i = 0; i < count; i++) {
991 (void) snprintf(name, sizeof (name), "%s_%s_%u",
992 zio_type_name[t], zio_taskq_types[q], i);
994 (void) snprintf(name, sizeof (name), "%s_%s",
995 zio_type_name[t], zio_taskq_types[q]);
999 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
1001 flags |= TASKQ_DC_BATCH;
1003 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
1004 spa->spa_proc, zio_taskq_basedc, flags);
1007 pri_t pri = maxclsyspri;
1009 * The write issue taskq can be extremely CPU
1010 * intensive. Run it at slightly lower priority
1011 * than the other taskqs.
1013 * - numerically higher priorities are lower priorities;
1014 * - if priorities divided by four (RQ_PPQ) are equal
1015 * then a difference between them is insignificant.
1017 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1024 tq = taskq_create_proc(name, value, pri, 50,
1025 INT_MAX, spa->spa_proc, flags);
1030 tqs->stqs_taskq[i] = tq;
1035 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1037 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1039 if (tqs->stqs_taskq == NULL) {
1040 ASSERT0(tqs->stqs_count);
1044 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1045 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1046 taskq_destroy(tqs->stqs_taskq[i]);
1049 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1050 tqs->stqs_taskq = NULL;
1054 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1055 * Note that a type may have multiple discrete taskqs to avoid lock contention
1056 * on the taskq itself. In that case we choose which taskq at random by using
1057 * the low bits of gethrtime().
1060 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1061 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1063 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1066 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1067 ASSERT3U(tqs->stqs_count, !=, 0);
1069 if (tqs->stqs_count == 1) {
1070 tq = tqs->stqs_taskq[0];
1073 tq = tqs->stqs_taskq[(u_int)(sbinuptime() + curcpu) %
1076 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1080 taskq_dispatch_ent(tq, func, arg, flags, ent);
1084 spa_create_zio_taskqs(spa_t *spa)
1086 for (int t = 0; t < ZIO_TYPES; t++) {
1087 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1088 spa_taskqs_init(spa, t, q);
1096 spa_thread(void *arg)
1098 callb_cpr_t cprinfo;
1101 user_t *pu = PTOU(curproc);
1103 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1106 ASSERT(curproc != &p0);
1107 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1108 "zpool-%s", spa->spa_name);
1109 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1112 /* bind this thread to the requested psrset */
1113 if (zio_taskq_psrset_bind != PS_NONE) {
1115 mutex_enter(&cpu_lock);
1116 mutex_enter(&pidlock);
1117 mutex_enter(&curproc->p_lock);
1119 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1120 0, NULL, NULL) == 0) {
1121 curthread->t_bind_pset = zio_taskq_psrset_bind;
1124 "Couldn't bind process for zfs pool \"%s\" to "
1125 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1128 mutex_exit(&curproc->p_lock);
1129 mutex_exit(&pidlock);
1130 mutex_exit(&cpu_lock);
1136 if (zio_taskq_sysdc) {
1137 sysdc_thread_enter(curthread, 100, 0);
1141 spa->spa_proc = curproc;
1142 spa->spa_did = curthread->t_did;
1144 spa_create_zio_taskqs(spa);
1146 mutex_enter(&spa->spa_proc_lock);
1147 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1149 spa->spa_proc_state = SPA_PROC_ACTIVE;
1150 cv_broadcast(&spa->spa_proc_cv);
1152 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1153 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1154 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1155 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1157 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1158 spa->spa_proc_state = SPA_PROC_GONE;
1159 spa->spa_proc = &p0;
1160 cv_broadcast(&spa->spa_proc_cv);
1161 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1163 mutex_enter(&curproc->p_lock);
1166 #endif /* SPA_PROCESS */
1170 * Activate an uninitialized pool.
1173 spa_activate(spa_t *spa, int mode)
1175 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1177 spa->spa_state = POOL_STATE_ACTIVE;
1178 spa->spa_mode = mode;
1180 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1181 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1183 /* Try to create a covering process */
1184 mutex_enter(&spa->spa_proc_lock);
1185 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1186 ASSERT(spa->spa_proc == &p0);
1190 /* Only create a process if we're going to be around a while. */
1191 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1192 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1194 spa->spa_proc_state = SPA_PROC_CREATED;
1195 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1196 cv_wait(&spa->spa_proc_cv,
1197 &spa->spa_proc_lock);
1199 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1200 ASSERT(spa->spa_proc != &p0);
1201 ASSERT(spa->spa_did != 0);
1205 "Couldn't create process for zfs pool \"%s\"\n",
1210 #endif /* SPA_PROCESS */
1211 mutex_exit(&spa->spa_proc_lock);
1213 /* If we didn't create a process, we need to create our taskqs. */
1214 ASSERT(spa->spa_proc == &p0);
1215 if (spa->spa_proc == &p0) {
1216 spa_create_zio_taskqs(spa);
1220 * Start TRIM thread.
1222 trim_thread_create(spa);
1224 for (size_t i = 0; i < TXG_SIZE; i++) {
1225 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL,
1229 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1230 offsetof(vdev_t, vdev_config_dirty_node));
1231 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1232 offsetof(objset_t, os_evicting_node));
1233 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1234 offsetof(vdev_t, vdev_state_dirty_node));
1236 txg_list_create(&spa->spa_vdev_txg_list, spa,
1237 offsetof(struct vdev, vdev_txg_node));
1239 avl_create(&spa->spa_errlist_scrub,
1240 spa_error_entry_compare, sizeof (spa_error_entry_t),
1241 offsetof(spa_error_entry_t, se_avl));
1242 avl_create(&spa->spa_errlist_last,
1243 spa_error_entry_compare, sizeof (spa_error_entry_t),
1244 offsetof(spa_error_entry_t, se_avl));
1248 * Opposite of spa_activate().
1251 spa_deactivate(spa_t *spa)
1253 ASSERT(spa->spa_sync_on == B_FALSE);
1254 ASSERT(spa->spa_dsl_pool == NULL);
1255 ASSERT(spa->spa_root_vdev == NULL);
1256 ASSERT(spa->spa_async_zio_root == NULL);
1257 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1260 * Stop TRIM thread in case spa_unload() wasn't called directly
1261 * before spa_deactivate().
1263 trim_thread_destroy(spa);
1265 spa_evicting_os_wait(spa);
1267 txg_list_destroy(&spa->spa_vdev_txg_list);
1269 list_destroy(&spa->spa_config_dirty_list);
1270 list_destroy(&spa->spa_evicting_os_list);
1271 list_destroy(&spa->spa_state_dirty_list);
1273 for (int t = 0; t < ZIO_TYPES; t++) {
1274 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1275 spa_taskqs_fini(spa, t, q);
1279 for (size_t i = 0; i < TXG_SIZE; i++) {
1280 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1281 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1282 spa->spa_txg_zio[i] = NULL;
1285 metaslab_class_destroy(spa->spa_normal_class);
1286 spa->spa_normal_class = NULL;
1288 metaslab_class_destroy(spa->spa_log_class);
1289 spa->spa_log_class = NULL;
1292 * If this was part of an import or the open otherwise failed, we may
1293 * still have errors left in the queues. Empty them just in case.
1295 spa_errlog_drain(spa);
1297 avl_destroy(&spa->spa_errlist_scrub);
1298 avl_destroy(&spa->spa_errlist_last);
1300 spa->spa_state = POOL_STATE_UNINITIALIZED;
1302 mutex_enter(&spa->spa_proc_lock);
1303 if (spa->spa_proc_state != SPA_PROC_NONE) {
1304 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1305 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1306 cv_broadcast(&spa->spa_proc_cv);
1307 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1308 ASSERT(spa->spa_proc != &p0);
1309 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1311 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1312 spa->spa_proc_state = SPA_PROC_NONE;
1314 ASSERT(spa->spa_proc == &p0);
1315 mutex_exit(&spa->spa_proc_lock);
1319 * We want to make sure spa_thread() has actually exited the ZFS
1320 * module, so that the module can't be unloaded out from underneath
1323 if (spa->spa_did != 0) {
1324 thread_join(spa->spa_did);
1327 #endif /* SPA_PROCESS */
1331 * Verify a pool configuration, and construct the vdev tree appropriately. This
1332 * will create all the necessary vdevs in the appropriate layout, with each vdev
1333 * in the CLOSED state. This will prep the pool before open/creation/import.
1334 * All vdev validation is done by the vdev_alloc() routine.
1337 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1338 uint_t id, int atype)
1344 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1347 if ((*vdp)->vdev_ops->vdev_op_leaf)
1350 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1353 if (error == ENOENT)
1359 return (SET_ERROR(EINVAL));
1362 for (int c = 0; c < children; c++) {
1364 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1372 ASSERT(*vdp != NULL);
1378 * Opposite of spa_load().
1381 spa_unload(spa_t *spa)
1385 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1387 spa_load_note(spa, "UNLOADING");
1392 trim_thread_destroy(spa);
1397 spa_async_suspend(spa);
1399 if (spa->spa_root_vdev) {
1400 vdev_initialize_stop_all(spa->spa_root_vdev,
1401 VDEV_INITIALIZE_ACTIVE);
1407 if (spa->spa_sync_on) {
1408 txg_sync_stop(spa->spa_dsl_pool);
1409 spa->spa_sync_on = B_FALSE;
1413 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1414 * to call it earlier, before we wait for async i/o to complete.
1415 * This ensures that there is no async metaslab prefetching, by
1416 * calling taskq_wait(mg_taskq).
1418 if (spa->spa_root_vdev != NULL) {
1419 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1420 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1421 vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1422 spa_config_exit(spa, SCL_ALL, spa);
1426 * Wait for any outstanding async I/O to complete.
1428 if (spa->spa_async_zio_root != NULL) {
1429 for (int i = 0; i < max_ncpus; i++)
1430 (void) zio_wait(spa->spa_async_zio_root[i]);
1431 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1432 spa->spa_async_zio_root = NULL;
1435 if (spa->spa_vdev_removal != NULL) {
1436 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1437 spa->spa_vdev_removal = NULL;
1440 if (spa->spa_condense_zthr != NULL) {
1441 ASSERT(!zthr_isrunning(spa->spa_condense_zthr));
1442 zthr_destroy(spa->spa_condense_zthr);
1443 spa->spa_condense_zthr = NULL;
1446 if (spa->spa_checkpoint_discard_zthr != NULL) {
1447 ASSERT(!zthr_isrunning(spa->spa_checkpoint_discard_zthr));
1448 zthr_destroy(spa->spa_checkpoint_discard_zthr);
1449 spa->spa_checkpoint_discard_zthr = NULL;
1452 spa_condense_fini(spa);
1454 bpobj_close(&spa->spa_deferred_bpobj);
1456 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1461 if (spa->spa_root_vdev)
1462 vdev_free(spa->spa_root_vdev);
1463 ASSERT(spa->spa_root_vdev == NULL);
1466 * Close the dsl pool.
1468 if (spa->spa_dsl_pool) {
1469 dsl_pool_close(spa->spa_dsl_pool);
1470 spa->spa_dsl_pool = NULL;
1471 spa->spa_meta_objset = NULL;
1477 * Drop and purge level 2 cache
1479 spa_l2cache_drop(spa);
1481 for (i = 0; i < spa->spa_spares.sav_count; i++)
1482 vdev_free(spa->spa_spares.sav_vdevs[i]);
1483 if (spa->spa_spares.sav_vdevs) {
1484 kmem_free(spa->spa_spares.sav_vdevs,
1485 spa->spa_spares.sav_count * sizeof (void *));
1486 spa->spa_spares.sav_vdevs = NULL;
1488 if (spa->spa_spares.sav_config) {
1489 nvlist_free(spa->spa_spares.sav_config);
1490 spa->spa_spares.sav_config = NULL;
1492 spa->spa_spares.sav_count = 0;
1494 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1495 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1496 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1498 if (spa->spa_l2cache.sav_vdevs) {
1499 kmem_free(spa->spa_l2cache.sav_vdevs,
1500 spa->spa_l2cache.sav_count * sizeof (void *));
1501 spa->spa_l2cache.sav_vdevs = NULL;
1503 if (spa->spa_l2cache.sav_config) {
1504 nvlist_free(spa->spa_l2cache.sav_config);
1505 spa->spa_l2cache.sav_config = NULL;
1507 spa->spa_l2cache.sav_count = 0;
1509 spa->spa_async_suspended = 0;
1511 spa->spa_indirect_vdevs_loaded = B_FALSE;
1513 if (spa->spa_comment != NULL) {
1514 spa_strfree(spa->spa_comment);
1515 spa->spa_comment = NULL;
1518 spa_config_exit(spa, SCL_ALL, spa);
1522 * Load (or re-load) the current list of vdevs describing the active spares for
1523 * this pool. When this is called, we have some form of basic information in
1524 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1525 * then re-generate a more complete list including status information.
1528 spa_load_spares(spa_t *spa)
1537 * zdb opens both the current state of the pool and the
1538 * checkpointed state (if present), with a different spa_t.
1540 * As spare vdevs are shared among open pools, we skip loading
1541 * them when we load the checkpointed state of the pool.
1543 if (!spa_writeable(spa))
1547 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1550 * First, close and free any existing spare vdevs.
1552 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1553 vd = spa->spa_spares.sav_vdevs[i];
1555 /* Undo the call to spa_activate() below */
1556 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1557 B_FALSE)) != NULL && tvd->vdev_isspare)
1558 spa_spare_remove(tvd);
1563 if (spa->spa_spares.sav_vdevs)
1564 kmem_free(spa->spa_spares.sav_vdevs,
1565 spa->spa_spares.sav_count * sizeof (void *));
1567 if (spa->spa_spares.sav_config == NULL)
1570 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1571 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1573 spa->spa_spares.sav_count = (int)nspares;
1574 spa->spa_spares.sav_vdevs = NULL;
1580 * Construct the array of vdevs, opening them to get status in the
1581 * process. For each spare, there is potentially two different vdev_t
1582 * structures associated with it: one in the list of spares (used only
1583 * for basic validation purposes) and one in the active vdev
1584 * configuration (if it's spared in). During this phase we open and
1585 * validate each vdev on the spare list. If the vdev also exists in the
1586 * active configuration, then we also mark this vdev as an active spare.
1588 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1590 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1591 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1592 VDEV_ALLOC_SPARE) == 0);
1595 spa->spa_spares.sav_vdevs[i] = vd;
1597 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1598 B_FALSE)) != NULL) {
1599 if (!tvd->vdev_isspare)
1603 * We only mark the spare active if we were successfully
1604 * able to load the vdev. Otherwise, importing a pool
1605 * with a bad active spare would result in strange
1606 * behavior, because multiple pool would think the spare
1607 * is actively in use.
1609 * There is a vulnerability here to an equally bizarre
1610 * circumstance, where a dead active spare is later
1611 * brought back to life (onlined or otherwise). Given
1612 * the rarity of this scenario, and the extra complexity
1613 * it adds, we ignore the possibility.
1615 if (!vdev_is_dead(tvd))
1616 spa_spare_activate(tvd);
1620 vd->vdev_aux = &spa->spa_spares;
1622 if (vdev_open(vd) != 0)
1625 if (vdev_validate_aux(vd) == 0)
1630 * Recompute the stashed list of spares, with status information
1633 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1634 DATA_TYPE_NVLIST_ARRAY) == 0);
1636 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1638 for (i = 0; i < spa->spa_spares.sav_count; i++)
1639 spares[i] = vdev_config_generate(spa,
1640 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1641 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1642 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1643 for (i = 0; i < spa->spa_spares.sav_count; i++)
1644 nvlist_free(spares[i]);
1645 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1649 * Load (or re-load) the current list of vdevs describing the active l2cache for
1650 * this pool. When this is called, we have some form of basic information in
1651 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1652 * then re-generate a more complete list including status information.
1653 * Devices which are already active have their details maintained, and are
1657 spa_load_l2cache(spa_t *spa)
1661 int i, j, oldnvdevs;
1663 vdev_t *vd, **oldvdevs, **newvdevs;
1664 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1668 * zdb opens both the current state of the pool and the
1669 * checkpointed state (if present), with a different spa_t.
1671 * As L2 caches are part of the ARC which is shared among open
1672 * pools, we skip loading them when we load the checkpointed
1673 * state of the pool.
1675 if (!spa_writeable(spa))
1679 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1681 if (sav->sav_config != NULL) {
1682 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1683 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1684 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1690 oldvdevs = sav->sav_vdevs;
1691 oldnvdevs = sav->sav_count;
1692 sav->sav_vdevs = NULL;
1696 * Process new nvlist of vdevs.
1698 for (i = 0; i < nl2cache; i++) {
1699 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1703 for (j = 0; j < oldnvdevs; j++) {
1705 if (vd != NULL && guid == vd->vdev_guid) {
1707 * Retain previous vdev for add/remove ops.
1715 if (newvdevs[i] == NULL) {
1719 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1720 VDEV_ALLOC_L2CACHE) == 0);
1725 * Commit this vdev as an l2cache device,
1726 * even if it fails to open.
1728 spa_l2cache_add(vd);
1733 spa_l2cache_activate(vd);
1735 if (vdev_open(vd) != 0)
1738 (void) vdev_validate_aux(vd);
1740 if (!vdev_is_dead(vd))
1741 l2arc_add_vdev(spa, vd);
1746 * Purge vdevs that were dropped
1748 for (i = 0; i < oldnvdevs; i++) {
1753 ASSERT(vd->vdev_isl2cache);
1755 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1756 pool != 0ULL && l2arc_vdev_present(vd))
1757 l2arc_remove_vdev(vd);
1758 vdev_clear_stats(vd);
1764 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1766 if (sav->sav_config == NULL)
1769 sav->sav_vdevs = newvdevs;
1770 sav->sav_count = (int)nl2cache;
1773 * Recompute the stashed list of l2cache devices, with status
1774 * information this time.
1776 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1777 DATA_TYPE_NVLIST_ARRAY) == 0);
1779 l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1780 for (i = 0; i < sav->sav_count; i++)
1781 l2cache[i] = vdev_config_generate(spa,
1782 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1783 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1784 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1786 for (i = 0; i < sav->sav_count; i++)
1787 nvlist_free(l2cache[i]);
1789 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1793 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1796 char *packed = NULL;
1801 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1805 nvsize = *(uint64_t *)db->db_data;
1806 dmu_buf_rele(db, FTAG);
1808 packed = kmem_alloc(nvsize, KM_SLEEP);
1809 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1812 error = nvlist_unpack(packed, nvsize, value, 0);
1813 kmem_free(packed, nvsize);
1819 * Concrete top-level vdevs that are not missing and are not logs. At every
1820 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1823 spa_healthy_core_tvds(spa_t *spa)
1825 vdev_t *rvd = spa->spa_root_vdev;
1828 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1829 vdev_t *vd = rvd->vdev_child[i];
1832 if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1840 * Checks to see if the given vdev could not be opened, in which case we post a
1841 * sysevent to notify the autoreplace code that the device has been removed.
1844 spa_check_removed(vdev_t *vd)
1846 for (uint64_t c = 0; c < vd->vdev_children; c++)
1847 spa_check_removed(vd->vdev_child[c]);
1849 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1850 vdev_is_concrete(vd)) {
1851 zfs_post_autoreplace(vd->vdev_spa, vd);
1852 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1857 spa_check_for_missing_logs(spa_t *spa)
1859 vdev_t *rvd = spa->spa_root_vdev;
1862 * If we're doing a normal import, then build up any additional
1863 * diagnostic information about missing log devices.
1864 * We'll pass this up to the user for further processing.
1866 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1867 nvlist_t **child, *nv;
1870 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1872 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1874 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1875 vdev_t *tvd = rvd->vdev_child[c];
1878 * We consider a device as missing only if it failed
1879 * to open (i.e. offline or faulted is not considered
1882 if (tvd->vdev_islog &&
1883 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1884 child[idx++] = vdev_config_generate(spa, tvd,
1885 B_FALSE, VDEV_CONFIG_MISSING);
1890 fnvlist_add_nvlist_array(nv,
1891 ZPOOL_CONFIG_CHILDREN, child, idx);
1892 fnvlist_add_nvlist(spa->spa_load_info,
1893 ZPOOL_CONFIG_MISSING_DEVICES, nv);
1895 for (uint64_t i = 0; i < idx; i++)
1896 nvlist_free(child[i]);
1899 kmem_free(child, rvd->vdev_children * sizeof (char **));
1902 spa_load_failed(spa, "some log devices are missing");
1903 vdev_dbgmsg_print_tree(rvd, 2);
1904 return (SET_ERROR(ENXIO));
1907 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1908 vdev_t *tvd = rvd->vdev_child[c];
1910 if (tvd->vdev_islog &&
1911 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1912 spa_set_log_state(spa, SPA_LOG_CLEAR);
1913 spa_load_note(spa, "some log devices are "
1914 "missing, ZIL is dropped.");
1915 vdev_dbgmsg_print_tree(rvd, 2);
1925 * Check for missing log devices
1928 spa_check_logs(spa_t *spa)
1930 boolean_t rv = B_FALSE;
1931 dsl_pool_t *dp = spa_get_dsl(spa);
1933 switch (spa->spa_log_state) {
1934 case SPA_LOG_MISSING:
1935 /* need to recheck in case slog has been restored */
1936 case SPA_LOG_UNKNOWN:
1937 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1938 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
1940 spa_set_log_state(spa, SPA_LOG_MISSING);
1947 spa_passivate_log(spa_t *spa)
1949 vdev_t *rvd = spa->spa_root_vdev;
1950 boolean_t slog_found = B_FALSE;
1952 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1954 if (!spa_has_slogs(spa))
1957 for (int c = 0; c < rvd->vdev_children; c++) {
1958 vdev_t *tvd = rvd->vdev_child[c];
1959 metaslab_group_t *mg = tvd->vdev_mg;
1961 if (tvd->vdev_islog) {
1962 metaslab_group_passivate(mg);
1963 slog_found = B_TRUE;
1967 return (slog_found);
1971 spa_activate_log(spa_t *spa)
1973 vdev_t *rvd = spa->spa_root_vdev;
1975 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1977 for (int c = 0; c < rvd->vdev_children; c++) {
1978 vdev_t *tvd = rvd->vdev_child[c];
1979 metaslab_group_t *mg = tvd->vdev_mg;
1981 if (tvd->vdev_islog)
1982 metaslab_group_activate(mg);
1987 spa_reset_logs(spa_t *spa)
1991 error = dmu_objset_find(spa_name(spa), zil_reset,
1992 NULL, DS_FIND_CHILDREN);
1995 * We successfully offlined the log device, sync out the
1996 * current txg so that the "stubby" block can be removed
1999 txg_wait_synced(spa->spa_dsl_pool, 0);
2005 spa_aux_check_removed(spa_aux_vdev_t *sav)
2009 for (i = 0; i < sav->sav_count; i++)
2010 spa_check_removed(sav->sav_vdevs[i]);
2014 spa_claim_notify(zio_t *zio)
2016 spa_t *spa = zio->io_spa;
2021 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2022 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2023 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2024 mutex_exit(&spa->spa_props_lock);
2027 typedef struct spa_load_error {
2028 uint64_t sle_meta_count;
2029 uint64_t sle_data_count;
2033 spa_load_verify_done(zio_t *zio)
2035 blkptr_t *bp = zio->io_bp;
2036 spa_load_error_t *sle = zio->io_private;
2037 dmu_object_type_t type = BP_GET_TYPE(bp);
2038 int error = zio->io_error;
2039 spa_t *spa = zio->io_spa;
2041 abd_free(zio->io_abd);
2043 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
2044 type != DMU_OT_INTENT_LOG)
2045 atomic_inc_64(&sle->sle_meta_count);
2047 atomic_inc_64(&sle->sle_data_count);
2050 mutex_enter(&spa->spa_scrub_lock);
2051 spa->spa_load_verify_ios--;
2052 cv_broadcast(&spa->spa_scrub_io_cv);
2053 mutex_exit(&spa->spa_scrub_lock);
2057 * Maximum number of concurrent scrub i/os to create while verifying
2058 * a pool while importing it.
2060 int spa_load_verify_maxinflight = 10000;
2061 boolean_t spa_load_verify_metadata = B_TRUE;
2062 boolean_t spa_load_verify_data = B_TRUE;
2064 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_maxinflight, CTLFLAG_RWTUN,
2065 &spa_load_verify_maxinflight, 0,
2066 "Maximum number of concurrent scrub I/Os to create while verifying a "
2067 "pool while importing it");
2069 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_metadata, CTLFLAG_RWTUN,
2070 &spa_load_verify_metadata, 0,
2071 "Check metadata on import?");
2073 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_data, CTLFLAG_RWTUN,
2074 &spa_load_verify_data, 0,
2075 "Check user data on import?");
2079 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2080 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2082 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2085 * Note: normally this routine will not be called if
2086 * spa_load_verify_metadata is not set. However, it may be useful
2087 * to manually set the flag after the traversal has begun.
2089 if (!spa_load_verify_metadata)
2091 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2095 size_t size = BP_GET_PSIZE(bp);
2097 mutex_enter(&spa->spa_scrub_lock);
2098 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
2099 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2100 spa->spa_load_verify_ios++;
2101 mutex_exit(&spa->spa_scrub_lock);
2103 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2104 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2105 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2106 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2112 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2114 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2115 return (SET_ERROR(ENAMETOOLONG));
2121 spa_load_verify(spa_t *spa)
2124 spa_load_error_t sle = { 0 };
2125 zpool_load_policy_t policy;
2126 boolean_t verify_ok = B_FALSE;
2129 zpool_get_load_policy(spa->spa_config, &policy);
2131 if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2134 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2135 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2136 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2138 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2142 rio = zio_root(spa, NULL, &sle,
2143 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2145 if (spa_load_verify_metadata) {
2146 if (spa->spa_extreme_rewind) {
2147 spa_load_note(spa, "performing a complete scan of the "
2148 "pool since extreme rewind is on. This may take "
2149 "a very long time.\n (spa_load_verify_data=%u, "
2150 "spa_load_verify_metadata=%u)",
2151 spa_load_verify_data, spa_load_verify_metadata);
2153 error = traverse_pool(spa, spa->spa_verify_min_txg,
2154 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2155 spa_load_verify_cb, rio);
2158 (void) zio_wait(rio);
2160 spa->spa_load_meta_errors = sle.sle_meta_count;
2161 spa->spa_load_data_errors = sle.sle_data_count;
2163 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2164 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2165 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2166 (u_longlong_t)sle.sle_data_count);
2169 if (spa_load_verify_dryrun ||
2170 (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2171 sle.sle_data_count <= policy.zlp_maxdata)) {
2175 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2176 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2178 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2179 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2180 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2181 VERIFY(nvlist_add_int64(spa->spa_load_info,
2182 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2183 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2184 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2186 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2189 if (spa_load_verify_dryrun)
2193 if (error != ENXIO && error != EIO)
2194 error = SET_ERROR(EIO);
2198 return (verify_ok ? 0 : EIO);
2202 * Find a value in the pool props object.
2205 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2207 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2208 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2212 * Find a value in the pool directory object.
2215 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2217 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2218 name, sizeof (uint64_t), 1, val);
2220 if (error != 0 && (error != ENOENT || log_enoent)) {
2221 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2222 "[error=%d]", name, error);
2229 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2231 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2232 return (SET_ERROR(err));
2236 spa_spawn_aux_threads(spa_t *spa)
2238 ASSERT(spa_writeable(spa));
2240 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2242 spa_start_indirect_condensing_thread(spa);
2244 ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2245 spa->spa_checkpoint_discard_zthr =
2246 zthr_create(spa_checkpoint_discard_thread_check,
2247 spa_checkpoint_discard_thread, spa);
2251 * Fix up config after a partly-completed split. This is done with the
2252 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2253 * pool have that entry in their config, but only the splitting one contains
2254 * a list of all the guids of the vdevs that are being split off.
2256 * This function determines what to do with that list: either rejoin
2257 * all the disks to the pool, or complete the splitting process. To attempt
2258 * the rejoin, each disk that is offlined is marked online again, and
2259 * we do a reopen() call. If the vdev label for every disk that was
2260 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2261 * then we call vdev_split() on each disk, and complete the split.
2263 * Otherwise we leave the config alone, with all the vdevs in place in
2264 * the original pool.
2267 spa_try_repair(spa_t *spa, nvlist_t *config)
2274 boolean_t attempt_reopen;
2276 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2279 /* check that the config is complete */
2280 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2281 &glist, &gcount) != 0)
2284 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2286 /* attempt to online all the vdevs & validate */
2287 attempt_reopen = B_TRUE;
2288 for (i = 0; i < gcount; i++) {
2289 if (glist[i] == 0) /* vdev is hole */
2292 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2293 if (vd[i] == NULL) {
2295 * Don't bother attempting to reopen the disks;
2296 * just do the split.
2298 attempt_reopen = B_FALSE;
2300 /* attempt to re-online it */
2301 vd[i]->vdev_offline = B_FALSE;
2305 if (attempt_reopen) {
2306 vdev_reopen(spa->spa_root_vdev);
2308 /* check each device to see what state it's in */
2309 for (extracted = 0, i = 0; i < gcount; i++) {
2310 if (vd[i] != NULL &&
2311 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2318 * If every disk has been moved to the new pool, or if we never
2319 * even attempted to look at them, then we split them off for
2322 if (!attempt_reopen || gcount == extracted) {
2323 for (i = 0; i < gcount; i++)
2326 vdev_reopen(spa->spa_root_vdev);
2329 kmem_free(vd, gcount * sizeof (vdev_t *));
2333 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2335 char *ereport = FM_EREPORT_ZFS_POOL;
2338 spa->spa_load_state = state;
2340 gethrestime(&spa->spa_loaded_ts);
2341 error = spa_load_impl(spa, type, &ereport);
2344 * Don't count references from objsets that are already closed
2345 * and are making their way through the eviction process.
2347 spa_evicting_os_wait(spa);
2348 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
2350 if (error != EEXIST) {
2351 spa->spa_loaded_ts.tv_sec = 0;
2352 spa->spa_loaded_ts.tv_nsec = 0;
2354 if (error != EBADF) {
2355 zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2358 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2365 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2366 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2367 * spa's per-vdev ZAP list.
2370 vdev_count_verify_zaps(vdev_t *vd)
2372 spa_t *spa = vd->vdev_spa;
2374 if (vd->vdev_top_zap != 0) {
2376 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2377 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2379 if (vd->vdev_leaf_zap != 0) {
2381 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2382 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2385 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2386 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2393 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2397 uint64_t myhostid = 0;
2399 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2400 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2401 hostname = fnvlist_lookup_string(mos_config,
2402 ZPOOL_CONFIG_HOSTNAME);
2404 myhostid = zone_get_hostid(NULL);
2406 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2407 cmn_err(CE_WARN, "pool '%s' could not be "
2408 "loaded as it was last accessed by "
2409 "another system (host: %s hostid: 0x%llx). "
2410 "See: http://illumos.org/msg/ZFS-8000-EY",
2411 spa_name(spa), hostname, (u_longlong_t)hostid);
2412 spa_load_failed(spa, "hostid verification failed: pool "
2413 "last accessed by host: %s (hostid: 0x%llx)",
2414 hostname, (u_longlong_t)hostid);
2415 return (SET_ERROR(EBADF));
2423 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2426 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2433 * Versioning wasn't explicitly added to the label until later, so if
2434 * it's not present treat it as the initial version.
2436 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2437 &spa->spa_ubsync.ub_version) != 0)
2438 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2440 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2441 spa_load_failed(spa, "invalid config provided: '%s' missing",
2442 ZPOOL_CONFIG_POOL_GUID);
2443 return (SET_ERROR(EINVAL));
2447 * If we are doing an import, ensure that the pool is not already
2448 * imported by checking if its pool guid already exists in the
2451 * The only case that we allow an already imported pool to be
2452 * imported again, is when the pool is checkpointed and we want to
2453 * look at its checkpointed state from userland tools like zdb.
2456 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2457 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2458 spa_guid_exists(pool_guid, 0)) {
2460 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2461 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2462 spa_guid_exists(pool_guid, 0) &&
2463 !spa_importing_readonly_checkpoint(spa)) {
2465 spa_load_failed(spa, "a pool with guid %llu is already open",
2466 (u_longlong_t)pool_guid);
2467 return (SET_ERROR(EEXIST));
2470 spa->spa_config_guid = pool_guid;
2472 nvlist_free(spa->spa_load_info);
2473 spa->spa_load_info = fnvlist_alloc();
2475 ASSERT(spa->spa_comment == NULL);
2476 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2477 spa->spa_comment = spa_strdup(comment);
2479 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2480 &spa->spa_config_txg);
2482 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2483 spa->spa_config_splitting = fnvlist_dup(nvl);
2485 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2486 spa_load_failed(spa, "invalid config provided: '%s' missing",
2487 ZPOOL_CONFIG_VDEV_TREE);
2488 return (SET_ERROR(EINVAL));
2492 * Create "The Godfather" zio to hold all async IOs
2494 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2496 for (int i = 0; i < max_ncpus; i++) {
2497 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2498 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2499 ZIO_FLAG_GODFATHER);
2503 * Parse the configuration into a vdev tree. We explicitly set the
2504 * value that will be returned by spa_version() since parsing the
2505 * configuration requires knowing the version number.
2507 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2508 parse = (type == SPA_IMPORT_EXISTING ?
2509 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2510 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2511 spa_config_exit(spa, SCL_ALL, FTAG);
2514 spa_load_failed(spa, "unable to parse config [error=%d]",
2519 ASSERT(spa->spa_root_vdev == rvd);
2520 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2521 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2523 if (type != SPA_IMPORT_ASSEMBLE) {
2524 ASSERT(spa_guid(spa) == pool_guid);
2531 * Recursively open all vdevs in the vdev tree. This function is called twice:
2532 * first with the untrusted config, then with the trusted config.
2535 spa_ld_open_vdevs(spa_t *spa)
2540 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2541 * missing/unopenable for the root vdev to be still considered openable.
2543 if (spa->spa_trust_config) {
2544 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2545 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2546 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2547 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2548 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2550 spa->spa_missing_tvds_allowed = 0;
2553 spa->spa_missing_tvds_allowed =
2554 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2556 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2557 error = vdev_open(spa->spa_root_vdev);
2558 spa_config_exit(spa, SCL_ALL, FTAG);
2560 if (spa->spa_missing_tvds != 0) {
2561 spa_load_note(spa, "vdev tree has %lld missing top-level "
2562 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2563 if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2565 * Although theoretically we could allow users to open
2566 * incomplete pools in RW mode, we'd need to add a lot
2567 * of extra logic (e.g. adjust pool space to account
2568 * for missing vdevs).
2569 * This limitation also prevents users from accidentally
2570 * opening the pool in RW mode during data recovery and
2571 * damaging it further.
2573 spa_load_note(spa, "pools with missing top-level "
2574 "vdevs can only be opened in read-only mode.");
2575 error = SET_ERROR(ENXIO);
2577 spa_load_note(spa, "current settings allow for maximum "
2578 "%lld missing top-level vdevs at this stage.",
2579 (u_longlong_t)spa->spa_missing_tvds_allowed);
2583 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2586 if (spa->spa_missing_tvds != 0 || error != 0)
2587 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2593 * We need to validate the vdev labels against the configuration that
2594 * we have in hand. This function is called twice: first with an untrusted
2595 * config, then with a trusted config. The validation is more strict when the
2596 * config is trusted.
2599 spa_ld_validate_vdevs(spa_t *spa)
2602 vdev_t *rvd = spa->spa_root_vdev;
2604 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2605 error = vdev_validate(rvd);
2606 spa_config_exit(spa, SCL_ALL, FTAG);
2609 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2613 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2614 spa_load_failed(spa, "cannot open vdev tree after invalidating "
2616 vdev_dbgmsg_print_tree(rvd, 2);
2617 return (SET_ERROR(ENXIO));
2624 spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2626 spa->spa_state = POOL_STATE_ACTIVE;
2627 spa->spa_ubsync = spa->spa_uberblock;
2628 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2629 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2630 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2631 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2632 spa->spa_claim_max_txg = spa->spa_first_txg;
2633 spa->spa_prev_software_version = ub->ub_software_version;
2637 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2639 vdev_t *rvd = spa->spa_root_vdev;
2641 uberblock_t *ub = &spa->spa_uberblock;
2644 * If we are opening the checkpointed state of the pool by
2645 * rewinding to it, at this point we will have written the
2646 * checkpointed uberblock to the vdev labels, so searching
2647 * the labels will find the right uberblock. However, if
2648 * we are opening the checkpointed state read-only, we have
2649 * not modified the labels. Therefore, we must ignore the
2650 * labels and continue using the spa_uberblock that was set
2651 * by spa_ld_checkpoint_rewind.
2653 * Note that it would be fine to ignore the labels when
2654 * rewinding (opening writeable) as well. However, if we
2655 * crash just after writing the labels, we will end up
2656 * searching the labels. Doing so in the common case means
2657 * that this code path gets exercised normally, rather than
2658 * just in the edge case.
2660 if (ub->ub_checkpoint_txg != 0 &&
2661 spa_importing_readonly_checkpoint(spa)) {
2662 spa_ld_select_uberblock_done(spa, ub);
2667 * Find the best uberblock.
2669 vdev_uberblock_load(rvd, ub, &label);
2672 * If we weren't able to find a single valid uberblock, return failure.
2674 if (ub->ub_txg == 0) {
2676 spa_load_failed(spa, "no valid uberblock found");
2677 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2680 spa_load_note(spa, "using uberblock with txg=%llu",
2681 (u_longlong_t)ub->ub_txg);
2684 * If the pool has an unsupported version we can't open it.
2686 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2688 spa_load_failed(spa, "version %llu is not supported",
2689 (u_longlong_t)ub->ub_version);
2690 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2693 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2697 * If we weren't able to find what's necessary for reading the
2698 * MOS in the label, return failure.
2700 if (label == NULL) {
2701 spa_load_failed(spa, "label config unavailable");
2702 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2706 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
2709 spa_load_failed(spa, "invalid label: '%s' missing",
2710 ZPOOL_CONFIG_FEATURES_FOR_READ);
2711 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2716 * Update our in-core representation with the definitive values
2719 nvlist_free(spa->spa_label_features);
2720 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2726 * Look through entries in the label nvlist's features_for_read. If
2727 * there is a feature listed there which we don't understand then we
2728 * cannot open a pool.
2730 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2731 nvlist_t *unsup_feat;
2733 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2736 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2738 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2739 if (!zfeature_is_supported(nvpair_name(nvp))) {
2740 VERIFY(nvlist_add_string(unsup_feat,
2741 nvpair_name(nvp), "") == 0);
2745 if (!nvlist_empty(unsup_feat)) {
2746 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2747 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2748 nvlist_free(unsup_feat);
2749 spa_load_failed(spa, "some features are unsupported");
2750 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2754 nvlist_free(unsup_feat);
2757 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2758 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2759 spa_try_repair(spa, spa->spa_config);
2760 spa_config_exit(spa, SCL_ALL, FTAG);
2761 nvlist_free(spa->spa_config_splitting);
2762 spa->spa_config_splitting = NULL;
2766 * Initialize internal SPA structures.
2768 spa_ld_select_uberblock_done(spa, ub);
2774 spa_ld_open_rootbp(spa_t *spa)
2777 vdev_t *rvd = spa->spa_root_vdev;
2779 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2781 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
2782 "[error=%d]", error);
2783 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2785 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2791 spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
2792 boolean_t reloading)
2794 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
2795 nvlist_t *nv, *mos_config, *policy;
2796 int error = 0, copy_error;
2797 uint64_t healthy_tvds, healthy_tvds_mos;
2798 uint64_t mos_config_txg;
2800 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
2802 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2805 * If we're assembling a pool from a split, the config provided is
2806 * already trusted so there is nothing to do.
2808 if (type == SPA_IMPORT_ASSEMBLE)
2811 healthy_tvds = spa_healthy_core_tvds(spa);
2813 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
2815 spa_load_failed(spa, "unable to retrieve MOS config");
2816 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2820 * If we are doing an open, pool owner wasn't verified yet, thus do
2821 * the verification here.
2823 if (spa->spa_load_state == SPA_LOAD_OPEN) {
2824 error = spa_verify_host(spa, mos_config);
2826 nvlist_free(mos_config);
2831 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
2833 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2836 * Build a new vdev tree from the trusted config
2838 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
2841 * Vdev paths in the MOS may be obsolete. If the untrusted config was
2842 * obtained by scanning /dev/dsk, then it will have the right vdev
2843 * paths. We update the trusted MOS config with this information.
2844 * We first try to copy the paths with vdev_copy_path_strict, which
2845 * succeeds only when both configs have exactly the same vdev tree.
2846 * If that fails, we fall back to a more flexible method that has a
2847 * best effort policy.
2849 copy_error = vdev_copy_path_strict(rvd, mrvd);
2850 if (copy_error != 0 || spa_load_print_vdev_tree) {
2851 spa_load_note(spa, "provided vdev tree:");
2852 vdev_dbgmsg_print_tree(rvd, 2);
2853 spa_load_note(spa, "MOS vdev tree:");
2854 vdev_dbgmsg_print_tree(mrvd, 2);
2856 if (copy_error != 0) {
2857 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
2858 "back to vdev_copy_path_relaxed");
2859 vdev_copy_path_relaxed(rvd, mrvd);
2864 spa->spa_root_vdev = mrvd;
2866 spa_config_exit(spa, SCL_ALL, FTAG);
2869 * We will use spa_config if we decide to reload the spa or if spa_load
2870 * fails and we rewind. We must thus regenerate the config using the
2871 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
2872 * pass settings on how to load the pool and is not stored in the MOS.
2873 * We copy it over to our new, trusted config.
2875 mos_config_txg = fnvlist_lookup_uint64(mos_config,
2876 ZPOOL_CONFIG_POOL_TXG);
2877 nvlist_free(mos_config);
2878 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
2879 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
2881 fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
2882 spa_config_set(spa, mos_config);
2883 spa->spa_config_source = SPA_CONFIG_SRC_MOS;
2886 * Now that we got the config from the MOS, we should be more strict
2887 * in checking blkptrs and can make assumptions about the consistency
2888 * of the vdev tree. spa_trust_config must be set to true before opening
2889 * vdevs in order for them to be writeable.
2891 spa->spa_trust_config = B_TRUE;
2894 * Open and validate the new vdev tree
2896 error = spa_ld_open_vdevs(spa);
2900 error = spa_ld_validate_vdevs(spa);
2904 if (copy_error != 0 || spa_load_print_vdev_tree) {
2905 spa_load_note(spa, "final vdev tree:");
2906 vdev_dbgmsg_print_tree(rvd, 2);
2909 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
2910 !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
2912 * Sanity check to make sure that we are indeed loading the
2913 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
2914 * in the config provided and they happened to be the only ones
2915 * to have the latest uberblock, we could involuntarily perform
2916 * an extreme rewind.
2918 healthy_tvds_mos = spa_healthy_core_tvds(spa);
2919 if (healthy_tvds_mos - healthy_tvds >=
2920 SPA_SYNC_MIN_VDEVS) {
2921 spa_load_note(spa, "config provided misses too many "
2922 "top-level vdevs compared to MOS (%lld vs %lld). ",
2923 (u_longlong_t)healthy_tvds,
2924 (u_longlong_t)healthy_tvds_mos);
2925 spa_load_note(spa, "vdev tree:");
2926 vdev_dbgmsg_print_tree(rvd, 2);
2928 spa_load_failed(spa, "config was already "
2929 "provided from MOS. Aborting.");
2930 return (spa_vdev_err(rvd,
2931 VDEV_AUX_CORRUPT_DATA, EIO));
2933 spa_load_note(spa, "spa must be reloaded using MOS "
2935 return (SET_ERROR(EAGAIN));
2939 error = spa_check_for_missing_logs(spa);
2941 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2943 if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
2944 spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
2945 "guid sum (%llu != %llu)",
2946 (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
2947 (u_longlong_t)rvd->vdev_guid_sum);
2948 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
2956 spa_ld_open_indirect_vdev_metadata(spa_t *spa)
2959 vdev_t *rvd = spa->spa_root_vdev;
2962 * Everything that we read before spa_remove_init() must be stored
2963 * on concreted vdevs. Therefore we do this as early as possible.
2965 error = spa_remove_init(spa);
2967 spa_load_failed(spa, "spa_remove_init failed [error=%d]",
2969 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2973 * Retrieve information needed to condense indirect vdev mappings.
2975 error = spa_condense_init(spa);
2977 spa_load_failed(spa, "spa_condense_init failed [error=%d]",
2979 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
2986 spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
2989 vdev_t *rvd = spa->spa_root_vdev;
2991 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2992 boolean_t missing_feat_read = B_FALSE;
2993 nvlist_t *unsup_feat, *enabled_feat;
2995 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
2996 &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
2997 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3000 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
3001 &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
3002 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3005 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
3006 &spa->spa_feat_desc_obj, B_TRUE) != 0) {
3007 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3010 enabled_feat = fnvlist_alloc();
3011 unsup_feat = fnvlist_alloc();
3013 if (!spa_features_check(spa, B_FALSE,
3014 unsup_feat, enabled_feat))
3015 missing_feat_read = B_TRUE;
3017 if (spa_writeable(spa) ||
3018 spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3019 if (!spa_features_check(spa, B_TRUE,
3020 unsup_feat, enabled_feat)) {
3021 *missing_feat_writep = B_TRUE;
3025 fnvlist_add_nvlist(spa->spa_load_info,
3026 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3028 if (!nvlist_empty(unsup_feat)) {
3029 fnvlist_add_nvlist(spa->spa_load_info,
3030 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3033 fnvlist_free(enabled_feat);
3034 fnvlist_free(unsup_feat);
3036 if (!missing_feat_read) {
3037 fnvlist_add_boolean(spa->spa_load_info,
3038 ZPOOL_CONFIG_CAN_RDONLY);
3042 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3043 * twofold: to determine whether the pool is available for
3044 * import in read-write mode and (if it is not) whether the
3045 * pool is available for import in read-only mode. If the pool
3046 * is available for import in read-write mode, it is displayed
3047 * as available in userland; if it is not available for import
3048 * in read-only mode, it is displayed as unavailable in
3049 * userland. If the pool is available for import in read-only
3050 * mode but not read-write mode, it is displayed as unavailable
3051 * in userland with a special note that the pool is actually
3052 * available for open in read-only mode.
3054 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3055 * missing a feature for write, we must first determine whether
3056 * the pool can be opened read-only before returning to
3057 * userland in order to know whether to display the
3058 * abovementioned note.
3060 if (missing_feat_read || (*missing_feat_writep &&
3061 spa_writeable(spa))) {
3062 spa_load_failed(spa, "pool uses unsupported features");
3063 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3068 * Load refcounts for ZFS features from disk into an in-memory
3069 * cache during SPA initialization.
3071 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
3074 error = feature_get_refcount_from_disk(spa,
3075 &spa_feature_table[i], &refcount);
3077 spa->spa_feat_refcount_cache[i] = refcount;
3078 } else if (error == ENOTSUP) {
3079 spa->spa_feat_refcount_cache[i] =
3080 SPA_FEATURE_DISABLED;
3082 spa_load_failed(spa, "error getting refcount "
3083 "for feature %s [error=%d]",
3084 spa_feature_table[i].fi_guid, error);
3085 return (spa_vdev_err(rvd,
3086 VDEV_AUX_CORRUPT_DATA, EIO));
3091 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3092 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
3093 &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
3094 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3101 spa_ld_load_special_directories(spa_t *spa)
3104 vdev_t *rvd = spa->spa_root_vdev;
3106 spa->spa_is_initializing = B_TRUE;
3107 error = dsl_pool_open(spa->spa_dsl_pool);
3108 spa->spa_is_initializing = B_FALSE;
3110 spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3111 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3118 spa_ld_get_props(spa_t *spa)
3122 vdev_t *rvd = spa->spa_root_vdev;
3124 /* Grab the secret checksum salt from the MOS. */
3125 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3126 DMU_POOL_CHECKSUM_SALT, 1,
3127 sizeof (spa->spa_cksum_salt.zcs_bytes),
3128 spa->spa_cksum_salt.zcs_bytes);
3129 if (error == ENOENT) {
3130 /* Generate a new salt for subsequent use */
3131 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3132 sizeof (spa->spa_cksum_salt.zcs_bytes));
3133 } else if (error != 0) {
3134 spa_load_failed(spa, "unable to retrieve checksum salt from "
3135 "MOS [error=%d]", error);
3136 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3139 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3140 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3141 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3143 spa_load_failed(spa, "error opening deferred-frees bpobj "
3144 "[error=%d]", error);
3145 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3149 * Load the bit that tells us to use the new accounting function
3150 * (raid-z deflation). If we have an older pool, this will not
3153 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3154 if (error != 0 && error != ENOENT)
3155 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3157 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3158 &spa->spa_creation_version, B_FALSE);
3159 if (error != 0 && error != ENOENT)
3160 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3163 * Load the persistent error log. If we have an older pool, this will
3166 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3168 if (error != 0 && error != ENOENT)
3169 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3171 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3172 &spa->spa_errlog_scrub, B_FALSE);
3173 if (error != 0 && error != ENOENT)
3174 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3177 * Load the history object. If we have an older pool, this
3178 * will not be present.
3180 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3181 if (error != 0 && error != ENOENT)
3182 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3185 * Load the per-vdev ZAP map. If we have an older pool, this will not
3186 * be present; in this case, defer its creation to a later time to
3187 * avoid dirtying the MOS this early / out of sync context. See
3188 * spa_sync_config_object.
3191 /* The sentinel is only available in the MOS config. */
3192 nvlist_t *mos_config;
3193 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3194 spa_load_failed(spa, "unable to retrieve MOS config");
3195 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3198 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3199 &spa->spa_all_vdev_zaps, B_FALSE);
3201 if (error == ENOENT) {
3202 VERIFY(!nvlist_exists(mos_config,
3203 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3204 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3205 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3206 } else if (error != 0) {
3207 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3208 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3210 * An older version of ZFS overwrote the sentinel value, so
3211 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3212 * destruction to later; see spa_sync_config_object.
3214 spa->spa_avz_action = AVZ_ACTION_DESTROY;
3216 * We're assuming that no vdevs have had their ZAPs created
3217 * before this. Better be sure of it.
3219 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3221 nvlist_free(mos_config);
3223 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3225 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3227 if (error && error != ENOENT)
3228 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3231 uint64_t autoreplace;
3233 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3234 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3235 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3236 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3237 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3238 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3239 &spa->spa_dedup_ditto);
3241 spa->spa_autoreplace = (autoreplace != 0);
3245 * If we are importing a pool with missing top-level vdevs,
3246 * we enforce that the pool doesn't panic or get suspended on
3247 * error since the likelihood of missing data is extremely high.
3249 if (spa->spa_missing_tvds > 0 &&
3250 spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3251 spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3252 spa_load_note(spa, "forcing failmode to 'continue' "
3253 "as some top level vdevs are missing");
3254 spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3261 spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3264 vdev_t *rvd = spa->spa_root_vdev;
3267 * If we're assembling the pool from the split-off vdevs of
3268 * an existing pool, we don't want to attach the spares & cache
3273 * Load any hot spares for this pool.
3275 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3277 if (error != 0 && error != ENOENT)
3278 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3279 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3280 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3281 if (load_nvlist(spa, spa->spa_spares.sav_object,
3282 &spa->spa_spares.sav_config) != 0) {
3283 spa_load_failed(spa, "error loading spares nvlist");
3284 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3287 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3288 spa_load_spares(spa);
3289 spa_config_exit(spa, SCL_ALL, FTAG);
3290 } else if (error == 0) {
3291 spa->spa_spares.sav_sync = B_TRUE;
3295 * Load any level 2 ARC devices for this pool.
3297 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3298 &spa->spa_l2cache.sav_object, B_FALSE);
3299 if (error != 0 && error != ENOENT)
3300 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3301 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3302 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3303 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3304 &spa->spa_l2cache.sav_config) != 0) {
3305 spa_load_failed(spa, "error loading l2cache nvlist");
3306 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3309 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3310 spa_load_l2cache(spa);
3311 spa_config_exit(spa, SCL_ALL, FTAG);
3312 } else if (error == 0) {
3313 spa->spa_l2cache.sav_sync = B_TRUE;
3320 spa_ld_load_vdev_metadata(spa_t *spa)
3323 vdev_t *rvd = spa->spa_root_vdev;
3326 * If the 'autoreplace' property is set, then post a resource notifying
3327 * the ZFS DE that it should not issue any faults for unopenable
3328 * devices. We also iterate over the vdevs, and post a sysevent for any
3329 * unopenable vdevs so that the normal autoreplace handler can take
3332 if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3333 spa_check_removed(spa->spa_root_vdev);
3335 * For the import case, this is done in spa_import(), because
3336 * at this point we're using the spare definitions from
3337 * the MOS config, not necessarily from the userland config.
3339 if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3340 spa_aux_check_removed(&spa->spa_spares);
3341 spa_aux_check_removed(&spa->spa_l2cache);
3346 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3348 error = vdev_load(rvd);
3350 spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3351 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3355 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3357 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3358 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3359 spa_config_exit(spa, SCL_ALL, FTAG);
3365 spa_ld_load_dedup_tables(spa_t *spa)
3368 vdev_t *rvd = spa->spa_root_vdev;
3370 error = ddt_load(spa);
3372 spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3373 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3380 spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3382 vdev_t *rvd = spa->spa_root_vdev;
3384 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3385 boolean_t missing = spa_check_logs(spa);
3387 if (spa->spa_missing_tvds != 0) {
3388 spa_load_note(spa, "spa_check_logs failed "
3389 "so dropping the logs");
3391 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3392 spa_load_failed(spa, "spa_check_logs failed");
3393 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3403 spa_ld_verify_pool_data(spa_t *spa)
3406 vdev_t *rvd = spa->spa_root_vdev;
3409 * We've successfully opened the pool, verify that we're ready
3410 * to start pushing transactions.
3412 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3413 error = spa_load_verify(spa);
3415 spa_load_failed(spa, "spa_load_verify failed "
3416 "[error=%d]", error);
3417 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3426 spa_ld_claim_log_blocks(spa_t *spa)
3429 dsl_pool_t *dp = spa_get_dsl(spa);
3432 * Claim log blocks that haven't been committed yet.
3433 * This must all happen in a single txg.
3434 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3435 * invoked from zil_claim_log_block()'s i/o done callback.
3436 * Price of rollback is that we abandon the log.
3438 spa->spa_claiming = B_TRUE;
3440 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3441 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3442 zil_claim, tx, DS_FIND_CHILDREN);
3445 spa->spa_claiming = B_FALSE;
3447 spa_set_log_state(spa, SPA_LOG_GOOD);
3451 spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3452 boolean_t update_config_cache)
3454 vdev_t *rvd = spa->spa_root_vdev;
3455 int need_update = B_FALSE;
3458 * If the config cache is stale, or we have uninitialized
3459 * metaslabs (see spa_vdev_add()), then update the config.
3461 * If this is a verbatim import, trust the current
3462 * in-core spa_config and update the disk labels.
3464 if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
3465 spa->spa_load_state == SPA_LOAD_IMPORT ||
3466 spa->spa_load_state == SPA_LOAD_RECOVER ||
3467 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3468 need_update = B_TRUE;
3470 for (int c = 0; c < rvd->vdev_children; c++)
3471 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3472 need_update = B_TRUE;
3475 * Update the config cache asychronously in case we're the
3476 * root pool, in which case the config cache isn't writable yet.
3479 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3483 spa_ld_prepare_for_reload(spa_t *spa)
3485 int mode = spa->spa_mode;
3486 int async_suspended = spa->spa_async_suspended;
3489 spa_deactivate(spa);
3490 spa_activate(spa, mode);
3493 * We save the value of spa_async_suspended as it gets reset to 0 by
3494 * spa_unload(). We want to restore it back to the original value before
3495 * returning as we might be calling spa_async_resume() later.
3497 spa->spa_async_suspended = async_suspended;
3501 spa_ld_read_checkpoint_txg(spa_t *spa)
3503 uberblock_t checkpoint;
3506 ASSERT0(spa->spa_checkpoint_txg);
3507 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3509 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3510 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3511 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3513 if (error == ENOENT)
3519 ASSERT3U(checkpoint.ub_txg, !=, 0);
3520 ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3521 ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3522 spa->spa_checkpoint_txg = checkpoint.ub_txg;
3523 spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3529 spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
3533 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3534 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3537 * Never trust the config that is provided unless we are assembling
3538 * a pool following a split.
3539 * This means don't trust blkptrs and the vdev tree in general. This
3540 * also effectively puts the spa in read-only mode since
3541 * spa_writeable() checks for spa_trust_config to be true.
3542 * We will later load a trusted config from the MOS.
3544 if (type != SPA_IMPORT_ASSEMBLE)
3545 spa->spa_trust_config = B_FALSE;
3548 * Parse the config provided to create a vdev tree.
3550 error = spa_ld_parse_config(spa, type);
3555 * Now that we have the vdev tree, try to open each vdev. This involves
3556 * opening the underlying physical device, retrieving its geometry and
3557 * probing the vdev with a dummy I/O. The state of each vdev will be set
3558 * based on the success of those operations. After this we'll be ready
3559 * to read from the vdevs.
3561 error = spa_ld_open_vdevs(spa);
3566 * Read the label of each vdev and make sure that the GUIDs stored
3567 * there match the GUIDs in the config provided.
3568 * If we're assembling a new pool that's been split off from an
3569 * existing pool, the labels haven't yet been updated so we skip
3570 * validation for now.
3572 if (type != SPA_IMPORT_ASSEMBLE) {
3573 error = spa_ld_validate_vdevs(spa);
3579 * Read all vdev labels to find the best uberblock (i.e. latest,
3580 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3581 * get the list of features required to read blkptrs in the MOS from
3582 * the vdev label with the best uberblock and verify that our version
3583 * of zfs supports them all.
3585 error = spa_ld_select_uberblock(spa, type);
3590 * Pass that uberblock to the dsl_pool layer which will open the root
3591 * blkptr. This blkptr points to the latest version of the MOS and will
3592 * allow us to read its contents.
3594 error = spa_ld_open_rootbp(spa);
3602 spa_ld_checkpoint_rewind(spa_t *spa)
3604 uberblock_t checkpoint;
3607 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3608 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3610 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3611 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3612 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3615 spa_load_failed(spa, "unable to retrieve checkpointed "
3616 "uberblock from the MOS config [error=%d]", error);
3618 if (error == ENOENT)
3619 error = ZFS_ERR_NO_CHECKPOINT;
3624 ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
3625 ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
3628 * We need to update the txg and timestamp of the checkpointed
3629 * uberblock to be higher than the latest one. This ensures that
3630 * the checkpointed uberblock is selected if we were to close and
3631 * reopen the pool right after we've written it in the vdev labels.
3632 * (also see block comment in vdev_uberblock_compare)
3634 checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
3635 checkpoint.ub_timestamp = gethrestime_sec();
3638 * Set current uberblock to be the checkpointed uberblock.
3640 spa->spa_uberblock = checkpoint;
3643 * If we are doing a normal rewind, then the pool is open for
3644 * writing and we sync the "updated" checkpointed uberblock to
3645 * disk. Once this is done, we've basically rewound the whole
3646 * pool and there is no way back.
3648 * There are cases when we don't want to attempt and sync the
3649 * checkpointed uberblock to disk because we are opening a
3650 * pool as read-only. Specifically, verifying the checkpointed
3651 * state with zdb, and importing the checkpointed state to get
3652 * a "preview" of its content.
3654 if (spa_writeable(spa)) {
3655 vdev_t *rvd = spa->spa_root_vdev;
3657 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3658 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
3660 int children = rvd->vdev_children;
3661 int c0 = spa_get_random(children);
3663 for (int c = 0; c < children; c++) {
3664 vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
3666 /* Stop when revisiting the first vdev */
3667 if (c > 0 && svd[0] == vd)
3670 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
3671 !vdev_is_concrete(vd))
3674 svd[svdcount++] = vd;
3675 if (svdcount == SPA_SYNC_MIN_VDEVS)
3678 error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
3680 spa->spa_last_synced_guid = rvd->vdev_guid;
3681 spa_config_exit(spa, SCL_ALL, FTAG);
3684 spa_load_failed(spa, "failed to write checkpointed "
3685 "uberblock to the vdev labels [error=%d]", error);
3694 spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
3695 boolean_t *update_config_cache)
3700 * Parse the config for pool, open and validate vdevs,
3701 * select an uberblock, and use that uberblock to open
3704 error = spa_ld_mos_init(spa, type);
3709 * Retrieve the trusted config stored in the MOS and use it to create
3710 * a new, exact version of the vdev tree, then reopen all vdevs.
3712 error = spa_ld_trusted_config(spa, type, B_FALSE);
3713 if (error == EAGAIN) {
3714 if (update_config_cache != NULL)
3715 *update_config_cache = B_TRUE;
3718 * Redo the loading process with the trusted config if it is
3719 * too different from the untrusted config.
3721 spa_ld_prepare_for_reload(spa);
3722 spa_load_note(spa, "RELOADING");
3723 error = spa_ld_mos_init(spa, type);
3727 error = spa_ld_trusted_config(spa, type, B_TRUE);
3731 } else if (error != 0) {
3739 * Load an existing storage pool, using the config provided. This config
3740 * describes which vdevs are part of the pool and is later validated against
3741 * partial configs present in each vdev's label and an entire copy of the
3742 * config stored in the MOS.
3745 spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
3748 boolean_t missing_feat_write = B_FALSE;
3749 boolean_t checkpoint_rewind =
3750 (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3751 boolean_t update_config_cache = B_FALSE;
3753 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3754 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3756 spa_load_note(spa, "LOADING");
3758 error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
3763 * If we are rewinding to the checkpoint then we need to repeat
3764 * everything we've done so far in this function but this time
3765 * selecting the checkpointed uberblock and using that to open
3768 if (checkpoint_rewind) {
3770 * If we are rewinding to the checkpoint update config cache
3773 update_config_cache = B_TRUE;
3776 * Extract the checkpointed uberblock from the current MOS
3777 * and use this as the pool's uberblock from now on. If the
3778 * pool is imported as writeable we also write the checkpoint
3779 * uberblock to the labels, making the rewind permanent.
3781 error = spa_ld_checkpoint_rewind(spa);
3786 * Redo the loading process process again with the
3787 * checkpointed uberblock.
3789 spa_ld_prepare_for_reload(spa);
3790 spa_load_note(spa, "LOADING checkpointed uberblock");
3791 error = spa_ld_mos_with_trusted_config(spa, type, NULL);
3797 * Retrieve the checkpoint txg if the pool has a checkpoint.
3799 error = spa_ld_read_checkpoint_txg(spa);
3804 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
3805 * from the pool and their contents were re-mapped to other vdevs. Note
3806 * that everything that we read before this step must have been
3807 * rewritten on concrete vdevs after the last device removal was
3808 * initiated. Otherwise we could be reading from indirect vdevs before
3809 * we have loaded their mappings.
3811 error = spa_ld_open_indirect_vdev_metadata(spa);
3816 * Retrieve the full list of active features from the MOS and check if
3817 * they are all supported.
3819 error = spa_ld_check_features(spa, &missing_feat_write);
3824 * Load several special directories from the MOS needed by the dsl_pool
3827 error = spa_ld_load_special_directories(spa);
3832 * Retrieve pool properties from the MOS.
3834 error = spa_ld_get_props(spa);
3839 * Retrieve the list of auxiliary devices - cache devices and spares -
3842 error = spa_ld_open_aux_vdevs(spa, type);
3847 * Load the metadata for all vdevs. Also check if unopenable devices
3848 * should be autoreplaced.
3850 error = spa_ld_load_vdev_metadata(spa);
3854 error = spa_ld_load_dedup_tables(spa);
3859 * Verify the logs now to make sure we don't have any unexpected errors
3860 * when we claim log blocks later.
3862 error = spa_ld_verify_logs(spa, type, ereport);
3866 if (missing_feat_write) {
3867 ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
3870 * At this point, we know that we can open the pool in
3871 * read-only mode but not read-write mode. We now have enough
3872 * information and can return to userland.
3874 return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
3879 * Traverse the last txgs to make sure the pool was left off in a safe
3880 * state. When performing an extreme rewind, we verify the whole pool,
3881 * which can take a very long time.
3883 error = spa_ld_verify_pool_data(spa);
3888 * Calculate the deflated space for the pool. This must be done before
3889 * we write anything to the pool because we'd need to update the space
3890 * accounting using the deflated sizes.
3892 spa_update_dspace(spa);
3895 * We have now retrieved all the information we needed to open the
3896 * pool. If we are importing the pool in read-write mode, a few
3897 * additional steps must be performed to finish the import.
3899 if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
3900 spa->spa_load_max_txg == UINT64_MAX)) {
3901 uint64_t config_cache_txg = spa->spa_config_txg;
3903 ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
3906 * In case of a checkpoint rewind, log the original txg
3907 * of the checkpointed uberblock.
3909 if (checkpoint_rewind) {
3910 spa_history_log_internal(spa, "checkpoint rewind",
3911 NULL, "rewound state to txg=%llu",
3912 (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
3916 * Traverse the ZIL and claim all blocks.
3918 spa_ld_claim_log_blocks(spa);
3921 * Kick-off the syncing thread.
3923 spa->spa_sync_on = B_TRUE;
3924 txg_sync_start(spa->spa_dsl_pool);
3927 * Wait for all claims to sync. We sync up to the highest
3928 * claimed log block birth time so that claimed log blocks
3929 * don't appear to be from the future. spa_claim_max_txg
3930 * will have been set for us by ZIL traversal operations
3933 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
3936 * Check if we need to request an update of the config. On the
3937 * next sync, we would update the config stored in vdev labels
3938 * and the cachefile (by default /etc/zfs/zpool.cache).
3940 spa_ld_check_for_config_update(spa, config_cache_txg,
3941 update_config_cache);
3944 * Check all DTLs to see if anything needs resilvering.
3946 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
3947 vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
3948 spa_async_request(spa, SPA_ASYNC_RESILVER);
3951 * Log the fact that we booted up (so that we can detect if
3952 * we rebooted in the middle of an operation).
3954 spa_history_log_version(spa, "open");
3956 spa_restart_removal(spa);
3957 spa_spawn_aux_threads(spa);
3960 * Delete any inconsistent datasets.
3963 * Since we may be issuing deletes for clones here,
3964 * we make sure to do so after we've spawned all the
3965 * auxiliary threads above (from which the livelist
3966 * deletion zthr is part of).
3968 (void) dmu_objset_find(spa_name(spa),
3969 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
3972 * Clean up any stale temporary dataset userrefs.
3974 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
3976 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3977 vdev_initialize_restart(spa->spa_root_vdev);
3978 spa_config_exit(spa, SCL_CONFIG, FTAG);
3981 spa_load_note(spa, "LOADED");
3987 spa_load_retry(spa_t *spa, spa_load_state_t state)
3989 int mode = spa->spa_mode;
3992 spa_deactivate(spa);
3994 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
3996 spa_activate(spa, mode);
3997 spa_async_suspend(spa);
3999 spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
4000 (u_longlong_t)spa->spa_load_max_txg);
4002 return (spa_load(spa, state, SPA_IMPORT_EXISTING));
4006 * If spa_load() fails this function will try loading prior txg's. If
4007 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
4008 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
4009 * function will not rewind the pool and will return the same error as
4013 spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4016 nvlist_t *loadinfo = NULL;
4017 nvlist_t *config = NULL;
4018 int load_error, rewind_error;
4019 uint64_t safe_rewind_txg;
4022 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4023 spa->spa_load_max_txg = spa->spa_load_txg;
4024 spa_set_log_state(spa, SPA_LOG_CLEAR);
4026 spa->spa_load_max_txg = max_request;
4027 if (max_request != UINT64_MAX)
4028 spa->spa_extreme_rewind = B_TRUE;
4031 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
4032 if (load_error == 0)
4034 if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4036 * When attempting checkpoint-rewind on a pool with no
4037 * checkpoint, we should not attempt to load uberblocks
4038 * from previous txgs when spa_load fails.
4040 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4041 return (load_error);
4044 if (spa->spa_root_vdev != NULL)
4045 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4047 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4048 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4050 if (rewind_flags & ZPOOL_NEVER_REWIND) {
4051 nvlist_free(config);
4052 return (load_error);
4055 if (state == SPA_LOAD_RECOVER) {
4056 /* Price of rolling back is discarding txgs, including log */
4057 spa_set_log_state(spa, SPA_LOG_CLEAR);
4060 * If we aren't rolling back save the load info from our first
4061 * import attempt so that we can restore it after attempting
4064 loadinfo = spa->spa_load_info;
4065 spa->spa_load_info = fnvlist_alloc();
4068 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4069 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4070 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4071 TXG_INITIAL : safe_rewind_txg;
4074 * Continue as long as we're finding errors, we're still within
4075 * the acceptable rewind range, and we're still finding uberblocks
4077 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4078 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4079 if (spa->spa_load_max_txg < safe_rewind_txg)
4080 spa->spa_extreme_rewind = B_TRUE;
4081 rewind_error = spa_load_retry(spa, state);
4084 spa->spa_extreme_rewind = B_FALSE;
4085 spa->spa_load_max_txg = UINT64_MAX;
4087 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4088 spa_config_set(spa, config);
4090 nvlist_free(config);
4092 if (state == SPA_LOAD_RECOVER) {
4093 ASSERT3P(loadinfo, ==, NULL);
4094 return (rewind_error);
4096 /* Store the rewind info as part of the initial load info */
4097 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4098 spa->spa_load_info);
4100 /* Restore the initial load info */
4101 fnvlist_free(spa->spa_load_info);
4102 spa->spa_load_info = loadinfo;
4104 return (load_error);
4111 * The import case is identical to an open except that the configuration is sent
4112 * down from userland, instead of grabbed from the configuration cache. For the
4113 * case of an open, the pool configuration will exist in the
4114 * POOL_STATE_UNINITIALIZED state.
4116 * The stats information (gen/count/ustats) is used to gather vdev statistics at
4117 * the same time open the pool, without having to keep around the spa_t in some
4121 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4125 spa_load_state_t state = SPA_LOAD_OPEN;
4127 int locked = B_FALSE;
4128 int firstopen = B_FALSE;
4133 * As disgusting as this is, we need to support recursive calls to this
4134 * function because dsl_dir_open() is called during spa_load(), and ends
4135 * up calling spa_open() again. The real fix is to figure out how to
4136 * avoid dsl_dir_open() calling this in the first place.
4138 if (mutex_owner(&spa_namespace_lock) != curthread) {
4139 mutex_enter(&spa_namespace_lock);
4143 if ((spa = spa_lookup(pool)) == NULL) {
4145 mutex_exit(&spa_namespace_lock);
4146 return (SET_ERROR(ENOENT));
4149 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
4150 zpool_load_policy_t policy;
4154 zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
4156 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
4157 state = SPA_LOAD_RECOVER;
4159 spa_activate(spa, spa_mode_global);
4161 if (state != SPA_LOAD_RECOVER)
4162 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4163 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
4165 zfs_dbgmsg("spa_open_common: opening %s", pool);
4166 error = spa_load_best(spa, state, policy.zlp_txg,
4169 if (error == EBADF) {
4171 * If vdev_validate() returns failure (indicated by
4172 * EBADF), it indicates that one of the vdevs indicates
4173 * that the pool has been exported or destroyed. If
4174 * this is the case, the config cache is out of sync and
4175 * we should remove the pool from the namespace.
4178 spa_deactivate(spa);
4179 spa_write_cachefile(spa, B_TRUE, B_TRUE);
4182 mutex_exit(&spa_namespace_lock);
4183 return (SET_ERROR(ENOENT));
4188 * We can't open the pool, but we still have useful
4189 * information: the state of each vdev after the
4190 * attempted vdev_open(). Return this to the user.
4192 if (config != NULL && spa->spa_config) {
4193 VERIFY(nvlist_dup(spa->spa_config, config,
4195 VERIFY(nvlist_add_nvlist(*config,
4196 ZPOOL_CONFIG_LOAD_INFO,
4197 spa->spa_load_info) == 0);
4200 spa_deactivate(spa);
4201 spa->spa_last_open_failed = error;
4203 mutex_exit(&spa_namespace_lock);
4209 spa_open_ref(spa, tag);
4212 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4215 * If we've recovered the pool, pass back any information we
4216 * gathered while doing the load.
4218 if (state == SPA_LOAD_RECOVER) {
4219 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4220 spa->spa_load_info) == 0);
4224 spa->spa_last_open_failed = 0;
4225 spa->spa_last_ubsync_txg = 0;
4226 spa->spa_load_txg = 0;
4227 mutex_exit(&spa_namespace_lock);
4231 zvol_create_minors(spa->spa_name);
4242 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4245 return (spa_open_common(name, spapp, tag, policy, config));
4249 spa_open(const char *name, spa_t **spapp, void *tag)
4251 return (spa_open_common(name, spapp, tag, NULL, NULL));
4255 * Lookup the given spa_t, incrementing the inject count in the process,
4256 * preventing it from being exported or destroyed.
4259 spa_inject_addref(char *name)
4263 mutex_enter(&spa_namespace_lock);
4264 if ((spa = spa_lookup(name)) == NULL) {
4265 mutex_exit(&spa_namespace_lock);
4268 spa->spa_inject_ref++;
4269 mutex_exit(&spa_namespace_lock);
4275 spa_inject_delref(spa_t *spa)
4277 mutex_enter(&spa_namespace_lock);
4278 spa->spa_inject_ref--;
4279 mutex_exit(&spa_namespace_lock);
4283 * Add spares device information to the nvlist.
4286 spa_add_spares(spa_t *spa, nvlist_t *config)
4296 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4298 if (spa->spa_spares.sav_count == 0)
4301 VERIFY(nvlist_lookup_nvlist(config,
4302 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4303 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4304 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4306 VERIFY(nvlist_add_nvlist_array(nvroot,
4307 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4308 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4309 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4312 * Go through and find any spares which have since been
4313 * repurposed as an active spare. If this is the case, update
4314 * their status appropriately.
4316 for (i = 0; i < nspares; i++) {
4317 VERIFY(nvlist_lookup_uint64(spares[i],
4318 ZPOOL_CONFIG_GUID, &guid) == 0);
4319 if (spa_spare_exists(guid, &pool, NULL) &&
4321 VERIFY(nvlist_lookup_uint64_array(
4322 spares[i], ZPOOL_CONFIG_VDEV_STATS,
4323 (uint64_t **)&vs, &vsc) == 0);
4324 vs->vs_state = VDEV_STATE_CANT_OPEN;
4325 vs->vs_aux = VDEV_AUX_SPARED;
4332 * Add l2cache device information to the nvlist, including vdev stats.
4335 spa_add_l2cache(spa_t *spa, nvlist_t *config)
4338 uint_t i, j, nl2cache;
4345 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4347 if (spa->spa_l2cache.sav_count == 0)
4350 VERIFY(nvlist_lookup_nvlist(config,
4351 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4352 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4353 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4354 if (nl2cache != 0) {
4355 VERIFY(nvlist_add_nvlist_array(nvroot,
4356 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4357 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4358 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4361 * Update level 2 cache device stats.
4364 for (i = 0; i < nl2cache; i++) {
4365 VERIFY(nvlist_lookup_uint64(l2cache[i],
4366 ZPOOL_CONFIG_GUID, &guid) == 0);
4369 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4371 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4372 vd = spa->spa_l2cache.sav_vdevs[j];
4378 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4379 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4381 vdev_get_stats(vd, vs);
4387 spa_feature_stats_from_disk(spa_t *spa, nvlist_t *features)
4392 /* We may be unable to read features if pool is suspended. */
4393 if (spa_suspended(spa))
4396 if (spa->spa_feat_for_read_obj != 0) {
4397 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4398 spa->spa_feat_for_read_obj);
4399 zap_cursor_retrieve(&zc, &za) == 0;
4400 zap_cursor_advance(&zc)) {
4401 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4402 za.za_num_integers == 1);
4403 VERIFY0(nvlist_add_uint64(features, za.za_name,
4404 za.za_first_integer));
4406 zap_cursor_fini(&zc);
4409 if (spa->spa_feat_for_write_obj != 0) {
4410 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4411 spa->spa_feat_for_write_obj);
4412 zap_cursor_retrieve(&zc, &za) == 0;
4413 zap_cursor_advance(&zc)) {
4414 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4415 za.za_num_integers == 1);
4416 VERIFY0(nvlist_add_uint64(features, za.za_name,
4417 za.za_first_integer));
4419 zap_cursor_fini(&zc);
4424 spa_feature_stats_from_cache(spa_t *spa, nvlist_t *features)
4428 for (i = 0; i < SPA_FEATURES; i++) {
4429 zfeature_info_t feature = spa_feature_table[i];
4432 if (feature_get_refcount(spa, &feature, &refcount) != 0)
4435 VERIFY0(nvlist_add_uint64(features, feature.fi_guid, refcount));
4440 * Store a list of pool features and their reference counts in the
4443 * The first time this is called on a spa, allocate a new nvlist, fetch
4444 * the pool features and reference counts from disk, then save the list
4445 * in the spa. In subsequent calls on the same spa use the saved nvlist
4446 * and refresh its values from the cached reference counts. This
4447 * ensures we don't block here on I/O on a suspended pool so 'zpool
4448 * clear' can resume the pool.
4451 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4455 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4457 mutex_enter(&spa->spa_feat_stats_lock);
4458 features = spa->spa_feat_stats;
4460 if (features != NULL) {
4461 spa_feature_stats_from_cache(spa, features);
4463 VERIFY0(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP));
4464 spa->spa_feat_stats = features;
4465 spa_feature_stats_from_disk(spa, features);
4468 VERIFY0(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4471 mutex_exit(&spa->spa_feat_stats_lock);
4475 spa_get_stats(const char *name, nvlist_t **config,
4476 char *altroot, size_t buflen)
4482 error = spa_open_common(name, &spa, FTAG, NULL, config);
4486 * This still leaves a window of inconsistency where the spares
4487 * or l2cache devices could change and the config would be
4488 * self-inconsistent.
4490 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4492 if (*config != NULL) {
4493 uint64_t loadtimes[2];
4495 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4496 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4497 VERIFY(nvlist_add_uint64_array(*config,
4498 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4500 VERIFY(nvlist_add_uint64(*config,
4501 ZPOOL_CONFIG_ERRCOUNT,
4502 spa_get_errlog_size(spa)) == 0);
4504 if (spa_suspended(spa))
4505 VERIFY(nvlist_add_uint64(*config,
4506 ZPOOL_CONFIG_SUSPENDED,
4507 spa->spa_failmode) == 0);
4509 spa_add_spares(spa, *config);
4510 spa_add_l2cache(spa, *config);
4511 spa_add_feature_stats(spa, *config);
4516 * We want to get the alternate root even for faulted pools, so we cheat
4517 * and call spa_lookup() directly.
4521 mutex_enter(&spa_namespace_lock);
4522 spa = spa_lookup(name);
4524 spa_altroot(spa, altroot, buflen);
4528 mutex_exit(&spa_namespace_lock);
4530 spa_altroot(spa, altroot, buflen);
4535 spa_config_exit(spa, SCL_CONFIG, FTAG);
4536 spa_close(spa, FTAG);
4543 * Validate that the auxiliary device array is well formed. We must have an
4544 * array of nvlists, each which describes a valid leaf vdev. If this is an
4545 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4546 * specified, as long as they are well-formed.
4549 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4550 spa_aux_vdev_t *sav, const char *config, uint64_t version,
4551 vdev_labeltype_t label)
4558 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4561 * It's acceptable to have no devs specified.
4563 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4567 return (SET_ERROR(EINVAL));
4570 * Make sure the pool is formatted with a version that supports this
4573 if (spa_version(spa) < version)
4574 return (SET_ERROR(ENOTSUP));
4577 * Set the pending device list so we correctly handle device in-use
4580 sav->sav_pending = dev;
4581 sav->sav_npending = ndev;
4583 for (i = 0; i < ndev; i++) {
4584 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4588 if (!vd->vdev_ops->vdev_op_leaf) {
4590 error = SET_ERROR(EINVAL);
4595 * The L2ARC currently only supports disk devices in
4596 * kernel context. For user-level testing, we allow it.
4599 if ((strcmp(config, ZPOOL_CONFIG_L2CACHE) == 0) &&
4600 strcmp(vd->vdev_ops->vdev_op_type, VDEV_TYPE_DISK) != 0) {
4601 error = SET_ERROR(ENOTBLK);
4608 if ((error = vdev_open(vd)) == 0 &&
4609 (error = vdev_label_init(vd, crtxg, label)) == 0) {
4610 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4611 vd->vdev_guid) == 0);
4617 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
4624 sav->sav_pending = NULL;
4625 sav->sav_npending = 0;
4630 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
4634 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4636 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4637 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
4638 VDEV_LABEL_SPARE)) != 0) {
4642 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4643 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
4644 VDEV_LABEL_L2CACHE));
4648 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
4653 if (sav->sav_config != NULL) {
4659 * Generate new dev list by concatentating with the
4662 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
4663 &olddevs, &oldndevs) == 0);
4665 newdevs = kmem_alloc(sizeof (void *) *
4666 (ndevs + oldndevs), KM_SLEEP);
4667 for (i = 0; i < oldndevs; i++)
4668 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
4670 for (i = 0; i < ndevs; i++)
4671 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
4674 VERIFY(nvlist_remove(sav->sav_config, config,
4675 DATA_TYPE_NVLIST_ARRAY) == 0);
4677 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
4678 config, newdevs, ndevs + oldndevs) == 0);
4679 for (i = 0; i < oldndevs + ndevs; i++)
4680 nvlist_free(newdevs[i]);
4681 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
4684 * Generate a new dev list.
4686 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
4688 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
4694 * Stop and drop level 2 ARC devices
4697 spa_l2cache_drop(spa_t *spa)
4701 spa_aux_vdev_t *sav = &spa->spa_l2cache;
4703 for (i = 0; i < sav->sav_count; i++) {
4706 vd = sav->sav_vdevs[i];
4709 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
4710 pool != 0ULL && l2arc_vdev_present(vd))
4711 l2arc_remove_vdev(vd);
4719 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
4723 char *altroot = NULL;
4728 uint64_t txg = TXG_INITIAL;
4729 nvlist_t **spares, **l2cache;
4730 uint_t nspares, nl2cache;
4731 uint64_t version, obj;
4732 boolean_t has_features;
4736 if (nvlist_lookup_string(props,
4737 zpool_prop_to_name(ZPOOL_PROP_TNAME), &poolname) != 0)
4738 poolname = (char *)pool;
4741 * If this pool already exists, return failure.
4743 mutex_enter(&spa_namespace_lock);
4744 if (spa_lookup(poolname) != NULL) {
4745 mutex_exit(&spa_namespace_lock);
4746 return (SET_ERROR(EEXIST));
4750 * Allocate a new spa_t structure.
4752 nvl = fnvlist_alloc();
4753 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
4754 (void) nvlist_lookup_string(props,
4755 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4756 spa = spa_add(poolname, nvl, altroot);
4758 spa_activate(spa, spa_mode_global);
4760 if (props && (error = spa_prop_validate(spa, props))) {
4761 spa_deactivate(spa);
4763 mutex_exit(&spa_namespace_lock);
4768 * Temporary pool names should never be written to disk.
4770 if (poolname != pool)
4771 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
4773 has_features = B_FALSE;
4774 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
4775 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
4776 if (zpool_prop_feature(nvpair_name(elem)))
4777 has_features = B_TRUE;
4780 if (has_features || nvlist_lookup_uint64(props,
4781 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
4782 version = SPA_VERSION;
4784 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
4786 spa->spa_first_txg = txg;
4787 spa->spa_uberblock.ub_txg = txg - 1;
4788 spa->spa_uberblock.ub_version = version;
4789 spa->spa_ubsync = spa->spa_uberblock;
4790 spa->spa_load_state = SPA_LOAD_CREATE;
4791 spa->spa_removing_phys.sr_state = DSS_NONE;
4792 spa->spa_removing_phys.sr_removing_vdev = -1;
4793 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
4794 spa->spa_indirect_vdevs_loaded = B_TRUE;
4797 * Create "The Godfather" zio to hold all async IOs
4799 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
4801 for (int i = 0; i < max_ncpus; i++) {
4802 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
4803 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4804 ZIO_FLAG_GODFATHER);
4808 * Create the root vdev.
4810 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4812 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
4814 ASSERT(error != 0 || rvd != NULL);
4815 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
4817 if (error == 0 && !zfs_allocatable_devs(nvroot))
4818 error = SET_ERROR(EINVAL);
4821 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
4822 (error = spa_validate_aux(spa, nvroot, txg,
4823 VDEV_ALLOC_ADD)) == 0) {
4824 for (int c = 0; c < rvd->vdev_children; c++) {
4825 vdev_ashift_optimize(rvd->vdev_child[c]);
4826 vdev_metaslab_set_size(rvd->vdev_child[c]);
4827 vdev_expand(rvd->vdev_child[c], txg);
4831 spa_config_exit(spa, SCL_ALL, FTAG);
4835 spa_deactivate(spa);
4837 mutex_exit(&spa_namespace_lock);
4842 * Get the list of spares, if specified.
4844 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4845 &spares, &nspares) == 0) {
4846 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
4848 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4849 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4850 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4851 spa_load_spares(spa);
4852 spa_config_exit(spa, SCL_ALL, FTAG);
4853 spa->spa_spares.sav_sync = B_TRUE;
4857 * Get the list of level 2 cache devices, if specified.
4859 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4860 &l2cache, &nl2cache) == 0) {
4861 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
4862 NV_UNIQUE_NAME, KM_SLEEP) == 0);
4863 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4864 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4865 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4866 spa_load_l2cache(spa);
4867 spa_config_exit(spa, SCL_ALL, FTAG);
4868 spa->spa_l2cache.sav_sync = B_TRUE;
4871 spa->spa_is_initializing = B_TRUE;
4872 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
4873 spa->spa_meta_objset = dp->dp_meta_objset;
4874 spa->spa_is_initializing = B_FALSE;
4877 * Create DDTs (dedup tables).
4881 spa_update_dspace(spa);
4883 tx = dmu_tx_create_assigned(dp, txg);
4886 * Create the pool config object.
4888 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
4889 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
4890 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
4892 if (zap_add(spa->spa_meta_objset,
4893 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
4894 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
4895 cmn_err(CE_PANIC, "failed to add pool config");
4898 if (spa_version(spa) >= SPA_VERSION_FEATURES)
4899 spa_feature_create_zap_objects(spa, tx);
4901 if (zap_add(spa->spa_meta_objset,
4902 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
4903 sizeof (uint64_t), 1, &version, tx) != 0) {
4904 cmn_err(CE_PANIC, "failed to add pool version");
4907 /* Newly created pools with the right version are always deflated. */
4908 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
4909 spa->spa_deflate = TRUE;
4910 if (zap_add(spa->spa_meta_objset,
4911 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
4912 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
4913 cmn_err(CE_PANIC, "failed to add deflate");
4918 * Create the deferred-free bpobj. Turn off compression
4919 * because sync-to-convergence takes longer if the blocksize
4922 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
4923 dmu_object_set_compress(spa->spa_meta_objset, obj,
4924 ZIO_COMPRESS_OFF, tx);
4925 if (zap_add(spa->spa_meta_objset,
4926 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
4927 sizeof (uint64_t), 1, &obj, tx) != 0) {
4928 cmn_err(CE_PANIC, "failed to add bpobj");
4930 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
4931 spa->spa_meta_objset, obj));
4934 * Create the pool's history object.
4936 if (version >= SPA_VERSION_ZPOOL_HISTORY)
4937 spa_history_create_obj(spa, tx);
4940 * Generate some random noise for salted checksums to operate on.
4942 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
4943 sizeof (spa->spa_cksum_salt.zcs_bytes));
4946 * Set pool properties.
4948 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
4949 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
4950 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
4951 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
4953 if (props != NULL) {
4954 spa_configfile_set(spa, props, B_FALSE);
4955 spa_sync_props(props, tx);
4960 spa->spa_sync_on = B_TRUE;
4961 txg_sync_start(spa->spa_dsl_pool);
4964 * We explicitly wait for the first transaction to complete so that our
4965 * bean counters are appropriately updated.
4967 txg_wait_synced(spa->spa_dsl_pool, txg);
4969 spa_spawn_aux_threads(spa);
4971 spa_write_cachefile(spa, B_FALSE, B_TRUE);
4972 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
4974 spa_history_log_version(spa, "create");
4977 * Don't count references from objsets that are already closed
4978 * and are making their way through the eviction process.
4980 spa_evicting_os_wait(spa);
4981 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
4982 spa->spa_load_state = SPA_LOAD_NONE;
4984 mutex_exit(&spa_namespace_lock);
4992 * Get the root pool information from the root disk, then import the root pool
4993 * during the system boot up time.
4995 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
4998 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
5001 nvlist_t *nvtop, *nvroot;
5004 if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
5008 * Add this top-level vdev to the child array.
5010 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5012 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5014 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
5017 * Put this pool's top-level vdevs into a root vdev.
5019 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5020 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5021 VDEV_TYPE_ROOT) == 0);
5022 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5023 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5024 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5028 * Replace the existing vdev_tree with the new root vdev in
5029 * this pool's configuration (remove the old, add the new).
5031 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5032 nvlist_free(nvroot);
5037 * Walk the vdev tree and see if we can find a device with "better"
5038 * configuration. A configuration is "better" if the label on that
5039 * device has a more recent txg.
5042 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
5044 for (int c = 0; c < vd->vdev_children; c++)
5045 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
5047 if (vd->vdev_ops->vdev_op_leaf) {
5051 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
5055 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
5059 * Do we have a better boot device?
5061 if (label_txg > *txg) {
5070 * Import a root pool.
5072 * For x86. devpath_list will consist of devid and/or physpath name of
5073 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
5074 * The GRUB "findroot" command will return the vdev we should boot.
5076 * For Sparc, devpath_list consists the physpath name of the booting device
5077 * no matter the rootpool is a single device pool or a mirrored pool.
5079 * "/pci@1f,0/ide@d/disk@0,0:a"
5082 spa_import_rootpool(char *devpath, char *devid)
5085 vdev_t *rvd, *bvd, *avd = NULL;
5086 nvlist_t *config, *nvtop;
5092 * Read the label from the boot device and generate a configuration.
5094 config = spa_generate_rootconf(devpath, devid, &guid);
5095 #if defined(_OBP) && defined(_KERNEL)
5096 if (config == NULL) {
5097 if (strstr(devpath, "/iscsi/ssd") != NULL) {
5099 get_iscsi_bootpath_phy(devpath);
5100 config = spa_generate_rootconf(devpath, devid, &guid);
5104 if (config == NULL) {
5105 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
5107 return (SET_ERROR(EIO));
5110 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5112 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
5114 mutex_enter(&spa_namespace_lock);
5115 if ((spa = spa_lookup(pname)) != NULL) {
5117 * Remove the existing root pool from the namespace so that we
5118 * can replace it with the correct config we just read in.
5123 spa = spa_add(pname, config, NULL);
5124 spa->spa_is_root = B_TRUE;
5125 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5126 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5127 &spa->spa_ubsync.ub_version) != 0)
5128 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5131 * Build up a vdev tree based on the boot device's label config.
5133 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5135 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5136 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5137 VDEV_ALLOC_ROOTPOOL);
5138 spa_config_exit(spa, SCL_ALL, FTAG);
5140 mutex_exit(&spa_namespace_lock);
5141 nvlist_free(config);
5142 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5148 * Get the boot vdev.
5150 if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
5151 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
5152 (u_longlong_t)guid);
5153 error = SET_ERROR(ENOENT);
5158 * Determine if there is a better boot device.
5161 spa_alt_rootvdev(rvd, &avd, &txg);
5163 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
5164 "try booting from '%s'", avd->vdev_path);
5165 error = SET_ERROR(EINVAL);
5170 * If the boot device is part of a spare vdev then ensure that
5171 * we're booting off the active spare.
5173 if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
5174 !bvd->vdev_isspare) {
5175 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
5176 "try booting from '%s'",
5178 vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
5179 error = SET_ERROR(EINVAL);
5185 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5187 spa_config_exit(spa, SCL_ALL, FTAG);
5188 mutex_exit(&spa_namespace_lock);
5190 nvlist_free(config);
5194 #else /* !illumos */
5196 extern int vdev_geom_read_pool_label(const char *name, nvlist_t ***configs,
5200 spa_generate_rootconf(const char *name)
5202 nvlist_t **configs, **tops;
5204 nvlist_t *best_cfg, *nvtop, *nvroot;
5213 if (vdev_geom_read_pool_label(name, &configs, &count) != 0)
5216 ASSERT3U(count, !=, 0);
5218 for (i = 0; i < count; i++) {
5221 VERIFY(nvlist_lookup_uint64(configs[i], ZPOOL_CONFIG_POOL_TXG,
5223 if (txg > best_txg) {
5225 best_cfg = configs[i];
5230 nvlist_lookup_uint64(best_cfg, ZPOOL_CONFIG_VDEV_CHILDREN, &nchildren);
5232 nvlist_lookup_uint64_array(best_cfg, ZPOOL_CONFIG_HOLE_ARRAY,
5235 tops = kmem_zalloc(nchildren * sizeof(void *), KM_SLEEP);
5236 for (i = 0; i < nchildren; i++) {
5239 if (configs[i] == NULL)
5241 VERIFY(nvlist_lookup_nvlist(configs[i], ZPOOL_CONFIG_VDEV_TREE,
5243 nvlist_dup(nvtop, &tops[i], KM_SLEEP);
5245 for (i = 0; holes != NULL && i < nholes; i++) {
5248 if (tops[holes[i]] != NULL)
5250 nvlist_alloc(&tops[holes[i]], NV_UNIQUE_NAME, KM_SLEEP);
5251 VERIFY(nvlist_add_string(tops[holes[i]], ZPOOL_CONFIG_TYPE,
5252 VDEV_TYPE_HOLE) == 0);
5253 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_ID,
5255 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_GUID,
5258 for (i = 0; i < nchildren; i++) {
5259 if (tops[i] != NULL)
5261 nvlist_alloc(&tops[i], NV_UNIQUE_NAME, KM_SLEEP);
5262 VERIFY(nvlist_add_string(tops[i], ZPOOL_CONFIG_TYPE,
5263 VDEV_TYPE_MISSING) == 0);
5264 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_ID,
5266 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_GUID,
5271 * Create pool config based on the best vdev config.
5273 nvlist_dup(best_cfg, &config, KM_SLEEP);
5276 * Put this pool's top-level vdevs into a root vdev.
5278 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5280 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5281 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5282 VDEV_TYPE_ROOT) == 0);
5283 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5284 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5285 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5286 tops, nchildren) == 0);
5289 * Replace the existing vdev_tree with the new root vdev in
5290 * this pool's configuration (remove the old, add the new).
5292 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5295 * Drop vdev config elements that should not be present at pool level.
5297 nvlist_remove(config, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64);
5298 nvlist_remove(config, ZPOOL_CONFIG_TOP_GUID, DATA_TYPE_UINT64);
5300 for (i = 0; i < count; i++)
5301 nvlist_free(configs[i]);
5302 kmem_free(configs, count * sizeof(void *));
5303 for (i = 0; i < nchildren; i++)
5304 nvlist_free(tops[i]);
5305 kmem_free(tops, nchildren * sizeof(void *));
5306 nvlist_free(nvroot);
5311 spa_import_rootpool(const char *name)
5314 vdev_t *rvd, *bvd, *avd = NULL;
5315 nvlist_t *config, *nvtop;
5321 * Read the label from the boot device and generate a configuration.
5323 config = spa_generate_rootconf(name);
5325 mutex_enter(&spa_namespace_lock);
5326 if (config != NULL) {
5327 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5328 &pname) == 0 && strcmp(name, pname) == 0);
5329 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg)
5332 if ((spa = spa_lookup(pname)) != NULL) {
5334 * The pool could already be imported,
5335 * e.g., after reboot -r.
5337 if (spa->spa_state == POOL_STATE_ACTIVE) {
5338 mutex_exit(&spa_namespace_lock);
5339 nvlist_free(config);
5344 * Remove the existing root pool from the namespace so
5345 * that we can replace it with the correct config
5350 spa = spa_add(pname, config, NULL);
5353 * Set spa_ubsync.ub_version as it can be used in vdev_alloc()
5354 * via spa_version().
5356 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5357 &spa->spa_ubsync.ub_version) != 0)
5358 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5359 } else if ((spa = spa_lookup(name)) == NULL) {
5360 mutex_exit(&spa_namespace_lock);
5361 nvlist_free(config);
5362 cmn_err(CE_NOTE, "Cannot find the pool label for '%s'",
5366 VERIFY(nvlist_dup(spa->spa_config, &config, KM_SLEEP) == 0);
5368 spa->spa_is_root = B_TRUE;
5369 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5372 * Build up a vdev tree based on the boot device's label config.
5374 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5376 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5377 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5378 VDEV_ALLOC_ROOTPOOL);
5379 spa_config_exit(spa, SCL_ALL, FTAG);
5381 mutex_exit(&spa_namespace_lock);
5382 nvlist_free(config);
5383 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5388 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5390 spa_config_exit(spa, SCL_ALL, FTAG);
5391 mutex_exit(&spa_namespace_lock);
5393 nvlist_free(config);
5397 #endif /* illumos */
5398 #endif /* _KERNEL */
5401 * Import a non-root pool into the system.
5404 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5407 char *altroot = NULL;
5408 spa_load_state_t state = SPA_LOAD_IMPORT;
5409 zpool_load_policy_t policy;
5410 uint64_t mode = spa_mode_global;
5411 uint64_t readonly = B_FALSE;
5414 nvlist_t **spares, **l2cache;
5415 uint_t nspares, nl2cache;
5418 * If a pool with this name exists, return failure.
5420 mutex_enter(&spa_namespace_lock);
5421 if (spa_lookup(pool) != NULL) {
5422 mutex_exit(&spa_namespace_lock);
5423 return (SET_ERROR(EEXIST));
5427 * Create and initialize the spa structure.
5429 (void) nvlist_lookup_string(props,
5430 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5431 (void) nvlist_lookup_uint64(props,
5432 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5435 spa = spa_add(pool, config, altroot);
5436 spa->spa_import_flags = flags;
5439 * Verbatim import - Take a pool and insert it into the namespace
5440 * as if it had been loaded at boot.
5442 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5444 spa_configfile_set(spa, props, B_FALSE);
5446 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5447 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5448 zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5449 mutex_exit(&spa_namespace_lock);
5453 spa_activate(spa, mode);
5456 * Don't start async tasks until we know everything is healthy.
5458 spa_async_suspend(spa);
5460 zpool_get_load_policy(config, &policy);
5461 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5462 state = SPA_LOAD_RECOVER;
5464 spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5466 if (state != SPA_LOAD_RECOVER) {
5467 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5468 zfs_dbgmsg("spa_import: importing %s", pool);
5470 zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5471 "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
5473 error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
5476 * Propagate anything learned while loading the pool and pass it
5477 * back to caller (i.e. rewind info, missing devices, etc).
5479 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5480 spa->spa_load_info) == 0);
5482 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5484 * Toss any existing sparelist, as it doesn't have any validity
5485 * anymore, and conflicts with spa_has_spare().
5487 if (spa->spa_spares.sav_config) {
5488 nvlist_free(spa->spa_spares.sav_config);
5489 spa->spa_spares.sav_config = NULL;
5490 spa_load_spares(spa);
5492 if (spa->spa_l2cache.sav_config) {
5493 nvlist_free(spa->spa_l2cache.sav_config);
5494 spa->spa_l2cache.sav_config = NULL;
5495 spa_load_l2cache(spa);
5498 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5501 error = spa_validate_aux(spa, nvroot, -1ULL,
5504 error = spa_validate_aux(spa, nvroot, -1ULL,
5505 VDEV_ALLOC_L2CACHE);
5506 spa_config_exit(spa, SCL_ALL, FTAG);
5509 spa_configfile_set(spa, props, B_FALSE);
5511 if (error != 0 || (props && spa_writeable(spa) &&
5512 (error = spa_prop_set(spa, props)))) {
5514 spa_deactivate(spa);
5516 mutex_exit(&spa_namespace_lock);
5520 spa_async_resume(spa);
5523 * Override any spares and level 2 cache devices as specified by
5524 * the user, as these may have correct device names/devids, etc.
5526 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5527 &spares, &nspares) == 0) {
5528 if (spa->spa_spares.sav_config)
5529 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5530 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5532 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5533 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5534 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5535 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5536 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5537 spa_load_spares(spa);
5538 spa_config_exit(spa, SCL_ALL, FTAG);
5539 spa->spa_spares.sav_sync = B_TRUE;
5541 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5542 &l2cache, &nl2cache) == 0) {
5543 if (spa->spa_l2cache.sav_config)
5544 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5545 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5547 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5548 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5549 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5550 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5551 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5552 spa_load_l2cache(spa);
5553 spa_config_exit(spa, SCL_ALL, FTAG);
5554 spa->spa_l2cache.sav_sync = B_TRUE;
5558 * Check for any removed devices.
5560 if (spa->spa_autoreplace) {
5561 spa_aux_check_removed(&spa->spa_spares);
5562 spa_aux_check_removed(&spa->spa_l2cache);
5565 if (spa_writeable(spa)) {
5567 * Update the config cache to include the newly-imported pool.
5569 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5573 * It's possible that the pool was expanded while it was exported.
5574 * We kick off an async task to handle this for us.
5576 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5578 spa_history_log_version(spa, "import");
5580 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5582 mutex_exit(&spa_namespace_lock);
5586 zvol_create_minors(pool);
5593 spa_tryimport(nvlist_t *tryconfig)
5595 nvlist_t *config = NULL;
5596 char *poolname, *cachefile;
5600 zpool_load_policy_t policy;
5602 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5605 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5609 * Create and initialize the spa structure.
5611 mutex_enter(&spa_namespace_lock);
5612 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
5613 spa_activate(spa, FREAD);
5616 * Rewind pool if a max txg was provided.
5618 zpool_get_load_policy(spa->spa_config, &policy);
5619 if (policy.zlp_txg != UINT64_MAX) {
5620 spa->spa_load_max_txg = policy.zlp_txg;
5621 spa->spa_extreme_rewind = B_TRUE;
5622 zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
5623 poolname, (longlong_t)policy.zlp_txg);
5625 zfs_dbgmsg("spa_tryimport: importing %s", poolname);
5628 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
5630 zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
5631 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5633 spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
5636 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
5639 * If 'tryconfig' was at least parsable, return the current config.
5641 if (spa->spa_root_vdev != NULL) {
5642 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5643 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
5645 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5647 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
5648 spa->spa_uberblock.ub_timestamp) == 0);
5649 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5650 spa->spa_load_info) == 0);
5653 * If the bootfs property exists on this pool then we
5654 * copy it out so that external consumers can tell which
5655 * pools are bootable.
5657 if ((!error || error == EEXIST) && spa->spa_bootfs) {
5658 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5661 * We have to play games with the name since the
5662 * pool was opened as TRYIMPORT_NAME.
5664 if (dsl_dsobj_to_dsname(spa_name(spa),
5665 spa->spa_bootfs, tmpname) == 0) {
5667 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5669 cp = strchr(tmpname, '/');
5671 (void) strlcpy(dsname, tmpname,
5674 (void) snprintf(dsname, MAXPATHLEN,
5675 "%s/%s", poolname, ++cp);
5677 VERIFY(nvlist_add_string(config,
5678 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
5679 kmem_free(dsname, MAXPATHLEN);
5681 kmem_free(tmpname, MAXPATHLEN);
5685 * Add the list of hot spares and level 2 cache devices.
5687 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5688 spa_add_spares(spa, config);
5689 spa_add_l2cache(spa, config);
5690 spa_config_exit(spa, SCL_CONFIG, FTAG);
5694 spa_deactivate(spa);
5696 mutex_exit(&spa_namespace_lock);
5702 * Pool export/destroy
5704 * The act of destroying or exporting a pool is very simple. We make sure there
5705 * is no more pending I/O and any references to the pool are gone. Then, we
5706 * update the pool state and sync all the labels to disk, removing the
5707 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
5708 * we don't sync the labels or remove the configuration cache.
5711 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
5712 boolean_t force, boolean_t hardforce)
5719 if (!(spa_mode_global & FWRITE))
5720 return (SET_ERROR(EROFS));
5722 mutex_enter(&spa_namespace_lock);
5723 if ((spa = spa_lookup(pool)) == NULL) {
5724 mutex_exit(&spa_namespace_lock);
5725 return (SET_ERROR(ENOENT));
5729 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5730 * reacquire the namespace lock, and see if we can export.
5732 spa_open_ref(spa, FTAG);
5733 mutex_exit(&spa_namespace_lock);
5734 spa_async_suspend(spa);
5735 mutex_enter(&spa_namespace_lock);
5736 spa_close(spa, FTAG);
5739 * The pool will be in core if it's openable,
5740 * in which case we can modify its state.
5742 if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
5745 * Objsets may be open only because they're dirty, so we
5746 * have to force it to sync before checking spa_refcnt.
5748 txg_wait_synced(spa->spa_dsl_pool, 0);
5749 spa_evicting_os_wait(spa);
5752 * A pool cannot be exported or destroyed if there are active
5753 * references. If we are resetting a pool, allow references by
5754 * fault injection handlers.
5756 if (!spa_refcount_zero(spa) ||
5757 (spa->spa_inject_ref != 0 &&
5758 new_state != POOL_STATE_UNINITIALIZED)) {
5759 spa_async_resume(spa);
5760 mutex_exit(&spa_namespace_lock);
5761 return (SET_ERROR(EBUSY));
5765 * A pool cannot be exported if it has an active shared spare.
5766 * This is to prevent other pools stealing the active spare
5767 * from an exported pool. At user's own will, such pool can
5768 * be forcedly exported.
5770 if (!force && new_state == POOL_STATE_EXPORTED &&
5771 spa_has_active_shared_spare(spa)) {
5772 spa_async_resume(spa);
5773 mutex_exit(&spa_namespace_lock);
5774 return (SET_ERROR(EXDEV));
5778 * We're about to export or destroy this pool. Make sure
5779 * we stop all initializtion activity here before we
5780 * set the spa_final_txg. This will ensure that all
5781 * dirty data resulting from the initialization is
5782 * committed to disk before we unload the pool.
5784 if (spa->spa_root_vdev != NULL) {
5785 vdev_initialize_stop_all(spa->spa_root_vdev,
5786 VDEV_INITIALIZE_ACTIVE);
5790 * We want this to be reflected on every label,
5791 * so mark them all dirty. spa_unload() will do the
5792 * final sync that pushes these changes out.
5794 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
5795 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5796 spa->spa_state = new_state;
5797 spa->spa_final_txg = spa_last_synced_txg(spa) +
5799 vdev_config_dirty(spa->spa_root_vdev);
5800 spa_config_exit(spa, SCL_ALL, FTAG);
5804 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
5806 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
5808 spa_deactivate(spa);
5811 if (oldconfig && spa->spa_config)
5812 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
5814 if (new_state != POOL_STATE_UNINITIALIZED) {
5816 spa_write_cachefile(spa, B_TRUE, B_TRUE);
5819 mutex_exit(&spa_namespace_lock);
5825 * Destroy a storage pool.
5828 spa_destroy(char *pool)
5830 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
5835 * Export a storage pool.
5838 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
5839 boolean_t hardforce)
5841 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
5846 * Similar to spa_export(), this unloads the spa_t without actually removing it
5847 * from the namespace in any way.
5850 spa_reset(char *pool)
5852 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
5857 * ==========================================================================
5858 * Device manipulation
5859 * ==========================================================================
5863 * Add a device to a storage pool.
5866 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
5870 vdev_t *rvd = spa->spa_root_vdev;
5872 nvlist_t **spares, **l2cache;
5873 uint_t nspares, nl2cache;
5875 ASSERT(spa_writeable(spa));
5877 txg = spa_vdev_enter(spa);
5879 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
5880 VDEV_ALLOC_ADD)) != 0)
5881 return (spa_vdev_exit(spa, NULL, txg, error));
5883 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
5885 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
5889 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
5893 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
5894 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5896 if (vd->vdev_children != 0 &&
5897 (error = vdev_create(vd, txg, B_FALSE)) != 0)
5898 return (spa_vdev_exit(spa, vd, txg, error));
5901 * We must validate the spares and l2cache devices after checking the
5902 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
5904 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
5905 return (spa_vdev_exit(spa, vd, txg, error));
5908 * If we are in the middle of a device removal, we can only add
5909 * devices which match the existing devices in the pool.
5910 * If we are in the middle of a removal, or have some indirect
5911 * vdevs, we can not add raidz toplevels.
5913 if (spa->spa_vdev_removal != NULL ||
5914 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
5915 for (int c = 0; c < vd->vdev_children; c++) {
5916 tvd = vd->vdev_child[c];
5917 if (spa->spa_vdev_removal != NULL &&
5918 tvd->vdev_ashift != spa->spa_max_ashift) {
5919 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5921 /* Fail if top level vdev is raidz */
5922 if (tvd->vdev_ops == &vdev_raidz_ops) {
5923 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5926 * Need the top level mirror to be
5927 * a mirror of leaf vdevs only
5929 if (tvd->vdev_ops == &vdev_mirror_ops) {
5930 for (uint64_t cid = 0;
5931 cid < tvd->vdev_children; cid++) {
5932 vdev_t *cvd = tvd->vdev_child[cid];
5933 if (!cvd->vdev_ops->vdev_op_leaf) {
5934 return (spa_vdev_exit(spa, vd,
5942 for (int c = 0; c < vd->vdev_children; c++) {
5945 * Set the vdev id to the first hole, if one exists.
5947 for (id = 0; id < rvd->vdev_children; id++) {
5948 if (rvd->vdev_child[id]->vdev_ishole) {
5949 vdev_free(rvd->vdev_child[id]);
5953 tvd = vd->vdev_child[c];
5954 vdev_remove_child(vd, tvd);
5956 vdev_add_child(rvd, tvd);
5957 vdev_config_dirty(tvd);
5961 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
5962 ZPOOL_CONFIG_SPARES);
5963 spa_load_spares(spa);
5964 spa->spa_spares.sav_sync = B_TRUE;
5967 if (nl2cache != 0) {
5968 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
5969 ZPOOL_CONFIG_L2CACHE);
5970 spa_load_l2cache(spa);
5971 spa->spa_l2cache.sav_sync = B_TRUE;
5975 * We have to be careful when adding new vdevs to an existing pool.
5976 * If other threads start allocating from these vdevs before we
5977 * sync the config cache, and we lose power, then upon reboot we may
5978 * fail to open the pool because there are DVAs that the config cache
5979 * can't translate. Therefore, we first add the vdevs without
5980 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
5981 * and then let spa_config_update() initialize the new metaslabs.
5983 * spa_load() checks for added-but-not-initialized vdevs, so that
5984 * if we lose power at any point in this sequence, the remaining
5985 * steps will be completed the next time we load the pool.
5987 (void) spa_vdev_exit(spa, vd, txg, 0);
5989 mutex_enter(&spa_namespace_lock);
5990 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5991 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
5992 mutex_exit(&spa_namespace_lock);
5998 * Attach a device to a mirror. The arguments are the path to any device
5999 * in the mirror, and the nvroot for the new device. If the path specifies
6000 * a device that is not mirrored, we automatically insert the mirror vdev.
6002 * If 'replacing' is specified, the new device is intended to replace the
6003 * existing device; in this case the two devices are made into their own
6004 * mirror using the 'replacing' vdev, which is functionally identical to
6005 * the mirror vdev (it actually reuses all the same ops) but has a few
6006 * extra rules: you can't attach to it after it's been created, and upon
6007 * completion of resilvering, the first disk (the one being replaced)
6008 * is automatically detached.
6011 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
6013 uint64_t txg, dtl_max_txg;
6014 vdev_t *rvd = spa->spa_root_vdev;
6015 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
6017 char *oldvdpath, *newvdpath;
6021 ASSERT(spa_writeable(spa));
6023 txg = spa_vdev_enter(spa);
6025 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
6027 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6028 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6029 error = (spa_has_checkpoint(spa)) ?
6030 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6031 return (spa_vdev_exit(spa, NULL, txg, error));
6034 if (spa->spa_vdev_removal != NULL)
6035 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6038 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6040 if (!oldvd->vdev_ops->vdev_op_leaf)
6041 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6043 pvd = oldvd->vdev_parent;
6045 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
6046 VDEV_ALLOC_ATTACH)) != 0)
6047 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6049 if (newrootvd->vdev_children != 1)
6050 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6052 newvd = newrootvd->vdev_child[0];
6054 if (!newvd->vdev_ops->vdev_op_leaf)
6055 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6057 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
6058 return (spa_vdev_exit(spa, newrootvd, txg, error));
6061 * Spares can't replace logs
6063 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
6064 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6068 * For attach, the only allowable parent is a mirror or the root
6071 if (pvd->vdev_ops != &vdev_mirror_ops &&
6072 pvd->vdev_ops != &vdev_root_ops)
6073 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6075 pvops = &vdev_mirror_ops;
6078 * Active hot spares can only be replaced by inactive hot
6081 if (pvd->vdev_ops == &vdev_spare_ops &&
6082 oldvd->vdev_isspare &&
6083 !spa_has_spare(spa, newvd->vdev_guid))
6084 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6087 * If the source is a hot spare, and the parent isn't already a
6088 * spare, then we want to create a new hot spare. Otherwise, we
6089 * want to create a replacing vdev. The user is not allowed to
6090 * attach to a spared vdev child unless the 'isspare' state is
6091 * the same (spare replaces spare, non-spare replaces
6094 if (pvd->vdev_ops == &vdev_replacing_ops &&
6095 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6096 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6097 } else if (pvd->vdev_ops == &vdev_spare_ops &&
6098 newvd->vdev_isspare != oldvd->vdev_isspare) {
6099 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6102 if (newvd->vdev_isspare)
6103 pvops = &vdev_spare_ops;
6105 pvops = &vdev_replacing_ops;
6109 * Make sure the new device is big enough.
6111 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6112 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6115 * The new device cannot have a higher alignment requirement
6116 * than the top-level vdev.
6118 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6119 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6122 * If this is an in-place replacement, update oldvd's path and devid
6123 * to make it distinguishable from newvd, and unopenable from now on.
6125 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6126 spa_strfree(oldvd->vdev_path);
6127 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6129 (void) sprintf(oldvd->vdev_path, "%s/%s",
6130 newvd->vdev_path, "old");
6131 if (oldvd->vdev_devid != NULL) {
6132 spa_strfree(oldvd->vdev_devid);
6133 oldvd->vdev_devid = NULL;
6137 /* mark the device being resilvered */
6138 newvd->vdev_resilver_txg = txg;
6141 * If the parent is not a mirror, or if we're replacing, insert the new
6142 * mirror/replacing/spare vdev above oldvd.
6144 if (pvd->vdev_ops != pvops)
6145 pvd = vdev_add_parent(oldvd, pvops);
6147 ASSERT(pvd->vdev_top->vdev_parent == rvd);
6148 ASSERT(pvd->vdev_ops == pvops);
6149 ASSERT(oldvd->vdev_parent == pvd);
6152 * Extract the new device from its root and add it to pvd.
6154 vdev_remove_child(newrootvd, newvd);
6155 newvd->vdev_id = pvd->vdev_children;
6156 newvd->vdev_crtxg = oldvd->vdev_crtxg;
6157 vdev_add_child(pvd, newvd);
6159 tvd = newvd->vdev_top;
6160 ASSERT(pvd->vdev_top == tvd);
6161 ASSERT(tvd->vdev_parent == rvd);
6163 vdev_config_dirty(tvd);
6166 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6167 * for any dmu_sync-ed blocks. It will propagate upward when
6168 * spa_vdev_exit() calls vdev_dtl_reassess().
6170 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6172 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6173 dtl_max_txg - TXG_INITIAL);
6175 if (newvd->vdev_isspare) {
6176 spa_spare_activate(newvd);
6177 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6180 oldvdpath = spa_strdup(oldvd->vdev_path);
6181 newvdpath = spa_strdup(newvd->vdev_path);
6182 newvd_isspare = newvd->vdev_isspare;
6185 * Mark newvd's DTL dirty in this txg.
6187 vdev_dirty(tvd, VDD_DTL, newvd, txg);
6190 * Schedule the resilver to restart in the future. We do this to
6191 * ensure that dmu_sync-ed blocks have been stitched into the
6192 * respective datasets.
6194 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
6196 if (spa->spa_bootfs)
6197 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6199 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6204 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6206 spa_history_log_internal(spa, "vdev attach", NULL,
6207 "%s vdev=%s %s vdev=%s",
6208 replacing && newvd_isspare ? "spare in" :
6209 replacing ? "replace" : "attach", newvdpath,
6210 replacing ? "for" : "to", oldvdpath);
6212 spa_strfree(oldvdpath);
6213 spa_strfree(newvdpath);
6219 * Detach a device from a mirror or replacing vdev.
6221 * If 'replace_done' is specified, only detach if the parent
6222 * is a replacing vdev.
6225 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6229 vdev_t *rvd = spa->spa_root_vdev;
6230 vdev_t *vd, *pvd, *cvd, *tvd;
6231 boolean_t unspare = B_FALSE;
6232 uint64_t unspare_guid = 0;
6235 ASSERT(spa_writeable(spa));
6237 txg = spa_vdev_enter(spa);
6239 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6242 * Besides being called directly from the userland through the
6243 * ioctl interface, spa_vdev_detach() can be potentially called
6244 * at the end of spa_vdev_resilver_done().
6246 * In the regular case, when we have a checkpoint this shouldn't
6247 * happen as we never empty the DTLs of a vdev during the scrub
6248 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6249 * should never get here when we have a checkpoint.
6251 * That said, even in a case when we checkpoint the pool exactly
6252 * as spa_vdev_resilver_done() calls this function everything
6253 * should be fine as the resilver will return right away.
6255 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6256 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6257 error = (spa_has_checkpoint(spa)) ?
6258 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6259 return (spa_vdev_exit(spa, NULL, txg, error));
6263 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6265 if (!vd->vdev_ops->vdev_op_leaf)
6266 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6268 pvd = vd->vdev_parent;
6271 * If the parent/child relationship is not as expected, don't do it.
6272 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6273 * vdev that's replacing B with C. The user's intent in replacing
6274 * is to go from M(A,B) to M(A,C). If the user decides to cancel
6275 * the replace by detaching C, the expected behavior is to end up
6276 * M(A,B). But suppose that right after deciding to detach C,
6277 * the replacement of B completes. We would have M(A,C), and then
6278 * ask to detach C, which would leave us with just A -- not what
6279 * the user wanted. To prevent this, we make sure that the
6280 * parent/child relationship hasn't changed -- in this example,
6281 * that C's parent is still the replacing vdev R.
6283 if (pvd->vdev_guid != pguid && pguid != 0)
6284 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6287 * Only 'replacing' or 'spare' vdevs can be replaced.
6289 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6290 pvd->vdev_ops != &vdev_spare_ops)
6291 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6293 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6294 spa_version(spa) >= SPA_VERSION_SPARES);
6297 * Only mirror, replacing, and spare vdevs support detach.
6299 if (pvd->vdev_ops != &vdev_replacing_ops &&
6300 pvd->vdev_ops != &vdev_mirror_ops &&
6301 pvd->vdev_ops != &vdev_spare_ops)
6302 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6305 * If this device has the only valid copy of some data,
6306 * we cannot safely detach it.
6308 if (vdev_dtl_required(vd))
6309 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6311 ASSERT(pvd->vdev_children >= 2);
6314 * If we are detaching the second disk from a replacing vdev, then
6315 * check to see if we changed the original vdev's path to have "/old"
6316 * at the end in spa_vdev_attach(). If so, undo that change now.
6318 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
6319 vd->vdev_path != NULL) {
6320 size_t len = strlen(vd->vdev_path);
6322 for (int c = 0; c < pvd->vdev_children; c++) {
6323 cvd = pvd->vdev_child[c];
6325 if (cvd == vd || cvd->vdev_path == NULL)
6328 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
6329 strcmp(cvd->vdev_path + len, "/old") == 0) {
6330 spa_strfree(cvd->vdev_path);
6331 cvd->vdev_path = spa_strdup(vd->vdev_path);
6338 * If we are detaching the original disk from a spare, then it implies
6339 * that the spare should become a real disk, and be removed from the
6340 * active spare list for the pool.
6342 if (pvd->vdev_ops == &vdev_spare_ops &&
6344 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
6348 * Erase the disk labels so the disk can be used for other things.
6349 * This must be done after all other error cases are handled,
6350 * but before we disembowel vd (so we can still do I/O to it).
6351 * But if we can't do it, don't treat the error as fatal --
6352 * it may be that the unwritability of the disk is the reason
6353 * it's being detached!
6355 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
6358 * Remove vd from its parent and compact the parent's children.
6360 vdev_remove_child(pvd, vd);
6361 vdev_compact_children(pvd);
6364 * Remember one of the remaining children so we can get tvd below.
6366 cvd = pvd->vdev_child[pvd->vdev_children - 1];
6369 * If we need to remove the remaining child from the list of hot spares,
6370 * do it now, marking the vdev as no longer a spare in the process.
6371 * We must do this before vdev_remove_parent(), because that can
6372 * change the GUID if it creates a new toplevel GUID. For a similar
6373 * reason, we must remove the spare now, in the same txg as the detach;
6374 * otherwise someone could attach a new sibling, change the GUID, and
6375 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
6378 ASSERT(cvd->vdev_isspare);
6379 spa_spare_remove(cvd);
6380 unspare_guid = cvd->vdev_guid;
6381 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
6382 cvd->vdev_unspare = B_TRUE;
6386 * If the parent mirror/replacing vdev only has one child,
6387 * the parent is no longer needed. Remove it from the tree.
6389 if (pvd->vdev_children == 1) {
6390 if (pvd->vdev_ops == &vdev_spare_ops)
6391 cvd->vdev_unspare = B_FALSE;
6392 vdev_remove_parent(cvd);
6397 * We don't set tvd until now because the parent we just removed
6398 * may have been the previous top-level vdev.
6400 tvd = cvd->vdev_top;
6401 ASSERT(tvd->vdev_parent == rvd);
6404 * Reevaluate the parent vdev state.
6406 vdev_propagate_state(cvd);
6409 * If the 'autoexpand' property is set on the pool then automatically
6410 * try to expand the size of the pool. For example if the device we
6411 * just detached was smaller than the others, it may be possible to
6412 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
6413 * first so that we can obtain the updated sizes of the leaf vdevs.
6415 if (spa->spa_autoexpand) {
6417 vdev_expand(tvd, txg);
6420 vdev_config_dirty(tvd);
6423 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
6424 * vd->vdev_detached is set and free vd's DTL object in syncing context.
6425 * But first make sure we're not on any *other* txg's DTL list, to
6426 * prevent vd from being accessed after it's freed.
6428 vdpath = spa_strdup(vd->vdev_path);
6429 for (int t = 0; t < TXG_SIZE; t++)
6430 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
6431 vd->vdev_detached = B_TRUE;
6432 vdev_dirty(tvd, VDD_DTL, vd, txg);
6434 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
6436 /* hang on to the spa before we release the lock */
6437 spa_open_ref(spa, FTAG);
6439 error = spa_vdev_exit(spa, vd, txg, 0);
6441 spa_history_log_internal(spa, "detach", NULL,
6443 spa_strfree(vdpath);
6446 * If this was the removal of the original device in a hot spare vdev,
6447 * then we want to go through and remove the device from the hot spare
6448 * list of every other pool.
6451 spa_t *altspa = NULL;
6453 mutex_enter(&spa_namespace_lock);
6454 while ((altspa = spa_next(altspa)) != NULL) {
6455 if (altspa->spa_state != POOL_STATE_ACTIVE ||
6459 spa_open_ref(altspa, FTAG);
6460 mutex_exit(&spa_namespace_lock);
6461 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
6462 mutex_enter(&spa_namespace_lock);
6463 spa_close(altspa, FTAG);
6465 mutex_exit(&spa_namespace_lock);
6467 /* search the rest of the vdevs for spares to remove */
6468 spa_vdev_resilver_done(spa);
6471 /* all done with the spa; OK to release */
6472 mutex_enter(&spa_namespace_lock);
6473 spa_close(spa, FTAG);
6474 mutex_exit(&spa_namespace_lock);
6480 spa_vdev_initialize(spa_t *spa, uint64_t guid, uint64_t cmd_type)
6483 * We hold the namespace lock through the whole function
6484 * to prevent any changes to the pool while we're starting or
6485 * stopping initialization. The config and state locks are held so that
6486 * we can properly assess the vdev state before we commit to
6487 * the initializing operation.
6489 mutex_enter(&spa_namespace_lock);
6490 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6492 /* Look up vdev and ensure it's a leaf. */
6493 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6494 if (vd == NULL || vd->vdev_detached) {
6495 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6496 mutex_exit(&spa_namespace_lock);
6497 return (SET_ERROR(ENODEV));
6498 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6499 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6500 mutex_exit(&spa_namespace_lock);
6501 return (SET_ERROR(EINVAL));
6502 } else if (!vdev_writeable(vd)) {
6503 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6504 mutex_exit(&spa_namespace_lock);
6505 return (SET_ERROR(EROFS));
6507 mutex_enter(&vd->vdev_initialize_lock);
6508 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6511 * When we activate an initialize action we check to see
6512 * if the vdev_initialize_thread is NULL. We do this instead
6513 * of using the vdev_initialize_state since there might be
6514 * a previous initialization process which has completed but
6515 * the thread is not exited.
6517 if (cmd_type == POOL_INITIALIZE_DO &&
6518 (vd->vdev_initialize_thread != NULL ||
6519 vd->vdev_top->vdev_removing)) {
6520 mutex_exit(&vd->vdev_initialize_lock);
6521 mutex_exit(&spa_namespace_lock);
6522 return (SET_ERROR(EBUSY));
6523 } else if (cmd_type == POOL_INITIALIZE_CANCEL &&
6524 (vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE &&
6525 vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED)) {
6526 mutex_exit(&vd->vdev_initialize_lock);
6527 mutex_exit(&spa_namespace_lock);
6528 return (SET_ERROR(ESRCH));
6529 } else if (cmd_type == POOL_INITIALIZE_SUSPEND &&
6530 vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE) {
6531 mutex_exit(&vd->vdev_initialize_lock);
6532 mutex_exit(&spa_namespace_lock);
6533 return (SET_ERROR(ESRCH));
6537 case POOL_INITIALIZE_DO:
6538 vdev_initialize(vd);
6540 case POOL_INITIALIZE_CANCEL:
6541 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED);
6543 case POOL_INITIALIZE_SUSPEND:
6544 vdev_initialize_stop(vd, VDEV_INITIALIZE_SUSPENDED);
6547 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6549 mutex_exit(&vd->vdev_initialize_lock);
6551 /* Sync out the initializing state */
6552 txg_wait_synced(spa->spa_dsl_pool, 0);
6553 mutex_exit(&spa_namespace_lock);
6560 * Split a set of devices from their mirrors, and create a new pool from them.
6563 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6564 nvlist_t *props, boolean_t exp)
6567 uint64_t txg, *glist;
6569 uint_t c, children, lastlog;
6570 nvlist_t **child, *nvl, *tmp;
6572 char *altroot = NULL;
6573 vdev_t *rvd, **vml = NULL; /* vdev modify list */
6574 boolean_t activate_slog;
6576 ASSERT(spa_writeable(spa));
6578 txg = spa_vdev_enter(spa);
6580 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6581 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6582 error = (spa_has_checkpoint(spa)) ?
6583 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6584 return (spa_vdev_exit(spa, NULL, txg, error));
6587 /* clear the log and flush everything up to now */
6588 activate_slog = spa_passivate_log(spa);
6589 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6590 error = spa_reset_logs(spa);
6591 txg = spa_vdev_config_enter(spa);
6594 spa_activate_log(spa);
6597 return (spa_vdev_exit(spa, NULL, txg, error));
6599 /* check new spa name before going any further */
6600 if (spa_lookup(newname) != NULL)
6601 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
6604 * scan through all the children to ensure they're all mirrors
6606 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
6607 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
6609 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6611 /* first, check to ensure we've got the right child count */
6612 rvd = spa->spa_root_vdev;
6614 for (c = 0; c < rvd->vdev_children; c++) {
6615 vdev_t *vd = rvd->vdev_child[c];
6617 /* don't count the holes & logs as children */
6618 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
6626 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
6627 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6629 /* next, ensure no spare or cache devices are part of the split */
6630 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
6631 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
6632 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6634 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
6635 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
6637 /* then, loop over each vdev and validate it */
6638 for (c = 0; c < children; c++) {
6639 uint64_t is_hole = 0;
6641 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
6645 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
6646 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
6649 error = SET_ERROR(EINVAL);
6654 /* which disk is going to be split? */
6655 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
6657 error = SET_ERROR(EINVAL);
6661 /* look it up in the spa */
6662 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
6663 if (vml[c] == NULL) {
6664 error = SET_ERROR(ENODEV);
6668 /* make sure there's nothing stopping the split */
6669 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
6670 vml[c]->vdev_islog ||
6671 !vdev_is_concrete(vml[c]) ||
6672 vml[c]->vdev_isspare ||
6673 vml[c]->vdev_isl2cache ||
6674 !vdev_writeable(vml[c]) ||
6675 vml[c]->vdev_children != 0 ||
6676 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
6677 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
6678 error = SET_ERROR(EINVAL);
6682 if (vdev_dtl_required(vml[c])) {
6683 error = SET_ERROR(EBUSY);
6687 /* we need certain info from the top level */
6688 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
6689 vml[c]->vdev_top->vdev_ms_array) == 0);
6690 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
6691 vml[c]->vdev_top->vdev_ms_shift) == 0);
6692 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
6693 vml[c]->vdev_top->vdev_asize) == 0);
6694 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
6695 vml[c]->vdev_top->vdev_ashift) == 0);
6697 /* transfer per-vdev ZAPs */
6698 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
6699 VERIFY0(nvlist_add_uint64(child[c],
6700 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
6702 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
6703 VERIFY0(nvlist_add_uint64(child[c],
6704 ZPOOL_CONFIG_VDEV_TOP_ZAP,
6705 vml[c]->vdev_parent->vdev_top_zap));
6709 kmem_free(vml, children * sizeof (vdev_t *));
6710 kmem_free(glist, children * sizeof (uint64_t));
6711 return (spa_vdev_exit(spa, NULL, txg, error));
6714 /* stop writers from using the disks */
6715 for (c = 0; c < children; c++) {
6717 vml[c]->vdev_offline = B_TRUE;
6719 vdev_reopen(spa->spa_root_vdev);
6722 * Temporarily record the splitting vdevs in the spa config. This
6723 * will disappear once the config is regenerated.
6725 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6726 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
6727 glist, children) == 0);
6728 kmem_free(glist, children * sizeof (uint64_t));
6730 mutex_enter(&spa->spa_props_lock);
6731 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
6733 mutex_exit(&spa->spa_props_lock);
6734 spa->spa_config_splitting = nvl;
6735 vdev_config_dirty(spa->spa_root_vdev);
6737 /* configure and create the new pool */
6738 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
6739 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6740 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
6741 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6742 spa_version(spa)) == 0);
6743 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
6744 spa->spa_config_txg) == 0);
6745 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
6746 spa_generate_guid(NULL)) == 0);
6747 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
6748 (void) nvlist_lookup_string(props,
6749 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
6751 /* add the new pool to the namespace */
6752 newspa = spa_add(newname, config, altroot);
6753 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
6754 newspa->spa_config_txg = spa->spa_config_txg;
6755 spa_set_log_state(newspa, SPA_LOG_CLEAR);
6757 /* release the spa config lock, retaining the namespace lock */
6758 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6760 if (zio_injection_enabled)
6761 zio_handle_panic_injection(spa, FTAG, 1);
6763 spa_activate(newspa, spa_mode_global);
6764 spa_async_suspend(newspa);
6766 for (c = 0; c < children; c++) {
6767 if (vml[c] != NULL) {
6769 * Temporarily stop the initializing activity. We set
6770 * the state to ACTIVE so that we know to resume
6771 * the initializing once the split has completed.
6773 mutex_enter(&vml[c]->vdev_initialize_lock);
6774 vdev_initialize_stop(vml[c], VDEV_INITIALIZE_ACTIVE);
6775 mutex_exit(&vml[c]->vdev_initialize_lock);
6780 /* mark that we are creating new spa by splitting */
6781 newspa->spa_splitting_newspa = B_TRUE;
6783 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
6785 /* create the new pool from the disks of the original pool */
6786 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
6788 newspa->spa_splitting_newspa = B_FALSE;
6793 /* if that worked, generate a real config for the new pool */
6794 if (newspa->spa_root_vdev != NULL) {
6795 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
6796 NV_UNIQUE_NAME, KM_SLEEP) == 0);
6797 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
6798 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
6799 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
6804 if (props != NULL) {
6805 spa_configfile_set(newspa, props, B_FALSE);
6806 error = spa_prop_set(newspa, props);
6811 /* flush everything */
6812 txg = spa_vdev_config_enter(newspa);
6813 vdev_config_dirty(newspa->spa_root_vdev);
6814 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
6816 if (zio_injection_enabled)
6817 zio_handle_panic_injection(spa, FTAG, 2);
6819 spa_async_resume(newspa);
6821 /* finally, update the original pool's config */
6822 txg = spa_vdev_config_enter(spa);
6823 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
6824 error = dmu_tx_assign(tx, TXG_WAIT);
6827 for (c = 0; c < children; c++) {
6828 if (vml[c] != NULL) {
6831 spa_history_log_internal(spa, "detach", tx,
6832 "vdev=%s", vml[c]->vdev_path);
6837 spa->spa_avz_action = AVZ_ACTION_REBUILD;
6838 vdev_config_dirty(spa->spa_root_vdev);
6839 spa->spa_config_splitting = NULL;
6843 (void) spa_vdev_exit(spa, NULL, txg, 0);
6845 if (zio_injection_enabled)
6846 zio_handle_panic_injection(spa, FTAG, 3);
6848 /* split is complete; log a history record */
6849 spa_history_log_internal(newspa, "split", NULL,
6850 "from pool %s", spa_name(spa));
6852 kmem_free(vml, children * sizeof (vdev_t *));
6854 /* if we're not going to mount the filesystems in userland, export */
6856 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
6863 spa_deactivate(newspa);
6866 txg = spa_vdev_config_enter(spa);
6868 /* re-online all offlined disks */
6869 for (c = 0; c < children; c++) {
6871 vml[c]->vdev_offline = B_FALSE;
6874 /* restart initializing disks as necessary */
6875 spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
6877 vdev_reopen(spa->spa_root_vdev);
6879 nvlist_free(spa->spa_config_splitting);
6880 spa->spa_config_splitting = NULL;
6881 (void) spa_vdev_exit(spa, NULL, txg, error);
6883 kmem_free(vml, children * sizeof (vdev_t *));
6888 * Find any device that's done replacing, or a vdev marked 'unspare' that's
6889 * currently spared, so we can detach it.
6892 spa_vdev_resilver_done_hunt(vdev_t *vd)
6894 vdev_t *newvd, *oldvd;
6896 for (int c = 0; c < vd->vdev_children; c++) {
6897 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
6903 * Check for a completed replacement. We always consider the first
6904 * vdev in the list to be the oldest vdev, and the last one to be
6905 * the newest (see spa_vdev_attach() for how that works). In
6906 * the case where the newest vdev is faulted, we will not automatically
6907 * remove it after a resilver completes. This is OK as it will require
6908 * user intervention to determine which disk the admin wishes to keep.
6910 if (vd->vdev_ops == &vdev_replacing_ops) {
6911 ASSERT(vd->vdev_children > 1);
6913 newvd = vd->vdev_child[vd->vdev_children - 1];
6914 oldvd = vd->vdev_child[0];
6916 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
6917 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6918 !vdev_dtl_required(oldvd))
6923 * Check for a completed resilver with the 'unspare' flag set.
6924 * Also potentially update faulted state.
6926 if (vd->vdev_ops == &vdev_spare_ops) {
6927 vdev_t *first = vd->vdev_child[0];
6928 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
6930 if (last->vdev_unspare) {
6933 } else if (first->vdev_unspare) {
6940 if (oldvd != NULL &&
6941 vdev_dtl_empty(newvd, DTL_MISSING) &&
6942 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6943 !vdev_dtl_required(oldvd))
6946 vdev_propagate_state(vd);
6949 * If there are more than two spares attached to a disk,
6950 * and those spares are not required, then we want to
6951 * attempt to free them up now so that they can be used
6952 * by other pools. Once we're back down to a single
6953 * disk+spare, we stop removing them.
6955 if (vd->vdev_children > 2) {
6956 newvd = vd->vdev_child[1];
6958 if (newvd->vdev_isspare && last->vdev_isspare &&
6959 vdev_dtl_empty(last, DTL_MISSING) &&
6960 vdev_dtl_empty(last, DTL_OUTAGE) &&
6961 !vdev_dtl_required(newvd))
6970 spa_vdev_resilver_done(spa_t *spa)
6972 vdev_t *vd, *pvd, *ppvd;
6973 uint64_t guid, sguid, pguid, ppguid;
6975 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6977 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
6978 pvd = vd->vdev_parent;
6979 ppvd = pvd->vdev_parent;
6980 guid = vd->vdev_guid;
6981 pguid = pvd->vdev_guid;
6982 ppguid = ppvd->vdev_guid;
6985 * If we have just finished replacing a hot spared device, then
6986 * we need to detach the parent's first child (the original hot
6989 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
6990 ppvd->vdev_children == 2) {
6991 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
6992 sguid = ppvd->vdev_child[1]->vdev_guid;
6994 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
6996 spa_config_exit(spa, SCL_ALL, FTAG);
6997 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
6999 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
7001 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7004 spa_config_exit(spa, SCL_ALL, FTAG);
7008 * Update the stored path or FRU for this vdev.
7011 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
7015 boolean_t sync = B_FALSE;
7017 ASSERT(spa_writeable(spa));
7019 spa_vdev_state_enter(spa, SCL_ALL);
7021 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
7022 return (spa_vdev_state_exit(spa, NULL, ENOENT));
7024 if (!vd->vdev_ops->vdev_op_leaf)
7025 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
7028 if (strcmp(value, vd->vdev_path) != 0) {
7029 spa_strfree(vd->vdev_path);
7030 vd->vdev_path = spa_strdup(value);
7034 if (vd->vdev_fru == NULL) {
7035 vd->vdev_fru = spa_strdup(value);
7037 } else if (strcmp(value, vd->vdev_fru) != 0) {
7038 spa_strfree(vd->vdev_fru);
7039 vd->vdev_fru = spa_strdup(value);
7044 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
7048 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
7050 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
7054 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
7056 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
7060 * ==========================================================================
7062 * ==========================================================================
7065 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
7067 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7069 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7070 return (SET_ERROR(EBUSY));
7072 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
7076 spa_scan_stop(spa_t *spa)
7078 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7079 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7080 return (SET_ERROR(EBUSY));
7081 return (dsl_scan_cancel(spa->spa_dsl_pool));
7085 spa_scan(spa_t *spa, pool_scan_func_t func)
7087 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7089 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
7090 return (SET_ERROR(ENOTSUP));
7093 * If a resilver was requested, but there is no DTL on a
7094 * writeable leaf device, we have nothing to do.
7096 if (func == POOL_SCAN_RESILVER &&
7097 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
7098 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
7102 return (dsl_scan(spa->spa_dsl_pool, func));
7106 * ==========================================================================
7107 * SPA async task processing
7108 * ==========================================================================
7112 spa_async_remove(spa_t *spa, vdev_t *vd)
7114 if (vd->vdev_remove_wanted) {
7115 vd->vdev_remove_wanted = B_FALSE;
7116 vd->vdev_delayed_close = B_FALSE;
7117 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
7120 * We want to clear the stats, but we don't want to do a full
7121 * vdev_clear() as that will cause us to throw away
7122 * degraded/faulted state as well as attempt to reopen the
7123 * device, all of which is a waste.
7125 vd->vdev_stat.vs_read_errors = 0;
7126 vd->vdev_stat.vs_write_errors = 0;
7127 vd->vdev_stat.vs_checksum_errors = 0;
7129 vdev_state_dirty(vd->vdev_top);
7130 /* Tell userspace that the vdev is gone. */
7131 zfs_post_remove(spa, vd);
7134 for (int c = 0; c < vd->vdev_children; c++)
7135 spa_async_remove(spa, vd->vdev_child[c]);
7139 spa_async_probe(spa_t *spa, vdev_t *vd)
7141 if (vd->vdev_probe_wanted) {
7142 vd->vdev_probe_wanted = B_FALSE;
7143 vdev_reopen(vd); /* vdev_open() does the actual probe */
7146 for (int c = 0; c < vd->vdev_children; c++)
7147 spa_async_probe(spa, vd->vdev_child[c]);
7151 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
7157 if (!spa->spa_autoexpand)
7160 for (int c = 0; c < vd->vdev_children; c++) {
7161 vdev_t *cvd = vd->vdev_child[c];
7162 spa_async_autoexpand(spa, cvd);
7165 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
7168 physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
7169 (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
7171 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7172 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
7174 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
7175 ESC_ZFS_VDEV_AUTOEXPAND, attr, &eid, DDI_SLEEP);
7178 kmem_free(physpath, MAXPATHLEN);
7182 spa_async_thread(void *arg)
7184 spa_t *spa = (spa_t *)arg;
7187 ASSERT(spa->spa_sync_on);
7189 mutex_enter(&spa->spa_async_lock);
7190 tasks = spa->spa_async_tasks;
7191 spa->spa_async_tasks &= SPA_ASYNC_REMOVE;
7192 mutex_exit(&spa->spa_async_lock);
7195 * See if the config needs to be updated.
7197 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
7198 uint64_t old_space, new_space;
7200 mutex_enter(&spa_namespace_lock);
7201 old_space = metaslab_class_get_space(spa_normal_class(spa));
7202 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
7203 new_space = metaslab_class_get_space(spa_normal_class(spa));
7204 mutex_exit(&spa_namespace_lock);
7207 * If the pool grew as a result of the config update,
7208 * then log an internal history event.
7210 if (new_space != old_space) {
7211 spa_history_log_internal(spa, "vdev online", NULL,
7212 "pool '%s' size: %llu(+%llu)",
7213 spa_name(spa), new_space, new_space - old_space);
7217 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
7218 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7219 spa_async_autoexpand(spa, spa->spa_root_vdev);
7220 spa_config_exit(spa, SCL_CONFIG, FTAG);
7224 * See if any devices need to be probed.
7226 if (tasks & SPA_ASYNC_PROBE) {
7227 spa_vdev_state_enter(spa, SCL_NONE);
7228 spa_async_probe(spa, spa->spa_root_vdev);
7229 (void) spa_vdev_state_exit(spa, NULL, 0);
7233 * If any devices are done replacing, detach them.
7235 if (tasks & SPA_ASYNC_RESILVER_DONE)
7236 spa_vdev_resilver_done(spa);
7239 * Kick off a resilver.
7241 if (tasks & SPA_ASYNC_RESILVER)
7242 dsl_resilver_restart(spa->spa_dsl_pool, 0);
7244 if (tasks & SPA_ASYNC_INITIALIZE_RESTART) {
7245 mutex_enter(&spa_namespace_lock);
7246 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7247 vdev_initialize_restart(spa->spa_root_vdev);
7248 spa_config_exit(spa, SCL_CONFIG, FTAG);
7249 mutex_exit(&spa_namespace_lock);
7253 * Let the world know that we're done.
7255 mutex_enter(&spa->spa_async_lock);
7256 spa->spa_async_thread = NULL;
7257 cv_broadcast(&spa->spa_async_cv);
7258 mutex_exit(&spa->spa_async_lock);
7263 spa_async_thread_vd(void *arg)
7268 mutex_enter(&spa->spa_async_lock);
7269 tasks = spa->spa_async_tasks;
7271 spa->spa_async_tasks &= ~SPA_ASYNC_REMOVE;
7272 mutex_exit(&spa->spa_async_lock);
7275 * See if any devices need to be marked REMOVED.
7277 if (tasks & SPA_ASYNC_REMOVE) {
7278 spa_vdev_state_enter(spa, SCL_NONE);
7279 spa_async_remove(spa, spa->spa_root_vdev);
7280 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
7281 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
7282 for (int i = 0; i < spa->spa_spares.sav_count; i++)
7283 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
7284 (void) spa_vdev_state_exit(spa, NULL, 0);
7288 * Let the world know that we're done.
7290 mutex_enter(&spa->spa_async_lock);
7291 tasks = spa->spa_async_tasks;
7292 if ((tasks & SPA_ASYNC_REMOVE) != 0)
7294 spa->spa_async_thread_vd = NULL;
7295 cv_broadcast(&spa->spa_async_cv);
7296 mutex_exit(&spa->spa_async_lock);
7301 spa_async_suspend(spa_t *spa)
7303 mutex_enter(&spa->spa_async_lock);
7304 spa->spa_async_suspended++;
7305 while (spa->spa_async_thread != NULL ||
7306 spa->spa_async_thread_vd != NULL)
7307 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
7308 mutex_exit(&spa->spa_async_lock);
7310 spa_vdev_remove_suspend(spa);
7312 zthr_t *condense_thread = spa->spa_condense_zthr;
7313 if (condense_thread != NULL && zthr_isrunning(condense_thread))
7314 VERIFY0(zthr_cancel(condense_thread));
7316 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7317 if (discard_thread != NULL && zthr_isrunning(discard_thread))
7318 VERIFY0(zthr_cancel(discard_thread));
7322 spa_async_resume(spa_t *spa)
7324 mutex_enter(&spa->spa_async_lock);
7325 ASSERT(spa->spa_async_suspended != 0);
7326 spa->spa_async_suspended--;
7327 mutex_exit(&spa->spa_async_lock);
7328 spa_restart_removal(spa);
7330 zthr_t *condense_thread = spa->spa_condense_zthr;
7331 if (condense_thread != NULL && !zthr_isrunning(condense_thread))
7332 zthr_resume(condense_thread);
7334 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7335 if (discard_thread != NULL && !zthr_isrunning(discard_thread))
7336 zthr_resume(discard_thread);
7340 spa_async_tasks_pending(spa_t *spa)
7342 uint_t non_config_tasks;
7344 boolean_t config_task_suspended;
7346 non_config_tasks = spa->spa_async_tasks & ~(SPA_ASYNC_CONFIG_UPDATE |
7348 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
7349 if (spa->spa_ccw_fail_time == 0) {
7350 config_task_suspended = B_FALSE;
7352 config_task_suspended =
7353 (gethrtime() - spa->spa_ccw_fail_time) <
7354 (zfs_ccw_retry_interval * NANOSEC);
7357 return (non_config_tasks || (config_task && !config_task_suspended));
7361 spa_async_dispatch(spa_t *spa)
7363 mutex_enter(&spa->spa_async_lock);
7364 if (spa_async_tasks_pending(spa) &&
7365 !spa->spa_async_suspended &&
7366 spa->spa_async_thread == NULL &&
7368 spa->spa_async_thread = thread_create(NULL, 0,
7369 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
7370 mutex_exit(&spa->spa_async_lock);
7374 spa_async_dispatch_vd(spa_t *spa)
7376 mutex_enter(&spa->spa_async_lock);
7377 if ((spa->spa_async_tasks & SPA_ASYNC_REMOVE) != 0 &&
7378 !spa->spa_async_suspended &&
7379 spa->spa_async_thread_vd == NULL &&
7381 spa->spa_async_thread_vd = thread_create(NULL, 0,
7382 spa_async_thread_vd, spa, 0, &p0, TS_RUN, maxclsyspri);
7383 mutex_exit(&spa->spa_async_lock);
7387 spa_async_request(spa_t *spa, int task)
7389 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
7390 mutex_enter(&spa->spa_async_lock);
7391 spa->spa_async_tasks |= task;
7392 mutex_exit(&spa->spa_async_lock);
7393 spa_async_dispatch_vd(spa);
7397 * ==========================================================================
7398 * SPA syncing routines
7399 * ==========================================================================
7403 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7406 bpobj_enqueue(bpo, bp, tx);
7411 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7415 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
7416 BP_GET_PSIZE(bp), zio->io_flags));
7421 * Note: this simple function is not inlined to make it easier to dtrace the
7422 * amount of time spent syncing frees.
7425 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
7427 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7428 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
7429 VERIFY(zio_wait(zio) == 0);
7433 * Note: this simple function is not inlined to make it easier to dtrace the
7434 * amount of time spent syncing deferred frees.
7437 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
7439 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7440 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
7441 spa_free_sync_cb, zio, tx), ==, 0);
7442 VERIFY0(zio_wait(zio));
7447 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
7449 char *packed = NULL;
7454 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
7457 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
7458 * information. This avoids the dmu_buf_will_dirty() path and
7459 * saves us a pre-read to get data we don't actually care about.
7461 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
7462 packed = kmem_alloc(bufsize, KM_SLEEP);
7464 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
7466 bzero(packed + nvsize, bufsize - nvsize);
7468 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
7470 kmem_free(packed, bufsize);
7472 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
7473 dmu_buf_will_dirty(db, tx);
7474 *(uint64_t *)db->db_data = nvsize;
7475 dmu_buf_rele(db, FTAG);
7479 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
7480 const char *config, const char *entry)
7490 * Update the MOS nvlist describing the list of available devices.
7491 * spa_validate_aux() will have already made sure this nvlist is
7492 * valid and the vdevs are labeled appropriately.
7494 if (sav->sav_object == 0) {
7495 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
7496 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
7497 sizeof (uint64_t), tx);
7498 VERIFY(zap_update(spa->spa_meta_objset,
7499 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
7500 &sav->sav_object, tx) == 0);
7503 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7504 if (sav->sav_count == 0) {
7505 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
7507 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
7508 for (i = 0; i < sav->sav_count; i++)
7509 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
7510 B_FALSE, VDEV_CONFIG_L2CACHE);
7511 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
7512 sav->sav_count) == 0);
7513 for (i = 0; i < sav->sav_count; i++)
7514 nvlist_free(list[i]);
7515 kmem_free(list, sav->sav_count * sizeof (void *));
7518 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
7519 nvlist_free(nvroot);
7521 sav->sav_sync = B_FALSE;
7525 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
7526 * The all-vdev ZAP must be empty.
7529 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
7531 spa_t *spa = vd->vdev_spa;
7532 if (vd->vdev_top_zap != 0) {
7533 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7534 vd->vdev_top_zap, tx));
7536 if (vd->vdev_leaf_zap != 0) {
7537 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7538 vd->vdev_leaf_zap, tx));
7540 for (uint64_t i = 0; i < vd->vdev_children; i++) {
7541 spa_avz_build(vd->vdev_child[i], avz, tx);
7546 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
7551 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
7552 * its config may not be dirty but we still need to build per-vdev ZAPs.
7553 * Similarly, if the pool is being assembled (e.g. after a split), we
7554 * need to rebuild the AVZ although the config may not be dirty.
7556 if (list_is_empty(&spa->spa_config_dirty_list) &&
7557 spa->spa_avz_action == AVZ_ACTION_NONE)
7560 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7562 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
7563 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
7564 spa->spa_all_vdev_zaps != 0);
7566 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
7567 /* Make and build the new AVZ */
7568 uint64_t new_avz = zap_create(spa->spa_meta_objset,
7569 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7570 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7572 /* Diff old AVZ with new one */
7576 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7577 spa->spa_all_vdev_zaps);
7578 zap_cursor_retrieve(&zc, &za) == 0;
7579 zap_cursor_advance(&zc)) {
7580 uint64_t vdzap = za.za_first_integer;
7581 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
7584 * ZAP is listed in old AVZ but not in new one;
7587 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
7592 zap_cursor_fini(&zc);
7594 /* Destroy the old AVZ */
7595 VERIFY0(zap_destroy(spa->spa_meta_objset,
7596 spa->spa_all_vdev_zaps, tx));
7598 /* Replace the old AVZ in the dir obj with the new one */
7599 VERIFY0(zap_update(spa->spa_meta_objset,
7600 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
7601 sizeof (new_avz), 1, &new_avz, tx));
7603 spa->spa_all_vdev_zaps = new_avz;
7604 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
7608 /* Walk through the AVZ and destroy all listed ZAPs */
7609 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7610 spa->spa_all_vdev_zaps);
7611 zap_cursor_retrieve(&zc, &za) == 0;
7612 zap_cursor_advance(&zc)) {
7613 uint64_t zap = za.za_first_integer;
7614 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
7617 zap_cursor_fini(&zc);
7619 /* Destroy and unlink the AVZ itself */
7620 VERIFY0(zap_destroy(spa->spa_meta_objset,
7621 spa->spa_all_vdev_zaps, tx));
7622 VERIFY0(zap_remove(spa->spa_meta_objset,
7623 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
7624 spa->spa_all_vdev_zaps = 0;
7627 if (spa->spa_all_vdev_zaps == 0) {
7628 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
7629 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
7630 DMU_POOL_VDEV_ZAP_MAP, tx);
7632 spa->spa_avz_action = AVZ_ACTION_NONE;
7634 /* Create ZAPs for vdevs that don't have them. */
7635 vdev_construct_zaps(spa->spa_root_vdev, tx);
7637 config = spa_config_generate(spa, spa->spa_root_vdev,
7638 dmu_tx_get_txg(tx), B_FALSE);
7641 * If we're upgrading the spa version then make sure that
7642 * the config object gets updated with the correct version.
7644 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
7645 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7646 spa->spa_uberblock.ub_version);
7648 spa_config_exit(spa, SCL_STATE, FTAG);
7650 nvlist_free(spa->spa_config_syncing);
7651 spa->spa_config_syncing = config;
7653 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
7657 spa_sync_version(void *arg, dmu_tx_t *tx)
7659 uint64_t *versionp = arg;
7660 uint64_t version = *versionp;
7661 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7664 * Setting the version is special cased when first creating the pool.
7666 ASSERT(tx->tx_txg != TXG_INITIAL);
7668 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
7669 ASSERT(version >= spa_version(spa));
7671 spa->spa_uberblock.ub_version = version;
7672 vdev_config_dirty(spa->spa_root_vdev);
7673 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
7677 * Set zpool properties.
7680 spa_sync_props(void *arg, dmu_tx_t *tx)
7682 nvlist_t *nvp = arg;
7683 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7684 objset_t *mos = spa->spa_meta_objset;
7685 nvpair_t *elem = NULL;
7687 mutex_enter(&spa->spa_props_lock);
7689 while ((elem = nvlist_next_nvpair(nvp, elem))) {
7691 char *strval, *fname;
7693 const char *propname;
7694 zprop_type_t proptype;
7697 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
7698 case ZPOOL_PROP_INVAL:
7700 * We checked this earlier in spa_prop_validate().
7702 ASSERT(zpool_prop_feature(nvpair_name(elem)));
7704 fname = strchr(nvpair_name(elem), '@') + 1;
7705 VERIFY0(zfeature_lookup_name(fname, &fid));
7707 spa_feature_enable(spa, fid, tx);
7708 spa_history_log_internal(spa, "set", tx,
7709 "%s=enabled", nvpair_name(elem));
7712 case ZPOOL_PROP_VERSION:
7713 intval = fnvpair_value_uint64(elem);
7715 * The version is synced seperatly before other
7716 * properties and should be correct by now.
7718 ASSERT3U(spa_version(spa), >=, intval);
7721 case ZPOOL_PROP_ALTROOT:
7723 * 'altroot' is a non-persistent property. It should
7724 * have been set temporarily at creation or import time.
7726 ASSERT(spa->spa_root != NULL);
7729 case ZPOOL_PROP_READONLY:
7730 case ZPOOL_PROP_CACHEFILE:
7732 * 'readonly' and 'cachefile' are also non-persisitent
7736 case ZPOOL_PROP_COMMENT:
7737 strval = fnvpair_value_string(elem);
7738 if (spa->spa_comment != NULL)
7739 spa_strfree(spa->spa_comment);
7740 spa->spa_comment = spa_strdup(strval);
7742 * We need to dirty the configuration on all the vdevs
7743 * so that their labels get updated. It's unnecessary
7744 * to do this for pool creation since the vdev's
7745 * configuratoin has already been dirtied.
7747 if (tx->tx_txg != TXG_INITIAL)
7748 vdev_config_dirty(spa->spa_root_vdev);
7749 spa_history_log_internal(spa, "set", tx,
7750 "%s=%s", nvpair_name(elem), strval);
7754 * Set pool property values in the poolprops mos object.
7756 if (spa->spa_pool_props_object == 0) {
7757 spa->spa_pool_props_object =
7758 zap_create_link(mos, DMU_OT_POOL_PROPS,
7759 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
7763 /* normalize the property name */
7764 propname = zpool_prop_to_name(prop);
7765 proptype = zpool_prop_get_type(prop);
7767 if (nvpair_type(elem) == DATA_TYPE_STRING) {
7768 ASSERT(proptype == PROP_TYPE_STRING);
7769 strval = fnvpair_value_string(elem);
7770 VERIFY0(zap_update(mos,
7771 spa->spa_pool_props_object, propname,
7772 1, strlen(strval) + 1, strval, tx));
7773 spa_history_log_internal(spa, "set", tx,
7774 "%s=%s", nvpair_name(elem), strval);
7775 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
7776 intval = fnvpair_value_uint64(elem);
7778 if (proptype == PROP_TYPE_INDEX) {
7780 VERIFY0(zpool_prop_index_to_string(
7781 prop, intval, &unused));
7783 VERIFY0(zap_update(mos,
7784 spa->spa_pool_props_object, propname,
7785 8, 1, &intval, tx));
7786 spa_history_log_internal(spa, "set", tx,
7787 "%s=%lld", nvpair_name(elem), intval);
7789 ASSERT(0); /* not allowed */
7793 case ZPOOL_PROP_DELEGATION:
7794 spa->spa_delegation = intval;
7796 case ZPOOL_PROP_BOOTFS:
7797 spa->spa_bootfs = intval;
7799 case ZPOOL_PROP_FAILUREMODE:
7800 spa->spa_failmode = intval;
7802 case ZPOOL_PROP_AUTOEXPAND:
7803 spa->spa_autoexpand = intval;
7804 if (tx->tx_txg != TXG_INITIAL)
7805 spa_async_request(spa,
7806 SPA_ASYNC_AUTOEXPAND);
7808 case ZPOOL_PROP_DEDUPDITTO:
7809 spa->spa_dedup_ditto = intval;
7818 mutex_exit(&spa->spa_props_lock);
7822 * Perform one-time upgrade on-disk changes. spa_version() does not
7823 * reflect the new version this txg, so there must be no changes this
7824 * txg to anything that the upgrade code depends on after it executes.
7825 * Therefore this must be called after dsl_pool_sync() does the sync
7829 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
7831 dsl_pool_t *dp = spa->spa_dsl_pool;
7833 ASSERT(spa->spa_sync_pass == 1);
7835 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
7837 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
7838 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
7839 dsl_pool_create_origin(dp, tx);
7841 /* Keeping the origin open increases spa_minref */
7842 spa->spa_minref += 3;
7845 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
7846 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
7847 dsl_pool_upgrade_clones(dp, tx);
7850 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
7851 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
7852 dsl_pool_upgrade_dir_clones(dp, tx);
7854 /* Keeping the freedir open increases spa_minref */
7855 spa->spa_minref += 3;
7858 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
7859 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7860 spa_feature_create_zap_objects(spa, tx);
7864 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
7865 * when possibility to use lz4 compression for metadata was added
7866 * Old pools that have this feature enabled must be upgraded to have
7867 * this feature active
7869 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7870 boolean_t lz4_en = spa_feature_is_enabled(spa,
7871 SPA_FEATURE_LZ4_COMPRESS);
7872 boolean_t lz4_ac = spa_feature_is_active(spa,
7873 SPA_FEATURE_LZ4_COMPRESS);
7875 if (lz4_en && !lz4_ac)
7876 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
7880 * If we haven't written the salt, do so now. Note that the
7881 * feature may not be activated yet, but that's fine since
7882 * the presence of this ZAP entry is backwards compatible.
7884 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7885 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
7886 VERIFY0(zap_add(spa->spa_meta_objset,
7887 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
7888 sizeof (spa->spa_cksum_salt.zcs_bytes),
7889 spa->spa_cksum_salt.zcs_bytes, tx));
7892 rrw_exit(&dp->dp_config_rwlock, FTAG);
7896 vdev_indirect_state_sync_verify(vdev_t *vd)
7898 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
7899 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
7901 if (vd->vdev_ops == &vdev_indirect_ops) {
7902 ASSERT(vim != NULL);
7903 ASSERT(vib != NULL);
7906 if (vdev_obsolete_sm_object(vd) != 0) {
7907 ASSERT(vd->vdev_obsolete_sm != NULL);
7908 ASSERT(vd->vdev_removing ||
7909 vd->vdev_ops == &vdev_indirect_ops);
7910 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
7911 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
7913 ASSERT3U(vdev_obsolete_sm_object(vd), ==,
7914 space_map_object(vd->vdev_obsolete_sm));
7915 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
7916 space_map_allocated(vd->vdev_obsolete_sm));
7918 ASSERT(vd->vdev_obsolete_segments != NULL);
7921 * Since frees / remaps to an indirect vdev can only
7922 * happen in syncing context, the obsolete segments
7923 * tree must be empty when we start syncing.
7925 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
7929 * Sync the specified transaction group. New blocks may be dirtied as
7930 * part of the process, so we iterate until it converges.
7933 spa_sync(spa_t *spa, uint64_t txg)
7935 dsl_pool_t *dp = spa->spa_dsl_pool;
7936 objset_t *mos = spa->spa_meta_objset;
7937 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
7938 vdev_t *rvd = spa->spa_root_vdev;
7942 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
7943 zfs_vdev_queue_depth_pct / 100;
7945 VERIFY(spa_writeable(spa));
7948 * Wait for i/os issued in open context that need to complete
7949 * before this txg syncs.
7951 (void) zio_wait(spa->spa_txg_zio[txg & TXG_MASK]);
7952 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL,
7956 * Lock out configuration changes.
7958 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7960 spa->spa_syncing_txg = txg;
7961 spa->spa_sync_pass = 0;
7963 for (int i = 0; i < spa->spa_alloc_count; i++) {
7964 mutex_enter(&spa->spa_alloc_locks[i]);
7965 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
7966 mutex_exit(&spa->spa_alloc_locks[i]);
7970 * If there are any pending vdev state changes, convert them
7971 * into config changes that go out with this transaction group.
7973 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7974 while (list_head(&spa->spa_state_dirty_list) != NULL) {
7976 * We need the write lock here because, for aux vdevs,
7977 * calling vdev_config_dirty() modifies sav_config.
7978 * This is ugly and will become unnecessary when we
7979 * eliminate the aux vdev wart by integrating all vdevs
7980 * into the root vdev tree.
7982 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7983 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
7984 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
7985 vdev_state_clean(vd);
7986 vdev_config_dirty(vd);
7988 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7989 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
7991 spa_config_exit(spa, SCL_STATE, FTAG);
7993 tx = dmu_tx_create_assigned(dp, txg);
7995 spa->spa_sync_starttime = gethrtime();
7997 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
7998 spa->spa_sync_starttime + spa->spa_deadman_synctime));
7999 #else /* !illumos */
8001 callout_schedule(&spa->spa_deadman_cycid,
8002 hz * spa->spa_deadman_synctime / NANOSEC);
8004 #endif /* illumos */
8007 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
8008 * set spa_deflate if we have no raid-z vdevs.
8010 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
8011 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
8014 for (i = 0; i < rvd->vdev_children; i++) {
8015 vd = rvd->vdev_child[i];
8016 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
8019 if (i == rvd->vdev_children) {
8020 spa->spa_deflate = TRUE;
8021 VERIFY(0 == zap_add(spa->spa_meta_objset,
8022 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
8023 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
8028 * Set the top-level vdev's max queue depth. Evaluate each
8029 * top-level's async write queue depth in case it changed.
8030 * The max queue depth will not change in the middle of syncing
8033 uint64_t slots_per_allocator = 0;
8034 for (int c = 0; c < rvd->vdev_children; c++) {
8035 vdev_t *tvd = rvd->vdev_child[c];
8036 metaslab_group_t *mg = tvd->vdev_mg;
8038 if (mg == NULL || mg->mg_class != spa_normal_class(spa) ||
8039 !metaslab_group_initialized(mg))
8043 * It is safe to do a lock-free check here because only async
8044 * allocations look at mg_max_alloc_queue_depth, and async
8045 * allocations all happen from spa_sync().
8047 for (int i = 0; i < spa->spa_alloc_count; i++)
8048 ASSERT0(zfs_refcount_count(
8049 &(mg->mg_alloc_queue_depth[i])));
8050 mg->mg_max_alloc_queue_depth = max_queue_depth;
8052 for (int i = 0; i < spa->spa_alloc_count; i++) {
8053 mg->mg_cur_max_alloc_queue_depth[i] =
8054 zfs_vdev_def_queue_depth;
8056 slots_per_allocator += zfs_vdev_def_queue_depth;
8058 metaslab_class_t *mc = spa_normal_class(spa);
8059 for (int i = 0; i < spa->spa_alloc_count; i++) {
8060 ASSERT0(zfs_refcount_count(&mc->mc_alloc_slots[i]));
8061 mc->mc_alloc_max_slots[i] = slots_per_allocator;
8063 mc->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8065 for (int c = 0; c < rvd->vdev_children; c++) {
8066 vdev_t *vd = rvd->vdev_child[c];
8067 vdev_indirect_state_sync_verify(vd);
8069 if (vdev_indirect_should_condense(vd)) {
8070 spa_condense_indirect_start_sync(vd, tx);
8076 * Iterate to convergence.
8079 int pass = ++spa->spa_sync_pass;
8081 spa_sync_config_object(spa, tx);
8082 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
8083 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
8084 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
8085 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
8086 spa_errlog_sync(spa, txg);
8087 dsl_pool_sync(dp, txg);
8089 if (pass < zfs_sync_pass_deferred_free) {
8090 spa_sync_frees(spa, free_bpl, tx);
8093 * We can not defer frees in pass 1, because
8094 * we sync the deferred frees later in pass 1.
8096 ASSERT3U(pass, >, 1);
8097 bplist_iterate(free_bpl, bpobj_enqueue_cb,
8098 &spa->spa_deferred_bpobj, tx);
8102 dsl_scan_sync(dp, tx);
8104 if (spa->spa_vdev_removal != NULL)
8107 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
8112 spa_sync_upgrades(spa, tx);
8114 spa->spa_uberblock.ub_rootbp.blk_birth);
8116 * Note: We need to check if the MOS is dirty
8117 * because we could have marked the MOS dirty
8118 * without updating the uberblock (e.g. if we
8119 * have sync tasks but no dirty user data). We
8120 * need to check the uberblock's rootbp because
8121 * it is updated if we have synced out dirty
8122 * data (though in this case the MOS will most
8123 * likely also be dirty due to second order
8124 * effects, we don't want to rely on that here).
8126 if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
8127 !dmu_objset_is_dirty(mos, txg)) {
8129 * Nothing changed on the first pass,
8130 * therefore this TXG is a no-op. Avoid
8131 * syncing deferred frees, so that we
8132 * can keep this TXG as a no-op.
8134 ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
8136 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8137 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
8138 ASSERT(txg_list_empty(&dp->dp_early_sync_tasks,
8142 spa_sync_deferred_frees(spa, tx);
8145 } while (dmu_objset_is_dirty(mos, txg));
8147 if (!list_is_empty(&spa->spa_config_dirty_list)) {
8149 * Make sure that the number of ZAPs for all the vdevs matches
8150 * the number of ZAPs in the per-vdev ZAP list. This only gets
8151 * called if the config is dirty; otherwise there may be
8152 * outstanding AVZ operations that weren't completed in
8153 * spa_sync_config_object.
8155 uint64_t all_vdev_zap_entry_count;
8156 ASSERT0(zap_count(spa->spa_meta_objset,
8157 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
8158 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
8159 all_vdev_zap_entry_count);
8162 if (spa->spa_vdev_removal != NULL) {
8163 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
8167 * Rewrite the vdev configuration (which includes the uberblock)
8168 * to commit the transaction group.
8170 * If there are no dirty vdevs, we sync the uberblock to a few
8171 * random top-level vdevs that are known to be visible in the
8172 * config cache (see spa_vdev_add() for a complete description).
8173 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
8177 * We hold SCL_STATE to prevent vdev open/close/etc.
8178 * while we're attempting to write the vdev labels.
8180 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8182 if (list_is_empty(&spa->spa_config_dirty_list)) {
8183 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
8185 int children = rvd->vdev_children;
8186 int c0 = spa_get_random(children);
8188 for (int c = 0; c < children; c++) {
8189 vd = rvd->vdev_child[(c0 + c) % children];
8191 /* Stop when revisiting the first vdev */
8192 if (c > 0 && svd[0] == vd)
8195 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
8196 !vdev_is_concrete(vd))
8199 svd[svdcount++] = vd;
8200 if (svdcount == SPA_SYNC_MIN_VDEVS)
8203 error = vdev_config_sync(svd, svdcount, txg);
8205 error = vdev_config_sync(rvd->vdev_child,
8206 rvd->vdev_children, txg);
8210 spa->spa_last_synced_guid = rvd->vdev_guid;
8212 spa_config_exit(spa, SCL_STATE, FTAG);
8216 zio_suspend(spa, NULL);
8217 zio_resume_wait(spa);
8222 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
8223 #else /* !illumos */
8225 callout_drain(&spa->spa_deadman_cycid);
8227 #endif /* illumos */
8230 * Clear the dirty config list.
8232 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
8233 vdev_config_clean(vd);
8236 * Now that the new config has synced transactionally,
8237 * let it become visible to the config cache.
8239 if (spa->spa_config_syncing != NULL) {
8240 spa_config_set(spa, spa->spa_config_syncing);
8241 spa->spa_config_txg = txg;
8242 spa->spa_config_syncing = NULL;
8245 dsl_pool_sync_done(dp, txg);
8247 for (int i = 0; i < spa->spa_alloc_count; i++) {
8248 mutex_enter(&spa->spa_alloc_locks[i]);
8249 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8250 mutex_exit(&spa->spa_alloc_locks[i]);
8254 * Update usable space statistics.
8256 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
8258 vdev_sync_done(vd, txg);
8260 spa_update_dspace(spa);
8263 * It had better be the case that we didn't dirty anything
8264 * since vdev_config_sync().
8266 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8267 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8268 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
8270 while (zfs_pause_spa_sync)
8273 spa->spa_sync_pass = 0;
8276 * Update the last synced uberblock here. We want to do this at
8277 * the end of spa_sync() so that consumers of spa_last_synced_txg()
8278 * will be guaranteed that all the processing associated with
8279 * that txg has been completed.
8281 spa->spa_ubsync = spa->spa_uberblock;
8282 spa_config_exit(spa, SCL_CONFIG, FTAG);
8284 spa_handle_ignored_writes(spa);
8287 * If any async tasks have been requested, kick them off.
8289 spa_async_dispatch(spa);
8290 spa_async_dispatch_vd(spa);
8294 * Sync all pools. We don't want to hold the namespace lock across these
8295 * operations, so we take a reference on the spa_t and drop the lock during the
8299 spa_sync_allpools(void)
8302 mutex_enter(&spa_namespace_lock);
8303 while ((spa = spa_next(spa)) != NULL) {
8304 if (spa_state(spa) != POOL_STATE_ACTIVE ||
8305 !spa_writeable(spa) || spa_suspended(spa))
8307 spa_open_ref(spa, FTAG);
8308 mutex_exit(&spa_namespace_lock);
8309 txg_wait_synced(spa_get_dsl(spa), 0);
8310 mutex_enter(&spa_namespace_lock);
8311 spa_close(spa, FTAG);
8313 mutex_exit(&spa_namespace_lock);
8317 * ==========================================================================
8318 * Miscellaneous routines
8319 * ==========================================================================
8323 * Remove all pools in the system.
8331 * Remove all cached state. All pools should be closed now,
8332 * so every spa in the AVL tree should be unreferenced.
8334 mutex_enter(&spa_namespace_lock);
8335 while ((spa = spa_next(NULL)) != NULL) {
8337 * Stop async tasks. The async thread may need to detach
8338 * a device that's been replaced, which requires grabbing
8339 * spa_namespace_lock, so we must drop it here.
8341 spa_open_ref(spa, FTAG);
8342 mutex_exit(&spa_namespace_lock);
8343 spa_async_suspend(spa);
8344 mutex_enter(&spa_namespace_lock);
8345 spa_close(spa, FTAG);
8347 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
8349 spa_deactivate(spa);
8353 mutex_exit(&spa_namespace_lock);
8357 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
8362 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
8366 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
8367 vd = spa->spa_l2cache.sav_vdevs[i];
8368 if (vd->vdev_guid == guid)
8372 for (i = 0; i < spa->spa_spares.sav_count; i++) {
8373 vd = spa->spa_spares.sav_vdevs[i];
8374 if (vd->vdev_guid == guid)
8383 spa_upgrade(spa_t *spa, uint64_t version)
8385 ASSERT(spa_writeable(spa));
8387 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
8390 * This should only be called for a non-faulted pool, and since a
8391 * future version would result in an unopenable pool, this shouldn't be
8394 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
8395 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
8397 spa->spa_uberblock.ub_version = version;
8398 vdev_config_dirty(spa->spa_root_vdev);
8400 spa_config_exit(spa, SCL_ALL, FTAG);
8402 txg_wait_synced(spa_get_dsl(spa), 0);
8406 spa_has_spare(spa_t *spa, uint64_t guid)
8410 spa_aux_vdev_t *sav = &spa->spa_spares;
8412 for (i = 0; i < sav->sav_count; i++)
8413 if (sav->sav_vdevs[i]->vdev_guid == guid)
8416 for (i = 0; i < sav->sav_npending; i++) {
8417 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
8418 &spareguid) == 0 && spareguid == guid)
8426 * Check if a pool has an active shared spare device.
8427 * Note: reference count of an active spare is 2, as a spare and as a replace
8430 spa_has_active_shared_spare(spa_t *spa)
8434 spa_aux_vdev_t *sav = &spa->spa_spares;
8436 for (i = 0; i < sav->sav_count; i++) {
8437 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
8438 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
8447 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8449 sysevent_t *ev = NULL;
8451 sysevent_attr_list_t *attr = NULL;
8452 sysevent_value_t value;
8454 ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
8458 value.value_type = SE_DATA_TYPE_STRING;
8459 value.value.sv_string = spa_name(spa);
8460 if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
8463 value.value_type = SE_DATA_TYPE_UINT64;
8464 value.value.sv_uint64 = spa_guid(spa);
8465 if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
8469 value.value_type = SE_DATA_TYPE_UINT64;
8470 value.value.sv_uint64 = vd->vdev_guid;
8471 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
8475 if (vd->vdev_path) {
8476 value.value_type = SE_DATA_TYPE_STRING;
8477 value.value.sv_string = vd->vdev_path;
8478 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
8479 &value, SE_SLEEP) != 0)
8484 if (hist_nvl != NULL) {
8485 fnvlist_merge((nvlist_t *)attr, hist_nvl);
8488 if (sysevent_attach_attributes(ev, attr) != 0)
8494 sysevent_free_attr(attr);
8501 spa_event_post(sysevent_t *ev)
8506 (void) log_sysevent(ev, SE_SLEEP, &eid);
8512 spa_event_discard(sysevent_t *ev)
8520 * Post a sysevent corresponding to the given event. The 'name' must be one of
8521 * the event definitions in sys/sysevent/eventdefs.h. The payload will be
8522 * filled in from the spa and (optionally) the vdev and history nvl. This
8523 * doesn't do anything in the userland libzpool, as we don't want consumers to
8524 * misinterpret ztest or zdb as real changes.
8527 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8529 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));