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, Intel Corporation.
33 * Copyright (c) 2017 Datto Inc.
34 * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
35 * Copyright (c) 2016 Actifio, Inc. All rights reserved.
39 * SPA: Storage Pool Allocator
41 * This file contains all the routines used when modifying on-disk SPA state.
42 * This includes opening, importing, destroying, exporting a pool, and syncing a
46 #include <sys/zfs_context.h>
47 #include <sys/fm/fs/zfs.h>
48 #include <sys/spa_impl.h>
50 #include <sys/zio_checksum.h>
52 #include <sys/dmu_tx.h>
56 #include <sys/vdev_impl.h>
57 #include <sys/vdev_removal.h>
58 #include <sys/vdev_indirect_mapping.h>
59 #include <sys/vdev_indirect_births.h>
60 #include <sys/vdev_initialize.h>
61 #include <sys/metaslab.h>
62 #include <sys/metaslab_impl.h>
64 #include <sys/uberblock_impl.h>
67 #include <sys/bpobj.h>
68 #include <sys/dmu_traverse.h>
69 #include <sys/dmu_objset.h>
70 #include <sys/unique.h>
71 #include <sys/dsl_pool.h>
72 #include <sys/dsl_dataset.h>
73 #include <sys/dsl_dir.h>
74 #include <sys/dsl_prop.h>
75 #include <sys/dsl_synctask.h>
76 #include <sys/fs/zfs.h>
78 #include <sys/callb.h>
79 #include <sys/spa_boot.h>
80 #include <sys/zfs_ioctl.h>
81 #include <sys/dsl_scan.h>
82 #include <sys/dmu_send.h>
83 #include <sys/dsl_destroy.h>
84 #include <sys/dsl_userhold.h>
85 #include <sys/zfeature.h>
87 #include <sys/trim_map.h>
91 #include <sys/callb.h>
92 #include <sys/cpupart.h>
97 #include "zfs_comutil.h"
99 /* Check hostid on import? */
100 static int check_hostid = 1;
103 * The interval, in seconds, at which failed configuration cache file writes
106 int zfs_ccw_retry_interval = 300;
108 SYSCTL_DECL(_vfs_zfs);
109 SYSCTL_INT(_vfs_zfs, OID_AUTO, check_hostid, CTLFLAG_RWTUN, &check_hostid, 0,
110 "Check hostid on import?");
111 TUNABLE_INT("vfs.zfs.ccw_retry_interval", &zfs_ccw_retry_interval);
112 SYSCTL_INT(_vfs_zfs, OID_AUTO, ccw_retry_interval, CTLFLAG_RW,
113 &zfs_ccw_retry_interval, 0,
114 "Configuration cache file write, retry after failure, interval (seconds)");
116 typedef enum zti_modes {
117 ZTI_MODE_FIXED, /* value is # of threads (min 1) */
118 ZTI_MODE_BATCH, /* cpu-intensive; value is ignored */
119 ZTI_MODE_NULL, /* don't create a taskq */
123 #define ZTI_P(n, q) { ZTI_MODE_FIXED, (n), (q) }
124 #define ZTI_BATCH { ZTI_MODE_BATCH, 0, 1 }
125 #define ZTI_NULL { ZTI_MODE_NULL, 0, 0 }
127 #define ZTI_N(n) ZTI_P(n, 1)
128 #define ZTI_ONE ZTI_N(1)
130 typedef struct zio_taskq_info {
131 zti_modes_t zti_mode;
136 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
137 "issue", "issue_high", "intr", "intr_high"
141 * This table defines the taskq settings for each ZFS I/O type. When
142 * initializing a pool, we use this table to create an appropriately sized
143 * taskq. Some operations are low volume and therefore have a small, static
144 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
145 * macros. Other operations process a large amount of data; the ZTI_BATCH
146 * macro causes us to create a taskq oriented for throughput. Some operations
147 * are so high frequency and short-lived that the taskq itself can become a a
148 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
149 * additional degree of parallelism specified by the number of threads per-
150 * taskq and the number of taskqs; when dispatching an event in this case, the
151 * particular taskq is chosen at random.
153 * The different taskq priorities are to handle the different contexts (issue
154 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
155 * need to be handled with minimum delay.
157 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
158 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
159 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* NULL */
160 { ZTI_N(8), ZTI_NULL, ZTI_P(12, 8), ZTI_NULL }, /* READ */
161 { ZTI_BATCH, ZTI_N(5), ZTI_P(12, 8), ZTI_N(5) }, /* WRITE */
162 { ZTI_P(12, 8), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* FREE */
163 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* CLAIM */
164 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* IOCTL */
167 static void spa_sync_version(void *arg, dmu_tx_t *tx);
168 static void spa_sync_props(void *arg, dmu_tx_t *tx);
169 static boolean_t spa_has_active_shared_spare(spa_t *spa);
170 static int spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport);
171 static void spa_vdev_resilver_done(spa_t *spa);
173 uint_t zio_taskq_batch_pct = 75; /* 1 thread per cpu in pset */
175 id_t zio_taskq_psrset_bind = PS_NONE;
178 boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
179 uint_t zio_taskq_basedc = 80; /* base duty cycle */
185 boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
187 extern int zfs_sync_pass_deferred_free;
190 * Report any spa_load_verify errors found, but do not fail spa_load.
191 * This is used by zdb to analyze non-idle pools.
193 boolean_t spa_load_verify_dryrun = B_FALSE;
196 * This (illegal) pool name is used when temporarily importing a spa_t in order
197 * to get the vdev stats associated with the imported devices.
199 #define TRYIMPORT_NAME "$import"
202 * For debugging purposes: print out vdev tree during pool import.
204 int spa_load_print_vdev_tree = B_FALSE;
207 * A non-zero value for zfs_max_missing_tvds means that we allow importing
208 * pools with missing top-level vdevs. This is strictly intended for advanced
209 * pool recovery cases since missing data is almost inevitable. Pools with
210 * missing devices can only be imported read-only for safety reasons, and their
211 * fail-mode will be automatically set to "continue".
213 * With 1 missing vdev we should be able to import the pool and mount all
214 * datasets. User data that was not modified after the missing device has been
215 * added should be recoverable. This means that snapshots created prior to the
216 * addition of that device should be completely intact.
218 * With 2 missing vdevs, some datasets may fail to mount since there are
219 * dataset statistics that are stored as regular metadata. Some data might be
220 * recoverable if those vdevs were added recently.
222 * With 3 or more missing vdevs, the pool is severely damaged and MOS entries
223 * may be missing entirely. Chances of data recovery are very low. Note that
224 * there are also risks of performing an inadvertent rewind as we might be
225 * missing all the vdevs with the latest uberblocks.
227 uint64_t zfs_max_missing_tvds = 0;
230 * The parameters below are similar to zfs_max_missing_tvds but are only
231 * intended for a preliminary open of the pool with an untrusted config which
232 * might be incomplete or out-dated.
234 * We are more tolerant for pools opened from a cachefile since we could have
235 * an out-dated cachefile where a device removal was not registered.
236 * We could have set the limit arbitrarily high but in the case where devices
237 * are really missing we would want to return the proper error codes; we chose
238 * SPA_DVAS_PER_BP - 1 so that some copies of the MOS would still be available
239 * and we get a chance to retrieve the trusted config.
241 uint64_t zfs_max_missing_tvds_cachefile = SPA_DVAS_PER_BP - 1;
244 * In the case where config was assembled by scanning device paths (/dev/dsks
245 * by default) we are less tolerant since all the existing devices should have
246 * been detected and we want spa_load to return the right error codes.
248 uint64_t zfs_max_missing_tvds_scan = 0;
251 SYSCTL_DECL(_vfs_zfs_zio);
252 SYSCTL_INT(_vfs_zfs_zio, OID_AUTO, taskq_batch_pct, CTLFLAG_RDTUN,
253 &zio_taskq_batch_pct, 0,
254 "Percentage of CPUs to run an IO worker thread");
255 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_print_vdev_tree, CTLFLAG_RWTUN,
256 &spa_load_print_vdev_tree, 0,
257 "print out vdev tree during pool import");
258 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds, CTLFLAG_RWTUN,
259 &zfs_max_missing_tvds, 0,
260 "allow importing pools with missing top-level vdevs");
261 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_cachefile, CTLFLAG_RWTUN,
262 &zfs_max_missing_tvds_cachefile, 0,
263 "allow importing pools with missing top-level vdevs in cache file");
264 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_scan, CTLFLAG_RWTUN,
265 &zfs_max_missing_tvds_scan, 0,
266 "allow importing pools with missing top-level vdevs during scan");
269 * Debugging aid that pauses spa_sync() towards the end.
271 boolean_t zfs_pause_spa_sync = B_FALSE;
274 * ==========================================================================
275 * SPA properties routines
276 * ==========================================================================
280 * Add a (source=src, propname=propval) list to an nvlist.
283 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
284 uint64_t intval, zprop_source_t src)
286 const char *propname = zpool_prop_to_name(prop);
289 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
290 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
293 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
295 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
297 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
298 nvlist_free(propval);
302 * Get property values from the spa configuration.
305 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
307 vdev_t *rvd = spa->spa_root_vdev;
308 dsl_pool_t *pool = spa->spa_dsl_pool;
309 uint64_t size, alloc, cap, version;
310 zprop_source_t src = ZPROP_SRC_NONE;
311 spa_config_dirent_t *dp;
312 metaslab_class_t *mc = spa_normal_class(spa);
314 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
317 alloc = metaslab_class_get_alloc(mc);
318 alloc += metaslab_class_get_alloc(spa_special_class(spa));
319 alloc += metaslab_class_get_alloc(spa_dedup_class(spa));
321 size = metaslab_class_get_space(mc);
322 size += metaslab_class_get_space(spa_special_class(spa));
323 size += metaslab_class_get_space(spa_dedup_class(spa));
325 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
326 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
327 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
328 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
330 spa_prop_add_list(*nvp, ZPOOL_PROP_CHECKPOINT, NULL,
331 spa->spa_checkpoint_info.sci_dspace, src);
333 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
334 metaslab_class_fragmentation(mc), src);
335 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
336 metaslab_class_expandable_space(mc), src);
337 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
338 (spa_mode(spa) == FREAD), src);
340 cap = (size == 0) ? 0 : (alloc * 100 / size);
341 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
343 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
344 ddt_get_pool_dedup_ratio(spa), src);
346 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
347 rvd->vdev_state, src);
349 version = spa_version(spa);
350 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
351 src = ZPROP_SRC_DEFAULT;
353 src = ZPROP_SRC_LOCAL;
354 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
359 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
360 * when opening pools before this version freedir will be NULL.
362 if (pool->dp_free_dir != NULL) {
363 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
364 dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
367 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
371 if (pool->dp_leak_dir != NULL) {
372 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
373 dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
376 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
381 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
383 if (spa->spa_comment != NULL) {
384 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
388 if (spa->spa_root != NULL)
389 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
392 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
393 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
394 MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
396 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
397 SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
400 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE)) {
401 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
402 DNODE_MAX_SIZE, ZPROP_SRC_NONE);
404 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
405 DNODE_MIN_SIZE, ZPROP_SRC_NONE);
408 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
409 if (dp->scd_path == NULL) {
410 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
411 "none", 0, ZPROP_SRC_LOCAL);
412 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
413 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
414 dp->scd_path, 0, ZPROP_SRC_LOCAL);
420 * Get zpool property values.
423 spa_prop_get(spa_t *spa, nvlist_t **nvp)
425 objset_t *mos = spa->spa_meta_objset;
430 VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
432 mutex_enter(&spa->spa_props_lock);
435 * Get properties from the spa config.
437 spa_prop_get_config(spa, nvp);
439 /* If no pool property object, no more prop to get. */
440 if (mos == NULL || spa->spa_pool_props_object == 0) {
441 mutex_exit(&spa->spa_props_lock);
446 * Get properties from the MOS pool property object.
448 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
449 (err = zap_cursor_retrieve(&zc, &za)) == 0;
450 zap_cursor_advance(&zc)) {
453 zprop_source_t src = ZPROP_SRC_DEFAULT;
456 if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
459 switch (za.za_integer_length) {
461 /* integer property */
462 if (za.za_first_integer !=
463 zpool_prop_default_numeric(prop))
464 src = ZPROP_SRC_LOCAL;
466 if (prop == ZPOOL_PROP_BOOTFS) {
468 dsl_dataset_t *ds = NULL;
470 dp = spa_get_dsl(spa);
471 dsl_pool_config_enter(dp, FTAG);
472 err = dsl_dataset_hold_obj(dp,
473 za.za_first_integer, FTAG, &ds);
475 dsl_pool_config_exit(dp, FTAG);
479 strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
481 dsl_dataset_name(ds, strval);
482 dsl_dataset_rele(ds, FTAG);
483 dsl_pool_config_exit(dp, FTAG);
486 intval = za.za_first_integer;
489 spa_prop_add_list(*nvp, prop, strval, intval, src);
492 kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
497 /* string property */
498 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
499 err = zap_lookup(mos, spa->spa_pool_props_object,
500 za.za_name, 1, za.za_num_integers, strval);
502 kmem_free(strval, za.za_num_integers);
505 spa_prop_add_list(*nvp, prop, strval, 0, src);
506 kmem_free(strval, za.za_num_integers);
513 zap_cursor_fini(&zc);
514 mutex_exit(&spa->spa_props_lock);
516 if (err && err != ENOENT) {
526 * Validate the given pool properties nvlist and modify the list
527 * for the property values to be set.
530 spa_prop_validate(spa_t *spa, nvlist_t *props)
533 int error = 0, reset_bootfs = 0;
535 boolean_t has_feature = B_FALSE;
538 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
540 char *strval, *slash, *check, *fname;
541 const char *propname = nvpair_name(elem);
542 zpool_prop_t prop = zpool_name_to_prop(propname);
545 case ZPOOL_PROP_INVAL:
546 if (!zpool_prop_feature(propname)) {
547 error = SET_ERROR(EINVAL);
552 * Sanitize the input.
554 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
555 error = SET_ERROR(EINVAL);
559 if (nvpair_value_uint64(elem, &intval) != 0) {
560 error = SET_ERROR(EINVAL);
565 error = SET_ERROR(EINVAL);
569 fname = strchr(propname, '@') + 1;
570 if (zfeature_lookup_name(fname, NULL) != 0) {
571 error = SET_ERROR(EINVAL);
575 has_feature = B_TRUE;
578 case ZPOOL_PROP_VERSION:
579 error = nvpair_value_uint64(elem, &intval);
581 (intval < spa_version(spa) ||
582 intval > SPA_VERSION_BEFORE_FEATURES ||
584 error = SET_ERROR(EINVAL);
587 case ZPOOL_PROP_DELEGATION:
588 case ZPOOL_PROP_AUTOREPLACE:
589 case ZPOOL_PROP_LISTSNAPS:
590 case ZPOOL_PROP_AUTOEXPAND:
591 error = nvpair_value_uint64(elem, &intval);
592 if (!error && intval > 1)
593 error = SET_ERROR(EINVAL);
596 case ZPOOL_PROP_MULTIHOST:
597 error = nvpair_value_uint64(elem, &intval);
598 if (!error && intval > 1)
599 error = SET_ERROR(EINVAL);
601 if (!error && !spa_get_hostid())
602 error = SET_ERROR(ENOTSUP);
606 case ZPOOL_PROP_BOOTFS:
608 * If the pool version is less than SPA_VERSION_BOOTFS,
609 * or the pool is still being created (version == 0),
610 * the bootfs property cannot be set.
612 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
613 error = SET_ERROR(ENOTSUP);
618 * Make sure the vdev config is bootable
620 if (!vdev_is_bootable(spa->spa_root_vdev)) {
621 error = SET_ERROR(ENOTSUP);
627 error = nvpair_value_string(elem, &strval);
633 if (strval == NULL || strval[0] == '\0') {
634 objnum = zpool_prop_default_numeric(
639 error = dmu_objset_hold(strval, FTAG, &os);
644 * Must be ZPL, and its property settings
648 if (dmu_objset_type(os) != DMU_OST_ZFS) {
649 error = SET_ERROR(ENOTSUP);
651 dsl_prop_get_int_ds(dmu_objset_ds(os),
652 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
654 !BOOTFS_COMPRESS_VALID(propval)) {
655 error = SET_ERROR(ENOTSUP);
657 objnum = dmu_objset_id(os);
659 dmu_objset_rele(os, FTAG);
663 case ZPOOL_PROP_FAILUREMODE:
664 error = nvpair_value_uint64(elem, &intval);
665 if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
666 intval > ZIO_FAILURE_MODE_PANIC))
667 error = SET_ERROR(EINVAL);
670 * This is a special case which only occurs when
671 * the pool has completely failed. This allows
672 * the user to change the in-core failmode property
673 * without syncing it out to disk (I/Os might
674 * currently be blocked). We do this by returning
675 * EIO to the caller (spa_prop_set) to trick it
676 * into thinking we encountered a property validation
679 if (!error && spa_suspended(spa)) {
680 spa->spa_failmode = intval;
681 error = SET_ERROR(EIO);
685 case ZPOOL_PROP_CACHEFILE:
686 if ((error = nvpair_value_string(elem, &strval)) != 0)
689 if (strval[0] == '\0')
692 if (strcmp(strval, "none") == 0)
695 if (strval[0] != '/') {
696 error = SET_ERROR(EINVAL);
700 slash = strrchr(strval, '/');
701 ASSERT(slash != NULL);
703 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
704 strcmp(slash, "/..") == 0)
705 error = SET_ERROR(EINVAL);
708 case ZPOOL_PROP_COMMENT:
709 if ((error = nvpair_value_string(elem, &strval)) != 0)
711 for (check = strval; *check != '\0'; check++) {
713 * The kernel doesn't have an easy isprint()
714 * check. For this kernel check, we merely
715 * check ASCII apart from DEL. Fix this if
716 * there is an easy-to-use kernel isprint().
718 if (*check >= 0x7f) {
719 error = SET_ERROR(EINVAL);
723 if (strlen(strval) > ZPROP_MAX_COMMENT)
727 case ZPOOL_PROP_DEDUPDITTO:
728 if (spa_version(spa) < SPA_VERSION_DEDUP)
729 error = SET_ERROR(ENOTSUP);
731 error = nvpair_value_uint64(elem, &intval);
733 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
734 error = SET_ERROR(EINVAL);
742 if (!error && reset_bootfs) {
743 error = nvlist_remove(props,
744 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
747 error = nvlist_add_uint64(props,
748 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
756 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
759 spa_config_dirent_t *dp;
761 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
765 dp = kmem_alloc(sizeof (spa_config_dirent_t),
768 if (cachefile[0] == '\0')
769 dp->scd_path = spa_strdup(spa_config_path);
770 else if (strcmp(cachefile, "none") == 0)
773 dp->scd_path = spa_strdup(cachefile);
775 list_insert_head(&spa->spa_config_list, dp);
777 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
781 spa_prop_set(spa_t *spa, nvlist_t *nvp)
784 nvpair_t *elem = NULL;
785 boolean_t need_sync = B_FALSE;
787 if ((error = spa_prop_validate(spa, nvp)) != 0)
790 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
791 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
793 if (prop == ZPOOL_PROP_CACHEFILE ||
794 prop == ZPOOL_PROP_ALTROOT ||
795 prop == ZPOOL_PROP_READONLY)
798 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
801 if (prop == ZPOOL_PROP_VERSION) {
802 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
804 ASSERT(zpool_prop_feature(nvpair_name(elem)));
805 ver = SPA_VERSION_FEATURES;
809 /* Save time if the version is already set. */
810 if (ver == spa_version(spa))
814 * In addition to the pool directory object, we might
815 * create the pool properties object, the features for
816 * read object, the features for write object, or the
817 * feature descriptions object.
819 error = dsl_sync_task(spa->spa_name, NULL,
820 spa_sync_version, &ver,
821 6, ZFS_SPACE_CHECK_RESERVED);
832 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
833 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
840 * If the bootfs property value is dsobj, clear it.
843 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
845 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
846 VERIFY(zap_remove(spa->spa_meta_objset,
847 spa->spa_pool_props_object,
848 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
855 spa_change_guid_check(void *arg, dmu_tx_t *tx)
857 uint64_t *newguid = arg;
858 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
859 vdev_t *rvd = spa->spa_root_vdev;
862 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
863 int error = (spa_has_checkpoint(spa)) ?
864 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
865 return (SET_ERROR(error));
868 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
869 vdev_state = rvd->vdev_state;
870 spa_config_exit(spa, SCL_STATE, FTAG);
872 if (vdev_state != VDEV_STATE_HEALTHY)
873 return (SET_ERROR(ENXIO));
875 ASSERT3U(spa_guid(spa), !=, *newguid);
881 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
883 uint64_t *newguid = arg;
884 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
886 vdev_t *rvd = spa->spa_root_vdev;
888 oldguid = spa_guid(spa);
890 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
891 rvd->vdev_guid = *newguid;
892 rvd->vdev_guid_sum += (*newguid - oldguid);
893 vdev_config_dirty(rvd);
894 spa_config_exit(spa, SCL_STATE, FTAG);
896 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
901 * Change the GUID for the pool. This is done so that we can later
902 * re-import a pool built from a clone of our own vdevs. We will modify
903 * the root vdev's guid, our own pool guid, and then mark all of our
904 * vdevs dirty. Note that we must make sure that all our vdevs are
905 * online when we do this, or else any vdevs that weren't present
906 * would be orphaned from our pool. We are also going to issue a
907 * sysevent to update any watchers.
910 spa_change_guid(spa_t *spa)
915 mutex_enter(&spa->spa_vdev_top_lock);
916 mutex_enter(&spa_namespace_lock);
917 guid = spa_generate_guid(NULL);
919 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
920 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
923 spa_write_cachefile(spa, B_FALSE, B_TRUE);
924 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
927 mutex_exit(&spa_namespace_lock);
928 mutex_exit(&spa->spa_vdev_top_lock);
934 * ==========================================================================
935 * SPA state manipulation (open/create/destroy/import/export)
936 * ==========================================================================
940 spa_error_entry_compare(const void *a, const void *b)
942 const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
943 const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
946 ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
947 sizeof (zbookmark_phys_t));
949 return (AVL_ISIGN(ret));
953 * Utility function which retrieves copies of the current logs and
954 * re-initializes them in the process.
957 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
959 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
961 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
962 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
964 avl_create(&spa->spa_errlist_scrub,
965 spa_error_entry_compare, sizeof (spa_error_entry_t),
966 offsetof(spa_error_entry_t, se_avl));
967 avl_create(&spa->spa_errlist_last,
968 spa_error_entry_compare, sizeof (spa_error_entry_t),
969 offsetof(spa_error_entry_t, se_avl));
973 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
975 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
976 enum zti_modes mode = ztip->zti_mode;
977 uint_t value = ztip->zti_value;
978 uint_t count = ztip->zti_count;
979 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
982 boolean_t batch = B_FALSE;
984 if (mode == ZTI_MODE_NULL) {
986 tqs->stqs_taskq = NULL;
990 ASSERT3U(count, >, 0);
992 tqs->stqs_count = count;
993 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
997 ASSERT3U(value, >=, 1);
998 value = MAX(value, 1);
1001 case ZTI_MODE_BATCH:
1003 flags |= TASKQ_THREADS_CPU_PCT;
1004 value = zio_taskq_batch_pct;
1008 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
1010 zio_type_name[t], zio_taskq_types[q], mode, value);
1014 for (uint_t i = 0; i < count; i++) {
1018 (void) snprintf(name, sizeof (name), "%s_%s_%u",
1019 zio_type_name[t], zio_taskq_types[q], i);
1021 (void) snprintf(name, sizeof (name), "%s_%s",
1022 zio_type_name[t], zio_taskq_types[q]);
1026 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
1028 flags |= TASKQ_DC_BATCH;
1030 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
1031 spa->spa_proc, zio_taskq_basedc, flags);
1034 pri_t pri = maxclsyspri;
1036 * The write issue taskq can be extremely CPU
1037 * intensive. Run it at slightly lower priority
1038 * than the other taskqs.
1040 * - numerically higher priorities are lower priorities;
1041 * - if priorities divided by four (RQ_PPQ) are equal
1042 * then a difference between them is insignificant.
1044 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1051 tq = taskq_create_proc(name, value, pri, 50,
1052 INT_MAX, spa->spa_proc, flags);
1057 tqs->stqs_taskq[i] = tq;
1062 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1064 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1066 if (tqs->stqs_taskq == NULL) {
1067 ASSERT0(tqs->stqs_count);
1071 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1072 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1073 taskq_destroy(tqs->stqs_taskq[i]);
1076 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1077 tqs->stqs_taskq = NULL;
1081 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1082 * Note that a type may have multiple discrete taskqs to avoid lock contention
1083 * on the taskq itself. In that case we choose which taskq at random by using
1084 * the low bits of gethrtime().
1087 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1088 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1090 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1093 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1094 ASSERT3U(tqs->stqs_count, !=, 0);
1096 if (tqs->stqs_count == 1) {
1097 tq = tqs->stqs_taskq[0];
1100 tq = tqs->stqs_taskq[(u_int)(sbinuptime() + curcpu) %
1103 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1107 taskq_dispatch_ent(tq, func, arg, flags, ent);
1111 spa_create_zio_taskqs(spa_t *spa)
1113 for (int t = 0; t < ZIO_TYPES; t++) {
1114 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1115 spa_taskqs_init(spa, t, q);
1122 newproc(void (*pc)(void *), void *arg, id_t cid, int pri,
1123 void **ct, pid_t pid)
1126 spa_t *spa = (spa_t *)arg; /* XXX */
1133 ASSERT(cid == syscid);
1135 error = kproc_create(pc, arg, &newp, 0, 0, "zpool-%s", spa->spa_name);
1138 td = FIRST_THREAD_IN_PROC(newp);
1140 sched_prio(td, pri);
1146 spa_thread(void *arg)
1148 callb_cpr_t cprinfo;
1152 user_t *pu = PTOU(curproc);
1154 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1157 ASSERT(curproc != &p0);
1159 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1160 "zpool-%s", spa->spa_name);
1161 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1165 /* bind this thread to the requested psrset */
1166 if (zio_taskq_psrset_bind != PS_NONE) {
1168 mutex_enter(&cpu_lock);
1169 mutex_enter(&pidlock);
1170 mutex_enter(&curproc->p_lock);
1172 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1173 0, NULL, NULL) == 0) {
1174 curthread->t_bind_pset = zio_taskq_psrset_bind;
1177 "Couldn't bind process for zfs pool \"%s\" to "
1178 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1181 mutex_exit(&curproc->p_lock);
1182 mutex_exit(&pidlock);
1183 mutex_exit(&cpu_lock);
1189 if (zio_taskq_sysdc) {
1190 sysdc_thread_enter(curthread, 100, 0);
1194 spa->spa_proc = curproc;
1195 spa->spa_did = curthread->t_did;
1197 spa_create_zio_taskqs(spa);
1199 mutex_enter(&spa->spa_proc_lock);
1200 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1202 spa->spa_proc_state = SPA_PROC_ACTIVE;
1203 cv_broadcast(&spa->spa_proc_cv);
1205 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1206 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1207 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1208 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1210 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1211 spa->spa_proc_state = SPA_PROC_GONE;
1212 spa->spa_proc = &p0;
1213 cv_broadcast(&spa->spa_proc_cv);
1214 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1217 mutex_enter(&curproc->p_lock);
1223 #endif /* SPA_PROCESS */
1226 * Activate an uninitialized pool.
1229 spa_activate(spa_t *spa, int mode)
1231 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1233 spa->spa_state = POOL_STATE_ACTIVE;
1234 spa->spa_mode = mode;
1236 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1237 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1238 spa->spa_special_class = metaslab_class_create(spa, zfs_metaslab_ops);
1239 spa->spa_dedup_class = metaslab_class_create(spa, zfs_metaslab_ops);
1241 /* Try to create a covering process */
1242 mutex_enter(&spa->spa_proc_lock);
1243 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1244 ASSERT(spa->spa_proc == &p0);
1248 /* Only create a process if we're going to be around a while. */
1249 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1250 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1252 spa->spa_proc_state = SPA_PROC_CREATED;
1253 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1254 cv_wait(&spa->spa_proc_cv,
1255 &spa->spa_proc_lock);
1257 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1258 ASSERT(spa->spa_proc != &p0);
1259 ASSERT(spa->spa_did != 0);
1263 "Couldn't create process for zfs pool \"%s\"\n",
1268 #endif /* SPA_PROCESS */
1269 mutex_exit(&spa->spa_proc_lock);
1271 /* If we didn't create a process, we need to create our taskqs. */
1273 ASSERT(spa->spa_proc == &p0);
1274 #endif /* SPA_PROCESS */
1275 if (spa->spa_proc == &p0) {
1276 spa_create_zio_taskqs(spa);
1280 * Start TRIM thread.
1282 trim_thread_create(spa);
1285 * This taskq is used to perform zvol-minor-related tasks
1286 * asynchronously. This has several advantages, including easy
1287 * resolution of various deadlocks (zfsonlinux bug #3681).
1289 * The taskq must be single threaded to ensure tasks are always
1290 * processed in the order in which they were dispatched.
1292 * A taskq per pool allows one to keep the pools independent.
1293 * This way if one pool is suspended, it will not impact another.
1295 * The preferred location to dispatch a zvol minor task is a sync
1296 * task. In this context, there is easy access to the spa_t and minimal
1297 * error handling is required because the sync task must succeed.
1299 spa->spa_zvol_taskq = taskq_create("z_zvol", 1, minclsyspri,
1302 for (size_t i = 0; i < TXG_SIZE; i++) {
1303 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL,
1307 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1308 offsetof(vdev_t, vdev_config_dirty_node));
1309 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1310 offsetof(objset_t, os_evicting_node));
1311 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1312 offsetof(vdev_t, vdev_state_dirty_node));
1314 txg_list_create(&spa->spa_vdev_txg_list, spa,
1315 offsetof(struct vdev, vdev_txg_node));
1317 avl_create(&spa->spa_errlist_scrub,
1318 spa_error_entry_compare, sizeof (spa_error_entry_t),
1319 offsetof(spa_error_entry_t, se_avl));
1320 avl_create(&spa->spa_errlist_last,
1321 spa_error_entry_compare, sizeof (spa_error_entry_t),
1322 offsetof(spa_error_entry_t, se_avl));
1326 * Opposite of spa_activate().
1329 spa_deactivate(spa_t *spa)
1331 ASSERT(spa->spa_sync_on == B_FALSE);
1332 ASSERT(spa->spa_dsl_pool == NULL);
1333 ASSERT(spa->spa_root_vdev == NULL);
1334 ASSERT(spa->spa_async_zio_root == NULL);
1335 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1338 * Stop TRIM thread in case spa_unload() wasn't called directly
1339 * before spa_deactivate().
1341 trim_thread_destroy(spa);
1343 spa_evicting_os_wait(spa);
1345 if (spa->spa_zvol_taskq) {
1346 taskq_destroy(spa->spa_zvol_taskq);
1347 spa->spa_zvol_taskq = NULL;
1350 txg_list_destroy(&spa->spa_vdev_txg_list);
1352 list_destroy(&spa->spa_config_dirty_list);
1353 list_destroy(&spa->spa_evicting_os_list);
1354 list_destroy(&spa->spa_state_dirty_list);
1356 for (int t = 0; t < ZIO_TYPES; t++) {
1357 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1358 spa_taskqs_fini(spa, t, q);
1362 for (size_t i = 0; i < TXG_SIZE; i++) {
1363 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1364 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1365 spa->spa_txg_zio[i] = NULL;
1368 metaslab_class_destroy(spa->spa_normal_class);
1369 spa->spa_normal_class = NULL;
1371 metaslab_class_destroy(spa->spa_log_class);
1372 spa->spa_log_class = NULL;
1374 metaslab_class_destroy(spa->spa_special_class);
1375 spa->spa_special_class = NULL;
1377 metaslab_class_destroy(spa->spa_dedup_class);
1378 spa->spa_dedup_class = NULL;
1381 * If this was part of an import or the open otherwise failed, we may
1382 * still have errors left in the queues. Empty them just in case.
1384 spa_errlog_drain(spa);
1386 avl_destroy(&spa->spa_errlist_scrub);
1387 avl_destroy(&spa->spa_errlist_last);
1389 spa->spa_state = POOL_STATE_UNINITIALIZED;
1391 mutex_enter(&spa->spa_proc_lock);
1392 if (spa->spa_proc_state != SPA_PROC_NONE) {
1393 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1394 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1395 cv_broadcast(&spa->spa_proc_cv);
1396 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1397 ASSERT(spa->spa_proc != &p0);
1398 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1400 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1401 spa->spa_proc_state = SPA_PROC_NONE;
1403 ASSERT(spa->spa_proc == &p0);
1404 mutex_exit(&spa->spa_proc_lock);
1409 * We want to make sure spa_thread() has actually exited the ZFS
1410 * module, so that the module can't be unloaded out from underneath
1413 if (spa->spa_did != 0) {
1414 thread_join(spa->spa_did);
1418 #endif /* SPA_PROCESS */
1422 * Verify a pool configuration, and construct the vdev tree appropriately. This
1423 * will create all the necessary vdevs in the appropriate layout, with each vdev
1424 * in the CLOSED state. This will prep the pool before open/creation/import.
1425 * All vdev validation is done by the vdev_alloc() routine.
1428 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1429 uint_t id, int atype)
1435 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1438 if ((*vdp)->vdev_ops->vdev_op_leaf)
1441 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1444 if (error == ENOENT)
1450 return (SET_ERROR(EINVAL));
1453 for (int c = 0; c < children; c++) {
1455 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1463 ASSERT(*vdp != NULL);
1469 * Opposite of spa_load().
1472 spa_unload(spa_t *spa)
1476 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1478 spa_load_note(spa, "UNLOADING");
1483 trim_thread_destroy(spa);
1488 spa_async_suspend(spa);
1490 if (spa->spa_root_vdev) {
1491 vdev_initialize_stop_all(spa->spa_root_vdev,
1492 VDEV_INITIALIZE_ACTIVE);
1498 if (spa->spa_sync_on) {
1499 txg_sync_stop(spa->spa_dsl_pool);
1500 spa->spa_sync_on = B_FALSE;
1504 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1505 * to call it earlier, before we wait for async i/o to complete.
1506 * This ensures that there is no async metaslab prefetching, by
1507 * calling taskq_wait(mg_taskq).
1509 if (spa->spa_root_vdev != NULL) {
1510 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1511 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1512 vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1513 spa_config_exit(spa, SCL_ALL, spa);
1516 if (spa->spa_mmp.mmp_thread)
1517 mmp_thread_stop(spa);
1520 * Wait for any outstanding async I/O to complete.
1522 if (spa->spa_async_zio_root != NULL) {
1523 for (int i = 0; i < max_ncpus; i++)
1524 (void) zio_wait(spa->spa_async_zio_root[i]);
1525 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1526 spa->spa_async_zio_root = NULL;
1529 if (spa->spa_vdev_removal != NULL) {
1530 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1531 spa->spa_vdev_removal = NULL;
1534 if (spa->spa_condense_zthr != NULL) {
1535 zthr_destroy(spa->spa_condense_zthr);
1536 spa->spa_condense_zthr = NULL;
1539 if (spa->spa_checkpoint_discard_zthr != NULL) {
1540 zthr_destroy(spa->spa_checkpoint_discard_zthr);
1541 spa->spa_checkpoint_discard_zthr = NULL;
1544 spa_condense_fini(spa);
1546 bpobj_close(&spa->spa_deferred_bpobj);
1548 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1553 if (spa->spa_root_vdev)
1554 vdev_free(spa->spa_root_vdev);
1555 ASSERT(spa->spa_root_vdev == NULL);
1558 * Close the dsl pool.
1560 if (spa->spa_dsl_pool) {
1561 dsl_pool_close(spa->spa_dsl_pool);
1562 spa->spa_dsl_pool = NULL;
1563 spa->spa_meta_objset = NULL;
1569 * Drop and purge level 2 cache
1571 spa_l2cache_drop(spa);
1573 for (i = 0; i < spa->spa_spares.sav_count; i++)
1574 vdev_free(spa->spa_spares.sav_vdevs[i]);
1575 if (spa->spa_spares.sav_vdevs) {
1576 kmem_free(spa->spa_spares.sav_vdevs,
1577 spa->spa_spares.sav_count * sizeof (void *));
1578 spa->spa_spares.sav_vdevs = NULL;
1580 if (spa->spa_spares.sav_config) {
1581 nvlist_free(spa->spa_spares.sav_config);
1582 spa->spa_spares.sav_config = NULL;
1584 spa->spa_spares.sav_count = 0;
1586 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1587 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1588 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1590 if (spa->spa_l2cache.sav_vdevs) {
1591 kmem_free(spa->spa_l2cache.sav_vdevs,
1592 spa->spa_l2cache.sav_count * sizeof (void *));
1593 spa->spa_l2cache.sav_vdevs = NULL;
1595 if (spa->spa_l2cache.sav_config) {
1596 nvlist_free(spa->spa_l2cache.sav_config);
1597 spa->spa_l2cache.sav_config = NULL;
1599 spa->spa_l2cache.sav_count = 0;
1601 spa->spa_async_suspended = 0;
1603 spa->spa_indirect_vdevs_loaded = B_FALSE;
1605 if (spa->spa_comment != NULL) {
1606 spa_strfree(spa->spa_comment);
1607 spa->spa_comment = NULL;
1610 spa_config_exit(spa, SCL_ALL, spa);
1614 * Load (or re-load) the current list of vdevs describing the active spares for
1615 * this pool. When this is called, we have some form of basic information in
1616 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1617 * then re-generate a more complete list including status information.
1620 spa_load_spares(spa_t *spa)
1629 * zdb opens both the current state of the pool and the
1630 * checkpointed state (if present), with a different spa_t.
1632 * As spare vdevs are shared among open pools, we skip loading
1633 * them when we load the checkpointed state of the pool.
1635 if (!spa_writeable(spa))
1639 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1642 * First, close and free any existing spare vdevs.
1644 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1645 vd = spa->spa_spares.sav_vdevs[i];
1647 /* Undo the call to spa_activate() below */
1648 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1649 B_FALSE)) != NULL && tvd->vdev_isspare)
1650 spa_spare_remove(tvd);
1655 if (spa->spa_spares.sav_vdevs)
1656 kmem_free(spa->spa_spares.sav_vdevs,
1657 spa->spa_spares.sav_count * sizeof (void *));
1659 if (spa->spa_spares.sav_config == NULL)
1662 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1663 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1665 spa->spa_spares.sav_count = (int)nspares;
1666 spa->spa_spares.sav_vdevs = NULL;
1672 * Construct the array of vdevs, opening them to get status in the
1673 * process. For each spare, there is potentially two different vdev_t
1674 * structures associated with it: one in the list of spares (used only
1675 * for basic validation purposes) and one in the active vdev
1676 * configuration (if it's spared in). During this phase we open and
1677 * validate each vdev on the spare list. If the vdev also exists in the
1678 * active configuration, then we also mark this vdev as an active spare.
1680 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1682 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1683 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1684 VDEV_ALLOC_SPARE) == 0);
1687 spa->spa_spares.sav_vdevs[i] = vd;
1689 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1690 B_FALSE)) != NULL) {
1691 if (!tvd->vdev_isspare)
1695 * We only mark the spare active if we were successfully
1696 * able to load the vdev. Otherwise, importing a pool
1697 * with a bad active spare would result in strange
1698 * behavior, because multiple pool would think the spare
1699 * is actively in use.
1701 * There is a vulnerability here to an equally bizarre
1702 * circumstance, where a dead active spare is later
1703 * brought back to life (onlined or otherwise). Given
1704 * the rarity of this scenario, and the extra complexity
1705 * it adds, we ignore the possibility.
1707 if (!vdev_is_dead(tvd))
1708 spa_spare_activate(tvd);
1712 vd->vdev_aux = &spa->spa_spares;
1714 if (vdev_open(vd) != 0)
1717 if (vdev_validate_aux(vd) == 0)
1722 * Recompute the stashed list of spares, with status information
1725 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1726 DATA_TYPE_NVLIST_ARRAY) == 0);
1728 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1730 for (i = 0; i < spa->spa_spares.sav_count; i++)
1731 spares[i] = vdev_config_generate(spa,
1732 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1733 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1734 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1735 for (i = 0; i < spa->spa_spares.sav_count; i++)
1736 nvlist_free(spares[i]);
1737 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1741 * Load (or re-load) the current list of vdevs describing the active l2cache for
1742 * this pool. When this is called, we have some form of basic information in
1743 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1744 * then re-generate a more complete list including status information.
1745 * Devices which are already active have their details maintained, and are
1749 spa_load_l2cache(spa_t *spa)
1753 int i, j, oldnvdevs;
1755 vdev_t *vd, **oldvdevs, **newvdevs;
1756 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1760 * zdb opens both the current state of the pool and the
1761 * checkpointed state (if present), with a different spa_t.
1763 * As L2 caches are part of the ARC which is shared among open
1764 * pools, we skip loading them when we load the checkpointed
1765 * state of the pool.
1767 if (!spa_writeable(spa))
1771 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1773 if (sav->sav_config != NULL) {
1774 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1775 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1776 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1782 oldvdevs = sav->sav_vdevs;
1783 oldnvdevs = sav->sav_count;
1784 sav->sav_vdevs = NULL;
1788 * Process new nvlist of vdevs.
1790 for (i = 0; i < nl2cache; i++) {
1791 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1795 for (j = 0; j < oldnvdevs; j++) {
1797 if (vd != NULL && guid == vd->vdev_guid) {
1799 * Retain previous vdev for add/remove ops.
1807 if (newvdevs[i] == NULL) {
1811 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1812 VDEV_ALLOC_L2CACHE) == 0);
1817 * Commit this vdev as an l2cache device,
1818 * even if it fails to open.
1820 spa_l2cache_add(vd);
1825 spa_l2cache_activate(vd);
1827 if (vdev_open(vd) != 0)
1830 (void) vdev_validate_aux(vd);
1832 if (!vdev_is_dead(vd))
1833 l2arc_add_vdev(spa, vd);
1838 * Purge vdevs that were dropped
1840 for (i = 0; i < oldnvdevs; i++) {
1845 ASSERT(vd->vdev_isl2cache);
1847 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1848 pool != 0ULL && l2arc_vdev_present(vd))
1849 l2arc_remove_vdev(vd);
1850 vdev_clear_stats(vd);
1856 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1858 if (sav->sav_config == NULL)
1861 sav->sav_vdevs = newvdevs;
1862 sav->sav_count = (int)nl2cache;
1865 * Recompute the stashed list of l2cache devices, with status
1866 * information this time.
1868 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1869 DATA_TYPE_NVLIST_ARRAY) == 0);
1871 l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1872 for (i = 0; i < sav->sav_count; i++)
1873 l2cache[i] = vdev_config_generate(spa,
1874 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1875 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1876 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1878 for (i = 0; i < sav->sav_count; i++)
1879 nvlist_free(l2cache[i]);
1881 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1885 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1888 char *packed = NULL;
1893 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1897 nvsize = *(uint64_t *)db->db_data;
1898 dmu_buf_rele(db, FTAG);
1900 packed = kmem_alloc(nvsize, KM_SLEEP);
1901 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1904 error = nvlist_unpack(packed, nvsize, value, 0);
1905 kmem_free(packed, nvsize);
1911 * Concrete top-level vdevs that are not missing and are not logs. At every
1912 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1915 spa_healthy_core_tvds(spa_t *spa)
1917 vdev_t *rvd = spa->spa_root_vdev;
1920 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1921 vdev_t *vd = rvd->vdev_child[i];
1924 if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1932 * Checks to see if the given vdev could not be opened, in which case we post a
1933 * sysevent to notify the autoreplace code that the device has been removed.
1936 spa_check_removed(vdev_t *vd)
1938 for (uint64_t c = 0; c < vd->vdev_children; c++)
1939 spa_check_removed(vd->vdev_child[c]);
1941 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1942 vdev_is_concrete(vd)) {
1943 zfs_post_autoreplace(vd->vdev_spa, vd);
1944 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1949 spa_check_for_missing_logs(spa_t *spa)
1951 vdev_t *rvd = spa->spa_root_vdev;
1954 * If we're doing a normal import, then build up any additional
1955 * diagnostic information about missing log devices.
1956 * We'll pass this up to the user for further processing.
1958 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1959 nvlist_t **child, *nv;
1962 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1964 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1966 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1967 vdev_t *tvd = rvd->vdev_child[c];
1970 * We consider a device as missing only if it failed
1971 * to open (i.e. offline or faulted is not considered
1974 if (tvd->vdev_islog &&
1975 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1976 child[idx++] = vdev_config_generate(spa, tvd,
1977 B_FALSE, VDEV_CONFIG_MISSING);
1982 fnvlist_add_nvlist_array(nv,
1983 ZPOOL_CONFIG_CHILDREN, child, idx);
1984 fnvlist_add_nvlist(spa->spa_load_info,
1985 ZPOOL_CONFIG_MISSING_DEVICES, nv);
1987 for (uint64_t i = 0; i < idx; i++)
1988 nvlist_free(child[i]);
1991 kmem_free(child, rvd->vdev_children * sizeof (char **));
1994 spa_load_failed(spa, "some log devices are missing");
1995 vdev_dbgmsg_print_tree(rvd, 2);
1996 return (SET_ERROR(ENXIO));
1999 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
2000 vdev_t *tvd = rvd->vdev_child[c];
2002 if (tvd->vdev_islog &&
2003 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
2004 spa_set_log_state(spa, SPA_LOG_CLEAR);
2005 spa_load_note(spa, "some log devices are "
2006 "missing, ZIL is dropped.");
2007 vdev_dbgmsg_print_tree(rvd, 2);
2017 * Check for missing log devices
2020 spa_check_logs(spa_t *spa)
2022 boolean_t rv = B_FALSE;
2023 dsl_pool_t *dp = spa_get_dsl(spa);
2025 switch (spa->spa_log_state) {
2026 case SPA_LOG_MISSING:
2027 /* need to recheck in case slog has been restored */
2028 case SPA_LOG_UNKNOWN:
2029 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2030 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
2032 spa_set_log_state(spa, SPA_LOG_MISSING);
2039 spa_passivate_log(spa_t *spa)
2041 vdev_t *rvd = spa->spa_root_vdev;
2042 boolean_t slog_found = B_FALSE;
2044 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
2046 if (!spa_has_slogs(spa))
2049 for (int c = 0; c < rvd->vdev_children; c++) {
2050 vdev_t *tvd = rvd->vdev_child[c];
2051 metaslab_group_t *mg = tvd->vdev_mg;
2053 if (tvd->vdev_islog) {
2054 metaslab_group_passivate(mg);
2055 slog_found = B_TRUE;
2059 return (slog_found);
2063 spa_activate_log(spa_t *spa)
2065 vdev_t *rvd = spa->spa_root_vdev;
2067 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
2069 for (int c = 0; c < rvd->vdev_children; c++) {
2070 vdev_t *tvd = rvd->vdev_child[c];
2071 metaslab_group_t *mg = tvd->vdev_mg;
2073 if (tvd->vdev_islog)
2074 metaslab_group_activate(mg);
2079 spa_reset_logs(spa_t *spa)
2083 error = dmu_objset_find(spa_name(spa), zil_reset,
2084 NULL, DS_FIND_CHILDREN);
2087 * We successfully offlined the log device, sync out the
2088 * current txg so that the "stubby" block can be removed
2091 txg_wait_synced(spa->spa_dsl_pool, 0);
2097 spa_aux_check_removed(spa_aux_vdev_t *sav)
2101 for (i = 0; i < sav->sav_count; i++)
2102 spa_check_removed(sav->sav_vdevs[i]);
2106 spa_claim_notify(zio_t *zio)
2108 spa_t *spa = zio->io_spa;
2113 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2114 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2115 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2116 mutex_exit(&spa->spa_props_lock);
2119 typedef struct spa_load_error {
2120 uint64_t sle_meta_count;
2121 uint64_t sle_data_count;
2125 spa_load_verify_done(zio_t *zio)
2127 blkptr_t *bp = zio->io_bp;
2128 spa_load_error_t *sle = zio->io_private;
2129 dmu_object_type_t type = BP_GET_TYPE(bp);
2130 int error = zio->io_error;
2131 spa_t *spa = zio->io_spa;
2133 abd_free(zio->io_abd);
2135 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
2136 type != DMU_OT_INTENT_LOG)
2137 atomic_inc_64(&sle->sle_meta_count);
2139 atomic_inc_64(&sle->sle_data_count);
2142 mutex_enter(&spa->spa_scrub_lock);
2143 spa->spa_load_verify_ios--;
2144 cv_broadcast(&spa->spa_scrub_io_cv);
2145 mutex_exit(&spa->spa_scrub_lock);
2149 * Maximum number of concurrent scrub i/os to create while verifying
2150 * a pool while importing it.
2152 int spa_load_verify_maxinflight = 10000;
2153 boolean_t spa_load_verify_metadata = B_TRUE;
2154 boolean_t spa_load_verify_data = B_TRUE;
2156 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_maxinflight, CTLFLAG_RWTUN,
2157 &spa_load_verify_maxinflight, 0,
2158 "Maximum number of concurrent scrub I/Os to create while verifying a "
2159 "pool while importing it");
2161 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_metadata, CTLFLAG_RWTUN,
2162 &spa_load_verify_metadata, 0,
2163 "Check metadata on import?");
2165 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_data, CTLFLAG_RWTUN,
2166 &spa_load_verify_data, 0,
2167 "Check user data on import?");
2171 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2172 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2174 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2177 * Note: normally this routine will not be called if
2178 * spa_load_verify_metadata is not set. However, it may be useful
2179 * to manually set the flag after the traversal has begun.
2181 if (!spa_load_verify_metadata)
2183 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2187 size_t size = BP_GET_PSIZE(bp);
2189 mutex_enter(&spa->spa_scrub_lock);
2190 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
2191 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2192 spa->spa_load_verify_ios++;
2193 mutex_exit(&spa->spa_scrub_lock);
2195 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2196 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2197 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2198 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2204 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2206 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2207 return (SET_ERROR(ENAMETOOLONG));
2213 spa_load_verify(spa_t *spa)
2216 spa_load_error_t sle = { 0 };
2217 zpool_load_policy_t policy;
2218 boolean_t verify_ok = B_FALSE;
2221 zpool_get_load_policy(spa->spa_config, &policy);
2223 if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2226 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2227 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2228 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2230 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2234 rio = zio_root(spa, NULL, &sle,
2235 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2237 if (spa_load_verify_metadata) {
2238 if (spa->spa_extreme_rewind) {
2239 spa_load_note(spa, "performing a complete scan of the "
2240 "pool since extreme rewind is on. This may take "
2241 "a very long time.\n (spa_load_verify_data=%u, "
2242 "spa_load_verify_metadata=%u)",
2243 spa_load_verify_data, spa_load_verify_metadata);
2245 error = traverse_pool(spa, spa->spa_verify_min_txg,
2246 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2247 spa_load_verify_cb, rio);
2250 (void) zio_wait(rio);
2252 spa->spa_load_meta_errors = sle.sle_meta_count;
2253 spa->spa_load_data_errors = sle.sle_data_count;
2255 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2256 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2257 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2258 (u_longlong_t)sle.sle_data_count);
2261 if (spa_load_verify_dryrun ||
2262 (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2263 sle.sle_data_count <= policy.zlp_maxdata)) {
2267 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2268 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2270 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2271 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2272 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2273 VERIFY(nvlist_add_int64(spa->spa_load_info,
2274 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2275 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2276 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2278 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2281 if (spa_load_verify_dryrun)
2285 if (error != ENXIO && error != EIO)
2286 error = SET_ERROR(EIO);
2290 return (verify_ok ? 0 : EIO);
2294 * Find a value in the pool props object.
2297 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2299 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2300 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2304 * Find a value in the pool directory object.
2307 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2309 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2310 name, sizeof (uint64_t), 1, val);
2312 if (error != 0 && (error != ENOENT || log_enoent)) {
2313 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2314 "[error=%d]", name, error);
2321 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2323 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2324 return (SET_ERROR(err));
2328 spa_spawn_aux_threads(spa_t *spa)
2330 ASSERT(spa_writeable(spa));
2332 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2334 spa_start_indirect_condensing_thread(spa);
2336 ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2337 spa->spa_checkpoint_discard_zthr =
2338 zthr_create(spa_checkpoint_discard_thread_check,
2339 spa_checkpoint_discard_thread, spa);
2343 * Fix up config after a partly-completed split. This is done with the
2344 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2345 * pool have that entry in their config, but only the splitting one contains
2346 * a list of all the guids of the vdevs that are being split off.
2348 * This function determines what to do with that list: either rejoin
2349 * all the disks to the pool, or complete the splitting process. To attempt
2350 * the rejoin, each disk that is offlined is marked online again, and
2351 * we do a reopen() call. If the vdev label for every disk that was
2352 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2353 * then we call vdev_split() on each disk, and complete the split.
2355 * Otherwise we leave the config alone, with all the vdevs in place in
2356 * the original pool.
2359 spa_try_repair(spa_t *spa, nvlist_t *config)
2366 boolean_t attempt_reopen;
2368 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2371 /* check that the config is complete */
2372 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2373 &glist, &gcount) != 0)
2376 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2378 /* attempt to online all the vdevs & validate */
2379 attempt_reopen = B_TRUE;
2380 for (i = 0; i < gcount; i++) {
2381 if (glist[i] == 0) /* vdev is hole */
2384 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2385 if (vd[i] == NULL) {
2387 * Don't bother attempting to reopen the disks;
2388 * just do the split.
2390 attempt_reopen = B_FALSE;
2392 /* attempt to re-online it */
2393 vd[i]->vdev_offline = B_FALSE;
2397 if (attempt_reopen) {
2398 vdev_reopen(spa->spa_root_vdev);
2400 /* check each device to see what state it's in */
2401 for (extracted = 0, i = 0; i < gcount; i++) {
2402 if (vd[i] != NULL &&
2403 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2410 * If every disk has been moved to the new pool, or if we never
2411 * even attempted to look at them, then we split them off for
2414 if (!attempt_reopen || gcount == extracted) {
2415 for (i = 0; i < gcount; i++)
2418 vdev_reopen(spa->spa_root_vdev);
2421 kmem_free(vd, gcount * sizeof (vdev_t *));
2425 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2427 char *ereport = FM_EREPORT_ZFS_POOL;
2430 spa->spa_load_state = state;
2432 gethrestime(&spa->spa_loaded_ts);
2433 error = spa_load_impl(spa, type, &ereport);
2436 * Don't count references from objsets that are already closed
2437 * and are making their way through the eviction process.
2439 spa_evicting_os_wait(spa);
2440 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
2442 if (error != EEXIST) {
2443 spa->spa_loaded_ts.tv_sec = 0;
2444 spa->spa_loaded_ts.tv_nsec = 0;
2446 if (error != EBADF) {
2447 zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2450 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2457 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2458 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2459 * spa's per-vdev ZAP list.
2462 vdev_count_verify_zaps(vdev_t *vd)
2464 spa_t *spa = vd->vdev_spa;
2466 if (vd->vdev_top_zap != 0) {
2468 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2469 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2471 if (vd->vdev_leaf_zap != 0) {
2473 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2474 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2477 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2478 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2485 * Determine whether the activity check is required.
2488 spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
2492 uint64_t hostid = 0;
2493 uint64_t tryconfig_txg = 0;
2494 uint64_t tryconfig_timestamp = 0;
2495 uint16_t tryconfig_mmp_seq = 0;
2498 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2499 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2500 (void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
2502 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2503 &tryconfig_timestamp);
2504 (void) nvlist_lookup_uint16(nvinfo, ZPOOL_CONFIG_MMP_SEQ,
2505 &tryconfig_mmp_seq);
2508 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
2511 * Disable the MMP activity check - This is used by zdb which
2512 * is intended to be used on potentially active pools.
2514 if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
2518 * Skip the activity check when the MMP feature is disabled.
2520 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
2524 * If the tryconfig_ values are nonzero, they are the results of an
2525 * earlier tryimport. If they all match the uberblock we just found,
2526 * then the pool has not changed and we return false so we do not test
2529 if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
2530 tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp &&
2531 tryconfig_mmp_seq && tryconfig_mmp_seq ==
2532 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0))
2536 * Allow the activity check to be skipped when importing the pool
2537 * on the same host which last imported it. Since the hostid from
2538 * configuration may be stale use the one read from the label.
2540 if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
2541 hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
2543 if (hostid == spa_get_hostid())
2547 * Skip the activity test when the pool was cleanly exported.
2549 if (state != POOL_STATE_ACTIVE)
2556 * Nanoseconds the activity check must watch for changes on-disk.
2559 spa_activity_check_duration(spa_t *spa, uberblock_t *ub)
2561 uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
2562 uint64_t multihost_interval = MSEC2NSEC(
2563 MMP_INTERVAL_OK(zfs_multihost_interval));
2564 uint64_t import_delay = MAX(NANOSEC, import_intervals *
2565 multihost_interval);
2568 * Local tunables determine a minimum duration except for the case
2569 * where we know when the remote host will suspend the pool if MMP
2570 * writes do not land.
2572 * See Big Theory comment at the top of mmp.c for the reasoning behind
2573 * these cases and times.
2576 ASSERT(MMP_IMPORT_SAFETY_FACTOR >= 100);
2578 if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
2579 MMP_FAIL_INT(ub) > 0) {
2581 /* MMP on remote host will suspend pool after failed writes */
2582 import_delay = MMP_FAIL_INT(ub) * MSEC2NSEC(MMP_INTERVAL(ub)) *
2583 MMP_IMPORT_SAFETY_FACTOR / 100;
2585 zfs_dbgmsg("fail_intvals>0 import_delay=%llu ub_mmp "
2586 "mmp_fails=%llu ub_mmp mmp_interval=%llu "
2587 "import_intervals=%u", import_delay, MMP_FAIL_INT(ub),
2588 MMP_INTERVAL(ub), import_intervals);
2590 } else if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
2591 MMP_FAIL_INT(ub) == 0) {
2593 /* MMP on remote host will never suspend pool */
2594 import_delay = MAX(import_delay, (MSEC2NSEC(MMP_INTERVAL(ub)) +
2595 ub->ub_mmp_delay) * import_intervals);
2597 zfs_dbgmsg("fail_intvals=0 import_delay=%llu ub_mmp "
2598 "mmp_interval=%llu ub_mmp_delay=%llu "
2599 "import_intervals=%u", import_delay, MMP_INTERVAL(ub),
2600 ub->ub_mmp_delay, import_intervals);
2602 } else if (MMP_VALID(ub)) {
2604 * zfs-0.7 compatability case
2607 import_delay = MAX(import_delay, (multihost_interval +
2608 ub->ub_mmp_delay) * import_intervals);
2610 zfs_dbgmsg("import_delay=%llu ub_mmp_delay=%llu "
2611 "import_intervals=%u leaves=%u", import_delay,
2612 ub->ub_mmp_delay, import_intervals,
2613 vdev_count_leaves(spa));
2615 /* Using local tunings is the only reasonable option */
2616 zfs_dbgmsg("pool last imported on non-MMP aware "
2617 "host using import_delay=%llu multihost_interval=%llu "
2618 "import_intervals=%u", import_delay, multihost_interval,
2622 return (import_delay);
2626 * Perform the import activity check. If the user canceled the import or
2627 * we detected activity then fail.
2630 spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
2632 uint64_t txg = ub->ub_txg;
2633 uint64_t timestamp = ub->ub_timestamp;
2634 uint64_t mmp_config = ub->ub_mmp_config;
2635 uint16_t mmp_seq = MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0;
2636 uint64_t import_delay;
2637 hrtime_t import_expire;
2638 nvlist_t *mmp_label = NULL;
2639 vdev_t *rvd = spa->spa_root_vdev;
2644 cv_init(&cv, NULL, CV_DEFAULT, NULL);
2645 mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
2649 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
2650 * during the earlier tryimport. If the txg recorded there is 0 then
2651 * the pool is known to be active on another host.
2653 * Otherwise, the pool might be in use on another host. Check for
2654 * changes in the uberblocks on disk if necessary.
2656 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2657 nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
2658 ZPOOL_CONFIG_LOAD_INFO);
2660 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
2661 fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
2662 vdev_uberblock_load(rvd, ub, &mmp_label);
2663 error = SET_ERROR(EREMOTEIO);
2668 import_delay = spa_activity_check_duration(spa, ub);
2670 /* Add a small random factor in case of simultaneous imports (0-25%) */
2671 import_delay += import_delay * spa_get_random(250) / 1000;
2673 import_expire = gethrtime() + import_delay;
2675 while (gethrtime() < import_expire) {
2676 vdev_uberblock_load(rvd, ub, &mmp_label);
2678 if (txg != ub->ub_txg || timestamp != ub->ub_timestamp ||
2679 mmp_seq != (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0)) {
2680 zfs_dbgmsg("multihost activity detected "
2681 "txg %llu ub_txg %llu "
2682 "timestamp %llu ub_timestamp %llu "
2683 "mmp_config %#llx ub_mmp_config %#llx",
2684 txg, ub->ub_txg, timestamp, ub->ub_timestamp,
2685 mmp_config, ub->ub_mmp_config);
2687 error = SET_ERROR(EREMOTEIO);
2692 nvlist_free(mmp_label);
2695 error = cv_timedwait_sig(&cv, &mtx, hz);
2696 #if defined(illumos) || !defined(_KERNEL)
2699 if (error != EWOULDBLOCK) {
2701 error = SET_ERROR(EINTR);
2709 mutex_destroy(&mtx);
2713 * If the pool is determined to be active store the status in the
2714 * spa->spa_load_info nvlist. If the remote hostname or hostid are
2715 * available from configuration read from disk store them as well.
2716 * This allows 'zpool import' to generate a more useful message.
2718 * ZPOOL_CONFIG_MMP_STATE - observed pool status (mandatory)
2719 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
2720 * ZPOOL_CONFIG_MMP_HOSTID - hostid from the active pool
2722 if (error == EREMOTEIO) {
2723 char *hostname = "<unknown>";
2724 uint64_t hostid = 0;
2727 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
2728 hostname = fnvlist_lookup_string(mmp_label,
2729 ZPOOL_CONFIG_HOSTNAME);
2730 fnvlist_add_string(spa->spa_load_info,
2731 ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
2734 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
2735 hostid = fnvlist_lookup_uint64(mmp_label,
2736 ZPOOL_CONFIG_HOSTID);
2737 fnvlist_add_uint64(spa->spa_load_info,
2738 ZPOOL_CONFIG_MMP_HOSTID, hostid);
2742 fnvlist_add_uint64(spa->spa_load_info,
2743 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
2744 fnvlist_add_uint64(spa->spa_load_info,
2745 ZPOOL_CONFIG_MMP_TXG, 0);
2747 error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
2751 nvlist_free(mmp_label);
2757 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2761 uint64_t myhostid = 0;
2763 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2764 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2765 hostname = fnvlist_lookup_string(mos_config,
2766 ZPOOL_CONFIG_HOSTNAME);
2768 myhostid = zone_get_hostid(NULL);
2770 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2771 cmn_err(CE_WARN, "pool '%s' could not be "
2772 "loaded as it was last accessed by "
2773 "another system (host: %s hostid: 0x%llx). "
2774 "See: http://illumos.org/msg/ZFS-8000-EY",
2775 spa_name(spa), hostname, (u_longlong_t)hostid);
2776 spa_load_failed(spa, "hostid verification failed: pool "
2777 "last accessed by host: %s (hostid: 0x%llx)",
2778 hostname, (u_longlong_t)hostid);
2779 return (SET_ERROR(EBADF));
2787 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2790 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2797 * Versioning wasn't explicitly added to the label until later, so if
2798 * it's not present treat it as the initial version.
2800 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2801 &spa->spa_ubsync.ub_version) != 0)
2802 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2804 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2805 spa_load_failed(spa, "invalid config provided: '%s' missing",
2806 ZPOOL_CONFIG_POOL_GUID);
2807 return (SET_ERROR(EINVAL));
2811 * If we are doing an import, ensure that the pool is not already
2812 * imported by checking if its pool guid already exists in the
2815 * The only case that we allow an already imported pool to be
2816 * imported again, is when the pool is checkpointed and we want to
2817 * look at its checkpointed state from userland tools like zdb.
2820 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2821 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2822 spa_guid_exists(pool_guid, 0)) {
2824 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2825 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2826 spa_guid_exists(pool_guid, 0) &&
2827 !spa_importing_readonly_checkpoint(spa)) {
2829 spa_load_failed(spa, "a pool with guid %llu is already open",
2830 (u_longlong_t)pool_guid);
2831 return (SET_ERROR(EEXIST));
2834 spa->spa_config_guid = pool_guid;
2836 nvlist_free(spa->spa_load_info);
2837 spa->spa_load_info = fnvlist_alloc();
2839 ASSERT(spa->spa_comment == NULL);
2840 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2841 spa->spa_comment = spa_strdup(comment);
2843 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2844 &spa->spa_config_txg);
2846 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2847 spa->spa_config_splitting = fnvlist_dup(nvl);
2849 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2850 spa_load_failed(spa, "invalid config provided: '%s' missing",
2851 ZPOOL_CONFIG_VDEV_TREE);
2852 return (SET_ERROR(EINVAL));
2856 * Create "The Godfather" zio to hold all async IOs
2858 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2860 for (int i = 0; i < max_ncpus; i++) {
2861 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2862 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2863 ZIO_FLAG_GODFATHER);
2867 * Parse the configuration into a vdev tree. We explicitly set the
2868 * value that will be returned by spa_version() since parsing the
2869 * configuration requires knowing the version number.
2871 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2872 parse = (type == SPA_IMPORT_EXISTING ?
2873 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2874 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2875 spa_config_exit(spa, SCL_ALL, FTAG);
2878 spa_load_failed(spa, "unable to parse config [error=%d]",
2883 ASSERT(spa->spa_root_vdev == rvd);
2884 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2885 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2887 if (type != SPA_IMPORT_ASSEMBLE) {
2888 ASSERT(spa_guid(spa) == pool_guid);
2895 * Recursively open all vdevs in the vdev tree. This function is called twice:
2896 * first with the untrusted config, then with the trusted config.
2899 spa_ld_open_vdevs(spa_t *spa)
2904 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2905 * missing/unopenable for the root vdev to be still considered openable.
2907 if (spa->spa_trust_config) {
2908 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2909 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2910 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2911 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2912 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2914 spa->spa_missing_tvds_allowed = 0;
2917 spa->spa_missing_tvds_allowed =
2918 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2920 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2921 error = vdev_open(spa->spa_root_vdev);
2922 spa_config_exit(spa, SCL_ALL, FTAG);
2924 if (spa->spa_missing_tvds != 0) {
2925 spa_load_note(spa, "vdev tree has %lld missing top-level "
2926 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2927 if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2929 * Although theoretically we could allow users to open
2930 * incomplete pools in RW mode, we'd need to add a lot
2931 * of extra logic (e.g. adjust pool space to account
2932 * for missing vdevs).
2933 * This limitation also prevents users from accidentally
2934 * opening the pool in RW mode during data recovery and
2935 * damaging it further.
2937 spa_load_note(spa, "pools with missing top-level "
2938 "vdevs can only be opened in read-only mode.");
2939 error = SET_ERROR(ENXIO);
2941 spa_load_note(spa, "current settings allow for maximum "
2942 "%lld missing top-level vdevs at this stage.",
2943 (u_longlong_t)spa->spa_missing_tvds_allowed);
2947 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2950 if (spa->spa_missing_tvds != 0 || error != 0)
2951 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2957 * We need to validate the vdev labels against the configuration that
2958 * we have in hand. This function is called twice: first with an untrusted
2959 * config, then with a trusted config. The validation is more strict when the
2960 * config is trusted.
2963 spa_ld_validate_vdevs(spa_t *spa)
2966 vdev_t *rvd = spa->spa_root_vdev;
2968 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2969 error = vdev_validate(rvd);
2970 spa_config_exit(spa, SCL_ALL, FTAG);
2973 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2977 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2978 spa_load_failed(spa, "cannot open vdev tree after invalidating "
2980 vdev_dbgmsg_print_tree(rvd, 2);
2981 return (SET_ERROR(ENXIO));
2988 spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2990 spa->spa_state = POOL_STATE_ACTIVE;
2991 spa->spa_ubsync = spa->spa_uberblock;
2992 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2993 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2994 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2995 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2996 spa->spa_claim_max_txg = spa->spa_first_txg;
2997 spa->spa_prev_software_version = ub->ub_software_version;
3001 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
3003 vdev_t *rvd = spa->spa_root_vdev;
3005 uberblock_t *ub = &spa->spa_uberblock;
3006 boolean_t activity_check = B_FALSE;
3009 * If we are opening the checkpointed state of the pool by
3010 * rewinding to it, at this point we will have written the
3011 * checkpointed uberblock to the vdev labels, so searching
3012 * the labels will find the right uberblock. However, if
3013 * we are opening the checkpointed state read-only, we have
3014 * not modified the labels. Therefore, we must ignore the
3015 * labels and continue using the spa_uberblock that was set
3016 * by spa_ld_checkpoint_rewind.
3018 * Note that it would be fine to ignore the labels when
3019 * rewinding (opening writeable) as well. However, if we
3020 * crash just after writing the labels, we will end up
3021 * searching the labels. Doing so in the common case means
3022 * that this code path gets exercised normally, rather than
3023 * just in the edge case.
3025 if (ub->ub_checkpoint_txg != 0 &&
3026 spa_importing_readonly_checkpoint(spa)) {
3027 spa_ld_select_uberblock_done(spa, ub);
3032 * Find the best uberblock.
3034 vdev_uberblock_load(rvd, ub, &label);
3037 * If we weren't able to find a single valid uberblock, return failure.
3039 if (ub->ub_txg == 0) {
3041 spa_load_failed(spa, "no valid uberblock found");
3042 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
3045 spa_load_note(spa, "using uberblock with txg=%llu",
3046 (u_longlong_t)ub->ub_txg);
3049 * For pools which have the multihost property on determine if the
3050 * pool is truly inactive and can be safely imported. Prevent
3051 * hosts which don't have a hostid set from importing the pool.
3053 activity_check = spa_activity_check_required(spa, ub, label,
3055 if (activity_check) {
3056 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
3057 spa_get_hostid() == 0) {
3059 fnvlist_add_uint64(spa->spa_load_info,
3060 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3061 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3064 int error = spa_activity_check(spa, ub, spa->spa_config);
3070 fnvlist_add_uint64(spa->spa_load_info,
3071 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
3072 fnvlist_add_uint64(spa->spa_load_info,
3073 ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
3074 fnvlist_add_uint16(spa->spa_load_info,
3075 ZPOOL_CONFIG_MMP_SEQ,
3076 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0));
3080 * If the pool has an unsupported version we can't open it.
3082 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
3084 spa_load_failed(spa, "version %llu is not supported",
3085 (u_longlong_t)ub->ub_version);
3086 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
3089 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3093 * If we weren't able to find what's necessary for reading the
3094 * MOS in the label, return failure.
3096 if (label == NULL) {
3097 spa_load_failed(spa, "label config unavailable");
3098 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3102 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
3105 spa_load_failed(spa, "invalid label: '%s' missing",
3106 ZPOOL_CONFIG_FEATURES_FOR_READ);
3107 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3112 * Update our in-core representation with the definitive values
3115 nvlist_free(spa->spa_label_features);
3116 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
3122 * Look through entries in the label nvlist's features_for_read. If
3123 * there is a feature listed there which we don't understand then we
3124 * cannot open a pool.
3126 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3127 nvlist_t *unsup_feat;
3129 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
3132 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
3134 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
3135 if (!zfeature_is_supported(nvpair_name(nvp))) {
3136 VERIFY(nvlist_add_string(unsup_feat,
3137 nvpair_name(nvp), "") == 0);
3141 if (!nvlist_empty(unsup_feat)) {
3142 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
3143 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
3144 nvlist_free(unsup_feat);
3145 spa_load_failed(spa, "some features are unsupported");
3146 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3150 nvlist_free(unsup_feat);
3153 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
3154 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3155 spa_try_repair(spa, spa->spa_config);
3156 spa_config_exit(spa, SCL_ALL, FTAG);
3157 nvlist_free(spa->spa_config_splitting);
3158 spa->spa_config_splitting = NULL;
3162 * Initialize internal SPA structures.
3164 spa_ld_select_uberblock_done(spa, ub);
3170 spa_ld_open_rootbp(spa_t *spa)
3173 vdev_t *rvd = spa->spa_root_vdev;
3175 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
3177 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
3178 "[error=%d]", error);
3179 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3181 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
3187 spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
3188 boolean_t reloading)
3190 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
3191 nvlist_t *nv, *mos_config, *policy;
3192 int error = 0, copy_error;
3193 uint64_t healthy_tvds, healthy_tvds_mos;
3194 uint64_t mos_config_txg;
3196 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
3198 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3201 * If we're assembling a pool from a split, the config provided is
3202 * already trusted so there is nothing to do.
3204 if (type == SPA_IMPORT_ASSEMBLE)
3207 healthy_tvds = spa_healthy_core_tvds(spa);
3209 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
3211 spa_load_failed(spa, "unable to retrieve MOS config");
3212 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3216 * If we are doing an open, pool owner wasn't verified yet, thus do
3217 * the verification here.
3219 if (spa->spa_load_state == SPA_LOAD_OPEN) {
3220 error = spa_verify_host(spa, mos_config);
3222 nvlist_free(mos_config);
3227 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
3229 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3232 * Build a new vdev tree from the trusted config
3234 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
3237 * Vdev paths in the MOS may be obsolete. If the untrusted config was
3238 * obtained by scanning /dev/dsk, then it will have the right vdev
3239 * paths. We update the trusted MOS config with this information.
3240 * We first try to copy the paths with vdev_copy_path_strict, which
3241 * succeeds only when both configs have exactly the same vdev tree.
3242 * If that fails, we fall back to a more flexible method that has a
3243 * best effort policy.
3245 copy_error = vdev_copy_path_strict(rvd, mrvd);
3246 if (copy_error != 0 || spa_load_print_vdev_tree) {
3247 spa_load_note(spa, "provided vdev tree:");
3248 vdev_dbgmsg_print_tree(rvd, 2);
3249 spa_load_note(spa, "MOS vdev tree:");
3250 vdev_dbgmsg_print_tree(mrvd, 2);
3252 if (copy_error != 0) {
3253 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
3254 "back to vdev_copy_path_relaxed");
3255 vdev_copy_path_relaxed(rvd, mrvd);
3260 spa->spa_root_vdev = mrvd;
3262 spa_config_exit(spa, SCL_ALL, FTAG);
3265 * We will use spa_config if we decide to reload the spa or if spa_load
3266 * fails and we rewind. We must thus regenerate the config using the
3267 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
3268 * pass settings on how to load the pool and is not stored in the MOS.
3269 * We copy it over to our new, trusted config.
3271 mos_config_txg = fnvlist_lookup_uint64(mos_config,
3272 ZPOOL_CONFIG_POOL_TXG);
3273 nvlist_free(mos_config);
3274 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
3275 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
3277 fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
3278 spa_config_set(spa, mos_config);
3279 spa->spa_config_source = SPA_CONFIG_SRC_MOS;
3282 * Now that we got the config from the MOS, we should be more strict
3283 * in checking blkptrs and can make assumptions about the consistency
3284 * of the vdev tree. spa_trust_config must be set to true before opening
3285 * vdevs in order for them to be writeable.
3287 spa->spa_trust_config = B_TRUE;
3290 * Open and validate the new vdev tree
3292 error = spa_ld_open_vdevs(spa);
3296 error = spa_ld_validate_vdevs(spa);
3300 if (copy_error != 0 || spa_load_print_vdev_tree) {
3301 spa_load_note(spa, "final vdev tree:");
3302 vdev_dbgmsg_print_tree(rvd, 2);
3305 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
3306 !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
3308 * Sanity check to make sure that we are indeed loading the
3309 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
3310 * in the config provided and they happened to be the only ones
3311 * to have the latest uberblock, we could involuntarily perform
3312 * an extreme rewind.
3314 healthy_tvds_mos = spa_healthy_core_tvds(spa);
3315 if (healthy_tvds_mos - healthy_tvds >=
3316 SPA_SYNC_MIN_VDEVS) {
3317 spa_load_note(spa, "config provided misses too many "
3318 "top-level vdevs compared to MOS (%lld vs %lld). ",
3319 (u_longlong_t)healthy_tvds,
3320 (u_longlong_t)healthy_tvds_mos);
3321 spa_load_note(spa, "vdev tree:");
3322 vdev_dbgmsg_print_tree(rvd, 2);
3324 spa_load_failed(spa, "config was already "
3325 "provided from MOS. Aborting.");
3326 return (spa_vdev_err(rvd,
3327 VDEV_AUX_CORRUPT_DATA, EIO));
3329 spa_load_note(spa, "spa must be reloaded using MOS "
3331 return (SET_ERROR(EAGAIN));
3335 error = spa_check_for_missing_logs(spa);
3337 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
3339 if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
3340 spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
3341 "guid sum (%llu != %llu)",
3342 (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
3343 (u_longlong_t)rvd->vdev_guid_sum);
3344 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
3352 spa_ld_open_indirect_vdev_metadata(spa_t *spa)
3355 vdev_t *rvd = spa->spa_root_vdev;
3358 * Everything that we read before spa_remove_init() must be stored
3359 * on concreted vdevs. Therefore we do this as early as possible.
3361 error = spa_remove_init(spa);
3363 spa_load_failed(spa, "spa_remove_init failed [error=%d]",
3365 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3369 * Retrieve information needed to condense indirect vdev mappings.
3371 error = spa_condense_init(spa);
3373 spa_load_failed(spa, "spa_condense_init failed [error=%d]",
3375 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3382 spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
3385 vdev_t *rvd = spa->spa_root_vdev;
3387 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
3388 boolean_t missing_feat_read = B_FALSE;
3389 nvlist_t *unsup_feat, *enabled_feat;
3391 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
3392 &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
3393 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3396 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
3397 &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
3398 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3401 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
3402 &spa->spa_feat_desc_obj, B_TRUE) != 0) {
3403 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3406 enabled_feat = fnvlist_alloc();
3407 unsup_feat = fnvlist_alloc();
3409 if (!spa_features_check(spa, B_FALSE,
3410 unsup_feat, enabled_feat))
3411 missing_feat_read = B_TRUE;
3413 if (spa_writeable(spa) ||
3414 spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3415 if (!spa_features_check(spa, B_TRUE,
3416 unsup_feat, enabled_feat)) {
3417 *missing_feat_writep = B_TRUE;
3421 fnvlist_add_nvlist(spa->spa_load_info,
3422 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3424 if (!nvlist_empty(unsup_feat)) {
3425 fnvlist_add_nvlist(spa->spa_load_info,
3426 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3429 fnvlist_free(enabled_feat);
3430 fnvlist_free(unsup_feat);
3432 if (!missing_feat_read) {
3433 fnvlist_add_boolean(spa->spa_load_info,
3434 ZPOOL_CONFIG_CAN_RDONLY);
3438 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3439 * twofold: to determine whether the pool is available for
3440 * import in read-write mode and (if it is not) whether the
3441 * pool is available for import in read-only mode. If the pool
3442 * is available for import in read-write mode, it is displayed
3443 * as available in userland; if it is not available for import
3444 * in read-only mode, it is displayed as unavailable in
3445 * userland. If the pool is available for import in read-only
3446 * mode but not read-write mode, it is displayed as unavailable
3447 * in userland with a special note that the pool is actually
3448 * available for open in read-only mode.
3450 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3451 * missing a feature for write, we must first determine whether
3452 * the pool can be opened read-only before returning to
3453 * userland in order to know whether to display the
3454 * abovementioned note.
3456 if (missing_feat_read || (*missing_feat_writep &&
3457 spa_writeable(spa))) {
3458 spa_load_failed(spa, "pool uses unsupported features");
3459 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3464 * Load refcounts for ZFS features from disk into an in-memory
3465 * cache during SPA initialization.
3467 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
3470 error = feature_get_refcount_from_disk(spa,
3471 &spa_feature_table[i], &refcount);
3473 spa->spa_feat_refcount_cache[i] = refcount;
3474 } else if (error == ENOTSUP) {
3475 spa->spa_feat_refcount_cache[i] =
3476 SPA_FEATURE_DISABLED;
3478 spa_load_failed(spa, "error getting refcount "
3479 "for feature %s [error=%d]",
3480 spa_feature_table[i].fi_guid, error);
3481 return (spa_vdev_err(rvd,
3482 VDEV_AUX_CORRUPT_DATA, EIO));
3487 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3488 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
3489 &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
3490 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3497 spa_ld_load_special_directories(spa_t *spa)
3500 vdev_t *rvd = spa->spa_root_vdev;
3502 spa->spa_is_initializing = B_TRUE;
3503 error = dsl_pool_open(spa->spa_dsl_pool);
3504 spa->spa_is_initializing = B_FALSE;
3506 spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3507 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3514 spa_ld_get_props(spa_t *spa)
3518 vdev_t *rvd = spa->spa_root_vdev;
3520 /* Grab the secret checksum salt from the MOS. */
3521 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3522 DMU_POOL_CHECKSUM_SALT, 1,
3523 sizeof (spa->spa_cksum_salt.zcs_bytes),
3524 spa->spa_cksum_salt.zcs_bytes);
3525 if (error == ENOENT) {
3526 /* Generate a new salt for subsequent use */
3527 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3528 sizeof (spa->spa_cksum_salt.zcs_bytes));
3529 } else if (error != 0) {
3530 spa_load_failed(spa, "unable to retrieve checksum salt from "
3531 "MOS [error=%d]", error);
3532 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3535 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3536 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3537 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3539 spa_load_failed(spa, "error opening deferred-frees bpobj "
3540 "[error=%d]", error);
3541 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3545 * Load the bit that tells us to use the new accounting function
3546 * (raid-z deflation). If we have an older pool, this will not
3549 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3550 if (error != 0 && error != ENOENT)
3551 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3553 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3554 &spa->spa_creation_version, B_FALSE);
3555 if (error != 0 && error != ENOENT)
3556 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3559 * Load the persistent error log. If we have an older pool, this will
3562 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3564 if (error != 0 && error != ENOENT)
3565 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3567 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3568 &spa->spa_errlog_scrub, B_FALSE);
3569 if (error != 0 && error != ENOENT)
3570 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3573 * Load the history object. If we have an older pool, this
3574 * will not be present.
3576 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3577 if (error != 0 && error != ENOENT)
3578 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3581 * Load the per-vdev ZAP map. If we have an older pool, this will not
3582 * be present; in this case, defer its creation to a later time to
3583 * avoid dirtying the MOS this early / out of sync context. See
3584 * spa_sync_config_object.
3587 /* The sentinel is only available in the MOS config. */
3588 nvlist_t *mos_config;
3589 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3590 spa_load_failed(spa, "unable to retrieve MOS config");
3591 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3594 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3595 &spa->spa_all_vdev_zaps, B_FALSE);
3597 if (error == ENOENT) {
3598 VERIFY(!nvlist_exists(mos_config,
3599 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3600 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3601 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3602 } else if (error != 0) {
3603 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3604 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3606 * An older version of ZFS overwrote the sentinel value, so
3607 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3608 * destruction to later; see spa_sync_config_object.
3610 spa->spa_avz_action = AVZ_ACTION_DESTROY;
3612 * We're assuming that no vdevs have had their ZAPs created
3613 * before this. Better be sure of it.
3615 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3617 nvlist_free(mos_config);
3619 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3621 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3623 if (error && error != ENOENT)
3624 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3627 uint64_t autoreplace;
3629 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3630 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3631 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3632 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3633 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3634 spa_prop_find(spa, ZPOOL_PROP_MULTIHOST, &spa->spa_multihost);
3635 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3636 &spa->spa_dedup_ditto);
3638 spa->spa_autoreplace = (autoreplace != 0);
3642 * If we are importing a pool with missing top-level vdevs,
3643 * we enforce that the pool doesn't panic or get suspended on
3644 * error since the likelihood of missing data is extremely high.
3646 if (spa->spa_missing_tvds > 0 &&
3647 spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3648 spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3649 spa_load_note(spa, "forcing failmode to 'continue' "
3650 "as some top level vdevs are missing");
3651 spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3658 spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3661 vdev_t *rvd = spa->spa_root_vdev;
3664 * If we're assembling the pool from the split-off vdevs of
3665 * an existing pool, we don't want to attach the spares & cache
3670 * Load any hot spares for this pool.
3672 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3674 if (error != 0 && error != ENOENT)
3675 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3676 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3677 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3678 if (load_nvlist(spa, spa->spa_spares.sav_object,
3679 &spa->spa_spares.sav_config) != 0) {
3680 spa_load_failed(spa, "error loading spares nvlist");
3681 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3684 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3685 spa_load_spares(spa);
3686 spa_config_exit(spa, SCL_ALL, FTAG);
3687 } else if (error == 0) {
3688 spa->spa_spares.sav_sync = B_TRUE;
3692 * Load any level 2 ARC devices for this pool.
3694 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3695 &spa->spa_l2cache.sav_object, B_FALSE);
3696 if (error != 0 && error != ENOENT)
3697 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3698 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3699 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3700 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3701 &spa->spa_l2cache.sav_config) != 0) {
3702 spa_load_failed(spa, "error loading l2cache nvlist");
3703 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3706 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3707 spa_load_l2cache(spa);
3708 spa_config_exit(spa, SCL_ALL, FTAG);
3709 } else if (error == 0) {
3710 spa->spa_l2cache.sav_sync = B_TRUE;
3717 spa_ld_load_vdev_metadata(spa_t *spa)
3720 vdev_t *rvd = spa->spa_root_vdev;
3723 * If the 'multihost' property is set, then never allow a pool to
3724 * be imported when the system hostid is zero. The exception to
3725 * this rule is zdb which is always allowed to access pools.
3727 if (spa_multihost(spa) && spa_get_hostid() == 0 &&
3728 (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP) == 0) {
3729 fnvlist_add_uint64(spa->spa_load_info,
3730 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3731 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3735 * If the 'autoreplace' property is set, then post a resource notifying
3736 * the ZFS DE that it should not issue any faults for unopenable
3737 * devices. We also iterate over the vdevs, and post a sysevent for any
3738 * unopenable vdevs so that the normal autoreplace handler can take
3741 if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3742 spa_check_removed(spa->spa_root_vdev);
3744 * For the import case, this is done in spa_import(), because
3745 * at this point we're using the spare definitions from
3746 * the MOS config, not necessarily from the userland config.
3748 if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3749 spa_aux_check_removed(&spa->spa_spares);
3750 spa_aux_check_removed(&spa->spa_l2cache);
3755 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3757 error = vdev_load(rvd);
3759 spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3760 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3764 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3766 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3767 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3768 spa_config_exit(spa, SCL_ALL, FTAG);
3774 spa_ld_load_dedup_tables(spa_t *spa)
3777 vdev_t *rvd = spa->spa_root_vdev;
3779 error = ddt_load(spa);
3781 spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3782 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3789 spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3791 vdev_t *rvd = spa->spa_root_vdev;
3793 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3794 boolean_t missing = spa_check_logs(spa);
3796 if (spa->spa_missing_tvds != 0) {
3797 spa_load_note(spa, "spa_check_logs failed "
3798 "so dropping the logs");
3800 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3801 spa_load_failed(spa, "spa_check_logs failed");
3802 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3812 spa_ld_verify_pool_data(spa_t *spa)
3815 vdev_t *rvd = spa->spa_root_vdev;
3818 * We've successfully opened the pool, verify that we're ready
3819 * to start pushing transactions.
3821 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3822 error = spa_load_verify(spa);
3824 spa_load_failed(spa, "spa_load_verify failed "
3825 "[error=%d]", error);
3826 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3835 spa_ld_claim_log_blocks(spa_t *spa)
3838 dsl_pool_t *dp = spa_get_dsl(spa);
3841 * Claim log blocks that haven't been committed yet.
3842 * This must all happen in a single txg.
3843 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3844 * invoked from zil_claim_log_block()'s i/o done callback.
3845 * Price of rollback is that we abandon the log.
3847 spa->spa_claiming = B_TRUE;
3849 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3850 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3851 zil_claim, tx, DS_FIND_CHILDREN);
3854 spa->spa_claiming = B_FALSE;
3856 spa_set_log_state(spa, SPA_LOG_GOOD);
3860 spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3861 boolean_t update_config_cache)
3863 vdev_t *rvd = spa->spa_root_vdev;
3864 int need_update = B_FALSE;
3867 * If the config cache is stale, or we have uninitialized
3868 * metaslabs (see spa_vdev_add()), then update the config.
3870 * If this is a verbatim import, trust the current
3871 * in-core spa_config and update the disk labels.
3873 if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
3874 spa->spa_load_state == SPA_LOAD_IMPORT ||
3875 spa->spa_load_state == SPA_LOAD_RECOVER ||
3876 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3877 need_update = B_TRUE;
3879 for (int c = 0; c < rvd->vdev_children; c++)
3880 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3881 need_update = B_TRUE;
3884 * Update the config cache asychronously in case we're the
3885 * root pool, in which case the config cache isn't writable yet.
3888 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3892 spa_ld_prepare_for_reload(spa_t *spa)
3894 int mode = spa->spa_mode;
3895 int async_suspended = spa->spa_async_suspended;
3898 spa_deactivate(spa);
3899 spa_activate(spa, mode);
3902 * We save the value of spa_async_suspended as it gets reset to 0 by
3903 * spa_unload(). We want to restore it back to the original value before
3904 * returning as we might be calling spa_async_resume() later.
3906 spa->spa_async_suspended = async_suspended;
3910 spa_ld_read_checkpoint_txg(spa_t *spa)
3912 uberblock_t checkpoint;
3915 ASSERT0(spa->spa_checkpoint_txg);
3916 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3918 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3919 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3920 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3922 if (error == ENOENT)
3928 ASSERT3U(checkpoint.ub_txg, !=, 0);
3929 ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3930 ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3931 spa->spa_checkpoint_txg = checkpoint.ub_txg;
3932 spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3938 spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
3942 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3943 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3946 * Never trust the config that is provided unless we are assembling
3947 * a pool following a split.
3948 * This means don't trust blkptrs and the vdev tree in general. This
3949 * also effectively puts the spa in read-only mode since
3950 * spa_writeable() checks for spa_trust_config to be true.
3951 * We will later load a trusted config from the MOS.
3953 if (type != SPA_IMPORT_ASSEMBLE)
3954 spa->spa_trust_config = B_FALSE;
3957 * Parse the config provided to create a vdev tree.
3959 error = spa_ld_parse_config(spa, type);
3964 * Now that we have the vdev tree, try to open each vdev. This involves
3965 * opening the underlying physical device, retrieving its geometry and
3966 * probing the vdev with a dummy I/O. The state of each vdev will be set
3967 * based on the success of those operations. After this we'll be ready
3968 * to read from the vdevs.
3970 error = spa_ld_open_vdevs(spa);
3975 * Read the label of each vdev and make sure that the GUIDs stored
3976 * there match the GUIDs in the config provided.
3977 * If we're assembling a new pool that's been split off from an
3978 * existing pool, the labels haven't yet been updated so we skip
3979 * validation for now.
3981 if (type != SPA_IMPORT_ASSEMBLE) {
3982 error = spa_ld_validate_vdevs(spa);
3988 * Read all vdev labels to find the best uberblock (i.e. latest,
3989 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3990 * get the list of features required to read blkptrs in the MOS from
3991 * the vdev label with the best uberblock and verify that our version
3992 * of zfs supports them all.
3994 error = spa_ld_select_uberblock(spa, type);
3999 * Pass that uberblock to the dsl_pool layer which will open the root
4000 * blkptr. This blkptr points to the latest version of the MOS and will
4001 * allow us to read its contents.
4003 error = spa_ld_open_rootbp(spa);
4011 spa_ld_checkpoint_rewind(spa_t *spa)
4013 uberblock_t checkpoint;
4016 ASSERT(MUTEX_HELD(&spa_namespace_lock));
4017 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4019 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
4020 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
4021 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
4024 spa_load_failed(spa, "unable to retrieve checkpointed "
4025 "uberblock from the MOS config [error=%d]", error);
4027 if (error == ENOENT)
4028 error = ZFS_ERR_NO_CHECKPOINT;
4033 ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
4034 ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
4037 * We need to update the txg and timestamp of the checkpointed
4038 * uberblock to be higher than the latest one. This ensures that
4039 * the checkpointed uberblock is selected if we were to close and
4040 * reopen the pool right after we've written it in the vdev labels.
4041 * (also see block comment in vdev_uberblock_compare)
4043 checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
4044 checkpoint.ub_timestamp = gethrestime_sec();
4047 * Set current uberblock to be the checkpointed uberblock.
4049 spa->spa_uberblock = checkpoint;
4052 * If we are doing a normal rewind, then the pool is open for
4053 * writing and we sync the "updated" checkpointed uberblock to
4054 * disk. Once this is done, we've basically rewound the whole
4055 * pool and there is no way back.
4057 * There are cases when we don't want to attempt and sync the
4058 * checkpointed uberblock to disk because we are opening a
4059 * pool as read-only. Specifically, verifying the checkpointed
4060 * state with zdb, and importing the checkpointed state to get
4061 * a "preview" of its content.
4063 if (spa_writeable(spa)) {
4064 vdev_t *rvd = spa->spa_root_vdev;
4066 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4067 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
4069 int children = rvd->vdev_children;
4070 int c0 = spa_get_random(children);
4072 for (int c = 0; c < children; c++) {
4073 vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
4075 /* Stop when revisiting the first vdev */
4076 if (c > 0 && svd[0] == vd)
4079 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
4080 !vdev_is_concrete(vd))
4083 svd[svdcount++] = vd;
4084 if (svdcount == SPA_SYNC_MIN_VDEVS)
4087 error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
4089 spa->spa_last_synced_guid = rvd->vdev_guid;
4090 spa_config_exit(spa, SCL_ALL, FTAG);
4093 spa_load_failed(spa, "failed to write checkpointed "
4094 "uberblock to the vdev labels [error=%d]", error);
4103 spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
4104 boolean_t *update_config_cache)
4109 * Parse the config for pool, open and validate vdevs,
4110 * select an uberblock, and use that uberblock to open
4113 error = spa_ld_mos_init(spa, type);
4118 * Retrieve the trusted config stored in the MOS and use it to create
4119 * a new, exact version of the vdev tree, then reopen all vdevs.
4121 error = spa_ld_trusted_config(spa, type, B_FALSE);
4122 if (error == EAGAIN) {
4123 if (update_config_cache != NULL)
4124 *update_config_cache = B_TRUE;
4127 * Redo the loading process with the trusted config if it is
4128 * too different from the untrusted config.
4130 spa_ld_prepare_for_reload(spa);
4131 spa_load_note(spa, "RELOADING");
4132 error = spa_ld_mos_init(spa, type);
4136 error = spa_ld_trusted_config(spa, type, B_TRUE);
4140 } else if (error != 0) {
4148 * Load an existing storage pool, using the config provided. This config
4149 * describes which vdevs are part of the pool and is later validated against
4150 * partial configs present in each vdev's label and an entire copy of the
4151 * config stored in the MOS.
4154 spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
4157 boolean_t missing_feat_write = B_FALSE;
4158 boolean_t checkpoint_rewind =
4159 (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4160 boolean_t update_config_cache = B_FALSE;
4162 ASSERT(MUTEX_HELD(&spa_namespace_lock));
4163 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
4165 spa_load_note(spa, "LOADING");
4167 error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
4172 * If we are rewinding to the checkpoint then we need to repeat
4173 * everything we've done so far in this function but this time
4174 * selecting the checkpointed uberblock and using that to open
4177 if (checkpoint_rewind) {
4179 * If we are rewinding to the checkpoint update config cache
4182 update_config_cache = B_TRUE;
4185 * Extract the checkpointed uberblock from the current MOS
4186 * and use this as the pool's uberblock from now on. If the
4187 * pool is imported as writeable we also write the checkpoint
4188 * uberblock to the labels, making the rewind permanent.
4190 error = spa_ld_checkpoint_rewind(spa);
4195 * Redo the loading process process again with the
4196 * checkpointed uberblock.
4198 spa_ld_prepare_for_reload(spa);
4199 spa_load_note(spa, "LOADING checkpointed uberblock");
4200 error = spa_ld_mos_with_trusted_config(spa, type, NULL);
4206 * Retrieve the checkpoint txg if the pool has a checkpoint.
4208 error = spa_ld_read_checkpoint_txg(spa);
4213 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
4214 * from the pool and their contents were re-mapped to other vdevs. Note
4215 * that everything that we read before this step must have been
4216 * rewritten on concrete vdevs after the last device removal was
4217 * initiated. Otherwise we could be reading from indirect vdevs before
4218 * we have loaded their mappings.
4220 error = spa_ld_open_indirect_vdev_metadata(spa);
4225 * Retrieve the full list of active features from the MOS and check if
4226 * they are all supported.
4228 error = spa_ld_check_features(spa, &missing_feat_write);
4233 * Load several special directories from the MOS needed by the dsl_pool
4236 error = spa_ld_load_special_directories(spa);
4241 * Retrieve pool properties from the MOS.
4243 error = spa_ld_get_props(spa);
4248 * Retrieve the list of auxiliary devices - cache devices and spares -
4251 error = spa_ld_open_aux_vdevs(spa, type);
4256 * Load the metadata for all vdevs. Also check if unopenable devices
4257 * should be autoreplaced.
4259 error = spa_ld_load_vdev_metadata(spa);
4263 error = spa_ld_load_dedup_tables(spa);
4268 * Verify the logs now to make sure we don't have any unexpected errors
4269 * when we claim log blocks later.
4271 error = spa_ld_verify_logs(spa, type, ereport);
4275 if (missing_feat_write) {
4276 ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
4279 * At this point, we know that we can open the pool in
4280 * read-only mode but not read-write mode. We now have enough
4281 * information and can return to userland.
4283 return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
4288 * Traverse the last txgs to make sure the pool was left off in a safe
4289 * state. When performing an extreme rewind, we verify the whole pool,
4290 * which can take a very long time.
4292 error = spa_ld_verify_pool_data(spa);
4297 * Calculate the deflated space for the pool. This must be done before
4298 * we write anything to the pool because we'd need to update the space
4299 * accounting using the deflated sizes.
4301 spa_update_dspace(spa);
4304 * We have now retrieved all the information we needed to open the
4305 * pool. If we are importing the pool in read-write mode, a few
4306 * additional steps must be performed to finish the import.
4308 if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
4309 spa->spa_load_max_txg == UINT64_MAX)) {
4310 uint64_t config_cache_txg = spa->spa_config_txg;
4312 ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
4315 * In case of a checkpoint rewind, log the original txg
4316 * of the checkpointed uberblock.
4318 if (checkpoint_rewind) {
4319 spa_history_log_internal(spa, "checkpoint rewind",
4320 NULL, "rewound state to txg=%llu",
4321 (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
4325 * Traverse the ZIL and claim all blocks.
4327 spa_ld_claim_log_blocks(spa);
4330 * Kick-off the syncing thread.
4332 spa->spa_sync_on = B_TRUE;
4333 txg_sync_start(spa->spa_dsl_pool);
4334 mmp_thread_start(spa);
4337 * Wait for all claims to sync. We sync up to the highest
4338 * claimed log block birth time so that claimed log blocks
4339 * don't appear to be from the future. spa_claim_max_txg
4340 * will have been set for us by ZIL traversal operations
4343 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
4346 * Check if we need to request an update of the config. On the
4347 * next sync, we would update the config stored in vdev labels
4348 * and the cachefile (by default /etc/zfs/zpool.cache).
4350 spa_ld_check_for_config_update(spa, config_cache_txg,
4351 update_config_cache);
4354 * Check all DTLs to see if anything needs resilvering.
4356 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
4357 vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
4358 spa_async_request(spa, SPA_ASYNC_RESILVER);
4361 * Log the fact that we booted up (so that we can detect if
4362 * we rebooted in the middle of an operation).
4364 spa_history_log_version(spa, "open");
4366 spa_restart_removal(spa);
4367 spa_spawn_aux_threads(spa);
4370 * Delete any inconsistent datasets.
4373 * Since we may be issuing deletes for clones here,
4374 * we make sure to do so after we've spawned all the
4375 * auxiliary threads above (from which the livelist
4376 * deletion zthr is part of).
4378 (void) dmu_objset_find(spa_name(spa),
4379 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
4382 * Clean up any stale temporary dataset userrefs.
4384 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
4386 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4387 vdev_initialize_restart(spa->spa_root_vdev);
4388 spa_config_exit(spa, SCL_CONFIG, FTAG);
4391 spa_load_note(spa, "LOADED");
4397 spa_load_retry(spa_t *spa, spa_load_state_t state)
4399 int mode = spa->spa_mode;
4402 spa_deactivate(spa);
4404 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
4406 spa_activate(spa, mode);
4407 spa_async_suspend(spa);
4409 spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
4410 (u_longlong_t)spa->spa_load_max_txg);
4412 return (spa_load(spa, state, SPA_IMPORT_EXISTING));
4416 * If spa_load() fails this function will try loading prior txg's. If
4417 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
4418 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
4419 * function will not rewind the pool and will return the same error as
4423 spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4426 nvlist_t *loadinfo = NULL;
4427 nvlist_t *config = NULL;
4428 int load_error, rewind_error;
4429 uint64_t safe_rewind_txg;
4432 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4433 spa->spa_load_max_txg = spa->spa_load_txg;
4434 spa_set_log_state(spa, SPA_LOG_CLEAR);
4436 spa->spa_load_max_txg = max_request;
4437 if (max_request != UINT64_MAX)
4438 spa->spa_extreme_rewind = B_TRUE;
4441 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
4442 if (load_error == 0)
4444 if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4446 * When attempting checkpoint-rewind on a pool with no
4447 * checkpoint, we should not attempt to load uberblocks
4448 * from previous txgs when spa_load fails.
4450 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4451 return (load_error);
4454 if (spa->spa_root_vdev != NULL)
4455 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4457 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4458 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4460 if (rewind_flags & ZPOOL_NEVER_REWIND) {
4461 nvlist_free(config);
4462 return (load_error);
4465 if (state == SPA_LOAD_RECOVER) {
4466 /* Price of rolling back is discarding txgs, including log */
4467 spa_set_log_state(spa, SPA_LOG_CLEAR);
4470 * If we aren't rolling back save the load info from our first
4471 * import attempt so that we can restore it after attempting
4474 loadinfo = spa->spa_load_info;
4475 spa->spa_load_info = fnvlist_alloc();
4478 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4479 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4480 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4481 TXG_INITIAL : safe_rewind_txg;
4484 * Continue as long as we're finding errors, we're still within
4485 * the acceptable rewind range, and we're still finding uberblocks
4487 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4488 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4489 if (spa->spa_load_max_txg < safe_rewind_txg)
4490 spa->spa_extreme_rewind = B_TRUE;
4491 rewind_error = spa_load_retry(spa, state);
4494 spa->spa_extreme_rewind = B_FALSE;
4495 spa->spa_load_max_txg = UINT64_MAX;
4497 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4498 spa_config_set(spa, config);
4500 nvlist_free(config);
4502 if (state == SPA_LOAD_RECOVER) {
4503 ASSERT3P(loadinfo, ==, NULL);
4504 return (rewind_error);
4506 /* Store the rewind info as part of the initial load info */
4507 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4508 spa->spa_load_info);
4510 /* Restore the initial load info */
4511 fnvlist_free(spa->spa_load_info);
4512 spa->spa_load_info = loadinfo;
4514 return (load_error);
4521 * The import case is identical to an open except that the configuration is sent
4522 * down from userland, instead of grabbed from the configuration cache. For the
4523 * case of an open, the pool configuration will exist in the
4524 * POOL_STATE_UNINITIALIZED state.
4526 * The stats information (gen/count/ustats) is used to gather vdev statistics at
4527 * the same time open the pool, without having to keep around the spa_t in some
4531 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4535 spa_load_state_t state = SPA_LOAD_OPEN;
4537 int locked = B_FALSE;
4538 int firstopen = B_FALSE;
4543 * As disgusting as this is, we need to support recursive calls to this
4544 * function because dsl_dir_open() is called during spa_load(), and ends
4545 * up calling spa_open() again. The real fix is to figure out how to
4546 * avoid dsl_dir_open() calling this in the first place.
4548 if (mutex_owner(&spa_namespace_lock) != curthread) {
4549 mutex_enter(&spa_namespace_lock);
4553 if ((spa = spa_lookup(pool)) == NULL) {
4555 mutex_exit(&spa_namespace_lock);
4556 return (SET_ERROR(ENOENT));
4559 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
4560 zpool_load_policy_t policy;
4564 zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
4566 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
4567 state = SPA_LOAD_RECOVER;
4569 spa_activate(spa, spa_mode_global);
4571 if (state != SPA_LOAD_RECOVER)
4572 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4573 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
4575 zfs_dbgmsg("spa_open_common: opening %s", pool);
4576 error = spa_load_best(spa, state, policy.zlp_txg,
4579 if (error == EBADF) {
4581 * If vdev_validate() returns failure (indicated by
4582 * EBADF), it indicates that one of the vdevs indicates
4583 * that the pool has been exported or destroyed. If
4584 * this is the case, the config cache is out of sync and
4585 * we should remove the pool from the namespace.
4588 spa_deactivate(spa);
4589 spa_write_cachefile(spa, B_TRUE, B_TRUE);
4592 mutex_exit(&spa_namespace_lock);
4593 return (SET_ERROR(ENOENT));
4598 * We can't open the pool, but we still have useful
4599 * information: the state of each vdev after the
4600 * attempted vdev_open(). Return this to the user.
4602 if (config != NULL && spa->spa_config) {
4603 VERIFY(nvlist_dup(spa->spa_config, config,
4605 VERIFY(nvlist_add_nvlist(*config,
4606 ZPOOL_CONFIG_LOAD_INFO,
4607 spa->spa_load_info) == 0);
4610 spa_deactivate(spa);
4611 spa->spa_last_open_failed = error;
4613 mutex_exit(&spa_namespace_lock);
4619 spa_open_ref(spa, tag);
4622 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4625 * If we've recovered the pool, pass back any information we
4626 * gathered while doing the load.
4628 if (state == SPA_LOAD_RECOVER) {
4629 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4630 spa->spa_load_info) == 0);
4634 spa->spa_last_open_failed = 0;
4635 spa->spa_last_ubsync_txg = 0;
4636 spa->spa_load_txg = 0;
4637 mutex_exit(&spa_namespace_lock);
4641 zvol_create_minors(spa, spa->spa_name);
4652 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4655 return (spa_open_common(name, spapp, tag, policy, config));
4659 spa_open(const char *name, spa_t **spapp, void *tag)
4661 return (spa_open_common(name, spapp, tag, NULL, NULL));
4665 * Lookup the given spa_t, incrementing the inject count in the process,
4666 * preventing it from being exported or destroyed.
4669 spa_inject_addref(char *name)
4673 mutex_enter(&spa_namespace_lock);
4674 if ((spa = spa_lookup(name)) == NULL) {
4675 mutex_exit(&spa_namespace_lock);
4678 spa->spa_inject_ref++;
4679 mutex_exit(&spa_namespace_lock);
4685 spa_inject_delref(spa_t *spa)
4687 mutex_enter(&spa_namespace_lock);
4688 spa->spa_inject_ref--;
4689 mutex_exit(&spa_namespace_lock);
4693 * Add spares device information to the nvlist.
4696 spa_add_spares(spa_t *spa, nvlist_t *config)
4706 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4708 if (spa->spa_spares.sav_count == 0)
4711 VERIFY(nvlist_lookup_nvlist(config,
4712 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4713 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4714 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4716 VERIFY(nvlist_add_nvlist_array(nvroot,
4717 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4718 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4719 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4722 * Go through and find any spares which have since been
4723 * repurposed as an active spare. If this is the case, update
4724 * their status appropriately.
4726 for (i = 0; i < nspares; i++) {
4727 VERIFY(nvlist_lookup_uint64(spares[i],
4728 ZPOOL_CONFIG_GUID, &guid) == 0);
4729 if (spa_spare_exists(guid, &pool, NULL) &&
4731 VERIFY(nvlist_lookup_uint64_array(
4732 spares[i], ZPOOL_CONFIG_VDEV_STATS,
4733 (uint64_t **)&vs, &vsc) == 0);
4734 vs->vs_state = VDEV_STATE_CANT_OPEN;
4735 vs->vs_aux = VDEV_AUX_SPARED;
4742 * Add l2cache device information to the nvlist, including vdev stats.
4745 spa_add_l2cache(spa_t *spa, nvlist_t *config)
4748 uint_t i, j, nl2cache;
4755 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4757 if (spa->spa_l2cache.sav_count == 0)
4760 VERIFY(nvlist_lookup_nvlist(config,
4761 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4762 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4763 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4764 if (nl2cache != 0) {
4765 VERIFY(nvlist_add_nvlist_array(nvroot,
4766 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4767 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4768 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4771 * Update level 2 cache device stats.
4774 for (i = 0; i < nl2cache; i++) {
4775 VERIFY(nvlist_lookup_uint64(l2cache[i],
4776 ZPOOL_CONFIG_GUID, &guid) == 0);
4779 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4781 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4782 vd = spa->spa_l2cache.sav_vdevs[j];
4788 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4789 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4791 vdev_get_stats(vd, vs);
4797 spa_feature_stats_from_disk(spa_t *spa, nvlist_t *features)
4802 /* We may be unable to read features if pool is suspended. */
4803 if (spa_suspended(spa))
4806 if (spa->spa_feat_for_read_obj != 0) {
4807 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4808 spa->spa_feat_for_read_obj);
4809 zap_cursor_retrieve(&zc, &za) == 0;
4810 zap_cursor_advance(&zc)) {
4811 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4812 za.za_num_integers == 1);
4813 VERIFY0(nvlist_add_uint64(features, za.za_name,
4814 za.za_first_integer));
4816 zap_cursor_fini(&zc);
4819 if (spa->spa_feat_for_write_obj != 0) {
4820 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4821 spa->spa_feat_for_write_obj);
4822 zap_cursor_retrieve(&zc, &za) == 0;
4823 zap_cursor_advance(&zc)) {
4824 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4825 za.za_num_integers == 1);
4826 VERIFY0(nvlist_add_uint64(features, za.za_name,
4827 za.za_first_integer));
4829 zap_cursor_fini(&zc);
4834 spa_feature_stats_from_cache(spa_t *spa, nvlist_t *features)
4838 for (i = 0; i < SPA_FEATURES; i++) {
4839 zfeature_info_t feature = spa_feature_table[i];
4842 if (feature_get_refcount(spa, &feature, &refcount) != 0)
4845 VERIFY0(nvlist_add_uint64(features, feature.fi_guid, refcount));
4850 * Store a list of pool features and their reference counts in the
4853 * The first time this is called on a spa, allocate a new nvlist, fetch
4854 * the pool features and reference counts from disk, then save the list
4855 * in the spa. In subsequent calls on the same spa use the saved nvlist
4856 * and refresh its values from the cached reference counts. This
4857 * ensures we don't block here on I/O on a suspended pool so 'zpool
4858 * clear' can resume the pool.
4861 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4865 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4867 mutex_enter(&spa->spa_feat_stats_lock);
4868 features = spa->spa_feat_stats;
4870 if (features != NULL) {
4871 spa_feature_stats_from_cache(spa, features);
4873 VERIFY0(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP));
4874 spa->spa_feat_stats = features;
4875 spa_feature_stats_from_disk(spa, features);
4878 VERIFY0(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4881 mutex_exit(&spa->spa_feat_stats_lock);
4885 spa_get_stats(const char *name, nvlist_t **config,
4886 char *altroot, size_t buflen)
4892 error = spa_open_common(name, &spa, FTAG, NULL, config);
4896 * This still leaves a window of inconsistency where the spares
4897 * or l2cache devices could change and the config would be
4898 * self-inconsistent.
4900 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4902 if (*config != NULL) {
4903 uint64_t loadtimes[2];
4905 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4906 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4907 VERIFY(nvlist_add_uint64_array(*config,
4908 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4910 VERIFY(nvlist_add_uint64(*config,
4911 ZPOOL_CONFIG_ERRCOUNT,
4912 spa_get_errlog_size(spa)) == 0);
4914 if (spa_suspended(spa)) {
4915 VERIFY(nvlist_add_uint64(*config,
4916 ZPOOL_CONFIG_SUSPENDED,
4917 spa->spa_failmode) == 0);
4918 VERIFY(nvlist_add_uint64(*config,
4919 ZPOOL_CONFIG_SUSPENDED_REASON,
4920 spa->spa_suspended) == 0);
4923 spa_add_spares(spa, *config);
4924 spa_add_l2cache(spa, *config);
4925 spa_add_feature_stats(spa, *config);
4930 * We want to get the alternate root even for faulted pools, so we cheat
4931 * and call spa_lookup() directly.
4935 mutex_enter(&spa_namespace_lock);
4936 spa = spa_lookup(name);
4938 spa_altroot(spa, altroot, buflen);
4942 mutex_exit(&spa_namespace_lock);
4944 spa_altroot(spa, altroot, buflen);
4949 spa_config_exit(spa, SCL_CONFIG, FTAG);
4950 spa_close(spa, FTAG);
4957 * Validate that the auxiliary device array is well formed. We must have an
4958 * array of nvlists, each which describes a valid leaf vdev. If this is an
4959 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4960 * specified, as long as they are well-formed.
4963 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4964 spa_aux_vdev_t *sav, const char *config, uint64_t version,
4965 vdev_labeltype_t label)
4972 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4975 * It's acceptable to have no devs specified.
4977 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4981 return (SET_ERROR(EINVAL));
4984 * Make sure the pool is formatted with a version that supports this
4987 if (spa_version(spa) < version)
4988 return (SET_ERROR(ENOTSUP));
4991 * Set the pending device list so we correctly handle device in-use
4994 sav->sav_pending = dev;
4995 sav->sav_npending = ndev;
4997 for (i = 0; i < ndev; i++) {
4998 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
5002 if (!vd->vdev_ops->vdev_op_leaf) {
5004 error = SET_ERROR(EINVAL);
5010 if ((error = vdev_open(vd)) == 0 &&
5011 (error = vdev_label_init(vd, crtxg, label)) == 0) {
5012 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
5013 vd->vdev_guid) == 0);
5019 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
5026 sav->sav_pending = NULL;
5027 sav->sav_npending = 0;
5032 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
5036 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5038 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
5039 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
5040 VDEV_LABEL_SPARE)) != 0) {
5044 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
5045 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
5046 VDEV_LABEL_L2CACHE));
5050 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
5055 if (sav->sav_config != NULL) {
5061 * Generate new dev list by concatentating with the
5064 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
5065 &olddevs, &oldndevs) == 0);
5067 newdevs = kmem_alloc(sizeof (void *) *
5068 (ndevs + oldndevs), KM_SLEEP);
5069 for (i = 0; i < oldndevs; i++)
5070 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
5072 for (i = 0; i < ndevs; i++)
5073 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
5076 VERIFY(nvlist_remove(sav->sav_config, config,
5077 DATA_TYPE_NVLIST_ARRAY) == 0);
5079 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
5080 config, newdevs, ndevs + oldndevs) == 0);
5081 for (i = 0; i < oldndevs + ndevs; i++)
5082 nvlist_free(newdevs[i]);
5083 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
5086 * Generate a new dev list.
5088 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
5090 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
5096 * Stop and drop level 2 ARC devices
5099 spa_l2cache_drop(spa_t *spa)
5103 spa_aux_vdev_t *sav = &spa->spa_l2cache;
5105 for (i = 0; i < sav->sav_count; i++) {
5108 vd = sav->sav_vdevs[i];
5111 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
5112 pool != 0ULL && l2arc_vdev_present(vd))
5113 l2arc_remove_vdev(vd);
5121 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
5125 char *altroot = NULL;
5130 uint64_t txg = TXG_INITIAL;
5131 nvlist_t **spares, **l2cache;
5132 uint_t nspares, nl2cache;
5133 uint64_t version, obj;
5134 boolean_t has_features;
5138 if (props == NULL ||
5139 nvlist_lookup_string(props,
5140 zpool_prop_to_name(ZPOOL_PROP_TNAME), &poolname) != 0)
5141 poolname = (char *)pool;
5144 * If this pool already exists, return failure.
5146 mutex_enter(&spa_namespace_lock);
5147 if (spa_lookup(poolname) != NULL) {
5148 mutex_exit(&spa_namespace_lock);
5149 return (SET_ERROR(EEXIST));
5153 * Allocate a new spa_t structure.
5155 nvl = fnvlist_alloc();
5156 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
5157 (void) nvlist_lookup_string(props,
5158 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5159 spa = spa_add(poolname, nvl, altroot);
5161 spa_activate(spa, spa_mode_global);
5163 if (props && (error = spa_prop_validate(spa, props))) {
5164 spa_deactivate(spa);
5166 mutex_exit(&spa_namespace_lock);
5171 * Temporary pool names should never be written to disk.
5173 if (poolname != pool)
5174 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
5176 has_features = B_FALSE;
5177 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
5178 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
5179 if (zpool_prop_feature(nvpair_name(elem)))
5180 has_features = B_TRUE;
5183 if (has_features || nvlist_lookup_uint64(props,
5184 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
5185 version = SPA_VERSION;
5187 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
5189 spa->spa_first_txg = txg;
5190 spa->spa_uberblock.ub_txg = txg - 1;
5191 spa->spa_uberblock.ub_version = version;
5192 spa->spa_ubsync = spa->spa_uberblock;
5193 spa->spa_load_state = SPA_LOAD_CREATE;
5194 spa->spa_removing_phys.sr_state = DSS_NONE;
5195 spa->spa_removing_phys.sr_removing_vdev = -1;
5196 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
5197 spa->spa_indirect_vdevs_loaded = B_TRUE;
5200 * Create "The Godfather" zio to hold all async IOs
5202 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
5204 for (int i = 0; i < max_ncpus; i++) {
5205 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
5206 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
5207 ZIO_FLAG_GODFATHER);
5211 * Create the root vdev.
5213 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5215 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
5217 ASSERT(error != 0 || rvd != NULL);
5218 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
5220 if (error == 0 && !zfs_allocatable_devs(nvroot))
5221 error = SET_ERROR(EINVAL);
5224 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
5225 (error = spa_validate_aux(spa, nvroot, txg,
5226 VDEV_ALLOC_ADD)) == 0) {
5228 * instantiate the metaslab groups (this will dirty the vdevs)
5229 * we can no longer error exit past this point
5231 for (int c = 0; error == 0 && c < rvd->vdev_children; c++) {
5232 vdev_t *vd = rvd->vdev_child[c];
5234 vdev_ashift_optimize(vd);
5235 vdev_metaslab_set_size(vd);
5236 vdev_expand(vd, txg);
5240 spa_config_exit(spa, SCL_ALL, FTAG);
5244 spa_deactivate(spa);
5246 mutex_exit(&spa_namespace_lock);
5251 * Get the list of spares, if specified.
5253 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5254 &spares, &nspares) == 0) {
5255 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
5257 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5258 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5259 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5260 spa_load_spares(spa);
5261 spa_config_exit(spa, SCL_ALL, FTAG);
5262 spa->spa_spares.sav_sync = B_TRUE;
5266 * Get the list of level 2 cache devices, if specified.
5268 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5269 &l2cache, &nl2cache) == 0) {
5270 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5271 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5272 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5273 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5274 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5275 spa_load_l2cache(spa);
5276 spa_config_exit(spa, SCL_ALL, FTAG);
5277 spa->spa_l2cache.sav_sync = B_TRUE;
5280 spa->spa_is_initializing = B_TRUE;
5281 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
5282 spa->spa_meta_objset = dp->dp_meta_objset;
5283 spa->spa_is_initializing = B_FALSE;
5286 * Create DDTs (dedup tables).
5290 spa_update_dspace(spa);
5292 tx = dmu_tx_create_assigned(dp, txg);
5295 * Create the pool config object.
5297 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
5298 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
5299 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
5301 if (zap_add(spa->spa_meta_objset,
5302 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
5303 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
5304 cmn_err(CE_PANIC, "failed to add pool config");
5307 if (spa_version(spa) >= SPA_VERSION_FEATURES)
5308 spa_feature_create_zap_objects(spa, tx);
5310 if (zap_add(spa->spa_meta_objset,
5311 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
5312 sizeof (uint64_t), 1, &version, tx) != 0) {
5313 cmn_err(CE_PANIC, "failed to add pool version");
5316 /* Newly created pools with the right version are always deflated. */
5317 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
5318 spa->spa_deflate = TRUE;
5319 if (zap_add(spa->spa_meta_objset,
5320 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
5321 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
5322 cmn_err(CE_PANIC, "failed to add deflate");
5327 * Create the deferred-free bpobj. Turn off compression
5328 * because sync-to-convergence takes longer if the blocksize
5331 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
5332 dmu_object_set_compress(spa->spa_meta_objset, obj,
5333 ZIO_COMPRESS_OFF, tx);
5334 if (zap_add(spa->spa_meta_objset,
5335 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
5336 sizeof (uint64_t), 1, &obj, tx) != 0) {
5337 cmn_err(CE_PANIC, "failed to add bpobj");
5339 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
5340 spa->spa_meta_objset, obj));
5343 * Create the pool's history object.
5345 if (version >= SPA_VERSION_ZPOOL_HISTORY)
5346 spa_history_create_obj(spa, tx);
5349 * Generate some random noise for salted checksums to operate on.
5351 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
5352 sizeof (spa->spa_cksum_salt.zcs_bytes));
5355 * Set pool properties.
5357 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
5358 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
5359 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
5360 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
5361 spa->spa_multihost = zpool_prop_default_numeric(ZPOOL_PROP_MULTIHOST);
5363 if (props != NULL) {
5364 spa_configfile_set(spa, props, B_FALSE);
5365 spa_sync_props(props, tx);
5370 spa->spa_sync_on = B_TRUE;
5371 txg_sync_start(spa->spa_dsl_pool);
5372 mmp_thread_start(spa);
5375 * We explicitly wait for the first transaction to complete so that our
5376 * bean counters are appropriately updated.
5378 txg_wait_synced(spa->spa_dsl_pool, txg);
5380 spa_spawn_aux_threads(spa);
5382 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5383 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
5385 spa_history_log_version(spa, "create");
5388 * Don't count references from objsets that are already closed
5389 * and are making their way through the eviction process.
5391 spa_evicting_os_wait(spa);
5392 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
5393 spa->spa_load_state = SPA_LOAD_NONE;
5395 mutex_exit(&spa_namespace_lock);
5403 * Get the root pool information from the root disk, then import the root pool
5404 * during the system boot up time.
5406 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
5409 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
5412 nvlist_t *nvtop, *nvroot;
5415 if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
5419 * Add this top-level vdev to the child array.
5421 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5423 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5425 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
5428 * Put this pool's top-level vdevs into a root vdev.
5430 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5431 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5432 VDEV_TYPE_ROOT) == 0);
5433 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5434 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5435 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5439 * Replace the existing vdev_tree with the new root vdev in
5440 * this pool's configuration (remove the old, add the new).
5442 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5443 nvlist_free(nvroot);
5448 * Walk the vdev tree and see if we can find a device with "better"
5449 * configuration. A configuration is "better" if the label on that
5450 * device has a more recent txg.
5453 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
5455 for (int c = 0; c < vd->vdev_children; c++)
5456 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
5458 if (vd->vdev_ops->vdev_op_leaf) {
5462 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
5466 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
5470 * Do we have a better boot device?
5472 if (label_txg > *txg) {
5481 * Import a root pool.
5483 * For x86. devpath_list will consist of devid and/or physpath name of
5484 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
5485 * The GRUB "findroot" command will return the vdev we should boot.
5487 * For Sparc, devpath_list consists the physpath name of the booting device
5488 * no matter the rootpool is a single device pool or a mirrored pool.
5490 * "/pci@1f,0/ide@d/disk@0,0:a"
5493 spa_import_rootpool(char *devpath, char *devid)
5496 vdev_t *rvd, *bvd, *avd = NULL;
5497 nvlist_t *config, *nvtop;
5503 * Read the label from the boot device and generate a configuration.
5505 config = spa_generate_rootconf(devpath, devid, &guid);
5506 #if defined(_OBP) && defined(_KERNEL)
5507 if (config == NULL) {
5508 if (strstr(devpath, "/iscsi/ssd") != NULL) {
5510 get_iscsi_bootpath_phy(devpath);
5511 config = spa_generate_rootconf(devpath, devid, &guid);
5515 if (config == NULL) {
5516 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
5518 return (SET_ERROR(EIO));
5521 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5523 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
5525 mutex_enter(&spa_namespace_lock);
5526 if ((spa = spa_lookup(pname)) != NULL) {
5528 * Remove the existing root pool from the namespace so that we
5529 * can replace it with the correct config we just read in.
5534 spa = spa_add(pname, config, NULL);
5535 spa->spa_is_root = B_TRUE;
5536 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5537 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5538 &spa->spa_ubsync.ub_version) != 0)
5539 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5542 * Build up a vdev tree based on the boot device's label config.
5544 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5546 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5547 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5548 VDEV_ALLOC_ROOTPOOL);
5549 spa_config_exit(spa, SCL_ALL, FTAG);
5551 mutex_exit(&spa_namespace_lock);
5552 nvlist_free(config);
5553 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5559 * Get the boot vdev.
5561 if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
5562 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
5563 (u_longlong_t)guid);
5564 error = SET_ERROR(ENOENT);
5569 * Determine if there is a better boot device.
5572 spa_alt_rootvdev(rvd, &avd, &txg);
5574 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
5575 "try booting from '%s'", avd->vdev_path);
5576 error = SET_ERROR(EINVAL);
5581 * If the boot device is part of a spare vdev then ensure that
5582 * we're booting off the active spare.
5584 if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
5585 !bvd->vdev_isspare) {
5586 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
5587 "try booting from '%s'",
5589 vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
5590 error = SET_ERROR(EINVAL);
5596 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5598 spa_config_exit(spa, SCL_ALL, FTAG);
5599 mutex_exit(&spa_namespace_lock);
5601 nvlist_free(config);
5605 #else /* !illumos */
5607 extern int vdev_geom_read_pool_label(const char *name, nvlist_t ***configs,
5611 spa_generate_rootconf(const char *name)
5613 nvlist_t **configs, **tops;
5615 nvlist_t *best_cfg, *nvtop, *nvroot;
5624 if (vdev_geom_read_pool_label(name, &configs, &count) != 0)
5627 ASSERT3U(count, !=, 0);
5629 for (i = 0; i < count; i++) {
5632 VERIFY(nvlist_lookup_uint64(configs[i], ZPOOL_CONFIG_POOL_TXG,
5634 if (txg > best_txg) {
5636 best_cfg = configs[i];
5641 nvlist_lookup_uint64(best_cfg, ZPOOL_CONFIG_VDEV_CHILDREN, &nchildren);
5643 nvlist_lookup_uint64_array(best_cfg, ZPOOL_CONFIG_HOLE_ARRAY,
5646 tops = kmem_zalloc(nchildren * sizeof(void *), KM_SLEEP);
5647 for (i = 0; i < nchildren; i++) {
5650 if (configs[i] == NULL)
5652 VERIFY(nvlist_lookup_nvlist(configs[i], ZPOOL_CONFIG_VDEV_TREE,
5654 nvlist_dup(nvtop, &tops[i], KM_SLEEP);
5656 for (i = 0; holes != NULL && i < nholes; i++) {
5659 if (tops[holes[i]] != NULL)
5661 nvlist_alloc(&tops[holes[i]], NV_UNIQUE_NAME, KM_SLEEP);
5662 VERIFY(nvlist_add_string(tops[holes[i]], ZPOOL_CONFIG_TYPE,
5663 VDEV_TYPE_HOLE) == 0);
5664 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_ID,
5666 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_GUID,
5669 for (i = 0; i < nchildren; i++) {
5670 if (tops[i] != NULL)
5672 nvlist_alloc(&tops[i], NV_UNIQUE_NAME, KM_SLEEP);
5673 VERIFY(nvlist_add_string(tops[i], ZPOOL_CONFIG_TYPE,
5674 VDEV_TYPE_MISSING) == 0);
5675 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_ID,
5677 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_GUID,
5682 * Create pool config based on the best vdev config.
5684 nvlist_dup(best_cfg, &config, KM_SLEEP);
5687 * Put this pool's top-level vdevs into a root vdev.
5689 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5691 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5692 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5693 VDEV_TYPE_ROOT) == 0);
5694 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5695 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5696 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5697 tops, nchildren) == 0);
5700 * Replace the existing vdev_tree with the new root vdev in
5701 * this pool's configuration (remove the old, add the new).
5703 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5706 * Drop vdev config elements that should not be present at pool level.
5708 nvlist_remove(config, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64);
5709 nvlist_remove(config, ZPOOL_CONFIG_TOP_GUID, DATA_TYPE_UINT64);
5711 for (i = 0; i < count; i++)
5712 nvlist_free(configs[i]);
5713 kmem_free(configs, count * sizeof(void *));
5714 for (i = 0; i < nchildren; i++)
5715 nvlist_free(tops[i]);
5716 kmem_free(tops, nchildren * sizeof(void *));
5717 nvlist_free(nvroot);
5722 spa_import_rootpool(const char *name)
5725 vdev_t *rvd, *bvd, *avd = NULL;
5726 nvlist_t *config, *nvtop;
5732 * Read the label from the boot device and generate a configuration.
5734 config = spa_generate_rootconf(name);
5736 mutex_enter(&spa_namespace_lock);
5737 if (config != NULL) {
5738 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5739 &pname) == 0 && strcmp(name, pname) == 0);
5740 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg)
5743 if ((spa = spa_lookup(pname)) != NULL) {
5745 * The pool could already be imported,
5746 * e.g., after reboot -r.
5748 if (spa->spa_state == POOL_STATE_ACTIVE) {
5749 mutex_exit(&spa_namespace_lock);
5750 nvlist_free(config);
5755 * Remove the existing root pool from the namespace so
5756 * that we can replace it with the correct config
5761 spa = spa_add(pname, config, NULL);
5764 * Set spa_ubsync.ub_version as it can be used in vdev_alloc()
5765 * via spa_version().
5767 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5768 &spa->spa_ubsync.ub_version) != 0)
5769 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5770 } else if ((spa = spa_lookup(name)) == NULL) {
5771 mutex_exit(&spa_namespace_lock);
5772 nvlist_free(config);
5773 cmn_err(CE_NOTE, "Cannot find the pool label for '%s'",
5777 VERIFY(nvlist_dup(spa->spa_config, &config, KM_SLEEP) == 0);
5779 spa->spa_is_root = B_TRUE;
5780 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5783 * Build up a vdev tree based on the boot device's label config.
5785 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5787 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5788 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5789 VDEV_ALLOC_ROOTPOOL);
5790 spa_config_exit(spa, SCL_ALL, FTAG);
5792 mutex_exit(&spa_namespace_lock);
5793 nvlist_free(config);
5794 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5799 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5801 spa_config_exit(spa, SCL_ALL, FTAG);
5802 mutex_exit(&spa_namespace_lock);
5804 nvlist_free(config);
5808 #endif /* illumos */
5809 #endif /* _KERNEL */
5812 * Import a non-root pool into the system.
5815 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5818 char *altroot = NULL;
5819 spa_load_state_t state = SPA_LOAD_IMPORT;
5820 zpool_load_policy_t policy;
5821 uint64_t mode = spa_mode_global;
5822 uint64_t readonly = B_FALSE;
5825 nvlist_t **spares, **l2cache;
5826 uint_t nspares, nl2cache;
5829 * If a pool with this name exists, return failure.
5831 mutex_enter(&spa_namespace_lock);
5832 if (spa_lookup(pool) != NULL) {
5833 mutex_exit(&spa_namespace_lock);
5834 return (SET_ERROR(EEXIST));
5838 * Create and initialize the spa structure.
5840 (void) nvlist_lookup_string(props,
5841 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5842 (void) nvlist_lookup_uint64(props,
5843 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5846 spa = spa_add(pool, config, altroot);
5847 spa->spa_import_flags = flags;
5850 * Verbatim import - Take a pool and insert it into the namespace
5851 * as if it had been loaded at boot.
5853 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5855 spa_configfile_set(spa, props, B_FALSE);
5857 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5858 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5859 zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5860 mutex_exit(&spa_namespace_lock);
5864 spa_activate(spa, mode);
5867 * Don't start async tasks until we know everything is healthy.
5869 spa_async_suspend(spa);
5871 zpool_get_load_policy(config, &policy);
5872 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5873 state = SPA_LOAD_RECOVER;
5875 spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5877 if (state != SPA_LOAD_RECOVER) {
5878 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5879 zfs_dbgmsg("spa_import: importing %s", pool);
5881 zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5882 "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
5884 error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
5887 * Propagate anything learned while loading the pool and pass it
5888 * back to caller (i.e. rewind info, missing devices, etc).
5890 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5891 spa->spa_load_info) == 0);
5893 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5895 * Toss any existing sparelist, as it doesn't have any validity
5896 * anymore, and conflicts with spa_has_spare().
5898 if (spa->spa_spares.sav_config) {
5899 nvlist_free(spa->spa_spares.sav_config);
5900 spa->spa_spares.sav_config = NULL;
5901 spa_load_spares(spa);
5903 if (spa->spa_l2cache.sav_config) {
5904 nvlist_free(spa->spa_l2cache.sav_config);
5905 spa->spa_l2cache.sav_config = NULL;
5906 spa_load_l2cache(spa);
5909 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5912 error = spa_validate_aux(spa, nvroot, -1ULL,
5915 error = spa_validate_aux(spa, nvroot, -1ULL,
5916 VDEV_ALLOC_L2CACHE);
5917 spa_config_exit(spa, SCL_ALL, FTAG);
5920 spa_configfile_set(spa, props, B_FALSE);
5922 if (error != 0 || (props && spa_writeable(spa) &&
5923 (error = spa_prop_set(spa, props)))) {
5925 spa_deactivate(spa);
5927 mutex_exit(&spa_namespace_lock);
5931 spa_async_resume(spa);
5934 * Override any spares and level 2 cache devices as specified by
5935 * the user, as these may have correct device names/devids, etc.
5937 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5938 &spares, &nspares) == 0) {
5939 if (spa->spa_spares.sav_config)
5940 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5941 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5943 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5944 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5945 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5946 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5947 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5948 spa_load_spares(spa);
5949 spa_config_exit(spa, SCL_ALL, FTAG);
5950 spa->spa_spares.sav_sync = B_TRUE;
5952 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5953 &l2cache, &nl2cache) == 0) {
5954 if (spa->spa_l2cache.sav_config)
5955 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5956 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5958 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5959 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5960 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5961 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5962 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5963 spa_load_l2cache(spa);
5964 spa_config_exit(spa, SCL_ALL, FTAG);
5965 spa->spa_l2cache.sav_sync = B_TRUE;
5969 * Check for any removed devices.
5971 if (spa->spa_autoreplace) {
5972 spa_aux_check_removed(&spa->spa_spares);
5973 spa_aux_check_removed(&spa->spa_l2cache);
5976 if (spa_writeable(spa)) {
5978 * Update the config cache to include the newly-imported pool.
5980 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5984 * It's possible that the pool was expanded while it was exported.
5985 * We kick off an async task to handle this for us.
5987 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5989 spa_history_log_version(spa, "import");
5991 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5993 mutex_exit(&spa_namespace_lock);
5997 zvol_create_minors(spa, pool);
6004 spa_tryimport(nvlist_t *tryconfig)
6006 nvlist_t *config = NULL;
6007 char *poolname, *cachefile;
6011 zpool_load_policy_t policy;
6013 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
6016 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
6020 * Create and initialize the spa structure.
6022 mutex_enter(&spa_namespace_lock);
6023 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
6024 spa_activate(spa, FREAD);
6027 * Rewind pool if a max txg was provided.
6029 zpool_get_load_policy(spa->spa_config, &policy);
6030 if (policy.zlp_txg != UINT64_MAX) {
6031 spa->spa_load_max_txg = policy.zlp_txg;
6032 spa->spa_extreme_rewind = B_TRUE;
6033 zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
6034 poolname, (longlong_t)policy.zlp_txg);
6036 zfs_dbgmsg("spa_tryimport: importing %s", poolname);
6039 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
6041 zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
6042 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
6044 spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
6047 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
6050 * If 'tryconfig' was at least parsable, return the current config.
6052 if (spa->spa_root_vdev != NULL) {
6053 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
6054 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
6056 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6058 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
6059 spa->spa_uberblock.ub_timestamp) == 0);
6060 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
6061 spa->spa_load_info) == 0);
6064 * If the bootfs property exists on this pool then we
6065 * copy it out so that external consumers can tell which
6066 * pools are bootable.
6068 if ((!error || error == EEXIST) && spa->spa_bootfs) {
6069 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
6072 * We have to play games with the name since the
6073 * pool was opened as TRYIMPORT_NAME.
6075 if (dsl_dsobj_to_dsname(spa_name(spa),
6076 spa->spa_bootfs, tmpname) == 0) {
6078 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
6080 cp = strchr(tmpname, '/');
6082 (void) strlcpy(dsname, tmpname,
6085 (void) snprintf(dsname, MAXPATHLEN,
6086 "%s/%s", poolname, ++cp);
6088 VERIFY(nvlist_add_string(config,
6089 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
6090 kmem_free(dsname, MAXPATHLEN);
6092 kmem_free(tmpname, MAXPATHLEN);
6096 * Add the list of hot spares and level 2 cache devices.
6098 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6099 spa_add_spares(spa, config);
6100 spa_add_l2cache(spa, config);
6101 spa_config_exit(spa, SCL_CONFIG, FTAG);
6105 spa_deactivate(spa);
6107 mutex_exit(&spa_namespace_lock);
6113 * Pool export/destroy
6115 * The act of destroying or exporting a pool is very simple. We make sure there
6116 * is no more pending I/O and any references to the pool are gone. Then, we
6117 * update the pool state and sync all the labels to disk, removing the
6118 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
6119 * we don't sync the labels or remove the configuration cache.
6122 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
6123 boolean_t force, boolean_t hardforce)
6130 if (!(spa_mode_global & FWRITE))
6131 return (SET_ERROR(EROFS));
6133 mutex_enter(&spa_namespace_lock);
6134 if ((spa = spa_lookup(pool)) == NULL) {
6135 mutex_exit(&spa_namespace_lock);
6136 return (SET_ERROR(ENOENT));
6140 * Put a hold on the pool, drop the namespace lock, stop async tasks,
6141 * reacquire the namespace lock, and see if we can export.
6143 spa_open_ref(spa, FTAG);
6144 mutex_exit(&spa_namespace_lock);
6145 spa_async_suspend(spa);
6146 if (spa->spa_zvol_taskq) {
6148 zvol_remove_minors(spa, spa_name(spa));
6150 taskq_wait(spa->spa_zvol_taskq);
6152 mutex_enter(&spa_namespace_lock);
6153 spa_close(spa, FTAG);
6156 * The pool will be in core if it's openable,
6157 * in which case we can modify its state.
6159 if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
6162 * Objsets may be open only because they're dirty, so we
6163 * have to force it to sync before checking spa_refcnt.
6165 txg_wait_synced(spa->spa_dsl_pool, 0);
6166 spa_evicting_os_wait(spa);
6169 * A pool cannot be exported or destroyed if there are active
6170 * references. If we are resetting a pool, allow references by
6171 * fault injection handlers.
6173 if (!spa_refcount_zero(spa) ||
6174 (spa->spa_inject_ref != 0 &&
6175 new_state != POOL_STATE_UNINITIALIZED)) {
6176 spa_async_resume(spa);
6177 mutex_exit(&spa_namespace_lock);
6178 return (SET_ERROR(EBUSY));
6182 * A pool cannot be exported if it has an active shared spare.
6183 * This is to prevent other pools stealing the active spare
6184 * from an exported pool. At user's own will, such pool can
6185 * be forcedly exported.
6187 if (!force && new_state == POOL_STATE_EXPORTED &&
6188 spa_has_active_shared_spare(spa)) {
6189 spa_async_resume(spa);
6190 mutex_exit(&spa_namespace_lock);
6191 return (SET_ERROR(EXDEV));
6195 * We're about to export or destroy this pool. Make sure
6196 * we stop all initializtion activity here before we
6197 * set the spa_final_txg. This will ensure that all
6198 * dirty data resulting from the initialization is
6199 * committed to disk before we unload the pool.
6201 if (spa->spa_root_vdev != NULL) {
6202 vdev_initialize_stop_all(spa->spa_root_vdev,
6203 VDEV_INITIALIZE_ACTIVE);
6207 * We want this to be reflected on every label,
6208 * so mark them all dirty. spa_unload() will do the
6209 * final sync that pushes these changes out.
6211 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
6212 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6213 spa->spa_state = new_state;
6214 spa->spa_final_txg = spa_last_synced_txg(spa) +
6216 vdev_config_dirty(spa->spa_root_vdev);
6217 spa_config_exit(spa, SCL_ALL, FTAG);
6221 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
6223 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
6225 spa_deactivate(spa);
6228 if (oldconfig && spa->spa_config)
6229 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
6231 if (new_state != POOL_STATE_UNINITIALIZED) {
6233 spa_write_cachefile(spa, B_TRUE, B_TRUE);
6236 mutex_exit(&spa_namespace_lock);
6242 * Destroy a storage pool.
6245 spa_destroy(char *pool)
6247 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
6252 * Export a storage pool.
6255 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
6256 boolean_t hardforce)
6258 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
6263 * Similar to spa_export(), this unloads the spa_t without actually removing it
6264 * from the namespace in any way.
6267 spa_reset(char *pool)
6269 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
6274 * ==========================================================================
6275 * Device manipulation
6276 * ==========================================================================
6280 * Add a device to a storage pool.
6283 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
6287 vdev_t *rvd = spa->spa_root_vdev;
6289 nvlist_t **spares, **l2cache;
6290 uint_t nspares, nl2cache;
6292 ASSERT(spa_writeable(spa));
6294 txg = spa_vdev_enter(spa);
6296 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
6297 VDEV_ALLOC_ADD)) != 0)
6298 return (spa_vdev_exit(spa, NULL, txg, error));
6300 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
6302 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
6306 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
6310 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
6311 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6313 if (vd->vdev_children != 0 &&
6314 (error = vdev_create(vd, txg, B_FALSE)) != 0)
6315 return (spa_vdev_exit(spa, vd, txg, error));
6318 * We must validate the spares and l2cache devices after checking the
6319 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
6321 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
6322 return (spa_vdev_exit(spa, vd, txg, error));
6325 * If we are in the middle of a device removal, we can only add
6326 * devices which match the existing devices in the pool.
6327 * If we are in the middle of a removal, or have some indirect
6328 * vdevs, we can not add raidz toplevels.
6330 if (spa->spa_vdev_removal != NULL ||
6331 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
6332 for (int c = 0; c < vd->vdev_children; c++) {
6333 tvd = vd->vdev_child[c];
6334 if (spa->spa_vdev_removal != NULL &&
6335 tvd->vdev_ashift != spa->spa_max_ashift) {
6336 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6338 /* Fail if top level vdev is raidz */
6339 if (tvd->vdev_ops == &vdev_raidz_ops) {
6340 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6343 * Need the top level mirror to be
6344 * a mirror of leaf vdevs only
6346 if (tvd->vdev_ops == &vdev_mirror_ops) {
6347 for (uint64_t cid = 0;
6348 cid < tvd->vdev_children; cid++) {
6349 vdev_t *cvd = tvd->vdev_child[cid];
6350 if (!cvd->vdev_ops->vdev_op_leaf) {
6351 return (spa_vdev_exit(spa, vd,
6359 for (int c = 0; c < vd->vdev_children; c++) {
6362 * Set the vdev id to the first hole, if one exists.
6364 for (id = 0; id < rvd->vdev_children; id++) {
6365 if (rvd->vdev_child[id]->vdev_ishole) {
6366 vdev_free(rvd->vdev_child[id]);
6370 tvd = vd->vdev_child[c];
6371 vdev_remove_child(vd, tvd);
6373 vdev_add_child(rvd, tvd);
6374 vdev_config_dirty(tvd);
6378 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
6379 ZPOOL_CONFIG_SPARES);
6380 spa_load_spares(spa);
6381 spa->spa_spares.sav_sync = B_TRUE;
6384 if (nl2cache != 0) {
6385 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
6386 ZPOOL_CONFIG_L2CACHE);
6387 spa_load_l2cache(spa);
6388 spa->spa_l2cache.sav_sync = B_TRUE;
6392 * We have to be careful when adding new vdevs to an existing pool.
6393 * If other threads start allocating from these vdevs before we
6394 * sync the config cache, and we lose power, then upon reboot we may
6395 * fail to open the pool because there are DVAs that the config cache
6396 * can't translate. Therefore, we first add the vdevs without
6397 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
6398 * and then let spa_config_update() initialize the new metaslabs.
6400 * spa_load() checks for added-but-not-initialized vdevs, so that
6401 * if we lose power at any point in this sequence, the remaining
6402 * steps will be completed the next time we load the pool.
6404 (void) spa_vdev_exit(spa, vd, txg, 0);
6406 mutex_enter(&spa_namespace_lock);
6407 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
6408 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
6409 mutex_exit(&spa_namespace_lock);
6415 * Attach a device to a mirror. The arguments are the path to any device
6416 * in the mirror, and the nvroot for the new device. If the path specifies
6417 * a device that is not mirrored, we automatically insert the mirror vdev.
6419 * If 'replacing' is specified, the new device is intended to replace the
6420 * existing device; in this case the two devices are made into their own
6421 * mirror using the 'replacing' vdev, which is functionally identical to
6422 * the mirror vdev (it actually reuses all the same ops) but has a few
6423 * extra rules: you can't attach to it after it's been created, and upon
6424 * completion of resilvering, the first disk (the one being replaced)
6425 * is automatically detached.
6428 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
6430 uint64_t txg, dtl_max_txg;
6431 vdev_t *rvd = spa->spa_root_vdev;
6432 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
6434 char *oldvdpath, *newvdpath;
6438 ASSERT(spa_writeable(spa));
6440 txg = spa_vdev_enter(spa);
6442 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
6444 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6445 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6446 error = (spa_has_checkpoint(spa)) ?
6447 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6448 return (spa_vdev_exit(spa, NULL, txg, error));
6451 if (spa->spa_vdev_removal != NULL)
6452 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6455 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6457 if (!oldvd->vdev_ops->vdev_op_leaf)
6458 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6460 pvd = oldvd->vdev_parent;
6462 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
6463 VDEV_ALLOC_ATTACH)) != 0)
6464 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6466 if (newrootvd->vdev_children != 1)
6467 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6469 newvd = newrootvd->vdev_child[0];
6471 if (!newvd->vdev_ops->vdev_op_leaf)
6472 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6474 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
6475 return (spa_vdev_exit(spa, newrootvd, txg, error));
6478 * Spares can't replace logs
6480 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
6481 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6485 * For attach, the only allowable parent is a mirror or the root
6488 if (pvd->vdev_ops != &vdev_mirror_ops &&
6489 pvd->vdev_ops != &vdev_root_ops)
6490 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6492 pvops = &vdev_mirror_ops;
6495 * Active hot spares can only be replaced by inactive hot
6498 if (pvd->vdev_ops == &vdev_spare_ops &&
6499 oldvd->vdev_isspare &&
6500 !spa_has_spare(spa, newvd->vdev_guid))
6501 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6504 * If the source is a hot spare, and the parent isn't already a
6505 * spare, then we want to create a new hot spare. Otherwise, we
6506 * want to create a replacing vdev. The user is not allowed to
6507 * attach to a spared vdev child unless the 'isspare' state is
6508 * the same (spare replaces spare, non-spare replaces
6511 if (pvd->vdev_ops == &vdev_replacing_ops &&
6512 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6513 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6514 } else if (pvd->vdev_ops == &vdev_spare_ops &&
6515 newvd->vdev_isspare != oldvd->vdev_isspare) {
6516 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6519 if (newvd->vdev_isspare)
6520 pvops = &vdev_spare_ops;
6522 pvops = &vdev_replacing_ops;
6526 * Make sure the new device is big enough.
6528 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6529 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6532 * The new device cannot have a higher alignment requirement
6533 * than the top-level vdev.
6535 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6536 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6539 * If this is an in-place replacement, update oldvd's path and devid
6540 * to make it distinguishable from newvd, and unopenable from now on.
6542 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6543 spa_strfree(oldvd->vdev_path);
6544 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6546 (void) sprintf(oldvd->vdev_path, "%s/%s",
6547 newvd->vdev_path, "old");
6548 if (oldvd->vdev_devid != NULL) {
6549 spa_strfree(oldvd->vdev_devid);
6550 oldvd->vdev_devid = NULL;
6554 /* mark the device being resilvered */
6555 newvd->vdev_resilver_txg = txg;
6558 * If the parent is not a mirror, or if we're replacing, insert the new
6559 * mirror/replacing/spare vdev above oldvd.
6561 if (pvd->vdev_ops != pvops)
6562 pvd = vdev_add_parent(oldvd, pvops);
6564 ASSERT(pvd->vdev_top->vdev_parent == rvd);
6565 ASSERT(pvd->vdev_ops == pvops);
6566 ASSERT(oldvd->vdev_parent == pvd);
6569 * Extract the new device from its root and add it to pvd.
6571 vdev_remove_child(newrootvd, newvd);
6572 newvd->vdev_id = pvd->vdev_children;
6573 newvd->vdev_crtxg = oldvd->vdev_crtxg;
6574 vdev_add_child(pvd, newvd);
6576 tvd = newvd->vdev_top;
6577 ASSERT(pvd->vdev_top == tvd);
6578 ASSERT(tvd->vdev_parent == rvd);
6580 vdev_config_dirty(tvd);
6583 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6584 * for any dmu_sync-ed blocks. It will propagate upward when
6585 * spa_vdev_exit() calls vdev_dtl_reassess().
6587 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6589 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6590 dtl_max_txg - TXG_INITIAL);
6592 if (newvd->vdev_isspare) {
6593 spa_spare_activate(newvd);
6594 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6597 oldvdpath = spa_strdup(oldvd->vdev_path);
6598 newvdpath = spa_strdup(newvd->vdev_path);
6599 newvd_isspare = newvd->vdev_isspare;
6602 * Mark newvd's DTL dirty in this txg.
6604 vdev_dirty(tvd, VDD_DTL, newvd, txg);
6607 * Schedule the resilver to restart in the future. We do this to
6608 * ensure that dmu_sync-ed blocks have been stitched into the
6609 * respective datasets.
6611 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
6613 if (spa->spa_bootfs)
6614 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6616 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6621 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6623 spa_history_log_internal(spa, "vdev attach", NULL,
6624 "%s vdev=%s %s vdev=%s",
6625 replacing && newvd_isspare ? "spare in" :
6626 replacing ? "replace" : "attach", newvdpath,
6627 replacing ? "for" : "to", oldvdpath);
6629 spa_strfree(oldvdpath);
6630 spa_strfree(newvdpath);
6636 * Detach a device from a mirror or replacing vdev.
6638 * If 'replace_done' is specified, only detach if the parent
6639 * is a replacing vdev.
6642 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6646 vdev_t *rvd = spa->spa_root_vdev;
6647 vdev_t *vd, *pvd, *cvd, *tvd;
6648 boolean_t unspare = B_FALSE;
6649 uint64_t unspare_guid = 0;
6652 ASSERT(spa_writeable(spa));
6654 txg = spa_vdev_enter(spa);
6656 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6659 * Besides being called directly from the userland through the
6660 * ioctl interface, spa_vdev_detach() can be potentially called
6661 * at the end of spa_vdev_resilver_done().
6663 * In the regular case, when we have a checkpoint this shouldn't
6664 * happen as we never empty the DTLs of a vdev during the scrub
6665 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6666 * should never get here when we have a checkpoint.
6668 * That said, even in a case when we checkpoint the pool exactly
6669 * as spa_vdev_resilver_done() calls this function everything
6670 * should be fine as the resilver will return right away.
6672 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6673 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6674 error = (spa_has_checkpoint(spa)) ?
6675 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6676 return (spa_vdev_exit(spa, NULL, txg, error));
6680 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6682 if (!vd->vdev_ops->vdev_op_leaf)
6683 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6685 pvd = vd->vdev_parent;
6688 * If the parent/child relationship is not as expected, don't do it.
6689 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6690 * vdev that's replacing B with C. The user's intent in replacing
6691 * is to go from M(A,B) to M(A,C). If the user decides to cancel
6692 * the replace by detaching C, the expected behavior is to end up
6693 * M(A,B). But suppose that right after deciding to detach C,
6694 * the replacement of B completes. We would have M(A,C), and then
6695 * ask to detach C, which would leave us with just A -- not what
6696 * the user wanted. To prevent this, we make sure that the
6697 * parent/child relationship hasn't changed -- in this example,
6698 * that C's parent is still the replacing vdev R.
6700 if (pvd->vdev_guid != pguid && pguid != 0)
6701 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6704 * Only 'replacing' or 'spare' vdevs can be replaced.
6706 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6707 pvd->vdev_ops != &vdev_spare_ops)
6708 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6710 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6711 spa_version(spa) >= SPA_VERSION_SPARES);
6714 * Only mirror, replacing, and spare vdevs support detach.
6716 if (pvd->vdev_ops != &vdev_replacing_ops &&
6717 pvd->vdev_ops != &vdev_mirror_ops &&
6718 pvd->vdev_ops != &vdev_spare_ops)
6719 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6722 * If this device has the only valid copy of some data,
6723 * we cannot safely detach it.
6725 if (vdev_dtl_required(vd))
6726 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6728 ASSERT(pvd->vdev_children >= 2);
6731 * If we are detaching the second disk from a replacing vdev, then
6732 * check to see if we changed the original vdev's path to have "/old"
6733 * at the end in spa_vdev_attach(). If so, undo that change now.
6735 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
6736 vd->vdev_path != NULL) {
6737 size_t len = strlen(vd->vdev_path);
6739 for (int c = 0; c < pvd->vdev_children; c++) {
6740 cvd = pvd->vdev_child[c];
6742 if (cvd == vd || cvd->vdev_path == NULL)
6745 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
6746 strcmp(cvd->vdev_path + len, "/old") == 0) {
6747 spa_strfree(cvd->vdev_path);
6748 cvd->vdev_path = spa_strdup(vd->vdev_path);
6755 * If we are detaching the original disk from a spare, then it implies
6756 * that the spare should become a real disk, and be removed from the
6757 * active spare list for the pool.
6759 if (pvd->vdev_ops == &vdev_spare_ops &&
6761 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
6765 * Erase the disk labels so the disk can be used for other things.
6766 * This must be done after all other error cases are handled,
6767 * but before we disembowel vd (so we can still do I/O to it).
6768 * But if we can't do it, don't treat the error as fatal --
6769 * it may be that the unwritability of the disk is the reason
6770 * it's being detached!
6772 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
6775 * Remove vd from its parent and compact the parent's children.
6777 vdev_remove_child(pvd, vd);
6778 vdev_compact_children(pvd);
6781 * Remember one of the remaining children so we can get tvd below.
6783 cvd = pvd->vdev_child[pvd->vdev_children - 1];
6786 * If we need to remove the remaining child from the list of hot spares,
6787 * do it now, marking the vdev as no longer a spare in the process.
6788 * We must do this before vdev_remove_parent(), because that can
6789 * change the GUID if it creates a new toplevel GUID. For a similar
6790 * reason, we must remove the spare now, in the same txg as the detach;
6791 * otherwise someone could attach a new sibling, change the GUID, and
6792 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
6795 ASSERT(cvd->vdev_isspare);
6796 spa_spare_remove(cvd);
6797 unspare_guid = cvd->vdev_guid;
6798 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
6799 cvd->vdev_unspare = B_TRUE;
6803 * If the parent mirror/replacing vdev only has one child,
6804 * the parent is no longer needed. Remove it from the tree.
6806 if (pvd->vdev_children == 1) {
6807 if (pvd->vdev_ops == &vdev_spare_ops)
6808 cvd->vdev_unspare = B_FALSE;
6809 vdev_remove_parent(cvd);
6814 * We don't set tvd until now because the parent we just removed
6815 * may have been the previous top-level vdev.
6817 tvd = cvd->vdev_top;
6818 ASSERT(tvd->vdev_parent == rvd);
6821 * Reevaluate the parent vdev state.
6823 vdev_propagate_state(cvd);
6826 * If the 'autoexpand' property is set on the pool then automatically
6827 * try to expand the size of the pool. For example if the device we
6828 * just detached was smaller than the others, it may be possible to
6829 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
6830 * first so that we can obtain the updated sizes of the leaf vdevs.
6832 if (spa->spa_autoexpand) {
6834 vdev_expand(tvd, txg);
6837 vdev_config_dirty(tvd);
6840 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
6841 * vd->vdev_detached is set and free vd's DTL object in syncing context.
6842 * But first make sure we're not on any *other* txg's DTL list, to
6843 * prevent vd from being accessed after it's freed.
6845 vdpath = spa_strdup(vd->vdev_path);
6846 for (int t = 0; t < TXG_SIZE; t++)
6847 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
6848 vd->vdev_detached = B_TRUE;
6849 vdev_dirty(tvd, VDD_DTL, vd, txg);
6851 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
6853 /* hang on to the spa before we release the lock */
6854 spa_open_ref(spa, FTAG);
6856 error = spa_vdev_exit(spa, vd, txg, 0);
6858 spa_history_log_internal(spa, "detach", NULL,
6860 spa_strfree(vdpath);
6863 * If this was the removal of the original device in a hot spare vdev,
6864 * then we want to go through and remove the device from the hot spare
6865 * list of every other pool.
6868 spa_t *altspa = NULL;
6870 mutex_enter(&spa_namespace_lock);
6871 while ((altspa = spa_next(altspa)) != NULL) {
6872 if (altspa->spa_state != POOL_STATE_ACTIVE ||
6876 spa_open_ref(altspa, FTAG);
6877 mutex_exit(&spa_namespace_lock);
6878 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
6879 mutex_enter(&spa_namespace_lock);
6880 spa_close(altspa, FTAG);
6882 mutex_exit(&spa_namespace_lock);
6884 /* search the rest of the vdevs for spares to remove */
6885 spa_vdev_resilver_done(spa);
6888 /* all done with the spa; OK to release */
6889 mutex_enter(&spa_namespace_lock);
6890 spa_close(spa, FTAG);
6891 mutex_exit(&spa_namespace_lock);
6897 spa_vdev_initialize(spa_t *spa, uint64_t guid, uint64_t cmd_type)
6900 * We hold the namespace lock through the whole function
6901 * to prevent any changes to the pool while we're starting or
6902 * stopping initialization. The config and state locks are held so that
6903 * we can properly assess the vdev state before we commit to
6904 * the initializing operation.
6906 mutex_enter(&spa_namespace_lock);
6907 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6909 /* Look up vdev and ensure it's a leaf. */
6910 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6911 if (vd == NULL || vd->vdev_detached) {
6912 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6913 mutex_exit(&spa_namespace_lock);
6914 return (SET_ERROR(ENODEV));
6915 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6916 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6917 mutex_exit(&spa_namespace_lock);
6918 return (SET_ERROR(EINVAL));
6919 } else if (!vdev_writeable(vd)) {
6920 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6921 mutex_exit(&spa_namespace_lock);
6922 return (SET_ERROR(EROFS));
6924 mutex_enter(&vd->vdev_initialize_lock);
6925 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6928 * When we activate an initialize action we check to see
6929 * if the vdev_initialize_thread is NULL. We do this instead
6930 * of using the vdev_initialize_state since there might be
6931 * a previous initialization process which has completed but
6932 * the thread is not exited.
6934 if (cmd_type == POOL_INITIALIZE_DO &&
6935 (vd->vdev_initialize_thread != NULL ||
6936 vd->vdev_top->vdev_removing)) {
6937 mutex_exit(&vd->vdev_initialize_lock);
6938 mutex_exit(&spa_namespace_lock);
6939 return (SET_ERROR(EBUSY));
6940 } else if (cmd_type == POOL_INITIALIZE_CANCEL &&
6941 (vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE &&
6942 vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED)) {
6943 mutex_exit(&vd->vdev_initialize_lock);
6944 mutex_exit(&spa_namespace_lock);
6945 return (SET_ERROR(ESRCH));
6946 } else if (cmd_type == POOL_INITIALIZE_SUSPEND &&
6947 vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE) {
6948 mutex_exit(&vd->vdev_initialize_lock);
6949 mutex_exit(&spa_namespace_lock);
6950 return (SET_ERROR(ESRCH));
6954 case POOL_INITIALIZE_DO:
6955 vdev_initialize(vd);
6957 case POOL_INITIALIZE_CANCEL:
6958 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED);
6960 case POOL_INITIALIZE_SUSPEND:
6961 vdev_initialize_stop(vd, VDEV_INITIALIZE_SUSPENDED);
6964 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6966 mutex_exit(&vd->vdev_initialize_lock);
6968 /* Sync out the initializing state */
6969 txg_wait_synced(spa->spa_dsl_pool, 0);
6970 mutex_exit(&spa_namespace_lock);
6977 * Split a set of devices from their mirrors, and create a new pool from them.
6980 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6981 nvlist_t *props, boolean_t exp)
6984 uint64_t txg, *glist;
6986 uint_t c, children, lastlog;
6987 nvlist_t **child, *nvl, *tmp;
6989 char *altroot = NULL;
6990 vdev_t *rvd, **vml = NULL; /* vdev modify list */
6991 boolean_t activate_slog;
6993 ASSERT(spa_writeable(spa));
6995 txg = spa_vdev_enter(spa);
6997 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6998 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6999 error = (spa_has_checkpoint(spa)) ?
7000 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
7001 return (spa_vdev_exit(spa, NULL, txg, error));
7004 /* clear the log and flush everything up to now */
7005 activate_slog = spa_passivate_log(spa);
7006 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
7007 error = spa_reset_logs(spa);
7008 txg = spa_vdev_config_enter(spa);
7011 spa_activate_log(spa);
7014 return (spa_vdev_exit(spa, NULL, txg, error));
7016 /* check new spa name before going any further */
7017 if (spa_lookup(newname) != NULL)
7018 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
7021 * scan through all the children to ensure they're all mirrors
7023 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
7024 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
7026 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
7028 /* first, check to ensure we've got the right child count */
7029 rvd = spa->spa_root_vdev;
7031 for (c = 0; c < rvd->vdev_children; c++) {
7032 vdev_t *vd = rvd->vdev_child[c];
7034 /* don't count the holes & logs as children */
7035 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
7043 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
7044 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
7046 /* next, ensure no spare or cache devices are part of the split */
7047 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
7048 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
7049 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
7051 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
7052 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
7054 /* then, loop over each vdev and validate it */
7055 for (c = 0; c < children; c++) {
7056 uint64_t is_hole = 0;
7058 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
7062 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
7063 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
7066 error = SET_ERROR(EINVAL);
7071 /* which disk is going to be split? */
7072 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
7074 error = SET_ERROR(EINVAL);
7078 /* look it up in the spa */
7079 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
7080 if (vml[c] == NULL) {
7081 error = SET_ERROR(ENODEV);
7085 /* make sure there's nothing stopping the split */
7086 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
7087 vml[c]->vdev_islog ||
7088 !vdev_is_concrete(vml[c]) ||
7089 vml[c]->vdev_isspare ||
7090 vml[c]->vdev_isl2cache ||
7091 !vdev_writeable(vml[c]) ||
7092 vml[c]->vdev_children != 0 ||
7093 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
7094 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
7095 error = SET_ERROR(EINVAL);
7099 if (vdev_dtl_required(vml[c])) {
7100 error = SET_ERROR(EBUSY);
7104 /* we need certain info from the top level */
7105 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
7106 vml[c]->vdev_top->vdev_ms_array) == 0);
7107 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
7108 vml[c]->vdev_top->vdev_ms_shift) == 0);
7109 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
7110 vml[c]->vdev_top->vdev_asize) == 0);
7111 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
7112 vml[c]->vdev_top->vdev_ashift) == 0);
7114 /* transfer per-vdev ZAPs */
7115 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
7116 VERIFY0(nvlist_add_uint64(child[c],
7117 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
7119 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
7120 VERIFY0(nvlist_add_uint64(child[c],
7121 ZPOOL_CONFIG_VDEV_TOP_ZAP,
7122 vml[c]->vdev_parent->vdev_top_zap));
7126 kmem_free(vml, children * sizeof (vdev_t *));
7127 kmem_free(glist, children * sizeof (uint64_t));
7128 return (spa_vdev_exit(spa, NULL, txg, error));
7131 /* stop writers from using the disks */
7132 for (c = 0; c < children; c++) {
7134 vml[c]->vdev_offline = B_TRUE;
7136 vdev_reopen(spa->spa_root_vdev);
7139 * Temporarily record the splitting vdevs in the spa config. This
7140 * will disappear once the config is regenerated.
7142 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7143 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
7144 glist, children) == 0);
7145 kmem_free(glist, children * sizeof (uint64_t));
7147 mutex_enter(&spa->spa_props_lock);
7148 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
7150 mutex_exit(&spa->spa_props_lock);
7151 spa->spa_config_splitting = nvl;
7152 vdev_config_dirty(spa->spa_root_vdev);
7154 /* configure and create the new pool */
7155 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
7156 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
7157 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
7158 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7159 spa_version(spa)) == 0);
7160 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
7161 spa->spa_config_txg) == 0);
7162 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
7163 spa_generate_guid(NULL)) == 0);
7164 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
7165 (void) nvlist_lookup_string(props,
7166 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
7168 /* add the new pool to the namespace */
7169 newspa = spa_add(newname, config, altroot);
7170 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
7171 newspa->spa_config_txg = spa->spa_config_txg;
7172 spa_set_log_state(newspa, SPA_LOG_CLEAR);
7174 /* release the spa config lock, retaining the namespace lock */
7175 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
7177 if (zio_injection_enabled)
7178 zio_handle_panic_injection(spa, FTAG, 1);
7180 spa_activate(newspa, spa_mode_global);
7181 spa_async_suspend(newspa);
7183 for (c = 0; c < children; c++) {
7184 if (vml[c] != NULL) {
7186 * Temporarily stop the initializing activity. We set
7187 * the state to ACTIVE so that we know to resume
7188 * the initializing once the split has completed.
7190 mutex_enter(&vml[c]->vdev_initialize_lock);
7191 vdev_initialize_stop(vml[c], VDEV_INITIALIZE_ACTIVE);
7192 mutex_exit(&vml[c]->vdev_initialize_lock);
7197 /* mark that we are creating new spa by splitting */
7198 newspa->spa_splitting_newspa = B_TRUE;
7200 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
7202 /* create the new pool from the disks of the original pool */
7203 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
7205 newspa->spa_splitting_newspa = B_FALSE;
7210 /* if that worked, generate a real config for the new pool */
7211 if (newspa->spa_root_vdev != NULL) {
7212 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
7213 NV_UNIQUE_NAME, KM_SLEEP) == 0);
7214 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
7215 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
7216 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
7221 if (props != NULL) {
7222 spa_configfile_set(newspa, props, B_FALSE);
7223 error = spa_prop_set(newspa, props);
7228 /* flush everything */
7229 txg = spa_vdev_config_enter(newspa);
7230 vdev_config_dirty(newspa->spa_root_vdev);
7231 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
7233 if (zio_injection_enabled)
7234 zio_handle_panic_injection(spa, FTAG, 2);
7236 spa_async_resume(newspa);
7238 /* finally, update the original pool's config */
7239 txg = spa_vdev_config_enter(spa);
7240 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
7241 error = dmu_tx_assign(tx, TXG_WAIT);
7244 for (c = 0; c < children; c++) {
7245 if (vml[c] != NULL) {
7248 spa_history_log_internal(spa, "detach", tx,
7249 "vdev=%s", vml[c]->vdev_path);
7254 spa->spa_avz_action = AVZ_ACTION_REBUILD;
7255 vdev_config_dirty(spa->spa_root_vdev);
7256 spa->spa_config_splitting = NULL;
7260 (void) spa_vdev_exit(spa, NULL, txg, 0);
7262 if (zio_injection_enabled)
7263 zio_handle_panic_injection(spa, FTAG, 3);
7265 /* split is complete; log a history record */
7266 spa_history_log_internal(newspa, "split", NULL,
7267 "from pool %s", spa_name(spa));
7269 kmem_free(vml, children * sizeof (vdev_t *));
7271 /* if we're not going to mount the filesystems in userland, export */
7273 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
7280 spa_deactivate(newspa);
7283 txg = spa_vdev_config_enter(spa);
7285 /* re-online all offlined disks */
7286 for (c = 0; c < children; c++) {
7288 vml[c]->vdev_offline = B_FALSE;
7291 /* restart initializing disks as necessary */
7292 spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
7294 vdev_reopen(spa->spa_root_vdev);
7296 nvlist_free(spa->spa_config_splitting);
7297 spa->spa_config_splitting = NULL;
7298 (void) spa_vdev_exit(spa, NULL, txg, error);
7300 kmem_free(vml, children * sizeof (vdev_t *));
7305 * Find any device that's done replacing, or a vdev marked 'unspare' that's
7306 * currently spared, so we can detach it.
7309 spa_vdev_resilver_done_hunt(vdev_t *vd)
7311 vdev_t *newvd, *oldvd;
7313 for (int c = 0; c < vd->vdev_children; c++) {
7314 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
7320 * Check for a completed replacement. We always consider the first
7321 * vdev in the list to be the oldest vdev, and the last one to be
7322 * the newest (see spa_vdev_attach() for how that works). In
7323 * the case where the newest vdev is faulted, we will not automatically
7324 * remove it after a resilver completes. This is OK as it will require
7325 * user intervention to determine which disk the admin wishes to keep.
7327 if (vd->vdev_ops == &vdev_replacing_ops) {
7328 ASSERT(vd->vdev_children > 1);
7330 newvd = vd->vdev_child[vd->vdev_children - 1];
7331 oldvd = vd->vdev_child[0];
7333 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
7334 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
7335 !vdev_dtl_required(oldvd))
7340 * Check for a completed resilver with the 'unspare' flag set.
7341 * Also potentially update faulted state.
7343 if (vd->vdev_ops == &vdev_spare_ops) {
7344 vdev_t *first = vd->vdev_child[0];
7345 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
7347 if (last->vdev_unspare) {
7350 } else if (first->vdev_unspare) {
7357 if (oldvd != NULL &&
7358 vdev_dtl_empty(newvd, DTL_MISSING) &&
7359 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
7360 !vdev_dtl_required(oldvd))
7363 vdev_propagate_state(vd);
7366 * If there are more than two spares attached to a disk,
7367 * and those spares are not required, then we want to
7368 * attempt to free them up now so that they can be used
7369 * by other pools. Once we're back down to a single
7370 * disk+spare, we stop removing them.
7372 if (vd->vdev_children > 2) {
7373 newvd = vd->vdev_child[1];
7375 if (newvd->vdev_isspare && last->vdev_isspare &&
7376 vdev_dtl_empty(last, DTL_MISSING) &&
7377 vdev_dtl_empty(last, DTL_OUTAGE) &&
7378 !vdev_dtl_required(newvd))
7387 spa_vdev_resilver_done(spa_t *spa)
7389 vdev_t *vd, *pvd, *ppvd;
7390 uint64_t guid, sguid, pguid, ppguid;
7392 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7394 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
7395 pvd = vd->vdev_parent;
7396 ppvd = pvd->vdev_parent;
7397 guid = vd->vdev_guid;
7398 pguid = pvd->vdev_guid;
7399 ppguid = ppvd->vdev_guid;
7402 * If we have just finished replacing a hot spared device, then
7403 * we need to detach the parent's first child (the original hot
7406 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
7407 ppvd->vdev_children == 2) {
7408 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
7409 sguid = ppvd->vdev_child[1]->vdev_guid;
7411 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
7413 spa_config_exit(spa, SCL_ALL, FTAG);
7414 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
7416 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
7418 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7421 spa_config_exit(spa, SCL_ALL, FTAG);
7425 * Update the stored path or FRU for this vdev.
7428 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
7432 boolean_t sync = B_FALSE;
7434 ASSERT(spa_writeable(spa));
7436 spa_vdev_state_enter(spa, SCL_ALL);
7438 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
7439 return (spa_vdev_state_exit(spa, NULL, ENOENT));
7441 if (!vd->vdev_ops->vdev_op_leaf)
7442 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
7445 if (strcmp(value, vd->vdev_path) != 0) {
7446 spa_strfree(vd->vdev_path);
7447 vd->vdev_path = spa_strdup(value);
7451 if (vd->vdev_fru == NULL) {
7452 vd->vdev_fru = spa_strdup(value);
7454 } else if (strcmp(value, vd->vdev_fru) != 0) {
7455 spa_strfree(vd->vdev_fru);
7456 vd->vdev_fru = spa_strdup(value);
7461 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
7465 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
7467 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
7471 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
7473 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
7477 * ==========================================================================
7479 * ==========================================================================
7482 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
7484 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7486 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7487 return (SET_ERROR(EBUSY));
7489 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
7493 spa_scan_stop(spa_t *spa)
7495 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7496 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7497 return (SET_ERROR(EBUSY));
7498 return (dsl_scan_cancel(spa->spa_dsl_pool));
7502 spa_scan(spa_t *spa, pool_scan_func_t func)
7504 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7506 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
7507 return (SET_ERROR(ENOTSUP));
7510 * If a resilver was requested, but there is no DTL on a
7511 * writeable leaf device, we have nothing to do.
7513 if (func == POOL_SCAN_RESILVER &&
7514 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
7515 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
7519 return (dsl_scan(spa->spa_dsl_pool, func));
7523 * ==========================================================================
7524 * SPA async task processing
7525 * ==========================================================================
7529 spa_async_remove(spa_t *spa, vdev_t *vd)
7531 if (vd->vdev_remove_wanted) {
7532 vd->vdev_remove_wanted = B_FALSE;
7533 vd->vdev_delayed_close = B_FALSE;
7534 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
7537 * We want to clear the stats, but we don't want to do a full
7538 * vdev_clear() as that will cause us to throw away
7539 * degraded/faulted state as well as attempt to reopen the
7540 * device, all of which is a waste.
7542 vd->vdev_stat.vs_read_errors = 0;
7543 vd->vdev_stat.vs_write_errors = 0;
7544 vd->vdev_stat.vs_checksum_errors = 0;
7546 vdev_state_dirty(vd->vdev_top);
7547 /* Tell userspace that the vdev is gone. */
7548 zfs_post_remove(spa, vd);
7551 for (int c = 0; c < vd->vdev_children; c++)
7552 spa_async_remove(spa, vd->vdev_child[c]);
7556 spa_async_probe(spa_t *spa, vdev_t *vd)
7558 if (vd->vdev_probe_wanted) {
7559 vd->vdev_probe_wanted = B_FALSE;
7560 vdev_reopen(vd); /* vdev_open() does the actual probe */
7563 for (int c = 0; c < vd->vdev_children; c++)
7564 spa_async_probe(spa, vd->vdev_child[c]);
7568 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
7574 if (!spa->spa_autoexpand)
7577 for (int c = 0; c < vd->vdev_children; c++) {
7578 vdev_t *cvd = vd->vdev_child[c];
7579 spa_async_autoexpand(spa, cvd);
7582 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
7585 physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
7586 (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
7588 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7589 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
7591 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
7592 ESC_ZFS_VDEV_AUTOEXPAND, attr, &eid, DDI_SLEEP);
7595 kmem_free(physpath, MAXPATHLEN);
7599 spa_async_thread(void *arg)
7601 spa_t *spa = (spa_t *)arg;
7604 ASSERT(spa->spa_sync_on);
7606 mutex_enter(&spa->spa_async_lock);
7607 tasks = spa->spa_async_tasks;
7608 spa->spa_async_tasks &= SPA_ASYNC_REMOVE;
7609 mutex_exit(&spa->spa_async_lock);
7612 * See if the config needs to be updated.
7614 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
7615 uint64_t old_space, new_space;
7617 mutex_enter(&spa_namespace_lock);
7618 old_space = metaslab_class_get_space(spa_normal_class(spa));
7619 old_space += metaslab_class_get_space(spa_special_class(spa));
7620 old_space += metaslab_class_get_space(spa_dedup_class(spa));
7622 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
7624 new_space = metaslab_class_get_space(spa_normal_class(spa));
7625 new_space += metaslab_class_get_space(spa_special_class(spa));
7626 new_space += metaslab_class_get_space(spa_dedup_class(spa));
7627 mutex_exit(&spa_namespace_lock);
7630 * If the pool grew as a result of the config update,
7631 * then log an internal history event.
7633 if (new_space != old_space) {
7634 spa_history_log_internal(spa, "vdev online", NULL,
7635 "pool '%s' size: %llu(+%llu)",
7636 spa_name(spa), new_space, new_space - old_space);
7640 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
7641 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7642 spa_async_autoexpand(spa, spa->spa_root_vdev);
7643 spa_config_exit(spa, SCL_CONFIG, FTAG);
7647 * See if any devices need to be probed.
7649 if (tasks & SPA_ASYNC_PROBE) {
7650 spa_vdev_state_enter(spa, SCL_NONE);
7651 spa_async_probe(spa, spa->spa_root_vdev);
7652 (void) spa_vdev_state_exit(spa, NULL, 0);
7656 * If any devices are done replacing, detach them.
7658 if (tasks & SPA_ASYNC_RESILVER_DONE)
7659 spa_vdev_resilver_done(spa);
7662 * Kick off a resilver.
7664 if (tasks & SPA_ASYNC_RESILVER)
7665 dsl_resilver_restart(spa->spa_dsl_pool, 0);
7667 if (tasks & SPA_ASYNC_INITIALIZE_RESTART) {
7668 mutex_enter(&spa_namespace_lock);
7669 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7670 vdev_initialize_restart(spa->spa_root_vdev);
7671 spa_config_exit(spa, SCL_CONFIG, FTAG);
7672 mutex_exit(&spa_namespace_lock);
7676 * Let the world know that we're done.
7678 mutex_enter(&spa->spa_async_lock);
7679 spa->spa_async_thread = NULL;
7680 cv_broadcast(&spa->spa_async_cv);
7681 mutex_exit(&spa->spa_async_lock);
7686 spa_async_thread_vd(void *arg)
7691 mutex_enter(&spa->spa_async_lock);
7692 tasks = spa->spa_async_tasks;
7694 spa->spa_async_tasks &= ~SPA_ASYNC_REMOVE;
7695 mutex_exit(&spa->spa_async_lock);
7698 * See if any devices need to be marked REMOVED.
7700 if (tasks & SPA_ASYNC_REMOVE) {
7701 spa_vdev_state_enter(spa, SCL_NONE);
7702 spa_async_remove(spa, spa->spa_root_vdev);
7703 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
7704 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
7705 for (int i = 0; i < spa->spa_spares.sav_count; i++)
7706 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
7707 (void) spa_vdev_state_exit(spa, NULL, 0);
7711 * Let the world know that we're done.
7713 mutex_enter(&spa->spa_async_lock);
7714 tasks = spa->spa_async_tasks;
7715 if ((tasks & SPA_ASYNC_REMOVE) != 0)
7717 spa->spa_async_thread_vd = NULL;
7718 cv_broadcast(&spa->spa_async_cv);
7719 mutex_exit(&spa->spa_async_lock);
7724 spa_async_suspend(spa_t *spa)
7726 mutex_enter(&spa->spa_async_lock);
7727 spa->spa_async_suspended++;
7728 while (spa->spa_async_thread != NULL ||
7729 spa->spa_async_thread_vd != NULL)
7730 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
7731 mutex_exit(&spa->spa_async_lock);
7733 spa_vdev_remove_suspend(spa);
7735 zthr_t *condense_thread = spa->spa_condense_zthr;
7736 if (condense_thread != NULL)
7737 zthr_cancel(condense_thread);
7739 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7740 if (discard_thread != NULL)
7741 zthr_cancel(discard_thread);
7745 spa_async_resume(spa_t *spa)
7747 mutex_enter(&spa->spa_async_lock);
7748 ASSERT(spa->spa_async_suspended != 0);
7749 spa->spa_async_suspended--;
7750 mutex_exit(&spa->spa_async_lock);
7751 spa_restart_removal(spa);
7753 zthr_t *condense_thread = spa->spa_condense_zthr;
7754 if (condense_thread != NULL)
7755 zthr_resume(condense_thread);
7757 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7758 if (discard_thread != NULL)
7759 zthr_resume(discard_thread);
7763 spa_async_tasks_pending(spa_t *spa)
7765 uint_t non_config_tasks;
7767 boolean_t config_task_suspended;
7769 non_config_tasks = spa->spa_async_tasks & ~(SPA_ASYNC_CONFIG_UPDATE |
7771 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
7772 if (spa->spa_ccw_fail_time == 0) {
7773 config_task_suspended = B_FALSE;
7775 config_task_suspended =
7776 (gethrtime() - spa->spa_ccw_fail_time) <
7777 (zfs_ccw_retry_interval * NANOSEC);
7780 return (non_config_tasks || (config_task && !config_task_suspended));
7784 spa_async_dispatch(spa_t *spa)
7786 mutex_enter(&spa->spa_async_lock);
7787 if (spa_async_tasks_pending(spa) &&
7788 !spa->spa_async_suspended &&
7789 spa->spa_async_thread == NULL &&
7791 spa->spa_async_thread = thread_create(NULL, 0,
7792 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
7793 mutex_exit(&spa->spa_async_lock);
7797 spa_async_dispatch_vd(spa_t *spa)
7799 mutex_enter(&spa->spa_async_lock);
7800 if ((spa->spa_async_tasks & SPA_ASYNC_REMOVE) != 0 &&
7801 !spa->spa_async_suspended &&
7802 spa->spa_async_thread_vd == NULL &&
7804 spa->spa_async_thread_vd = thread_create(NULL, 0,
7805 spa_async_thread_vd, spa, 0, &p0, TS_RUN, maxclsyspri);
7806 mutex_exit(&spa->spa_async_lock);
7810 spa_async_request(spa_t *spa, int task)
7812 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
7813 mutex_enter(&spa->spa_async_lock);
7814 spa->spa_async_tasks |= task;
7815 mutex_exit(&spa->spa_async_lock);
7816 spa_async_dispatch_vd(spa);
7820 * ==========================================================================
7821 * SPA syncing routines
7822 * ==========================================================================
7826 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7829 bpobj_enqueue(bpo, bp, tx);
7834 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7838 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
7839 BP_GET_PSIZE(bp), zio->io_flags));
7844 * Note: this simple function is not inlined to make it easier to dtrace the
7845 * amount of time spent syncing frees.
7848 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
7850 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7851 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
7852 VERIFY(zio_wait(zio) == 0);
7856 * Note: this simple function is not inlined to make it easier to dtrace the
7857 * amount of time spent syncing deferred frees.
7860 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
7862 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7863 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
7864 spa_free_sync_cb, zio, tx), ==, 0);
7865 VERIFY0(zio_wait(zio));
7870 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
7872 char *packed = NULL;
7877 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
7880 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
7881 * information. This avoids the dmu_buf_will_dirty() path and
7882 * saves us a pre-read to get data we don't actually care about.
7884 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
7885 packed = kmem_alloc(bufsize, KM_SLEEP);
7887 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
7889 bzero(packed + nvsize, bufsize - nvsize);
7891 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
7893 kmem_free(packed, bufsize);
7895 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
7896 dmu_buf_will_dirty(db, tx);
7897 *(uint64_t *)db->db_data = nvsize;
7898 dmu_buf_rele(db, FTAG);
7902 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
7903 const char *config, const char *entry)
7913 * Update the MOS nvlist describing the list of available devices.
7914 * spa_validate_aux() will have already made sure this nvlist is
7915 * valid and the vdevs are labeled appropriately.
7917 if (sav->sav_object == 0) {
7918 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
7919 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
7920 sizeof (uint64_t), tx);
7921 VERIFY(zap_update(spa->spa_meta_objset,
7922 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
7923 &sav->sav_object, tx) == 0);
7926 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7927 if (sav->sav_count == 0) {
7928 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
7930 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
7931 for (i = 0; i < sav->sav_count; i++)
7932 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
7933 B_FALSE, VDEV_CONFIG_L2CACHE);
7934 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
7935 sav->sav_count) == 0);
7936 for (i = 0; i < sav->sav_count; i++)
7937 nvlist_free(list[i]);
7938 kmem_free(list, sav->sav_count * sizeof (void *));
7941 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
7942 nvlist_free(nvroot);
7944 sav->sav_sync = B_FALSE;
7948 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
7949 * The all-vdev ZAP must be empty.
7952 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
7954 spa_t *spa = vd->vdev_spa;
7955 if (vd->vdev_top_zap != 0) {
7956 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7957 vd->vdev_top_zap, tx));
7959 if (vd->vdev_leaf_zap != 0) {
7960 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7961 vd->vdev_leaf_zap, tx));
7963 for (uint64_t i = 0; i < vd->vdev_children; i++) {
7964 spa_avz_build(vd->vdev_child[i], avz, tx);
7969 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
7974 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
7975 * its config may not be dirty but we still need to build per-vdev ZAPs.
7976 * Similarly, if the pool is being assembled (e.g. after a split), we
7977 * need to rebuild the AVZ although the config may not be dirty.
7979 if (list_is_empty(&spa->spa_config_dirty_list) &&
7980 spa->spa_avz_action == AVZ_ACTION_NONE)
7983 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7985 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
7986 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
7987 spa->spa_all_vdev_zaps != 0);
7989 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
7990 /* Make and build the new AVZ */
7991 uint64_t new_avz = zap_create(spa->spa_meta_objset,
7992 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7993 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7995 /* Diff old AVZ with new one */
7999 for (zap_cursor_init(&zc, spa->spa_meta_objset,
8000 spa->spa_all_vdev_zaps);
8001 zap_cursor_retrieve(&zc, &za) == 0;
8002 zap_cursor_advance(&zc)) {
8003 uint64_t vdzap = za.za_first_integer;
8004 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
8007 * ZAP is listed in old AVZ but not in new one;
8010 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
8015 zap_cursor_fini(&zc);
8017 /* Destroy the old AVZ */
8018 VERIFY0(zap_destroy(spa->spa_meta_objset,
8019 spa->spa_all_vdev_zaps, tx));
8021 /* Replace the old AVZ in the dir obj with the new one */
8022 VERIFY0(zap_update(spa->spa_meta_objset,
8023 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
8024 sizeof (new_avz), 1, &new_avz, tx));
8026 spa->spa_all_vdev_zaps = new_avz;
8027 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
8031 /* Walk through the AVZ and destroy all listed ZAPs */
8032 for (zap_cursor_init(&zc, spa->spa_meta_objset,
8033 spa->spa_all_vdev_zaps);
8034 zap_cursor_retrieve(&zc, &za) == 0;
8035 zap_cursor_advance(&zc)) {
8036 uint64_t zap = za.za_first_integer;
8037 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
8040 zap_cursor_fini(&zc);
8042 /* Destroy and unlink the AVZ itself */
8043 VERIFY0(zap_destroy(spa->spa_meta_objset,
8044 spa->spa_all_vdev_zaps, tx));
8045 VERIFY0(zap_remove(spa->spa_meta_objset,
8046 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
8047 spa->spa_all_vdev_zaps = 0;
8050 if (spa->spa_all_vdev_zaps == 0) {
8051 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
8052 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
8053 DMU_POOL_VDEV_ZAP_MAP, tx);
8055 spa->spa_avz_action = AVZ_ACTION_NONE;
8057 /* Create ZAPs for vdevs that don't have them. */
8058 vdev_construct_zaps(spa->spa_root_vdev, tx);
8060 config = spa_config_generate(spa, spa->spa_root_vdev,
8061 dmu_tx_get_txg(tx), B_FALSE);
8064 * If we're upgrading the spa version then make sure that
8065 * the config object gets updated with the correct version.
8067 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
8068 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
8069 spa->spa_uberblock.ub_version);
8071 spa_config_exit(spa, SCL_STATE, FTAG);
8073 nvlist_free(spa->spa_config_syncing);
8074 spa->spa_config_syncing = config;
8076 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
8080 spa_sync_version(void *arg, dmu_tx_t *tx)
8082 uint64_t *versionp = arg;
8083 uint64_t version = *versionp;
8084 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
8087 * Setting the version is special cased when first creating the pool.
8089 ASSERT(tx->tx_txg != TXG_INITIAL);
8091 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
8092 ASSERT(version >= spa_version(spa));
8094 spa->spa_uberblock.ub_version = version;
8095 vdev_config_dirty(spa->spa_root_vdev);
8096 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
8100 * Set zpool properties.
8103 spa_sync_props(void *arg, dmu_tx_t *tx)
8105 nvlist_t *nvp = arg;
8106 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
8107 objset_t *mos = spa->spa_meta_objset;
8108 nvpair_t *elem = NULL;
8110 mutex_enter(&spa->spa_props_lock);
8112 while ((elem = nvlist_next_nvpair(nvp, elem))) {
8114 char *strval, *fname;
8116 const char *propname;
8117 zprop_type_t proptype;
8120 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
8121 case ZPOOL_PROP_INVAL:
8123 * We checked this earlier in spa_prop_validate().
8125 ASSERT(zpool_prop_feature(nvpair_name(elem)));
8127 fname = strchr(nvpair_name(elem), '@') + 1;
8128 VERIFY0(zfeature_lookup_name(fname, &fid));
8130 spa_feature_enable(spa, fid, tx);
8131 spa_history_log_internal(spa, "set", tx,
8132 "%s=enabled", nvpair_name(elem));
8135 case ZPOOL_PROP_VERSION:
8136 intval = fnvpair_value_uint64(elem);
8138 * The version is synced seperatly before other
8139 * properties and should be correct by now.
8141 ASSERT3U(spa_version(spa), >=, intval);
8144 case ZPOOL_PROP_ALTROOT:
8146 * 'altroot' is a non-persistent property. It should
8147 * have been set temporarily at creation or import time.
8149 ASSERT(spa->spa_root != NULL);
8152 case ZPOOL_PROP_READONLY:
8153 case ZPOOL_PROP_CACHEFILE:
8155 * 'readonly' and 'cachefile' are also non-persisitent
8159 case ZPOOL_PROP_COMMENT:
8160 strval = fnvpair_value_string(elem);
8161 if (spa->spa_comment != NULL)
8162 spa_strfree(spa->spa_comment);
8163 spa->spa_comment = spa_strdup(strval);
8165 * We need to dirty the configuration on all the vdevs
8166 * so that their labels get updated. It's unnecessary
8167 * to do this for pool creation since the vdev's
8168 * configuratoin has already been dirtied.
8170 if (tx->tx_txg != TXG_INITIAL)
8171 vdev_config_dirty(spa->spa_root_vdev);
8172 spa_history_log_internal(spa, "set", tx,
8173 "%s=%s", nvpair_name(elem), strval);
8177 * Set pool property values in the poolprops mos object.
8179 if (spa->spa_pool_props_object == 0) {
8180 spa->spa_pool_props_object =
8181 zap_create_link(mos, DMU_OT_POOL_PROPS,
8182 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
8186 /* normalize the property name */
8187 propname = zpool_prop_to_name(prop);
8188 proptype = zpool_prop_get_type(prop);
8190 if (nvpair_type(elem) == DATA_TYPE_STRING) {
8191 ASSERT(proptype == PROP_TYPE_STRING);
8192 strval = fnvpair_value_string(elem);
8193 VERIFY0(zap_update(mos,
8194 spa->spa_pool_props_object, propname,
8195 1, strlen(strval) + 1, strval, tx));
8196 spa_history_log_internal(spa, "set", tx,
8197 "%s=%s", nvpair_name(elem), strval);
8198 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
8199 intval = fnvpair_value_uint64(elem);
8201 if (proptype == PROP_TYPE_INDEX) {
8203 VERIFY0(zpool_prop_index_to_string(
8204 prop, intval, &unused));
8206 VERIFY0(zap_update(mos,
8207 spa->spa_pool_props_object, propname,
8208 8, 1, &intval, tx));
8209 spa_history_log_internal(spa, "set", tx,
8210 "%s=%lld", nvpair_name(elem), intval);
8212 ASSERT(0); /* not allowed */
8216 case ZPOOL_PROP_DELEGATION:
8217 spa->spa_delegation = intval;
8219 case ZPOOL_PROP_BOOTFS:
8220 spa->spa_bootfs = intval;
8222 case ZPOOL_PROP_FAILUREMODE:
8223 spa->spa_failmode = intval;
8225 case ZPOOL_PROP_AUTOEXPAND:
8226 spa->spa_autoexpand = intval;
8227 if (tx->tx_txg != TXG_INITIAL)
8228 spa_async_request(spa,
8229 SPA_ASYNC_AUTOEXPAND);
8231 case ZPOOL_PROP_MULTIHOST:
8232 spa->spa_multihost = intval;
8234 case ZPOOL_PROP_DEDUPDITTO:
8235 spa->spa_dedup_ditto = intval;
8244 mutex_exit(&spa->spa_props_lock);
8248 * Perform one-time upgrade on-disk changes. spa_version() does not
8249 * reflect the new version this txg, so there must be no changes this
8250 * txg to anything that the upgrade code depends on after it executes.
8251 * Therefore this must be called after dsl_pool_sync() does the sync
8255 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
8257 dsl_pool_t *dp = spa->spa_dsl_pool;
8259 ASSERT(spa->spa_sync_pass == 1);
8261 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
8263 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
8264 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
8265 dsl_pool_create_origin(dp, tx);
8267 /* Keeping the origin open increases spa_minref */
8268 spa->spa_minref += 3;
8271 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
8272 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
8273 dsl_pool_upgrade_clones(dp, tx);
8276 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
8277 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
8278 dsl_pool_upgrade_dir_clones(dp, tx);
8280 /* Keeping the freedir open increases spa_minref */
8281 spa->spa_minref += 3;
8284 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
8285 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8286 spa_feature_create_zap_objects(spa, tx);
8290 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
8291 * when possibility to use lz4 compression for metadata was added
8292 * Old pools that have this feature enabled must be upgraded to have
8293 * this feature active
8295 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8296 boolean_t lz4_en = spa_feature_is_enabled(spa,
8297 SPA_FEATURE_LZ4_COMPRESS);
8298 boolean_t lz4_ac = spa_feature_is_active(spa,
8299 SPA_FEATURE_LZ4_COMPRESS);
8301 if (lz4_en && !lz4_ac)
8302 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
8306 * If we haven't written the salt, do so now. Note that the
8307 * feature may not be activated yet, but that's fine since
8308 * the presence of this ZAP entry is backwards compatible.
8310 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
8311 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
8312 VERIFY0(zap_add(spa->spa_meta_objset,
8313 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
8314 sizeof (spa->spa_cksum_salt.zcs_bytes),
8315 spa->spa_cksum_salt.zcs_bytes, tx));
8318 rrw_exit(&dp->dp_config_rwlock, FTAG);
8322 vdev_indirect_state_sync_verify(vdev_t *vd)
8324 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
8325 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
8327 if (vd->vdev_ops == &vdev_indirect_ops) {
8328 ASSERT(vim != NULL);
8329 ASSERT(vib != NULL);
8332 if (vdev_obsolete_sm_object(vd) != 0) {
8333 ASSERT(vd->vdev_obsolete_sm != NULL);
8334 ASSERT(vd->vdev_removing ||
8335 vd->vdev_ops == &vdev_indirect_ops);
8336 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
8337 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
8339 ASSERT3U(vdev_obsolete_sm_object(vd), ==,
8340 space_map_object(vd->vdev_obsolete_sm));
8341 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
8342 space_map_allocated(vd->vdev_obsolete_sm));
8344 ASSERT(vd->vdev_obsolete_segments != NULL);
8347 * Since frees / remaps to an indirect vdev can only
8348 * happen in syncing context, the obsolete segments
8349 * tree must be empty when we start syncing.
8351 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
8355 * Sync the specified transaction group. New blocks may be dirtied as
8356 * part of the process, so we iterate until it converges.
8359 spa_sync(spa_t *spa, uint64_t txg)
8361 dsl_pool_t *dp = spa->spa_dsl_pool;
8362 objset_t *mos = spa->spa_meta_objset;
8363 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
8364 metaslab_class_t *normal = spa_normal_class(spa);
8365 metaslab_class_t *special = spa_special_class(spa);
8366 metaslab_class_t *dedup = spa_dedup_class(spa);
8367 vdev_t *rvd = spa->spa_root_vdev;
8371 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
8372 zfs_vdev_queue_depth_pct / 100;
8374 VERIFY(spa_writeable(spa));
8377 * Wait for i/os issued in open context that need to complete
8378 * before this txg syncs.
8380 (void) zio_wait(spa->spa_txg_zio[txg & TXG_MASK]);
8381 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL,
8385 * Lock out configuration changes.
8387 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8389 spa->spa_syncing_txg = txg;
8390 spa->spa_sync_pass = 0;
8392 for (int i = 0; i < spa->spa_alloc_count; i++) {
8393 mutex_enter(&spa->spa_alloc_locks[i]);
8394 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8395 mutex_exit(&spa->spa_alloc_locks[i]);
8399 * If there are any pending vdev state changes, convert them
8400 * into config changes that go out with this transaction group.
8402 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8403 while (list_head(&spa->spa_state_dirty_list) != NULL) {
8405 * We need the write lock here because, for aux vdevs,
8406 * calling vdev_config_dirty() modifies sav_config.
8407 * This is ugly and will become unnecessary when we
8408 * eliminate the aux vdev wart by integrating all vdevs
8409 * into the root vdev tree.
8411 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8412 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
8413 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
8414 vdev_state_clean(vd);
8415 vdev_config_dirty(vd);
8417 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8418 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
8420 spa_config_exit(spa, SCL_STATE, FTAG);
8422 tx = dmu_tx_create_assigned(dp, txg);
8424 spa->spa_sync_starttime = gethrtime();
8426 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
8427 spa->spa_sync_starttime + spa->spa_deadman_synctime));
8428 #else /* !illumos */
8430 callout_schedule(&spa->spa_deadman_cycid,
8431 hz * spa->spa_deadman_synctime / NANOSEC);
8433 #endif /* illumos */
8436 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
8437 * set spa_deflate if we have no raid-z vdevs.
8439 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
8440 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
8443 for (i = 0; i < rvd->vdev_children; i++) {
8444 vd = rvd->vdev_child[i];
8445 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
8448 if (i == rvd->vdev_children) {
8449 spa->spa_deflate = TRUE;
8450 VERIFY(0 == zap_add(spa->spa_meta_objset,
8451 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
8452 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
8457 * Set the top-level vdev's max queue depth. Evaluate each
8458 * top-level's async write queue depth in case it changed.
8459 * The max queue depth will not change in the middle of syncing
8462 uint64_t slots_per_allocator = 0;
8463 for (int c = 0; c < rvd->vdev_children; c++) {
8464 vdev_t *tvd = rvd->vdev_child[c];
8465 metaslab_group_t *mg = tvd->vdev_mg;
8466 metaslab_class_t *mc;
8468 if (mg == NULL || !metaslab_group_initialized(mg))
8472 if (mc != normal && mc != special && mc != dedup)
8476 * It is safe to do a lock-free check here because only async
8477 * allocations look at mg_max_alloc_queue_depth, and async
8478 * allocations all happen from spa_sync().
8480 for (int i = 0; i < spa->spa_alloc_count; i++)
8481 ASSERT0(zfs_refcount_count(
8482 &(mg->mg_alloc_queue_depth[i])));
8483 mg->mg_max_alloc_queue_depth = max_queue_depth;
8485 for (int i = 0; i < spa->spa_alloc_count; i++) {
8486 mg->mg_cur_max_alloc_queue_depth[i] =
8487 zfs_vdev_def_queue_depth;
8489 slots_per_allocator += zfs_vdev_def_queue_depth;
8492 for (int i = 0; i < spa->spa_alloc_count; i++) {
8493 ASSERT0(zfs_refcount_count(&normal->mc_alloc_slots[i]));
8494 ASSERT0(zfs_refcount_count(&special->mc_alloc_slots[i]));
8495 ASSERT0(zfs_refcount_count(&dedup->mc_alloc_slots[i]));
8496 normal->mc_alloc_max_slots[i] = slots_per_allocator;
8497 special->mc_alloc_max_slots[i] = slots_per_allocator;
8498 dedup->mc_alloc_max_slots[i] = slots_per_allocator;
8500 normal->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8501 special->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8502 dedup->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8504 for (int c = 0; c < rvd->vdev_children; c++) {
8505 vdev_t *vd = rvd->vdev_child[c];
8506 vdev_indirect_state_sync_verify(vd);
8508 if (vdev_indirect_should_condense(vd)) {
8509 spa_condense_indirect_start_sync(vd, tx);
8515 * Iterate to convergence.
8518 int pass = ++spa->spa_sync_pass;
8520 spa_sync_config_object(spa, tx);
8521 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
8522 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
8523 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
8524 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
8525 spa_errlog_sync(spa, txg);
8526 dsl_pool_sync(dp, txg);
8528 if (pass < zfs_sync_pass_deferred_free) {
8529 spa_sync_frees(spa, free_bpl, tx);
8532 * We can not defer frees in pass 1, because
8533 * we sync the deferred frees later in pass 1.
8535 ASSERT3U(pass, >, 1);
8536 bplist_iterate(free_bpl, bpobj_enqueue_cb,
8537 &spa->spa_deferred_bpobj, tx);
8541 dsl_scan_sync(dp, tx);
8543 if (spa->spa_vdev_removal != NULL)
8546 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
8551 spa_sync_upgrades(spa, tx);
8553 spa->spa_uberblock.ub_rootbp.blk_birth);
8555 * Note: We need to check if the MOS is dirty
8556 * because we could have marked the MOS dirty
8557 * without updating the uberblock (e.g. if we
8558 * have sync tasks but no dirty user data). We
8559 * need to check the uberblock's rootbp because
8560 * it is updated if we have synced out dirty
8561 * data (though in this case the MOS will most
8562 * likely also be dirty due to second order
8563 * effects, we don't want to rely on that here).
8565 if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
8566 !dmu_objset_is_dirty(mos, txg)) {
8568 * Nothing changed on the first pass,
8569 * therefore this TXG is a no-op. Avoid
8570 * syncing deferred frees, so that we
8571 * can keep this TXG as a no-op.
8573 ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
8575 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8576 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
8577 ASSERT(txg_list_empty(&dp->dp_early_sync_tasks,
8581 spa_sync_deferred_frees(spa, tx);
8584 } while (dmu_objset_is_dirty(mos, txg));
8586 if (!list_is_empty(&spa->spa_config_dirty_list)) {
8588 * Make sure that the number of ZAPs for all the vdevs matches
8589 * the number of ZAPs in the per-vdev ZAP list. This only gets
8590 * called if the config is dirty; otherwise there may be
8591 * outstanding AVZ operations that weren't completed in
8592 * spa_sync_config_object.
8594 uint64_t all_vdev_zap_entry_count;
8595 ASSERT0(zap_count(spa->spa_meta_objset,
8596 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
8597 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
8598 all_vdev_zap_entry_count);
8601 if (spa->spa_vdev_removal != NULL) {
8602 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
8606 * Rewrite the vdev configuration (which includes the uberblock)
8607 * to commit the transaction group.
8609 * If there are no dirty vdevs, we sync the uberblock to a few
8610 * random top-level vdevs that are known to be visible in the
8611 * config cache (see spa_vdev_add() for a complete description).
8612 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
8616 * We hold SCL_STATE to prevent vdev open/close/etc.
8617 * while we're attempting to write the vdev labels.
8619 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8621 if (list_is_empty(&spa->spa_config_dirty_list)) {
8622 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
8624 int children = rvd->vdev_children;
8625 int c0 = spa_get_random(children);
8627 for (int c = 0; c < children; c++) {
8628 vd = rvd->vdev_child[(c0 + c) % children];
8630 /* Stop when revisiting the first vdev */
8631 if (c > 0 && svd[0] == vd)
8634 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
8635 !vdev_is_concrete(vd))
8638 svd[svdcount++] = vd;
8639 if (svdcount == SPA_SYNC_MIN_VDEVS)
8642 error = vdev_config_sync(svd, svdcount, txg);
8644 error = vdev_config_sync(rvd->vdev_child,
8645 rvd->vdev_children, txg);
8649 spa->spa_last_synced_guid = rvd->vdev_guid;
8651 spa_config_exit(spa, SCL_STATE, FTAG);
8655 zio_suspend(spa, NULL, ZIO_SUSPEND_IOERR);
8656 zio_resume_wait(spa);
8661 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
8662 #else /* !illumos */
8664 callout_drain(&spa->spa_deadman_cycid);
8666 #endif /* illumos */
8669 * Clear the dirty config list.
8671 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
8672 vdev_config_clean(vd);
8675 * Now that the new config has synced transactionally,
8676 * let it become visible to the config cache.
8678 if (spa->spa_config_syncing != NULL) {
8679 spa_config_set(spa, spa->spa_config_syncing);
8680 spa->spa_config_txg = txg;
8681 spa->spa_config_syncing = NULL;
8684 dsl_pool_sync_done(dp, txg);
8686 for (int i = 0; i < spa->spa_alloc_count; i++) {
8687 mutex_enter(&spa->spa_alloc_locks[i]);
8688 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8689 mutex_exit(&spa->spa_alloc_locks[i]);
8693 * Update usable space statistics.
8695 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
8697 vdev_sync_done(vd, txg);
8699 spa_update_dspace(spa);
8702 * It had better be the case that we didn't dirty anything
8703 * since vdev_config_sync().
8705 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8706 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8707 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
8709 while (zfs_pause_spa_sync)
8712 spa->spa_sync_pass = 0;
8715 * Update the last synced uberblock here. We want to do this at
8716 * the end of spa_sync() so that consumers of spa_last_synced_txg()
8717 * will be guaranteed that all the processing associated with
8718 * that txg has been completed.
8720 spa->spa_ubsync = spa->spa_uberblock;
8721 spa_config_exit(spa, SCL_CONFIG, FTAG);
8723 spa_handle_ignored_writes(spa);
8726 * If any async tasks have been requested, kick them off.
8728 spa_async_dispatch(spa);
8729 spa_async_dispatch_vd(spa);
8733 * Sync all pools. We don't want to hold the namespace lock across these
8734 * operations, so we take a reference on the spa_t and drop the lock during the
8738 spa_sync_allpools(void)
8741 mutex_enter(&spa_namespace_lock);
8742 while ((spa = spa_next(spa)) != NULL) {
8743 if (spa_state(spa) != POOL_STATE_ACTIVE ||
8744 !spa_writeable(spa) || spa_suspended(spa))
8746 spa_open_ref(spa, FTAG);
8747 mutex_exit(&spa_namespace_lock);
8748 txg_wait_synced(spa_get_dsl(spa), 0);
8749 mutex_enter(&spa_namespace_lock);
8750 spa_close(spa, FTAG);
8752 mutex_exit(&spa_namespace_lock);
8756 * ==========================================================================
8757 * Miscellaneous routines
8758 * ==========================================================================
8762 * Remove all pools in the system.
8770 * Remove all cached state. All pools should be closed now,
8771 * so every spa in the AVL tree should be unreferenced.
8773 mutex_enter(&spa_namespace_lock);
8774 while ((spa = spa_next(NULL)) != NULL) {
8776 * Stop async tasks. The async thread may need to detach
8777 * a device that's been replaced, which requires grabbing
8778 * spa_namespace_lock, so we must drop it here.
8780 spa_open_ref(spa, FTAG);
8781 mutex_exit(&spa_namespace_lock);
8782 spa_async_suspend(spa);
8783 mutex_enter(&spa_namespace_lock);
8784 spa_close(spa, FTAG);
8786 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
8788 spa_deactivate(spa);
8792 mutex_exit(&spa_namespace_lock);
8796 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
8801 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
8805 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
8806 vd = spa->spa_l2cache.sav_vdevs[i];
8807 if (vd->vdev_guid == guid)
8811 for (i = 0; i < spa->spa_spares.sav_count; i++) {
8812 vd = spa->spa_spares.sav_vdevs[i];
8813 if (vd->vdev_guid == guid)
8822 spa_upgrade(spa_t *spa, uint64_t version)
8824 ASSERT(spa_writeable(spa));
8826 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
8829 * This should only be called for a non-faulted pool, and since a
8830 * future version would result in an unopenable pool, this shouldn't be
8833 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
8834 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
8836 spa->spa_uberblock.ub_version = version;
8837 vdev_config_dirty(spa->spa_root_vdev);
8839 spa_config_exit(spa, SCL_ALL, FTAG);
8841 txg_wait_synced(spa_get_dsl(spa), 0);
8845 spa_has_spare(spa_t *spa, uint64_t guid)
8849 spa_aux_vdev_t *sav = &spa->spa_spares;
8851 for (i = 0; i < sav->sav_count; i++)
8852 if (sav->sav_vdevs[i]->vdev_guid == guid)
8855 for (i = 0; i < sav->sav_npending; i++) {
8856 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
8857 &spareguid) == 0 && spareguid == guid)
8865 * Check if a pool has an active shared spare device.
8866 * Note: reference count of an active spare is 2, as a spare and as a replace
8869 spa_has_active_shared_spare(spa_t *spa)
8873 spa_aux_vdev_t *sav = &spa->spa_spares;
8875 for (i = 0; i < sav->sav_count; i++) {
8876 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
8877 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
8886 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8888 sysevent_t *ev = NULL;
8890 sysevent_attr_list_t *attr = NULL;
8891 sysevent_value_t value;
8893 ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
8897 value.value_type = SE_DATA_TYPE_STRING;
8898 value.value.sv_string = spa_name(spa);
8899 if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
8902 value.value_type = SE_DATA_TYPE_UINT64;
8903 value.value.sv_uint64 = spa_guid(spa);
8904 if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
8908 value.value_type = SE_DATA_TYPE_UINT64;
8909 value.value.sv_uint64 = vd->vdev_guid;
8910 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
8914 if (vd->vdev_path) {
8915 value.value_type = SE_DATA_TYPE_STRING;
8916 value.value.sv_string = vd->vdev_path;
8917 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
8918 &value, SE_SLEEP) != 0)
8923 if (hist_nvl != NULL) {
8924 fnvlist_merge((nvlist_t *)attr, hist_nvl);
8927 if (sysevent_attach_attributes(ev, attr) != 0)
8933 sysevent_free_attr(attr);
8940 spa_event_post(sysevent_t *ev)
8945 (void) log_sysevent(ev, SE_SLEEP, &eid);
8951 spa_event_discard(sysevent_t *ev)
8959 * Post a sysevent corresponding to the given event. The 'name' must be one of
8960 * the event definitions in sys/sysevent/eventdefs.h. The payload will be
8961 * filled in from the spa and (optionally) the vdev and history nvl. This
8962 * doesn't do anything in the userland libzpool, as we don't want consumers to
8963 * misinterpret ztest or zdb as real changes.
8966 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8968 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));