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, 2017 by Delphix. All rights reserved.
25 * Copyright (c) 2018, Nexenta Systems, Inc. All rights reserved.
26 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27 * Copyright 2013 Saso Kiselkov. All rights reserved.
28 * Copyright (c) 2014 Integros [integros.com]
29 * Copyright 2016 Toomas Soome <tsoome@me.com>
30 * Copyright (c) 2016 Actifio, Inc. All rights reserved.
31 * Copyright (c) 2017 Datto Inc.
32 * Copyright 2017 Joyent, Inc.
33 * Copyright (c) 2017, Intel Corporation.
37 * SPA: Storage Pool Allocator
39 * This file contains all the routines used when modifying on-disk SPA state.
40 * This includes opening, importing, destroying, exporting a pool, and syncing a
44 #include <sys/zfs_context.h>
45 #include <sys/fm/fs/zfs.h>
46 #include <sys/spa_impl.h>
48 #include <sys/zio_checksum.h>
50 #include <sys/dmu_tx.h>
54 #include <sys/vdev_impl.h>
55 #include <sys/vdev_removal.h>
56 #include <sys/vdev_indirect_mapping.h>
57 #include <sys/vdev_indirect_births.h>
58 #include <sys/vdev_disk.h>
59 #include <sys/metaslab.h>
60 #include <sys/metaslab_impl.h>
62 #include <sys/uberblock_impl.h>
65 #include <sys/bpobj.h>
66 #include <sys/dmu_traverse.h>
67 #include <sys/dmu_objset.h>
68 #include <sys/unique.h>
69 #include <sys/dsl_pool.h>
70 #include <sys/dsl_dataset.h>
71 #include <sys/dsl_dir.h>
72 #include <sys/dsl_prop.h>
73 #include <sys/dsl_synctask.h>
74 #include <sys/fs/zfs.h>
76 #include <sys/callb.h>
77 #include <sys/systeminfo.h>
78 #include <sys/spa_boot.h>
79 #include <sys/zfs_ioctl.h>
80 #include <sys/dsl_scan.h>
81 #include <sys/zfeature.h>
82 #include <sys/dsl_destroy.h>
86 #include <sys/fm/protocol.h>
87 #include <sys/fm/util.h>
88 #include <sys/callb.h>
93 #include "zfs_comutil.h"
96 * The interval, in seconds, at which failed configuration cache file writes
99 int zfs_ccw_retry_interval = 300;
101 typedef enum zti_modes {
102 ZTI_MODE_FIXED, /* value is # of threads (min 1) */
103 ZTI_MODE_BATCH, /* cpu-intensive; value is ignored */
104 ZTI_MODE_NULL, /* don't create a taskq */
108 #define ZTI_P(n, q) { ZTI_MODE_FIXED, (n), (q) }
109 #define ZTI_PCT(n) { ZTI_MODE_ONLINE_PERCENT, (n), 1 }
110 #define ZTI_BATCH { ZTI_MODE_BATCH, 0, 1 }
111 #define ZTI_NULL { ZTI_MODE_NULL, 0, 0 }
113 #define ZTI_N(n) ZTI_P(n, 1)
114 #define ZTI_ONE ZTI_N(1)
116 typedef struct zio_taskq_info {
117 zti_modes_t zti_mode;
122 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
123 "iss", "iss_h", "int", "int_h"
127 * This table defines the taskq settings for each ZFS I/O type. When
128 * initializing a pool, we use this table to create an appropriately sized
129 * taskq. Some operations are low volume and therefore have a small, static
130 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
131 * macros. Other operations process a large amount of data; the ZTI_BATCH
132 * macro causes us to create a taskq oriented for throughput. Some operations
133 * are so high frequency and short-lived that the taskq itself can become a a
134 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
135 * additional degree of parallelism specified by the number of threads per-
136 * taskq and the number of taskqs; when dispatching an event in this case, the
137 * particular taskq is chosen at random.
139 * The different taskq priorities are to handle the different contexts (issue
140 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
141 * need to be handled with minimum delay.
143 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
144 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
145 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* NULL */
146 { ZTI_N(8), ZTI_NULL, ZTI_P(12, 8), ZTI_NULL }, /* READ */
147 { ZTI_BATCH, ZTI_N(5), ZTI_P(12, 8), ZTI_N(5) }, /* WRITE */
148 { ZTI_P(12, 8), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* FREE */
149 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* CLAIM */
150 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* IOCTL */
153 static void spa_sync_version(void *arg, dmu_tx_t *tx);
154 static void spa_sync_props(void *arg, dmu_tx_t *tx);
155 static boolean_t spa_has_active_shared_spare(spa_t *spa);
156 static int spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport);
157 static void spa_vdev_resilver_done(spa_t *spa);
159 uint_t zio_taskq_batch_pct = 75; /* 1 thread per cpu in pset */
160 boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
161 uint_t zio_taskq_basedc = 80; /* base duty cycle */
163 boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
166 * Report any spa_load_verify errors found, but do not fail spa_load.
167 * This is used by zdb to analyze non-idle pools.
169 boolean_t spa_load_verify_dryrun = B_FALSE;
172 * This (illegal) pool name is used when temporarily importing a spa_t in order
173 * to get the vdev stats associated with the imported devices.
175 #define TRYIMPORT_NAME "$import"
178 * For debugging purposes: print out vdev tree during pool import.
180 int spa_load_print_vdev_tree = B_FALSE;
183 * A non-zero value for zfs_max_missing_tvds means that we allow importing
184 * pools with missing top-level vdevs. This is strictly intended for advanced
185 * pool recovery cases since missing data is almost inevitable. Pools with
186 * missing devices can only be imported read-only for safety reasons, and their
187 * fail-mode will be automatically set to "continue".
189 * With 1 missing vdev we should be able to import the pool and mount all
190 * datasets. User data that was not modified after the missing device has been
191 * added should be recoverable. This means that snapshots created prior to the
192 * addition of that device should be completely intact.
194 * With 2 missing vdevs, some datasets may fail to mount since there are
195 * dataset statistics that are stored as regular metadata. Some data might be
196 * recoverable if those vdevs were added recently.
198 * With 3 or more missing vdevs, the pool is severely damaged and MOS entries
199 * may be missing entirely. Chances of data recovery are very low. Note that
200 * there are also risks of performing an inadvertent rewind as we might be
201 * missing all the vdevs with the latest uberblocks.
203 unsigned long zfs_max_missing_tvds = 0;
206 * The parameters below are similar to zfs_max_missing_tvds but are only
207 * intended for a preliminary open of the pool with an untrusted config which
208 * might be incomplete or out-dated.
210 * We are more tolerant for pools opened from a cachefile since we could have
211 * an out-dated cachefile where a device removal was not registered.
212 * We could have set the limit arbitrarily high but in the case where devices
213 * are really missing we would want to return the proper error codes; we chose
214 * SPA_DVAS_PER_BP - 1 so that some copies of the MOS would still be available
215 * and we get a chance to retrieve the trusted config.
217 uint64_t zfs_max_missing_tvds_cachefile = SPA_DVAS_PER_BP - 1;
220 * In the case where config was assembled by scanning device paths (/dev/dsks
221 * by default) we are less tolerant since all the existing devices should have
222 * been detected and we want spa_load to return the right error codes.
224 uint64_t zfs_max_missing_tvds_scan = 0;
227 * Debugging aid that pauses spa_sync() towards the end.
229 boolean_t zfs_pause_spa_sync = B_FALSE;
232 * ==========================================================================
233 * SPA properties routines
234 * ==========================================================================
238 * Add a (source=src, propname=propval) list to an nvlist.
241 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
242 uint64_t intval, zprop_source_t src)
244 const char *propname = zpool_prop_to_name(prop);
247 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
248 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
251 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
253 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
255 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
256 nvlist_free(propval);
260 * Get property values from the spa configuration.
263 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
265 vdev_t *rvd = spa->spa_root_vdev;
266 dsl_pool_t *pool = spa->spa_dsl_pool;
267 uint64_t size, alloc, cap, version;
268 const zprop_source_t src = ZPROP_SRC_NONE;
269 spa_config_dirent_t *dp;
270 metaslab_class_t *mc = spa_normal_class(spa);
272 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
275 alloc = metaslab_class_get_alloc(mc);
276 alloc += metaslab_class_get_alloc(spa_special_class(spa));
277 alloc += metaslab_class_get_alloc(spa_dedup_class(spa));
279 size = metaslab_class_get_space(mc);
280 size += metaslab_class_get_space(spa_special_class(spa));
281 size += metaslab_class_get_space(spa_dedup_class(spa));
283 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
284 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
285 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
286 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
288 spa_prop_add_list(*nvp, ZPOOL_PROP_CHECKPOINT, NULL,
289 spa->spa_checkpoint_info.sci_dspace, src);
291 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
292 metaslab_class_fragmentation(mc), src);
293 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
294 metaslab_class_expandable_space(mc), src);
295 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
296 (spa_mode(spa) == FREAD), src);
298 cap = (size == 0) ? 0 : (alloc * 100 / size);
299 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
301 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
302 ddt_get_pool_dedup_ratio(spa), src);
304 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
305 rvd->vdev_state, src);
307 version = spa_version(spa);
308 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION)) {
309 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL,
310 version, ZPROP_SRC_DEFAULT);
312 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL,
313 version, ZPROP_SRC_LOCAL);
315 spa_prop_add_list(*nvp, ZPOOL_PROP_LOAD_GUID,
316 NULL, spa_load_guid(spa), src);
321 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
322 * when opening pools before this version freedir will be NULL.
324 if (pool->dp_free_dir != NULL) {
325 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
326 dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
329 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
333 if (pool->dp_leak_dir != NULL) {
334 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
335 dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
338 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
343 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
345 if (spa->spa_comment != NULL) {
346 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
350 if (spa->spa_root != NULL)
351 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
354 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
355 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
356 MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
358 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
359 SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
362 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE)) {
363 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
364 DNODE_MAX_SIZE, ZPROP_SRC_NONE);
366 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
367 DNODE_MIN_SIZE, ZPROP_SRC_NONE);
370 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
371 if (dp->scd_path == NULL) {
372 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
373 "none", 0, ZPROP_SRC_LOCAL);
374 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
375 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
376 dp->scd_path, 0, ZPROP_SRC_LOCAL);
382 * Get zpool property values.
385 spa_prop_get(spa_t *spa, nvlist_t **nvp)
387 objset_t *mos = spa->spa_meta_objset;
392 err = nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP);
396 mutex_enter(&spa->spa_props_lock);
399 * Get properties from the spa config.
401 spa_prop_get_config(spa, nvp);
403 /* If no pool property object, no more prop to get. */
404 if (mos == NULL || spa->spa_pool_props_object == 0) {
405 mutex_exit(&spa->spa_props_lock);
410 * Get properties from the MOS pool property object.
412 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
413 (err = zap_cursor_retrieve(&zc, &za)) == 0;
414 zap_cursor_advance(&zc)) {
417 zprop_source_t src = ZPROP_SRC_DEFAULT;
420 if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
423 switch (za.za_integer_length) {
425 /* integer property */
426 if (za.za_first_integer !=
427 zpool_prop_default_numeric(prop))
428 src = ZPROP_SRC_LOCAL;
430 if (prop == ZPOOL_PROP_BOOTFS) {
432 dsl_dataset_t *ds = NULL;
434 dp = spa_get_dsl(spa);
435 dsl_pool_config_enter(dp, FTAG);
436 if ((err = dsl_dataset_hold_obj(dp,
437 za.za_first_integer, FTAG, &ds))) {
438 dsl_pool_config_exit(dp, FTAG);
442 strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
444 dsl_dataset_name(ds, strval);
445 dsl_dataset_rele(ds, FTAG);
446 dsl_pool_config_exit(dp, FTAG);
449 intval = za.za_first_integer;
452 spa_prop_add_list(*nvp, prop, strval, intval, src);
455 kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
460 /* string property */
461 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
462 err = zap_lookup(mos, spa->spa_pool_props_object,
463 za.za_name, 1, za.za_num_integers, strval);
465 kmem_free(strval, za.za_num_integers);
468 spa_prop_add_list(*nvp, prop, strval, 0, src);
469 kmem_free(strval, za.za_num_integers);
476 zap_cursor_fini(&zc);
477 mutex_exit(&spa->spa_props_lock);
479 if (err && err != ENOENT) {
489 * Validate the given pool properties nvlist and modify the list
490 * for the property values to be set.
493 spa_prop_validate(spa_t *spa, nvlist_t *props)
496 int error = 0, reset_bootfs = 0;
498 boolean_t has_feature = B_FALSE;
501 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
503 char *strval, *slash, *check, *fname;
504 const char *propname = nvpair_name(elem);
505 zpool_prop_t prop = zpool_name_to_prop(propname);
508 case ZPOOL_PROP_INVAL:
509 if (!zpool_prop_feature(propname)) {
510 error = SET_ERROR(EINVAL);
515 * Sanitize the input.
517 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
518 error = SET_ERROR(EINVAL);
522 if (nvpair_value_uint64(elem, &intval) != 0) {
523 error = SET_ERROR(EINVAL);
528 error = SET_ERROR(EINVAL);
532 fname = strchr(propname, '@') + 1;
533 if (zfeature_lookup_name(fname, NULL) != 0) {
534 error = SET_ERROR(EINVAL);
538 has_feature = B_TRUE;
541 case ZPOOL_PROP_VERSION:
542 error = nvpair_value_uint64(elem, &intval);
544 (intval < spa_version(spa) ||
545 intval > SPA_VERSION_BEFORE_FEATURES ||
547 error = SET_ERROR(EINVAL);
550 case ZPOOL_PROP_DELEGATION:
551 case ZPOOL_PROP_AUTOREPLACE:
552 case ZPOOL_PROP_LISTSNAPS:
553 case ZPOOL_PROP_AUTOEXPAND:
554 error = nvpair_value_uint64(elem, &intval);
555 if (!error && intval > 1)
556 error = SET_ERROR(EINVAL);
559 case ZPOOL_PROP_MULTIHOST:
560 error = nvpair_value_uint64(elem, &intval);
561 if (!error && intval > 1)
562 error = SET_ERROR(EINVAL);
564 if (!error && !spa_get_hostid())
565 error = SET_ERROR(ENOTSUP);
569 case ZPOOL_PROP_BOOTFS:
571 * If the pool version is less than SPA_VERSION_BOOTFS,
572 * or the pool is still being created (version == 0),
573 * the bootfs property cannot be set.
575 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
576 error = SET_ERROR(ENOTSUP);
581 * Make sure the vdev config is bootable
583 if (!vdev_is_bootable(spa->spa_root_vdev)) {
584 error = SET_ERROR(ENOTSUP);
590 error = nvpair_value_string(elem, &strval);
596 if (strval == NULL || strval[0] == '\0') {
597 objnum = zpool_prop_default_numeric(
602 error = dmu_objset_hold(strval, FTAG, &os);
607 * Must be ZPL, and its property settings
608 * must be supported by GRUB (compression
609 * is not gzip, and large blocks or large
610 * dnodes are not used).
613 if (dmu_objset_type(os) != DMU_OST_ZFS) {
614 error = SET_ERROR(ENOTSUP);
616 dsl_prop_get_int_ds(dmu_objset_ds(os),
617 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
619 !BOOTFS_COMPRESS_VALID(propval)) {
620 error = SET_ERROR(ENOTSUP);
622 dsl_prop_get_int_ds(dmu_objset_ds(os),
623 zfs_prop_to_name(ZFS_PROP_DNODESIZE),
625 propval != ZFS_DNSIZE_LEGACY) {
626 error = SET_ERROR(ENOTSUP);
628 objnum = dmu_objset_id(os);
630 dmu_objset_rele(os, FTAG);
634 case ZPOOL_PROP_FAILUREMODE:
635 error = nvpair_value_uint64(elem, &intval);
636 if (!error && intval > ZIO_FAILURE_MODE_PANIC)
637 error = SET_ERROR(EINVAL);
640 * This is a special case which only occurs when
641 * the pool has completely failed. This allows
642 * the user to change the in-core failmode property
643 * without syncing it out to disk (I/Os might
644 * currently be blocked). We do this by returning
645 * EIO to the caller (spa_prop_set) to trick it
646 * into thinking we encountered a property validation
649 if (!error && spa_suspended(spa)) {
650 spa->spa_failmode = intval;
651 error = SET_ERROR(EIO);
655 case ZPOOL_PROP_CACHEFILE:
656 if ((error = nvpair_value_string(elem, &strval)) != 0)
659 if (strval[0] == '\0')
662 if (strcmp(strval, "none") == 0)
665 if (strval[0] != '/') {
666 error = SET_ERROR(EINVAL);
670 slash = strrchr(strval, '/');
671 ASSERT(slash != NULL);
673 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
674 strcmp(slash, "/..") == 0)
675 error = SET_ERROR(EINVAL);
678 case ZPOOL_PROP_COMMENT:
679 if ((error = nvpair_value_string(elem, &strval)) != 0)
681 for (check = strval; *check != '\0'; check++) {
682 if (!isprint(*check)) {
683 error = SET_ERROR(EINVAL);
687 if (strlen(strval) > ZPROP_MAX_COMMENT)
688 error = SET_ERROR(E2BIG);
691 case ZPOOL_PROP_DEDUPDITTO:
692 if (spa_version(spa) < SPA_VERSION_DEDUP)
693 error = SET_ERROR(ENOTSUP);
695 error = nvpair_value_uint64(elem, &intval);
697 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
698 error = SET_ERROR(EINVAL);
709 if (!error && reset_bootfs) {
710 error = nvlist_remove(props,
711 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
714 error = nvlist_add_uint64(props,
715 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
723 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
726 spa_config_dirent_t *dp;
728 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
732 dp = kmem_alloc(sizeof (spa_config_dirent_t),
735 if (cachefile[0] == '\0')
736 dp->scd_path = spa_strdup(spa_config_path);
737 else if (strcmp(cachefile, "none") == 0)
740 dp->scd_path = spa_strdup(cachefile);
742 list_insert_head(&spa->spa_config_list, dp);
744 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
748 spa_prop_set(spa_t *spa, nvlist_t *nvp)
751 nvpair_t *elem = NULL;
752 boolean_t need_sync = B_FALSE;
754 if ((error = spa_prop_validate(spa, nvp)) != 0)
757 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
758 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
760 if (prop == ZPOOL_PROP_CACHEFILE ||
761 prop == ZPOOL_PROP_ALTROOT ||
762 prop == ZPOOL_PROP_READONLY)
765 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
768 if (prop == ZPOOL_PROP_VERSION) {
769 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
771 ASSERT(zpool_prop_feature(nvpair_name(elem)));
772 ver = SPA_VERSION_FEATURES;
776 /* Save time if the version is already set. */
777 if (ver == spa_version(spa))
781 * In addition to the pool directory object, we might
782 * create the pool properties object, the features for
783 * read object, the features for write object, or the
784 * feature descriptions object.
786 error = dsl_sync_task(spa->spa_name, NULL,
787 spa_sync_version, &ver,
788 6, ZFS_SPACE_CHECK_RESERVED);
799 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
800 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
807 * If the bootfs property value is dsobj, clear it.
810 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
812 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
813 VERIFY(zap_remove(spa->spa_meta_objset,
814 spa->spa_pool_props_object,
815 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
822 spa_change_guid_check(void *arg, dmu_tx_t *tx)
824 ASSERTV(uint64_t *newguid = arg);
825 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
826 vdev_t *rvd = spa->spa_root_vdev;
829 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
830 int error = (spa_has_checkpoint(spa)) ?
831 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
832 return (SET_ERROR(error));
835 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
836 vdev_state = rvd->vdev_state;
837 spa_config_exit(spa, SCL_STATE, FTAG);
839 if (vdev_state != VDEV_STATE_HEALTHY)
840 return (SET_ERROR(ENXIO));
842 ASSERT3U(spa_guid(spa), !=, *newguid);
848 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
850 uint64_t *newguid = arg;
851 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
853 vdev_t *rvd = spa->spa_root_vdev;
855 oldguid = spa_guid(spa);
857 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
858 rvd->vdev_guid = *newguid;
859 rvd->vdev_guid_sum += (*newguid - oldguid);
860 vdev_config_dirty(rvd);
861 spa_config_exit(spa, SCL_STATE, FTAG);
863 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
868 * Change the GUID for the pool. This is done so that we can later
869 * re-import a pool built from a clone of our own vdevs. We will modify
870 * the root vdev's guid, our own pool guid, and then mark all of our
871 * vdevs dirty. Note that we must make sure that all our vdevs are
872 * online when we do this, or else any vdevs that weren't present
873 * would be orphaned from our pool. We are also going to issue a
874 * sysevent to update any watchers.
877 spa_change_guid(spa_t *spa)
882 mutex_enter(&spa->spa_vdev_top_lock);
883 mutex_enter(&spa_namespace_lock);
884 guid = spa_generate_guid(NULL);
886 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
887 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
890 spa_write_cachefile(spa, B_FALSE, B_TRUE);
891 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
894 mutex_exit(&spa_namespace_lock);
895 mutex_exit(&spa->spa_vdev_top_lock);
901 * ==========================================================================
902 * SPA state manipulation (open/create/destroy/import/export)
903 * ==========================================================================
907 spa_error_entry_compare(const void *a, const void *b)
909 const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
910 const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
913 ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
914 sizeof (zbookmark_phys_t));
916 return (AVL_ISIGN(ret));
920 * Utility function which retrieves copies of the current logs and
921 * re-initializes them in the process.
924 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
926 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
928 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
929 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
931 avl_create(&spa->spa_errlist_scrub,
932 spa_error_entry_compare, sizeof (spa_error_entry_t),
933 offsetof(spa_error_entry_t, se_avl));
934 avl_create(&spa->spa_errlist_last,
935 spa_error_entry_compare, sizeof (spa_error_entry_t),
936 offsetof(spa_error_entry_t, se_avl));
940 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
942 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
943 enum zti_modes mode = ztip->zti_mode;
944 uint_t value = ztip->zti_value;
945 uint_t count = ztip->zti_count;
946 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
948 boolean_t batch = B_FALSE;
950 if (mode == ZTI_MODE_NULL) {
952 tqs->stqs_taskq = NULL;
956 ASSERT3U(count, >, 0);
958 tqs->stqs_count = count;
959 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
963 ASSERT3U(value, >=, 1);
964 value = MAX(value, 1);
965 flags |= TASKQ_DYNAMIC;
970 flags |= TASKQ_THREADS_CPU_PCT;
971 value = MIN(zio_taskq_batch_pct, 100);
975 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
977 zio_type_name[t], zio_taskq_types[q], mode, value);
981 for (uint_t i = 0; i < count; i++) {
985 (void) snprintf(name, sizeof (name), "%s_%s",
986 zio_type_name[t], zio_taskq_types[q]);
988 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
990 flags |= TASKQ_DC_BATCH;
992 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
993 spa->spa_proc, zio_taskq_basedc, flags);
995 pri_t pri = maxclsyspri;
997 * The write issue taskq can be extremely CPU
998 * intensive. Run it at slightly less important
999 * priority than the other taskqs. Under Linux this
1000 * means incrementing the priority value on platforms
1001 * like illumos it should be decremented.
1003 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1006 tq = taskq_create_proc(name, value, pri, 50,
1007 INT_MAX, spa->spa_proc, flags);
1010 tqs->stqs_taskq[i] = tq;
1015 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1017 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1019 if (tqs->stqs_taskq == NULL) {
1020 ASSERT3U(tqs->stqs_count, ==, 0);
1024 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1025 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1026 taskq_destroy(tqs->stqs_taskq[i]);
1029 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1030 tqs->stqs_taskq = NULL;
1034 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1035 * Note that a type may have multiple discrete taskqs to avoid lock contention
1036 * on the taskq itself. In that case we choose which taskq at random by using
1037 * the low bits of gethrtime().
1040 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1041 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1043 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1046 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1047 ASSERT3U(tqs->stqs_count, !=, 0);
1049 if (tqs->stqs_count == 1) {
1050 tq = tqs->stqs_taskq[0];
1052 tq = tqs->stqs_taskq[((uint64_t)gethrtime()) % tqs->stqs_count];
1055 taskq_dispatch_ent(tq, func, arg, flags, ent);
1059 * Same as spa_taskq_dispatch_ent() but block on the task until completion.
1062 spa_taskq_dispatch_sync(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1063 task_func_t *func, void *arg, uint_t flags)
1065 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1069 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1070 ASSERT3U(tqs->stqs_count, !=, 0);
1072 if (tqs->stqs_count == 1) {
1073 tq = tqs->stqs_taskq[0];
1075 tq = tqs->stqs_taskq[((uint64_t)gethrtime()) % tqs->stqs_count];
1078 id = taskq_dispatch(tq, func, arg, flags);
1080 taskq_wait_id(tq, id);
1084 spa_create_zio_taskqs(spa_t *spa)
1086 for (int t = 0; t < ZIO_TYPES; t++) {
1087 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1088 spa_taskqs_init(spa, t, q);
1094 * Disabled until spa_thread() can be adapted for Linux.
1096 #undef HAVE_SPA_THREAD
1098 #if defined(_KERNEL) && defined(HAVE_SPA_THREAD)
1100 spa_thread(void *arg)
1102 psetid_t zio_taskq_psrset_bind = PS_NONE;
1103 callb_cpr_t cprinfo;
1106 user_t *pu = PTOU(curproc);
1108 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1111 ASSERT(curproc != &p0);
1112 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1113 "zpool-%s", spa->spa_name);
1114 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1116 /* bind this thread to the requested psrset */
1117 if (zio_taskq_psrset_bind != PS_NONE) {
1119 mutex_enter(&cpu_lock);
1120 mutex_enter(&pidlock);
1121 mutex_enter(&curproc->p_lock);
1123 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1124 0, NULL, NULL) == 0) {
1125 curthread->t_bind_pset = zio_taskq_psrset_bind;
1128 "Couldn't bind process for zfs pool \"%s\" to "
1129 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1132 mutex_exit(&curproc->p_lock);
1133 mutex_exit(&pidlock);
1134 mutex_exit(&cpu_lock);
1138 if (zio_taskq_sysdc) {
1139 sysdc_thread_enter(curthread, 100, 0);
1142 spa->spa_proc = curproc;
1143 spa->spa_did = curthread->t_did;
1145 spa_create_zio_taskqs(spa);
1147 mutex_enter(&spa->spa_proc_lock);
1148 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1150 spa->spa_proc_state = SPA_PROC_ACTIVE;
1151 cv_broadcast(&spa->spa_proc_cv);
1153 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1154 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1155 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1156 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1158 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1159 spa->spa_proc_state = SPA_PROC_GONE;
1160 spa->spa_proc = &p0;
1161 cv_broadcast(&spa->spa_proc_cv);
1162 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1164 mutex_enter(&curproc->p_lock);
1170 * Activate an uninitialized pool.
1173 spa_activate(spa_t *spa, int mode)
1175 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1177 spa->spa_state = POOL_STATE_ACTIVE;
1178 spa->spa_mode = mode;
1180 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1181 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1182 spa->spa_special_class = metaslab_class_create(spa, zfs_metaslab_ops);
1183 spa->spa_dedup_class = metaslab_class_create(spa, zfs_metaslab_ops);
1185 /* Try to create a covering process */
1186 mutex_enter(&spa->spa_proc_lock);
1187 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1188 ASSERT(spa->spa_proc == &p0);
1191 #ifdef HAVE_SPA_THREAD
1192 /* Only create a process if we're going to be around a while. */
1193 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1194 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1196 spa->spa_proc_state = SPA_PROC_CREATED;
1197 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1198 cv_wait(&spa->spa_proc_cv,
1199 &spa->spa_proc_lock);
1201 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1202 ASSERT(spa->spa_proc != &p0);
1203 ASSERT(spa->spa_did != 0);
1207 "Couldn't create process for zfs pool \"%s\"\n",
1212 #endif /* HAVE_SPA_THREAD */
1213 mutex_exit(&spa->spa_proc_lock);
1215 /* If we didn't create a process, we need to create our taskqs. */
1216 if (spa->spa_proc == &p0) {
1217 spa_create_zio_taskqs(spa);
1220 for (size_t i = 0; i < TXG_SIZE; i++)
1221 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL, 0);
1223 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1224 offsetof(vdev_t, vdev_config_dirty_node));
1225 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1226 offsetof(objset_t, os_evicting_node));
1227 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1228 offsetof(vdev_t, vdev_state_dirty_node));
1230 txg_list_create(&spa->spa_vdev_txg_list, spa,
1231 offsetof(struct vdev, vdev_txg_node));
1233 avl_create(&spa->spa_errlist_scrub,
1234 spa_error_entry_compare, sizeof (spa_error_entry_t),
1235 offsetof(spa_error_entry_t, se_avl));
1236 avl_create(&spa->spa_errlist_last,
1237 spa_error_entry_compare, sizeof (spa_error_entry_t),
1238 offsetof(spa_error_entry_t, se_avl));
1240 spa_keystore_init(&spa->spa_keystore);
1243 * This taskq is used to perform zvol-minor-related tasks
1244 * asynchronously. This has several advantages, including easy
1245 * resolution of various deadlocks (zfsonlinux bug #3681).
1247 * The taskq must be single threaded to ensure tasks are always
1248 * processed in the order in which they were dispatched.
1250 * A taskq per pool allows one to keep the pools independent.
1251 * This way if one pool is suspended, it will not impact another.
1253 * The preferred location to dispatch a zvol minor task is a sync
1254 * task. In this context, there is easy access to the spa_t and minimal
1255 * error handling is required because the sync task must succeed.
1257 spa->spa_zvol_taskq = taskq_create("z_zvol", 1, defclsyspri,
1261 * Taskq dedicated to prefetcher threads: this is used to prevent the
1262 * pool traverse code from monopolizing the global (and limited)
1263 * system_taskq by inappropriately scheduling long running tasks on it.
1265 spa->spa_prefetch_taskq = taskq_create("z_prefetch", boot_ncpus,
1266 defclsyspri, 1, INT_MAX, TASKQ_DYNAMIC);
1269 * The taskq to upgrade datasets in this pool. Currently used by
1270 * feature SPA_FEATURE_USEROBJ_ACCOUNTING/SPA_FEATURE_PROJECT_QUOTA.
1272 spa->spa_upgrade_taskq = taskq_create("z_upgrade", boot_ncpus,
1273 defclsyspri, 1, INT_MAX, TASKQ_DYNAMIC);
1277 * Opposite of spa_activate().
1280 spa_deactivate(spa_t *spa)
1282 ASSERT(spa->spa_sync_on == B_FALSE);
1283 ASSERT(spa->spa_dsl_pool == NULL);
1284 ASSERT(spa->spa_root_vdev == NULL);
1285 ASSERT(spa->spa_async_zio_root == NULL);
1286 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1288 spa_evicting_os_wait(spa);
1290 if (spa->spa_zvol_taskq) {
1291 taskq_destroy(spa->spa_zvol_taskq);
1292 spa->spa_zvol_taskq = NULL;
1295 if (spa->spa_prefetch_taskq) {
1296 taskq_destroy(spa->spa_prefetch_taskq);
1297 spa->spa_prefetch_taskq = NULL;
1300 if (spa->spa_upgrade_taskq) {
1301 taskq_destroy(spa->spa_upgrade_taskq);
1302 spa->spa_upgrade_taskq = NULL;
1305 txg_list_destroy(&spa->spa_vdev_txg_list);
1307 list_destroy(&spa->spa_config_dirty_list);
1308 list_destroy(&spa->spa_evicting_os_list);
1309 list_destroy(&spa->spa_state_dirty_list);
1311 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
1313 for (int t = 0; t < ZIO_TYPES; t++) {
1314 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1315 spa_taskqs_fini(spa, t, q);
1319 for (size_t i = 0; i < TXG_SIZE; i++) {
1320 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1321 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1322 spa->spa_txg_zio[i] = NULL;
1325 metaslab_class_destroy(spa->spa_normal_class);
1326 spa->spa_normal_class = NULL;
1328 metaslab_class_destroy(spa->spa_log_class);
1329 spa->spa_log_class = NULL;
1331 metaslab_class_destroy(spa->spa_special_class);
1332 spa->spa_special_class = NULL;
1334 metaslab_class_destroy(spa->spa_dedup_class);
1335 spa->spa_dedup_class = NULL;
1338 * If this was part of an import or the open otherwise failed, we may
1339 * still have errors left in the queues. Empty them just in case.
1341 spa_errlog_drain(spa);
1342 avl_destroy(&spa->spa_errlist_scrub);
1343 avl_destroy(&spa->spa_errlist_last);
1345 spa_keystore_fini(&spa->spa_keystore);
1347 spa->spa_state = POOL_STATE_UNINITIALIZED;
1349 mutex_enter(&spa->spa_proc_lock);
1350 if (spa->spa_proc_state != SPA_PROC_NONE) {
1351 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1352 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1353 cv_broadcast(&spa->spa_proc_cv);
1354 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1355 ASSERT(spa->spa_proc != &p0);
1356 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1358 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1359 spa->spa_proc_state = SPA_PROC_NONE;
1361 ASSERT(spa->spa_proc == &p0);
1362 mutex_exit(&spa->spa_proc_lock);
1365 * We want to make sure spa_thread() has actually exited the ZFS
1366 * module, so that the module can't be unloaded out from underneath
1369 if (spa->spa_did != 0) {
1370 thread_join(spa->spa_did);
1376 * Verify a pool configuration, and construct the vdev tree appropriately. This
1377 * will create all the necessary vdevs in the appropriate layout, with each vdev
1378 * in the CLOSED state. This will prep the pool before open/creation/import.
1379 * All vdev validation is done by the vdev_alloc() routine.
1382 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1383 uint_t id, int atype)
1389 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1392 if ((*vdp)->vdev_ops->vdev_op_leaf)
1395 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1398 if (error == ENOENT)
1404 return (SET_ERROR(EINVAL));
1407 for (int c = 0; c < children; c++) {
1409 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1417 ASSERT(*vdp != NULL);
1423 * Opposite of spa_load().
1426 spa_unload(spa_t *spa)
1430 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1432 spa_load_note(spa, "UNLOADING");
1437 spa_async_suspend(spa);
1442 if (spa->spa_sync_on) {
1443 txg_sync_stop(spa->spa_dsl_pool);
1444 spa->spa_sync_on = B_FALSE;
1448 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1449 * to call it earlier, before we wait for async i/o to complete.
1450 * This ensures that there is no async metaslab prefetching, by
1451 * calling taskq_wait(mg_taskq).
1453 if (spa->spa_root_vdev != NULL) {
1454 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1455 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1456 vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1457 spa_config_exit(spa, SCL_ALL, FTAG);
1460 if (spa->spa_mmp.mmp_thread)
1461 mmp_thread_stop(spa);
1464 * Wait for any outstanding async I/O to complete.
1466 if (spa->spa_async_zio_root != NULL) {
1467 for (int i = 0; i < max_ncpus; i++)
1468 (void) zio_wait(spa->spa_async_zio_root[i]);
1469 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1470 spa->spa_async_zio_root = NULL;
1473 if (spa->spa_vdev_removal != NULL) {
1474 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1475 spa->spa_vdev_removal = NULL;
1478 if (spa->spa_condense_zthr != NULL) {
1479 ASSERT(!zthr_isrunning(spa->spa_condense_zthr));
1480 zthr_destroy(spa->spa_condense_zthr);
1481 spa->spa_condense_zthr = NULL;
1484 if (spa->spa_checkpoint_discard_zthr != NULL) {
1485 ASSERT(!zthr_isrunning(spa->spa_checkpoint_discard_zthr));
1486 zthr_destroy(spa->spa_checkpoint_discard_zthr);
1487 spa->spa_checkpoint_discard_zthr = NULL;
1490 spa_condense_fini(spa);
1492 bpobj_close(&spa->spa_deferred_bpobj);
1494 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1499 if (spa->spa_root_vdev)
1500 vdev_free(spa->spa_root_vdev);
1501 ASSERT(spa->spa_root_vdev == NULL);
1504 * Close the dsl pool.
1506 if (spa->spa_dsl_pool) {
1507 dsl_pool_close(spa->spa_dsl_pool);
1508 spa->spa_dsl_pool = NULL;
1509 spa->spa_meta_objset = NULL;
1515 * Drop and purge level 2 cache
1517 spa_l2cache_drop(spa);
1519 for (i = 0; i < spa->spa_spares.sav_count; i++)
1520 vdev_free(spa->spa_spares.sav_vdevs[i]);
1521 if (spa->spa_spares.sav_vdevs) {
1522 kmem_free(spa->spa_spares.sav_vdevs,
1523 spa->spa_spares.sav_count * sizeof (void *));
1524 spa->spa_spares.sav_vdevs = NULL;
1526 if (spa->spa_spares.sav_config) {
1527 nvlist_free(spa->spa_spares.sav_config);
1528 spa->spa_spares.sav_config = NULL;
1530 spa->spa_spares.sav_count = 0;
1532 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1533 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1534 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1536 if (spa->spa_l2cache.sav_vdevs) {
1537 kmem_free(spa->spa_l2cache.sav_vdevs,
1538 spa->spa_l2cache.sav_count * sizeof (void *));
1539 spa->spa_l2cache.sav_vdevs = NULL;
1541 if (spa->spa_l2cache.sav_config) {
1542 nvlist_free(spa->spa_l2cache.sav_config);
1543 spa->spa_l2cache.sav_config = NULL;
1545 spa->spa_l2cache.sav_count = 0;
1547 spa->spa_async_suspended = 0;
1549 spa->spa_indirect_vdevs_loaded = B_FALSE;
1551 if (spa->spa_comment != NULL) {
1552 spa_strfree(spa->spa_comment);
1553 spa->spa_comment = NULL;
1556 spa_config_exit(spa, SCL_ALL, FTAG);
1560 * Load (or re-load) the current list of vdevs describing the active spares for
1561 * this pool. When this is called, we have some form of basic information in
1562 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1563 * then re-generate a more complete list including status information.
1566 spa_load_spares(spa_t *spa)
1575 * zdb opens both the current state of the pool and the
1576 * checkpointed state (if present), with a different spa_t.
1578 * As spare vdevs are shared among open pools, we skip loading
1579 * them when we load the checkpointed state of the pool.
1581 if (!spa_writeable(spa))
1585 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1588 * First, close and free any existing spare vdevs.
1590 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1591 vd = spa->spa_spares.sav_vdevs[i];
1593 /* Undo the call to spa_activate() below */
1594 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1595 B_FALSE)) != NULL && tvd->vdev_isspare)
1596 spa_spare_remove(tvd);
1601 if (spa->spa_spares.sav_vdevs)
1602 kmem_free(spa->spa_spares.sav_vdevs,
1603 spa->spa_spares.sav_count * sizeof (void *));
1605 if (spa->spa_spares.sav_config == NULL)
1608 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1609 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1611 spa->spa_spares.sav_count = (int)nspares;
1612 spa->spa_spares.sav_vdevs = NULL;
1618 * Construct the array of vdevs, opening them to get status in the
1619 * process. For each spare, there is potentially two different vdev_t
1620 * structures associated with it: one in the list of spares (used only
1621 * for basic validation purposes) and one in the active vdev
1622 * configuration (if it's spared in). During this phase we open and
1623 * validate each vdev on the spare list. If the vdev also exists in the
1624 * active configuration, then we also mark this vdev as an active spare.
1626 spa->spa_spares.sav_vdevs = kmem_zalloc(nspares * sizeof (void *),
1628 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1629 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1630 VDEV_ALLOC_SPARE) == 0);
1633 spa->spa_spares.sav_vdevs[i] = vd;
1635 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1636 B_FALSE)) != NULL) {
1637 if (!tvd->vdev_isspare)
1641 * We only mark the spare active if we were successfully
1642 * able to load the vdev. Otherwise, importing a pool
1643 * with a bad active spare would result in strange
1644 * behavior, because multiple pool would think the spare
1645 * is actively in use.
1647 * There is a vulnerability here to an equally bizarre
1648 * circumstance, where a dead active spare is later
1649 * brought back to life (onlined or otherwise). Given
1650 * the rarity of this scenario, and the extra complexity
1651 * it adds, we ignore the possibility.
1653 if (!vdev_is_dead(tvd))
1654 spa_spare_activate(tvd);
1658 vd->vdev_aux = &spa->spa_spares;
1660 if (vdev_open(vd) != 0)
1663 if (vdev_validate_aux(vd) == 0)
1668 * Recompute the stashed list of spares, with status information
1671 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1672 DATA_TYPE_NVLIST_ARRAY) == 0);
1674 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1676 for (i = 0; i < spa->spa_spares.sav_count; i++)
1677 spares[i] = vdev_config_generate(spa,
1678 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1679 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1680 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1681 for (i = 0; i < spa->spa_spares.sav_count; i++)
1682 nvlist_free(spares[i]);
1683 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1687 * Load (or re-load) the current list of vdevs describing the active l2cache for
1688 * this pool. When this is called, we have some form of basic information in
1689 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1690 * then re-generate a more complete list including status information.
1691 * Devices which are already active have their details maintained, and are
1695 spa_load_l2cache(spa_t *spa)
1697 nvlist_t **l2cache = NULL;
1699 int i, j, oldnvdevs;
1701 vdev_t *vd, **oldvdevs, **newvdevs;
1702 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1706 * zdb opens both the current state of the pool and the
1707 * checkpointed state (if present), with a different spa_t.
1709 * As L2 caches are part of the ARC which is shared among open
1710 * pools, we skip loading them when we load the checkpointed
1711 * state of the pool.
1713 if (!spa_writeable(spa))
1717 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1719 oldvdevs = sav->sav_vdevs;
1720 oldnvdevs = sav->sav_count;
1721 sav->sav_vdevs = NULL;
1724 if (sav->sav_config == NULL) {
1730 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1731 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1732 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1735 * Process new nvlist of vdevs.
1737 for (i = 0; i < nl2cache; i++) {
1738 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1742 for (j = 0; j < oldnvdevs; j++) {
1744 if (vd != NULL && guid == vd->vdev_guid) {
1746 * Retain previous vdev for add/remove ops.
1754 if (newvdevs[i] == NULL) {
1758 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1759 VDEV_ALLOC_L2CACHE) == 0);
1764 * Commit this vdev as an l2cache device,
1765 * even if it fails to open.
1767 spa_l2cache_add(vd);
1772 spa_l2cache_activate(vd);
1774 if (vdev_open(vd) != 0)
1777 (void) vdev_validate_aux(vd);
1779 if (!vdev_is_dead(vd))
1780 l2arc_add_vdev(spa, vd);
1784 sav->sav_vdevs = newvdevs;
1785 sav->sav_count = (int)nl2cache;
1788 * Recompute the stashed list of l2cache devices, with status
1789 * information this time.
1791 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1792 DATA_TYPE_NVLIST_ARRAY) == 0);
1794 if (sav->sav_count > 0)
1795 l2cache = kmem_alloc(sav->sav_count * sizeof (void *),
1797 for (i = 0; i < sav->sav_count; i++)
1798 l2cache[i] = vdev_config_generate(spa,
1799 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1800 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1801 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1805 * Purge vdevs that were dropped
1807 for (i = 0; i < oldnvdevs; i++) {
1812 ASSERT(vd->vdev_isl2cache);
1814 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1815 pool != 0ULL && l2arc_vdev_present(vd))
1816 l2arc_remove_vdev(vd);
1817 vdev_clear_stats(vd);
1823 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1825 for (i = 0; i < sav->sav_count; i++)
1826 nvlist_free(l2cache[i]);
1828 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1832 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1835 char *packed = NULL;
1840 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1844 nvsize = *(uint64_t *)db->db_data;
1845 dmu_buf_rele(db, FTAG);
1847 packed = vmem_alloc(nvsize, KM_SLEEP);
1848 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1851 error = nvlist_unpack(packed, nvsize, value, 0);
1852 vmem_free(packed, nvsize);
1858 * Concrete top-level vdevs that are not missing and are not logs. At every
1859 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1862 spa_healthy_core_tvds(spa_t *spa)
1864 vdev_t *rvd = spa->spa_root_vdev;
1867 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1868 vdev_t *vd = rvd->vdev_child[i];
1871 if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1879 * Checks to see if the given vdev could not be opened, in which case we post a
1880 * sysevent to notify the autoreplace code that the device has been removed.
1883 spa_check_removed(vdev_t *vd)
1885 for (uint64_t c = 0; c < vd->vdev_children; c++)
1886 spa_check_removed(vd->vdev_child[c]);
1888 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1889 vdev_is_concrete(vd)) {
1890 zfs_post_autoreplace(vd->vdev_spa, vd);
1891 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1896 spa_check_for_missing_logs(spa_t *spa)
1898 vdev_t *rvd = spa->spa_root_vdev;
1901 * If we're doing a normal import, then build up any additional
1902 * diagnostic information about missing log devices.
1903 * We'll pass this up to the user for further processing.
1905 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1906 nvlist_t **child, *nv;
1909 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t *),
1911 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1913 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1914 vdev_t *tvd = rvd->vdev_child[c];
1917 * We consider a device as missing only if it failed
1918 * to open (i.e. offline or faulted is not considered
1921 if (tvd->vdev_islog &&
1922 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1923 child[idx++] = vdev_config_generate(spa, tvd,
1924 B_FALSE, VDEV_CONFIG_MISSING);
1929 fnvlist_add_nvlist_array(nv,
1930 ZPOOL_CONFIG_CHILDREN, child, idx);
1931 fnvlist_add_nvlist(spa->spa_load_info,
1932 ZPOOL_CONFIG_MISSING_DEVICES, nv);
1934 for (uint64_t i = 0; i < idx; i++)
1935 nvlist_free(child[i]);
1938 kmem_free(child, rvd->vdev_children * sizeof (char **));
1941 spa_load_failed(spa, "some log devices are missing");
1942 vdev_dbgmsg_print_tree(rvd, 2);
1943 return (SET_ERROR(ENXIO));
1946 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1947 vdev_t *tvd = rvd->vdev_child[c];
1949 if (tvd->vdev_islog &&
1950 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1951 spa_set_log_state(spa, SPA_LOG_CLEAR);
1952 spa_load_note(spa, "some log devices are "
1953 "missing, ZIL is dropped.");
1954 vdev_dbgmsg_print_tree(rvd, 2);
1964 * Check for missing log devices
1967 spa_check_logs(spa_t *spa)
1969 boolean_t rv = B_FALSE;
1970 dsl_pool_t *dp = spa_get_dsl(spa);
1972 switch (spa->spa_log_state) {
1975 case SPA_LOG_MISSING:
1976 /* need to recheck in case slog has been restored */
1977 case SPA_LOG_UNKNOWN:
1978 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1979 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
1981 spa_set_log_state(spa, SPA_LOG_MISSING);
1988 spa_passivate_log(spa_t *spa)
1990 vdev_t *rvd = spa->spa_root_vdev;
1991 boolean_t slog_found = B_FALSE;
1993 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1995 if (!spa_has_slogs(spa))
1998 for (int c = 0; c < rvd->vdev_children; c++) {
1999 vdev_t *tvd = rvd->vdev_child[c];
2000 metaslab_group_t *mg = tvd->vdev_mg;
2002 if (tvd->vdev_islog) {
2003 metaslab_group_passivate(mg);
2004 slog_found = B_TRUE;
2008 return (slog_found);
2012 spa_activate_log(spa_t *spa)
2014 vdev_t *rvd = spa->spa_root_vdev;
2016 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
2018 for (int c = 0; c < rvd->vdev_children; c++) {
2019 vdev_t *tvd = rvd->vdev_child[c];
2020 metaslab_group_t *mg = tvd->vdev_mg;
2022 if (tvd->vdev_islog)
2023 metaslab_group_activate(mg);
2028 spa_reset_logs(spa_t *spa)
2032 error = dmu_objset_find(spa_name(spa), zil_reset,
2033 NULL, DS_FIND_CHILDREN);
2036 * We successfully offlined the log device, sync out the
2037 * current txg so that the "stubby" block can be removed
2040 txg_wait_synced(spa->spa_dsl_pool, 0);
2046 spa_aux_check_removed(spa_aux_vdev_t *sav)
2048 for (int i = 0; i < sav->sav_count; i++)
2049 spa_check_removed(sav->sav_vdevs[i]);
2053 spa_claim_notify(zio_t *zio)
2055 spa_t *spa = zio->io_spa;
2060 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2061 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2062 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2063 mutex_exit(&spa->spa_props_lock);
2066 typedef struct spa_load_error {
2067 uint64_t sle_meta_count;
2068 uint64_t sle_data_count;
2072 spa_load_verify_done(zio_t *zio)
2074 blkptr_t *bp = zio->io_bp;
2075 spa_load_error_t *sle = zio->io_private;
2076 dmu_object_type_t type = BP_GET_TYPE(bp);
2077 int error = zio->io_error;
2078 spa_t *spa = zio->io_spa;
2080 abd_free(zio->io_abd);
2082 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
2083 type != DMU_OT_INTENT_LOG)
2084 atomic_inc_64(&sle->sle_meta_count);
2086 atomic_inc_64(&sle->sle_data_count);
2089 mutex_enter(&spa->spa_scrub_lock);
2090 spa->spa_load_verify_ios--;
2091 cv_broadcast(&spa->spa_scrub_io_cv);
2092 mutex_exit(&spa->spa_scrub_lock);
2096 * Maximum number of concurrent scrub i/os to create while verifying
2097 * a pool while importing it.
2099 int spa_load_verify_maxinflight = 10000;
2100 int spa_load_verify_metadata = B_TRUE;
2101 int spa_load_verify_data = B_TRUE;
2105 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2106 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2108 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2111 * Note: normally this routine will not be called if
2112 * spa_load_verify_metadata is not set. However, it may be useful
2113 * to manually set the flag after the traversal has begun.
2115 if (!spa_load_verify_metadata)
2117 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2121 size_t size = BP_GET_PSIZE(bp);
2123 mutex_enter(&spa->spa_scrub_lock);
2124 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
2125 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2126 spa->spa_load_verify_ios++;
2127 mutex_exit(&spa->spa_scrub_lock);
2129 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2130 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2131 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2132 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2138 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2140 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2141 return (SET_ERROR(ENAMETOOLONG));
2147 spa_load_verify(spa_t *spa)
2150 spa_load_error_t sle = { 0 };
2151 zpool_load_policy_t policy;
2152 boolean_t verify_ok = B_FALSE;
2155 zpool_get_load_policy(spa->spa_config, &policy);
2157 if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2160 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2161 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2162 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2164 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2168 rio = zio_root(spa, NULL, &sle,
2169 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2171 if (spa_load_verify_metadata) {
2172 if (spa->spa_extreme_rewind) {
2173 spa_load_note(spa, "performing a complete scan of the "
2174 "pool since extreme rewind is on. This may take "
2175 "a very long time.\n (spa_load_verify_data=%u, "
2176 "spa_load_verify_metadata=%u)",
2177 spa_load_verify_data, spa_load_verify_metadata);
2179 error = traverse_pool(spa, spa->spa_verify_min_txg,
2180 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA |
2181 TRAVERSE_NO_DECRYPT, spa_load_verify_cb, rio);
2184 (void) zio_wait(rio);
2186 spa->spa_load_meta_errors = sle.sle_meta_count;
2187 spa->spa_load_data_errors = sle.sle_data_count;
2189 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2190 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2191 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2192 (u_longlong_t)sle.sle_data_count);
2195 if (spa_load_verify_dryrun ||
2196 (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2197 sle.sle_data_count <= policy.zlp_maxdata)) {
2201 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2202 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2204 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2205 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2206 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2207 VERIFY(nvlist_add_int64(spa->spa_load_info,
2208 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2209 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2210 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2212 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2215 if (spa_load_verify_dryrun)
2219 if (error != ENXIO && error != EIO)
2220 error = SET_ERROR(EIO);
2224 return (verify_ok ? 0 : EIO);
2228 * Find a value in the pool props object.
2231 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2233 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2234 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2238 * Find a value in the pool directory object.
2241 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2243 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2244 name, sizeof (uint64_t), 1, val);
2246 if (error != 0 && (error != ENOENT || log_enoent)) {
2247 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2248 "[error=%d]", name, error);
2255 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2257 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2258 return (SET_ERROR(err));
2262 spa_spawn_aux_threads(spa_t *spa)
2264 ASSERT(spa_writeable(spa));
2266 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2268 spa_start_indirect_condensing_thread(spa);
2270 ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2271 spa->spa_checkpoint_discard_zthr =
2272 zthr_create(spa_checkpoint_discard_thread_check,
2273 spa_checkpoint_discard_thread, spa);
2277 * Fix up config after a partly-completed split. This is done with the
2278 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2279 * pool have that entry in their config, but only the splitting one contains
2280 * a list of all the guids of the vdevs that are being split off.
2282 * This function determines what to do with that list: either rejoin
2283 * all the disks to the pool, or complete the splitting process. To attempt
2284 * the rejoin, each disk that is offlined is marked online again, and
2285 * we do a reopen() call. If the vdev label for every disk that was
2286 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2287 * then we call vdev_split() on each disk, and complete the split.
2289 * Otherwise we leave the config alone, with all the vdevs in place in
2290 * the original pool.
2293 spa_try_repair(spa_t *spa, nvlist_t *config)
2300 boolean_t attempt_reopen;
2302 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2305 /* check that the config is complete */
2306 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2307 &glist, &gcount) != 0)
2310 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2312 /* attempt to online all the vdevs & validate */
2313 attempt_reopen = B_TRUE;
2314 for (i = 0; i < gcount; i++) {
2315 if (glist[i] == 0) /* vdev is hole */
2318 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2319 if (vd[i] == NULL) {
2321 * Don't bother attempting to reopen the disks;
2322 * just do the split.
2324 attempt_reopen = B_FALSE;
2326 /* attempt to re-online it */
2327 vd[i]->vdev_offline = B_FALSE;
2331 if (attempt_reopen) {
2332 vdev_reopen(spa->spa_root_vdev);
2334 /* check each device to see what state it's in */
2335 for (extracted = 0, i = 0; i < gcount; i++) {
2336 if (vd[i] != NULL &&
2337 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2344 * If every disk has been moved to the new pool, or if we never
2345 * even attempted to look at them, then we split them off for
2348 if (!attempt_reopen || gcount == extracted) {
2349 for (i = 0; i < gcount; i++)
2352 vdev_reopen(spa->spa_root_vdev);
2355 kmem_free(vd, gcount * sizeof (vdev_t *));
2359 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2361 char *ereport = FM_EREPORT_ZFS_POOL;
2364 spa->spa_load_state = state;
2366 gethrestime(&spa->spa_loaded_ts);
2367 error = spa_load_impl(spa, type, &ereport);
2370 * Don't count references from objsets that are already closed
2371 * and are making their way through the eviction process.
2373 spa_evicting_os_wait(spa);
2374 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
2376 if (error != EEXIST) {
2377 spa->spa_loaded_ts.tv_sec = 0;
2378 spa->spa_loaded_ts.tv_nsec = 0;
2380 if (error != EBADF) {
2381 zfs_ereport_post(ereport, spa, NULL, NULL, NULL, 0, 0);
2384 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2392 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2393 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2394 * spa's per-vdev ZAP list.
2397 vdev_count_verify_zaps(vdev_t *vd)
2399 spa_t *spa = vd->vdev_spa;
2402 if (vd->vdev_top_zap != 0) {
2404 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2405 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2407 if (vd->vdev_leaf_zap != 0) {
2409 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2410 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2413 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2414 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2422 * Determine whether the activity check is required.
2425 spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
2429 uint64_t hostid = 0;
2430 uint64_t tryconfig_txg = 0;
2431 uint64_t tryconfig_timestamp = 0;
2434 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2435 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2436 (void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
2438 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2439 &tryconfig_timestamp);
2442 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
2445 * Disable the MMP activity check - This is used by zdb which
2446 * is intended to be used on potentially active pools.
2448 if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
2452 * Skip the activity check when the MMP feature is disabled.
2454 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
2457 * If the tryconfig_* values are nonzero, they are the results of an
2458 * earlier tryimport. If they match the uberblock we just found, then
2459 * the pool has not changed and we return false so we do not test a
2462 if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
2463 tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp)
2467 * Allow the activity check to be skipped when importing the pool
2468 * on the same host which last imported it. Since the hostid from
2469 * configuration may be stale use the one read from the label.
2471 if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
2472 hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
2474 if (hostid == spa_get_hostid())
2478 * Skip the activity test when the pool was cleanly exported.
2480 if (state != POOL_STATE_ACTIVE)
2487 * Perform the import activity check. If the user canceled the import or
2488 * we detected activity then fail.
2491 spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
2493 uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
2494 uint64_t txg = ub->ub_txg;
2495 uint64_t timestamp = ub->ub_timestamp;
2496 uint64_t import_delay = NANOSEC;
2497 hrtime_t import_expire;
2498 nvlist_t *mmp_label = NULL;
2499 vdev_t *rvd = spa->spa_root_vdev;
2504 cv_init(&cv, NULL, CV_DEFAULT, NULL);
2505 mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
2509 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
2510 * during the earlier tryimport. If the txg recorded there is 0 then
2511 * the pool is known to be active on another host.
2513 * Otherwise, the pool might be in use on another node. Check for
2514 * changes in the uberblocks on disk if necessary.
2516 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2517 nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
2518 ZPOOL_CONFIG_LOAD_INFO);
2520 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
2521 fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
2522 vdev_uberblock_load(rvd, ub, &mmp_label);
2523 error = SET_ERROR(EREMOTEIO);
2529 * Preferentially use the zfs_multihost_interval from the node which
2530 * last imported the pool. This value is stored in an MMP uberblock as.
2532 * ub_mmp_delay * vdev_count_leaves() == zfs_multihost_interval
2534 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay)
2535 import_delay = MAX(import_delay, import_intervals *
2536 ub->ub_mmp_delay * MAX(vdev_count_leaves(spa), 1));
2538 /* Apply a floor using the local default values. */
2539 import_delay = MAX(import_delay, import_intervals *
2540 MSEC2NSEC(MAX(zfs_multihost_interval, MMP_MIN_INTERVAL)));
2542 zfs_dbgmsg("import_delay=%llu ub_mmp_delay=%llu import_intervals=%u "
2543 "leaves=%u", import_delay, ub->ub_mmp_delay, import_intervals,
2544 vdev_count_leaves(spa));
2546 /* Add a small random factor in case of simultaneous imports (0-25%) */
2547 import_expire = gethrtime() + import_delay +
2548 (import_delay * spa_get_random(250) / 1000);
2550 while (gethrtime() < import_expire) {
2551 vdev_uberblock_load(rvd, ub, &mmp_label);
2553 if (txg != ub->ub_txg || timestamp != ub->ub_timestamp) {
2554 error = SET_ERROR(EREMOTEIO);
2559 nvlist_free(mmp_label);
2563 error = cv_timedwait_sig(&cv, &mtx, ddi_get_lbolt() + hz);
2565 error = SET_ERROR(EINTR);
2573 mutex_destroy(&mtx);
2577 * If the pool is determined to be active store the status in the
2578 * spa->spa_load_info nvlist. If the remote hostname or hostid are
2579 * available from configuration read from disk store them as well.
2580 * This allows 'zpool import' to generate a more useful message.
2582 * ZPOOL_CONFIG_MMP_STATE - observed pool status (mandatory)
2583 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
2584 * ZPOOL_CONFIG_MMP_HOSTID - hostid from the active pool
2586 if (error == EREMOTEIO) {
2587 char *hostname = "<unknown>";
2588 uint64_t hostid = 0;
2591 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
2592 hostname = fnvlist_lookup_string(mmp_label,
2593 ZPOOL_CONFIG_HOSTNAME);
2594 fnvlist_add_string(spa->spa_load_info,
2595 ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
2598 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
2599 hostid = fnvlist_lookup_uint64(mmp_label,
2600 ZPOOL_CONFIG_HOSTID);
2601 fnvlist_add_uint64(spa->spa_load_info,
2602 ZPOOL_CONFIG_MMP_HOSTID, hostid);
2606 fnvlist_add_uint64(spa->spa_load_info,
2607 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
2608 fnvlist_add_uint64(spa->spa_load_info,
2609 ZPOOL_CONFIG_MMP_TXG, 0);
2611 error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
2615 nvlist_free(mmp_label);
2621 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2625 uint64_t myhostid = 0;
2627 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2628 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2629 hostname = fnvlist_lookup_string(mos_config,
2630 ZPOOL_CONFIG_HOSTNAME);
2632 myhostid = zone_get_hostid(NULL);
2634 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2635 cmn_err(CE_WARN, "pool '%s' could not be "
2636 "loaded as it was last accessed by "
2637 "another system (host: %s hostid: 0x%llx). "
2638 "See: http://illumos.org/msg/ZFS-8000-EY",
2639 spa_name(spa), hostname, (u_longlong_t)hostid);
2640 spa_load_failed(spa, "hostid verification failed: pool "
2641 "last accessed by host: %s (hostid: 0x%llx)",
2642 hostname, (u_longlong_t)hostid);
2643 return (SET_ERROR(EBADF));
2651 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2654 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2661 * Versioning wasn't explicitly added to the label until later, so if
2662 * it's not present treat it as the initial version.
2664 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2665 &spa->spa_ubsync.ub_version) != 0)
2666 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2668 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2669 spa_load_failed(spa, "invalid config provided: '%s' missing",
2670 ZPOOL_CONFIG_POOL_GUID);
2671 return (SET_ERROR(EINVAL));
2675 * If we are doing an import, ensure that the pool is not already
2676 * imported by checking if its pool guid already exists in the
2679 * The only case that we allow an already imported pool to be
2680 * imported again, is when the pool is checkpointed and we want to
2681 * look at its checkpointed state from userland tools like zdb.
2684 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2685 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2686 spa_guid_exists(pool_guid, 0)) {
2688 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2689 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2690 spa_guid_exists(pool_guid, 0) &&
2691 !spa_importing_readonly_checkpoint(spa)) {
2693 spa_load_failed(spa, "a pool with guid %llu is already open",
2694 (u_longlong_t)pool_guid);
2695 return (SET_ERROR(EEXIST));
2698 spa->spa_config_guid = pool_guid;
2700 nvlist_free(spa->spa_load_info);
2701 spa->spa_load_info = fnvlist_alloc();
2703 ASSERT(spa->spa_comment == NULL);
2704 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2705 spa->spa_comment = spa_strdup(comment);
2707 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2708 &spa->spa_config_txg);
2710 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2711 spa->spa_config_splitting = fnvlist_dup(nvl);
2713 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2714 spa_load_failed(spa, "invalid config provided: '%s' missing",
2715 ZPOOL_CONFIG_VDEV_TREE);
2716 return (SET_ERROR(EINVAL));
2720 * Create "The Godfather" zio to hold all async IOs
2722 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2724 for (int i = 0; i < max_ncpus; i++) {
2725 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2726 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2727 ZIO_FLAG_GODFATHER);
2731 * Parse the configuration into a vdev tree. We explicitly set the
2732 * value that will be returned by spa_version() since parsing the
2733 * configuration requires knowing the version number.
2735 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2736 parse = (type == SPA_IMPORT_EXISTING ?
2737 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2738 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2739 spa_config_exit(spa, SCL_ALL, FTAG);
2742 spa_load_failed(spa, "unable to parse config [error=%d]",
2747 ASSERT(spa->spa_root_vdev == rvd);
2748 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2749 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2751 if (type != SPA_IMPORT_ASSEMBLE) {
2752 ASSERT(spa_guid(spa) == pool_guid);
2759 * Recursively open all vdevs in the vdev tree. This function is called twice:
2760 * first with the untrusted config, then with the trusted config.
2763 spa_ld_open_vdevs(spa_t *spa)
2768 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2769 * missing/unopenable for the root vdev to be still considered openable.
2771 if (spa->spa_trust_config) {
2772 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2773 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2774 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2775 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2776 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2778 spa->spa_missing_tvds_allowed = 0;
2781 spa->spa_missing_tvds_allowed =
2782 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2784 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2785 error = vdev_open(spa->spa_root_vdev);
2786 spa_config_exit(spa, SCL_ALL, FTAG);
2788 if (spa->spa_missing_tvds != 0) {
2789 spa_load_note(spa, "vdev tree has %lld missing top-level "
2790 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2791 if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2793 * Although theoretically we could allow users to open
2794 * incomplete pools in RW mode, we'd need to add a lot
2795 * of extra logic (e.g. adjust pool space to account
2796 * for missing vdevs).
2797 * This limitation also prevents users from accidentally
2798 * opening the pool in RW mode during data recovery and
2799 * damaging it further.
2801 spa_load_note(spa, "pools with missing top-level "
2802 "vdevs can only be opened in read-only mode.");
2803 error = SET_ERROR(ENXIO);
2805 spa_load_note(spa, "current settings allow for maximum "
2806 "%lld missing top-level vdevs at this stage.",
2807 (u_longlong_t)spa->spa_missing_tvds_allowed);
2811 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2814 if (spa->spa_missing_tvds != 0 || error != 0)
2815 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2821 * We need to validate the vdev labels against the configuration that
2822 * we have in hand. This function is called twice: first with an untrusted
2823 * config, then with a trusted config. The validation is more strict when the
2824 * config is trusted.
2827 spa_ld_validate_vdevs(spa_t *spa)
2830 vdev_t *rvd = spa->spa_root_vdev;
2832 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2833 error = vdev_validate(rvd);
2834 spa_config_exit(spa, SCL_ALL, FTAG);
2837 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2841 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2842 spa_load_failed(spa, "cannot open vdev tree after invalidating "
2844 vdev_dbgmsg_print_tree(rvd, 2);
2845 return (SET_ERROR(ENXIO));
2852 spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2854 spa->spa_state = POOL_STATE_ACTIVE;
2855 spa->spa_ubsync = spa->spa_uberblock;
2856 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2857 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2858 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2859 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2860 spa->spa_claim_max_txg = spa->spa_first_txg;
2861 spa->spa_prev_software_version = ub->ub_software_version;
2865 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2867 vdev_t *rvd = spa->spa_root_vdev;
2869 uberblock_t *ub = &spa->spa_uberblock;
2870 boolean_t activity_check = B_FALSE;
2873 * If we are opening the checkpointed state of the pool by
2874 * rewinding to it, at this point we will have written the
2875 * checkpointed uberblock to the vdev labels, so searching
2876 * the labels will find the right uberblock. However, if
2877 * we are opening the checkpointed state read-only, we have
2878 * not modified the labels. Therefore, we must ignore the
2879 * labels and continue using the spa_uberblock that was set
2880 * by spa_ld_checkpoint_rewind.
2882 * Note that it would be fine to ignore the labels when
2883 * rewinding (opening writeable) as well. However, if we
2884 * crash just after writing the labels, we will end up
2885 * searching the labels. Doing so in the common case means
2886 * that this code path gets exercised normally, rather than
2887 * just in the edge case.
2889 if (ub->ub_checkpoint_txg != 0 &&
2890 spa_importing_readonly_checkpoint(spa)) {
2891 spa_ld_select_uberblock_done(spa, ub);
2896 * Find the best uberblock.
2898 vdev_uberblock_load(rvd, ub, &label);
2901 * If we weren't able to find a single valid uberblock, return failure.
2903 if (ub->ub_txg == 0) {
2905 spa_load_failed(spa, "no valid uberblock found");
2906 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2909 spa_load_note(spa, "using uberblock with txg=%llu",
2910 (u_longlong_t)ub->ub_txg);
2914 * For pools which have the multihost property on determine if the
2915 * pool is truly inactive and can be safely imported. Prevent
2916 * hosts which don't have a hostid set from importing the pool.
2918 activity_check = spa_activity_check_required(spa, ub, label,
2920 if (activity_check) {
2921 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
2922 spa_get_hostid() == 0) {
2924 fnvlist_add_uint64(spa->spa_load_info,
2925 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
2926 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
2929 int error = spa_activity_check(spa, ub, spa->spa_config);
2935 fnvlist_add_uint64(spa->spa_load_info,
2936 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
2937 fnvlist_add_uint64(spa->spa_load_info,
2938 ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
2942 * If the pool has an unsupported version we can't open it.
2944 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2946 spa_load_failed(spa, "version %llu is not supported",
2947 (u_longlong_t)ub->ub_version);
2948 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2951 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2955 * If we weren't able to find what's necessary for reading the
2956 * MOS in the label, return failure.
2958 if (label == NULL) {
2959 spa_load_failed(spa, "label config unavailable");
2960 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2964 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
2967 spa_load_failed(spa, "invalid label: '%s' missing",
2968 ZPOOL_CONFIG_FEATURES_FOR_READ);
2969 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2974 * Update our in-core representation with the definitive values
2977 nvlist_free(spa->spa_label_features);
2978 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2984 * Look through entries in the label nvlist's features_for_read. If
2985 * there is a feature listed there which we don't understand then we
2986 * cannot open a pool.
2988 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2989 nvlist_t *unsup_feat;
2991 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2994 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2996 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2997 if (!zfeature_is_supported(nvpair_name(nvp))) {
2998 VERIFY(nvlist_add_string(unsup_feat,
2999 nvpair_name(nvp), "") == 0);
3003 if (!nvlist_empty(unsup_feat)) {
3004 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
3005 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
3006 nvlist_free(unsup_feat);
3007 spa_load_failed(spa, "some features are unsupported");
3008 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3012 nvlist_free(unsup_feat);
3015 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
3016 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3017 spa_try_repair(spa, spa->spa_config);
3018 spa_config_exit(spa, SCL_ALL, FTAG);
3019 nvlist_free(spa->spa_config_splitting);
3020 spa->spa_config_splitting = NULL;
3024 * Initialize internal SPA structures.
3026 spa_ld_select_uberblock_done(spa, ub);
3032 spa_ld_open_rootbp(spa_t *spa)
3035 vdev_t *rvd = spa->spa_root_vdev;
3037 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
3039 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
3040 "[error=%d]", error);
3041 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3043 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
3049 spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
3050 boolean_t reloading)
3052 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
3053 nvlist_t *nv, *mos_config, *policy;
3054 int error = 0, copy_error;
3055 uint64_t healthy_tvds, healthy_tvds_mos;
3056 uint64_t mos_config_txg;
3058 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
3060 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3063 * If we're assembling a pool from a split, the config provided is
3064 * already trusted so there is nothing to do.
3066 if (type == SPA_IMPORT_ASSEMBLE)
3069 healthy_tvds = spa_healthy_core_tvds(spa);
3071 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
3073 spa_load_failed(spa, "unable to retrieve MOS config");
3074 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3078 * If we are doing an open, pool owner wasn't verified yet, thus do
3079 * the verification here.
3081 if (spa->spa_load_state == SPA_LOAD_OPEN) {
3082 error = spa_verify_host(spa, mos_config);
3084 nvlist_free(mos_config);
3089 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
3091 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3094 * Build a new vdev tree from the trusted config
3096 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
3099 * Vdev paths in the MOS may be obsolete. If the untrusted config was
3100 * obtained by scanning /dev/dsk, then it will have the right vdev
3101 * paths. We update the trusted MOS config with this information.
3102 * We first try to copy the paths with vdev_copy_path_strict, which
3103 * succeeds only when both configs have exactly the same vdev tree.
3104 * If that fails, we fall back to a more flexible method that has a
3105 * best effort policy.
3107 copy_error = vdev_copy_path_strict(rvd, mrvd);
3108 if (copy_error != 0 || spa_load_print_vdev_tree) {
3109 spa_load_note(spa, "provided vdev tree:");
3110 vdev_dbgmsg_print_tree(rvd, 2);
3111 spa_load_note(spa, "MOS vdev tree:");
3112 vdev_dbgmsg_print_tree(mrvd, 2);
3114 if (copy_error != 0) {
3115 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
3116 "back to vdev_copy_path_relaxed");
3117 vdev_copy_path_relaxed(rvd, mrvd);
3122 spa->spa_root_vdev = mrvd;
3124 spa_config_exit(spa, SCL_ALL, FTAG);
3127 * We will use spa_config if we decide to reload the spa or if spa_load
3128 * fails and we rewind. We must thus regenerate the config using the
3129 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
3130 * pass settings on how to load the pool and is not stored in the MOS.
3131 * We copy it over to our new, trusted config.
3133 mos_config_txg = fnvlist_lookup_uint64(mos_config,
3134 ZPOOL_CONFIG_POOL_TXG);
3135 nvlist_free(mos_config);
3136 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
3137 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
3139 fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
3140 spa_config_set(spa, mos_config);
3141 spa->spa_config_source = SPA_CONFIG_SRC_MOS;
3144 * Now that we got the config from the MOS, we should be more strict
3145 * in checking blkptrs and can make assumptions about the consistency
3146 * of the vdev tree. spa_trust_config must be set to true before opening
3147 * vdevs in order for them to be writeable.
3149 spa->spa_trust_config = B_TRUE;
3152 * Open and validate the new vdev tree
3154 error = spa_ld_open_vdevs(spa);
3158 error = spa_ld_validate_vdevs(spa);
3162 if (copy_error != 0 || spa_load_print_vdev_tree) {
3163 spa_load_note(spa, "final vdev tree:");
3164 vdev_dbgmsg_print_tree(rvd, 2);
3167 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
3168 !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
3170 * Sanity check to make sure that we are indeed loading the
3171 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
3172 * in the config provided and they happened to be the only ones
3173 * to have the latest uberblock, we could involuntarily perform
3174 * an extreme rewind.
3176 healthy_tvds_mos = spa_healthy_core_tvds(spa);
3177 if (healthy_tvds_mos - healthy_tvds >=
3178 SPA_SYNC_MIN_VDEVS) {
3179 spa_load_note(spa, "config provided misses too many "
3180 "top-level vdevs compared to MOS (%lld vs %lld). ",
3181 (u_longlong_t)healthy_tvds,
3182 (u_longlong_t)healthy_tvds_mos);
3183 spa_load_note(spa, "vdev tree:");
3184 vdev_dbgmsg_print_tree(rvd, 2);
3186 spa_load_failed(spa, "config was already "
3187 "provided from MOS. Aborting.");
3188 return (spa_vdev_err(rvd,
3189 VDEV_AUX_CORRUPT_DATA, EIO));
3191 spa_load_note(spa, "spa must be reloaded using MOS "
3193 return (SET_ERROR(EAGAIN));
3197 error = spa_check_for_missing_logs(spa);
3199 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
3201 if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
3202 spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
3203 "guid sum (%llu != %llu)",
3204 (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
3205 (u_longlong_t)rvd->vdev_guid_sum);
3206 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
3214 spa_ld_open_indirect_vdev_metadata(spa_t *spa)
3217 vdev_t *rvd = spa->spa_root_vdev;
3220 * Everything that we read before spa_remove_init() must be stored
3221 * on concreted vdevs. Therefore we do this as early as possible.
3223 error = spa_remove_init(spa);
3225 spa_load_failed(spa, "spa_remove_init failed [error=%d]",
3227 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3231 * Retrieve information needed to condense indirect vdev mappings.
3233 error = spa_condense_init(spa);
3235 spa_load_failed(spa, "spa_condense_init failed [error=%d]",
3237 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3244 spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
3247 vdev_t *rvd = spa->spa_root_vdev;
3249 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
3250 boolean_t missing_feat_read = B_FALSE;
3251 nvlist_t *unsup_feat, *enabled_feat;
3253 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
3254 &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
3255 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3258 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
3259 &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
3260 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3263 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
3264 &spa->spa_feat_desc_obj, B_TRUE) != 0) {
3265 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3268 enabled_feat = fnvlist_alloc();
3269 unsup_feat = fnvlist_alloc();
3271 if (!spa_features_check(spa, B_FALSE,
3272 unsup_feat, enabled_feat))
3273 missing_feat_read = B_TRUE;
3275 if (spa_writeable(spa) ||
3276 spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3277 if (!spa_features_check(spa, B_TRUE,
3278 unsup_feat, enabled_feat)) {
3279 *missing_feat_writep = B_TRUE;
3283 fnvlist_add_nvlist(spa->spa_load_info,
3284 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3286 if (!nvlist_empty(unsup_feat)) {
3287 fnvlist_add_nvlist(spa->spa_load_info,
3288 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3291 fnvlist_free(enabled_feat);
3292 fnvlist_free(unsup_feat);
3294 if (!missing_feat_read) {
3295 fnvlist_add_boolean(spa->spa_load_info,
3296 ZPOOL_CONFIG_CAN_RDONLY);
3300 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3301 * twofold: to determine whether the pool is available for
3302 * import in read-write mode and (if it is not) whether the
3303 * pool is available for import in read-only mode. If the pool
3304 * is available for import in read-write mode, it is displayed
3305 * as available in userland; if it is not available for import
3306 * in read-only mode, it is displayed as unavailable in
3307 * userland. If the pool is available for import in read-only
3308 * mode but not read-write mode, it is displayed as unavailable
3309 * in userland with a special note that the pool is actually
3310 * available for open in read-only mode.
3312 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3313 * missing a feature for write, we must first determine whether
3314 * the pool can be opened read-only before returning to
3315 * userland in order to know whether to display the
3316 * abovementioned note.
3318 if (missing_feat_read || (*missing_feat_writep &&
3319 spa_writeable(spa))) {
3320 spa_load_failed(spa, "pool uses unsupported features");
3321 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3326 * Load refcounts for ZFS features from disk into an in-memory
3327 * cache during SPA initialization.
3329 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
3332 error = feature_get_refcount_from_disk(spa,
3333 &spa_feature_table[i], &refcount);
3335 spa->spa_feat_refcount_cache[i] = refcount;
3336 } else if (error == ENOTSUP) {
3337 spa->spa_feat_refcount_cache[i] =
3338 SPA_FEATURE_DISABLED;
3340 spa_load_failed(spa, "error getting refcount "
3341 "for feature %s [error=%d]",
3342 spa_feature_table[i].fi_guid, error);
3343 return (spa_vdev_err(rvd,
3344 VDEV_AUX_CORRUPT_DATA, EIO));
3349 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3350 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
3351 &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
3352 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3359 spa_ld_load_special_directories(spa_t *spa)
3362 vdev_t *rvd = spa->spa_root_vdev;
3364 spa->spa_is_initializing = B_TRUE;
3365 error = dsl_pool_open(spa->spa_dsl_pool);
3366 spa->spa_is_initializing = B_FALSE;
3368 spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3369 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3376 spa_ld_get_props(spa_t *spa)
3380 vdev_t *rvd = spa->spa_root_vdev;
3382 /* Grab the checksum salt from the MOS. */
3383 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3384 DMU_POOL_CHECKSUM_SALT, 1,
3385 sizeof (spa->spa_cksum_salt.zcs_bytes),
3386 spa->spa_cksum_salt.zcs_bytes);
3387 if (error == ENOENT) {
3388 /* Generate a new salt for subsequent use */
3389 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3390 sizeof (spa->spa_cksum_salt.zcs_bytes));
3391 } else if (error != 0) {
3392 spa_load_failed(spa, "unable to retrieve checksum salt from "
3393 "MOS [error=%d]", error);
3394 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3397 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3398 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3399 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3401 spa_load_failed(spa, "error opening deferred-frees bpobj "
3402 "[error=%d]", error);
3403 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3407 * Load the bit that tells us to use the new accounting function
3408 * (raid-z deflation). If we have an older pool, this will not
3411 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3412 if (error != 0 && error != ENOENT)
3413 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3415 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3416 &spa->spa_creation_version, B_FALSE);
3417 if (error != 0 && error != ENOENT)
3418 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3421 * Load the persistent error log. If we have an older pool, this will
3424 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3426 if (error != 0 && error != ENOENT)
3427 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3429 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3430 &spa->spa_errlog_scrub, B_FALSE);
3431 if (error != 0 && error != ENOENT)
3432 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3435 * Load the history object. If we have an older pool, this
3436 * will not be present.
3438 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3439 if (error != 0 && error != ENOENT)
3440 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3443 * Load the per-vdev ZAP map. If we have an older pool, this will not
3444 * be present; in this case, defer its creation to a later time to
3445 * avoid dirtying the MOS this early / out of sync context. See
3446 * spa_sync_config_object.
3449 /* The sentinel is only available in the MOS config. */
3450 nvlist_t *mos_config;
3451 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3452 spa_load_failed(spa, "unable to retrieve MOS config");
3453 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3456 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3457 &spa->spa_all_vdev_zaps, B_FALSE);
3459 if (error == ENOENT) {
3460 VERIFY(!nvlist_exists(mos_config,
3461 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3462 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3463 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3464 } else if (error != 0) {
3465 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3466 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3468 * An older version of ZFS overwrote the sentinel value, so
3469 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3470 * destruction to later; see spa_sync_config_object.
3472 spa->spa_avz_action = AVZ_ACTION_DESTROY;
3474 * We're assuming that no vdevs have had their ZAPs created
3475 * before this. Better be sure of it.
3477 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3479 nvlist_free(mos_config);
3481 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3483 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3485 if (error && error != ENOENT)
3486 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3489 uint64_t autoreplace;
3491 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3492 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3493 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3494 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3495 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3496 spa_prop_find(spa, ZPOOL_PROP_MULTIHOST, &spa->spa_multihost);
3497 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3498 &spa->spa_dedup_ditto);
3500 spa->spa_autoreplace = (autoreplace != 0);
3504 * If we are importing a pool with missing top-level vdevs,
3505 * we enforce that the pool doesn't panic or get suspended on
3506 * error since the likelihood of missing data is extremely high.
3508 if (spa->spa_missing_tvds > 0 &&
3509 spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3510 spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3511 spa_load_note(spa, "forcing failmode to 'continue' "
3512 "as some top level vdevs are missing");
3513 spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3520 spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3523 vdev_t *rvd = spa->spa_root_vdev;
3526 * If we're assembling the pool from the split-off vdevs of
3527 * an existing pool, we don't want to attach the spares & cache
3532 * Load any hot spares for this pool.
3534 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3536 if (error != 0 && error != ENOENT)
3537 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3538 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3539 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3540 if (load_nvlist(spa, spa->spa_spares.sav_object,
3541 &spa->spa_spares.sav_config) != 0) {
3542 spa_load_failed(spa, "error loading spares nvlist");
3543 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3546 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3547 spa_load_spares(spa);
3548 spa_config_exit(spa, SCL_ALL, FTAG);
3549 } else if (error == 0) {
3550 spa->spa_spares.sav_sync = B_TRUE;
3554 * Load any level 2 ARC devices for this pool.
3556 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3557 &spa->spa_l2cache.sav_object, B_FALSE);
3558 if (error != 0 && error != ENOENT)
3559 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3560 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3561 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3562 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3563 &spa->spa_l2cache.sav_config) != 0) {
3564 spa_load_failed(spa, "error loading l2cache nvlist");
3565 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3568 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3569 spa_load_l2cache(spa);
3570 spa_config_exit(spa, SCL_ALL, FTAG);
3571 } else if (error == 0) {
3572 spa->spa_l2cache.sav_sync = B_TRUE;
3579 spa_ld_load_vdev_metadata(spa_t *spa)
3582 vdev_t *rvd = spa->spa_root_vdev;
3585 * If the 'multihost' property is set, then never allow a pool to
3586 * be imported when the system hostid is zero. The exception to
3587 * this rule is zdb which is always allowed to access pools.
3589 if (spa_multihost(spa) && spa_get_hostid() == 0 &&
3590 (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP) == 0) {
3591 fnvlist_add_uint64(spa->spa_load_info,
3592 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3593 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3597 * If the 'autoreplace' property is set, then post a resource notifying
3598 * the ZFS DE that it should not issue any faults for unopenable
3599 * devices. We also iterate over the vdevs, and post a sysevent for any
3600 * unopenable vdevs so that the normal autoreplace handler can take
3603 if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3604 spa_check_removed(spa->spa_root_vdev);
3606 * For the import case, this is done in spa_import(), because
3607 * at this point we're using the spare definitions from
3608 * the MOS config, not necessarily from the userland config.
3610 if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3611 spa_aux_check_removed(&spa->spa_spares);
3612 spa_aux_check_removed(&spa->spa_l2cache);
3617 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3619 error = vdev_load(rvd);
3621 spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3622 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3626 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3628 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3629 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3630 spa_config_exit(spa, SCL_ALL, FTAG);
3636 spa_ld_load_dedup_tables(spa_t *spa)
3639 vdev_t *rvd = spa->spa_root_vdev;
3641 error = ddt_load(spa);
3643 spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3644 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3651 spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3653 vdev_t *rvd = spa->spa_root_vdev;
3655 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3656 boolean_t missing = spa_check_logs(spa);
3658 if (spa->spa_missing_tvds != 0) {
3659 spa_load_note(spa, "spa_check_logs failed "
3660 "so dropping the logs");
3662 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3663 spa_load_failed(spa, "spa_check_logs failed");
3664 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3674 spa_ld_verify_pool_data(spa_t *spa)
3677 vdev_t *rvd = spa->spa_root_vdev;
3680 * We've successfully opened the pool, verify that we're ready
3681 * to start pushing transactions.
3683 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3684 error = spa_load_verify(spa);
3686 spa_load_failed(spa, "spa_load_verify failed "
3687 "[error=%d]", error);
3688 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3697 spa_ld_claim_log_blocks(spa_t *spa)
3700 dsl_pool_t *dp = spa_get_dsl(spa);
3703 * Claim log blocks that haven't been committed yet.
3704 * This must all happen in a single txg.
3705 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3706 * invoked from zil_claim_log_block()'s i/o done callback.
3707 * Price of rollback is that we abandon the log.
3709 spa->spa_claiming = B_TRUE;
3711 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3712 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3713 zil_claim, tx, DS_FIND_CHILDREN);
3716 spa->spa_claiming = B_FALSE;
3718 spa_set_log_state(spa, SPA_LOG_GOOD);
3722 spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3723 boolean_t update_config_cache)
3725 vdev_t *rvd = spa->spa_root_vdev;
3726 int need_update = B_FALSE;
3729 * If the config cache is stale, or we have uninitialized
3730 * metaslabs (see spa_vdev_add()), then update the config.
3732 * If this is a verbatim import, trust the current
3733 * in-core spa_config and update the disk labels.
3735 if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
3736 spa->spa_load_state == SPA_LOAD_IMPORT ||
3737 spa->spa_load_state == SPA_LOAD_RECOVER ||
3738 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3739 need_update = B_TRUE;
3741 for (int c = 0; c < rvd->vdev_children; c++)
3742 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3743 need_update = B_TRUE;
3746 * Update the config cache asychronously in case we're the
3747 * root pool, in which case the config cache isn't writable yet.
3750 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3754 spa_ld_prepare_for_reload(spa_t *spa)
3756 int mode = spa->spa_mode;
3757 int async_suspended = spa->spa_async_suspended;
3760 spa_deactivate(spa);
3761 spa_activate(spa, mode);
3764 * We save the value of spa_async_suspended as it gets reset to 0 by
3765 * spa_unload(). We want to restore it back to the original value before
3766 * returning as we might be calling spa_async_resume() later.
3768 spa->spa_async_suspended = async_suspended;
3772 spa_ld_read_checkpoint_txg(spa_t *spa)
3774 uberblock_t checkpoint;
3777 ASSERT0(spa->spa_checkpoint_txg);
3778 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3780 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3781 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3782 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3784 if (error == ENOENT)
3790 ASSERT3U(checkpoint.ub_txg, !=, 0);
3791 ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3792 ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3793 spa->spa_checkpoint_txg = checkpoint.ub_txg;
3794 spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3800 spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
3804 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3805 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3808 * Never trust the config that is provided unless we are assembling
3809 * a pool following a split.
3810 * This means don't trust blkptrs and the vdev tree in general. This
3811 * also effectively puts the spa in read-only mode since
3812 * spa_writeable() checks for spa_trust_config to be true.
3813 * We will later load a trusted config from the MOS.
3815 if (type != SPA_IMPORT_ASSEMBLE)
3816 spa->spa_trust_config = B_FALSE;
3819 * Parse the config provided to create a vdev tree.
3821 error = spa_ld_parse_config(spa, type);
3826 * Now that we have the vdev tree, try to open each vdev. This involves
3827 * opening the underlying physical device, retrieving its geometry and
3828 * probing the vdev with a dummy I/O. The state of each vdev will be set
3829 * based on the success of those operations. After this we'll be ready
3830 * to read from the vdevs.
3832 error = spa_ld_open_vdevs(spa);
3837 * Read the label of each vdev and make sure that the GUIDs stored
3838 * there match the GUIDs in the config provided.
3839 * If we're assembling a new pool that's been split off from an
3840 * existing pool, the labels haven't yet been updated so we skip
3841 * validation for now.
3843 if (type != SPA_IMPORT_ASSEMBLE) {
3844 error = spa_ld_validate_vdevs(spa);
3850 * Read all vdev labels to find the best uberblock (i.e. latest,
3851 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3852 * get the list of features required to read blkptrs in the MOS from
3853 * the vdev label with the best uberblock and verify that our version
3854 * of zfs supports them all.
3856 error = spa_ld_select_uberblock(spa, type);
3861 * Pass that uberblock to the dsl_pool layer which will open the root
3862 * blkptr. This blkptr points to the latest version of the MOS and will
3863 * allow us to read its contents.
3865 error = spa_ld_open_rootbp(spa);
3873 spa_ld_checkpoint_rewind(spa_t *spa)
3875 uberblock_t checkpoint;
3878 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3879 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3881 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3882 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3883 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3886 spa_load_failed(spa, "unable to retrieve checkpointed "
3887 "uberblock from the MOS config [error=%d]", error);
3889 if (error == ENOENT)
3890 error = ZFS_ERR_NO_CHECKPOINT;
3895 ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
3896 ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
3899 * We need to update the txg and timestamp of the checkpointed
3900 * uberblock to be higher than the latest one. This ensures that
3901 * the checkpointed uberblock is selected if we were to close and
3902 * reopen the pool right after we've written it in the vdev labels.
3903 * (also see block comment in vdev_uberblock_compare)
3905 checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
3906 checkpoint.ub_timestamp = gethrestime_sec();
3909 * Set current uberblock to be the checkpointed uberblock.
3911 spa->spa_uberblock = checkpoint;
3914 * If we are doing a normal rewind, then the pool is open for
3915 * writing and we sync the "updated" checkpointed uberblock to
3916 * disk. Once this is done, we've basically rewound the whole
3917 * pool and there is no way back.
3919 * There are cases when we don't want to attempt and sync the
3920 * checkpointed uberblock to disk because we are opening a
3921 * pool as read-only. Specifically, verifying the checkpointed
3922 * state with zdb, and importing the checkpointed state to get
3923 * a "preview" of its content.
3925 if (spa_writeable(spa)) {
3926 vdev_t *rvd = spa->spa_root_vdev;
3928 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3929 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
3931 int children = rvd->vdev_children;
3932 int c0 = spa_get_random(children);
3934 for (int c = 0; c < children; c++) {
3935 vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
3937 /* Stop when revisiting the first vdev */
3938 if (c > 0 && svd[0] == vd)
3941 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
3942 !vdev_is_concrete(vd))
3945 svd[svdcount++] = vd;
3946 if (svdcount == SPA_SYNC_MIN_VDEVS)
3949 error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
3951 spa->spa_last_synced_guid = rvd->vdev_guid;
3952 spa_config_exit(spa, SCL_ALL, FTAG);
3955 spa_load_failed(spa, "failed to write checkpointed "
3956 "uberblock to the vdev labels [error=%d]", error);
3965 spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
3966 boolean_t *update_config_cache)
3971 * Parse the config for pool, open and validate vdevs,
3972 * select an uberblock, and use that uberblock to open
3975 error = spa_ld_mos_init(spa, type);
3980 * Retrieve the trusted config stored in the MOS and use it to create
3981 * a new, exact version of the vdev tree, then reopen all vdevs.
3983 error = spa_ld_trusted_config(spa, type, B_FALSE);
3984 if (error == EAGAIN) {
3985 if (update_config_cache != NULL)
3986 *update_config_cache = B_TRUE;
3989 * Redo the loading process with the trusted config if it is
3990 * too different from the untrusted config.
3992 spa_ld_prepare_for_reload(spa);
3993 spa_load_note(spa, "RELOADING");
3994 error = spa_ld_mos_init(spa, type);
3998 error = spa_ld_trusted_config(spa, type, B_TRUE);
4002 } else if (error != 0) {
4010 * Load an existing storage pool, using the config provided. This config
4011 * describes which vdevs are part of the pool and is later validated against
4012 * partial configs present in each vdev's label and an entire copy of the
4013 * config stored in the MOS.
4016 spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
4019 boolean_t missing_feat_write = B_FALSE;
4020 boolean_t checkpoint_rewind =
4021 (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4022 boolean_t update_config_cache = B_FALSE;
4024 ASSERT(MUTEX_HELD(&spa_namespace_lock));
4025 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
4027 spa_load_note(spa, "LOADING");
4029 error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
4034 * If we are rewinding to the checkpoint then we need to repeat
4035 * everything we've done so far in this function but this time
4036 * selecting the checkpointed uberblock and using that to open
4039 if (checkpoint_rewind) {
4041 * If we are rewinding to the checkpoint update config cache
4044 update_config_cache = B_TRUE;
4047 * Extract the checkpointed uberblock from the current MOS
4048 * and use this as the pool's uberblock from now on. If the
4049 * pool is imported as writeable we also write the checkpoint
4050 * uberblock to the labels, making the rewind permanent.
4052 error = spa_ld_checkpoint_rewind(spa);
4057 * Redo the loading process process again with the
4058 * checkpointed uberblock.
4060 spa_ld_prepare_for_reload(spa);
4061 spa_load_note(spa, "LOADING checkpointed uberblock");
4062 error = spa_ld_mos_with_trusted_config(spa, type, NULL);
4068 * Retrieve the checkpoint txg if the pool has a checkpoint.
4070 error = spa_ld_read_checkpoint_txg(spa);
4075 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
4076 * from the pool and their contents were re-mapped to other vdevs. Note
4077 * that everything that we read before this step must have been
4078 * rewritten on concrete vdevs after the last device removal was
4079 * initiated. Otherwise we could be reading from indirect vdevs before
4080 * we have loaded their mappings.
4082 error = spa_ld_open_indirect_vdev_metadata(spa);
4087 * Retrieve the full list of active features from the MOS and check if
4088 * they are all supported.
4090 error = spa_ld_check_features(spa, &missing_feat_write);
4095 * Load several special directories from the MOS needed by the dsl_pool
4098 error = spa_ld_load_special_directories(spa);
4103 * Retrieve pool properties from the MOS.
4105 error = spa_ld_get_props(spa);
4110 * Retrieve the list of auxiliary devices - cache devices and spares -
4113 error = spa_ld_open_aux_vdevs(spa, type);
4118 * Load the metadata for all vdevs. Also check if unopenable devices
4119 * should be autoreplaced.
4121 error = spa_ld_load_vdev_metadata(spa);
4125 error = spa_ld_load_dedup_tables(spa);
4130 * Verify the logs now to make sure we don't have any unexpected errors
4131 * when we claim log blocks later.
4133 error = spa_ld_verify_logs(spa, type, ereport);
4137 if (missing_feat_write) {
4138 ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
4141 * At this point, we know that we can open the pool in
4142 * read-only mode but not read-write mode. We now have enough
4143 * information and can return to userland.
4145 return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
4150 * Traverse the last txgs to make sure the pool was left off in a safe
4151 * state. When performing an extreme rewind, we verify the whole pool,
4152 * which can take a very long time.
4154 error = spa_ld_verify_pool_data(spa);
4159 * Calculate the deflated space for the pool. This must be done before
4160 * we write anything to the pool because we'd need to update the space
4161 * accounting using the deflated sizes.
4163 spa_update_dspace(spa);
4166 * We have now retrieved all the information we needed to open the
4167 * pool. If we are importing the pool in read-write mode, a few
4168 * additional steps must be performed to finish the import.
4170 if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
4171 spa->spa_load_max_txg == UINT64_MAX)) {
4172 uint64_t config_cache_txg = spa->spa_config_txg;
4174 ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
4177 * In case of a checkpoint rewind, log the original txg
4178 * of the checkpointed uberblock.
4180 if (checkpoint_rewind) {
4181 spa_history_log_internal(spa, "checkpoint rewind",
4182 NULL, "rewound state to txg=%llu",
4183 (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
4187 * Traverse the ZIL and claim all blocks.
4189 spa_ld_claim_log_blocks(spa);
4192 * Kick-off the syncing thread.
4194 spa->spa_sync_on = B_TRUE;
4195 txg_sync_start(spa->spa_dsl_pool);
4196 mmp_thread_start(spa);
4199 * Wait for all claims to sync. We sync up to the highest
4200 * claimed log block birth time so that claimed log blocks
4201 * don't appear to be from the future. spa_claim_max_txg
4202 * will have been set for us by ZIL traversal operations
4205 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
4208 * Check if we need to request an update of the config. On the
4209 * next sync, we would update the config stored in vdev labels
4210 * and the cachefile (by default /etc/zfs/zpool.cache).
4212 spa_ld_check_for_config_update(spa, config_cache_txg,
4213 update_config_cache);
4216 * Check all DTLs to see if anything needs resilvering.
4218 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
4219 vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
4220 spa_async_request(spa, SPA_ASYNC_RESILVER);
4223 * Log the fact that we booted up (so that we can detect if
4224 * we rebooted in the middle of an operation).
4226 spa_history_log_version(spa, "open", NULL);
4229 * Delete any inconsistent datasets.
4231 (void) dmu_objset_find(spa_name(spa),
4232 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
4235 * Clean up any stale temporary dataset userrefs.
4237 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
4239 spa_restart_removal(spa);
4241 spa_spawn_aux_threads(spa);
4244 spa_load_note(spa, "LOADED");
4250 spa_load_retry(spa_t *spa, spa_load_state_t state)
4252 int mode = spa->spa_mode;
4255 spa_deactivate(spa);
4257 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
4259 spa_activate(spa, mode);
4260 spa_async_suspend(spa);
4262 spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
4263 (u_longlong_t)spa->spa_load_max_txg);
4265 return (spa_load(spa, state, SPA_IMPORT_EXISTING));
4269 * If spa_load() fails this function will try loading prior txg's. If
4270 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
4271 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
4272 * function will not rewind the pool and will return the same error as
4276 spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4279 nvlist_t *loadinfo = NULL;
4280 nvlist_t *config = NULL;
4281 int load_error, rewind_error;
4282 uint64_t safe_rewind_txg;
4285 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4286 spa->spa_load_max_txg = spa->spa_load_txg;
4287 spa_set_log_state(spa, SPA_LOG_CLEAR);
4289 spa->spa_load_max_txg = max_request;
4290 if (max_request != UINT64_MAX)
4291 spa->spa_extreme_rewind = B_TRUE;
4294 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
4295 if (load_error == 0)
4297 if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4299 * When attempting checkpoint-rewind on a pool with no
4300 * checkpoint, we should not attempt to load uberblocks
4301 * from previous txgs when spa_load fails.
4303 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4304 return (load_error);
4307 if (spa->spa_root_vdev != NULL)
4308 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4310 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4311 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4313 if (rewind_flags & ZPOOL_NEVER_REWIND) {
4314 nvlist_free(config);
4315 return (load_error);
4318 if (state == SPA_LOAD_RECOVER) {
4319 /* Price of rolling back is discarding txgs, including log */
4320 spa_set_log_state(spa, SPA_LOG_CLEAR);
4323 * If we aren't rolling back save the load info from our first
4324 * import attempt so that we can restore it after attempting
4327 loadinfo = spa->spa_load_info;
4328 spa->spa_load_info = fnvlist_alloc();
4331 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4332 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4333 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4334 TXG_INITIAL : safe_rewind_txg;
4337 * Continue as long as we're finding errors, we're still within
4338 * the acceptable rewind range, and we're still finding uberblocks
4340 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4341 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4342 if (spa->spa_load_max_txg < safe_rewind_txg)
4343 spa->spa_extreme_rewind = B_TRUE;
4344 rewind_error = spa_load_retry(spa, state);
4347 spa->spa_extreme_rewind = B_FALSE;
4348 spa->spa_load_max_txg = UINT64_MAX;
4350 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4351 spa_config_set(spa, config);
4353 nvlist_free(config);
4355 if (state == SPA_LOAD_RECOVER) {
4356 ASSERT3P(loadinfo, ==, NULL);
4357 return (rewind_error);
4359 /* Store the rewind info as part of the initial load info */
4360 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4361 spa->spa_load_info);
4363 /* Restore the initial load info */
4364 fnvlist_free(spa->spa_load_info);
4365 spa->spa_load_info = loadinfo;
4367 return (load_error);
4374 * The import case is identical to an open except that the configuration is sent
4375 * down from userland, instead of grabbed from the configuration cache. For the
4376 * case of an open, the pool configuration will exist in the
4377 * POOL_STATE_UNINITIALIZED state.
4379 * The stats information (gen/count/ustats) is used to gather vdev statistics at
4380 * the same time open the pool, without having to keep around the spa_t in some
4384 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4388 spa_load_state_t state = SPA_LOAD_OPEN;
4390 int locked = B_FALSE;
4391 int firstopen = B_FALSE;
4396 * As disgusting as this is, we need to support recursive calls to this
4397 * function because dsl_dir_open() is called during spa_load(), and ends
4398 * up calling spa_open() again. The real fix is to figure out how to
4399 * avoid dsl_dir_open() calling this in the first place.
4401 if (MUTEX_NOT_HELD(&spa_namespace_lock)) {
4402 mutex_enter(&spa_namespace_lock);
4406 if ((spa = spa_lookup(pool)) == NULL) {
4408 mutex_exit(&spa_namespace_lock);
4409 return (SET_ERROR(ENOENT));
4412 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
4413 zpool_load_policy_t policy;
4417 zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
4419 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
4420 state = SPA_LOAD_RECOVER;
4422 spa_activate(spa, spa_mode_global);
4424 if (state != SPA_LOAD_RECOVER)
4425 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4426 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
4428 zfs_dbgmsg("spa_open_common: opening %s", pool);
4429 error = spa_load_best(spa, state, policy.zlp_txg,
4432 if (error == EBADF) {
4434 * If vdev_validate() returns failure (indicated by
4435 * EBADF), it indicates that one of the vdevs indicates
4436 * that the pool has been exported or destroyed. If
4437 * this is the case, the config cache is out of sync and
4438 * we should remove the pool from the namespace.
4441 spa_deactivate(spa);
4442 spa_write_cachefile(spa, B_TRUE, B_TRUE);
4445 mutex_exit(&spa_namespace_lock);
4446 return (SET_ERROR(ENOENT));
4451 * We can't open the pool, but we still have useful
4452 * information: the state of each vdev after the
4453 * attempted vdev_open(). Return this to the user.
4455 if (config != NULL && spa->spa_config) {
4456 VERIFY(nvlist_dup(spa->spa_config, config,
4458 VERIFY(nvlist_add_nvlist(*config,
4459 ZPOOL_CONFIG_LOAD_INFO,
4460 spa->spa_load_info) == 0);
4463 spa_deactivate(spa);
4464 spa->spa_last_open_failed = error;
4466 mutex_exit(&spa_namespace_lock);
4472 spa_open_ref(spa, tag);
4475 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4478 * If we've recovered the pool, pass back any information we
4479 * gathered while doing the load.
4481 if (state == SPA_LOAD_RECOVER) {
4482 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4483 spa->spa_load_info) == 0);
4487 spa->spa_last_open_failed = 0;
4488 spa->spa_last_ubsync_txg = 0;
4489 spa->spa_load_txg = 0;
4490 mutex_exit(&spa_namespace_lock);
4494 zvol_create_minors(spa, spa_name(spa), B_TRUE);
4502 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4505 return (spa_open_common(name, spapp, tag, policy, config));
4509 spa_open(const char *name, spa_t **spapp, void *tag)
4511 return (spa_open_common(name, spapp, tag, NULL, NULL));
4515 * Lookup the given spa_t, incrementing the inject count in the process,
4516 * preventing it from being exported or destroyed.
4519 spa_inject_addref(char *name)
4523 mutex_enter(&spa_namespace_lock);
4524 if ((spa = spa_lookup(name)) == NULL) {
4525 mutex_exit(&spa_namespace_lock);
4528 spa->spa_inject_ref++;
4529 mutex_exit(&spa_namespace_lock);
4535 spa_inject_delref(spa_t *spa)
4537 mutex_enter(&spa_namespace_lock);
4538 spa->spa_inject_ref--;
4539 mutex_exit(&spa_namespace_lock);
4543 * Add spares device information to the nvlist.
4546 spa_add_spares(spa_t *spa, nvlist_t *config)
4556 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4558 if (spa->spa_spares.sav_count == 0)
4561 VERIFY(nvlist_lookup_nvlist(config,
4562 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4563 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4564 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4566 VERIFY(nvlist_add_nvlist_array(nvroot,
4567 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4568 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4569 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4572 * Go through and find any spares which have since been
4573 * repurposed as an active spare. If this is the case, update
4574 * their status appropriately.
4576 for (i = 0; i < nspares; i++) {
4577 VERIFY(nvlist_lookup_uint64(spares[i],
4578 ZPOOL_CONFIG_GUID, &guid) == 0);
4579 if (spa_spare_exists(guid, &pool, NULL) &&
4581 VERIFY(nvlist_lookup_uint64_array(
4582 spares[i], ZPOOL_CONFIG_VDEV_STATS,
4583 (uint64_t **)&vs, &vsc) == 0);
4584 vs->vs_state = VDEV_STATE_CANT_OPEN;
4585 vs->vs_aux = VDEV_AUX_SPARED;
4592 * Add l2cache device information to the nvlist, including vdev stats.
4595 spa_add_l2cache(spa_t *spa, nvlist_t *config)
4598 uint_t i, j, nl2cache;
4605 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4607 if (spa->spa_l2cache.sav_count == 0)
4610 VERIFY(nvlist_lookup_nvlist(config,
4611 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4612 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4613 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4614 if (nl2cache != 0) {
4615 VERIFY(nvlist_add_nvlist_array(nvroot,
4616 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4617 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4618 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4621 * Update level 2 cache device stats.
4624 for (i = 0; i < nl2cache; i++) {
4625 VERIFY(nvlist_lookup_uint64(l2cache[i],
4626 ZPOOL_CONFIG_GUID, &guid) == 0);
4629 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4631 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4632 vd = spa->spa_l2cache.sav_vdevs[j];
4638 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4639 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4641 vdev_get_stats(vd, vs);
4642 vdev_config_generate_stats(vd, l2cache[i]);
4649 spa_feature_stats_from_disk(spa_t *spa, nvlist_t *features)
4654 if (spa->spa_feat_for_read_obj != 0) {
4655 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4656 spa->spa_feat_for_read_obj);
4657 zap_cursor_retrieve(&zc, &za) == 0;
4658 zap_cursor_advance(&zc)) {
4659 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4660 za.za_num_integers == 1);
4661 VERIFY0(nvlist_add_uint64(features, za.za_name,
4662 za.za_first_integer));
4664 zap_cursor_fini(&zc);
4667 if (spa->spa_feat_for_write_obj != 0) {
4668 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4669 spa->spa_feat_for_write_obj);
4670 zap_cursor_retrieve(&zc, &za) == 0;
4671 zap_cursor_advance(&zc)) {
4672 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4673 za.za_num_integers == 1);
4674 VERIFY0(nvlist_add_uint64(features, za.za_name,
4675 za.za_first_integer));
4677 zap_cursor_fini(&zc);
4682 spa_feature_stats_from_cache(spa_t *spa, nvlist_t *features)
4686 for (i = 0; i < SPA_FEATURES; i++) {
4687 zfeature_info_t feature = spa_feature_table[i];
4690 if (feature_get_refcount(spa, &feature, &refcount) != 0)
4693 VERIFY0(nvlist_add_uint64(features, feature.fi_guid, refcount));
4698 * Store a list of pool features and their reference counts in the
4701 * The first time this is called on a spa, allocate a new nvlist, fetch
4702 * the pool features and reference counts from disk, then save the list
4703 * in the spa. In subsequent calls on the same spa use the saved nvlist
4704 * and refresh its values from the cached reference counts. This
4705 * ensures we don't block here on I/O on a suspended pool so 'zpool
4706 * clear' can resume the pool.
4709 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4713 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4715 mutex_enter(&spa->spa_feat_stats_lock);
4716 features = spa->spa_feat_stats;
4718 if (features != NULL) {
4719 spa_feature_stats_from_cache(spa, features);
4721 VERIFY0(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP));
4722 spa->spa_feat_stats = features;
4723 spa_feature_stats_from_disk(spa, features);
4726 VERIFY0(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4729 mutex_exit(&spa->spa_feat_stats_lock);
4733 spa_get_stats(const char *name, nvlist_t **config,
4734 char *altroot, size_t buflen)
4740 error = spa_open_common(name, &spa, FTAG, NULL, config);
4744 * This still leaves a window of inconsistency where the spares
4745 * or l2cache devices could change and the config would be
4746 * self-inconsistent.
4748 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4750 if (*config != NULL) {
4751 uint64_t loadtimes[2];
4753 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4754 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4755 VERIFY(nvlist_add_uint64_array(*config,
4756 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4758 VERIFY(nvlist_add_uint64(*config,
4759 ZPOOL_CONFIG_ERRCOUNT,
4760 spa_get_errlog_size(spa)) == 0);
4762 if (spa_suspended(spa)) {
4763 VERIFY(nvlist_add_uint64(*config,
4764 ZPOOL_CONFIG_SUSPENDED,
4765 spa->spa_failmode) == 0);
4766 VERIFY(nvlist_add_uint64(*config,
4767 ZPOOL_CONFIG_SUSPENDED_REASON,
4768 spa->spa_suspended) == 0);
4771 spa_add_spares(spa, *config);
4772 spa_add_l2cache(spa, *config);
4773 spa_add_feature_stats(spa, *config);
4778 * We want to get the alternate root even for faulted pools, so we cheat
4779 * and call spa_lookup() directly.
4783 mutex_enter(&spa_namespace_lock);
4784 spa = spa_lookup(name);
4786 spa_altroot(spa, altroot, buflen);
4790 mutex_exit(&spa_namespace_lock);
4792 spa_altroot(spa, altroot, buflen);
4797 spa_config_exit(spa, SCL_CONFIG, FTAG);
4798 spa_close(spa, FTAG);
4805 * Validate that the auxiliary device array is well formed. We must have an
4806 * array of nvlists, each which describes a valid leaf vdev. If this is an
4807 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4808 * specified, as long as they are well-formed.
4811 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4812 spa_aux_vdev_t *sav, const char *config, uint64_t version,
4813 vdev_labeltype_t label)
4820 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4823 * It's acceptable to have no devs specified.
4825 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4829 return (SET_ERROR(EINVAL));
4832 * Make sure the pool is formatted with a version that supports this
4835 if (spa_version(spa) < version)
4836 return (SET_ERROR(ENOTSUP));
4839 * Set the pending device list so we correctly handle device in-use
4842 sav->sav_pending = dev;
4843 sav->sav_npending = ndev;
4845 for (i = 0; i < ndev; i++) {
4846 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4850 if (!vd->vdev_ops->vdev_op_leaf) {
4852 error = SET_ERROR(EINVAL);
4858 if ((error = vdev_open(vd)) == 0 &&
4859 (error = vdev_label_init(vd, crtxg, label)) == 0) {
4860 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4861 vd->vdev_guid) == 0);
4867 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
4874 sav->sav_pending = NULL;
4875 sav->sav_npending = 0;
4880 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
4884 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4886 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4887 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
4888 VDEV_LABEL_SPARE)) != 0) {
4892 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4893 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
4894 VDEV_LABEL_L2CACHE));
4898 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
4903 if (sav->sav_config != NULL) {
4909 * Generate new dev list by concatenating with the
4912 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
4913 &olddevs, &oldndevs) == 0);
4915 newdevs = kmem_alloc(sizeof (void *) *
4916 (ndevs + oldndevs), KM_SLEEP);
4917 for (i = 0; i < oldndevs; i++)
4918 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
4920 for (i = 0; i < ndevs; i++)
4921 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
4924 VERIFY(nvlist_remove(sav->sav_config, config,
4925 DATA_TYPE_NVLIST_ARRAY) == 0);
4927 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
4928 config, newdevs, ndevs + oldndevs) == 0);
4929 for (i = 0; i < oldndevs + ndevs; i++)
4930 nvlist_free(newdevs[i]);
4931 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
4934 * Generate a new dev list.
4936 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
4938 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
4944 * Stop and drop level 2 ARC devices
4947 spa_l2cache_drop(spa_t *spa)
4951 spa_aux_vdev_t *sav = &spa->spa_l2cache;
4953 for (i = 0; i < sav->sav_count; i++) {
4956 vd = sav->sav_vdevs[i];
4959 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
4960 pool != 0ULL && l2arc_vdev_present(vd))
4961 l2arc_remove_vdev(vd);
4966 * Verify encryption parameters for spa creation. If we are encrypting, we must
4967 * have the encryption feature flag enabled.
4970 spa_create_check_encryption_params(dsl_crypto_params_t *dcp,
4971 boolean_t has_encryption)
4973 if (dcp->cp_crypt != ZIO_CRYPT_OFF &&
4974 dcp->cp_crypt != ZIO_CRYPT_INHERIT &&
4976 return (SET_ERROR(ENOTSUP));
4978 return (dmu_objset_create_crypt_check(NULL, dcp, NULL));
4985 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
4986 nvlist_t *zplprops, dsl_crypto_params_t *dcp)
4989 char *altroot = NULL;
4994 uint64_t txg = TXG_INITIAL;
4995 nvlist_t **spares, **l2cache;
4996 uint_t nspares, nl2cache;
4997 uint64_t version, obj, root_dsobj = 0;
4998 boolean_t has_features;
4999 boolean_t has_encryption;
5005 if (props == NULL ||
5006 nvlist_lookup_string(props, "tname", &poolname) != 0)
5007 poolname = (char *)pool;
5010 * If this pool already exists, return failure.
5012 mutex_enter(&spa_namespace_lock);
5013 if (spa_lookup(poolname) != NULL) {
5014 mutex_exit(&spa_namespace_lock);
5015 return (SET_ERROR(EEXIST));
5019 * Allocate a new spa_t structure.
5021 nvl = fnvlist_alloc();
5022 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
5023 (void) nvlist_lookup_string(props,
5024 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5025 spa = spa_add(poolname, nvl, altroot);
5027 spa_activate(spa, spa_mode_global);
5029 if (props && (error = spa_prop_validate(spa, props))) {
5030 spa_deactivate(spa);
5032 mutex_exit(&spa_namespace_lock);
5037 * Temporary pool names should never be written to disk.
5039 if (poolname != pool)
5040 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
5042 has_features = B_FALSE;
5043 has_encryption = B_FALSE;
5044 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
5045 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
5046 if (zpool_prop_feature(nvpair_name(elem))) {
5047 has_features = B_TRUE;
5049 feat_name = strchr(nvpair_name(elem), '@') + 1;
5050 VERIFY0(zfeature_lookup_name(feat_name, &feat));
5051 if (feat == SPA_FEATURE_ENCRYPTION)
5052 has_encryption = B_TRUE;
5056 /* verify encryption params, if they were provided */
5058 error = spa_create_check_encryption_params(dcp, has_encryption);
5060 spa_deactivate(spa);
5062 mutex_exit(&spa_namespace_lock);
5067 if (has_features || nvlist_lookup_uint64(props,
5068 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
5069 version = SPA_VERSION;
5071 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
5073 spa->spa_first_txg = txg;
5074 spa->spa_uberblock.ub_txg = txg - 1;
5075 spa->spa_uberblock.ub_version = version;
5076 spa->spa_ubsync = spa->spa_uberblock;
5077 spa->spa_load_state = SPA_LOAD_CREATE;
5078 spa->spa_removing_phys.sr_state = DSS_NONE;
5079 spa->spa_removing_phys.sr_removing_vdev = -1;
5080 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
5083 * Create "The Godfather" zio to hold all async IOs
5085 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
5087 for (int i = 0; i < max_ncpus; i++) {
5088 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
5089 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
5090 ZIO_FLAG_GODFATHER);
5094 * Create the root vdev.
5096 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5098 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
5100 ASSERT(error != 0 || rvd != NULL);
5101 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
5103 if (error == 0 && !zfs_allocatable_devs(nvroot))
5104 error = SET_ERROR(EINVAL);
5107 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
5108 (error = spa_validate_aux(spa, nvroot, txg,
5109 VDEV_ALLOC_ADD)) == 0) {
5111 * instantiate the metaslab groups (this will dirty the vdevs)
5112 * we can no longer error exit past this point
5114 for (int c = 0; error == 0 && c < rvd->vdev_children; c++) {
5115 vdev_t *vd = rvd->vdev_child[c];
5117 vdev_metaslab_set_size(vd);
5118 vdev_expand(vd, txg);
5122 spa_config_exit(spa, SCL_ALL, FTAG);
5126 spa_deactivate(spa);
5128 mutex_exit(&spa_namespace_lock);
5133 * Get the list of spares, if specified.
5135 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5136 &spares, &nspares) == 0) {
5137 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
5139 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5140 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5141 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5142 spa_load_spares(spa);
5143 spa_config_exit(spa, SCL_ALL, FTAG);
5144 spa->spa_spares.sav_sync = B_TRUE;
5148 * Get the list of level 2 cache devices, if specified.
5150 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5151 &l2cache, &nl2cache) == 0) {
5152 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5153 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5154 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5155 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5156 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5157 spa_load_l2cache(spa);
5158 spa_config_exit(spa, SCL_ALL, FTAG);
5159 spa->spa_l2cache.sav_sync = B_TRUE;
5162 spa->spa_is_initializing = B_TRUE;
5163 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, dcp, txg);
5164 spa->spa_is_initializing = B_FALSE;
5167 * Create DDTs (dedup tables).
5171 spa_update_dspace(spa);
5173 tx = dmu_tx_create_assigned(dp, txg);
5176 * Create the pool's history object.
5178 if (version >= SPA_VERSION_ZPOOL_HISTORY && !spa->spa_history)
5179 spa_history_create_obj(spa, tx);
5181 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
5182 spa_history_log_version(spa, "create", tx);
5185 * Create the pool config object.
5187 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
5188 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
5189 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
5191 if (zap_add(spa->spa_meta_objset,
5192 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
5193 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
5194 cmn_err(CE_PANIC, "failed to add pool config");
5197 if (zap_add(spa->spa_meta_objset,
5198 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
5199 sizeof (uint64_t), 1, &version, tx) != 0) {
5200 cmn_err(CE_PANIC, "failed to add pool version");
5203 /* Newly created pools with the right version are always deflated. */
5204 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
5205 spa->spa_deflate = TRUE;
5206 if (zap_add(spa->spa_meta_objset,
5207 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
5208 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
5209 cmn_err(CE_PANIC, "failed to add deflate");
5214 * Create the deferred-free bpobj. Turn off compression
5215 * because sync-to-convergence takes longer if the blocksize
5218 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
5219 dmu_object_set_compress(spa->spa_meta_objset, obj,
5220 ZIO_COMPRESS_OFF, tx);
5221 if (zap_add(spa->spa_meta_objset,
5222 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
5223 sizeof (uint64_t), 1, &obj, tx) != 0) {
5224 cmn_err(CE_PANIC, "failed to add bpobj");
5226 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
5227 spa->spa_meta_objset, obj));
5230 * Generate some random noise for salted checksums to operate on.
5232 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
5233 sizeof (spa->spa_cksum_salt.zcs_bytes));
5236 * Set pool properties.
5238 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
5239 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
5240 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
5241 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
5242 spa->spa_multihost = zpool_prop_default_numeric(ZPOOL_PROP_MULTIHOST);
5244 if (props != NULL) {
5245 spa_configfile_set(spa, props, B_FALSE);
5246 spa_sync_props(props, tx);
5252 * If the root dataset is encrypted we will need to create key mappings
5253 * for the zio layer before we start to write any data to disk and hold
5254 * them until after the first txg has been synced. Waiting for the first
5255 * transaction to complete also ensures that our bean counters are
5256 * appropriately updated.
5258 if (dp->dp_root_dir->dd_crypto_obj != 0) {
5259 root_dsobj = dsl_dir_phys(dp->dp_root_dir)->dd_head_dataset_obj;
5260 VERIFY0(spa_keystore_create_mapping_impl(spa, root_dsobj,
5261 dp->dp_root_dir, FTAG));
5264 spa->spa_sync_on = B_TRUE;
5266 mmp_thread_start(spa);
5267 txg_wait_synced(dp, txg);
5269 if (dp->dp_root_dir->dd_crypto_obj != 0)
5270 VERIFY0(spa_keystore_remove_mapping(spa, root_dsobj, FTAG));
5272 spa_spawn_aux_threads(spa);
5274 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5277 * Don't count references from objsets that are already closed
5278 * and are making their way through the eviction process.
5280 spa_evicting_os_wait(spa);
5281 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
5282 spa->spa_load_state = SPA_LOAD_NONE;
5284 mutex_exit(&spa_namespace_lock);
5290 * Import a non-root pool into the system.
5293 spa_import(char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5296 char *altroot = NULL;
5297 spa_load_state_t state = SPA_LOAD_IMPORT;
5298 zpool_load_policy_t policy;
5299 uint64_t mode = spa_mode_global;
5300 uint64_t readonly = B_FALSE;
5303 nvlist_t **spares, **l2cache;
5304 uint_t nspares, nl2cache;
5307 * If a pool with this name exists, return failure.
5309 mutex_enter(&spa_namespace_lock);
5310 if (spa_lookup(pool) != NULL) {
5311 mutex_exit(&spa_namespace_lock);
5312 return (SET_ERROR(EEXIST));
5316 * Create and initialize the spa structure.
5318 (void) nvlist_lookup_string(props,
5319 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5320 (void) nvlist_lookup_uint64(props,
5321 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5324 spa = spa_add(pool, config, altroot);
5325 spa->spa_import_flags = flags;
5328 * Verbatim import - Take a pool and insert it into the namespace
5329 * as if it had been loaded at boot.
5331 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5333 spa_configfile_set(spa, props, B_FALSE);
5335 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5336 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5337 zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5338 mutex_exit(&spa_namespace_lock);
5342 spa_activate(spa, mode);
5345 * Don't start async tasks until we know everything is healthy.
5347 spa_async_suspend(spa);
5349 zpool_get_load_policy(config, &policy);
5350 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5351 state = SPA_LOAD_RECOVER;
5353 spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5355 if (state != SPA_LOAD_RECOVER) {
5356 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5357 zfs_dbgmsg("spa_import: importing %s", pool);
5359 zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5360 "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
5362 error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
5365 * Propagate anything learned while loading the pool and pass it
5366 * back to caller (i.e. rewind info, missing devices, etc).
5368 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5369 spa->spa_load_info) == 0);
5371 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5373 * Toss any existing sparelist, as it doesn't have any validity
5374 * anymore, and conflicts with spa_has_spare().
5376 if (spa->spa_spares.sav_config) {
5377 nvlist_free(spa->spa_spares.sav_config);
5378 spa->spa_spares.sav_config = NULL;
5379 spa_load_spares(spa);
5381 if (spa->spa_l2cache.sav_config) {
5382 nvlist_free(spa->spa_l2cache.sav_config);
5383 spa->spa_l2cache.sav_config = NULL;
5384 spa_load_l2cache(spa);
5387 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5389 spa_config_exit(spa, SCL_ALL, FTAG);
5392 spa_configfile_set(spa, props, B_FALSE);
5394 if (error != 0 || (props && spa_writeable(spa) &&
5395 (error = spa_prop_set(spa, props)))) {
5397 spa_deactivate(spa);
5399 mutex_exit(&spa_namespace_lock);
5403 spa_async_resume(spa);
5406 * Override any spares and level 2 cache devices as specified by
5407 * the user, as these may have correct device names/devids, etc.
5409 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5410 &spares, &nspares) == 0) {
5411 if (spa->spa_spares.sav_config)
5412 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5413 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5415 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5416 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5417 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5418 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5419 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5420 spa_load_spares(spa);
5421 spa_config_exit(spa, SCL_ALL, FTAG);
5422 spa->spa_spares.sav_sync = B_TRUE;
5424 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5425 &l2cache, &nl2cache) == 0) {
5426 if (spa->spa_l2cache.sav_config)
5427 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5428 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5430 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5431 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5432 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5433 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5434 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5435 spa_load_l2cache(spa);
5436 spa_config_exit(spa, SCL_ALL, FTAG);
5437 spa->spa_l2cache.sav_sync = B_TRUE;
5441 * Check for any removed devices.
5443 if (spa->spa_autoreplace) {
5444 spa_aux_check_removed(&spa->spa_spares);
5445 spa_aux_check_removed(&spa->spa_l2cache);
5448 if (spa_writeable(spa)) {
5450 * Update the config cache to include the newly-imported pool.
5452 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5456 * It's possible that the pool was expanded while it was exported.
5457 * We kick off an async task to handle this for us.
5459 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5461 spa_history_log_version(spa, "import", NULL);
5463 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5465 zvol_create_minors(spa, pool, B_TRUE);
5467 mutex_exit(&spa_namespace_lock);
5473 spa_tryimport(nvlist_t *tryconfig)
5475 nvlist_t *config = NULL;
5476 char *poolname, *cachefile;
5480 zpool_load_policy_t policy;
5482 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5485 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5489 * Create and initialize the spa structure.
5491 mutex_enter(&spa_namespace_lock);
5492 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
5493 spa_activate(spa, FREAD);
5496 * Rewind pool if a max txg was provided.
5498 zpool_get_load_policy(spa->spa_config, &policy);
5499 if (policy.zlp_txg != UINT64_MAX) {
5500 spa->spa_load_max_txg = policy.zlp_txg;
5501 spa->spa_extreme_rewind = B_TRUE;
5502 zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
5503 poolname, (longlong_t)policy.zlp_txg);
5505 zfs_dbgmsg("spa_tryimport: importing %s", poolname);
5508 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
5510 zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
5511 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5513 spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
5516 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
5519 * If 'tryconfig' was at least parsable, return the current config.
5521 if (spa->spa_root_vdev != NULL) {
5522 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5523 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
5525 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5527 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
5528 spa->spa_uberblock.ub_timestamp) == 0);
5529 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5530 spa->spa_load_info) == 0);
5531 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_ERRATA,
5532 spa->spa_errata) == 0);
5535 * If the bootfs property exists on this pool then we
5536 * copy it out so that external consumers can tell which
5537 * pools are bootable.
5539 if ((!error || error == EEXIST) && spa->spa_bootfs) {
5540 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5543 * We have to play games with the name since the
5544 * pool was opened as TRYIMPORT_NAME.
5546 if (dsl_dsobj_to_dsname(spa_name(spa),
5547 spa->spa_bootfs, tmpname) == 0) {
5551 dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5553 cp = strchr(tmpname, '/');
5555 (void) strlcpy(dsname, tmpname,
5558 (void) snprintf(dsname, MAXPATHLEN,
5559 "%s/%s", poolname, ++cp);
5561 VERIFY(nvlist_add_string(config,
5562 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
5563 kmem_free(dsname, MAXPATHLEN);
5565 kmem_free(tmpname, MAXPATHLEN);
5569 * Add the list of hot spares and level 2 cache devices.
5571 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5572 spa_add_spares(spa, config);
5573 spa_add_l2cache(spa, config);
5574 spa_config_exit(spa, SCL_CONFIG, FTAG);
5578 spa_deactivate(spa);
5580 mutex_exit(&spa_namespace_lock);
5586 * Pool export/destroy
5588 * The act of destroying or exporting a pool is very simple. We make sure there
5589 * is no more pending I/O and any references to the pool are gone. Then, we
5590 * update the pool state and sync all the labels to disk, removing the
5591 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
5592 * we don't sync the labels or remove the configuration cache.
5595 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
5596 boolean_t force, boolean_t hardforce)
5603 if (!(spa_mode_global & FWRITE))
5604 return (SET_ERROR(EROFS));
5606 mutex_enter(&spa_namespace_lock);
5607 if ((spa = spa_lookup(pool)) == NULL) {
5608 mutex_exit(&spa_namespace_lock);
5609 return (SET_ERROR(ENOENT));
5613 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5614 * reacquire the namespace lock, and see if we can export.
5616 spa_open_ref(spa, FTAG);
5617 mutex_exit(&spa_namespace_lock);
5618 spa_async_suspend(spa);
5619 if (spa->spa_zvol_taskq) {
5620 zvol_remove_minors(spa, spa_name(spa), B_TRUE);
5621 taskq_wait(spa->spa_zvol_taskq);
5623 mutex_enter(&spa_namespace_lock);
5624 spa_close(spa, FTAG);
5626 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
5629 * The pool will be in core if it's openable, in which case we can
5630 * modify its state. Objsets may be open only because they're dirty,
5631 * so we have to force it to sync before checking spa_refcnt.
5633 if (spa->spa_sync_on) {
5634 txg_wait_synced(spa->spa_dsl_pool, 0);
5635 spa_evicting_os_wait(spa);
5639 * A pool cannot be exported or destroyed if there are active
5640 * references. If we are resetting a pool, allow references by
5641 * fault injection handlers.
5643 if (!spa_refcount_zero(spa) ||
5644 (spa->spa_inject_ref != 0 &&
5645 new_state != POOL_STATE_UNINITIALIZED)) {
5646 spa_async_resume(spa);
5647 mutex_exit(&spa_namespace_lock);
5648 return (SET_ERROR(EBUSY));
5651 if (spa->spa_sync_on) {
5653 * A pool cannot be exported if it has an active shared spare.
5654 * This is to prevent other pools stealing the active spare
5655 * from an exported pool. At user's own will, such pool can
5656 * be forcedly exported.
5658 if (!force && new_state == POOL_STATE_EXPORTED &&
5659 spa_has_active_shared_spare(spa)) {
5660 spa_async_resume(spa);
5661 mutex_exit(&spa_namespace_lock);
5662 return (SET_ERROR(EXDEV));
5666 * We want this to be reflected on every label,
5667 * so mark them all dirty. spa_unload() will do the
5668 * final sync that pushes these changes out.
5670 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
5671 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5672 spa->spa_state = new_state;
5673 spa->spa_final_txg = spa_last_synced_txg(spa) +
5675 vdev_config_dirty(spa->spa_root_vdev);
5676 spa_config_exit(spa, SCL_ALL, FTAG);
5681 if (new_state == POOL_STATE_DESTROYED)
5682 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
5683 else if (new_state == POOL_STATE_EXPORTED)
5684 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_EXPORT);
5686 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
5688 spa_deactivate(spa);
5691 if (oldconfig && spa->spa_config)
5692 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
5694 if (new_state != POOL_STATE_UNINITIALIZED) {
5696 spa_write_cachefile(spa, B_TRUE, B_TRUE);
5699 mutex_exit(&spa_namespace_lock);
5705 * Destroy a storage pool.
5708 spa_destroy(char *pool)
5710 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
5715 * Export a storage pool.
5718 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
5719 boolean_t hardforce)
5721 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
5726 * Similar to spa_export(), this unloads the spa_t without actually removing it
5727 * from the namespace in any way.
5730 spa_reset(char *pool)
5732 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
5737 * ==========================================================================
5738 * Device manipulation
5739 * ==========================================================================
5743 * Add a device to a storage pool.
5746 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
5750 vdev_t *rvd = spa->spa_root_vdev;
5752 nvlist_t **spares, **l2cache;
5753 uint_t nspares, nl2cache;
5755 ASSERT(spa_writeable(spa));
5757 txg = spa_vdev_enter(spa);
5759 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
5760 VDEV_ALLOC_ADD)) != 0)
5761 return (spa_vdev_exit(spa, NULL, txg, error));
5763 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
5765 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
5769 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
5773 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
5774 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5776 if (vd->vdev_children != 0 &&
5777 (error = vdev_create(vd, txg, B_FALSE)) != 0)
5778 return (spa_vdev_exit(spa, vd, txg, error));
5781 * We must validate the spares and l2cache devices after checking the
5782 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
5784 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
5785 return (spa_vdev_exit(spa, vd, txg, error));
5788 * If we are in the middle of a device removal, we can only add
5789 * devices which match the existing devices in the pool.
5790 * If we are in the middle of a removal, or have some indirect
5791 * vdevs, we can not add raidz toplevels.
5793 if (spa->spa_vdev_removal != NULL ||
5794 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
5795 for (int c = 0; c < vd->vdev_children; c++) {
5796 tvd = vd->vdev_child[c];
5797 if (spa->spa_vdev_removal != NULL &&
5798 tvd->vdev_ashift != spa->spa_max_ashift) {
5799 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5801 /* Fail if top level vdev is raidz */
5802 if (tvd->vdev_ops == &vdev_raidz_ops) {
5803 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5806 * Need the top level mirror to be
5807 * a mirror of leaf vdevs only
5809 if (tvd->vdev_ops == &vdev_mirror_ops) {
5810 for (uint64_t cid = 0;
5811 cid < tvd->vdev_children; cid++) {
5812 vdev_t *cvd = tvd->vdev_child[cid];
5813 if (!cvd->vdev_ops->vdev_op_leaf) {
5814 return (spa_vdev_exit(spa, vd,
5822 for (int c = 0; c < vd->vdev_children; c++) {
5825 * Set the vdev id to the first hole, if one exists.
5827 for (id = 0; id < rvd->vdev_children; id++) {
5828 if (rvd->vdev_child[id]->vdev_ishole) {
5829 vdev_free(rvd->vdev_child[id]);
5833 tvd = vd->vdev_child[c];
5834 vdev_remove_child(vd, tvd);
5836 vdev_add_child(rvd, tvd);
5837 vdev_config_dirty(tvd);
5841 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
5842 ZPOOL_CONFIG_SPARES);
5843 spa_load_spares(spa);
5844 spa->spa_spares.sav_sync = B_TRUE;
5847 if (nl2cache != 0) {
5848 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
5849 ZPOOL_CONFIG_L2CACHE);
5850 spa_load_l2cache(spa);
5851 spa->spa_l2cache.sav_sync = B_TRUE;
5855 * We have to be careful when adding new vdevs to an existing pool.
5856 * If other threads start allocating from these vdevs before we
5857 * sync the config cache, and we lose power, then upon reboot we may
5858 * fail to open the pool because there are DVAs that the config cache
5859 * can't translate. Therefore, we first add the vdevs without
5860 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
5861 * and then let spa_config_update() initialize the new metaslabs.
5863 * spa_load() checks for added-but-not-initialized vdevs, so that
5864 * if we lose power at any point in this sequence, the remaining
5865 * steps will be completed the next time we load the pool.
5867 (void) spa_vdev_exit(spa, vd, txg, 0);
5869 mutex_enter(&spa_namespace_lock);
5870 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5871 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
5872 mutex_exit(&spa_namespace_lock);
5878 * Attach a device to a mirror. The arguments are the path to any device
5879 * in the mirror, and the nvroot for the new device. If the path specifies
5880 * a device that is not mirrored, we automatically insert the mirror vdev.
5882 * If 'replacing' is specified, the new device is intended to replace the
5883 * existing device; in this case the two devices are made into their own
5884 * mirror using the 'replacing' vdev, which is functionally identical to
5885 * the mirror vdev (it actually reuses all the same ops) but has a few
5886 * extra rules: you can't attach to it after it's been created, and upon
5887 * completion of resilvering, the first disk (the one being replaced)
5888 * is automatically detached.
5891 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
5893 uint64_t txg, dtl_max_txg;
5894 ASSERTV(vdev_t *rvd = spa->spa_root_vdev);
5895 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
5897 char *oldvdpath, *newvdpath;
5901 ASSERT(spa_writeable(spa));
5903 txg = spa_vdev_enter(spa);
5905 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
5907 ASSERT(MUTEX_HELD(&spa_namespace_lock));
5908 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
5909 error = (spa_has_checkpoint(spa)) ?
5910 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
5911 return (spa_vdev_exit(spa, NULL, txg, error));
5914 if (spa->spa_vdev_removal != NULL)
5915 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5918 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5920 if (!oldvd->vdev_ops->vdev_op_leaf)
5921 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5923 pvd = oldvd->vdev_parent;
5925 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
5926 VDEV_ALLOC_ATTACH)) != 0)
5927 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5929 if (newrootvd->vdev_children != 1)
5930 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
5932 newvd = newrootvd->vdev_child[0];
5934 if (!newvd->vdev_ops->vdev_op_leaf)
5935 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
5937 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
5938 return (spa_vdev_exit(spa, newrootvd, txg, error));
5941 * Spares can't replace logs
5943 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
5944 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5948 * For attach, the only allowable parent is a mirror or the root
5951 if (pvd->vdev_ops != &vdev_mirror_ops &&
5952 pvd->vdev_ops != &vdev_root_ops)
5953 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5955 pvops = &vdev_mirror_ops;
5958 * Active hot spares can only be replaced by inactive hot
5961 if (pvd->vdev_ops == &vdev_spare_ops &&
5962 oldvd->vdev_isspare &&
5963 !spa_has_spare(spa, newvd->vdev_guid))
5964 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5967 * If the source is a hot spare, and the parent isn't already a
5968 * spare, then we want to create a new hot spare. Otherwise, we
5969 * want to create a replacing vdev. The user is not allowed to
5970 * attach to a spared vdev child unless the 'isspare' state is
5971 * the same (spare replaces spare, non-spare replaces
5974 if (pvd->vdev_ops == &vdev_replacing_ops &&
5975 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
5976 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5977 } else if (pvd->vdev_ops == &vdev_spare_ops &&
5978 newvd->vdev_isspare != oldvd->vdev_isspare) {
5979 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5982 if (newvd->vdev_isspare)
5983 pvops = &vdev_spare_ops;
5985 pvops = &vdev_replacing_ops;
5989 * Make sure the new device is big enough.
5991 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
5992 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
5995 * The new device cannot have a higher alignment requirement
5996 * than the top-level vdev.
5998 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
5999 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6002 * If this is an in-place replacement, update oldvd's path and devid
6003 * to make it distinguishable from newvd, and unopenable from now on.
6005 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6006 spa_strfree(oldvd->vdev_path);
6007 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6009 (void) sprintf(oldvd->vdev_path, "%s/%s",
6010 newvd->vdev_path, "old");
6011 if (oldvd->vdev_devid != NULL) {
6012 spa_strfree(oldvd->vdev_devid);
6013 oldvd->vdev_devid = NULL;
6017 /* mark the device being resilvered */
6018 newvd->vdev_resilver_txg = txg;
6021 * If the parent is not a mirror, or if we're replacing, insert the new
6022 * mirror/replacing/spare vdev above oldvd.
6024 if (pvd->vdev_ops != pvops)
6025 pvd = vdev_add_parent(oldvd, pvops);
6027 ASSERT(pvd->vdev_top->vdev_parent == rvd);
6028 ASSERT(pvd->vdev_ops == pvops);
6029 ASSERT(oldvd->vdev_parent == pvd);
6032 * Extract the new device from its root and add it to pvd.
6034 vdev_remove_child(newrootvd, newvd);
6035 newvd->vdev_id = pvd->vdev_children;
6036 newvd->vdev_crtxg = oldvd->vdev_crtxg;
6037 vdev_add_child(pvd, newvd);
6040 * Reevaluate the parent vdev state.
6042 vdev_propagate_state(pvd);
6044 tvd = newvd->vdev_top;
6045 ASSERT(pvd->vdev_top == tvd);
6046 ASSERT(tvd->vdev_parent == rvd);
6048 vdev_config_dirty(tvd);
6051 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6052 * for any dmu_sync-ed blocks. It will propagate upward when
6053 * spa_vdev_exit() calls vdev_dtl_reassess().
6055 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6057 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6058 dtl_max_txg - TXG_INITIAL);
6060 if (newvd->vdev_isspare) {
6061 spa_spare_activate(newvd);
6062 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6065 oldvdpath = spa_strdup(oldvd->vdev_path);
6066 newvdpath = spa_strdup(newvd->vdev_path);
6067 newvd_isspare = newvd->vdev_isspare;
6070 * Mark newvd's DTL dirty in this txg.
6072 vdev_dirty(tvd, VDD_DTL, newvd, txg);
6075 * Schedule the resilver to restart in the future. We do this to
6076 * ensure that dmu_sync-ed blocks have been stitched into the
6077 * respective datasets.
6079 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
6081 if (spa->spa_bootfs)
6082 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6084 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6089 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6091 spa_history_log_internal(spa, "vdev attach", NULL,
6092 "%s vdev=%s %s vdev=%s",
6093 replacing && newvd_isspare ? "spare in" :
6094 replacing ? "replace" : "attach", newvdpath,
6095 replacing ? "for" : "to", oldvdpath);
6097 spa_strfree(oldvdpath);
6098 spa_strfree(newvdpath);
6104 * Detach a device from a mirror or replacing vdev.
6106 * If 'replace_done' is specified, only detach if the parent
6107 * is a replacing vdev.
6110 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6114 ASSERTV(vdev_t *rvd = spa->spa_root_vdev);
6115 vdev_t *vd, *pvd, *cvd, *tvd;
6116 boolean_t unspare = B_FALSE;
6117 uint64_t unspare_guid = 0;
6120 ASSERT(spa_writeable(spa));
6122 txg = spa_vdev_enter(spa);
6124 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6127 * Besides being called directly from the userland through the
6128 * ioctl interface, spa_vdev_detach() can be potentially called
6129 * at the end of spa_vdev_resilver_done().
6131 * In the regular case, when we have a checkpoint this shouldn't
6132 * happen as we never empty the DTLs of a vdev during the scrub
6133 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6134 * should never get here when we have a checkpoint.
6136 * That said, even in a case when we checkpoint the pool exactly
6137 * as spa_vdev_resilver_done() calls this function everything
6138 * should be fine as the resilver will return right away.
6140 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6141 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6142 error = (spa_has_checkpoint(spa)) ?
6143 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6144 return (spa_vdev_exit(spa, NULL, txg, error));
6148 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6150 if (!vd->vdev_ops->vdev_op_leaf)
6151 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6153 pvd = vd->vdev_parent;
6156 * If the parent/child relationship is not as expected, don't do it.
6157 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6158 * vdev that's replacing B with C. The user's intent in replacing
6159 * is to go from M(A,B) to M(A,C). If the user decides to cancel
6160 * the replace by detaching C, the expected behavior is to end up
6161 * M(A,B). But suppose that right after deciding to detach C,
6162 * the replacement of B completes. We would have M(A,C), and then
6163 * ask to detach C, which would leave us with just A -- not what
6164 * the user wanted. To prevent this, we make sure that the
6165 * parent/child relationship hasn't changed -- in this example,
6166 * that C's parent is still the replacing vdev R.
6168 if (pvd->vdev_guid != pguid && pguid != 0)
6169 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6172 * Only 'replacing' or 'spare' vdevs can be replaced.
6174 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6175 pvd->vdev_ops != &vdev_spare_ops)
6176 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6178 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6179 spa_version(spa) >= SPA_VERSION_SPARES);
6182 * Only mirror, replacing, and spare vdevs support detach.
6184 if (pvd->vdev_ops != &vdev_replacing_ops &&
6185 pvd->vdev_ops != &vdev_mirror_ops &&
6186 pvd->vdev_ops != &vdev_spare_ops)
6187 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6190 * If this device has the only valid copy of some data,
6191 * we cannot safely detach it.
6193 if (vdev_dtl_required(vd))
6194 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6196 ASSERT(pvd->vdev_children >= 2);
6199 * If we are detaching the second disk from a replacing vdev, then
6200 * check to see if we changed the original vdev's path to have "/old"
6201 * at the end in spa_vdev_attach(). If so, undo that change now.
6203 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
6204 vd->vdev_path != NULL) {
6205 size_t len = strlen(vd->vdev_path);
6207 for (int c = 0; c < pvd->vdev_children; c++) {
6208 cvd = pvd->vdev_child[c];
6210 if (cvd == vd || cvd->vdev_path == NULL)
6213 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
6214 strcmp(cvd->vdev_path + len, "/old") == 0) {
6215 spa_strfree(cvd->vdev_path);
6216 cvd->vdev_path = spa_strdup(vd->vdev_path);
6223 * If we are detaching the original disk from a spare, then it implies
6224 * that the spare should become a real disk, and be removed from the
6225 * active spare list for the pool.
6227 if (pvd->vdev_ops == &vdev_spare_ops &&
6229 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
6233 * Erase the disk labels so the disk can be used for other things.
6234 * This must be done after all other error cases are handled,
6235 * but before we disembowel vd (so we can still do I/O to it).
6236 * But if we can't do it, don't treat the error as fatal --
6237 * it may be that the unwritability of the disk is the reason
6238 * it's being detached!
6240 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
6243 * Remove vd from its parent and compact the parent's children.
6245 vdev_remove_child(pvd, vd);
6246 vdev_compact_children(pvd);
6249 * Remember one of the remaining children so we can get tvd below.
6251 cvd = pvd->vdev_child[pvd->vdev_children - 1];
6254 * If we need to remove the remaining child from the list of hot spares,
6255 * do it now, marking the vdev as no longer a spare in the process.
6256 * We must do this before vdev_remove_parent(), because that can
6257 * change the GUID if it creates a new toplevel GUID. For a similar
6258 * reason, we must remove the spare now, in the same txg as the detach;
6259 * otherwise someone could attach a new sibling, change the GUID, and
6260 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
6263 ASSERT(cvd->vdev_isspare);
6264 spa_spare_remove(cvd);
6265 unspare_guid = cvd->vdev_guid;
6266 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
6267 cvd->vdev_unspare = B_TRUE;
6271 * If the parent mirror/replacing vdev only has one child,
6272 * the parent is no longer needed. Remove it from the tree.
6274 if (pvd->vdev_children == 1) {
6275 if (pvd->vdev_ops == &vdev_spare_ops)
6276 cvd->vdev_unspare = B_FALSE;
6277 vdev_remove_parent(cvd);
6282 * We don't set tvd until now because the parent we just removed
6283 * may have been the previous top-level vdev.
6285 tvd = cvd->vdev_top;
6286 ASSERT(tvd->vdev_parent == rvd);
6289 * Reevaluate the parent vdev state.
6291 vdev_propagate_state(cvd);
6294 * If the 'autoexpand' property is set on the pool then automatically
6295 * try to expand the size of the pool. For example if the device we
6296 * just detached was smaller than the others, it may be possible to
6297 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
6298 * first so that we can obtain the updated sizes of the leaf vdevs.
6300 if (spa->spa_autoexpand) {
6302 vdev_expand(tvd, txg);
6305 vdev_config_dirty(tvd);
6308 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
6309 * vd->vdev_detached is set and free vd's DTL object in syncing context.
6310 * But first make sure we're not on any *other* txg's DTL list, to
6311 * prevent vd from being accessed after it's freed.
6313 vdpath = spa_strdup(vd->vdev_path ? vd->vdev_path : "none");
6314 for (int t = 0; t < TXG_SIZE; t++)
6315 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
6316 vd->vdev_detached = B_TRUE;
6317 vdev_dirty(tvd, VDD_DTL, vd, txg);
6319 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
6321 /* hang on to the spa before we release the lock */
6322 spa_open_ref(spa, FTAG);
6324 error = spa_vdev_exit(spa, vd, txg, 0);
6326 spa_history_log_internal(spa, "detach", NULL,
6328 spa_strfree(vdpath);
6331 * If this was the removal of the original device in a hot spare vdev,
6332 * then we want to go through and remove the device from the hot spare
6333 * list of every other pool.
6336 spa_t *altspa = NULL;
6338 mutex_enter(&spa_namespace_lock);
6339 while ((altspa = spa_next(altspa)) != NULL) {
6340 if (altspa->spa_state != POOL_STATE_ACTIVE ||
6344 spa_open_ref(altspa, FTAG);
6345 mutex_exit(&spa_namespace_lock);
6346 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
6347 mutex_enter(&spa_namespace_lock);
6348 spa_close(altspa, FTAG);
6350 mutex_exit(&spa_namespace_lock);
6352 /* search the rest of the vdevs for spares to remove */
6353 spa_vdev_resilver_done(spa);
6356 /* all done with the spa; OK to release */
6357 mutex_enter(&spa_namespace_lock);
6358 spa_close(spa, FTAG);
6359 mutex_exit(&spa_namespace_lock);
6365 * Split a set of devices from their mirrors, and create a new pool from them.
6368 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6369 nvlist_t *props, boolean_t exp)
6372 uint64_t txg, *glist;
6374 uint_t c, children, lastlog;
6375 nvlist_t **child, *nvl, *tmp;
6377 char *altroot = NULL;
6378 vdev_t *rvd, **vml = NULL; /* vdev modify list */
6379 boolean_t activate_slog;
6381 ASSERT(spa_writeable(spa));
6383 txg = spa_vdev_enter(spa);
6385 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6386 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6387 error = (spa_has_checkpoint(spa)) ?
6388 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6389 return (spa_vdev_exit(spa, NULL, txg, error));
6392 /* clear the log and flush everything up to now */
6393 activate_slog = spa_passivate_log(spa);
6394 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6395 error = spa_reset_logs(spa);
6396 txg = spa_vdev_config_enter(spa);
6399 spa_activate_log(spa);
6402 return (spa_vdev_exit(spa, NULL, txg, error));
6404 /* check new spa name before going any further */
6405 if (spa_lookup(newname) != NULL)
6406 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
6409 * scan through all the children to ensure they're all mirrors
6411 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
6412 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
6414 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6416 /* first, check to ensure we've got the right child count */
6417 rvd = spa->spa_root_vdev;
6419 for (c = 0; c < rvd->vdev_children; c++) {
6420 vdev_t *vd = rvd->vdev_child[c];
6422 /* don't count the holes & logs as children */
6423 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
6431 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
6432 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6434 /* next, ensure no spare or cache devices are part of the split */
6435 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
6436 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
6437 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6439 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
6440 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
6442 /* then, loop over each vdev and validate it */
6443 for (c = 0; c < children; c++) {
6444 uint64_t is_hole = 0;
6446 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
6450 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
6451 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
6454 error = SET_ERROR(EINVAL);
6459 /* which disk is going to be split? */
6460 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
6462 error = SET_ERROR(EINVAL);
6466 /* look it up in the spa */
6467 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
6468 if (vml[c] == NULL) {
6469 error = SET_ERROR(ENODEV);
6473 /* make sure there's nothing stopping the split */
6474 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
6475 vml[c]->vdev_islog ||
6476 !vdev_is_concrete(vml[c]) ||
6477 vml[c]->vdev_isspare ||
6478 vml[c]->vdev_isl2cache ||
6479 !vdev_writeable(vml[c]) ||
6480 vml[c]->vdev_children != 0 ||
6481 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
6482 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
6483 error = SET_ERROR(EINVAL);
6487 if (vdev_dtl_required(vml[c]) ||
6488 vdev_resilver_needed(vml[c], NULL, NULL)) {
6489 error = SET_ERROR(EBUSY);
6493 /* we need certain info from the top level */
6494 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
6495 vml[c]->vdev_top->vdev_ms_array) == 0);
6496 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
6497 vml[c]->vdev_top->vdev_ms_shift) == 0);
6498 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
6499 vml[c]->vdev_top->vdev_asize) == 0);
6500 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
6501 vml[c]->vdev_top->vdev_ashift) == 0);
6503 /* transfer per-vdev ZAPs */
6504 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
6505 VERIFY0(nvlist_add_uint64(child[c],
6506 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
6508 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
6509 VERIFY0(nvlist_add_uint64(child[c],
6510 ZPOOL_CONFIG_VDEV_TOP_ZAP,
6511 vml[c]->vdev_parent->vdev_top_zap));
6515 kmem_free(vml, children * sizeof (vdev_t *));
6516 kmem_free(glist, children * sizeof (uint64_t));
6517 return (spa_vdev_exit(spa, NULL, txg, error));
6520 /* stop writers from using the disks */
6521 for (c = 0; c < children; c++) {
6523 vml[c]->vdev_offline = B_TRUE;
6525 vdev_reopen(spa->spa_root_vdev);
6528 * Temporarily record the splitting vdevs in the spa config. This
6529 * will disappear once the config is regenerated.
6531 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6532 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
6533 glist, children) == 0);
6534 kmem_free(glist, children * sizeof (uint64_t));
6536 mutex_enter(&spa->spa_props_lock);
6537 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
6539 mutex_exit(&spa->spa_props_lock);
6540 spa->spa_config_splitting = nvl;
6541 vdev_config_dirty(spa->spa_root_vdev);
6543 /* configure and create the new pool */
6544 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
6545 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6546 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
6547 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6548 spa_version(spa)) == 0);
6549 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
6550 spa->spa_config_txg) == 0);
6551 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
6552 spa_generate_guid(NULL)) == 0);
6553 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
6554 (void) nvlist_lookup_string(props,
6555 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
6557 /* add the new pool to the namespace */
6558 newspa = spa_add(newname, config, altroot);
6559 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
6560 newspa->spa_config_txg = spa->spa_config_txg;
6561 spa_set_log_state(newspa, SPA_LOG_CLEAR);
6563 /* release the spa config lock, retaining the namespace lock */
6564 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6566 if (zio_injection_enabled)
6567 zio_handle_panic_injection(spa, FTAG, 1);
6569 spa_activate(newspa, spa_mode_global);
6570 spa_async_suspend(newspa);
6572 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
6574 /* create the new pool from the disks of the original pool */
6575 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
6579 /* if that worked, generate a real config for the new pool */
6580 if (newspa->spa_root_vdev != NULL) {
6581 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
6582 NV_UNIQUE_NAME, KM_SLEEP) == 0);
6583 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
6584 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
6585 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
6590 if (props != NULL) {
6591 spa_configfile_set(newspa, props, B_FALSE);
6592 error = spa_prop_set(newspa, props);
6597 /* flush everything */
6598 txg = spa_vdev_config_enter(newspa);
6599 vdev_config_dirty(newspa->spa_root_vdev);
6600 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
6602 if (zio_injection_enabled)
6603 zio_handle_panic_injection(spa, FTAG, 2);
6605 spa_async_resume(newspa);
6607 /* finally, update the original pool's config */
6608 txg = spa_vdev_config_enter(spa);
6609 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
6610 error = dmu_tx_assign(tx, TXG_WAIT);
6613 for (c = 0; c < children; c++) {
6614 if (vml[c] != NULL) {
6617 spa_history_log_internal(spa, "detach", tx,
6618 "vdev=%s", vml[c]->vdev_path);
6623 spa->spa_avz_action = AVZ_ACTION_REBUILD;
6624 vdev_config_dirty(spa->spa_root_vdev);
6625 spa->spa_config_splitting = NULL;
6629 (void) spa_vdev_exit(spa, NULL, txg, 0);
6631 if (zio_injection_enabled)
6632 zio_handle_panic_injection(spa, FTAG, 3);
6634 /* split is complete; log a history record */
6635 spa_history_log_internal(newspa, "split", NULL,
6636 "from pool %s", spa_name(spa));
6638 kmem_free(vml, children * sizeof (vdev_t *));
6640 /* if we're not going to mount the filesystems in userland, export */
6642 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
6649 spa_deactivate(newspa);
6652 txg = spa_vdev_config_enter(spa);
6654 /* re-online all offlined disks */
6655 for (c = 0; c < children; c++) {
6657 vml[c]->vdev_offline = B_FALSE;
6659 vdev_reopen(spa->spa_root_vdev);
6661 nvlist_free(spa->spa_config_splitting);
6662 spa->spa_config_splitting = NULL;
6663 (void) spa_vdev_exit(spa, NULL, txg, error);
6665 kmem_free(vml, children * sizeof (vdev_t *));
6670 * Find any device that's done replacing, or a vdev marked 'unspare' that's
6671 * currently spared, so we can detach it.
6674 spa_vdev_resilver_done_hunt(vdev_t *vd)
6676 vdev_t *newvd, *oldvd;
6678 for (int c = 0; c < vd->vdev_children; c++) {
6679 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
6685 * Check for a completed replacement. We always consider the first
6686 * vdev in the list to be the oldest vdev, and the last one to be
6687 * the newest (see spa_vdev_attach() for how that works). In
6688 * the case where the newest vdev is faulted, we will not automatically
6689 * remove it after a resilver completes. This is OK as it will require
6690 * user intervention to determine which disk the admin wishes to keep.
6692 if (vd->vdev_ops == &vdev_replacing_ops) {
6693 ASSERT(vd->vdev_children > 1);
6695 newvd = vd->vdev_child[vd->vdev_children - 1];
6696 oldvd = vd->vdev_child[0];
6698 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
6699 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6700 !vdev_dtl_required(oldvd))
6705 * Check for a completed resilver with the 'unspare' flag set.
6707 if (vd->vdev_ops == &vdev_spare_ops) {
6708 vdev_t *first = vd->vdev_child[0];
6709 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
6711 if (last->vdev_unspare) {
6714 } else if (first->vdev_unspare) {
6721 if (oldvd != NULL &&
6722 vdev_dtl_empty(newvd, DTL_MISSING) &&
6723 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6724 !vdev_dtl_required(oldvd))
6728 * If there are more than two spares attached to a disk,
6729 * and those spares are not required, then we want to
6730 * attempt to free them up now so that they can be used
6731 * by other pools. Once we're back down to a single
6732 * disk+spare, we stop removing them.
6734 if (vd->vdev_children > 2) {
6735 newvd = vd->vdev_child[1];
6737 if (newvd->vdev_isspare && last->vdev_isspare &&
6738 vdev_dtl_empty(last, DTL_MISSING) &&
6739 vdev_dtl_empty(last, DTL_OUTAGE) &&
6740 !vdev_dtl_required(newvd))
6749 spa_vdev_resilver_done(spa_t *spa)
6751 vdev_t *vd, *pvd, *ppvd;
6752 uint64_t guid, sguid, pguid, ppguid;
6754 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6756 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
6757 pvd = vd->vdev_parent;
6758 ppvd = pvd->vdev_parent;
6759 guid = vd->vdev_guid;
6760 pguid = pvd->vdev_guid;
6761 ppguid = ppvd->vdev_guid;
6764 * If we have just finished replacing a hot spared device, then
6765 * we need to detach the parent's first child (the original hot
6768 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
6769 ppvd->vdev_children == 2) {
6770 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
6771 sguid = ppvd->vdev_child[1]->vdev_guid;
6773 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
6775 spa_config_exit(spa, SCL_ALL, FTAG);
6776 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
6778 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
6780 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6783 spa_config_exit(spa, SCL_ALL, FTAG);
6787 * Update the stored path or FRU for this vdev.
6790 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
6794 boolean_t sync = B_FALSE;
6796 ASSERT(spa_writeable(spa));
6798 spa_vdev_state_enter(spa, SCL_ALL);
6800 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
6801 return (spa_vdev_state_exit(spa, NULL, ENOENT));
6803 if (!vd->vdev_ops->vdev_op_leaf)
6804 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
6807 if (strcmp(value, vd->vdev_path) != 0) {
6808 spa_strfree(vd->vdev_path);
6809 vd->vdev_path = spa_strdup(value);
6813 if (vd->vdev_fru == NULL) {
6814 vd->vdev_fru = spa_strdup(value);
6816 } else if (strcmp(value, vd->vdev_fru) != 0) {
6817 spa_strfree(vd->vdev_fru);
6818 vd->vdev_fru = spa_strdup(value);
6823 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
6827 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
6829 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
6833 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
6835 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
6839 * ==========================================================================
6841 * ==========================================================================
6844 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
6846 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6848 if (dsl_scan_resilvering(spa->spa_dsl_pool))
6849 return (SET_ERROR(EBUSY));
6851 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
6855 spa_scan_stop(spa_t *spa)
6857 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6858 if (dsl_scan_resilvering(spa->spa_dsl_pool))
6859 return (SET_ERROR(EBUSY));
6860 return (dsl_scan_cancel(spa->spa_dsl_pool));
6864 spa_scan(spa_t *spa, pool_scan_func_t func)
6866 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6868 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
6869 return (SET_ERROR(ENOTSUP));
6872 * If a resilver was requested, but there is no DTL on a
6873 * writeable leaf device, we have nothing to do.
6875 if (func == POOL_SCAN_RESILVER &&
6876 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
6877 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
6881 return (dsl_scan(spa->spa_dsl_pool, func));
6885 * ==========================================================================
6886 * SPA async task processing
6887 * ==========================================================================
6891 spa_async_remove(spa_t *spa, vdev_t *vd)
6893 if (vd->vdev_remove_wanted) {
6894 vd->vdev_remove_wanted = B_FALSE;
6895 vd->vdev_delayed_close = B_FALSE;
6896 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
6899 * We want to clear the stats, but we don't want to do a full
6900 * vdev_clear() as that will cause us to throw away
6901 * degraded/faulted state as well as attempt to reopen the
6902 * device, all of which is a waste.
6904 vd->vdev_stat.vs_read_errors = 0;
6905 vd->vdev_stat.vs_write_errors = 0;
6906 vd->vdev_stat.vs_checksum_errors = 0;
6908 vdev_state_dirty(vd->vdev_top);
6911 for (int c = 0; c < vd->vdev_children; c++)
6912 spa_async_remove(spa, vd->vdev_child[c]);
6916 spa_async_probe(spa_t *spa, vdev_t *vd)
6918 if (vd->vdev_probe_wanted) {
6919 vd->vdev_probe_wanted = B_FALSE;
6920 vdev_reopen(vd); /* vdev_open() does the actual probe */
6923 for (int c = 0; c < vd->vdev_children; c++)
6924 spa_async_probe(spa, vd->vdev_child[c]);
6928 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
6930 if (!spa->spa_autoexpand)
6933 for (int c = 0; c < vd->vdev_children; c++) {
6934 vdev_t *cvd = vd->vdev_child[c];
6935 spa_async_autoexpand(spa, cvd);
6938 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
6941 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_AUTOEXPAND);
6945 spa_async_thread(void *arg)
6947 spa_t *spa = (spa_t *)arg;
6950 ASSERT(spa->spa_sync_on);
6952 mutex_enter(&spa->spa_async_lock);
6953 tasks = spa->spa_async_tasks;
6954 spa->spa_async_tasks = 0;
6955 mutex_exit(&spa->spa_async_lock);
6958 * See if the config needs to be updated.
6960 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
6961 uint64_t old_space, new_space;
6963 mutex_enter(&spa_namespace_lock);
6964 old_space = metaslab_class_get_space(spa_normal_class(spa));
6965 old_space += metaslab_class_get_space(spa_special_class(spa));
6966 old_space += metaslab_class_get_space(spa_dedup_class(spa));
6968 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
6970 new_space = metaslab_class_get_space(spa_normal_class(spa));
6971 new_space += metaslab_class_get_space(spa_special_class(spa));
6972 new_space += metaslab_class_get_space(spa_dedup_class(spa));
6973 mutex_exit(&spa_namespace_lock);
6976 * If the pool grew as a result of the config update,
6977 * then log an internal history event.
6979 if (new_space != old_space) {
6980 spa_history_log_internal(spa, "vdev online", NULL,
6981 "pool '%s' size: %llu(+%llu)",
6982 spa_name(spa), new_space, new_space - old_space);
6987 * See if any devices need to be marked REMOVED.
6989 if (tasks & SPA_ASYNC_REMOVE) {
6990 spa_vdev_state_enter(spa, SCL_NONE);
6991 spa_async_remove(spa, spa->spa_root_vdev);
6992 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
6993 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
6994 for (int i = 0; i < spa->spa_spares.sav_count; i++)
6995 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
6996 (void) spa_vdev_state_exit(spa, NULL, 0);
6999 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
7000 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7001 spa_async_autoexpand(spa, spa->spa_root_vdev);
7002 spa_config_exit(spa, SCL_CONFIG, FTAG);
7006 * See if any devices need to be probed.
7008 if (tasks & SPA_ASYNC_PROBE) {
7009 spa_vdev_state_enter(spa, SCL_NONE);
7010 spa_async_probe(spa, spa->spa_root_vdev);
7011 (void) spa_vdev_state_exit(spa, NULL, 0);
7015 * If any devices are done replacing, detach them.
7017 if (tasks & SPA_ASYNC_RESILVER_DONE)
7018 spa_vdev_resilver_done(spa);
7021 * Kick off a resilver.
7023 if (tasks & SPA_ASYNC_RESILVER)
7024 dsl_resilver_restart(spa->spa_dsl_pool, 0);
7027 * Let the world know that we're done.
7029 mutex_enter(&spa->spa_async_lock);
7030 spa->spa_async_thread = NULL;
7031 cv_broadcast(&spa->spa_async_cv);
7032 mutex_exit(&spa->spa_async_lock);
7037 spa_async_suspend(spa_t *spa)
7039 mutex_enter(&spa->spa_async_lock);
7040 spa->spa_async_suspended++;
7041 while (spa->spa_async_thread != NULL)
7042 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
7043 mutex_exit(&spa->spa_async_lock);
7045 spa_vdev_remove_suspend(spa);
7047 zthr_t *condense_thread = spa->spa_condense_zthr;
7048 if (condense_thread != NULL && zthr_isrunning(condense_thread))
7049 VERIFY0(zthr_cancel(condense_thread));
7051 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7052 if (discard_thread != NULL && zthr_isrunning(discard_thread))
7053 VERIFY0(zthr_cancel(discard_thread));
7057 spa_async_resume(spa_t *spa)
7059 mutex_enter(&spa->spa_async_lock);
7060 ASSERT(spa->spa_async_suspended != 0);
7061 spa->spa_async_suspended--;
7062 mutex_exit(&spa->spa_async_lock);
7063 spa_restart_removal(spa);
7065 zthr_t *condense_thread = spa->spa_condense_zthr;
7066 if (condense_thread != NULL && !zthr_isrunning(condense_thread))
7067 zthr_resume(condense_thread);
7069 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7070 if (discard_thread != NULL && !zthr_isrunning(discard_thread))
7071 zthr_resume(discard_thread);
7075 spa_async_tasks_pending(spa_t *spa)
7077 uint_t non_config_tasks;
7079 boolean_t config_task_suspended;
7081 non_config_tasks = spa->spa_async_tasks & ~SPA_ASYNC_CONFIG_UPDATE;
7082 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
7083 if (spa->spa_ccw_fail_time == 0) {
7084 config_task_suspended = B_FALSE;
7086 config_task_suspended =
7087 (gethrtime() - spa->spa_ccw_fail_time) <
7088 ((hrtime_t)zfs_ccw_retry_interval * NANOSEC);
7091 return (non_config_tasks || (config_task && !config_task_suspended));
7095 spa_async_dispatch(spa_t *spa)
7097 mutex_enter(&spa->spa_async_lock);
7098 if (spa_async_tasks_pending(spa) &&
7099 !spa->spa_async_suspended &&
7100 spa->spa_async_thread == NULL &&
7102 spa->spa_async_thread = thread_create(NULL, 0,
7103 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
7104 mutex_exit(&spa->spa_async_lock);
7108 spa_async_request(spa_t *spa, int task)
7110 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
7111 mutex_enter(&spa->spa_async_lock);
7112 spa->spa_async_tasks |= task;
7113 mutex_exit(&spa->spa_async_lock);
7117 * ==========================================================================
7118 * SPA syncing routines
7119 * ==========================================================================
7123 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7126 bpobj_enqueue(bpo, bp, tx);
7131 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7135 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
7141 * Note: this simple function is not inlined to make it easier to dtrace the
7142 * amount of time spent syncing frees.
7145 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
7147 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7148 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
7149 VERIFY(zio_wait(zio) == 0);
7153 * Note: this simple function is not inlined to make it easier to dtrace the
7154 * amount of time spent syncing deferred frees.
7157 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
7159 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7160 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
7161 spa_free_sync_cb, zio, tx), ==, 0);
7162 VERIFY0(zio_wait(zio));
7166 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
7168 char *packed = NULL;
7173 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
7176 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
7177 * information. This avoids the dmu_buf_will_dirty() path and
7178 * saves us a pre-read to get data we don't actually care about.
7180 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
7181 packed = vmem_alloc(bufsize, KM_SLEEP);
7183 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
7185 bzero(packed + nvsize, bufsize - nvsize);
7187 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
7189 vmem_free(packed, bufsize);
7191 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
7192 dmu_buf_will_dirty(db, tx);
7193 *(uint64_t *)db->db_data = nvsize;
7194 dmu_buf_rele(db, FTAG);
7198 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
7199 const char *config, const char *entry)
7209 * Update the MOS nvlist describing the list of available devices.
7210 * spa_validate_aux() will have already made sure this nvlist is
7211 * valid and the vdevs are labeled appropriately.
7213 if (sav->sav_object == 0) {
7214 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
7215 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
7216 sizeof (uint64_t), tx);
7217 VERIFY(zap_update(spa->spa_meta_objset,
7218 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
7219 &sav->sav_object, tx) == 0);
7222 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7223 if (sav->sav_count == 0) {
7224 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
7226 list = kmem_alloc(sav->sav_count*sizeof (void *), KM_SLEEP);
7227 for (i = 0; i < sav->sav_count; i++)
7228 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
7229 B_FALSE, VDEV_CONFIG_L2CACHE);
7230 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
7231 sav->sav_count) == 0);
7232 for (i = 0; i < sav->sav_count; i++)
7233 nvlist_free(list[i]);
7234 kmem_free(list, sav->sav_count * sizeof (void *));
7237 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
7238 nvlist_free(nvroot);
7240 sav->sav_sync = B_FALSE;
7244 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
7245 * The all-vdev ZAP must be empty.
7248 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
7250 spa_t *spa = vd->vdev_spa;
7252 if (vd->vdev_top_zap != 0) {
7253 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7254 vd->vdev_top_zap, tx));
7256 if (vd->vdev_leaf_zap != 0) {
7257 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7258 vd->vdev_leaf_zap, tx));
7260 for (uint64_t i = 0; i < vd->vdev_children; i++) {
7261 spa_avz_build(vd->vdev_child[i], avz, tx);
7266 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
7271 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
7272 * its config may not be dirty but we still need to build per-vdev ZAPs.
7273 * Similarly, if the pool is being assembled (e.g. after a split), we
7274 * need to rebuild the AVZ although the config may not be dirty.
7276 if (list_is_empty(&spa->spa_config_dirty_list) &&
7277 spa->spa_avz_action == AVZ_ACTION_NONE)
7280 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7282 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
7283 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
7284 spa->spa_all_vdev_zaps != 0);
7286 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
7287 /* Make and build the new AVZ */
7288 uint64_t new_avz = zap_create(spa->spa_meta_objset,
7289 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7290 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7292 /* Diff old AVZ with new one */
7296 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7297 spa->spa_all_vdev_zaps);
7298 zap_cursor_retrieve(&zc, &za) == 0;
7299 zap_cursor_advance(&zc)) {
7300 uint64_t vdzap = za.za_first_integer;
7301 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
7304 * ZAP is listed in old AVZ but not in new one;
7307 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
7312 zap_cursor_fini(&zc);
7314 /* Destroy the old AVZ */
7315 VERIFY0(zap_destroy(spa->spa_meta_objset,
7316 spa->spa_all_vdev_zaps, tx));
7318 /* Replace the old AVZ in the dir obj with the new one */
7319 VERIFY0(zap_update(spa->spa_meta_objset,
7320 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
7321 sizeof (new_avz), 1, &new_avz, tx));
7323 spa->spa_all_vdev_zaps = new_avz;
7324 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
7328 /* Walk through the AVZ and destroy all listed ZAPs */
7329 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7330 spa->spa_all_vdev_zaps);
7331 zap_cursor_retrieve(&zc, &za) == 0;
7332 zap_cursor_advance(&zc)) {
7333 uint64_t zap = za.za_first_integer;
7334 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
7337 zap_cursor_fini(&zc);
7339 /* Destroy and unlink the AVZ itself */
7340 VERIFY0(zap_destroy(spa->spa_meta_objset,
7341 spa->spa_all_vdev_zaps, tx));
7342 VERIFY0(zap_remove(spa->spa_meta_objset,
7343 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
7344 spa->spa_all_vdev_zaps = 0;
7347 if (spa->spa_all_vdev_zaps == 0) {
7348 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
7349 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
7350 DMU_POOL_VDEV_ZAP_MAP, tx);
7352 spa->spa_avz_action = AVZ_ACTION_NONE;
7354 /* Create ZAPs for vdevs that don't have them. */
7355 vdev_construct_zaps(spa->spa_root_vdev, tx);
7357 config = spa_config_generate(spa, spa->spa_root_vdev,
7358 dmu_tx_get_txg(tx), B_FALSE);
7361 * If we're upgrading the spa version then make sure that
7362 * the config object gets updated with the correct version.
7364 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
7365 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7366 spa->spa_uberblock.ub_version);
7368 spa_config_exit(spa, SCL_STATE, FTAG);
7370 nvlist_free(spa->spa_config_syncing);
7371 spa->spa_config_syncing = config;
7373 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
7377 spa_sync_version(void *arg, dmu_tx_t *tx)
7379 uint64_t *versionp = arg;
7380 uint64_t version = *versionp;
7381 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7384 * Setting the version is special cased when first creating the pool.
7386 ASSERT(tx->tx_txg != TXG_INITIAL);
7388 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
7389 ASSERT(version >= spa_version(spa));
7391 spa->spa_uberblock.ub_version = version;
7392 vdev_config_dirty(spa->spa_root_vdev);
7393 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
7397 * Set zpool properties.
7400 spa_sync_props(void *arg, dmu_tx_t *tx)
7402 nvlist_t *nvp = arg;
7403 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7404 objset_t *mos = spa->spa_meta_objset;
7405 nvpair_t *elem = NULL;
7407 mutex_enter(&spa->spa_props_lock);
7409 while ((elem = nvlist_next_nvpair(nvp, elem))) {
7411 char *strval, *fname;
7413 const char *propname;
7414 zprop_type_t proptype;
7417 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
7418 case ZPOOL_PROP_INVAL:
7420 * We checked this earlier in spa_prop_validate().
7422 ASSERT(zpool_prop_feature(nvpair_name(elem)));
7424 fname = strchr(nvpair_name(elem), '@') + 1;
7425 VERIFY0(zfeature_lookup_name(fname, &fid));
7427 spa_feature_enable(spa, fid, tx);
7428 spa_history_log_internal(spa, "set", tx,
7429 "%s=enabled", nvpair_name(elem));
7432 case ZPOOL_PROP_VERSION:
7433 intval = fnvpair_value_uint64(elem);
7435 * The version is synced separately before other
7436 * properties and should be correct by now.
7438 ASSERT3U(spa_version(spa), >=, intval);
7441 case ZPOOL_PROP_ALTROOT:
7443 * 'altroot' is a non-persistent property. It should
7444 * have been set temporarily at creation or import time.
7446 ASSERT(spa->spa_root != NULL);
7449 case ZPOOL_PROP_READONLY:
7450 case ZPOOL_PROP_CACHEFILE:
7452 * 'readonly' and 'cachefile' are also non-persisitent
7456 case ZPOOL_PROP_COMMENT:
7457 strval = fnvpair_value_string(elem);
7458 if (spa->spa_comment != NULL)
7459 spa_strfree(spa->spa_comment);
7460 spa->spa_comment = spa_strdup(strval);
7462 * We need to dirty the configuration on all the vdevs
7463 * so that their labels get updated. It's unnecessary
7464 * to do this for pool creation since the vdev's
7465 * configuration has already been dirtied.
7467 if (tx->tx_txg != TXG_INITIAL)
7468 vdev_config_dirty(spa->spa_root_vdev);
7469 spa_history_log_internal(spa, "set", tx,
7470 "%s=%s", nvpair_name(elem), strval);
7474 * Set pool property values in the poolprops mos object.
7476 if (spa->spa_pool_props_object == 0) {
7477 spa->spa_pool_props_object =
7478 zap_create_link(mos, DMU_OT_POOL_PROPS,
7479 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
7483 /* normalize the property name */
7484 propname = zpool_prop_to_name(prop);
7485 proptype = zpool_prop_get_type(prop);
7487 if (nvpair_type(elem) == DATA_TYPE_STRING) {
7488 ASSERT(proptype == PROP_TYPE_STRING);
7489 strval = fnvpair_value_string(elem);
7490 VERIFY0(zap_update(mos,
7491 spa->spa_pool_props_object, propname,
7492 1, strlen(strval) + 1, strval, tx));
7493 spa_history_log_internal(spa, "set", tx,
7494 "%s=%s", nvpair_name(elem), strval);
7495 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
7496 intval = fnvpair_value_uint64(elem);
7498 if (proptype == PROP_TYPE_INDEX) {
7500 VERIFY0(zpool_prop_index_to_string(
7501 prop, intval, &unused));
7503 VERIFY0(zap_update(mos,
7504 spa->spa_pool_props_object, propname,
7505 8, 1, &intval, tx));
7506 spa_history_log_internal(spa, "set", tx,
7507 "%s=%lld", nvpair_name(elem), intval);
7509 ASSERT(0); /* not allowed */
7513 case ZPOOL_PROP_DELEGATION:
7514 spa->spa_delegation = intval;
7516 case ZPOOL_PROP_BOOTFS:
7517 spa->spa_bootfs = intval;
7519 case ZPOOL_PROP_FAILUREMODE:
7520 spa->spa_failmode = intval;
7522 case ZPOOL_PROP_AUTOEXPAND:
7523 spa->spa_autoexpand = intval;
7524 if (tx->tx_txg != TXG_INITIAL)
7525 spa_async_request(spa,
7526 SPA_ASYNC_AUTOEXPAND);
7528 case ZPOOL_PROP_MULTIHOST:
7529 spa->spa_multihost = intval;
7531 case ZPOOL_PROP_DEDUPDITTO:
7532 spa->spa_dedup_ditto = intval;
7541 mutex_exit(&spa->spa_props_lock);
7545 * Perform one-time upgrade on-disk changes. spa_version() does not
7546 * reflect the new version this txg, so there must be no changes this
7547 * txg to anything that the upgrade code depends on after it executes.
7548 * Therefore this must be called after dsl_pool_sync() does the sync
7552 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
7554 dsl_pool_t *dp = spa->spa_dsl_pool;
7556 ASSERT(spa->spa_sync_pass == 1);
7558 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
7560 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
7561 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
7562 dsl_pool_create_origin(dp, tx);
7564 /* Keeping the origin open increases spa_minref */
7565 spa->spa_minref += 3;
7568 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
7569 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
7570 dsl_pool_upgrade_clones(dp, tx);
7573 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
7574 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
7575 dsl_pool_upgrade_dir_clones(dp, tx);
7577 /* Keeping the freedir open increases spa_minref */
7578 spa->spa_minref += 3;
7581 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
7582 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7583 spa_feature_create_zap_objects(spa, tx);
7587 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
7588 * when possibility to use lz4 compression for metadata was added
7589 * Old pools that have this feature enabled must be upgraded to have
7590 * this feature active
7592 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7593 boolean_t lz4_en = spa_feature_is_enabled(spa,
7594 SPA_FEATURE_LZ4_COMPRESS);
7595 boolean_t lz4_ac = spa_feature_is_active(spa,
7596 SPA_FEATURE_LZ4_COMPRESS);
7598 if (lz4_en && !lz4_ac)
7599 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
7603 * If we haven't written the salt, do so now. Note that the
7604 * feature may not be activated yet, but that's fine since
7605 * the presence of this ZAP entry is backwards compatible.
7607 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7608 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
7609 VERIFY0(zap_add(spa->spa_meta_objset,
7610 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
7611 sizeof (spa->spa_cksum_salt.zcs_bytes),
7612 spa->spa_cksum_salt.zcs_bytes, tx));
7615 rrw_exit(&dp->dp_config_rwlock, FTAG);
7619 vdev_indirect_state_sync_verify(vdev_t *vd)
7621 ASSERTV(vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping);
7622 ASSERTV(vdev_indirect_births_t *vib = vd->vdev_indirect_births);
7624 if (vd->vdev_ops == &vdev_indirect_ops) {
7625 ASSERT(vim != NULL);
7626 ASSERT(vib != NULL);
7629 if (vdev_obsolete_sm_object(vd) != 0) {
7630 ASSERT(vd->vdev_obsolete_sm != NULL);
7631 ASSERT(vd->vdev_removing ||
7632 vd->vdev_ops == &vdev_indirect_ops);
7633 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
7634 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
7636 ASSERT3U(vdev_obsolete_sm_object(vd), ==,
7637 space_map_object(vd->vdev_obsolete_sm));
7638 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
7639 space_map_allocated(vd->vdev_obsolete_sm));
7641 ASSERT(vd->vdev_obsolete_segments != NULL);
7644 * Since frees / remaps to an indirect vdev can only
7645 * happen in syncing context, the obsolete segments
7646 * tree must be empty when we start syncing.
7648 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
7652 * Sync the specified transaction group. New blocks may be dirtied as
7653 * part of the process, so we iterate until it converges.
7656 spa_sync(spa_t *spa, uint64_t txg)
7658 dsl_pool_t *dp = spa->spa_dsl_pool;
7659 objset_t *mos = spa->spa_meta_objset;
7660 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
7661 metaslab_class_t *normal = spa_normal_class(spa);
7662 metaslab_class_t *special = spa_special_class(spa);
7663 metaslab_class_t *dedup = spa_dedup_class(spa);
7664 vdev_t *rvd = spa->spa_root_vdev;
7668 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
7669 zfs_vdev_queue_depth_pct / 100;
7671 VERIFY(spa_writeable(spa));
7674 * Wait for i/os issued in open context that need to complete
7675 * before this txg syncs.
7677 VERIFY0(zio_wait(spa->spa_txg_zio[txg & TXG_MASK]));
7678 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL, 0);
7681 * Lock out configuration changes.
7683 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7685 spa->spa_syncing_txg = txg;
7686 spa->spa_sync_pass = 0;
7688 for (int i = 0; i < spa->spa_alloc_count; i++) {
7689 mutex_enter(&spa->spa_alloc_locks[i]);
7690 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
7691 mutex_exit(&spa->spa_alloc_locks[i]);
7695 * If there are any pending vdev state changes, convert them
7696 * into config changes that go out with this transaction group.
7698 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7699 while (list_head(&spa->spa_state_dirty_list) != NULL) {
7701 * We need the write lock here because, for aux vdevs,
7702 * calling vdev_config_dirty() modifies sav_config.
7703 * This is ugly and will become unnecessary when we
7704 * eliminate the aux vdev wart by integrating all vdevs
7705 * into the root vdev tree.
7707 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7708 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
7709 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
7710 vdev_state_clean(vd);
7711 vdev_config_dirty(vd);
7713 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7714 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
7716 spa_config_exit(spa, SCL_STATE, FTAG);
7718 tx = dmu_tx_create_assigned(dp, txg);
7720 spa->spa_sync_starttime = gethrtime();
7721 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
7722 spa->spa_deadman_tqid = taskq_dispatch_delay(system_delay_taskq,
7723 spa_deadman, spa, TQ_SLEEP, ddi_get_lbolt() +
7724 NSEC_TO_TICK(spa->spa_deadman_synctime));
7727 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
7728 * set spa_deflate if we have no raid-z vdevs.
7730 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
7731 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
7734 for (i = 0; i < rvd->vdev_children; i++) {
7735 vd = rvd->vdev_child[i];
7736 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
7739 if (i == rvd->vdev_children) {
7740 spa->spa_deflate = TRUE;
7741 VERIFY(0 == zap_add(spa->spa_meta_objset,
7742 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
7743 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
7748 * Set the top-level vdev's max queue depth. Evaluate each
7749 * top-level's async write queue depth in case it changed.
7750 * The max queue depth will not change in the middle of syncing
7753 uint64_t slots_per_allocator = 0;
7754 for (int c = 0; c < rvd->vdev_children; c++) {
7755 vdev_t *tvd = rvd->vdev_child[c];
7756 metaslab_group_t *mg = tvd->vdev_mg;
7757 metaslab_class_t *mc;
7759 if (mg == NULL || !metaslab_group_initialized(mg))
7763 if (mc != normal && mc != special && mc != dedup)
7767 * It is safe to do a lock-free check here because only async
7768 * allocations look at mg_max_alloc_queue_depth, and async
7769 * allocations all happen from spa_sync().
7771 for (int i = 0; i < spa->spa_alloc_count; i++)
7772 ASSERT0(zfs_refcount_count(
7773 &(mg->mg_alloc_queue_depth[i])));
7774 mg->mg_max_alloc_queue_depth = max_queue_depth;
7776 for (int i = 0; i < spa->spa_alloc_count; i++) {
7777 mg->mg_cur_max_alloc_queue_depth[i] =
7778 zfs_vdev_def_queue_depth;
7780 slots_per_allocator += zfs_vdev_def_queue_depth;
7783 for (int i = 0; i < spa->spa_alloc_count; i++) {
7784 ASSERT0(zfs_refcount_count(&normal->mc_alloc_slots[i]));
7785 ASSERT0(zfs_refcount_count(&special->mc_alloc_slots[i]));
7786 ASSERT0(zfs_refcount_count(&dedup->mc_alloc_slots[i]));
7787 normal->mc_alloc_max_slots[i] = slots_per_allocator;
7788 special->mc_alloc_max_slots[i] = slots_per_allocator;
7789 dedup->mc_alloc_max_slots[i] = slots_per_allocator;
7791 normal->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
7792 special->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
7793 dedup->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
7795 for (int c = 0; c < rvd->vdev_children; c++) {
7796 vdev_t *vd = rvd->vdev_child[c];
7797 vdev_indirect_state_sync_verify(vd);
7799 if (vdev_indirect_should_condense(vd)) {
7800 spa_condense_indirect_start_sync(vd, tx);
7806 * Iterate to convergence.
7809 int pass = ++spa->spa_sync_pass;
7811 spa_sync_config_object(spa, tx);
7812 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
7813 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
7814 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
7815 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
7816 spa_errlog_sync(spa, txg);
7817 dsl_pool_sync(dp, txg);
7819 if (pass < zfs_sync_pass_deferred_free) {
7820 spa_sync_frees(spa, free_bpl, tx);
7823 * We can not defer frees in pass 1, because
7824 * we sync the deferred frees later in pass 1.
7826 ASSERT3U(pass, >, 1);
7827 bplist_iterate(free_bpl, bpobj_enqueue_cb,
7828 &spa->spa_deferred_bpobj, tx);
7832 dsl_scan_sync(dp, tx);
7834 if (spa->spa_vdev_removal != NULL)
7837 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
7842 spa_sync_upgrades(spa, tx);
7844 spa->spa_uberblock.ub_rootbp.blk_birth);
7846 * Note: We need to check if the MOS is dirty
7847 * because we could have marked the MOS dirty
7848 * without updating the uberblock (e.g. if we
7849 * have sync tasks but no dirty user data). We
7850 * need to check the uberblock's rootbp because
7851 * it is updated if we have synced out dirty
7852 * data (though in this case the MOS will most
7853 * likely also be dirty due to second order
7854 * effects, we don't want to rely on that here).
7856 if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
7857 !dmu_objset_is_dirty(mos, txg)) {
7859 * Nothing changed on the first pass,
7860 * therefore this TXG is a no-op. Avoid
7861 * syncing deferred frees, so that we
7862 * can keep this TXG as a no-op.
7864 ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
7866 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
7867 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
7868 ASSERT(txg_list_empty(&dp->dp_early_sync_tasks,
7872 spa_sync_deferred_frees(spa, tx);
7875 } while (dmu_objset_is_dirty(mos, txg));
7878 if (!list_is_empty(&spa->spa_config_dirty_list)) {
7880 * Make sure that the number of ZAPs for all the vdevs matches
7881 * the number of ZAPs in the per-vdev ZAP list. This only gets
7882 * called if the config is dirty; otherwise there may be
7883 * outstanding AVZ operations that weren't completed in
7884 * spa_sync_config_object.
7886 uint64_t all_vdev_zap_entry_count;
7887 ASSERT0(zap_count(spa->spa_meta_objset,
7888 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
7889 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
7890 all_vdev_zap_entry_count);
7894 if (spa->spa_vdev_removal != NULL) {
7895 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
7899 * Rewrite the vdev configuration (which includes the uberblock)
7900 * to commit the transaction group.
7902 * If there are no dirty vdevs, we sync the uberblock to a few
7903 * random top-level vdevs that are known to be visible in the
7904 * config cache (see spa_vdev_add() for a complete description).
7905 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
7909 * We hold SCL_STATE to prevent vdev open/close/etc.
7910 * while we're attempting to write the vdev labels.
7912 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7914 if (list_is_empty(&spa->spa_config_dirty_list)) {
7915 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
7917 int children = rvd->vdev_children;
7918 int c0 = spa_get_random(children);
7920 for (int c = 0; c < children; c++) {
7921 vd = rvd->vdev_child[(c0 + c) % children];
7923 /* Stop when revisiting the first vdev */
7924 if (c > 0 && svd[0] == vd)
7927 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
7928 !vdev_is_concrete(vd))
7931 svd[svdcount++] = vd;
7932 if (svdcount == SPA_SYNC_MIN_VDEVS)
7935 error = vdev_config_sync(svd, svdcount, txg);
7937 error = vdev_config_sync(rvd->vdev_child,
7938 rvd->vdev_children, txg);
7942 spa->spa_last_synced_guid = rvd->vdev_guid;
7944 spa_config_exit(spa, SCL_STATE, FTAG);
7948 zio_suspend(spa, NULL, ZIO_SUSPEND_IOERR);
7949 zio_resume_wait(spa);
7953 taskq_cancel_id(system_delay_taskq, spa->spa_deadman_tqid);
7954 spa->spa_deadman_tqid = 0;
7957 * Clear the dirty config list.
7959 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
7960 vdev_config_clean(vd);
7963 * Now that the new config has synced transactionally,
7964 * let it become visible to the config cache.
7966 if (spa->spa_config_syncing != NULL) {
7967 spa_config_set(spa, spa->spa_config_syncing);
7968 spa->spa_config_txg = txg;
7969 spa->spa_config_syncing = NULL;
7972 dsl_pool_sync_done(dp, txg);
7974 for (int i = 0; i < spa->spa_alloc_count; i++) {
7975 mutex_enter(&spa->spa_alloc_locks[i]);
7976 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
7977 mutex_exit(&spa->spa_alloc_locks[i]);
7981 * Update usable space statistics.
7983 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg))))
7984 vdev_sync_done(vd, txg);
7986 spa_update_dspace(spa);
7989 * It had better be the case that we didn't dirty anything
7990 * since vdev_config_sync().
7992 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
7993 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
7994 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
7996 while (zfs_pause_spa_sync)
7999 spa->spa_sync_pass = 0;
8002 * Update the last synced uberblock here. We want to do this at
8003 * the end of spa_sync() so that consumers of spa_last_synced_txg()
8004 * will be guaranteed that all the processing associated with
8005 * that txg has been completed.
8007 spa->spa_ubsync = spa->spa_uberblock;
8008 spa_config_exit(spa, SCL_CONFIG, FTAG);
8010 spa_handle_ignored_writes(spa);
8013 * If any async tasks have been requested, kick them off.
8015 spa_async_dispatch(spa);
8019 * Sync all pools. We don't want to hold the namespace lock across these
8020 * operations, so we take a reference on the spa_t and drop the lock during the
8024 spa_sync_allpools(void)
8027 mutex_enter(&spa_namespace_lock);
8028 while ((spa = spa_next(spa)) != NULL) {
8029 if (spa_state(spa) != POOL_STATE_ACTIVE ||
8030 !spa_writeable(spa) || spa_suspended(spa))
8032 spa_open_ref(spa, FTAG);
8033 mutex_exit(&spa_namespace_lock);
8034 txg_wait_synced(spa_get_dsl(spa), 0);
8035 mutex_enter(&spa_namespace_lock);
8036 spa_close(spa, FTAG);
8038 mutex_exit(&spa_namespace_lock);
8042 * ==========================================================================
8043 * Miscellaneous routines
8044 * ==========================================================================
8048 * Remove all pools in the system.
8056 * Remove all cached state. All pools should be closed now,
8057 * so every spa in the AVL tree should be unreferenced.
8059 mutex_enter(&spa_namespace_lock);
8060 while ((spa = spa_next(NULL)) != NULL) {
8062 * Stop async tasks. The async thread may need to detach
8063 * a device that's been replaced, which requires grabbing
8064 * spa_namespace_lock, so we must drop it here.
8066 spa_open_ref(spa, FTAG);
8067 mutex_exit(&spa_namespace_lock);
8068 spa_async_suspend(spa);
8069 mutex_enter(&spa_namespace_lock);
8070 spa_close(spa, FTAG);
8072 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
8074 spa_deactivate(spa);
8078 mutex_exit(&spa_namespace_lock);
8082 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
8087 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
8091 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
8092 vd = spa->spa_l2cache.sav_vdevs[i];
8093 if (vd->vdev_guid == guid)
8097 for (i = 0; i < spa->spa_spares.sav_count; i++) {
8098 vd = spa->spa_spares.sav_vdevs[i];
8099 if (vd->vdev_guid == guid)
8108 spa_upgrade(spa_t *spa, uint64_t version)
8110 ASSERT(spa_writeable(spa));
8112 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
8115 * This should only be called for a non-faulted pool, and since a
8116 * future version would result in an unopenable pool, this shouldn't be
8119 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
8120 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
8122 spa->spa_uberblock.ub_version = version;
8123 vdev_config_dirty(spa->spa_root_vdev);
8125 spa_config_exit(spa, SCL_ALL, FTAG);
8127 txg_wait_synced(spa_get_dsl(spa), 0);
8131 spa_has_spare(spa_t *spa, uint64_t guid)
8135 spa_aux_vdev_t *sav = &spa->spa_spares;
8137 for (i = 0; i < sav->sav_count; i++)
8138 if (sav->sav_vdevs[i]->vdev_guid == guid)
8141 for (i = 0; i < sav->sav_npending; i++) {
8142 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
8143 &spareguid) == 0 && spareguid == guid)
8151 * Check if a pool has an active shared spare device.
8152 * Note: reference count of an active spare is 2, as a spare and as a replace
8155 spa_has_active_shared_spare(spa_t *spa)
8159 spa_aux_vdev_t *sav = &spa->spa_spares;
8161 for (i = 0; i < sav->sav_count; i++) {
8162 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
8163 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
8172 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8174 sysevent_t *ev = NULL;
8178 resource = zfs_event_create(spa, vd, FM_SYSEVENT_CLASS, name, hist_nvl);
8180 ev = kmem_alloc(sizeof (sysevent_t), KM_SLEEP);
8181 ev->resource = resource;
8188 spa_event_post(sysevent_t *ev)
8192 zfs_zevent_post(ev->resource, NULL, zfs_zevent_post_cb);
8193 kmem_free(ev, sizeof (*ev));
8199 * Post a zevent corresponding to the given sysevent. The 'name' must be one
8200 * of the event definitions in sys/sysevent/eventdefs.h. The payload will be
8201 * filled in from the spa and (optionally) the vdev. This doesn't do anything
8202 * in the userland libzpool, as we don't want consumers to misinterpret ztest
8203 * or zdb as real changes.
8206 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8208 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));
8211 #if defined(_KERNEL)
8212 /* state manipulation functions */
8213 EXPORT_SYMBOL(spa_open);
8214 EXPORT_SYMBOL(spa_open_rewind);
8215 EXPORT_SYMBOL(spa_get_stats);
8216 EXPORT_SYMBOL(spa_create);
8217 EXPORT_SYMBOL(spa_import);
8218 EXPORT_SYMBOL(spa_tryimport);
8219 EXPORT_SYMBOL(spa_destroy);
8220 EXPORT_SYMBOL(spa_export);
8221 EXPORT_SYMBOL(spa_reset);
8222 EXPORT_SYMBOL(spa_async_request);
8223 EXPORT_SYMBOL(spa_async_suspend);
8224 EXPORT_SYMBOL(spa_async_resume);
8225 EXPORT_SYMBOL(spa_inject_addref);
8226 EXPORT_SYMBOL(spa_inject_delref);
8227 EXPORT_SYMBOL(spa_scan_stat_init);
8228 EXPORT_SYMBOL(spa_scan_get_stats);
8230 /* device maniion */
8231 EXPORT_SYMBOL(spa_vdev_add);
8232 EXPORT_SYMBOL(spa_vdev_attach);
8233 EXPORT_SYMBOL(spa_vdev_detach);
8234 EXPORT_SYMBOL(spa_vdev_setpath);
8235 EXPORT_SYMBOL(spa_vdev_setfru);
8236 EXPORT_SYMBOL(spa_vdev_split_mirror);
8238 /* spare statech is global across all pools) */
8239 EXPORT_SYMBOL(spa_spare_add);
8240 EXPORT_SYMBOL(spa_spare_remove);
8241 EXPORT_SYMBOL(spa_spare_exists);
8242 EXPORT_SYMBOL(spa_spare_activate);
8244 /* L2ARC statech is global across all pools) */
8245 EXPORT_SYMBOL(spa_l2cache_add);
8246 EXPORT_SYMBOL(spa_l2cache_remove);
8247 EXPORT_SYMBOL(spa_l2cache_exists);
8248 EXPORT_SYMBOL(spa_l2cache_activate);
8249 EXPORT_SYMBOL(spa_l2cache_drop);
8252 EXPORT_SYMBOL(spa_scan);
8253 EXPORT_SYMBOL(spa_scan_stop);
8256 EXPORT_SYMBOL(spa_sync); /* only for DMU use */
8257 EXPORT_SYMBOL(spa_sync_allpools);
8260 EXPORT_SYMBOL(spa_prop_set);
8261 EXPORT_SYMBOL(spa_prop_get);
8262 EXPORT_SYMBOL(spa_prop_clear_bootfs);
8264 /* asynchronous event notification */
8265 EXPORT_SYMBOL(spa_event_notify);
8268 #if defined(_KERNEL)
8269 module_param(spa_load_verify_maxinflight, int, 0644);
8270 MODULE_PARM_DESC(spa_load_verify_maxinflight,
8271 "Max concurrent traversal I/Os while verifying pool during import -X");
8273 module_param(spa_load_verify_metadata, int, 0644);
8274 MODULE_PARM_DESC(spa_load_verify_metadata,
8275 "Set to traverse metadata on pool import");
8277 module_param(spa_load_verify_data, int, 0644);
8278 MODULE_PARM_DESC(spa_load_verify_data,
8279 "Set to traverse data on pool import");
8281 module_param(spa_load_print_vdev_tree, int, 0644);
8282 MODULE_PARM_DESC(spa_load_print_vdev_tree,
8283 "Print vdev tree to zfs_dbgmsg during pool import");
8286 module_param(zio_taskq_batch_pct, uint, 0444);
8287 MODULE_PARM_DESC(zio_taskq_batch_pct,
8288 "Percentage of CPUs to run an IO worker thread");
8291 module_param(zfs_max_missing_tvds, ulong, 0644);
8292 MODULE_PARM_DESC(zfs_max_missing_tvds,
8293 "Allow importing pool with up to this number of missing top-level vdevs"
8294 " (in read-only mode)");