4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25 * Copyright (c) 2015, Nexenta Systems, Inc. All rights reserved.
26 * Copyright (c) 2013 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
27 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28 * Copyright 2013 Saso Kiselkov. All rights reserved.
29 * Copyright (c) 2014 Integros [integros.com]
30 * Copyright 2016 Toomas Soome <tsoome@me.com>
31 * Copyright 2018 Joyent, Inc.
32 * Copyright (c) 2017, Intel Corporation.
33 * Copyright (c) 2017 Datto Inc.
34 * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
38 * SPA: Storage Pool Allocator
40 * This file contains all the routines used when modifying on-disk SPA state.
41 * This includes opening, importing, destroying, exporting a pool, and syncing a
45 #include <sys/zfs_context.h>
46 #include <sys/fm/fs/zfs.h>
47 #include <sys/spa_impl.h>
49 #include <sys/zio_checksum.h>
51 #include <sys/dmu_tx.h>
55 #include <sys/vdev_impl.h>
56 #include <sys/vdev_removal.h>
57 #include <sys/vdev_indirect_mapping.h>
58 #include <sys/vdev_indirect_births.h>
59 #include <sys/vdev_initialize.h>
60 #include <sys/metaslab.h>
61 #include <sys/metaslab_impl.h>
63 #include <sys/uberblock_impl.h>
66 #include <sys/bpobj.h>
67 #include <sys/dmu_traverse.h>
68 #include <sys/dmu_objset.h>
69 #include <sys/unique.h>
70 #include <sys/dsl_pool.h>
71 #include <sys/dsl_dataset.h>
72 #include <sys/dsl_dir.h>
73 #include <sys/dsl_prop.h>
74 #include <sys/dsl_synctask.h>
75 #include <sys/fs/zfs.h>
77 #include <sys/callb.h>
78 #include <sys/spa_boot.h>
79 #include <sys/zfs_ioctl.h>
80 #include <sys/dsl_scan.h>
81 #include <sys/dmu_send.h>
82 #include <sys/dsl_destroy.h>
83 #include <sys/dsl_userhold.h>
84 #include <sys/zfeature.h>
86 #include <sys/trim_map.h>
90 #include <sys/callb.h>
91 #include <sys/cpupart.h>
96 #include "zfs_comutil.h"
98 /* Check hostid on import? */
99 static int check_hostid = 1;
102 * The interval, in seconds, at which failed configuration cache file writes
105 int zfs_ccw_retry_interval = 300;
107 SYSCTL_DECL(_vfs_zfs);
108 SYSCTL_INT(_vfs_zfs, OID_AUTO, check_hostid, CTLFLAG_RWTUN, &check_hostid, 0,
109 "Check hostid on import?");
110 TUNABLE_INT("vfs.zfs.ccw_retry_interval", &zfs_ccw_retry_interval);
111 SYSCTL_INT(_vfs_zfs, OID_AUTO, ccw_retry_interval, CTLFLAG_RW,
112 &zfs_ccw_retry_interval, 0,
113 "Configuration cache file write, retry after failure, interval (seconds)");
115 typedef enum zti_modes {
116 ZTI_MODE_FIXED, /* value is # of threads (min 1) */
117 ZTI_MODE_BATCH, /* cpu-intensive; value is ignored */
118 ZTI_MODE_NULL, /* don't create a taskq */
122 #define ZTI_P(n, q) { ZTI_MODE_FIXED, (n), (q) }
123 #define ZTI_BATCH { ZTI_MODE_BATCH, 0, 1 }
124 #define ZTI_NULL { ZTI_MODE_NULL, 0, 0 }
126 #define ZTI_N(n) ZTI_P(n, 1)
127 #define ZTI_ONE ZTI_N(1)
129 typedef struct zio_taskq_info {
130 zti_modes_t zti_mode;
135 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
136 "issue", "issue_high", "intr", "intr_high"
140 * This table defines the taskq settings for each ZFS I/O type. When
141 * initializing a pool, we use this table to create an appropriately sized
142 * taskq. Some operations are low volume and therefore have a small, static
143 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
144 * macros. Other operations process a large amount of data; the ZTI_BATCH
145 * macro causes us to create a taskq oriented for throughput. Some operations
146 * are so high frequency and short-lived that the taskq itself can become a a
147 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
148 * additional degree of parallelism specified by the number of threads per-
149 * taskq and the number of taskqs; when dispatching an event in this case, the
150 * particular taskq is chosen at random.
152 * The different taskq priorities are to handle the different contexts (issue
153 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
154 * need to be handled with minimum delay.
156 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
157 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
158 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* NULL */
159 { ZTI_N(8), ZTI_NULL, ZTI_P(12, 8), ZTI_NULL }, /* READ */
160 { ZTI_BATCH, ZTI_N(5), ZTI_P(12, 8), ZTI_N(5) }, /* WRITE */
161 { ZTI_P(12, 8), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* FREE */
162 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* CLAIM */
163 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* IOCTL */
166 static void spa_sync_version(void *arg, dmu_tx_t *tx);
167 static void spa_sync_props(void *arg, dmu_tx_t *tx);
168 static boolean_t spa_has_active_shared_spare(spa_t *spa);
169 static int spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport);
170 static void spa_vdev_resilver_done(spa_t *spa);
172 uint_t zio_taskq_batch_pct = 75; /* 1 thread per cpu in pset */
174 id_t zio_taskq_psrset_bind = PS_NONE;
177 boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
178 uint_t zio_taskq_basedc = 80; /* base duty cycle */
184 boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
186 extern int zfs_sync_pass_deferred_free;
189 * Report any spa_load_verify errors found, but do not fail spa_load.
190 * This is used by zdb to analyze non-idle pools.
192 boolean_t spa_load_verify_dryrun = B_FALSE;
195 * This (illegal) pool name is used when temporarily importing a spa_t in order
196 * to get the vdev stats associated with the imported devices.
198 #define TRYIMPORT_NAME "$import"
201 * For debugging purposes: print out vdev tree during pool import.
203 int spa_load_print_vdev_tree = B_FALSE;
206 * A non-zero value for zfs_max_missing_tvds means that we allow importing
207 * pools with missing top-level vdevs. This is strictly intended for advanced
208 * pool recovery cases since missing data is almost inevitable. Pools with
209 * missing devices can only be imported read-only for safety reasons, and their
210 * fail-mode will be automatically set to "continue".
212 * With 1 missing vdev we should be able to import the pool and mount all
213 * datasets. User data that was not modified after the missing device has been
214 * added should be recoverable. This means that snapshots created prior to the
215 * addition of that device should be completely intact.
217 * With 2 missing vdevs, some datasets may fail to mount since there are
218 * dataset statistics that are stored as regular metadata. Some data might be
219 * recoverable if those vdevs were added recently.
221 * With 3 or more missing vdevs, the pool is severely damaged and MOS entries
222 * may be missing entirely. Chances of data recovery are very low. Note that
223 * there are also risks of performing an inadvertent rewind as we might be
224 * missing all the vdevs with the latest uberblocks.
226 uint64_t zfs_max_missing_tvds = 0;
229 * The parameters below are similar to zfs_max_missing_tvds but are only
230 * intended for a preliminary open of the pool with an untrusted config which
231 * might be incomplete or out-dated.
233 * We are more tolerant for pools opened from a cachefile since we could have
234 * an out-dated cachefile where a device removal was not registered.
235 * We could have set the limit arbitrarily high but in the case where devices
236 * are really missing we would want to return the proper error codes; we chose
237 * SPA_DVAS_PER_BP - 1 so that some copies of the MOS would still be available
238 * and we get a chance to retrieve the trusted config.
240 uint64_t zfs_max_missing_tvds_cachefile = SPA_DVAS_PER_BP - 1;
243 * In the case where config was assembled by scanning device paths (/dev/dsks
244 * by default) we are less tolerant since all the existing devices should have
245 * been detected and we want spa_load to return the right error codes.
247 uint64_t zfs_max_missing_tvds_scan = 0;
250 SYSCTL_DECL(_vfs_zfs_zio);
251 SYSCTL_INT(_vfs_zfs_zio, OID_AUTO, taskq_batch_pct, CTLFLAG_RDTUN,
252 &zio_taskq_batch_pct, 0,
253 "Percentage of CPUs to run an IO worker thread");
254 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_print_vdev_tree, CTLFLAG_RWTUN,
255 &spa_load_print_vdev_tree, 0,
256 "print out vdev tree during pool import");
257 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds, CTLFLAG_RWTUN,
258 &zfs_max_missing_tvds, 0,
259 "allow importing pools with missing top-level vdevs");
260 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_cachefile, CTLFLAG_RWTUN,
261 &zfs_max_missing_tvds_cachefile, 0,
262 "allow importing pools with missing top-level vdevs in cache file");
263 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_scan, CTLFLAG_RWTUN,
264 &zfs_max_missing_tvds_scan, 0,
265 "allow importing pools with missing top-level vdevs during scan");
268 * Debugging aid that pauses spa_sync() towards the end.
270 boolean_t zfs_pause_spa_sync = B_FALSE;
273 * ==========================================================================
274 * SPA properties routines
275 * ==========================================================================
279 * Add a (source=src, propname=propval) list to an nvlist.
282 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
283 uint64_t intval, zprop_source_t src)
285 const char *propname = zpool_prop_to_name(prop);
288 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
289 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
292 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
294 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
296 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
297 nvlist_free(propval);
301 * Get property values from the spa configuration.
304 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
306 vdev_t *rvd = spa->spa_root_vdev;
307 dsl_pool_t *pool = spa->spa_dsl_pool;
308 uint64_t size, alloc, cap, version;
309 zprop_source_t src = ZPROP_SRC_NONE;
310 spa_config_dirent_t *dp;
311 metaslab_class_t *mc = spa_normal_class(spa);
313 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
316 alloc = metaslab_class_get_alloc(mc);
317 alloc += metaslab_class_get_alloc(spa_special_class(spa));
318 alloc += metaslab_class_get_alloc(spa_dedup_class(spa));
320 size = metaslab_class_get_space(mc);
321 size += metaslab_class_get_space(spa_special_class(spa));
322 size += metaslab_class_get_space(spa_dedup_class(spa));
324 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
325 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
326 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
327 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
329 spa_prop_add_list(*nvp, ZPOOL_PROP_CHECKPOINT, NULL,
330 spa->spa_checkpoint_info.sci_dspace, src);
332 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
333 metaslab_class_fragmentation(mc), src);
334 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
335 metaslab_class_expandable_space(mc), src);
336 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
337 (spa_mode(spa) == FREAD), src);
339 cap = (size == 0) ? 0 : (alloc * 100 / size);
340 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
342 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
343 ddt_get_pool_dedup_ratio(spa), src);
345 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
346 rvd->vdev_state, src);
348 version = spa_version(spa);
349 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
350 src = ZPROP_SRC_DEFAULT;
352 src = ZPROP_SRC_LOCAL;
353 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
358 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
359 * when opening pools before this version freedir will be NULL.
361 if (pool->dp_free_dir != NULL) {
362 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
363 dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
366 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
370 if (pool->dp_leak_dir != NULL) {
371 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
372 dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
375 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
380 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
382 if (spa->spa_comment != NULL) {
383 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
387 if (spa->spa_root != NULL)
388 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
391 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
392 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
393 MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
395 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
396 SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
399 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE)) {
400 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
401 DNODE_MAX_SIZE, ZPROP_SRC_NONE);
403 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
404 DNODE_MIN_SIZE, ZPROP_SRC_NONE);
407 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
408 if (dp->scd_path == NULL) {
409 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
410 "none", 0, ZPROP_SRC_LOCAL);
411 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
412 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
413 dp->scd_path, 0, ZPROP_SRC_LOCAL);
419 * Get zpool property values.
422 spa_prop_get(spa_t *spa, nvlist_t **nvp)
424 objset_t *mos = spa->spa_meta_objset;
429 VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
431 mutex_enter(&spa->spa_props_lock);
434 * Get properties from the spa config.
436 spa_prop_get_config(spa, nvp);
438 /* If no pool property object, no more prop to get. */
439 if (mos == NULL || spa->spa_pool_props_object == 0) {
440 mutex_exit(&spa->spa_props_lock);
445 * Get properties from the MOS pool property object.
447 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
448 (err = zap_cursor_retrieve(&zc, &za)) == 0;
449 zap_cursor_advance(&zc)) {
452 zprop_source_t src = ZPROP_SRC_DEFAULT;
455 if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
458 switch (za.za_integer_length) {
460 /* integer property */
461 if (za.za_first_integer !=
462 zpool_prop_default_numeric(prop))
463 src = ZPROP_SRC_LOCAL;
465 if (prop == ZPOOL_PROP_BOOTFS) {
467 dsl_dataset_t *ds = NULL;
469 dp = spa_get_dsl(spa);
470 dsl_pool_config_enter(dp, FTAG);
471 err = dsl_dataset_hold_obj(dp,
472 za.za_first_integer, FTAG, &ds);
474 dsl_pool_config_exit(dp, FTAG);
478 strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
480 dsl_dataset_name(ds, strval);
481 dsl_dataset_rele(ds, FTAG);
482 dsl_pool_config_exit(dp, FTAG);
485 intval = za.za_first_integer;
488 spa_prop_add_list(*nvp, prop, strval, intval, src);
491 kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
496 /* string property */
497 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
498 err = zap_lookup(mos, spa->spa_pool_props_object,
499 za.za_name, 1, za.za_num_integers, strval);
501 kmem_free(strval, za.za_num_integers);
504 spa_prop_add_list(*nvp, prop, strval, 0, src);
505 kmem_free(strval, za.za_num_integers);
512 zap_cursor_fini(&zc);
513 mutex_exit(&spa->spa_props_lock);
515 if (err && err != ENOENT) {
525 * Validate the given pool properties nvlist and modify the list
526 * for the property values to be set.
529 spa_prop_validate(spa_t *spa, nvlist_t *props)
532 int error = 0, reset_bootfs = 0;
534 boolean_t has_feature = B_FALSE;
537 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
539 char *strval, *slash, *check, *fname;
540 const char *propname = nvpair_name(elem);
541 zpool_prop_t prop = zpool_name_to_prop(propname);
544 case ZPOOL_PROP_INVAL:
545 if (!zpool_prop_feature(propname)) {
546 error = SET_ERROR(EINVAL);
551 * Sanitize the input.
553 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
554 error = SET_ERROR(EINVAL);
558 if (nvpair_value_uint64(elem, &intval) != 0) {
559 error = SET_ERROR(EINVAL);
564 error = SET_ERROR(EINVAL);
568 fname = strchr(propname, '@') + 1;
569 if (zfeature_lookup_name(fname, NULL) != 0) {
570 error = SET_ERROR(EINVAL);
574 has_feature = B_TRUE;
577 case ZPOOL_PROP_VERSION:
578 error = nvpair_value_uint64(elem, &intval);
580 (intval < spa_version(spa) ||
581 intval > SPA_VERSION_BEFORE_FEATURES ||
583 error = SET_ERROR(EINVAL);
586 case ZPOOL_PROP_DELEGATION:
587 case ZPOOL_PROP_AUTOREPLACE:
588 case ZPOOL_PROP_LISTSNAPS:
589 case ZPOOL_PROP_AUTOEXPAND:
590 error = nvpair_value_uint64(elem, &intval);
591 if (!error && intval > 1)
592 error = SET_ERROR(EINVAL);
595 case ZPOOL_PROP_MULTIHOST:
596 error = nvpair_value_uint64(elem, &intval);
597 if (!error && intval > 1)
598 error = SET_ERROR(EINVAL);
600 if (!error && !spa_get_hostid())
601 error = SET_ERROR(ENOTSUP);
605 case ZPOOL_PROP_BOOTFS:
607 * If the pool version is less than SPA_VERSION_BOOTFS,
608 * or the pool is still being created (version == 0),
609 * the bootfs property cannot be set.
611 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
612 error = SET_ERROR(ENOTSUP);
617 * Make sure the vdev config is bootable
619 if (!vdev_is_bootable(spa->spa_root_vdev)) {
620 error = SET_ERROR(ENOTSUP);
626 error = nvpair_value_string(elem, &strval);
632 if (strval == NULL || strval[0] == '\0') {
633 objnum = zpool_prop_default_numeric(
638 error = dmu_objset_hold(strval, FTAG, &os);
643 * Must be ZPL, and its property settings
647 if (dmu_objset_type(os) != DMU_OST_ZFS) {
648 error = SET_ERROR(ENOTSUP);
650 dsl_prop_get_int_ds(dmu_objset_ds(os),
651 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
653 !BOOTFS_COMPRESS_VALID(propval)) {
654 error = SET_ERROR(ENOTSUP);
656 objnum = dmu_objset_id(os);
658 dmu_objset_rele(os, FTAG);
662 case ZPOOL_PROP_FAILUREMODE:
663 error = nvpair_value_uint64(elem, &intval);
664 if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
665 intval > ZIO_FAILURE_MODE_PANIC))
666 error = SET_ERROR(EINVAL);
669 * This is a special case which only occurs when
670 * the pool has completely failed. This allows
671 * the user to change the in-core failmode property
672 * without syncing it out to disk (I/Os might
673 * currently be blocked). We do this by returning
674 * EIO to the caller (spa_prop_set) to trick it
675 * into thinking we encountered a property validation
678 if (!error && spa_suspended(spa)) {
679 spa->spa_failmode = intval;
680 error = SET_ERROR(EIO);
684 case ZPOOL_PROP_CACHEFILE:
685 if ((error = nvpair_value_string(elem, &strval)) != 0)
688 if (strval[0] == '\0')
691 if (strcmp(strval, "none") == 0)
694 if (strval[0] != '/') {
695 error = SET_ERROR(EINVAL);
699 slash = strrchr(strval, '/');
700 ASSERT(slash != NULL);
702 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
703 strcmp(slash, "/..") == 0)
704 error = SET_ERROR(EINVAL);
707 case ZPOOL_PROP_COMMENT:
708 if ((error = nvpair_value_string(elem, &strval)) != 0)
710 for (check = strval; *check != '\0'; check++) {
712 * The kernel doesn't have an easy isprint()
713 * check. For this kernel check, we merely
714 * check ASCII apart from DEL. Fix this if
715 * there is an easy-to-use kernel isprint().
717 if (*check >= 0x7f) {
718 error = SET_ERROR(EINVAL);
722 if (strlen(strval) > ZPROP_MAX_COMMENT)
726 case ZPOOL_PROP_DEDUPDITTO:
727 if (spa_version(spa) < SPA_VERSION_DEDUP)
728 error = SET_ERROR(ENOTSUP);
730 error = nvpair_value_uint64(elem, &intval);
732 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
733 error = SET_ERROR(EINVAL);
741 if (!error && reset_bootfs) {
742 error = nvlist_remove(props,
743 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
746 error = nvlist_add_uint64(props,
747 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
755 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
758 spa_config_dirent_t *dp;
760 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
764 dp = kmem_alloc(sizeof (spa_config_dirent_t),
767 if (cachefile[0] == '\0')
768 dp->scd_path = spa_strdup(spa_config_path);
769 else if (strcmp(cachefile, "none") == 0)
772 dp->scd_path = spa_strdup(cachefile);
774 list_insert_head(&spa->spa_config_list, dp);
776 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
780 spa_prop_set(spa_t *spa, nvlist_t *nvp)
783 nvpair_t *elem = NULL;
784 boolean_t need_sync = B_FALSE;
786 if ((error = spa_prop_validate(spa, nvp)) != 0)
789 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
790 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
792 if (prop == ZPOOL_PROP_CACHEFILE ||
793 prop == ZPOOL_PROP_ALTROOT ||
794 prop == ZPOOL_PROP_READONLY)
797 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
800 if (prop == ZPOOL_PROP_VERSION) {
801 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
803 ASSERT(zpool_prop_feature(nvpair_name(elem)));
804 ver = SPA_VERSION_FEATURES;
808 /* Save time if the version is already set. */
809 if (ver == spa_version(spa))
813 * In addition to the pool directory object, we might
814 * create the pool properties object, the features for
815 * read object, the features for write object, or the
816 * feature descriptions object.
818 error = dsl_sync_task(spa->spa_name, NULL,
819 spa_sync_version, &ver,
820 6, ZFS_SPACE_CHECK_RESERVED);
831 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
832 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
839 * If the bootfs property value is dsobj, clear it.
842 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
844 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
845 VERIFY(zap_remove(spa->spa_meta_objset,
846 spa->spa_pool_props_object,
847 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
854 spa_change_guid_check(void *arg, dmu_tx_t *tx)
856 uint64_t *newguid = arg;
857 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
858 vdev_t *rvd = spa->spa_root_vdev;
861 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
862 int error = (spa_has_checkpoint(spa)) ?
863 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
864 return (SET_ERROR(error));
867 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
868 vdev_state = rvd->vdev_state;
869 spa_config_exit(spa, SCL_STATE, FTAG);
871 if (vdev_state != VDEV_STATE_HEALTHY)
872 return (SET_ERROR(ENXIO));
874 ASSERT3U(spa_guid(spa), !=, *newguid);
880 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
882 uint64_t *newguid = arg;
883 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
885 vdev_t *rvd = spa->spa_root_vdev;
887 oldguid = spa_guid(spa);
889 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
890 rvd->vdev_guid = *newguid;
891 rvd->vdev_guid_sum += (*newguid - oldguid);
892 vdev_config_dirty(rvd);
893 spa_config_exit(spa, SCL_STATE, FTAG);
895 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
900 * Change the GUID for the pool. This is done so that we can later
901 * re-import a pool built from a clone of our own vdevs. We will modify
902 * the root vdev's guid, our own pool guid, and then mark all of our
903 * vdevs dirty. Note that we must make sure that all our vdevs are
904 * online when we do this, or else any vdevs that weren't present
905 * would be orphaned from our pool. We are also going to issue a
906 * sysevent to update any watchers.
909 spa_change_guid(spa_t *spa)
914 mutex_enter(&spa->spa_vdev_top_lock);
915 mutex_enter(&spa_namespace_lock);
916 guid = spa_generate_guid(NULL);
918 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
919 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
922 spa_write_cachefile(spa, B_FALSE, B_TRUE);
923 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
926 mutex_exit(&spa_namespace_lock);
927 mutex_exit(&spa->spa_vdev_top_lock);
933 * ==========================================================================
934 * SPA state manipulation (open/create/destroy/import/export)
935 * ==========================================================================
939 spa_error_entry_compare(const void *a, const void *b)
941 const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
942 const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
945 ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
946 sizeof (zbookmark_phys_t));
948 return (AVL_ISIGN(ret));
952 * Utility function which retrieves copies of the current logs and
953 * re-initializes them in the process.
956 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
958 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
960 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
961 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
963 avl_create(&spa->spa_errlist_scrub,
964 spa_error_entry_compare, sizeof (spa_error_entry_t),
965 offsetof(spa_error_entry_t, se_avl));
966 avl_create(&spa->spa_errlist_last,
967 spa_error_entry_compare, sizeof (spa_error_entry_t),
968 offsetof(spa_error_entry_t, se_avl));
972 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
974 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
975 enum zti_modes mode = ztip->zti_mode;
976 uint_t value = ztip->zti_value;
977 uint_t count = ztip->zti_count;
978 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
981 boolean_t batch = B_FALSE;
983 if (mode == ZTI_MODE_NULL) {
985 tqs->stqs_taskq = NULL;
989 ASSERT3U(count, >, 0);
991 tqs->stqs_count = count;
992 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
996 ASSERT3U(value, >=, 1);
997 value = MAX(value, 1);
1000 case ZTI_MODE_BATCH:
1002 flags |= TASKQ_THREADS_CPU_PCT;
1003 value = zio_taskq_batch_pct;
1007 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
1009 zio_type_name[t], zio_taskq_types[q], mode, value);
1013 for (uint_t i = 0; i < count; i++) {
1017 (void) snprintf(name, sizeof (name), "%s_%s_%u",
1018 zio_type_name[t], zio_taskq_types[q], i);
1020 (void) snprintf(name, sizeof (name), "%s_%s",
1021 zio_type_name[t], zio_taskq_types[q]);
1025 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
1027 flags |= TASKQ_DC_BATCH;
1029 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
1030 spa->spa_proc, zio_taskq_basedc, flags);
1033 pri_t pri = maxclsyspri;
1035 * The write issue taskq can be extremely CPU
1036 * intensive. Run it at slightly lower priority
1037 * than the other taskqs.
1039 * - numerically higher priorities are lower priorities;
1040 * - if priorities divided by four (RQ_PPQ) are equal
1041 * then a difference between them is insignificant.
1043 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1050 tq = taskq_create_proc(name, value, pri, 50,
1051 INT_MAX, spa->spa_proc, flags);
1056 tqs->stqs_taskq[i] = tq;
1061 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1063 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1065 if (tqs->stqs_taskq == NULL) {
1066 ASSERT0(tqs->stqs_count);
1070 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1071 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1072 taskq_destroy(tqs->stqs_taskq[i]);
1075 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1076 tqs->stqs_taskq = NULL;
1080 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1081 * Note that a type may have multiple discrete taskqs to avoid lock contention
1082 * on the taskq itself. In that case we choose which taskq at random by using
1083 * the low bits of gethrtime().
1086 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1087 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1089 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1092 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1093 ASSERT3U(tqs->stqs_count, !=, 0);
1095 if (tqs->stqs_count == 1) {
1096 tq = tqs->stqs_taskq[0];
1099 tq = tqs->stqs_taskq[(u_int)(sbinuptime() + curcpu) %
1102 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1106 taskq_dispatch_ent(tq, func, arg, flags, ent);
1110 spa_create_zio_taskqs(spa_t *spa)
1112 for (int t = 0; t < ZIO_TYPES; t++) {
1113 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1114 spa_taskqs_init(spa, t, q);
1121 newproc(void (*pc)(void *), void *arg, id_t cid, int pri,
1122 void **ct, pid_t pid)
1125 spa_t *spa = (spa_t *)arg; /* XXX */
1132 ASSERT(cid == syscid);
1134 error = kproc_create(pc, arg, &newp, 0, 0, "zpool-%s", spa->spa_name);
1137 td = FIRST_THREAD_IN_PROC(newp);
1139 sched_prio(td, pri);
1145 spa_thread(void *arg)
1147 callb_cpr_t cprinfo;
1151 user_t *pu = PTOU(curproc);
1153 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1156 ASSERT(curproc != &p0);
1158 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1159 "zpool-%s", spa->spa_name);
1160 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1164 /* bind this thread to the requested psrset */
1165 if (zio_taskq_psrset_bind != PS_NONE) {
1167 mutex_enter(&cpu_lock);
1168 mutex_enter(&pidlock);
1169 mutex_enter(&curproc->p_lock);
1171 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1172 0, NULL, NULL) == 0) {
1173 curthread->t_bind_pset = zio_taskq_psrset_bind;
1176 "Couldn't bind process for zfs pool \"%s\" to "
1177 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1180 mutex_exit(&curproc->p_lock);
1181 mutex_exit(&pidlock);
1182 mutex_exit(&cpu_lock);
1188 if (zio_taskq_sysdc) {
1189 sysdc_thread_enter(curthread, 100, 0);
1193 spa->spa_proc = curproc;
1194 spa->spa_did = curthread->t_did;
1196 spa_create_zio_taskqs(spa);
1198 mutex_enter(&spa->spa_proc_lock);
1199 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1201 spa->spa_proc_state = SPA_PROC_ACTIVE;
1202 cv_broadcast(&spa->spa_proc_cv);
1204 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1205 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1206 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1207 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1209 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1210 spa->spa_proc_state = SPA_PROC_GONE;
1211 spa->spa_proc = &p0;
1212 cv_broadcast(&spa->spa_proc_cv);
1213 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1216 mutex_enter(&curproc->p_lock);
1222 #endif /* SPA_PROCESS */
1225 * Activate an uninitialized pool.
1228 spa_activate(spa_t *spa, int mode)
1230 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1232 spa->spa_state = POOL_STATE_ACTIVE;
1233 spa->spa_mode = mode;
1235 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1236 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1237 spa->spa_special_class = metaslab_class_create(spa, zfs_metaslab_ops);
1238 spa->spa_dedup_class = metaslab_class_create(spa, zfs_metaslab_ops);
1240 /* Try to create a covering process */
1241 mutex_enter(&spa->spa_proc_lock);
1242 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1243 ASSERT(spa->spa_proc == &p0);
1247 /* Only create a process if we're going to be around a while. */
1248 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1249 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1251 spa->spa_proc_state = SPA_PROC_CREATED;
1252 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1253 cv_wait(&spa->spa_proc_cv,
1254 &spa->spa_proc_lock);
1256 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1257 ASSERT(spa->spa_proc != &p0);
1258 ASSERT(spa->spa_did != 0);
1262 "Couldn't create process for zfs pool \"%s\"\n",
1267 #endif /* SPA_PROCESS */
1268 mutex_exit(&spa->spa_proc_lock);
1270 /* If we didn't create a process, we need to create our taskqs. */
1272 ASSERT(spa->spa_proc == &p0);
1273 #endif /* SPA_PROCESS */
1274 if (spa->spa_proc == &p0) {
1275 spa_create_zio_taskqs(spa);
1279 * Start TRIM thread.
1281 trim_thread_create(spa);
1283 for (size_t i = 0; i < TXG_SIZE; i++) {
1284 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL,
1288 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1289 offsetof(vdev_t, vdev_config_dirty_node));
1290 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1291 offsetof(objset_t, os_evicting_node));
1292 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1293 offsetof(vdev_t, vdev_state_dirty_node));
1295 txg_list_create(&spa->spa_vdev_txg_list, spa,
1296 offsetof(struct vdev, vdev_txg_node));
1298 avl_create(&spa->spa_errlist_scrub,
1299 spa_error_entry_compare, sizeof (spa_error_entry_t),
1300 offsetof(spa_error_entry_t, se_avl));
1301 avl_create(&spa->spa_errlist_last,
1302 spa_error_entry_compare, sizeof (spa_error_entry_t),
1303 offsetof(spa_error_entry_t, se_avl));
1307 * Opposite of spa_activate().
1310 spa_deactivate(spa_t *spa)
1312 ASSERT(spa->spa_sync_on == B_FALSE);
1313 ASSERT(spa->spa_dsl_pool == NULL);
1314 ASSERT(spa->spa_root_vdev == NULL);
1315 ASSERT(spa->spa_async_zio_root == NULL);
1316 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1319 * Stop TRIM thread in case spa_unload() wasn't called directly
1320 * before spa_deactivate().
1322 trim_thread_destroy(spa);
1324 spa_evicting_os_wait(spa);
1326 txg_list_destroy(&spa->spa_vdev_txg_list);
1328 list_destroy(&spa->spa_config_dirty_list);
1329 list_destroy(&spa->spa_evicting_os_list);
1330 list_destroy(&spa->spa_state_dirty_list);
1332 for (int t = 0; t < ZIO_TYPES; t++) {
1333 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1334 spa_taskqs_fini(spa, t, q);
1338 for (size_t i = 0; i < TXG_SIZE; i++) {
1339 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1340 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1341 spa->spa_txg_zio[i] = NULL;
1344 metaslab_class_destroy(spa->spa_normal_class);
1345 spa->spa_normal_class = NULL;
1347 metaslab_class_destroy(spa->spa_log_class);
1348 spa->spa_log_class = NULL;
1350 metaslab_class_destroy(spa->spa_special_class);
1351 spa->spa_special_class = NULL;
1353 metaslab_class_destroy(spa->spa_dedup_class);
1354 spa->spa_dedup_class = NULL;
1357 * If this was part of an import or the open otherwise failed, we may
1358 * still have errors left in the queues. Empty them just in case.
1360 spa_errlog_drain(spa);
1362 avl_destroy(&spa->spa_errlist_scrub);
1363 avl_destroy(&spa->spa_errlist_last);
1365 spa->spa_state = POOL_STATE_UNINITIALIZED;
1367 mutex_enter(&spa->spa_proc_lock);
1368 if (spa->spa_proc_state != SPA_PROC_NONE) {
1369 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1370 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1371 cv_broadcast(&spa->spa_proc_cv);
1372 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1373 ASSERT(spa->spa_proc != &p0);
1374 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1376 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1377 spa->spa_proc_state = SPA_PROC_NONE;
1379 ASSERT(spa->spa_proc == &p0);
1380 mutex_exit(&spa->spa_proc_lock);
1385 * We want to make sure spa_thread() has actually exited the ZFS
1386 * module, so that the module can't be unloaded out from underneath
1389 if (spa->spa_did != 0) {
1390 thread_join(spa->spa_did);
1394 #endif /* SPA_PROCESS */
1398 * Verify a pool configuration, and construct the vdev tree appropriately. This
1399 * will create all the necessary vdevs in the appropriate layout, with each vdev
1400 * in the CLOSED state. This will prep the pool before open/creation/import.
1401 * All vdev validation is done by the vdev_alloc() routine.
1404 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1405 uint_t id, int atype)
1411 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1414 if ((*vdp)->vdev_ops->vdev_op_leaf)
1417 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1420 if (error == ENOENT)
1426 return (SET_ERROR(EINVAL));
1429 for (int c = 0; c < children; c++) {
1431 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1439 ASSERT(*vdp != NULL);
1445 * Opposite of spa_load().
1448 spa_unload(spa_t *spa)
1452 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1454 spa_load_note(spa, "UNLOADING");
1459 trim_thread_destroy(spa);
1464 spa_async_suspend(spa);
1466 if (spa->spa_root_vdev) {
1467 vdev_initialize_stop_all(spa->spa_root_vdev,
1468 VDEV_INITIALIZE_ACTIVE);
1474 if (spa->spa_sync_on) {
1475 txg_sync_stop(spa->spa_dsl_pool);
1476 spa->spa_sync_on = B_FALSE;
1480 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1481 * to call it earlier, before we wait for async i/o to complete.
1482 * This ensures that there is no async metaslab prefetching, by
1483 * calling taskq_wait(mg_taskq).
1485 if (spa->spa_root_vdev != NULL) {
1486 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1487 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1488 vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1489 spa_config_exit(spa, SCL_ALL, spa);
1492 if (spa->spa_mmp.mmp_thread)
1493 mmp_thread_stop(spa);
1496 * Wait for any outstanding async I/O to complete.
1498 if (spa->spa_async_zio_root != NULL) {
1499 for (int i = 0; i < max_ncpus; i++)
1500 (void) zio_wait(spa->spa_async_zio_root[i]);
1501 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1502 spa->spa_async_zio_root = NULL;
1505 if (spa->spa_vdev_removal != NULL) {
1506 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1507 spa->spa_vdev_removal = NULL;
1510 if (spa->spa_condense_zthr != NULL) {
1511 zthr_destroy(spa->spa_condense_zthr);
1512 spa->spa_condense_zthr = NULL;
1515 if (spa->spa_checkpoint_discard_zthr != NULL) {
1516 zthr_destroy(spa->spa_checkpoint_discard_zthr);
1517 spa->spa_checkpoint_discard_zthr = NULL;
1520 spa_condense_fini(spa);
1522 bpobj_close(&spa->spa_deferred_bpobj);
1524 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1529 if (spa->spa_root_vdev)
1530 vdev_free(spa->spa_root_vdev);
1531 ASSERT(spa->spa_root_vdev == NULL);
1534 * Close the dsl pool.
1536 if (spa->spa_dsl_pool) {
1537 dsl_pool_close(spa->spa_dsl_pool);
1538 spa->spa_dsl_pool = NULL;
1539 spa->spa_meta_objset = NULL;
1545 * Drop and purge level 2 cache
1547 spa_l2cache_drop(spa);
1549 for (i = 0; i < spa->spa_spares.sav_count; i++)
1550 vdev_free(spa->spa_spares.sav_vdevs[i]);
1551 if (spa->spa_spares.sav_vdevs) {
1552 kmem_free(spa->spa_spares.sav_vdevs,
1553 spa->spa_spares.sav_count * sizeof (void *));
1554 spa->spa_spares.sav_vdevs = NULL;
1556 if (spa->spa_spares.sav_config) {
1557 nvlist_free(spa->spa_spares.sav_config);
1558 spa->spa_spares.sav_config = NULL;
1560 spa->spa_spares.sav_count = 0;
1562 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1563 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1564 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1566 if (spa->spa_l2cache.sav_vdevs) {
1567 kmem_free(spa->spa_l2cache.sav_vdevs,
1568 spa->spa_l2cache.sav_count * sizeof (void *));
1569 spa->spa_l2cache.sav_vdevs = NULL;
1571 if (spa->spa_l2cache.sav_config) {
1572 nvlist_free(spa->spa_l2cache.sav_config);
1573 spa->spa_l2cache.sav_config = NULL;
1575 spa->spa_l2cache.sav_count = 0;
1577 spa->spa_async_suspended = 0;
1579 spa->spa_indirect_vdevs_loaded = B_FALSE;
1581 if (spa->spa_comment != NULL) {
1582 spa_strfree(spa->spa_comment);
1583 spa->spa_comment = NULL;
1586 spa_config_exit(spa, SCL_ALL, spa);
1590 * Load (or re-load) the current list of vdevs describing the active spares for
1591 * this pool. When this is called, we have some form of basic information in
1592 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1593 * then re-generate a more complete list including status information.
1596 spa_load_spares(spa_t *spa)
1605 * zdb opens both the current state of the pool and the
1606 * checkpointed state (if present), with a different spa_t.
1608 * As spare vdevs are shared among open pools, we skip loading
1609 * them when we load the checkpointed state of the pool.
1611 if (!spa_writeable(spa))
1615 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1618 * First, close and free any existing spare vdevs.
1620 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1621 vd = spa->spa_spares.sav_vdevs[i];
1623 /* Undo the call to spa_activate() below */
1624 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1625 B_FALSE)) != NULL && tvd->vdev_isspare)
1626 spa_spare_remove(tvd);
1631 if (spa->spa_spares.sav_vdevs)
1632 kmem_free(spa->spa_spares.sav_vdevs,
1633 spa->spa_spares.sav_count * sizeof (void *));
1635 if (spa->spa_spares.sav_config == NULL)
1638 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1639 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1641 spa->spa_spares.sav_count = (int)nspares;
1642 spa->spa_spares.sav_vdevs = NULL;
1648 * Construct the array of vdevs, opening them to get status in the
1649 * process. For each spare, there is potentially two different vdev_t
1650 * structures associated with it: one in the list of spares (used only
1651 * for basic validation purposes) and one in the active vdev
1652 * configuration (if it's spared in). During this phase we open and
1653 * validate each vdev on the spare list. If the vdev also exists in the
1654 * active configuration, then we also mark this vdev as an active spare.
1656 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1658 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1659 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1660 VDEV_ALLOC_SPARE) == 0);
1663 spa->spa_spares.sav_vdevs[i] = vd;
1665 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1666 B_FALSE)) != NULL) {
1667 if (!tvd->vdev_isspare)
1671 * We only mark the spare active if we were successfully
1672 * able to load the vdev. Otherwise, importing a pool
1673 * with a bad active spare would result in strange
1674 * behavior, because multiple pool would think the spare
1675 * is actively in use.
1677 * There is a vulnerability here to an equally bizarre
1678 * circumstance, where a dead active spare is later
1679 * brought back to life (onlined or otherwise). Given
1680 * the rarity of this scenario, and the extra complexity
1681 * it adds, we ignore the possibility.
1683 if (!vdev_is_dead(tvd))
1684 spa_spare_activate(tvd);
1688 vd->vdev_aux = &spa->spa_spares;
1690 if (vdev_open(vd) != 0)
1693 if (vdev_validate_aux(vd) == 0)
1698 * Recompute the stashed list of spares, with status information
1701 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1702 DATA_TYPE_NVLIST_ARRAY) == 0);
1704 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1706 for (i = 0; i < spa->spa_spares.sav_count; i++)
1707 spares[i] = vdev_config_generate(spa,
1708 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1709 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1710 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1711 for (i = 0; i < spa->spa_spares.sav_count; i++)
1712 nvlist_free(spares[i]);
1713 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1717 * Load (or re-load) the current list of vdevs describing the active l2cache for
1718 * this pool. When this is called, we have some form of basic information in
1719 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1720 * then re-generate a more complete list including status information.
1721 * Devices which are already active have their details maintained, and are
1725 spa_load_l2cache(spa_t *spa)
1729 int i, j, oldnvdevs;
1731 vdev_t *vd, **oldvdevs, **newvdevs;
1732 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1736 * zdb opens both the current state of the pool and the
1737 * checkpointed state (if present), with a different spa_t.
1739 * As L2 caches are part of the ARC which is shared among open
1740 * pools, we skip loading them when we load the checkpointed
1741 * state of the pool.
1743 if (!spa_writeable(spa))
1747 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1749 if (sav->sav_config != NULL) {
1750 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1751 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1752 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1758 oldvdevs = sav->sav_vdevs;
1759 oldnvdevs = sav->sav_count;
1760 sav->sav_vdevs = NULL;
1764 * Process new nvlist of vdevs.
1766 for (i = 0; i < nl2cache; i++) {
1767 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1771 for (j = 0; j < oldnvdevs; j++) {
1773 if (vd != NULL && guid == vd->vdev_guid) {
1775 * Retain previous vdev for add/remove ops.
1783 if (newvdevs[i] == NULL) {
1787 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1788 VDEV_ALLOC_L2CACHE) == 0);
1793 * Commit this vdev as an l2cache device,
1794 * even if it fails to open.
1796 spa_l2cache_add(vd);
1801 spa_l2cache_activate(vd);
1803 if (vdev_open(vd) != 0)
1806 (void) vdev_validate_aux(vd);
1808 if (!vdev_is_dead(vd))
1809 l2arc_add_vdev(spa, vd);
1814 * Purge vdevs that were dropped
1816 for (i = 0; i < oldnvdevs; i++) {
1821 ASSERT(vd->vdev_isl2cache);
1823 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1824 pool != 0ULL && l2arc_vdev_present(vd))
1825 l2arc_remove_vdev(vd);
1826 vdev_clear_stats(vd);
1832 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1834 if (sav->sav_config == NULL)
1837 sav->sav_vdevs = newvdevs;
1838 sav->sav_count = (int)nl2cache;
1841 * Recompute the stashed list of l2cache devices, with status
1842 * information this time.
1844 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1845 DATA_TYPE_NVLIST_ARRAY) == 0);
1847 l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1848 for (i = 0; i < sav->sav_count; i++)
1849 l2cache[i] = vdev_config_generate(spa,
1850 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1851 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1852 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1854 for (i = 0; i < sav->sav_count; i++)
1855 nvlist_free(l2cache[i]);
1857 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1861 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1864 char *packed = NULL;
1869 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1873 nvsize = *(uint64_t *)db->db_data;
1874 dmu_buf_rele(db, FTAG);
1876 packed = kmem_alloc(nvsize, KM_SLEEP);
1877 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1880 error = nvlist_unpack(packed, nvsize, value, 0);
1881 kmem_free(packed, nvsize);
1887 * Concrete top-level vdevs that are not missing and are not logs. At every
1888 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1891 spa_healthy_core_tvds(spa_t *spa)
1893 vdev_t *rvd = spa->spa_root_vdev;
1896 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1897 vdev_t *vd = rvd->vdev_child[i];
1900 if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1908 * Checks to see if the given vdev could not be opened, in which case we post a
1909 * sysevent to notify the autoreplace code that the device has been removed.
1912 spa_check_removed(vdev_t *vd)
1914 for (uint64_t c = 0; c < vd->vdev_children; c++)
1915 spa_check_removed(vd->vdev_child[c]);
1917 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1918 vdev_is_concrete(vd)) {
1919 zfs_post_autoreplace(vd->vdev_spa, vd);
1920 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1925 spa_check_for_missing_logs(spa_t *spa)
1927 vdev_t *rvd = spa->spa_root_vdev;
1930 * If we're doing a normal import, then build up any additional
1931 * diagnostic information about missing log devices.
1932 * We'll pass this up to the user for further processing.
1934 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1935 nvlist_t **child, *nv;
1938 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1940 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1942 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1943 vdev_t *tvd = rvd->vdev_child[c];
1946 * We consider a device as missing only if it failed
1947 * to open (i.e. offline or faulted is not considered
1950 if (tvd->vdev_islog &&
1951 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1952 child[idx++] = vdev_config_generate(spa, tvd,
1953 B_FALSE, VDEV_CONFIG_MISSING);
1958 fnvlist_add_nvlist_array(nv,
1959 ZPOOL_CONFIG_CHILDREN, child, idx);
1960 fnvlist_add_nvlist(spa->spa_load_info,
1961 ZPOOL_CONFIG_MISSING_DEVICES, nv);
1963 for (uint64_t i = 0; i < idx; i++)
1964 nvlist_free(child[i]);
1967 kmem_free(child, rvd->vdev_children * sizeof (char **));
1970 spa_load_failed(spa, "some log devices are missing");
1971 vdev_dbgmsg_print_tree(rvd, 2);
1972 return (SET_ERROR(ENXIO));
1975 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1976 vdev_t *tvd = rvd->vdev_child[c];
1978 if (tvd->vdev_islog &&
1979 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1980 spa_set_log_state(spa, SPA_LOG_CLEAR);
1981 spa_load_note(spa, "some log devices are "
1982 "missing, ZIL is dropped.");
1983 vdev_dbgmsg_print_tree(rvd, 2);
1993 * Check for missing log devices
1996 spa_check_logs(spa_t *spa)
1998 boolean_t rv = B_FALSE;
1999 dsl_pool_t *dp = spa_get_dsl(spa);
2001 switch (spa->spa_log_state) {
2002 case SPA_LOG_MISSING:
2003 /* need to recheck in case slog has been restored */
2004 case SPA_LOG_UNKNOWN:
2005 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
2006 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
2008 spa_set_log_state(spa, SPA_LOG_MISSING);
2015 spa_passivate_log(spa_t *spa)
2017 vdev_t *rvd = spa->spa_root_vdev;
2018 boolean_t slog_found = B_FALSE;
2020 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
2022 if (!spa_has_slogs(spa))
2025 for (int c = 0; c < rvd->vdev_children; c++) {
2026 vdev_t *tvd = rvd->vdev_child[c];
2027 metaslab_group_t *mg = tvd->vdev_mg;
2029 if (tvd->vdev_islog) {
2030 metaslab_group_passivate(mg);
2031 slog_found = B_TRUE;
2035 return (slog_found);
2039 spa_activate_log(spa_t *spa)
2041 vdev_t *rvd = spa->spa_root_vdev;
2043 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
2045 for (int c = 0; c < rvd->vdev_children; c++) {
2046 vdev_t *tvd = rvd->vdev_child[c];
2047 metaslab_group_t *mg = tvd->vdev_mg;
2049 if (tvd->vdev_islog)
2050 metaslab_group_activate(mg);
2055 spa_reset_logs(spa_t *spa)
2059 error = dmu_objset_find(spa_name(spa), zil_reset,
2060 NULL, DS_FIND_CHILDREN);
2063 * We successfully offlined the log device, sync out the
2064 * current txg so that the "stubby" block can be removed
2067 txg_wait_synced(spa->spa_dsl_pool, 0);
2073 spa_aux_check_removed(spa_aux_vdev_t *sav)
2077 for (i = 0; i < sav->sav_count; i++)
2078 spa_check_removed(sav->sav_vdevs[i]);
2082 spa_claim_notify(zio_t *zio)
2084 spa_t *spa = zio->io_spa;
2089 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2090 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2091 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2092 mutex_exit(&spa->spa_props_lock);
2095 typedef struct spa_load_error {
2096 uint64_t sle_meta_count;
2097 uint64_t sle_data_count;
2101 spa_load_verify_done(zio_t *zio)
2103 blkptr_t *bp = zio->io_bp;
2104 spa_load_error_t *sle = zio->io_private;
2105 dmu_object_type_t type = BP_GET_TYPE(bp);
2106 int error = zio->io_error;
2107 spa_t *spa = zio->io_spa;
2109 abd_free(zio->io_abd);
2111 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
2112 type != DMU_OT_INTENT_LOG)
2113 atomic_inc_64(&sle->sle_meta_count);
2115 atomic_inc_64(&sle->sle_data_count);
2118 mutex_enter(&spa->spa_scrub_lock);
2119 spa->spa_load_verify_ios--;
2120 cv_broadcast(&spa->spa_scrub_io_cv);
2121 mutex_exit(&spa->spa_scrub_lock);
2125 * Maximum number of concurrent scrub i/os to create while verifying
2126 * a pool while importing it.
2128 int spa_load_verify_maxinflight = 10000;
2129 boolean_t spa_load_verify_metadata = B_TRUE;
2130 boolean_t spa_load_verify_data = B_TRUE;
2132 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_maxinflight, CTLFLAG_RWTUN,
2133 &spa_load_verify_maxinflight, 0,
2134 "Maximum number of concurrent scrub I/Os to create while verifying a "
2135 "pool while importing it");
2137 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_metadata, CTLFLAG_RWTUN,
2138 &spa_load_verify_metadata, 0,
2139 "Check metadata on import?");
2141 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_data, CTLFLAG_RWTUN,
2142 &spa_load_verify_data, 0,
2143 "Check user data on import?");
2147 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2148 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2150 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2153 * Note: normally this routine will not be called if
2154 * spa_load_verify_metadata is not set. However, it may be useful
2155 * to manually set the flag after the traversal has begun.
2157 if (!spa_load_verify_metadata)
2159 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2163 size_t size = BP_GET_PSIZE(bp);
2165 mutex_enter(&spa->spa_scrub_lock);
2166 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
2167 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2168 spa->spa_load_verify_ios++;
2169 mutex_exit(&spa->spa_scrub_lock);
2171 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2172 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2173 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2174 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2180 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2182 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2183 return (SET_ERROR(ENAMETOOLONG));
2189 spa_load_verify(spa_t *spa)
2192 spa_load_error_t sle = { 0 };
2193 zpool_load_policy_t policy;
2194 boolean_t verify_ok = B_FALSE;
2197 zpool_get_load_policy(spa->spa_config, &policy);
2199 if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2202 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2203 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2204 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2206 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2210 rio = zio_root(spa, NULL, &sle,
2211 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2213 if (spa_load_verify_metadata) {
2214 if (spa->spa_extreme_rewind) {
2215 spa_load_note(spa, "performing a complete scan of the "
2216 "pool since extreme rewind is on. This may take "
2217 "a very long time.\n (spa_load_verify_data=%u, "
2218 "spa_load_verify_metadata=%u)",
2219 spa_load_verify_data, spa_load_verify_metadata);
2221 error = traverse_pool(spa, spa->spa_verify_min_txg,
2222 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2223 spa_load_verify_cb, rio);
2226 (void) zio_wait(rio);
2228 spa->spa_load_meta_errors = sle.sle_meta_count;
2229 spa->spa_load_data_errors = sle.sle_data_count;
2231 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2232 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2233 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2234 (u_longlong_t)sle.sle_data_count);
2237 if (spa_load_verify_dryrun ||
2238 (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2239 sle.sle_data_count <= policy.zlp_maxdata)) {
2243 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2244 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2246 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2247 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2248 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2249 VERIFY(nvlist_add_int64(spa->spa_load_info,
2250 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2251 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2252 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2254 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2257 if (spa_load_verify_dryrun)
2261 if (error != ENXIO && error != EIO)
2262 error = SET_ERROR(EIO);
2266 return (verify_ok ? 0 : EIO);
2270 * Find a value in the pool props object.
2273 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2275 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2276 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2280 * Find a value in the pool directory object.
2283 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2285 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2286 name, sizeof (uint64_t), 1, val);
2288 if (error != 0 && (error != ENOENT || log_enoent)) {
2289 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2290 "[error=%d]", name, error);
2297 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2299 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2300 return (SET_ERROR(err));
2304 spa_spawn_aux_threads(spa_t *spa)
2306 ASSERT(spa_writeable(spa));
2308 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2310 spa_start_indirect_condensing_thread(spa);
2312 ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2313 spa->spa_checkpoint_discard_zthr =
2314 zthr_create(spa_checkpoint_discard_thread_check,
2315 spa_checkpoint_discard_thread, spa);
2319 * Fix up config after a partly-completed split. This is done with the
2320 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2321 * pool have that entry in their config, but only the splitting one contains
2322 * a list of all the guids of the vdevs that are being split off.
2324 * This function determines what to do with that list: either rejoin
2325 * all the disks to the pool, or complete the splitting process. To attempt
2326 * the rejoin, each disk that is offlined is marked online again, and
2327 * we do a reopen() call. If the vdev label for every disk that was
2328 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2329 * then we call vdev_split() on each disk, and complete the split.
2331 * Otherwise we leave the config alone, with all the vdevs in place in
2332 * the original pool.
2335 spa_try_repair(spa_t *spa, nvlist_t *config)
2342 boolean_t attempt_reopen;
2344 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2347 /* check that the config is complete */
2348 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2349 &glist, &gcount) != 0)
2352 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2354 /* attempt to online all the vdevs & validate */
2355 attempt_reopen = B_TRUE;
2356 for (i = 0; i < gcount; i++) {
2357 if (glist[i] == 0) /* vdev is hole */
2360 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2361 if (vd[i] == NULL) {
2363 * Don't bother attempting to reopen the disks;
2364 * just do the split.
2366 attempt_reopen = B_FALSE;
2368 /* attempt to re-online it */
2369 vd[i]->vdev_offline = B_FALSE;
2373 if (attempt_reopen) {
2374 vdev_reopen(spa->spa_root_vdev);
2376 /* check each device to see what state it's in */
2377 for (extracted = 0, i = 0; i < gcount; i++) {
2378 if (vd[i] != NULL &&
2379 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2386 * If every disk has been moved to the new pool, or if we never
2387 * even attempted to look at them, then we split them off for
2390 if (!attempt_reopen || gcount == extracted) {
2391 for (i = 0; i < gcount; i++)
2394 vdev_reopen(spa->spa_root_vdev);
2397 kmem_free(vd, gcount * sizeof (vdev_t *));
2401 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2403 char *ereport = FM_EREPORT_ZFS_POOL;
2406 spa->spa_load_state = state;
2408 gethrestime(&spa->spa_loaded_ts);
2409 error = spa_load_impl(spa, type, &ereport);
2412 * Don't count references from objsets that are already closed
2413 * and are making their way through the eviction process.
2415 spa_evicting_os_wait(spa);
2416 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
2418 if (error != EEXIST) {
2419 spa->spa_loaded_ts.tv_sec = 0;
2420 spa->spa_loaded_ts.tv_nsec = 0;
2422 if (error != EBADF) {
2423 zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2426 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2433 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2434 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2435 * spa's per-vdev ZAP list.
2438 vdev_count_verify_zaps(vdev_t *vd)
2440 spa_t *spa = vd->vdev_spa;
2442 if (vd->vdev_top_zap != 0) {
2444 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2445 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2447 if (vd->vdev_leaf_zap != 0) {
2449 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2450 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2453 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2454 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2461 * Determine whether the activity check is required.
2464 spa_activity_check_required(spa_t *spa, uberblock_t *ub, nvlist_t *label,
2468 uint64_t hostid = 0;
2469 uint64_t tryconfig_txg = 0;
2470 uint64_t tryconfig_timestamp = 0;
2471 uint16_t tryconfig_mmp_seq = 0;
2474 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2475 nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
2476 (void) nvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG,
2478 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
2479 &tryconfig_timestamp);
2480 (void) nvlist_lookup_uint16(nvinfo, ZPOOL_CONFIG_MMP_SEQ,
2481 &tryconfig_mmp_seq);
2484 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE, &state);
2487 * Disable the MMP activity check - This is used by zdb which
2488 * is intended to be used on potentially active pools.
2490 if (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP)
2494 * Skip the activity check when the MMP feature is disabled.
2496 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay == 0)
2500 * If the tryconfig_ values are nonzero, they are the results of an
2501 * earlier tryimport. If they all match the uberblock we just found,
2502 * then the pool has not changed and we return false so we do not test
2505 if (tryconfig_txg && tryconfig_txg == ub->ub_txg &&
2506 tryconfig_timestamp && tryconfig_timestamp == ub->ub_timestamp &&
2507 tryconfig_mmp_seq && tryconfig_mmp_seq ==
2508 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0))
2512 * Allow the activity check to be skipped when importing the pool
2513 * on the same host which last imported it. Since the hostid from
2514 * configuration may be stale use the one read from the label.
2516 if (nvlist_exists(label, ZPOOL_CONFIG_HOSTID))
2517 hostid = fnvlist_lookup_uint64(label, ZPOOL_CONFIG_HOSTID);
2519 if (hostid == spa_get_hostid())
2523 * Skip the activity test when the pool was cleanly exported.
2525 if (state != POOL_STATE_ACTIVE)
2532 * Nanoseconds the activity check must watch for changes on-disk.
2535 spa_activity_check_duration(spa_t *spa, uberblock_t *ub)
2537 uint64_t import_intervals = MAX(zfs_multihost_import_intervals, 1);
2538 uint64_t multihost_interval = MSEC2NSEC(
2539 MMP_INTERVAL_OK(zfs_multihost_interval));
2540 uint64_t import_delay = MAX(NANOSEC, import_intervals *
2541 multihost_interval);
2544 * Local tunables determine a minimum duration except for the case
2545 * where we know when the remote host will suspend the pool if MMP
2546 * writes do not land.
2548 * See Big Theory comment at the top of mmp.c for the reasoning behind
2549 * these cases and times.
2552 ASSERT(MMP_IMPORT_SAFETY_FACTOR >= 100);
2554 if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
2555 MMP_FAIL_INT(ub) > 0) {
2557 /* MMP on remote host will suspend pool after failed writes */
2558 import_delay = MMP_FAIL_INT(ub) * MSEC2NSEC(MMP_INTERVAL(ub)) *
2559 MMP_IMPORT_SAFETY_FACTOR / 100;
2561 zfs_dbgmsg("fail_intvals>0 import_delay=%llu ub_mmp "
2562 "mmp_fails=%llu ub_mmp mmp_interval=%llu "
2563 "import_intervals=%u", import_delay, MMP_FAIL_INT(ub),
2564 MMP_INTERVAL(ub), import_intervals);
2566 } else if (MMP_INTERVAL_VALID(ub) && MMP_FAIL_INT_VALID(ub) &&
2567 MMP_FAIL_INT(ub) == 0) {
2569 /* MMP on remote host will never suspend pool */
2570 import_delay = MAX(import_delay, (MSEC2NSEC(MMP_INTERVAL(ub)) +
2571 ub->ub_mmp_delay) * import_intervals);
2573 zfs_dbgmsg("fail_intvals=0 import_delay=%llu ub_mmp "
2574 "mmp_interval=%llu ub_mmp_delay=%llu "
2575 "import_intervals=%u", import_delay, MMP_INTERVAL(ub),
2576 ub->ub_mmp_delay, import_intervals);
2578 } else if (MMP_VALID(ub)) {
2580 * zfs-0.7 compatability case
2583 import_delay = MAX(import_delay, (multihost_interval +
2584 ub->ub_mmp_delay) * import_intervals);
2586 zfs_dbgmsg("import_delay=%llu ub_mmp_delay=%llu "
2587 "import_intervals=%u leaves=%u", import_delay,
2588 ub->ub_mmp_delay, import_intervals,
2589 vdev_count_leaves(spa));
2591 /* Using local tunings is the only reasonable option */
2592 zfs_dbgmsg("pool last imported on non-MMP aware "
2593 "host using import_delay=%llu multihost_interval=%llu "
2594 "import_intervals=%u", import_delay, multihost_interval,
2598 return (import_delay);
2602 * Perform the import activity check. If the user canceled the import or
2603 * we detected activity then fail.
2606 spa_activity_check(spa_t *spa, uberblock_t *ub, nvlist_t *config)
2608 uint64_t txg = ub->ub_txg;
2609 uint64_t timestamp = ub->ub_timestamp;
2610 uint64_t mmp_config = ub->ub_mmp_config;
2611 uint16_t mmp_seq = MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0;
2612 uint64_t import_delay;
2613 hrtime_t import_expire;
2614 nvlist_t *mmp_label = NULL;
2615 vdev_t *rvd = spa->spa_root_vdev;
2620 cv_init(&cv, NULL, CV_DEFAULT, NULL);
2621 mutex_init(&mtx, NULL, MUTEX_DEFAULT, NULL);
2625 * If ZPOOL_CONFIG_MMP_TXG is present an activity check was performed
2626 * during the earlier tryimport. If the txg recorded there is 0 then
2627 * the pool is known to be active on another host.
2629 * Otherwise, the pool might be in use on another host. Check for
2630 * changes in the uberblocks on disk if necessary.
2632 if (nvlist_exists(config, ZPOOL_CONFIG_LOAD_INFO)) {
2633 nvlist_t *nvinfo = fnvlist_lookup_nvlist(config,
2634 ZPOOL_CONFIG_LOAD_INFO);
2636 if (nvlist_exists(nvinfo, ZPOOL_CONFIG_MMP_TXG) &&
2637 fnvlist_lookup_uint64(nvinfo, ZPOOL_CONFIG_MMP_TXG) == 0) {
2638 vdev_uberblock_load(rvd, ub, &mmp_label);
2639 error = SET_ERROR(EREMOTEIO);
2644 import_delay = spa_activity_check_duration(spa, ub);
2646 /* Add a small random factor in case of simultaneous imports (0-25%) */
2647 import_delay += import_delay * spa_get_random(250) / 1000;
2649 import_expire = gethrtime() + import_delay;
2651 while (gethrtime() < import_expire) {
2652 vdev_uberblock_load(rvd, ub, &mmp_label);
2654 if (txg != ub->ub_txg || timestamp != ub->ub_timestamp ||
2655 mmp_seq != (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0)) {
2656 zfs_dbgmsg("multihost activity detected "
2657 "txg %llu ub_txg %llu "
2658 "timestamp %llu ub_timestamp %llu "
2659 "mmp_config %#llx ub_mmp_config %#llx",
2660 txg, ub->ub_txg, timestamp, ub->ub_timestamp,
2661 mmp_config, ub->ub_mmp_config);
2663 error = SET_ERROR(EREMOTEIO);
2668 nvlist_free(mmp_label);
2671 error = cv_timedwait_sig(&cv, &mtx, hz);
2672 #if defined(illumos) || !defined(_KERNEL)
2675 if (error != EWOULDBLOCK) {
2677 error = SET_ERROR(EINTR);
2685 mutex_destroy(&mtx);
2689 * If the pool is determined to be active store the status in the
2690 * spa->spa_load_info nvlist. If the remote hostname or hostid are
2691 * available from configuration read from disk store them as well.
2692 * This allows 'zpool import' to generate a more useful message.
2694 * ZPOOL_CONFIG_MMP_STATE - observed pool status (mandatory)
2695 * ZPOOL_CONFIG_MMP_HOSTNAME - hostname from the active pool
2696 * ZPOOL_CONFIG_MMP_HOSTID - hostid from the active pool
2698 if (error == EREMOTEIO) {
2699 char *hostname = "<unknown>";
2700 uint64_t hostid = 0;
2703 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTNAME)) {
2704 hostname = fnvlist_lookup_string(mmp_label,
2705 ZPOOL_CONFIG_HOSTNAME);
2706 fnvlist_add_string(spa->spa_load_info,
2707 ZPOOL_CONFIG_MMP_HOSTNAME, hostname);
2710 if (nvlist_exists(mmp_label, ZPOOL_CONFIG_HOSTID)) {
2711 hostid = fnvlist_lookup_uint64(mmp_label,
2712 ZPOOL_CONFIG_HOSTID);
2713 fnvlist_add_uint64(spa->spa_load_info,
2714 ZPOOL_CONFIG_MMP_HOSTID, hostid);
2718 fnvlist_add_uint64(spa->spa_load_info,
2719 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_ACTIVE);
2720 fnvlist_add_uint64(spa->spa_load_info,
2721 ZPOOL_CONFIG_MMP_TXG, 0);
2723 error = spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO);
2727 nvlist_free(mmp_label);
2733 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2737 uint64_t myhostid = 0;
2739 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2740 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2741 hostname = fnvlist_lookup_string(mos_config,
2742 ZPOOL_CONFIG_HOSTNAME);
2744 myhostid = zone_get_hostid(NULL);
2746 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2747 cmn_err(CE_WARN, "pool '%s' could not be "
2748 "loaded as it was last accessed by "
2749 "another system (host: %s hostid: 0x%llx). "
2750 "See: http://illumos.org/msg/ZFS-8000-EY",
2751 spa_name(spa), hostname, (u_longlong_t)hostid);
2752 spa_load_failed(spa, "hostid verification failed: pool "
2753 "last accessed by host: %s (hostid: 0x%llx)",
2754 hostname, (u_longlong_t)hostid);
2755 return (SET_ERROR(EBADF));
2763 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2766 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2773 * Versioning wasn't explicitly added to the label until later, so if
2774 * it's not present treat it as the initial version.
2776 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2777 &spa->spa_ubsync.ub_version) != 0)
2778 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2780 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2781 spa_load_failed(spa, "invalid config provided: '%s' missing",
2782 ZPOOL_CONFIG_POOL_GUID);
2783 return (SET_ERROR(EINVAL));
2787 * If we are doing an import, ensure that the pool is not already
2788 * imported by checking if its pool guid already exists in the
2791 * The only case that we allow an already imported pool to be
2792 * imported again, is when the pool is checkpointed and we want to
2793 * look at its checkpointed state from userland tools like zdb.
2796 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2797 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2798 spa_guid_exists(pool_guid, 0)) {
2800 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2801 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2802 spa_guid_exists(pool_guid, 0) &&
2803 !spa_importing_readonly_checkpoint(spa)) {
2805 spa_load_failed(spa, "a pool with guid %llu is already open",
2806 (u_longlong_t)pool_guid);
2807 return (SET_ERROR(EEXIST));
2810 spa->spa_config_guid = pool_guid;
2812 nvlist_free(spa->spa_load_info);
2813 spa->spa_load_info = fnvlist_alloc();
2815 ASSERT(spa->spa_comment == NULL);
2816 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2817 spa->spa_comment = spa_strdup(comment);
2819 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2820 &spa->spa_config_txg);
2822 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2823 spa->spa_config_splitting = fnvlist_dup(nvl);
2825 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2826 spa_load_failed(spa, "invalid config provided: '%s' missing",
2827 ZPOOL_CONFIG_VDEV_TREE);
2828 return (SET_ERROR(EINVAL));
2832 * Create "The Godfather" zio to hold all async IOs
2834 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2836 for (int i = 0; i < max_ncpus; i++) {
2837 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2838 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2839 ZIO_FLAG_GODFATHER);
2843 * Parse the configuration into a vdev tree. We explicitly set the
2844 * value that will be returned by spa_version() since parsing the
2845 * configuration requires knowing the version number.
2847 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2848 parse = (type == SPA_IMPORT_EXISTING ?
2849 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2850 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2851 spa_config_exit(spa, SCL_ALL, FTAG);
2854 spa_load_failed(spa, "unable to parse config [error=%d]",
2859 ASSERT(spa->spa_root_vdev == rvd);
2860 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2861 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2863 if (type != SPA_IMPORT_ASSEMBLE) {
2864 ASSERT(spa_guid(spa) == pool_guid);
2871 * Recursively open all vdevs in the vdev tree. This function is called twice:
2872 * first with the untrusted config, then with the trusted config.
2875 spa_ld_open_vdevs(spa_t *spa)
2880 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2881 * missing/unopenable for the root vdev to be still considered openable.
2883 if (spa->spa_trust_config) {
2884 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2885 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2886 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2887 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2888 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2890 spa->spa_missing_tvds_allowed = 0;
2893 spa->spa_missing_tvds_allowed =
2894 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2896 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2897 error = vdev_open(spa->spa_root_vdev);
2898 spa_config_exit(spa, SCL_ALL, FTAG);
2900 if (spa->spa_missing_tvds != 0) {
2901 spa_load_note(spa, "vdev tree has %lld missing top-level "
2902 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2903 if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2905 * Although theoretically we could allow users to open
2906 * incomplete pools in RW mode, we'd need to add a lot
2907 * of extra logic (e.g. adjust pool space to account
2908 * for missing vdevs).
2909 * This limitation also prevents users from accidentally
2910 * opening the pool in RW mode during data recovery and
2911 * damaging it further.
2913 spa_load_note(spa, "pools with missing top-level "
2914 "vdevs can only be opened in read-only mode.");
2915 error = SET_ERROR(ENXIO);
2917 spa_load_note(spa, "current settings allow for maximum "
2918 "%lld missing top-level vdevs at this stage.",
2919 (u_longlong_t)spa->spa_missing_tvds_allowed);
2923 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2926 if (spa->spa_missing_tvds != 0 || error != 0)
2927 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2933 * We need to validate the vdev labels against the configuration that
2934 * we have in hand. This function is called twice: first with an untrusted
2935 * config, then with a trusted config. The validation is more strict when the
2936 * config is trusted.
2939 spa_ld_validate_vdevs(spa_t *spa)
2942 vdev_t *rvd = spa->spa_root_vdev;
2944 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2945 error = vdev_validate(rvd);
2946 spa_config_exit(spa, SCL_ALL, FTAG);
2949 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2953 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2954 spa_load_failed(spa, "cannot open vdev tree after invalidating "
2956 vdev_dbgmsg_print_tree(rvd, 2);
2957 return (SET_ERROR(ENXIO));
2964 spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2966 spa->spa_state = POOL_STATE_ACTIVE;
2967 spa->spa_ubsync = spa->spa_uberblock;
2968 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2969 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2970 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2971 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2972 spa->spa_claim_max_txg = spa->spa_first_txg;
2973 spa->spa_prev_software_version = ub->ub_software_version;
2977 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2979 vdev_t *rvd = spa->spa_root_vdev;
2981 uberblock_t *ub = &spa->spa_uberblock;
2982 boolean_t activity_check = B_FALSE;
2985 * If we are opening the checkpointed state of the pool by
2986 * rewinding to it, at this point we will have written the
2987 * checkpointed uberblock to the vdev labels, so searching
2988 * the labels will find the right uberblock. However, if
2989 * we are opening the checkpointed state read-only, we have
2990 * not modified the labels. Therefore, we must ignore the
2991 * labels and continue using the spa_uberblock that was set
2992 * by spa_ld_checkpoint_rewind.
2994 * Note that it would be fine to ignore the labels when
2995 * rewinding (opening writeable) as well. However, if we
2996 * crash just after writing the labels, we will end up
2997 * searching the labels. Doing so in the common case means
2998 * that this code path gets exercised normally, rather than
2999 * just in the edge case.
3001 if (ub->ub_checkpoint_txg != 0 &&
3002 spa_importing_readonly_checkpoint(spa)) {
3003 spa_ld_select_uberblock_done(spa, ub);
3008 * Find the best uberblock.
3010 vdev_uberblock_load(rvd, ub, &label);
3013 * If we weren't able to find a single valid uberblock, return failure.
3015 if (ub->ub_txg == 0) {
3017 spa_load_failed(spa, "no valid uberblock found");
3018 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
3021 spa_load_note(spa, "using uberblock with txg=%llu",
3022 (u_longlong_t)ub->ub_txg);
3025 * For pools which have the multihost property on determine if the
3026 * pool is truly inactive and can be safely imported. Prevent
3027 * hosts which don't have a hostid set from importing the pool.
3029 activity_check = spa_activity_check_required(spa, ub, label,
3031 if (activity_check) {
3032 if (ub->ub_mmp_magic == MMP_MAGIC && ub->ub_mmp_delay &&
3033 spa_get_hostid() == 0) {
3035 fnvlist_add_uint64(spa->spa_load_info,
3036 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3037 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3040 int error = spa_activity_check(spa, ub, spa->spa_config);
3046 fnvlist_add_uint64(spa->spa_load_info,
3047 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_INACTIVE);
3048 fnvlist_add_uint64(spa->spa_load_info,
3049 ZPOOL_CONFIG_MMP_TXG, ub->ub_txg);
3050 fnvlist_add_uint16(spa->spa_load_info,
3051 ZPOOL_CONFIG_MMP_SEQ,
3052 (MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0));
3056 * If the pool has an unsupported version we can't open it.
3058 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
3060 spa_load_failed(spa, "version %llu is not supported",
3061 (u_longlong_t)ub->ub_version);
3062 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
3065 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3069 * If we weren't able to find what's necessary for reading the
3070 * MOS in the label, return failure.
3072 if (label == NULL) {
3073 spa_load_failed(spa, "label config unavailable");
3074 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3078 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
3081 spa_load_failed(spa, "invalid label: '%s' missing",
3082 ZPOOL_CONFIG_FEATURES_FOR_READ);
3083 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3088 * Update our in-core representation with the definitive values
3091 nvlist_free(spa->spa_label_features);
3092 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
3098 * Look through entries in the label nvlist's features_for_read. If
3099 * there is a feature listed there which we don't understand then we
3100 * cannot open a pool.
3102 if (ub->ub_version >= SPA_VERSION_FEATURES) {
3103 nvlist_t *unsup_feat;
3105 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
3108 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
3110 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
3111 if (!zfeature_is_supported(nvpair_name(nvp))) {
3112 VERIFY(nvlist_add_string(unsup_feat,
3113 nvpair_name(nvp), "") == 0);
3117 if (!nvlist_empty(unsup_feat)) {
3118 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
3119 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
3120 nvlist_free(unsup_feat);
3121 spa_load_failed(spa, "some features are unsupported");
3122 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3126 nvlist_free(unsup_feat);
3129 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
3130 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3131 spa_try_repair(spa, spa->spa_config);
3132 spa_config_exit(spa, SCL_ALL, FTAG);
3133 nvlist_free(spa->spa_config_splitting);
3134 spa->spa_config_splitting = NULL;
3138 * Initialize internal SPA structures.
3140 spa_ld_select_uberblock_done(spa, ub);
3146 spa_ld_open_rootbp(spa_t *spa)
3149 vdev_t *rvd = spa->spa_root_vdev;
3151 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
3153 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
3154 "[error=%d]", error);
3155 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3157 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
3163 spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
3164 boolean_t reloading)
3166 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
3167 nvlist_t *nv, *mos_config, *policy;
3168 int error = 0, copy_error;
3169 uint64_t healthy_tvds, healthy_tvds_mos;
3170 uint64_t mos_config_txg;
3172 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
3174 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3177 * If we're assembling a pool from a split, the config provided is
3178 * already trusted so there is nothing to do.
3180 if (type == SPA_IMPORT_ASSEMBLE)
3183 healthy_tvds = spa_healthy_core_tvds(spa);
3185 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
3187 spa_load_failed(spa, "unable to retrieve MOS config");
3188 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3192 * If we are doing an open, pool owner wasn't verified yet, thus do
3193 * the verification here.
3195 if (spa->spa_load_state == SPA_LOAD_OPEN) {
3196 error = spa_verify_host(spa, mos_config);
3198 nvlist_free(mos_config);
3203 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
3205 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3208 * Build a new vdev tree from the trusted config
3210 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
3213 * Vdev paths in the MOS may be obsolete. If the untrusted config was
3214 * obtained by scanning /dev/dsk, then it will have the right vdev
3215 * paths. We update the trusted MOS config with this information.
3216 * We first try to copy the paths with vdev_copy_path_strict, which
3217 * succeeds only when both configs have exactly the same vdev tree.
3218 * If that fails, we fall back to a more flexible method that has a
3219 * best effort policy.
3221 copy_error = vdev_copy_path_strict(rvd, mrvd);
3222 if (copy_error != 0 || spa_load_print_vdev_tree) {
3223 spa_load_note(spa, "provided vdev tree:");
3224 vdev_dbgmsg_print_tree(rvd, 2);
3225 spa_load_note(spa, "MOS vdev tree:");
3226 vdev_dbgmsg_print_tree(mrvd, 2);
3228 if (copy_error != 0) {
3229 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
3230 "back to vdev_copy_path_relaxed");
3231 vdev_copy_path_relaxed(rvd, mrvd);
3236 spa->spa_root_vdev = mrvd;
3238 spa_config_exit(spa, SCL_ALL, FTAG);
3241 * We will use spa_config if we decide to reload the spa or if spa_load
3242 * fails and we rewind. We must thus regenerate the config using the
3243 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
3244 * pass settings on how to load the pool and is not stored in the MOS.
3245 * We copy it over to our new, trusted config.
3247 mos_config_txg = fnvlist_lookup_uint64(mos_config,
3248 ZPOOL_CONFIG_POOL_TXG);
3249 nvlist_free(mos_config);
3250 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
3251 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
3253 fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
3254 spa_config_set(spa, mos_config);
3255 spa->spa_config_source = SPA_CONFIG_SRC_MOS;
3258 * Now that we got the config from the MOS, we should be more strict
3259 * in checking blkptrs and can make assumptions about the consistency
3260 * of the vdev tree. spa_trust_config must be set to true before opening
3261 * vdevs in order for them to be writeable.
3263 spa->spa_trust_config = B_TRUE;
3266 * Open and validate the new vdev tree
3268 error = spa_ld_open_vdevs(spa);
3272 error = spa_ld_validate_vdevs(spa);
3276 if (copy_error != 0 || spa_load_print_vdev_tree) {
3277 spa_load_note(spa, "final vdev tree:");
3278 vdev_dbgmsg_print_tree(rvd, 2);
3281 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
3282 !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
3284 * Sanity check to make sure that we are indeed loading the
3285 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
3286 * in the config provided and they happened to be the only ones
3287 * to have the latest uberblock, we could involuntarily perform
3288 * an extreme rewind.
3290 healthy_tvds_mos = spa_healthy_core_tvds(spa);
3291 if (healthy_tvds_mos - healthy_tvds >=
3292 SPA_SYNC_MIN_VDEVS) {
3293 spa_load_note(spa, "config provided misses too many "
3294 "top-level vdevs compared to MOS (%lld vs %lld). ",
3295 (u_longlong_t)healthy_tvds,
3296 (u_longlong_t)healthy_tvds_mos);
3297 spa_load_note(spa, "vdev tree:");
3298 vdev_dbgmsg_print_tree(rvd, 2);
3300 spa_load_failed(spa, "config was already "
3301 "provided from MOS. Aborting.");
3302 return (spa_vdev_err(rvd,
3303 VDEV_AUX_CORRUPT_DATA, EIO));
3305 spa_load_note(spa, "spa must be reloaded using MOS "
3307 return (SET_ERROR(EAGAIN));
3311 error = spa_check_for_missing_logs(spa);
3313 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
3315 if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
3316 spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
3317 "guid sum (%llu != %llu)",
3318 (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
3319 (u_longlong_t)rvd->vdev_guid_sum);
3320 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
3328 spa_ld_open_indirect_vdev_metadata(spa_t *spa)
3331 vdev_t *rvd = spa->spa_root_vdev;
3334 * Everything that we read before spa_remove_init() must be stored
3335 * on concreted vdevs. Therefore we do this as early as possible.
3337 error = spa_remove_init(spa);
3339 spa_load_failed(spa, "spa_remove_init failed [error=%d]",
3341 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3345 * Retrieve information needed to condense indirect vdev mappings.
3347 error = spa_condense_init(spa);
3349 spa_load_failed(spa, "spa_condense_init failed [error=%d]",
3351 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3358 spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
3361 vdev_t *rvd = spa->spa_root_vdev;
3363 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
3364 boolean_t missing_feat_read = B_FALSE;
3365 nvlist_t *unsup_feat, *enabled_feat;
3367 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
3368 &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
3369 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3372 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
3373 &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
3374 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3377 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
3378 &spa->spa_feat_desc_obj, B_TRUE) != 0) {
3379 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3382 enabled_feat = fnvlist_alloc();
3383 unsup_feat = fnvlist_alloc();
3385 if (!spa_features_check(spa, B_FALSE,
3386 unsup_feat, enabled_feat))
3387 missing_feat_read = B_TRUE;
3389 if (spa_writeable(spa) ||
3390 spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3391 if (!spa_features_check(spa, B_TRUE,
3392 unsup_feat, enabled_feat)) {
3393 *missing_feat_writep = B_TRUE;
3397 fnvlist_add_nvlist(spa->spa_load_info,
3398 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3400 if (!nvlist_empty(unsup_feat)) {
3401 fnvlist_add_nvlist(spa->spa_load_info,
3402 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3405 fnvlist_free(enabled_feat);
3406 fnvlist_free(unsup_feat);
3408 if (!missing_feat_read) {
3409 fnvlist_add_boolean(spa->spa_load_info,
3410 ZPOOL_CONFIG_CAN_RDONLY);
3414 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3415 * twofold: to determine whether the pool is available for
3416 * import in read-write mode and (if it is not) whether the
3417 * pool is available for import in read-only mode. If the pool
3418 * is available for import in read-write mode, it is displayed
3419 * as available in userland; if it is not available for import
3420 * in read-only mode, it is displayed as unavailable in
3421 * userland. If the pool is available for import in read-only
3422 * mode but not read-write mode, it is displayed as unavailable
3423 * in userland with a special note that the pool is actually
3424 * available for open in read-only mode.
3426 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3427 * missing a feature for write, we must first determine whether
3428 * the pool can be opened read-only before returning to
3429 * userland in order to know whether to display the
3430 * abovementioned note.
3432 if (missing_feat_read || (*missing_feat_writep &&
3433 spa_writeable(spa))) {
3434 spa_load_failed(spa, "pool uses unsupported features");
3435 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3440 * Load refcounts for ZFS features from disk into an in-memory
3441 * cache during SPA initialization.
3443 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
3446 error = feature_get_refcount_from_disk(spa,
3447 &spa_feature_table[i], &refcount);
3449 spa->spa_feat_refcount_cache[i] = refcount;
3450 } else if (error == ENOTSUP) {
3451 spa->spa_feat_refcount_cache[i] =
3452 SPA_FEATURE_DISABLED;
3454 spa_load_failed(spa, "error getting refcount "
3455 "for feature %s [error=%d]",
3456 spa_feature_table[i].fi_guid, error);
3457 return (spa_vdev_err(rvd,
3458 VDEV_AUX_CORRUPT_DATA, EIO));
3463 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3464 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
3465 &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
3466 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3473 spa_ld_load_special_directories(spa_t *spa)
3476 vdev_t *rvd = spa->spa_root_vdev;
3478 spa->spa_is_initializing = B_TRUE;
3479 error = dsl_pool_open(spa->spa_dsl_pool);
3480 spa->spa_is_initializing = B_FALSE;
3482 spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3483 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3490 spa_ld_get_props(spa_t *spa)
3494 vdev_t *rvd = spa->spa_root_vdev;
3496 /* Grab the secret checksum salt from the MOS. */
3497 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3498 DMU_POOL_CHECKSUM_SALT, 1,
3499 sizeof (spa->spa_cksum_salt.zcs_bytes),
3500 spa->spa_cksum_salt.zcs_bytes);
3501 if (error == ENOENT) {
3502 /* Generate a new salt for subsequent use */
3503 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3504 sizeof (spa->spa_cksum_salt.zcs_bytes));
3505 } else if (error != 0) {
3506 spa_load_failed(spa, "unable to retrieve checksum salt from "
3507 "MOS [error=%d]", error);
3508 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3511 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3512 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3513 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3515 spa_load_failed(spa, "error opening deferred-frees bpobj "
3516 "[error=%d]", error);
3517 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3521 * Load the bit that tells us to use the new accounting function
3522 * (raid-z deflation). If we have an older pool, this will not
3525 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3526 if (error != 0 && error != ENOENT)
3527 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3529 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3530 &spa->spa_creation_version, B_FALSE);
3531 if (error != 0 && error != ENOENT)
3532 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3535 * Load the persistent error log. If we have an older pool, this will
3538 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3540 if (error != 0 && error != ENOENT)
3541 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3543 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3544 &spa->spa_errlog_scrub, B_FALSE);
3545 if (error != 0 && error != ENOENT)
3546 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3549 * Load the history object. If we have an older pool, this
3550 * will not be present.
3552 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3553 if (error != 0 && error != ENOENT)
3554 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3557 * Load the per-vdev ZAP map. If we have an older pool, this will not
3558 * be present; in this case, defer its creation to a later time to
3559 * avoid dirtying the MOS this early / out of sync context. See
3560 * spa_sync_config_object.
3563 /* The sentinel is only available in the MOS config. */
3564 nvlist_t *mos_config;
3565 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3566 spa_load_failed(spa, "unable to retrieve MOS config");
3567 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3570 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3571 &spa->spa_all_vdev_zaps, B_FALSE);
3573 if (error == ENOENT) {
3574 VERIFY(!nvlist_exists(mos_config,
3575 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3576 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3577 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3578 } else if (error != 0) {
3579 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3580 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3582 * An older version of ZFS overwrote the sentinel value, so
3583 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3584 * destruction to later; see spa_sync_config_object.
3586 spa->spa_avz_action = AVZ_ACTION_DESTROY;
3588 * We're assuming that no vdevs have had their ZAPs created
3589 * before this. Better be sure of it.
3591 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3593 nvlist_free(mos_config);
3595 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3597 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3599 if (error && error != ENOENT)
3600 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3603 uint64_t autoreplace;
3605 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3606 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3607 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3608 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3609 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3610 spa_prop_find(spa, ZPOOL_PROP_MULTIHOST, &spa->spa_multihost);
3611 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3612 &spa->spa_dedup_ditto);
3614 spa->spa_autoreplace = (autoreplace != 0);
3618 * If we are importing a pool with missing top-level vdevs,
3619 * we enforce that the pool doesn't panic or get suspended on
3620 * error since the likelihood of missing data is extremely high.
3622 if (spa->spa_missing_tvds > 0 &&
3623 spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3624 spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3625 spa_load_note(spa, "forcing failmode to 'continue' "
3626 "as some top level vdevs are missing");
3627 spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3634 spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3637 vdev_t *rvd = spa->spa_root_vdev;
3640 * If we're assembling the pool from the split-off vdevs of
3641 * an existing pool, we don't want to attach the spares & cache
3646 * Load any hot spares for this pool.
3648 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3650 if (error != 0 && error != ENOENT)
3651 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3652 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3653 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3654 if (load_nvlist(spa, spa->spa_spares.sav_object,
3655 &spa->spa_spares.sav_config) != 0) {
3656 spa_load_failed(spa, "error loading spares nvlist");
3657 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3660 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3661 spa_load_spares(spa);
3662 spa_config_exit(spa, SCL_ALL, FTAG);
3663 } else if (error == 0) {
3664 spa->spa_spares.sav_sync = B_TRUE;
3668 * Load any level 2 ARC devices for this pool.
3670 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3671 &spa->spa_l2cache.sav_object, B_FALSE);
3672 if (error != 0 && error != ENOENT)
3673 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3674 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3675 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3676 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3677 &spa->spa_l2cache.sav_config) != 0) {
3678 spa_load_failed(spa, "error loading l2cache nvlist");
3679 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3682 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3683 spa_load_l2cache(spa);
3684 spa_config_exit(spa, SCL_ALL, FTAG);
3685 } else if (error == 0) {
3686 spa->spa_l2cache.sav_sync = B_TRUE;
3693 spa_ld_load_vdev_metadata(spa_t *spa)
3696 vdev_t *rvd = spa->spa_root_vdev;
3699 * If the 'multihost' property is set, then never allow a pool to
3700 * be imported when the system hostid is zero. The exception to
3701 * this rule is zdb which is always allowed to access pools.
3703 if (spa_multihost(spa) && spa_get_hostid() == 0 &&
3704 (spa->spa_import_flags & ZFS_IMPORT_SKIP_MMP) == 0) {
3705 fnvlist_add_uint64(spa->spa_load_info,
3706 ZPOOL_CONFIG_MMP_STATE, MMP_STATE_NO_HOSTID);
3707 return (spa_vdev_err(rvd, VDEV_AUX_ACTIVE, EREMOTEIO));
3711 * If the 'autoreplace' property is set, then post a resource notifying
3712 * the ZFS DE that it should not issue any faults for unopenable
3713 * devices. We also iterate over the vdevs, and post a sysevent for any
3714 * unopenable vdevs so that the normal autoreplace handler can take
3717 if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3718 spa_check_removed(spa->spa_root_vdev);
3720 * For the import case, this is done in spa_import(), because
3721 * at this point we're using the spare definitions from
3722 * the MOS config, not necessarily from the userland config.
3724 if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3725 spa_aux_check_removed(&spa->spa_spares);
3726 spa_aux_check_removed(&spa->spa_l2cache);
3731 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3733 error = vdev_load(rvd);
3735 spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3736 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3740 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3742 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3743 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3744 spa_config_exit(spa, SCL_ALL, FTAG);
3750 spa_ld_load_dedup_tables(spa_t *spa)
3753 vdev_t *rvd = spa->spa_root_vdev;
3755 error = ddt_load(spa);
3757 spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3758 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3765 spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3767 vdev_t *rvd = spa->spa_root_vdev;
3769 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3770 boolean_t missing = spa_check_logs(spa);
3772 if (spa->spa_missing_tvds != 0) {
3773 spa_load_note(spa, "spa_check_logs failed "
3774 "so dropping the logs");
3776 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3777 spa_load_failed(spa, "spa_check_logs failed");
3778 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3788 spa_ld_verify_pool_data(spa_t *spa)
3791 vdev_t *rvd = spa->spa_root_vdev;
3794 * We've successfully opened the pool, verify that we're ready
3795 * to start pushing transactions.
3797 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3798 error = spa_load_verify(spa);
3800 spa_load_failed(spa, "spa_load_verify failed "
3801 "[error=%d]", error);
3802 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3811 spa_ld_claim_log_blocks(spa_t *spa)
3814 dsl_pool_t *dp = spa_get_dsl(spa);
3817 * Claim log blocks that haven't been committed yet.
3818 * This must all happen in a single txg.
3819 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3820 * invoked from zil_claim_log_block()'s i/o done callback.
3821 * Price of rollback is that we abandon the log.
3823 spa->spa_claiming = B_TRUE;
3825 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3826 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3827 zil_claim, tx, DS_FIND_CHILDREN);
3830 spa->spa_claiming = B_FALSE;
3832 spa_set_log_state(spa, SPA_LOG_GOOD);
3836 spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3837 boolean_t update_config_cache)
3839 vdev_t *rvd = spa->spa_root_vdev;
3840 int need_update = B_FALSE;
3843 * If the config cache is stale, or we have uninitialized
3844 * metaslabs (see spa_vdev_add()), then update the config.
3846 * If this is a verbatim import, trust the current
3847 * in-core spa_config and update the disk labels.
3849 if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
3850 spa->spa_load_state == SPA_LOAD_IMPORT ||
3851 spa->spa_load_state == SPA_LOAD_RECOVER ||
3852 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3853 need_update = B_TRUE;
3855 for (int c = 0; c < rvd->vdev_children; c++)
3856 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3857 need_update = B_TRUE;
3860 * Update the config cache asychronously in case we're the
3861 * root pool, in which case the config cache isn't writable yet.
3864 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3868 spa_ld_prepare_for_reload(spa_t *spa)
3870 int mode = spa->spa_mode;
3871 int async_suspended = spa->spa_async_suspended;
3874 spa_deactivate(spa);
3875 spa_activate(spa, mode);
3878 * We save the value of spa_async_suspended as it gets reset to 0 by
3879 * spa_unload(). We want to restore it back to the original value before
3880 * returning as we might be calling spa_async_resume() later.
3882 spa->spa_async_suspended = async_suspended;
3886 spa_ld_read_checkpoint_txg(spa_t *spa)
3888 uberblock_t checkpoint;
3891 ASSERT0(spa->spa_checkpoint_txg);
3892 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3894 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3895 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3896 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3898 if (error == ENOENT)
3904 ASSERT3U(checkpoint.ub_txg, !=, 0);
3905 ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3906 ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3907 spa->spa_checkpoint_txg = checkpoint.ub_txg;
3908 spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3914 spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
3918 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3919 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3922 * Never trust the config that is provided unless we are assembling
3923 * a pool following a split.
3924 * This means don't trust blkptrs and the vdev tree in general. This
3925 * also effectively puts the spa in read-only mode since
3926 * spa_writeable() checks for spa_trust_config to be true.
3927 * We will later load a trusted config from the MOS.
3929 if (type != SPA_IMPORT_ASSEMBLE)
3930 spa->spa_trust_config = B_FALSE;
3933 * Parse the config provided to create a vdev tree.
3935 error = spa_ld_parse_config(spa, type);
3940 * Now that we have the vdev tree, try to open each vdev. This involves
3941 * opening the underlying physical device, retrieving its geometry and
3942 * probing the vdev with a dummy I/O. The state of each vdev will be set
3943 * based on the success of those operations. After this we'll be ready
3944 * to read from the vdevs.
3946 error = spa_ld_open_vdevs(spa);
3951 * Read the label of each vdev and make sure that the GUIDs stored
3952 * there match the GUIDs in the config provided.
3953 * If we're assembling a new pool that's been split off from an
3954 * existing pool, the labels haven't yet been updated so we skip
3955 * validation for now.
3957 if (type != SPA_IMPORT_ASSEMBLE) {
3958 error = spa_ld_validate_vdevs(spa);
3964 * Read all vdev labels to find the best uberblock (i.e. latest,
3965 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3966 * get the list of features required to read blkptrs in the MOS from
3967 * the vdev label with the best uberblock and verify that our version
3968 * of zfs supports them all.
3970 error = spa_ld_select_uberblock(spa, type);
3975 * Pass that uberblock to the dsl_pool layer which will open the root
3976 * blkptr. This blkptr points to the latest version of the MOS and will
3977 * allow us to read its contents.
3979 error = spa_ld_open_rootbp(spa);
3987 spa_ld_checkpoint_rewind(spa_t *spa)
3989 uberblock_t checkpoint;
3992 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3993 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3995 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3996 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3997 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
4000 spa_load_failed(spa, "unable to retrieve checkpointed "
4001 "uberblock from the MOS config [error=%d]", error);
4003 if (error == ENOENT)
4004 error = ZFS_ERR_NO_CHECKPOINT;
4009 ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
4010 ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
4013 * We need to update the txg and timestamp of the checkpointed
4014 * uberblock to be higher than the latest one. This ensures that
4015 * the checkpointed uberblock is selected if we were to close and
4016 * reopen the pool right after we've written it in the vdev labels.
4017 * (also see block comment in vdev_uberblock_compare)
4019 checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
4020 checkpoint.ub_timestamp = gethrestime_sec();
4023 * Set current uberblock to be the checkpointed uberblock.
4025 spa->spa_uberblock = checkpoint;
4028 * If we are doing a normal rewind, then the pool is open for
4029 * writing and we sync the "updated" checkpointed uberblock to
4030 * disk. Once this is done, we've basically rewound the whole
4031 * pool and there is no way back.
4033 * There are cases when we don't want to attempt and sync the
4034 * checkpointed uberblock to disk because we are opening a
4035 * pool as read-only. Specifically, verifying the checkpointed
4036 * state with zdb, and importing the checkpointed state to get
4037 * a "preview" of its content.
4039 if (spa_writeable(spa)) {
4040 vdev_t *rvd = spa->spa_root_vdev;
4042 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4043 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
4045 int children = rvd->vdev_children;
4046 int c0 = spa_get_random(children);
4048 for (int c = 0; c < children; c++) {
4049 vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
4051 /* Stop when revisiting the first vdev */
4052 if (c > 0 && svd[0] == vd)
4055 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
4056 !vdev_is_concrete(vd))
4059 svd[svdcount++] = vd;
4060 if (svdcount == SPA_SYNC_MIN_VDEVS)
4063 error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
4065 spa->spa_last_synced_guid = rvd->vdev_guid;
4066 spa_config_exit(spa, SCL_ALL, FTAG);
4069 spa_load_failed(spa, "failed to write checkpointed "
4070 "uberblock to the vdev labels [error=%d]", error);
4079 spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
4080 boolean_t *update_config_cache)
4085 * Parse the config for pool, open and validate vdevs,
4086 * select an uberblock, and use that uberblock to open
4089 error = spa_ld_mos_init(spa, type);
4094 * Retrieve the trusted config stored in the MOS and use it to create
4095 * a new, exact version of the vdev tree, then reopen all vdevs.
4097 error = spa_ld_trusted_config(spa, type, B_FALSE);
4098 if (error == EAGAIN) {
4099 if (update_config_cache != NULL)
4100 *update_config_cache = B_TRUE;
4103 * Redo the loading process with the trusted config if it is
4104 * too different from the untrusted config.
4106 spa_ld_prepare_for_reload(spa);
4107 spa_load_note(spa, "RELOADING");
4108 error = spa_ld_mos_init(spa, type);
4112 error = spa_ld_trusted_config(spa, type, B_TRUE);
4116 } else if (error != 0) {
4124 * Load an existing storage pool, using the config provided. This config
4125 * describes which vdevs are part of the pool and is later validated against
4126 * partial configs present in each vdev's label and an entire copy of the
4127 * config stored in the MOS.
4130 spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
4133 boolean_t missing_feat_write = B_FALSE;
4134 boolean_t checkpoint_rewind =
4135 (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4136 boolean_t update_config_cache = B_FALSE;
4138 ASSERT(MUTEX_HELD(&spa_namespace_lock));
4139 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
4141 spa_load_note(spa, "LOADING");
4143 error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
4148 * If we are rewinding to the checkpoint then we need to repeat
4149 * everything we've done so far in this function but this time
4150 * selecting the checkpointed uberblock and using that to open
4153 if (checkpoint_rewind) {
4155 * If we are rewinding to the checkpoint update config cache
4158 update_config_cache = B_TRUE;
4161 * Extract the checkpointed uberblock from the current MOS
4162 * and use this as the pool's uberblock from now on. If the
4163 * pool is imported as writeable we also write the checkpoint
4164 * uberblock to the labels, making the rewind permanent.
4166 error = spa_ld_checkpoint_rewind(spa);
4171 * Redo the loading process process again with the
4172 * checkpointed uberblock.
4174 spa_ld_prepare_for_reload(spa);
4175 spa_load_note(spa, "LOADING checkpointed uberblock");
4176 error = spa_ld_mos_with_trusted_config(spa, type, NULL);
4182 * Retrieve the checkpoint txg if the pool has a checkpoint.
4184 error = spa_ld_read_checkpoint_txg(spa);
4189 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
4190 * from the pool and their contents were re-mapped to other vdevs. Note
4191 * that everything that we read before this step must have been
4192 * rewritten on concrete vdevs after the last device removal was
4193 * initiated. Otherwise we could be reading from indirect vdevs before
4194 * we have loaded their mappings.
4196 error = spa_ld_open_indirect_vdev_metadata(spa);
4201 * Retrieve the full list of active features from the MOS and check if
4202 * they are all supported.
4204 error = spa_ld_check_features(spa, &missing_feat_write);
4209 * Load several special directories from the MOS needed by the dsl_pool
4212 error = spa_ld_load_special_directories(spa);
4217 * Retrieve pool properties from the MOS.
4219 error = spa_ld_get_props(spa);
4224 * Retrieve the list of auxiliary devices - cache devices and spares -
4227 error = spa_ld_open_aux_vdevs(spa, type);
4232 * Load the metadata for all vdevs. Also check if unopenable devices
4233 * should be autoreplaced.
4235 error = spa_ld_load_vdev_metadata(spa);
4239 error = spa_ld_load_dedup_tables(spa);
4244 * Verify the logs now to make sure we don't have any unexpected errors
4245 * when we claim log blocks later.
4247 error = spa_ld_verify_logs(spa, type, ereport);
4251 if (missing_feat_write) {
4252 ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
4255 * At this point, we know that we can open the pool in
4256 * read-only mode but not read-write mode. We now have enough
4257 * information and can return to userland.
4259 return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
4264 * Traverse the last txgs to make sure the pool was left off in a safe
4265 * state. When performing an extreme rewind, we verify the whole pool,
4266 * which can take a very long time.
4268 error = spa_ld_verify_pool_data(spa);
4273 * Calculate the deflated space for the pool. This must be done before
4274 * we write anything to the pool because we'd need to update the space
4275 * accounting using the deflated sizes.
4277 spa_update_dspace(spa);
4280 * We have now retrieved all the information we needed to open the
4281 * pool. If we are importing the pool in read-write mode, a few
4282 * additional steps must be performed to finish the import.
4284 if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
4285 spa->spa_load_max_txg == UINT64_MAX)) {
4286 uint64_t config_cache_txg = spa->spa_config_txg;
4288 ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
4291 * In case of a checkpoint rewind, log the original txg
4292 * of the checkpointed uberblock.
4294 if (checkpoint_rewind) {
4295 spa_history_log_internal(spa, "checkpoint rewind",
4296 NULL, "rewound state to txg=%llu",
4297 (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
4301 * Traverse the ZIL and claim all blocks.
4303 spa_ld_claim_log_blocks(spa);
4306 * Kick-off the syncing thread.
4308 spa->spa_sync_on = B_TRUE;
4309 txg_sync_start(spa->spa_dsl_pool);
4310 mmp_thread_start(spa);
4313 * Wait for all claims to sync. We sync up to the highest
4314 * claimed log block birth time so that claimed log blocks
4315 * don't appear to be from the future. spa_claim_max_txg
4316 * will have been set for us by ZIL traversal operations
4319 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
4322 * Check if we need to request an update of the config. On the
4323 * next sync, we would update the config stored in vdev labels
4324 * and the cachefile (by default /etc/zfs/zpool.cache).
4326 spa_ld_check_for_config_update(spa, config_cache_txg,
4327 update_config_cache);
4330 * Check all DTLs to see if anything needs resilvering.
4332 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
4333 vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
4334 spa_async_request(spa, SPA_ASYNC_RESILVER);
4337 * Log the fact that we booted up (so that we can detect if
4338 * we rebooted in the middle of an operation).
4340 spa_history_log_version(spa, "open");
4342 spa_restart_removal(spa);
4343 spa_spawn_aux_threads(spa);
4346 * Delete any inconsistent datasets.
4349 * Since we may be issuing deletes for clones here,
4350 * we make sure to do so after we've spawned all the
4351 * auxiliary threads above (from which the livelist
4352 * deletion zthr is part of).
4354 (void) dmu_objset_find(spa_name(spa),
4355 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
4358 * Clean up any stale temporary dataset userrefs.
4360 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
4362 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4363 vdev_initialize_restart(spa->spa_root_vdev);
4364 spa_config_exit(spa, SCL_CONFIG, FTAG);
4367 spa_load_note(spa, "LOADED");
4373 spa_load_retry(spa_t *spa, spa_load_state_t state)
4375 int mode = spa->spa_mode;
4378 spa_deactivate(spa);
4380 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
4382 spa_activate(spa, mode);
4383 spa_async_suspend(spa);
4385 spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
4386 (u_longlong_t)spa->spa_load_max_txg);
4388 return (spa_load(spa, state, SPA_IMPORT_EXISTING));
4392 * If spa_load() fails this function will try loading prior txg's. If
4393 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
4394 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
4395 * function will not rewind the pool and will return the same error as
4399 spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4402 nvlist_t *loadinfo = NULL;
4403 nvlist_t *config = NULL;
4404 int load_error, rewind_error;
4405 uint64_t safe_rewind_txg;
4408 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4409 spa->spa_load_max_txg = spa->spa_load_txg;
4410 spa_set_log_state(spa, SPA_LOG_CLEAR);
4412 spa->spa_load_max_txg = max_request;
4413 if (max_request != UINT64_MAX)
4414 spa->spa_extreme_rewind = B_TRUE;
4417 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
4418 if (load_error == 0)
4420 if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4422 * When attempting checkpoint-rewind on a pool with no
4423 * checkpoint, we should not attempt to load uberblocks
4424 * from previous txgs when spa_load fails.
4426 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4427 return (load_error);
4430 if (spa->spa_root_vdev != NULL)
4431 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4433 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4434 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4436 if (rewind_flags & ZPOOL_NEVER_REWIND) {
4437 nvlist_free(config);
4438 return (load_error);
4441 if (state == SPA_LOAD_RECOVER) {
4442 /* Price of rolling back is discarding txgs, including log */
4443 spa_set_log_state(spa, SPA_LOG_CLEAR);
4446 * If we aren't rolling back save the load info from our first
4447 * import attempt so that we can restore it after attempting
4450 loadinfo = spa->spa_load_info;
4451 spa->spa_load_info = fnvlist_alloc();
4454 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4455 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4456 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4457 TXG_INITIAL : safe_rewind_txg;
4460 * Continue as long as we're finding errors, we're still within
4461 * the acceptable rewind range, and we're still finding uberblocks
4463 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4464 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4465 if (spa->spa_load_max_txg < safe_rewind_txg)
4466 spa->spa_extreme_rewind = B_TRUE;
4467 rewind_error = spa_load_retry(spa, state);
4470 spa->spa_extreme_rewind = B_FALSE;
4471 spa->spa_load_max_txg = UINT64_MAX;
4473 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4474 spa_config_set(spa, config);
4476 nvlist_free(config);
4478 if (state == SPA_LOAD_RECOVER) {
4479 ASSERT3P(loadinfo, ==, NULL);
4480 return (rewind_error);
4482 /* Store the rewind info as part of the initial load info */
4483 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4484 spa->spa_load_info);
4486 /* Restore the initial load info */
4487 fnvlist_free(spa->spa_load_info);
4488 spa->spa_load_info = loadinfo;
4490 return (load_error);
4497 * The import case is identical to an open except that the configuration is sent
4498 * down from userland, instead of grabbed from the configuration cache. For the
4499 * case of an open, the pool configuration will exist in the
4500 * POOL_STATE_UNINITIALIZED state.
4502 * The stats information (gen/count/ustats) is used to gather vdev statistics at
4503 * the same time open the pool, without having to keep around the spa_t in some
4507 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4511 spa_load_state_t state = SPA_LOAD_OPEN;
4513 int locked = B_FALSE;
4514 int firstopen = B_FALSE;
4519 * As disgusting as this is, we need to support recursive calls to this
4520 * function because dsl_dir_open() is called during spa_load(), and ends
4521 * up calling spa_open() again. The real fix is to figure out how to
4522 * avoid dsl_dir_open() calling this in the first place.
4524 if (mutex_owner(&spa_namespace_lock) != curthread) {
4525 mutex_enter(&spa_namespace_lock);
4529 if ((spa = spa_lookup(pool)) == NULL) {
4531 mutex_exit(&spa_namespace_lock);
4532 return (SET_ERROR(ENOENT));
4535 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
4536 zpool_load_policy_t policy;
4540 zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
4542 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
4543 state = SPA_LOAD_RECOVER;
4545 spa_activate(spa, spa_mode_global);
4547 if (state != SPA_LOAD_RECOVER)
4548 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4549 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
4551 zfs_dbgmsg("spa_open_common: opening %s", pool);
4552 error = spa_load_best(spa, state, policy.zlp_txg,
4555 if (error == EBADF) {
4557 * If vdev_validate() returns failure (indicated by
4558 * EBADF), it indicates that one of the vdevs indicates
4559 * that the pool has been exported or destroyed. If
4560 * this is the case, the config cache is out of sync and
4561 * we should remove the pool from the namespace.
4564 spa_deactivate(spa);
4565 spa_write_cachefile(spa, B_TRUE, B_TRUE);
4568 mutex_exit(&spa_namespace_lock);
4569 return (SET_ERROR(ENOENT));
4574 * We can't open the pool, but we still have useful
4575 * information: the state of each vdev after the
4576 * attempted vdev_open(). Return this to the user.
4578 if (config != NULL && spa->spa_config) {
4579 VERIFY(nvlist_dup(spa->spa_config, config,
4581 VERIFY(nvlist_add_nvlist(*config,
4582 ZPOOL_CONFIG_LOAD_INFO,
4583 spa->spa_load_info) == 0);
4586 spa_deactivate(spa);
4587 spa->spa_last_open_failed = error;
4589 mutex_exit(&spa_namespace_lock);
4595 spa_open_ref(spa, tag);
4598 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4601 * If we've recovered the pool, pass back any information we
4602 * gathered while doing the load.
4604 if (state == SPA_LOAD_RECOVER) {
4605 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4606 spa->spa_load_info) == 0);
4610 spa->spa_last_open_failed = 0;
4611 spa->spa_last_ubsync_txg = 0;
4612 spa->spa_load_txg = 0;
4613 mutex_exit(&spa_namespace_lock);
4617 zvol_create_minors(spa->spa_name);
4628 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4631 return (spa_open_common(name, spapp, tag, policy, config));
4635 spa_open(const char *name, spa_t **spapp, void *tag)
4637 return (spa_open_common(name, spapp, tag, NULL, NULL));
4641 * Lookup the given spa_t, incrementing the inject count in the process,
4642 * preventing it from being exported or destroyed.
4645 spa_inject_addref(char *name)
4649 mutex_enter(&spa_namespace_lock);
4650 if ((spa = spa_lookup(name)) == NULL) {
4651 mutex_exit(&spa_namespace_lock);
4654 spa->spa_inject_ref++;
4655 mutex_exit(&spa_namespace_lock);
4661 spa_inject_delref(spa_t *spa)
4663 mutex_enter(&spa_namespace_lock);
4664 spa->spa_inject_ref--;
4665 mutex_exit(&spa_namespace_lock);
4669 * Add spares device information to the nvlist.
4672 spa_add_spares(spa_t *spa, nvlist_t *config)
4682 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4684 if (spa->spa_spares.sav_count == 0)
4687 VERIFY(nvlist_lookup_nvlist(config,
4688 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4689 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4690 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4692 VERIFY(nvlist_add_nvlist_array(nvroot,
4693 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4694 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4695 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4698 * Go through and find any spares which have since been
4699 * repurposed as an active spare. If this is the case, update
4700 * their status appropriately.
4702 for (i = 0; i < nspares; i++) {
4703 VERIFY(nvlist_lookup_uint64(spares[i],
4704 ZPOOL_CONFIG_GUID, &guid) == 0);
4705 if (spa_spare_exists(guid, &pool, NULL) &&
4707 VERIFY(nvlist_lookup_uint64_array(
4708 spares[i], ZPOOL_CONFIG_VDEV_STATS,
4709 (uint64_t **)&vs, &vsc) == 0);
4710 vs->vs_state = VDEV_STATE_CANT_OPEN;
4711 vs->vs_aux = VDEV_AUX_SPARED;
4718 * Add l2cache device information to the nvlist, including vdev stats.
4721 spa_add_l2cache(spa_t *spa, nvlist_t *config)
4724 uint_t i, j, nl2cache;
4731 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4733 if (spa->spa_l2cache.sav_count == 0)
4736 VERIFY(nvlist_lookup_nvlist(config,
4737 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4738 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4739 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4740 if (nl2cache != 0) {
4741 VERIFY(nvlist_add_nvlist_array(nvroot,
4742 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4743 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4744 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4747 * Update level 2 cache device stats.
4750 for (i = 0; i < nl2cache; i++) {
4751 VERIFY(nvlist_lookup_uint64(l2cache[i],
4752 ZPOOL_CONFIG_GUID, &guid) == 0);
4755 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4757 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4758 vd = spa->spa_l2cache.sav_vdevs[j];
4764 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4765 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4767 vdev_get_stats(vd, vs);
4773 spa_feature_stats_from_disk(spa_t *spa, nvlist_t *features)
4778 /* We may be unable to read features if pool is suspended. */
4779 if (spa_suspended(spa))
4782 if (spa->spa_feat_for_read_obj != 0) {
4783 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4784 spa->spa_feat_for_read_obj);
4785 zap_cursor_retrieve(&zc, &za) == 0;
4786 zap_cursor_advance(&zc)) {
4787 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4788 za.za_num_integers == 1);
4789 VERIFY0(nvlist_add_uint64(features, za.za_name,
4790 za.za_first_integer));
4792 zap_cursor_fini(&zc);
4795 if (spa->spa_feat_for_write_obj != 0) {
4796 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4797 spa->spa_feat_for_write_obj);
4798 zap_cursor_retrieve(&zc, &za) == 0;
4799 zap_cursor_advance(&zc)) {
4800 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4801 za.za_num_integers == 1);
4802 VERIFY0(nvlist_add_uint64(features, za.za_name,
4803 za.za_first_integer));
4805 zap_cursor_fini(&zc);
4810 spa_feature_stats_from_cache(spa_t *spa, nvlist_t *features)
4814 for (i = 0; i < SPA_FEATURES; i++) {
4815 zfeature_info_t feature = spa_feature_table[i];
4818 if (feature_get_refcount(spa, &feature, &refcount) != 0)
4821 VERIFY0(nvlist_add_uint64(features, feature.fi_guid, refcount));
4826 * Store a list of pool features and their reference counts in the
4829 * The first time this is called on a spa, allocate a new nvlist, fetch
4830 * the pool features and reference counts from disk, then save the list
4831 * in the spa. In subsequent calls on the same spa use the saved nvlist
4832 * and refresh its values from the cached reference counts. This
4833 * ensures we don't block here on I/O on a suspended pool so 'zpool
4834 * clear' can resume the pool.
4837 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4841 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4843 mutex_enter(&spa->spa_feat_stats_lock);
4844 features = spa->spa_feat_stats;
4846 if (features != NULL) {
4847 spa_feature_stats_from_cache(spa, features);
4849 VERIFY0(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP));
4850 spa->spa_feat_stats = features;
4851 spa_feature_stats_from_disk(spa, features);
4854 VERIFY0(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4857 mutex_exit(&spa->spa_feat_stats_lock);
4861 spa_get_stats(const char *name, nvlist_t **config,
4862 char *altroot, size_t buflen)
4868 error = spa_open_common(name, &spa, FTAG, NULL, config);
4872 * This still leaves a window of inconsistency where the spares
4873 * or l2cache devices could change and the config would be
4874 * self-inconsistent.
4876 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4878 if (*config != NULL) {
4879 uint64_t loadtimes[2];
4881 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4882 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4883 VERIFY(nvlist_add_uint64_array(*config,
4884 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4886 VERIFY(nvlist_add_uint64(*config,
4887 ZPOOL_CONFIG_ERRCOUNT,
4888 spa_get_errlog_size(spa)) == 0);
4890 if (spa_suspended(spa)) {
4891 VERIFY(nvlist_add_uint64(*config,
4892 ZPOOL_CONFIG_SUSPENDED,
4893 spa->spa_failmode) == 0);
4894 VERIFY(nvlist_add_uint64(*config,
4895 ZPOOL_CONFIG_SUSPENDED_REASON,
4896 spa->spa_suspended) == 0);
4899 spa_add_spares(spa, *config);
4900 spa_add_l2cache(spa, *config);
4901 spa_add_feature_stats(spa, *config);
4906 * We want to get the alternate root even for faulted pools, so we cheat
4907 * and call spa_lookup() directly.
4911 mutex_enter(&spa_namespace_lock);
4912 spa = spa_lookup(name);
4914 spa_altroot(spa, altroot, buflen);
4918 mutex_exit(&spa_namespace_lock);
4920 spa_altroot(spa, altroot, buflen);
4925 spa_config_exit(spa, SCL_CONFIG, FTAG);
4926 spa_close(spa, FTAG);
4933 * Validate that the auxiliary device array is well formed. We must have an
4934 * array of nvlists, each which describes a valid leaf vdev. If this is an
4935 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4936 * specified, as long as they are well-formed.
4939 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4940 spa_aux_vdev_t *sav, const char *config, uint64_t version,
4941 vdev_labeltype_t label)
4948 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4951 * It's acceptable to have no devs specified.
4953 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4957 return (SET_ERROR(EINVAL));
4960 * Make sure the pool is formatted with a version that supports this
4963 if (spa_version(spa) < version)
4964 return (SET_ERROR(ENOTSUP));
4967 * Set the pending device list so we correctly handle device in-use
4970 sav->sav_pending = dev;
4971 sav->sav_npending = ndev;
4973 for (i = 0; i < ndev; i++) {
4974 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4978 if (!vd->vdev_ops->vdev_op_leaf) {
4980 error = SET_ERROR(EINVAL);
4986 if ((error = vdev_open(vd)) == 0 &&
4987 (error = vdev_label_init(vd, crtxg, label)) == 0) {
4988 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4989 vd->vdev_guid) == 0);
4995 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
5002 sav->sav_pending = NULL;
5003 sav->sav_npending = 0;
5008 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
5012 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5014 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
5015 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
5016 VDEV_LABEL_SPARE)) != 0) {
5020 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
5021 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
5022 VDEV_LABEL_L2CACHE));
5026 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
5031 if (sav->sav_config != NULL) {
5037 * Generate new dev list by concatentating with the
5040 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
5041 &olddevs, &oldndevs) == 0);
5043 newdevs = kmem_alloc(sizeof (void *) *
5044 (ndevs + oldndevs), KM_SLEEP);
5045 for (i = 0; i < oldndevs; i++)
5046 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
5048 for (i = 0; i < ndevs; i++)
5049 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
5052 VERIFY(nvlist_remove(sav->sav_config, config,
5053 DATA_TYPE_NVLIST_ARRAY) == 0);
5055 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
5056 config, newdevs, ndevs + oldndevs) == 0);
5057 for (i = 0; i < oldndevs + ndevs; i++)
5058 nvlist_free(newdevs[i]);
5059 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
5062 * Generate a new dev list.
5064 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
5066 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
5072 * Stop and drop level 2 ARC devices
5075 spa_l2cache_drop(spa_t *spa)
5079 spa_aux_vdev_t *sav = &spa->spa_l2cache;
5081 for (i = 0; i < sav->sav_count; i++) {
5084 vd = sav->sav_vdevs[i];
5087 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
5088 pool != 0ULL && l2arc_vdev_present(vd))
5089 l2arc_remove_vdev(vd);
5097 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
5101 char *altroot = NULL;
5106 uint64_t txg = TXG_INITIAL;
5107 nvlist_t **spares, **l2cache;
5108 uint_t nspares, nl2cache;
5109 uint64_t version, obj;
5110 boolean_t has_features;
5114 if (props == NULL ||
5115 nvlist_lookup_string(props,
5116 zpool_prop_to_name(ZPOOL_PROP_TNAME), &poolname) != 0)
5117 poolname = (char *)pool;
5120 * If this pool already exists, return failure.
5122 mutex_enter(&spa_namespace_lock);
5123 if (spa_lookup(poolname) != NULL) {
5124 mutex_exit(&spa_namespace_lock);
5125 return (SET_ERROR(EEXIST));
5129 * Allocate a new spa_t structure.
5131 nvl = fnvlist_alloc();
5132 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
5133 (void) nvlist_lookup_string(props,
5134 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5135 spa = spa_add(poolname, nvl, altroot);
5137 spa_activate(spa, spa_mode_global);
5139 if (props && (error = spa_prop_validate(spa, props))) {
5140 spa_deactivate(spa);
5142 mutex_exit(&spa_namespace_lock);
5147 * Temporary pool names should never be written to disk.
5149 if (poolname != pool)
5150 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
5152 has_features = B_FALSE;
5153 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
5154 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
5155 if (zpool_prop_feature(nvpair_name(elem)))
5156 has_features = B_TRUE;
5159 if (has_features || nvlist_lookup_uint64(props,
5160 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
5161 version = SPA_VERSION;
5163 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
5165 spa->spa_first_txg = txg;
5166 spa->spa_uberblock.ub_txg = txg - 1;
5167 spa->spa_uberblock.ub_version = version;
5168 spa->spa_ubsync = spa->spa_uberblock;
5169 spa->spa_load_state = SPA_LOAD_CREATE;
5170 spa->spa_removing_phys.sr_state = DSS_NONE;
5171 spa->spa_removing_phys.sr_removing_vdev = -1;
5172 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
5173 spa->spa_indirect_vdevs_loaded = B_TRUE;
5176 * Create "The Godfather" zio to hold all async IOs
5178 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
5180 for (int i = 0; i < max_ncpus; i++) {
5181 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
5182 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
5183 ZIO_FLAG_GODFATHER);
5187 * Create the root vdev.
5189 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5191 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
5193 ASSERT(error != 0 || rvd != NULL);
5194 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
5196 if (error == 0 && !zfs_allocatable_devs(nvroot))
5197 error = SET_ERROR(EINVAL);
5200 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
5201 (error = spa_validate_aux(spa, nvroot, txg,
5202 VDEV_ALLOC_ADD)) == 0) {
5204 * instantiate the metaslab groups (this will dirty the vdevs)
5205 * we can no longer error exit past this point
5207 for (int c = 0; error == 0 && c < rvd->vdev_children; c++) {
5208 vdev_t *vd = rvd->vdev_child[c];
5210 vdev_ashift_optimize(vd);
5211 vdev_metaslab_set_size(vd);
5212 vdev_expand(vd, txg);
5216 spa_config_exit(spa, SCL_ALL, FTAG);
5220 spa_deactivate(spa);
5222 mutex_exit(&spa_namespace_lock);
5227 * Get the list of spares, if specified.
5229 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5230 &spares, &nspares) == 0) {
5231 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
5233 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5234 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5235 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5236 spa_load_spares(spa);
5237 spa_config_exit(spa, SCL_ALL, FTAG);
5238 spa->spa_spares.sav_sync = B_TRUE;
5242 * Get the list of level 2 cache devices, if specified.
5244 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5245 &l2cache, &nl2cache) == 0) {
5246 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5247 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5248 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5249 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5250 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5251 spa_load_l2cache(spa);
5252 spa_config_exit(spa, SCL_ALL, FTAG);
5253 spa->spa_l2cache.sav_sync = B_TRUE;
5256 spa->spa_is_initializing = B_TRUE;
5257 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
5258 spa->spa_meta_objset = dp->dp_meta_objset;
5259 spa->spa_is_initializing = B_FALSE;
5262 * Create DDTs (dedup tables).
5266 spa_update_dspace(spa);
5268 tx = dmu_tx_create_assigned(dp, txg);
5271 * Create the pool config object.
5273 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
5274 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
5275 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
5277 if (zap_add(spa->spa_meta_objset,
5278 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
5279 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
5280 cmn_err(CE_PANIC, "failed to add pool config");
5283 if (spa_version(spa) >= SPA_VERSION_FEATURES)
5284 spa_feature_create_zap_objects(spa, tx);
5286 if (zap_add(spa->spa_meta_objset,
5287 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
5288 sizeof (uint64_t), 1, &version, tx) != 0) {
5289 cmn_err(CE_PANIC, "failed to add pool version");
5292 /* Newly created pools with the right version are always deflated. */
5293 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
5294 spa->spa_deflate = TRUE;
5295 if (zap_add(spa->spa_meta_objset,
5296 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
5297 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
5298 cmn_err(CE_PANIC, "failed to add deflate");
5303 * Create the deferred-free bpobj. Turn off compression
5304 * because sync-to-convergence takes longer if the blocksize
5307 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
5308 dmu_object_set_compress(spa->spa_meta_objset, obj,
5309 ZIO_COMPRESS_OFF, tx);
5310 if (zap_add(spa->spa_meta_objset,
5311 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
5312 sizeof (uint64_t), 1, &obj, tx) != 0) {
5313 cmn_err(CE_PANIC, "failed to add bpobj");
5315 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
5316 spa->spa_meta_objset, obj));
5319 * Create the pool's history object.
5321 if (version >= SPA_VERSION_ZPOOL_HISTORY)
5322 spa_history_create_obj(spa, tx);
5325 * Generate some random noise for salted checksums to operate on.
5327 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
5328 sizeof (spa->spa_cksum_salt.zcs_bytes));
5331 * Set pool properties.
5333 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
5334 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
5335 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
5336 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
5337 spa->spa_multihost = zpool_prop_default_numeric(ZPOOL_PROP_MULTIHOST);
5339 if (props != NULL) {
5340 spa_configfile_set(spa, props, B_FALSE);
5341 spa_sync_props(props, tx);
5346 spa->spa_sync_on = B_TRUE;
5347 txg_sync_start(spa->spa_dsl_pool);
5348 mmp_thread_start(spa);
5351 * We explicitly wait for the first transaction to complete so that our
5352 * bean counters are appropriately updated.
5354 txg_wait_synced(spa->spa_dsl_pool, txg);
5356 spa_spawn_aux_threads(spa);
5358 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5359 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
5361 spa_history_log_version(spa, "create");
5364 * Don't count references from objsets that are already closed
5365 * and are making their way through the eviction process.
5367 spa_evicting_os_wait(spa);
5368 spa->spa_minref = zfs_refcount_count(&spa->spa_refcount);
5369 spa->spa_load_state = SPA_LOAD_NONE;
5371 mutex_exit(&spa_namespace_lock);
5379 * Get the root pool information from the root disk, then import the root pool
5380 * during the system boot up time.
5382 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
5385 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
5388 nvlist_t *nvtop, *nvroot;
5391 if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
5395 * Add this top-level vdev to the child array.
5397 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5399 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5401 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
5404 * Put this pool's top-level vdevs into a root vdev.
5406 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5407 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5408 VDEV_TYPE_ROOT) == 0);
5409 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5410 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5411 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5415 * Replace the existing vdev_tree with the new root vdev in
5416 * this pool's configuration (remove the old, add the new).
5418 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5419 nvlist_free(nvroot);
5424 * Walk the vdev tree and see if we can find a device with "better"
5425 * configuration. A configuration is "better" if the label on that
5426 * device has a more recent txg.
5429 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
5431 for (int c = 0; c < vd->vdev_children; c++)
5432 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
5434 if (vd->vdev_ops->vdev_op_leaf) {
5438 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
5442 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
5446 * Do we have a better boot device?
5448 if (label_txg > *txg) {
5457 * Import a root pool.
5459 * For x86. devpath_list will consist of devid and/or physpath name of
5460 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
5461 * The GRUB "findroot" command will return the vdev we should boot.
5463 * For Sparc, devpath_list consists the physpath name of the booting device
5464 * no matter the rootpool is a single device pool or a mirrored pool.
5466 * "/pci@1f,0/ide@d/disk@0,0:a"
5469 spa_import_rootpool(char *devpath, char *devid)
5472 vdev_t *rvd, *bvd, *avd = NULL;
5473 nvlist_t *config, *nvtop;
5479 * Read the label from the boot device and generate a configuration.
5481 config = spa_generate_rootconf(devpath, devid, &guid);
5482 #if defined(_OBP) && defined(_KERNEL)
5483 if (config == NULL) {
5484 if (strstr(devpath, "/iscsi/ssd") != NULL) {
5486 get_iscsi_bootpath_phy(devpath);
5487 config = spa_generate_rootconf(devpath, devid, &guid);
5491 if (config == NULL) {
5492 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
5494 return (SET_ERROR(EIO));
5497 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5499 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
5501 mutex_enter(&spa_namespace_lock);
5502 if ((spa = spa_lookup(pname)) != NULL) {
5504 * Remove the existing root pool from the namespace so that we
5505 * can replace it with the correct config we just read in.
5510 spa = spa_add(pname, config, NULL);
5511 spa->spa_is_root = B_TRUE;
5512 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5513 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5514 &spa->spa_ubsync.ub_version) != 0)
5515 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5518 * Build up a vdev tree based on the boot device's label config.
5520 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5522 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5523 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5524 VDEV_ALLOC_ROOTPOOL);
5525 spa_config_exit(spa, SCL_ALL, FTAG);
5527 mutex_exit(&spa_namespace_lock);
5528 nvlist_free(config);
5529 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5535 * Get the boot vdev.
5537 if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
5538 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
5539 (u_longlong_t)guid);
5540 error = SET_ERROR(ENOENT);
5545 * Determine if there is a better boot device.
5548 spa_alt_rootvdev(rvd, &avd, &txg);
5550 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
5551 "try booting from '%s'", avd->vdev_path);
5552 error = SET_ERROR(EINVAL);
5557 * If the boot device is part of a spare vdev then ensure that
5558 * we're booting off the active spare.
5560 if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
5561 !bvd->vdev_isspare) {
5562 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
5563 "try booting from '%s'",
5565 vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
5566 error = SET_ERROR(EINVAL);
5572 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5574 spa_config_exit(spa, SCL_ALL, FTAG);
5575 mutex_exit(&spa_namespace_lock);
5577 nvlist_free(config);
5581 #else /* !illumos */
5583 extern int vdev_geom_read_pool_label(const char *name, nvlist_t ***configs,
5587 spa_generate_rootconf(const char *name)
5589 nvlist_t **configs, **tops;
5591 nvlist_t *best_cfg, *nvtop, *nvroot;
5600 if (vdev_geom_read_pool_label(name, &configs, &count) != 0)
5603 ASSERT3U(count, !=, 0);
5605 for (i = 0; i < count; i++) {
5608 VERIFY(nvlist_lookup_uint64(configs[i], ZPOOL_CONFIG_POOL_TXG,
5610 if (txg > best_txg) {
5612 best_cfg = configs[i];
5617 nvlist_lookup_uint64(best_cfg, ZPOOL_CONFIG_VDEV_CHILDREN, &nchildren);
5619 nvlist_lookup_uint64_array(best_cfg, ZPOOL_CONFIG_HOLE_ARRAY,
5622 tops = kmem_zalloc(nchildren * sizeof(void *), KM_SLEEP);
5623 for (i = 0; i < nchildren; i++) {
5626 if (configs[i] == NULL)
5628 VERIFY(nvlist_lookup_nvlist(configs[i], ZPOOL_CONFIG_VDEV_TREE,
5630 nvlist_dup(nvtop, &tops[i], KM_SLEEP);
5632 for (i = 0; holes != NULL && i < nholes; i++) {
5635 if (tops[holes[i]] != NULL)
5637 nvlist_alloc(&tops[holes[i]], NV_UNIQUE_NAME, KM_SLEEP);
5638 VERIFY(nvlist_add_string(tops[holes[i]], ZPOOL_CONFIG_TYPE,
5639 VDEV_TYPE_HOLE) == 0);
5640 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_ID,
5642 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_GUID,
5645 for (i = 0; i < nchildren; i++) {
5646 if (tops[i] != NULL)
5648 nvlist_alloc(&tops[i], NV_UNIQUE_NAME, KM_SLEEP);
5649 VERIFY(nvlist_add_string(tops[i], ZPOOL_CONFIG_TYPE,
5650 VDEV_TYPE_MISSING) == 0);
5651 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_ID,
5653 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_GUID,
5658 * Create pool config based on the best vdev config.
5660 nvlist_dup(best_cfg, &config, KM_SLEEP);
5663 * Put this pool's top-level vdevs into a root vdev.
5665 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5667 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5668 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5669 VDEV_TYPE_ROOT) == 0);
5670 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5671 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5672 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5673 tops, nchildren) == 0);
5676 * Replace the existing vdev_tree with the new root vdev in
5677 * this pool's configuration (remove the old, add the new).
5679 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5682 * Drop vdev config elements that should not be present at pool level.
5684 nvlist_remove(config, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64);
5685 nvlist_remove(config, ZPOOL_CONFIG_TOP_GUID, DATA_TYPE_UINT64);
5687 for (i = 0; i < count; i++)
5688 nvlist_free(configs[i]);
5689 kmem_free(configs, count * sizeof(void *));
5690 for (i = 0; i < nchildren; i++)
5691 nvlist_free(tops[i]);
5692 kmem_free(tops, nchildren * sizeof(void *));
5693 nvlist_free(nvroot);
5698 spa_import_rootpool(const char *name)
5701 vdev_t *rvd, *bvd, *avd = NULL;
5702 nvlist_t *config, *nvtop;
5708 * Read the label from the boot device and generate a configuration.
5710 config = spa_generate_rootconf(name);
5712 mutex_enter(&spa_namespace_lock);
5713 if (config != NULL) {
5714 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5715 &pname) == 0 && strcmp(name, pname) == 0);
5716 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg)
5719 if ((spa = spa_lookup(pname)) != NULL) {
5721 * The pool could already be imported,
5722 * e.g., after reboot -r.
5724 if (spa->spa_state == POOL_STATE_ACTIVE) {
5725 mutex_exit(&spa_namespace_lock);
5726 nvlist_free(config);
5731 * Remove the existing root pool from the namespace so
5732 * that we can replace it with the correct config
5737 spa = spa_add(pname, config, NULL);
5740 * Set spa_ubsync.ub_version as it can be used in vdev_alloc()
5741 * via spa_version().
5743 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5744 &spa->spa_ubsync.ub_version) != 0)
5745 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5746 } else if ((spa = spa_lookup(name)) == NULL) {
5747 mutex_exit(&spa_namespace_lock);
5748 nvlist_free(config);
5749 cmn_err(CE_NOTE, "Cannot find the pool label for '%s'",
5753 VERIFY(nvlist_dup(spa->spa_config, &config, KM_SLEEP) == 0);
5755 spa->spa_is_root = B_TRUE;
5756 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5759 * Build up a vdev tree based on the boot device's label config.
5761 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5763 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5764 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5765 VDEV_ALLOC_ROOTPOOL);
5766 spa_config_exit(spa, SCL_ALL, FTAG);
5768 mutex_exit(&spa_namespace_lock);
5769 nvlist_free(config);
5770 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5775 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5777 spa_config_exit(spa, SCL_ALL, FTAG);
5778 mutex_exit(&spa_namespace_lock);
5780 nvlist_free(config);
5784 #endif /* illumos */
5785 #endif /* _KERNEL */
5788 * Import a non-root pool into the system.
5791 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5794 char *altroot = NULL;
5795 spa_load_state_t state = SPA_LOAD_IMPORT;
5796 zpool_load_policy_t policy;
5797 uint64_t mode = spa_mode_global;
5798 uint64_t readonly = B_FALSE;
5801 nvlist_t **spares, **l2cache;
5802 uint_t nspares, nl2cache;
5805 * If a pool with this name exists, return failure.
5807 mutex_enter(&spa_namespace_lock);
5808 if (spa_lookup(pool) != NULL) {
5809 mutex_exit(&spa_namespace_lock);
5810 return (SET_ERROR(EEXIST));
5814 * Create and initialize the spa structure.
5816 (void) nvlist_lookup_string(props,
5817 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5818 (void) nvlist_lookup_uint64(props,
5819 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5822 spa = spa_add(pool, config, altroot);
5823 spa->spa_import_flags = flags;
5826 * Verbatim import - Take a pool and insert it into the namespace
5827 * as if it had been loaded at boot.
5829 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5831 spa_configfile_set(spa, props, B_FALSE);
5833 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5834 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5835 zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5836 mutex_exit(&spa_namespace_lock);
5840 spa_activate(spa, mode);
5843 * Don't start async tasks until we know everything is healthy.
5845 spa_async_suspend(spa);
5847 zpool_get_load_policy(config, &policy);
5848 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5849 state = SPA_LOAD_RECOVER;
5851 spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5853 if (state != SPA_LOAD_RECOVER) {
5854 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5855 zfs_dbgmsg("spa_import: importing %s", pool);
5857 zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5858 "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
5860 error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
5863 * Propagate anything learned while loading the pool and pass it
5864 * back to caller (i.e. rewind info, missing devices, etc).
5866 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5867 spa->spa_load_info) == 0);
5869 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5871 * Toss any existing sparelist, as it doesn't have any validity
5872 * anymore, and conflicts with spa_has_spare().
5874 if (spa->spa_spares.sav_config) {
5875 nvlist_free(spa->spa_spares.sav_config);
5876 spa->spa_spares.sav_config = NULL;
5877 spa_load_spares(spa);
5879 if (spa->spa_l2cache.sav_config) {
5880 nvlist_free(spa->spa_l2cache.sav_config);
5881 spa->spa_l2cache.sav_config = NULL;
5882 spa_load_l2cache(spa);
5885 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5888 error = spa_validate_aux(spa, nvroot, -1ULL,
5891 error = spa_validate_aux(spa, nvroot, -1ULL,
5892 VDEV_ALLOC_L2CACHE);
5893 spa_config_exit(spa, SCL_ALL, FTAG);
5896 spa_configfile_set(spa, props, B_FALSE);
5898 if (error != 0 || (props && spa_writeable(spa) &&
5899 (error = spa_prop_set(spa, props)))) {
5901 spa_deactivate(spa);
5903 mutex_exit(&spa_namespace_lock);
5907 spa_async_resume(spa);
5910 * Override any spares and level 2 cache devices as specified by
5911 * the user, as these may have correct device names/devids, etc.
5913 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5914 &spares, &nspares) == 0) {
5915 if (spa->spa_spares.sav_config)
5916 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5917 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5919 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5920 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5921 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5922 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5923 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5924 spa_load_spares(spa);
5925 spa_config_exit(spa, SCL_ALL, FTAG);
5926 spa->spa_spares.sav_sync = B_TRUE;
5928 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5929 &l2cache, &nl2cache) == 0) {
5930 if (spa->spa_l2cache.sav_config)
5931 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5932 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5934 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5935 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5936 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5937 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5938 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5939 spa_load_l2cache(spa);
5940 spa_config_exit(spa, SCL_ALL, FTAG);
5941 spa->spa_l2cache.sav_sync = B_TRUE;
5945 * Check for any removed devices.
5947 if (spa->spa_autoreplace) {
5948 spa_aux_check_removed(&spa->spa_spares);
5949 spa_aux_check_removed(&spa->spa_l2cache);
5952 if (spa_writeable(spa)) {
5954 * Update the config cache to include the newly-imported pool.
5956 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5960 * It's possible that the pool was expanded while it was exported.
5961 * We kick off an async task to handle this for us.
5963 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5965 spa_history_log_version(spa, "import");
5967 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5969 mutex_exit(&spa_namespace_lock);
5973 zvol_create_minors(pool);
5980 spa_tryimport(nvlist_t *tryconfig)
5982 nvlist_t *config = NULL;
5983 char *poolname, *cachefile;
5987 zpool_load_policy_t policy;
5989 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5992 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5996 * Create and initialize the spa structure.
5998 mutex_enter(&spa_namespace_lock);
5999 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
6000 spa_activate(spa, FREAD);
6003 * Rewind pool if a max txg was provided.
6005 zpool_get_load_policy(spa->spa_config, &policy);
6006 if (policy.zlp_txg != UINT64_MAX) {
6007 spa->spa_load_max_txg = policy.zlp_txg;
6008 spa->spa_extreme_rewind = B_TRUE;
6009 zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
6010 poolname, (longlong_t)policy.zlp_txg);
6012 zfs_dbgmsg("spa_tryimport: importing %s", poolname);
6015 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
6017 zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
6018 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
6020 spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
6023 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
6026 * If 'tryconfig' was at least parsable, return the current config.
6028 if (spa->spa_root_vdev != NULL) {
6029 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
6030 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
6032 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6034 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
6035 spa->spa_uberblock.ub_timestamp) == 0);
6036 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
6037 spa->spa_load_info) == 0);
6040 * If the bootfs property exists on this pool then we
6041 * copy it out so that external consumers can tell which
6042 * pools are bootable.
6044 if ((!error || error == EEXIST) && spa->spa_bootfs) {
6045 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
6048 * We have to play games with the name since the
6049 * pool was opened as TRYIMPORT_NAME.
6051 if (dsl_dsobj_to_dsname(spa_name(spa),
6052 spa->spa_bootfs, tmpname) == 0) {
6054 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
6056 cp = strchr(tmpname, '/');
6058 (void) strlcpy(dsname, tmpname,
6061 (void) snprintf(dsname, MAXPATHLEN,
6062 "%s/%s", poolname, ++cp);
6064 VERIFY(nvlist_add_string(config,
6065 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
6066 kmem_free(dsname, MAXPATHLEN);
6068 kmem_free(tmpname, MAXPATHLEN);
6072 * Add the list of hot spares and level 2 cache devices.
6074 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6075 spa_add_spares(spa, config);
6076 spa_add_l2cache(spa, config);
6077 spa_config_exit(spa, SCL_CONFIG, FTAG);
6081 spa_deactivate(spa);
6083 mutex_exit(&spa_namespace_lock);
6089 * Pool export/destroy
6091 * The act of destroying or exporting a pool is very simple. We make sure there
6092 * is no more pending I/O and any references to the pool are gone. Then, we
6093 * update the pool state and sync all the labels to disk, removing the
6094 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
6095 * we don't sync the labels or remove the configuration cache.
6098 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
6099 boolean_t force, boolean_t hardforce)
6106 if (!(spa_mode_global & FWRITE))
6107 return (SET_ERROR(EROFS));
6109 mutex_enter(&spa_namespace_lock);
6110 if ((spa = spa_lookup(pool)) == NULL) {
6111 mutex_exit(&spa_namespace_lock);
6112 return (SET_ERROR(ENOENT));
6116 * Put a hold on the pool, drop the namespace lock, stop async tasks,
6117 * reacquire the namespace lock, and see if we can export.
6119 spa_open_ref(spa, FTAG);
6120 mutex_exit(&spa_namespace_lock);
6121 spa_async_suspend(spa);
6122 mutex_enter(&spa_namespace_lock);
6123 spa_close(spa, FTAG);
6126 * The pool will be in core if it's openable,
6127 * in which case we can modify its state.
6129 if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
6132 * Objsets may be open only because they're dirty, so we
6133 * have to force it to sync before checking spa_refcnt.
6135 txg_wait_synced(spa->spa_dsl_pool, 0);
6136 spa_evicting_os_wait(spa);
6139 * A pool cannot be exported or destroyed if there are active
6140 * references. If we are resetting a pool, allow references by
6141 * fault injection handlers.
6143 if (!spa_refcount_zero(spa) ||
6144 (spa->spa_inject_ref != 0 &&
6145 new_state != POOL_STATE_UNINITIALIZED)) {
6146 spa_async_resume(spa);
6147 mutex_exit(&spa_namespace_lock);
6148 return (SET_ERROR(EBUSY));
6152 * A pool cannot be exported if it has an active shared spare.
6153 * This is to prevent other pools stealing the active spare
6154 * from an exported pool. At user's own will, such pool can
6155 * be forcedly exported.
6157 if (!force && new_state == POOL_STATE_EXPORTED &&
6158 spa_has_active_shared_spare(spa)) {
6159 spa_async_resume(spa);
6160 mutex_exit(&spa_namespace_lock);
6161 return (SET_ERROR(EXDEV));
6165 * We're about to export or destroy this pool. Make sure
6166 * we stop all initializtion activity here before we
6167 * set the spa_final_txg. This will ensure that all
6168 * dirty data resulting from the initialization is
6169 * committed to disk before we unload the pool.
6171 if (spa->spa_root_vdev != NULL) {
6172 vdev_initialize_stop_all(spa->spa_root_vdev,
6173 VDEV_INITIALIZE_ACTIVE);
6177 * We want this to be reflected on every label,
6178 * so mark them all dirty. spa_unload() will do the
6179 * final sync that pushes these changes out.
6181 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
6182 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6183 spa->spa_state = new_state;
6184 spa->spa_final_txg = spa_last_synced_txg(spa) +
6186 vdev_config_dirty(spa->spa_root_vdev);
6187 spa_config_exit(spa, SCL_ALL, FTAG);
6191 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
6193 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
6195 spa_deactivate(spa);
6198 if (oldconfig && spa->spa_config)
6199 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
6201 if (new_state != POOL_STATE_UNINITIALIZED) {
6203 spa_write_cachefile(spa, B_TRUE, B_TRUE);
6206 mutex_exit(&spa_namespace_lock);
6212 * Destroy a storage pool.
6215 spa_destroy(char *pool)
6217 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
6222 * Export a storage pool.
6225 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
6226 boolean_t hardforce)
6228 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
6233 * Similar to spa_export(), this unloads the spa_t without actually removing it
6234 * from the namespace in any way.
6237 spa_reset(char *pool)
6239 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
6244 * ==========================================================================
6245 * Device manipulation
6246 * ==========================================================================
6250 * Add a device to a storage pool.
6253 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
6257 vdev_t *rvd = spa->spa_root_vdev;
6259 nvlist_t **spares, **l2cache;
6260 uint_t nspares, nl2cache;
6262 ASSERT(spa_writeable(spa));
6264 txg = spa_vdev_enter(spa);
6266 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
6267 VDEV_ALLOC_ADD)) != 0)
6268 return (spa_vdev_exit(spa, NULL, txg, error));
6270 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
6272 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
6276 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
6280 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
6281 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6283 if (vd->vdev_children != 0 &&
6284 (error = vdev_create(vd, txg, B_FALSE)) != 0)
6285 return (spa_vdev_exit(spa, vd, txg, error));
6288 * We must validate the spares and l2cache devices after checking the
6289 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
6291 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
6292 return (spa_vdev_exit(spa, vd, txg, error));
6295 * If we are in the middle of a device removal, we can only add
6296 * devices which match the existing devices in the pool.
6297 * If we are in the middle of a removal, or have some indirect
6298 * vdevs, we can not add raidz toplevels.
6300 if (spa->spa_vdev_removal != NULL ||
6301 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
6302 for (int c = 0; c < vd->vdev_children; c++) {
6303 tvd = vd->vdev_child[c];
6304 if (spa->spa_vdev_removal != NULL &&
6305 tvd->vdev_ashift != spa->spa_max_ashift) {
6306 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6308 /* Fail if top level vdev is raidz */
6309 if (tvd->vdev_ops == &vdev_raidz_ops) {
6310 return (spa_vdev_exit(spa, vd, txg, EINVAL));
6313 * Need the top level mirror to be
6314 * a mirror of leaf vdevs only
6316 if (tvd->vdev_ops == &vdev_mirror_ops) {
6317 for (uint64_t cid = 0;
6318 cid < tvd->vdev_children; cid++) {
6319 vdev_t *cvd = tvd->vdev_child[cid];
6320 if (!cvd->vdev_ops->vdev_op_leaf) {
6321 return (spa_vdev_exit(spa, vd,
6329 for (int c = 0; c < vd->vdev_children; c++) {
6332 * Set the vdev id to the first hole, if one exists.
6334 for (id = 0; id < rvd->vdev_children; id++) {
6335 if (rvd->vdev_child[id]->vdev_ishole) {
6336 vdev_free(rvd->vdev_child[id]);
6340 tvd = vd->vdev_child[c];
6341 vdev_remove_child(vd, tvd);
6343 vdev_add_child(rvd, tvd);
6344 vdev_config_dirty(tvd);
6348 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
6349 ZPOOL_CONFIG_SPARES);
6350 spa_load_spares(spa);
6351 spa->spa_spares.sav_sync = B_TRUE;
6354 if (nl2cache != 0) {
6355 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
6356 ZPOOL_CONFIG_L2CACHE);
6357 spa_load_l2cache(spa);
6358 spa->spa_l2cache.sav_sync = B_TRUE;
6362 * We have to be careful when adding new vdevs to an existing pool.
6363 * If other threads start allocating from these vdevs before we
6364 * sync the config cache, and we lose power, then upon reboot we may
6365 * fail to open the pool because there are DVAs that the config cache
6366 * can't translate. Therefore, we first add the vdevs without
6367 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
6368 * and then let spa_config_update() initialize the new metaslabs.
6370 * spa_load() checks for added-but-not-initialized vdevs, so that
6371 * if we lose power at any point in this sequence, the remaining
6372 * steps will be completed the next time we load the pool.
6374 (void) spa_vdev_exit(spa, vd, txg, 0);
6376 mutex_enter(&spa_namespace_lock);
6377 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
6378 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
6379 mutex_exit(&spa_namespace_lock);
6385 * Attach a device to a mirror. The arguments are the path to any device
6386 * in the mirror, and the nvroot for the new device. If the path specifies
6387 * a device that is not mirrored, we automatically insert the mirror vdev.
6389 * If 'replacing' is specified, the new device is intended to replace the
6390 * existing device; in this case the two devices are made into their own
6391 * mirror using the 'replacing' vdev, which is functionally identical to
6392 * the mirror vdev (it actually reuses all the same ops) but has a few
6393 * extra rules: you can't attach to it after it's been created, and upon
6394 * completion of resilvering, the first disk (the one being replaced)
6395 * is automatically detached.
6398 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
6400 uint64_t txg, dtl_max_txg;
6401 vdev_t *rvd = spa->spa_root_vdev;
6402 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
6404 char *oldvdpath, *newvdpath;
6408 ASSERT(spa_writeable(spa));
6410 txg = spa_vdev_enter(spa);
6412 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
6414 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6415 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6416 error = (spa_has_checkpoint(spa)) ?
6417 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6418 return (spa_vdev_exit(spa, NULL, txg, error));
6421 if (spa->spa_vdev_removal != NULL)
6422 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6425 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6427 if (!oldvd->vdev_ops->vdev_op_leaf)
6428 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6430 pvd = oldvd->vdev_parent;
6432 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
6433 VDEV_ALLOC_ATTACH)) != 0)
6434 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6436 if (newrootvd->vdev_children != 1)
6437 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6439 newvd = newrootvd->vdev_child[0];
6441 if (!newvd->vdev_ops->vdev_op_leaf)
6442 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6444 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
6445 return (spa_vdev_exit(spa, newrootvd, txg, error));
6448 * Spares can't replace logs
6450 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
6451 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6455 * For attach, the only allowable parent is a mirror or the root
6458 if (pvd->vdev_ops != &vdev_mirror_ops &&
6459 pvd->vdev_ops != &vdev_root_ops)
6460 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6462 pvops = &vdev_mirror_ops;
6465 * Active hot spares can only be replaced by inactive hot
6468 if (pvd->vdev_ops == &vdev_spare_ops &&
6469 oldvd->vdev_isspare &&
6470 !spa_has_spare(spa, newvd->vdev_guid))
6471 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6474 * If the source is a hot spare, and the parent isn't already a
6475 * spare, then we want to create a new hot spare. Otherwise, we
6476 * want to create a replacing vdev. The user is not allowed to
6477 * attach to a spared vdev child unless the 'isspare' state is
6478 * the same (spare replaces spare, non-spare replaces
6481 if (pvd->vdev_ops == &vdev_replacing_ops &&
6482 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6483 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6484 } else if (pvd->vdev_ops == &vdev_spare_ops &&
6485 newvd->vdev_isspare != oldvd->vdev_isspare) {
6486 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6489 if (newvd->vdev_isspare)
6490 pvops = &vdev_spare_ops;
6492 pvops = &vdev_replacing_ops;
6496 * Make sure the new device is big enough.
6498 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6499 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6502 * The new device cannot have a higher alignment requirement
6503 * than the top-level vdev.
6505 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6506 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6509 * If this is an in-place replacement, update oldvd's path and devid
6510 * to make it distinguishable from newvd, and unopenable from now on.
6512 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6513 spa_strfree(oldvd->vdev_path);
6514 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6516 (void) sprintf(oldvd->vdev_path, "%s/%s",
6517 newvd->vdev_path, "old");
6518 if (oldvd->vdev_devid != NULL) {
6519 spa_strfree(oldvd->vdev_devid);
6520 oldvd->vdev_devid = NULL;
6524 /* mark the device being resilvered */
6525 newvd->vdev_resilver_txg = txg;
6528 * If the parent is not a mirror, or if we're replacing, insert the new
6529 * mirror/replacing/spare vdev above oldvd.
6531 if (pvd->vdev_ops != pvops)
6532 pvd = vdev_add_parent(oldvd, pvops);
6534 ASSERT(pvd->vdev_top->vdev_parent == rvd);
6535 ASSERT(pvd->vdev_ops == pvops);
6536 ASSERT(oldvd->vdev_parent == pvd);
6539 * Extract the new device from its root and add it to pvd.
6541 vdev_remove_child(newrootvd, newvd);
6542 newvd->vdev_id = pvd->vdev_children;
6543 newvd->vdev_crtxg = oldvd->vdev_crtxg;
6544 vdev_add_child(pvd, newvd);
6546 tvd = newvd->vdev_top;
6547 ASSERT(pvd->vdev_top == tvd);
6548 ASSERT(tvd->vdev_parent == rvd);
6550 vdev_config_dirty(tvd);
6553 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6554 * for any dmu_sync-ed blocks. It will propagate upward when
6555 * spa_vdev_exit() calls vdev_dtl_reassess().
6557 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6559 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6560 dtl_max_txg - TXG_INITIAL);
6562 if (newvd->vdev_isspare) {
6563 spa_spare_activate(newvd);
6564 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6567 oldvdpath = spa_strdup(oldvd->vdev_path);
6568 newvdpath = spa_strdup(newvd->vdev_path);
6569 newvd_isspare = newvd->vdev_isspare;
6572 * Mark newvd's DTL dirty in this txg.
6574 vdev_dirty(tvd, VDD_DTL, newvd, txg);
6577 * Schedule the resilver to restart in the future. We do this to
6578 * ensure that dmu_sync-ed blocks have been stitched into the
6579 * respective datasets.
6581 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
6583 if (spa->spa_bootfs)
6584 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6586 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6591 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6593 spa_history_log_internal(spa, "vdev attach", NULL,
6594 "%s vdev=%s %s vdev=%s",
6595 replacing && newvd_isspare ? "spare in" :
6596 replacing ? "replace" : "attach", newvdpath,
6597 replacing ? "for" : "to", oldvdpath);
6599 spa_strfree(oldvdpath);
6600 spa_strfree(newvdpath);
6606 * Detach a device from a mirror or replacing vdev.
6608 * If 'replace_done' is specified, only detach if the parent
6609 * is a replacing vdev.
6612 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6616 vdev_t *rvd = spa->spa_root_vdev;
6617 vdev_t *vd, *pvd, *cvd, *tvd;
6618 boolean_t unspare = B_FALSE;
6619 uint64_t unspare_guid = 0;
6622 ASSERT(spa_writeable(spa));
6624 txg = spa_vdev_enter(spa);
6626 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6629 * Besides being called directly from the userland through the
6630 * ioctl interface, spa_vdev_detach() can be potentially called
6631 * at the end of spa_vdev_resilver_done().
6633 * In the regular case, when we have a checkpoint this shouldn't
6634 * happen as we never empty the DTLs of a vdev during the scrub
6635 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6636 * should never get here when we have a checkpoint.
6638 * That said, even in a case when we checkpoint the pool exactly
6639 * as spa_vdev_resilver_done() calls this function everything
6640 * should be fine as the resilver will return right away.
6642 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6643 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6644 error = (spa_has_checkpoint(spa)) ?
6645 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6646 return (spa_vdev_exit(spa, NULL, txg, error));
6650 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6652 if (!vd->vdev_ops->vdev_op_leaf)
6653 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6655 pvd = vd->vdev_parent;
6658 * If the parent/child relationship is not as expected, don't do it.
6659 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6660 * vdev that's replacing B with C. The user's intent in replacing
6661 * is to go from M(A,B) to M(A,C). If the user decides to cancel
6662 * the replace by detaching C, the expected behavior is to end up
6663 * M(A,B). But suppose that right after deciding to detach C,
6664 * the replacement of B completes. We would have M(A,C), and then
6665 * ask to detach C, which would leave us with just A -- not what
6666 * the user wanted. To prevent this, we make sure that the
6667 * parent/child relationship hasn't changed -- in this example,
6668 * that C's parent is still the replacing vdev R.
6670 if (pvd->vdev_guid != pguid && pguid != 0)
6671 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6674 * Only 'replacing' or 'spare' vdevs can be replaced.
6676 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6677 pvd->vdev_ops != &vdev_spare_ops)
6678 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6680 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6681 spa_version(spa) >= SPA_VERSION_SPARES);
6684 * Only mirror, replacing, and spare vdevs support detach.
6686 if (pvd->vdev_ops != &vdev_replacing_ops &&
6687 pvd->vdev_ops != &vdev_mirror_ops &&
6688 pvd->vdev_ops != &vdev_spare_ops)
6689 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6692 * If this device has the only valid copy of some data,
6693 * we cannot safely detach it.
6695 if (vdev_dtl_required(vd))
6696 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6698 ASSERT(pvd->vdev_children >= 2);
6701 * If we are detaching the second disk from a replacing vdev, then
6702 * check to see if we changed the original vdev's path to have "/old"
6703 * at the end in spa_vdev_attach(). If so, undo that change now.
6705 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
6706 vd->vdev_path != NULL) {
6707 size_t len = strlen(vd->vdev_path);
6709 for (int c = 0; c < pvd->vdev_children; c++) {
6710 cvd = pvd->vdev_child[c];
6712 if (cvd == vd || cvd->vdev_path == NULL)
6715 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
6716 strcmp(cvd->vdev_path + len, "/old") == 0) {
6717 spa_strfree(cvd->vdev_path);
6718 cvd->vdev_path = spa_strdup(vd->vdev_path);
6725 * If we are detaching the original disk from a spare, then it implies
6726 * that the spare should become a real disk, and be removed from the
6727 * active spare list for the pool.
6729 if (pvd->vdev_ops == &vdev_spare_ops &&
6731 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
6735 * Erase the disk labels so the disk can be used for other things.
6736 * This must be done after all other error cases are handled,
6737 * but before we disembowel vd (so we can still do I/O to it).
6738 * But if we can't do it, don't treat the error as fatal --
6739 * it may be that the unwritability of the disk is the reason
6740 * it's being detached!
6742 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
6745 * Remove vd from its parent and compact the parent's children.
6747 vdev_remove_child(pvd, vd);
6748 vdev_compact_children(pvd);
6751 * Remember one of the remaining children so we can get tvd below.
6753 cvd = pvd->vdev_child[pvd->vdev_children - 1];
6756 * If we need to remove the remaining child from the list of hot spares,
6757 * do it now, marking the vdev as no longer a spare in the process.
6758 * We must do this before vdev_remove_parent(), because that can
6759 * change the GUID if it creates a new toplevel GUID. For a similar
6760 * reason, we must remove the spare now, in the same txg as the detach;
6761 * otherwise someone could attach a new sibling, change the GUID, and
6762 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
6765 ASSERT(cvd->vdev_isspare);
6766 spa_spare_remove(cvd);
6767 unspare_guid = cvd->vdev_guid;
6768 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
6769 cvd->vdev_unspare = B_TRUE;
6773 * If the parent mirror/replacing vdev only has one child,
6774 * the parent is no longer needed. Remove it from the tree.
6776 if (pvd->vdev_children == 1) {
6777 if (pvd->vdev_ops == &vdev_spare_ops)
6778 cvd->vdev_unspare = B_FALSE;
6779 vdev_remove_parent(cvd);
6784 * We don't set tvd until now because the parent we just removed
6785 * may have been the previous top-level vdev.
6787 tvd = cvd->vdev_top;
6788 ASSERT(tvd->vdev_parent == rvd);
6791 * Reevaluate the parent vdev state.
6793 vdev_propagate_state(cvd);
6796 * If the 'autoexpand' property is set on the pool then automatically
6797 * try to expand the size of the pool. For example if the device we
6798 * just detached was smaller than the others, it may be possible to
6799 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
6800 * first so that we can obtain the updated sizes of the leaf vdevs.
6802 if (spa->spa_autoexpand) {
6804 vdev_expand(tvd, txg);
6807 vdev_config_dirty(tvd);
6810 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
6811 * vd->vdev_detached is set and free vd's DTL object in syncing context.
6812 * But first make sure we're not on any *other* txg's DTL list, to
6813 * prevent vd from being accessed after it's freed.
6815 vdpath = spa_strdup(vd->vdev_path);
6816 for (int t = 0; t < TXG_SIZE; t++)
6817 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
6818 vd->vdev_detached = B_TRUE;
6819 vdev_dirty(tvd, VDD_DTL, vd, txg);
6821 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
6823 /* hang on to the spa before we release the lock */
6824 spa_open_ref(spa, FTAG);
6826 error = spa_vdev_exit(spa, vd, txg, 0);
6828 spa_history_log_internal(spa, "detach", NULL,
6830 spa_strfree(vdpath);
6833 * If this was the removal of the original device in a hot spare vdev,
6834 * then we want to go through and remove the device from the hot spare
6835 * list of every other pool.
6838 spa_t *altspa = NULL;
6840 mutex_enter(&spa_namespace_lock);
6841 while ((altspa = spa_next(altspa)) != NULL) {
6842 if (altspa->spa_state != POOL_STATE_ACTIVE ||
6846 spa_open_ref(altspa, FTAG);
6847 mutex_exit(&spa_namespace_lock);
6848 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
6849 mutex_enter(&spa_namespace_lock);
6850 spa_close(altspa, FTAG);
6852 mutex_exit(&spa_namespace_lock);
6854 /* search the rest of the vdevs for spares to remove */
6855 spa_vdev_resilver_done(spa);
6858 /* all done with the spa; OK to release */
6859 mutex_enter(&spa_namespace_lock);
6860 spa_close(spa, FTAG);
6861 mutex_exit(&spa_namespace_lock);
6867 spa_vdev_initialize(spa_t *spa, uint64_t guid, uint64_t cmd_type)
6870 * We hold the namespace lock through the whole function
6871 * to prevent any changes to the pool while we're starting or
6872 * stopping initialization. The config and state locks are held so that
6873 * we can properly assess the vdev state before we commit to
6874 * the initializing operation.
6876 mutex_enter(&spa_namespace_lock);
6877 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6879 /* Look up vdev and ensure it's a leaf. */
6880 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6881 if (vd == NULL || vd->vdev_detached) {
6882 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6883 mutex_exit(&spa_namespace_lock);
6884 return (SET_ERROR(ENODEV));
6885 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6886 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6887 mutex_exit(&spa_namespace_lock);
6888 return (SET_ERROR(EINVAL));
6889 } else if (!vdev_writeable(vd)) {
6890 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6891 mutex_exit(&spa_namespace_lock);
6892 return (SET_ERROR(EROFS));
6894 mutex_enter(&vd->vdev_initialize_lock);
6895 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6898 * When we activate an initialize action we check to see
6899 * if the vdev_initialize_thread is NULL. We do this instead
6900 * of using the vdev_initialize_state since there might be
6901 * a previous initialization process which has completed but
6902 * the thread is not exited.
6904 if (cmd_type == POOL_INITIALIZE_DO &&
6905 (vd->vdev_initialize_thread != NULL ||
6906 vd->vdev_top->vdev_removing)) {
6907 mutex_exit(&vd->vdev_initialize_lock);
6908 mutex_exit(&spa_namespace_lock);
6909 return (SET_ERROR(EBUSY));
6910 } else if (cmd_type == POOL_INITIALIZE_CANCEL &&
6911 (vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE &&
6912 vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED)) {
6913 mutex_exit(&vd->vdev_initialize_lock);
6914 mutex_exit(&spa_namespace_lock);
6915 return (SET_ERROR(ESRCH));
6916 } else if (cmd_type == POOL_INITIALIZE_SUSPEND &&
6917 vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE) {
6918 mutex_exit(&vd->vdev_initialize_lock);
6919 mutex_exit(&spa_namespace_lock);
6920 return (SET_ERROR(ESRCH));
6924 case POOL_INITIALIZE_DO:
6925 vdev_initialize(vd);
6927 case POOL_INITIALIZE_CANCEL:
6928 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED);
6930 case POOL_INITIALIZE_SUSPEND:
6931 vdev_initialize_stop(vd, VDEV_INITIALIZE_SUSPENDED);
6934 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6936 mutex_exit(&vd->vdev_initialize_lock);
6938 /* Sync out the initializing state */
6939 txg_wait_synced(spa->spa_dsl_pool, 0);
6940 mutex_exit(&spa_namespace_lock);
6947 * Split a set of devices from their mirrors, and create a new pool from them.
6950 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6951 nvlist_t *props, boolean_t exp)
6954 uint64_t txg, *glist;
6956 uint_t c, children, lastlog;
6957 nvlist_t **child, *nvl, *tmp;
6959 char *altroot = NULL;
6960 vdev_t *rvd, **vml = NULL; /* vdev modify list */
6961 boolean_t activate_slog;
6963 ASSERT(spa_writeable(spa));
6965 txg = spa_vdev_enter(spa);
6967 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6968 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6969 error = (spa_has_checkpoint(spa)) ?
6970 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6971 return (spa_vdev_exit(spa, NULL, txg, error));
6974 /* clear the log and flush everything up to now */
6975 activate_slog = spa_passivate_log(spa);
6976 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6977 error = spa_reset_logs(spa);
6978 txg = spa_vdev_config_enter(spa);
6981 spa_activate_log(spa);
6984 return (spa_vdev_exit(spa, NULL, txg, error));
6986 /* check new spa name before going any further */
6987 if (spa_lookup(newname) != NULL)
6988 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
6991 * scan through all the children to ensure they're all mirrors
6993 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
6994 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
6996 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6998 /* first, check to ensure we've got the right child count */
6999 rvd = spa->spa_root_vdev;
7001 for (c = 0; c < rvd->vdev_children; c++) {
7002 vdev_t *vd = rvd->vdev_child[c];
7004 /* don't count the holes & logs as children */
7005 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
7013 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
7014 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
7016 /* next, ensure no spare or cache devices are part of the split */
7017 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
7018 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
7019 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
7021 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
7022 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
7024 /* then, loop over each vdev and validate it */
7025 for (c = 0; c < children; c++) {
7026 uint64_t is_hole = 0;
7028 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
7032 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
7033 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
7036 error = SET_ERROR(EINVAL);
7041 /* which disk is going to be split? */
7042 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
7044 error = SET_ERROR(EINVAL);
7048 /* look it up in the spa */
7049 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
7050 if (vml[c] == NULL) {
7051 error = SET_ERROR(ENODEV);
7055 /* make sure there's nothing stopping the split */
7056 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
7057 vml[c]->vdev_islog ||
7058 !vdev_is_concrete(vml[c]) ||
7059 vml[c]->vdev_isspare ||
7060 vml[c]->vdev_isl2cache ||
7061 !vdev_writeable(vml[c]) ||
7062 vml[c]->vdev_children != 0 ||
7063 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
7064 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
7065 error = SET_ERROR(EINVAL);
7069 if (vdev_dtl_required(vml[c])) {
7070 error = SET_ERROR(EBUSY);
7074 /* we need certain info from the top level */
7075 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
7076 vml[c]->vdev_top->vdev_ms_array) == 0);
7077 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
7078 vml[c]->vdev_top->vdev_ms_shift) == 0);
7079 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
7080 vml[c]->vdev_top->vdev_asize) == 0);
7081 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
7082 vml[c]->vdev_top->vdev_ashift) == 0);
7084 /* transfer per-vdev ZAPs */
7085 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
7086 VERIFY0(nvlist_add_uint64(child[c],
7087 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
7089 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
7090 VERIFY0(nvlist_add_uint64(child[c],
7091 ZPOOL_CONFIG_VDEV_TOP_ZAP,
7092 vml[c]->vdev_parent->vdev_top_zap));
7096 kmem_free(vml, children * sizeof (vdev_t *));
7097 kmem_free(glist, children * sizeof (uint64_t));
7098 return (spa_vdev_exit(spa, NULL, txg, error));
7101 /* stop writers from using the disks */
7102 for (c = 0; c < children; c++) {
7104 vml[c]->vdev_offline = B_TRUE;
7106 vdev_reopen(spa->spa_root_vdev);
7109 * Temporarily record the splitting vdevs in the spa config. This
7110 * will disappear once the config is regenerated.
7112 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7113 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
7114 glist, children) == 0);
7115 kmem_free(glist, children * sizeof (uint64_t));
7117 mutex_enter(&spa->spa_props_lock);
7118 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
7120 mutex_exit(&spa->spa_props_lock);
7121 spa->spa_config_splitting = nvl;
7122 vdev_config_dirty(spa->spa_root_vdev);
7124 /* configure and create the new pool */
7125 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
7126 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
7127 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
7128 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7129 spa_version(spa)) == 0);
7130 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
7131 spa->spa_config_txg) == 0);
7132 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
7133 spa_generate_guid(NULL)) == 0);
7134 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
7135 (void) nvlist_lookup_string(props,
7136 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
7138 /* add the new pool to the namespace */
7139 newspa = spa_add(newname, config, altroot);
7140 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
7141 newspa->spa_config_txg = spa->spa_config_txg;
7142 spa_set_log_state(newspa, SPA_LOG_CLEAR);
7144 /* release the spa config lock, retaining the namespace lock */
7145 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
7147 if (zio_injection_enabled)
7148 zio_handle_panic_injection(spa, FTAG, 1);
7150 spa_activate(newspa, spa_mode_global);
7151 spa_async_suspend(newspa);
7153 for (c = 0; c < children; c++) {
7154 if (vml[c] != NULL) {
7156 * Temporarily stop the initializing activity. We set
7157 * the state to ACTIVE so that we know to resume
7158 * the initializing once the split has completed.
7160 mutex_enter(&vml[c]->vdev_initialize_lock);
7161 vdev_initialize_stop(vml[c], VDEV_INITIALIZE_ACTIVE);
7162 mutex_exit(&vml[c]->vdev_initialize_lock);
7167 /* mark that we are creating new spa by splitting */
7168 newspa->spa_splitting_newspa = B_TRUE;
7170 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
7172 /* create the new pool from the disks of the original pool */
7173 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
7175 newspa->spa_splitting_newspa = B_FALSE;
7180 /* if that worked, generate a real config for the new pool */
7181 if (newspa->spa_root_vdev != NULL) {
7182 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
7183 NV_UNIQUE_NAME, KM_SLEEP) == 0);
7184 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
7185 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
7186 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
7191 if (props != NULL) {
7192 spa_configfile_set(newspa, props, B_FALSE);
7193 error = spa_prop_set(newspa, props);
7198 /* flush everything */
7199 txg = spa_vdev_config_enter(newspa);
7200 vdev_config_dirty(newspa->spa_root_vdev);
7201 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
7203 if (zio_injection_enabled)
7204 zio_handle_panic_injection(spa, FTAG, 2);
7206 spa_async_resume(newspa);
7208 /* finally, update the original pool's config */
7209 txg = spa_vdev_config_enter(spa);
7210 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
7211 error = dmu_tx_assign(tx, TXG_WAIT);
7214 for (c = 0; c < children; c++) {
7215 if (vml[c] != NULL) {
7218 spa_history_log_internal(spa, "detach", tx,
7219 "vdev=%s", vml[c]->vdev_path);
7224 spa->spa_avz_action = AVZ_ACTION_REBUILD;
7225 vdev_config_dirty(spa->spa_root_vdev);
7226 spa->spa_config_splitting = NULL;
7230 (void) spa_vdev_exit(spa, NULL, txg, 0);
7232 if (zio_injection_enabled)
7233 zio_handle_panic_injection(spa, FTAG, 3);
7235 /* split is complete; log a history record */
7236 spa_history_log_internal(newspa, "split", NULL,
7237 "from pool %s", spa_name(spa));
7239 kmem_free(vml, children * sizeof (vdev_t *));
7241 /* if we're not going to mount the filesystems in userland, export */
7243 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
7250 spa_deactivate(newspa);
7253 txg = spa_vdev_config_enter(spa);
7255 /* re-online all offlined disks */
7256 for (c = 0; c < children; c++) {
7258 vml[c]->vdev_offline = B_FALSE;
7261 /* restart initializing disks as necessary */
7262 spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
7264 vdev_reopen(spa->spa_root_vdev);
7266 nvlist_free(spa->spa_config_splitting);
7267 spa->spa_config_splitting = NULL;
7268 (void) spa_vdev_exit(spa, NULL, txg, error);
7270 kmem_free(vml, children * sizeof (vdev_t *));
7275 * Find any device that's done replacing, or a vdev marked 'unspare' that's
7276 * currently spared, so we can detach it.
7279 spa_vdev_resilver_done_hunt(vdev_t *vd)
7281 vdev_t *newvd, *oldvd;
7283 for (int c = 0; c < vd->vdev_children; c++) {
7284 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
7290 * Check for a completed replacement. We always consider the first
7291 * vdev in the list to be the oldest vdev, and the last one to be
7292 * the newest (see spa_vdev_attach() for how that works). In
7293 * the case where the newest vdev is faulted, we will not automatically
7294 * remove it after a resilver completes. This is OK as it will require
7295 * user intervention to determine which disk the admin wishes to keep.
7297 if (vd->vdev_ops == &vdev_replacing_ops) {
7298 ASSERT(vd->vdev_children > 1);
7300 newvd = vd->vdev_child[vd->vdev_children - 1];
7301 oldvd = vd->vdev_child[0];
7303 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
7304 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
7305 !vdev_dtl_required(oldvd))
7310 * Check for a completed resilver with the 'unspare' flag set.
7311 * Also potentially update faulted state.
7313 if (vd->vdev_ops == &vdev_spare_ops) {
7314 vdev_t *first = vd->vdev_child[0];
7315 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
7317 if (last->vdev_unspare) {
7320 } else if (first->vdev_unspare) {
7327 if (oldvd != NULL &&
7328 vdev_dtl_empty(newvd, DTL_MISSING) &&
7329 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
7330 !vdev_dtl_required(oldvd))
7333 vdev_propagate_state(vd);
7336 * If there are more than two spares attached to a disk,
7337 * and those spares are not required, then we want to
7338 * attempt to free them up now so that they can be used
7339 * by other pools. Once we're back down to a single
7340 * disk+spare, we stop removing them.
7342 if (vd->vdev_children > 2) {
7343 newvd = vd->vdev_child[1];
7345 if (newvd->vdev_isspare && last->vdev_isspare &&
7346 vdev_dtl_empty(last, DTL_MISSING) &&
7347 vdev_dtl_empty(last, DTL_OUTAGE) &&
7348 !vdev_dtl_required(newvd))
7357 spa_vdev_resilver_done(spa_t *spa)
7359 vdev_t *vd, *pvd, *ppvd;
7360 uint64_t guid, sguid, pguid, ppguid;
7362 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7364 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
7365 pvd = vd->vdev_parent;
7366 ppvd = pvd->vdev_parent;
7367 guid = vd->vdev_guid;
7368 pguid = pvd->vdev_guid;
7369 ppguid = ppvd->vdev_guid;
7372 * If we have just finished replacing a hot spared device, then
7373 * we need to detach the parent's first child (the original hot
7376 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
7377 ppvd->vdev_children == 2) {
7378 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
7379 sguid = ppvd->vdev_child[1]->vdev_guid;
7381 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
7383 spa_config_exit(spa, SCL_ALL, FTAG);
7384 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
7386 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
7388 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7391 spa_config_exit(spa, SCL_ALL, FTAG);
7395 * Update the stored path or FRU for this vdev.
7398 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
7402 boolean_t sync = B_FALSE;
7404 ASSERT(spa_writeable(spa));
7406 spa_vdev_state_enter(spa, SCL_ALL);
7408 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
7409 return (spa_vdev_state_exit(spa, NULL, ENOENT));
7411 if (!vd->vdev_ops->vdev_op_leaf)
7412 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
7415 if (strcmp(value, vd->vdev_path) != 0) {
7416 spa_strfree(vd->vdev_path);
7417 vd->vdev_path = spa_strdup(value);
7421 if (vd->vdev_fru == NULL) {
7422 vd->vdev_fru = spa_strdup(value);
7424 } else if (strcmp(value, vd->vdev_fru) != 0) {
7425 spa_strfree(vd->vdev_fru);
7426 vd->vdev_fru = spa_strdup(value);
7431 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
7435 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
7437 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
7441 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
7443 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
7447 * ==========================================================================
7449 * ==========================================================================
7452 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
7454 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7456 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7457 return (SET_ERROR(EBUSY));
7459 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
7463 spa_scan_stop(spa_t *spa)
7465 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7466 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7467 return (SET_ERROR(EBUSY));
7468 return (dsl_scan_cancel(spa->spa_dsl_pool));
7472 spa_scan(spa_t *spa, pool_scan_func_t func)
7474 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7476 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
7477 return (SET_ERROR(ENOTSUP));
7480 * If a resilver was requested, but there is no DTL on a
7481 * writeable leaf device, we have nothing to do.
7483 if (func == POOL_SCAN_RESILVER &&
7484 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
7485 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
7489 return (dsl_scan(spa->spa_dsl_pool, func));
7493 * ==========================================================================
7494 * SPA async task processing
7495 * ==========================================================================
7499 spa_async_remove(spa_t *spa, vdev_t *vd)
7501 if (vd->vdev_remove_wanted) {
7502 vd->vdev_remove_wanted = B_FALSE;
7503 vd->vdev_delayed_close = B_FALSE;
7504 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
7507 * We want to clear the stats, but we don't want to do a full
7508 * vdev_clear() as that will cause us to throw away
7509 * degraded/faulted state as well as attempt to reopen the
7510 * device, all of which is a waste.
7512 vd->vdev_stat.vs_read_errors = 0;
7513 vd->vdev_stat.vs_write_errors = 0;
7514 vd->vdev_stat.vs_checksum_errors = 0;
7516 vdev_state_dirty(vd->vdev_top);
7517 /* Tell userspace that the vdev is gone. */
7518 zfs_post_remove(spa, vd);
7521 for (int c = 0; c < vd->vdev_children; c++)
7522 spa_async_remove(spa, vd->vdev_child[c]);
7526 spa_async_probe(spa_t *spa, vdev_t *vd)
7528 if (vd->vdev_probe_wanted) {
7529 vd->vdev_probe_wanted = B_FALSE;
7530 vdev_reopen(vd); /* vdev_open() does the actual probe */
7533 for (int c = 0; c < vd->vdev_children; c++)
7534 spa_async_probe(spa, vd->vdev_child[c]);
7538 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
7544 if (!spa->spa_autoexpand)
7547 for (int c = 0; c < vd->vdev_children; c++) {
7548 vdev_t *cvd = vd->vdev_child[c];
7549 spa_async_autoexpand(spa, cvd);
7552 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
7555 physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
7556 (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
7558 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7559 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
7561 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
7562 ESC_ZFS_VDEV_AUTOEXPAND, attr, &eid, DDI_SLEEP);
7565 kmem_free(physpath, MAXPATHLEN);
7569 spa_async_thread(void *arg)
7571 spa_t *spa = (spa_t *)arg;
7574 ASSERT(spa->spa_sync_on);
7576 mutex_enter(&spa->spa_async_lock);
7577 tasks = spa->spa_async_tasks;
7578 spa->spa_async_tasks &= SPA_ASYNC_REMOVE;
7579 mutex_exit(&spa->spa_async_lock);
7582 * See if the config needs to be updated.
7584 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
7585 uint64_t old_space, new_space;
7587 mutex_enter(&spa_namespace_lock);
7588 old_space = metaslab_class_get_space(spa_normal_class(spa));
7589 old_space += metaslab_class_get_space(spa_special_class(spa));
7590 old_space += metaslab_class_get_space(spa_dedup_class(spa));
7592 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
7594 new_space = metaslab_class_get_space(spa_normal_class(spa));
7595 new_space += metaslab_class_get_space(spa_special_class(spa));
7596 new_space += metaslab_class_get_space(spa_dedup_class(spa));
7597 mutex_exit(&spa_namespace_lock);
7600 * If the pool grew as a result of the config update,
7601 * then log an internal history event.
7603 if (new_space != old_space) {
7604 spa_history_log_internal(spa, "vdev online", NULL,
7605 "pool '%s' size: %llu(+%llu)",
7606 spa_name(spa), new_space, new_space - old_space);
7610 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
7611 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7612 spa_async_autoexpand(spa, spa->spa_root_vdev);
7613 spa_config_exit(spa, SCL_CONFIG, FTAG);
7617 * See if any devices need to be probed.
7619 if (tasks & SPA_ASYNC_PROBE) {
7620 spa_vdev_state_enter(spa, SCL_NONE);
7621 spa_async_probe(spa, spa->spa_root_vdev);
7622 (void) spa_vdev_state_exit(spa, NULL, 0);
7626 * If any devices are done replacing, detach them.
7628 if (tasks & SPA_ASYNC_RESILVER_DONE)
7629 spa_vdev_resilver_done(spa);
7632 * Kick off a resilver.
7634 if (tasks & SPA_ASYNC_RESILVER)
7635 dsl_resilver_restart(spa->spa_dsl_pool, 0);
7637 if (tasks & SPA_ASYNC_INITIALIZE_RESTART) {
7638 mutex_enter(&spa_namespace_lock);
7639 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7640 vdev_initialize_restart(spa->spa_root_vdev);
7641 spa_config_exit(spa, SCL_CONFIG, FTAG);
7642 mutex_exit(&spa_namespace_lock);
7646 * Let the world know that we're done.
7648 mutex_enter(&spa->spa_async_lock);
7649 spa->spa_async_thread = NULL;
7650 cv_broadcast(&spa->spa_async_cv);
7651 mutex_exit(&spa->spa_async_lock);
7656 spa_async_thread_vd(void *arg)
7661 mutex_enter(&spa->spa_async_lock);
7662 tasks = spa->spa_async_tasks;
7664 spa->spa_async_tasks &= ~SPA_ASYNC_REMOVE;
7665 mutex_exit(&spa->spa_async_lock);
7668 * See if any devices need to be marked REMOVED.
7670 if (tasks & SPA_ASYNC_REMOVE) {
7671 spa_vdev_state_enter(spa, SCL_NONE);
7672 spa_async_remove(spa, spa->spa_root_vdev);
7673 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
7674 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
7675 for (int i = 0; i < spa->spa_spares.sav_count; i++)
7676 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
7677 (void) spa_vdev_state_exit(spa, NULL, 0);
7681 * Let the world know that we're done.
7683 mutex_enter(&spa->spa_async_lock);
7684 tasks = spa->spa_async_tasks;
7685 if ((tasks & SPA_ASYNC_REMOVE) != 0)
7687 spa->spa_async_thread_vd = NULL;
7688 cv_broadcast(&spa->spa_async_cv);
7689 mutex_exit(&spa->spa_async_lock);
7694 spa_async_suspend(spa_t *spa)
7696 mutex_enter(&spa->spa_async_lock);
7697 spa->spa_async_suspended++;
7698 while (spa->spa_async_thread != NULL ||
7699 spa->spa_async_thread_vd != NULL)
7700 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
7701 mutex_exit(&spa->spa_async_lock);
7703 spa_vdev_remove_suspend(spa);
7705 zthr_t *condense_thread = spa->spa_condense_zthr;
7706 if (condense_thread != NULL)
7707 zthr_cancel(condense_thread);
7709 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7710 if (discard_thread != NULL)
7711 zthr_cancel(discard_thread);
7715 spa_async_resume(spa_t *spa)
7717 mutex_enter(&spa->spa_async_lock);
7718 ASSERT(spa->spa_async_suspended != 0);
7719 spa->spa_async_suspended--;
7720 mutex_exit(&spa->spa_async_lock);
7721 spa_restart_removal(spa);
7723 zthr_t *condense_thread = spa->spa_condense_zthr;
7724 if (condense_thread != NULL)
7725 zthr_resume(condense_thread);
7727 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7728 if (discard_thread != NULL)
7729 zthr_resume(discard_thread);
7733 spa_async_tasks_pending(spa_t *spa)
7735 uint_t non_config_tasks;
7737 boolean_t config_task_suspended;
7739 non_config_tasks = spa->spa_async_tasks & ~(SPA_ASYNC_CONFIG_UPDATE |
7741 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
7742 if (spa->spa_ccw_fail_time == 0) {
7743 config_task_suspended = B_FALSE;
7745 config_task_suspended =
7746 (gethrtime() - spa->spa_ccw_fail_time) <
7747 (zfs_ccw_retry_interval * NANOSEC);
7750 return (non_config_tasks || (config_task && !config_task_suspended));
7754 spa_async_dispatch(spa_t *spa)
7756 mutex_enter(&spa->spa_async_lock);
7757 if (spa_async_tasks_pending(spa) &&
7758 !spa->spa_async_suspended &&
7759 spa->spa_async_thread == NULL &&
7761 spa->spa_async_thread = thread_create(NULL, 0,
7762 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
7763 mutex_exit(&spa->spa_async_lock);
7767 spa_async_dispatch_vd(spa_t *spa)
7769 mutex_enter(&spa->spa_async_lock);
7770 if ((spa->spa_async_tasks & SPA_ASYNC_REMOVE) != 0 &&
7771 !spa->spa_async_suspended &&
7772 spa->spa_async_thread_vd == NULL &&
7774 spa->spa_async_thread_vd = thread_create(NULL, 0,
7775 spa_async_thread_vd, spa, 0, &p0, TS_RUN, maxclsyspri);
7776 mutex_exit(&spa->spa_async_lock);
7780 spa_async_request(spa_t *spa, int task)
7782 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
7783 mutex_enter(&spa->spa_async_lock);
7784 spa->spa_async_tasks |= task;
7785 mutex_exit(&spa->spa_async_lock);
7786 spa_async_dispatch_vd(spa);
7790 * ==========================================================================
7791 * SPA syncing routines
7792 * ==========================================================================
7796 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7799 bpobj_enqueue(bpo, bp, tx);
7804 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7808 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
7809 BP_GET_PSIZE(bp), zio->io_flags));
7814 * Note: this simple function is not inlined to make it easier to dtrace the
7815 * amount of time spent syncing frees.
7818 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
7820 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7821 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
7822 VERIFY(zio_wait(zio) == 0);
7826 * Note: this simple function is not inlined to make it easier to dtrace the
7827 * amount of time spent syncing deferred frees.
7830 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
7832 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7833 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
7834 spa_free_sync_cb, zio, tx), ==, 0);
7835 VERIFY0(zio_wait(zio));
7840 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
7842 char *packed = NULL;
7847 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
7850 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
7851 * information. This avoids the dmu_buf_will_dirty() path and
7852 * saves us a pre-read to get data we don't actually care about.
7854 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
7855 packed = kmem_alloc(bufsize, KM_SLEEP);
7857 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
7859 bzero(packed + nvsize, bufsize - nvsize);
7861 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
7863 kmem_free(packed, bufsize);
7865 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
7866 dmu_buf_will_dirty(db, tx);
7867 *(uint64_t *)db->db_data = nvsize;
7868 dmu_buf_rele(db, FTAG);
7872 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
7873 const char *config, const char *entry)
7883 * Update the MOS nvlist describing the list of available devices.
7884 * spa_validate_aux() will have already made sure this nvlist is
7885 * valid and the vdevs are labeled appropriately.
7887 if (sav->sav_object == 0) {
7888 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
7889 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
7890 sizeof (uint64_t), tx);
7891 VERIFY(zap_update(spa->spa_meta_objset,
7892 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
7893 &sav->sav_object, tx) == 0);
7896 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7897 if (sav->sav_count == 0) {
7898 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
7900 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
7901 for (i = 0; i < sav->sav_count; i++)
7902 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
7903 B_FALSE, VDEV_CONFIG_L2CACHE);
7904 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
7905 sav->sav_count) == 0);
7906 for (i = 0; i < sav->sav_count; i++)
7907 nvlist_free(list[i]);
7908 kmem_free(list, sav->sav_count * sizeof (void *));
7911 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
7912 nvlist_free(nvroot);
7914 sav->sav_sync = B_FALSE;
7918 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
7919 * The all-vdev ZAP must be empty.
7922 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
7924 spa_t *spa = vd->vdev_spa;
7925 if (vd->vdev_top_zap != 0) {
7926 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7927 vd->vdev_top_zap, tx));
7929 if (vd->vdev_leaf_zap != 0) {
7930 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7931 vd->vdev_leaf_zap, tx));
7933 for (uint64_t i = 0; i < vd->vdev_children; i++) {
7934 spa_avz_build(vd->vdev_child[i], avz, tx);
7939 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
7944 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
7945 * its config may not be dirty but we still need to build per-vdev ZAPs.
7946 * Similarly, if the pool is being assembled (e.g. after a split), we
7947 * need to rebuild the AVZ although the config may not be dirty.
7949 if (list_is_empty(&spa->spa_config_dirty_list) &&
7950 spa->spa_avz_action == AVZ_ACTION_NONE)
7953 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7955 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
7956 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
7957 spa->spa_all_vdev_zaps != 0);
7959 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
7960 /* Make and build the new AVZ */
7961 uint64_t new_avz = zap_create(spa->spa_meta_objset,
7962 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7963 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7965 /* Diff old AVZ with new one */
7969 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7970 spa->spa_all_vdev_zaps);
7971 zap_cursor_retrieve(&zc, &za) == 0;
7972 zap_cursor_advance(&zc)) {
7973 uint64_t vdzap = za.za_first_integer;
7974 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
7977 * ZAP is listed in old AVZ but not in new one;
7980 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
7985 zap_cursor_fini(&zc);
7987 /* Destroy the old AVZ */
7988 VERIFY0(zap_destroy(spa->spa_meta_objset,
7989 spa->spa_all_vdev_zaps, tx));
7991 /* Replace the old AVZ in the dir obj with the new one */
7992 VERIFY0(zap_update(spa->spa_meta_objset,
7993 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
7994 sizeof (new_avz), 1, &new_avz, tx));
7996 spa->spa_all_vdev_zaps = new_avz;
7997 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
8001 /* Walk through the AVZ and destroy all listed ZAPs */
8002 for (zap_cursor_init(&zc, spa->spa_meta_objset,
8003 spa->spa_all_vdev_zaps);
8004 zap_cursor_retrieve(&zc, &za) == 0;
8005 zap_cursor_advance(&zc)) {
8006 uint64_t zap = za.za_first_integer;
8007 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
8010 zap_cursor_fini(&zc);
8012 /* Destroy and unlink the AVZ itself */
8013 VERIFY0(zap_destroy(spa->spa_meta_objset,
8014 spa->spa_all_vdev_zaps, tx));
8015 VERIFY0(zap_remove(spa->spa_meta_objset,
8016 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
8017 spa->spa_all_vdev_zaps = 0;
8020 if (spa->spa_all_vdev_zaps == 0) {
8021 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
8022 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
8023 DMU_POOL_VDEV_ZAP_MAP, tx);
8025 spa->spa_avz_action = AVZ_ACTION_NONE;
8027 /* Create ZAPs for vdevs that don't have them. */
8028 vdev_construct_zaps(spa->spa_root_vdev, tx);
8030 config = spa_config_generate(spa, spa->spa_root_vdev,
8031 dmu_tx_get_txg(tx), B_FALSE);
8034 * If we're upgrading the spa version then make sure that
8035 * the config object gets updated with the correct version.
8037 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
8038 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
8039 spa->spa_uberblock.ub_version);
8041 spa_config_exit(spa, SCL_STATE, FTAG);
8043 nvlist_free(spa->spa_config_syncing);
8044 spa->spa_config_syncing = config;
8046 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
8050 spa_sync_version(void *arg, dmu_tx_t *tx)
8052 uint64_t *versionp = arg;
8053 uint64_t version = *versionp;
8054 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
8057 * Setting the version is special cased when first creating the pool.
8059 ASSERT(tx->tx_txg != TXG_INITIAL);
8061 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
8062 ASSERT(version >= spa_version(spa));
8064 spa->spa_uberblock.ub_version = version;
8065 vdev_config_dirty(spa->spa_root_vdev);
8066 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
8070 * Set zpool properties.
8073 spa_sync_props(void *arg, dmu_tx_t *tx)
8075 nvlist_t *nvp = arg;
8076 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
8077 objset_t *mos = spa->spa_meta_objset;
8078 nvpair_t *elem = NULL;
8080 mutex_enter(&spa->spa_props_lock);
8082 while ((elem = nvlist_next_nvpair(nvp, elem))) {
8084 char *strval, *fname;
8086 const char *propname;
8087 zprop_type_t proptype;
8090 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
8091 case ZPOOL_PROP_INVAL:
8093 * We checked this earlier in spa_prop_validate().
8095 ASSERT(zpool_prop_feature(nvpair_name(elem)));
8097 fname = strchr(nvpair_name(elem), '@') + 1;
8098 VERIFY0(zfeature_lookup_name(fname, &fid));
8100 spa_feature_enable(spa, fid, tx);
8101 spa_history_log_internal(spa, "set", tx,
8102 "%s=enabled", nvpair_name(elem));
8105 case ZPOOL_PROP_VERSION:
8106 intval = fnvpair_value_uint64(elem);
8108 * The version is synced seperatly before other
8109 * properties and should be correct by now.
8111 ASSERT3U(spa_version(spa), >=, intval);
8114 case ZPOOL_PROP_ALTROOT:
8116 * 'altroot' is a non-persistent property. It should
8117 * have been set temporarily at creation or import time.
8119 ASSERT(spa->spa_root != NULL);
8122 case ZPOOL_PROP_READONLY:
8123 case ZPOOL_PROP_CACHEFILE:
8125 * 'readonly' and 'cachefile' are also non-persisitent
8129 case ZPOOL_PROP_COMMENT:
8130 strval = fnvpair_value_string(elem);
8131 if (spa->spa_comment != NULL)
8132 spa_strfree(spa->spa_comment);
8133 spa->spa_comment = spa_strdup(strval);
8135 * We need to dirty the configuration on all the vdevs
8136 * so that their labels get updated. It's unnecessary
8137 * to do this for pool creation since the vdev's
8138 * configuratoin has already been dirtied.
8140 if (tx->tx_txg != TXG_INITIAL)
8141 vdev_config_dirty(spa->spa_root_vdev);
8142 spa_history_log_internal(spa, "set", tx,
8143 "%s=%s", nvpair_name(elem), strval);
8147 * Set pool property values in the poolprops mos object.
8149 if (spa->spa_pool_props_object == 0) {
8150 spa->spa_pool_props_object =
8151 zap_create_link(mos, DMU_OT_POOL_PROPS,
8152 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
8156 /* normalize the property name */
8157 propname = zpool_prop_to_name(prop);
8158 proptype = zpool_prop_get_type(prop);
8160 if (nvpair_type(elem) == DATA_TYPE_STRING) {
8161 ASSERT(proptype == PROP_TYPE_STRING);
8162 strval = fnvpair_value_string(elem);
8163 VERIFY0(zap_update(mos,
8164 spa->spa_pool_props_object, propname,
8165 1, strlen(strval) + 1, strval, tx));
8166 spa_history_log_internal(spa, "set", tx,
8167 "%s=%s", nvpair_name(elem), strval);
8168 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
8169 intval = fnvpair_value_uint64(elem);
8171 if (proptype == PROP_TYPE_INDEX) {
8173 VERIFY0(zpool_prop_index_to_string(
8174 prop, intval, &unused));
8176 VERIFY0(zap_update(mos,
8177 spa->spa_pool_props_object, propname,
8178 8, 1, &intval, tx));
8179 spa_history_log_internal(spa, "set", tx,
8180 "%s=%lld", nvpair_name(elem), intval);
8182 ASSERT(0); /* not allowed */
8186 case ZPOOL_PROP_DELEGATION:
8187 spa->spa_delegation = intval;
8189 case ZPOOL_PROP_BOOTFS:
8190 spa->spa_bootfs = intval;
8192 case ZPOOL_PROP_FAILUREMODE:
8193 spa->spa_failmode = intval;
8195 case ZPOOL_PROP_AUTOEXPAND:
8196 spa->spa_autoexpand = intval;
8197 if (tx->tx_txg != TXG_INITIAL)
8198 spa_async_request(spa,
8199 SPA_ASYNC_AUTOEXPAND);
8201 case ZPOOL_PROP_MULTIHOST:
8202 spa->spa_multihost = intval;
8204 case ZPOOL_PROP_DEDUPDITTO:
8205 spa->spa_dedup_ditto = intval;
8214 mutex_exit(&spa->spa_props_lock);
8218 * Perform one-time upgrade on-disk changes. spa_version() does not
8219 * reflect the new version this txg, so there must be no changes this
8220 * txg to anything that the upgrade code depends on after it executes.
8221 * Therefore this must be called after dsl_pool_sync() does the sync
8225 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
8227 dsl_pool_t *dp = spa->spa_dsl_pool;
8229 ASSERT(spa->spa_sync_pass == 1);
8231 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
8233 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
8234 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
8235 dsl_pool_create_origin(dp, tx);
8237 /* Keeping the origin open increases spa_minref */
8238 spa->spa_minref += 3;
8241 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
8242 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
8243 dsl_pool_upgrade_clones(dp, tx);
8246 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
8247 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
8248 dsl_pool_upgrade_dir_clones(dp, tx);
8250 /* Keeping the freedir open increases spa_minref */
8251 spa->spa_minref += 3;
8254 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
8255 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8256 spa_feature_create_zap_objects(spa, tx);
8260 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
8261 * when possibility to use lz4 compression for metadata was added
8262 * Old pools that have this feature enabled must be upgraded to have
8263 * this feature active
8265 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
8266 boolean_t lz4_en = spa_feature_is_enabled(spa,
8267 SPA_FEATURE_LZ4_COMPRESS);
8268 boolean_t lz4_ac = spa_feature_is_active(spa,
8269 SPA_FEATURE_LZ4_COMPRESS);
8271 if (lz4_en && !lz4_ac)
8272 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
8276 * If we haven't written the salt, do so now. Note that the
8277 * feature may not be activated yet, but that's fine since
8278 * the presence of this ZAP entry is backwards compatible.
8280 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
8281 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
8282 VERIFY0(zap_add(spa->spa_meta_objset,
8283 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
8284 sizeof (spa->spa_cksum_salt.zcs_bytes),
8285 spa->spa_cksum_salt.zcs_bytes, tx));
8288 rrw_exit(&dp->dp_config_rwlock, FTAG);
8292 vdev_indirect_state_sync_verify(vdev_t *vd)
8294 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
8295 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
8297 if (vd->vdev_ops == &vdev_indirect_ops) {
8298 ASSERT(vim != NULL);
8299 ASSERT(vib != NULL);
8302 if (vdev_obsolete_sm_object(vd) != 0) {
8303 ASSERT(vd->vdev_obsolete_sm != NULL);
8304 ASSERT(vd->vdev_removing ||
8305 vd->vdev_ops == &vdev_indirect_ops);
8306 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
8307 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
8309 ASSERT3U(vdev_obsolete_sm_object(vd), ==,
8310 space_map_object(vd->vdev_obsolete_sm));
8311 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
8312 space_map_allocated(vd->vdev_obsolete_sm));
8314 ASSERT(vd->vdev_obsolete_segments != NULL);
8317 * Since frees / remaps to an indirect vdev can only
8318 * happen in syncing context, the obsolete segments
8319 * tree must be empty when we start syncing.
8321 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
8325 * Sync the specified transaction group. New blocks may be dirtied as
8326 * part of the process, so we iterate until it converges.
8329 spa_sync(spa_t *spa, uint64_t txg)
8331 dsl_pool_t *dp = spa->spa_dsl_pool;
8332 objset_t *mos = spa->spa_meta_objset;
8333 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
8334 metaslab_class_t *normal = spa_normal_class(spa);
8335 metaslab_class_t *special = spa_special_class(spa);
8336 metaslab_class_t *dedup = spa_dedup_class(spa);
8337 vdev_t *rvd = spa->spa_root_vdev;
8341 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
8342 zfs_vdev_queue_depth_pct / 100;
8344 VERIFY(spa_writeable(spa));
8347 * Wait for i/os issued in open context that need to complete
8348 * before this txg syncs.
8350 (void) zio_wait(spa->spa_txg_zio[txg & TXG_MASK]);
8351 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL,
8355 * Lock out configuration changes.
8357 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8359 spa->spa_syncing_txg = txg;
8360 spa->spa_sync_pass = 0;
8362 for (int i = 0; i < spa->spa_alloc_count; i++) {
8363 mutex_enter(&spa->spa_alloc_locks[i]);
8364 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8365 mutex_exit(&spa->spa_alloc_locks[i]);
8369 * If there are any pending vdev state changes, convert them
8370 * into config changes that go out with this transaction group.
8372 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8373 while (list_head(&spa->spa_state_dirty_list) != NULL) {
8375 * We need the write lock here because, for aux vdevs,
8376 * calling vdev_config_dirty() modifies sav_config.
8377 * This is ugly and will become unnecessary when we
8378 * eliminate the aux vdev wart by integrating all vdevs
8379 * into the root vdev tree.
8381 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8382 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
8383 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
8384 vdev_state_clean(vd);
8385 vdev_config_dirty(vd);
8387 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
8388 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
8390 spa_config_exit(spa, SCL_STATE, FTAG);
8392 tx = dmu_tx_create_assigned(dp, txg);
8394 spa->spa_sync_starttime = gethrtime();
8396 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
8397 spa->spa_sync_starttime + spa->spa_deadman_synctime));
8398 #else /* !illumos */
8400 callout_schedule(&spa->spa_deadman_cycid,
8401 hz * spa->spa_deadman_synctime / NANOSEC);
8403 #endif /* illumos */
8406 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
8407 * set spa_deflate if we have no raid-z vdevs.
8409 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
8410 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
8413 for (i = 0; i < rvd->vdev_children; i++) {
8414 vd = rvd->vdev_child[i];
8415 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
8418 if (i == rvd->vdev_children) {
8419 spa->spa_deflate = TRUE;
8420 VERIFY(0 == zap_add(spa->spa_meta_objset,
8421 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
8422 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
8427 * Set the top-level vdev's max queue depth. Evaluate each
8428 * top-level's async write queue depth in case it changed.
8429 * The max queue depth will not change in the middle of syncing
8432 uint64_t slots_per_allocator = 0;
8433 for (int c = 0; c < rvd->vdev_children; c++) {
8434 vdev_t *tvd = rvd->vdev_child[c];
8435 metaslab_group_t *mg = tvd->vdev_mg;
8436 metaslab_class_t *mc;
8438 if (mg == NULL || !metaslab_group_initialized(mg))
8442 if (mc != normal && mc != special && mc != dedup)
8446 * It is safe to do a lock-free check here because only async
8447 * allocations look at mg_max_alloc_queue_depth, and async
8448 * allocations all happen from spa_sync().
8450 for (int i = 0; i < spa->spa_alloc_count; i++)
8451 ASSERT0(zfs_refcount_count(
8452 &(mg->mg_alloc_queue_depth[i])));
8453 mg->mg_max_alloc_queue_depth = max_queue_depth;
8455 for (int i = 0; i < spa->spa_alloc_count; i++) {
8456 mg->mg_cur_max_alloc_queue_depth[i] =
8457 zfs_vdev_def_queue_depth;
8459 slots_per_allocator += zfs_vdev_def_queue_depth;
8462 for (int i = 0; i < spa->spa_alloc_count; i++) {
8463 ASSERT0(zfs_refcount_count(&normal->mc_alloc_slots[i]));
8464 ASSERT0(zfs_refcount_count(&special->mc_alloc_slots[i]));
8465 ASSERT0(zfs_refcount_count(&dedup->mc_alloc_slots[i]));
8466 normal->mc_alloc_max_slots[i] = slots_per_allocator;
8467 special->mc_alloc_max_slots[i] = slots_per_allocator;
8468 dedup->mc_alloc_max_slots[i] = slots_per_allocator;
8470 normal->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8471 special->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8472 dedup->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8474 for (int c = 0; c < rvd->vdev_children; c++) {
8475 vdev_t *vd = rvd->vdev_child[c];
8476 vdev_indirect_state_sync_verify(vd);
8478 if (vdev_indirect_should_condense(vd)) {
8479 spa_condense_indirect_start_sync(vd, tx);
8485 * Iterate to convergence.
8488 int pass = ++spa->spa_sync_pass;
8490 spa_sync_config_object(spa, tx);
8491 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
8492 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
8493 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
8494 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
8495 spa_errlog_sync(spa, txg);
8496 dsl_pool_sync(dp, txg);
8498 if (pass < zfs_sync_pass_deferred_free) {
8499 spa_sync_frees(spa, free_bpl, tx);
8502 * We can not defer frees in pass 1, because
8503 * we sync the deferred frees later in pass 1.
8505 ASSERT3U(pass, >, 1);
8506 bplist_iterate(free_bpl, bpobj_enqueue_cb,
8507 &spa->spa_deferred_bpobj, tx);
8511 dsl_scan_sync(dp, tx);
8513 if (spa->spa_vdev_removal != NULL)
8516 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
8521 spa_sync_upgrades(spa, tx);
8523 spa->spa_uberblock.ub_rootbp.blk_birth);
8525 * Note: We need to check if the MOS is dirty
8526 * because we could have marked the MOS dirty
8527 * without updating the uberblock (e.g. if we
8528 * have sync tasks but no dirty user data). We
8529 * need to check the uberblock's rootbp because
8530 * it is updated if we have synced out dirty
8531 * data (though in this case the MOS will most
8532 * likely also be dirty due to second order
8533 * effects, we don't want to rely on that here).
8535 if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
8536 !dmu_objset_is_dirty(mos, txg)) {
8538 * Nothing changed on the first pass,
8539 * therefore this TXG is a no-op. Avoid
8540 * syncing deferred frees, so that we
8541 * can keep this TXG as a no-op.
8543 ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
8545 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8546 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
8547 ASSERT(txg_list_empty(&dp->dp_early_sync_tasks,
8551 spa_sync_deferred_frees(spa, tx);
8554 } while (dmu_objset_is_dirty(mos, txg));
8556 if (!list_is_empty(&spa->spa_config_dirty_list)) {
8558 * Make sure that the number of ZAPs for all the vdevs matches
8559 * the number of ZAPs in the per-vdev ZAP list. This only gets
8560 * called if the config is dirty; otherwise there may be
8561 * outstanding AVZ operations that weren't completed in
8562 * spa_sync_config_object.
8564 uint64_t all_vdev_zap_entry_count;
8565 ASSERT0(zap_count(spa->spa_meta_objset,
8566 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
8567 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
8568 all_vdev_zap_entry_count);
8571 if (spa->spa_vdev_removal != NULL) {
8572 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
8576 * Rewrite the vdev configuration (which includes the uberblock)
8577 * to commit the transaction group.
8579 * If there are no dirty vdevs, we sync the uberblock to a few
8580 * random top-level vdevs that are known to be visible in the
8581 * config cache (see spa_vdev_add() for a complete description).
8582 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
8586 * We hold SCL_STATE to prevent vdev open/close/etc.
8587 * while we're attempting to write the vdev labels.
8589 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8591 if (list_is_empty(&spa->spa_config_dirty_list)) {
8592 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
8594 int children = rvd->vdev_children;
8595 int c0 = spa_get_random(children);
8597 for (int c = 0; c < children; c++) {
8598 vd = rvd->vdev_child[(c0 + c) % children];
8600 /* Stop when revisiting the first vdev */
8601 if (c > 0 && svd[0] == vd)
8604 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
8605 !vdev_is_concrete(vd))
8608 svd[svdcount++] = vd;
8609 if (svdcount == SPA_SYNC_MIN_VDEVS)
8612 error = vdev_config_sync(svd, svdcount, txg);
8614 error = vdev_config_sync(rvd->vdev_child,
8615 rvd->vdev_children, txg);
8619 spa->spa_last_synced_guid = rvd->vdev_guid;
8621 spa_config_exit(spa, SCL_STATE, FTAG);
8625 zio_suspend(spa, NULL, ZIO_SUSPEND_IOERR);
8626 zio_resume_wait(spa);
8631 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
8632 #else /* !illumos */
8634 callout_drain(&spa->spa_deadman_cycid);
8636 #endif /* illumos */
8639 * Clear the dirty config list.
8641 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
8642 vdev_config_clean(vd);
8645 * Now that the new config has synced transactionally,
8646 * let it become visible to the config cache.
8648 if (spa->spa_config_syncing != NULL) {
8649 spa_config_set(spa, spa->spa_config_syncing);
8650 spa->spa_config_txg = txg;
8651 spa->spa_config_syncing = NULL;
8654 dsl_pool_sync_done(dp, txg);
8656 for (int i = 0; i < spa->spa_alloc_count; i++) {
8657 mutex_enter(&spa->spa_alloc_locks[i]);
8658 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8659 mutex_exit(&spa->spa_alloc_locks[i]);
8663 * Update usable space statistics.
8665 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
8667 vdev_sync_done(vd, txg);
8669 spa_update_dspace(spa);
8672 * It had better be the case that we didn't dirty anything
8673 * since vdev_config_sync().
8675 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8676 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8677 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
8679 while (zfs_pause_spa_sync)
8682 spa->spa_sync_pass = 0;
8685 * Update the last synced uberblock here. We want to do this at
8686 * the end of spa_sync() so that consumers of spa_last_synced_txg()
8687 * will be guaranteed that all the processing associated with
8688 * that txg has been completed.
8690 spa->spa_ubsync = spa->spa_uberblock;
8691 spa_config_exit(spa, SCL_CONFIG, FTAG);
8693 spa_handle_ignored_writes(spa);
8696 * If any async tasks have been requested, kick them off.
8698 spa_async_dispatch(spa);
8699 spa_async_dispatch_vd(spa);
8703 * Sync all pools. We don't want to hold the namespace lock across these
8704 * operations, so we take a reference on the spa_t and drop the lock during the
8708 spa_sync_allpools(void)
8711 mutex_enter(&spa_namespace_lock);
8712 while ((spa = spa_next(spa)) != NULL) {
8713 if (spa_state(spa) != POOL_STATE_ACTIVE ||
8714 !spa_writeable(spa) || spa_suspended(spa))
8716 spa_open_ref(spa, FTAG);
8717 mutex_exit(&spa_namespace_lock);
8718 txg_wait_synced(spa_get_dsl(spa), 0);
8719 mutex_enter(&spa_namespace_lock);
8720 spa_close(spa, FTAG);
8722 mutex_exit(&spa_namespace_lock);
8726 * ==========================================================================
8727 * Miscellaneous routines
8728 * ==========================================================================
8732 * Remove all pools in the system.
8740 * Remove all cached state. All pools should be closed now,
8741 * so every spa in the AVL tree should be unreferenced.
8743 mutex_enter(&spa_namespace_lock);
8744 while ((spa = spa_next(NULL)) != NULL) {
8746 * Stop async tasks. The async thread may need to detach
8747 * a device that's been replaced, which requires grabbing
8748 * spa_namespace_lock, so we must drop it here.
8750 spa_open_ref(spa, FTAG);
8751 mutex_exit(&spa_namespace_lock);
8752 spa_async_suspend(spa);
8753 mutex_enter(&spa_namespace_lock);
8754 spa_close(spa, FTAG);
8756 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
8758 spa_deactivate(spa);
8762 mutex_exit(&spa_namespace_lock);
8766 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
8771 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
8775 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
8776 vd = spa->spa_l2cache.sav_vdevs[i];
8777 if (vd->vdev_guid == guid)
8781 for (i = 0; i < spa->spa_spares.sav_count; i++) {
8782 vd = spa->spa_spares.sav_vdevs[i];
8783 if (vd->vdev_guid == guid)
8792 spa_upgrade(spa_t *spa, uint64_t version)
8794 ASSERT(spa_writeable(spa));
8796 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
8799 * This should only be called for a non-faulted pool, and since a
8800 * future version would result in an unopenable pool, this shouldn't be
8803 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
8804 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
8806 spa->spa_uberblock.ub_version = version;
8807 vdev_config_dirty(spa->spa_root_vdev);
8809 spa_config_exit(spa, SCL_ALL, FTAG);
8811 txg_wait_synced(spa_get_dsl(spa), 0);
8815 spa_has_spare(spa_t *spa, uint64_t guid)
8819 spa_aux_vdev_t *sav = &spa->spa_spares;
8821 for (i = 0; i < sav->sav_count; i++)
8822 if (sav->sav_vdevs[i]->vdev_guid == guid)
8825 for (i = 0; i < sav->sav_npending; i++) {
8826 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
8827 &spareguid) == 0 && spareguid == guid)
8835 * Check if a pool has an active shared spare device.
8836 * Note: reference count of an active spare is 2, as a spare and as a replace
8839 spa_has_active_shared_spare(spa_t *spa)
8843 spa_aux_vdev_t *sav = &spa->spa_spares;
8845 for (i = 0; i < sav->sav_count; i++) {
8846 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
8847 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
8856 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8858 sysevent_t *ev = NULL;
8860 sysevent_attr_list_t *attr = NULL;
8861 sysevent_value_t value;
8863 ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
8867 value.value_type = SE_DATA_TYPE_STRING;
8868 value.value.sv_string = spa_name(spa);
8869 if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
8872 value.value_type = SE_DATA_TYPE_UINT64;
8873 value.value.sv_uint64 = spa_guid(spa);
8874 if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
8878 value.value_type = SE_DATA_TYPE_UINT64;
8879 value.value.sv_uint64 = vd->vdev_guid;
8880 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
8884 if (vd->vdev_path) {
8885 value.value_type = SE_DATA_TYPE_STRING;
8886 value.value.sv_string = vd->vdev_path;
8887 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
8888 &value, SE_SLEEP) != 0)
8893 if (hist_nvl != NULL) {
8894 fnvlist_merge((nvlist_t *)attr, hist_nvl);
8897 if (sysevent_attach_attributes(ev, attr) != 0)
8903 sysevent_free_attr(attr);
8910 spa_event_post(sysevent_t *ev)
8915 (void) log_sysevent(ev, SE_SLEEP, &eid);
8921 spa_event_discard(sysevent_t *ev)
8929 * Post a sysevent corresponding to the given event. The 'name' must be one of
8930 * the event definitions in sys/sysevent/eventdefs.h. The payload will be
8931 * filled in from the spa and (optionally) the vdev and history nvl. This
8932 * doesn't do anything in the userland libzpool, as we don't want consumers to
8933 * misinterpret ztest or zdb as real changes.
8936 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8938 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));