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 2017 Joyent, Inc.
32 * Copyright (c) 2017 Datto Inc.
33 * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
37 * SPA: Storage Pool Allocator
39 * This file contains all the routines used when modifying on-disk SPA state.
40 * This includes opening, importing, destroying, exporting a pool, and syncing a
44 #include <sys/zfs_context.h>
45 #include <sys/fm/fs/zfs.h>
46 #include <sys/spa_impl.h>
48 #include <sys/zio_checksum.h>
50 #include <sys/dmu_tx.h>
54 #include <sys/vdev_impl.h>
55 #include <sys/vdev_removal.h>
56 #include <sys/vdev_indirect_mapping.h>
57 #include <sys/vdev_indirect_births.h>
58 #include <sys/vdev_initialize.h>
59 #include <sys/metaslab.h>
60 #include <sys/metaslab_impl.h>
61 #include <sys/uberblock_impl.h>
64 #include <sys/bpobj.h>
65 #include <sys/dmu_traverse.h>
66 #include <sys/dmu_objset.h>
67 #include <sys/unique.h>
68 #include <sys/dsl_pool.h>
69 #include <sys/dsl_dataset.h>
70 #include <sys/dsl_dir.h>
71 #include <sys/dsl_prop.h>
72 #include <sys/dsl_synctask.h>
73 #include <sys/fs/zfs.h>
75 #include <sys/callb.h>
76 #include <sys/spa_boot.h>
77 #include <sys/zfs_ioctl.h>
78 #include <sys/dsl_scan.h>
79 #include <sys/dmu_send.h>
80 #include <sys/dsl_destroy.h>
81 #include <sys/dsl_userhold.h>
82 #include <sys/zfeature.h>
84 #include <sys/trim_map.h>
88 #include <sys/callb.h>
89 #include <sys/cpupart.h>
94 #include "zfs_comutil.h"
96 /* Check hostid on import? */
97 static int check_hostid = 1;
100 * The interval, in seconds, at which failed configuration cache file writes
103 int zfs_ccw_retry_interval = 300;
105 SYSCTL_DECL(_vfs_zfs);
106 SYSCTL_INT(_vfs_zfs, OID_AUTO, check_hostid, CTLFLAG_RWTUN, &check_hostid, 0,
107 "Check hostid on import?");
108 TUNABLE_INT("vfs.zfs.ccw_retry_interval", &zfs_ccw_retry_interval);
109 SYSCTL_INT(_vfs_zfs, OID_AUTO, ccw_retry_interval, CTLFLAG_RW,
110 &zfs_ccw_retry_interval, 0,
111 "Configuration cache file write, retry after failure, interval (seconds)");
113 typedef enum zti_modes {
114 ZTI_MODE_FIXED, /* value is # of threads (min 1) */
115 ZTI_MODE_BATCH, /* cpu-intensive; value is ignored */
116 ZTI_MODE_NULL, /* don't create a taskq */
120 #define ZTI_P(n, q) { ZTI_MODE_FIXED, (n), (q) }
121 #define ZTI_BATCH { ZTI_MODE_BATCH, 0, 1 }
122 #define ZTI_NULL { ZTI_MODE_NULL, 0, 0 }
124 #define ZTI_N(n) ZTI_P(n, 1)
125 #define ZTI_ONE ZTI_N(1)
127 typedef struct zio_taskq_info {
128 zti_modes_t zti_mode;
133 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
134 "issue", "issue_high", "intr", "intr_high"
138 * This table defines the taskq settings for each ZFS I/O type. When
139 * initializing a pool, we use this table to create an appropriately sized
140 * taskq. Some operations are low volume and therefore have a small, static
141 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
142 * macros. Other operations process a large amount of data; the ZTI_BATCH
143 * macro causes us to create a taskq oriented for throughput. Some operations
144 * are so high frequency and short-lived that the taskq itself can become a a
145 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
146 * additional degree of parallelism specified by the number of threads per-
147 * taskq and the number of taskqs; when dispatching an event in this case, the
148 * particular taskq is chosen at random.
150 * The different taskq priorities are to handle the different contexts (issue
151 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
152 * need to be handled with minimum delay.
154 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
155 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
156 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* NULL */
157 { ZTI_N(8), ZTI_NULL, ZTI_P(12, 8), ZTI_NULL }, /* READ */
158 { ZTI_BATCH, ZTI_N(5), ZTI_N(8), ZTI_N(5) }, /* WRITE */
159 { ZTI_P(12, 8), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* FREE */
160 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* CLAIM */
161 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* IOCTL */
164 static void spa_sync_version(void *arg, dmu_tx_t *tx);
165 static void spa_sync_props(void *arg, dmu_tx_t *tx);
166 static boolean_t spa_has_active_shared_spare(spa_t *spa);
167 static int spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport);
168 static void spa_vdev_resilver_done(spa_t *spa);
170 uint_t zio_taskq_batch_pct = 75; /* 1 thread per cpu in pset */
172 id_t zio_taskq_psrset_bind = PS_NONE;
175 boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
176 uint_t zio_taskq_basedc = 80; /* base duty cycle */
179 boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
180 extern int zfs_sync_pass_deferred_free;
183 * Report any spa_load_verify errors found, but do not fail spa_load.
184 * This is used by zdb to analyze non-idle pools.
186 boolean_t spa_load_verify_dryrun = B_FALSE;
189 * This (illegal) pool name is used when temporarily importing a spa_t in order
190 * to get the vdev stats associated with the imported devices.
192 #define TRYIMPORT_NAME "$import"
195 * For debugging purposes: print out vdev tree during pool import.
197 int spa_load_print_vdev_tree = B_FALSE;
200 * A non-zero value for zfs_max_missing_tvds means that we allow importing
201 * pools with missing top-level vdevs. This is strictly intended for advanced
202 * pool recovery cases since missing data is almost inevitable. Pools with
203 * missing devices can only be imported read-only for safety reasons, and their
204 * fail-mode will be automatically set to "continue".
206 * With 1 missing vdev we should be able to import the pool and mount all
207 * datasets. User data that was not modified after the missing device has been
208 * added should be recoverable. This means that snapshots created prior to the
209 * addition of that device should be completely intact.
211 * With 2 missing vdevs, some datasets may fail to mount since there are
212 * dataset statistics that are stored as regular metadata. Some data might be
213 * recoverable if those vdevs were added recently.
215 * With 3 or more missing vdevs, the pool is severely damaged and MOS entries
216 * may be missing entirely. Chances of data recovery are very low. Note that
217 * there are also risks of performing an inadvertent rewind as we might be
218 * missing all the vdevs with the latest uberblocks.
220 uint64_t zfs_max_missing_tvds = 0;
223 * The parameters below are similar to zfs_max_missing_tvds but are only
224 * intended for a preliminary open of the pool with an untrusted config which
225 * might be incomplete or out-dated.
227 * We are more tolerant for pools opened from a cachefile since we could have
228 * an out-dated cachefile where a device removal was not registered.
229 * We could have set the limit arbitrarily high but in the case where devices
230 * are really missing we would want to return the proper error codes; we chose
231 * SPA_DVAS_PER_BP - 1 so that some copies of the MOS would still be available
232 * and we get a chance to retrieve the trusted config.
234 uint64_t zfs_max_missing_tvds_cachefile = SPA_DVAS_PER_BP - 1;
237 * In the case where config was assembled by scanning device paths (/dev/dsks
238 * by default) we are less tolerant since all the existing devices should have
239 * been detected and we want spa_load to return the right error codes.
241 uint64_t zfs_max_missing_tvds_scan = 0;
244 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_print_vdev_tree, CTLFLAG_RWTUN,
245 &spa_load_print_vdev_tree, 0,
246 "print out vdev tree during pool import");
247 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds, CTLFLAG_RWTUN,
248 &zfs_max_missing_tvds, 0,
249 "allow importing pools with missing top-level vdevs");
250 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_cachefile, CTLFLAG_RWTUN,
251 &zfs_max_missing_tvds_cachefile, 0,
252 "allow importing pools with missing top-level vdevs in cache file");
253 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_scan, CTLFLAG_RWTUN,
254 &zfs_max_missing_tvds_scan, 0,
255 "allow importing pools with missing top-level vdevs during scan");
258 * Debugging aid that pauses spa_sync() towards the end.
260 boolean_t zfs_pause_spa_sync = B_FALSE;
263 * ==========================================================================
264 * SPA properties routines
265 * ==========================================================================
269 * Add a (source=src, propname=propval) list to an nvlist.
272 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
273 uint64_t intval, zprop_source_t src)
275 const char *propname = zpool_prop_to_name(prop);
278 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
279 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
282 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
284 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
286 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
287 nvlist_free(propval);
291 * Get property values from the spa configuration.
294 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
296 vdev_t *rvd = spa->spa_root_vdev;
297 dsl_pool_t *pool = spa->spa_dsl_pool;
298 uint64_t size, alloc, cap, version;
299 zprop_source_t src = ZPROP_SRC_NONE;
300 spa_config_dirent_t *dp;
301 metaslab_class_t *mc = spa_normal_class(spa);
303 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
306 alloc = metaslab_class_get_alloc(spa_normal_class(spa));
307 size = metaslab_class_get_space(spa_normal_class(spa));
308 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
309 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
310 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
311 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
313 spa_prop_add_list(*nvp, ZPOOL_PROP_CHECKPOINT, NULL,
314 spa->spa_checkpoint_info.sci_dspace, src);
316 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
317 metaslab_class_fragmentation(mc), src);
318 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
319 metaslab_class_expandable_space(mc), src);
320 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
321 (spa_mode(spa) == FREAD), src);
323 cap = (size == 0) ? 0 : (alloc * 100 / size);
324 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
326 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
327 ddt_get_pool_dedup_ratio(spa), src);
329 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
330 rvd->vdev_state, src);
332 version = spa_version(spa);
333 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
334 src = ZPROP_SRC_DEFAULT;
336 src = ZPROP_SRC_LOCAL;
337 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
342 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
343 * when opening pools before this version freedir will be NULL.
345 if (pool->dp_free_dir != NULL) {
346 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
347 dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
350 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
354 if (pool->dp_leak_dir != NULL) {
355 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
356 dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
359 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
364 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
366 if (spa->spa_comment != NULL) {
367 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
371 if (spa->spa_root != NULL)
372 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
375 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
376 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
377 MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
379 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
380 SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
383 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE)) {
384 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
385 DNODE_MAX_SIZE, ZPROP_SRC_NONE);
387 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXDNODESIZE, NULL,
388 DNODE_MIN_SIZE, ZPROP_SRC_NONE);
391 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
392 if (dp->scd_path == NULL) {
393 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
394 "none", 0, ZPROP_SRC_LOCAL);
395 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
396 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
397 dp->scd_path, 0, ZPROP_SRC_LOCAL);
403 * Get zpool property values.
406 spa_prop_get(spa_t *spa, nvlist_t **nvp)
408 objset_t *mos = spa->spa_meta_objset;
413 VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
415 mutex_enter(&spa->spa_props_lock);
418 * Get properties from the spa config.
420 spa_prop_get_config(spa, nvp);
422 /* If no pool property object, no more prop to get. */
423 if (mos == NULL || spa->spa_pool_props_object == 0) {
424 mutex_exit(&spa->spa_props_lock);
429 * Get properties from the MOS pool property object.
431 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
432 (err = zap_cursor_retrieve(&zc, &za)) == 0;
433 zap_cursor_advance(&zc)) {
436 zprop_source_t src = ZPROP_SRC_DEFAULT;
439 if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
442 switch (za.za_integer_length) {
444 /* integer property */
445 if (za.za_first_integer !=
446 zpool_prop_default_numeric(prop))
447 src = ZPROP_SRC_LOCAL;
449 if (prop == ZPOOL_PROP_BOOTFS) {
451 dsl_dataset_t *ds = NULL;
453 dp = spa_get_dsl(spa);
454 dsl_pool_config_enter(dp, FTAG);
455 err = dsl_dataset_hold_obj(dp,
456 za.za_first_integer, FTAG, &ds);
458 dsl_pool_config_exit(dp, FTAG);
462 strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
464 dsl_dataset_name(ds, strval);
465 dsl_dataset_rele(ds, FTAG);
466 dsl_pool_config_exit(dp, FTAG);
469 intval = za.za_first_integer;
472 spa_prop_add_list(*nvp, prop, strval, intval, src);
475 kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
480 /* string property */
481 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
482 err = zap_lookup(mos, spa->spa_pool_props_object,
483 za.za_name, 1, za.za_num_integers, strval);
485 kmem_free(strval, za.za_num_integers);
488 spa_prop_add_list(*nvp, prop, strval, 0, src);
489 kmem_free(strval, za.za_num_integers);
496 zap_cursor_fini(&zc);
497 mutex_exit(&spa->spa_props_lock);
499 if (err && err != ENOENT) {
509 * Validate the given pool properties nvlist and modify the list
510 * for the property values to be set.
513 spa_prop_validate(spa_t *spa, nvlist_t *props)
516 int error = 0, reset_bootfs = 0;
518 boolean_t has_feature = B_FALSE;
521 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
523 char *strval, *slash, *check, *fname;
524 const char *propname = nvpair_name(elem);
525 zpool_prop_t prop = zpool_name_to_prop(propname);
528 case ZPOOL_PROP_INVAL:
529 if (!zpool_prop_feature(propname)) {
530 error = SET_ERROR(EINVAL);
535 * Sanitize the input.
537 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
538 error = SET_ERROR(EINVAL);
542 if (nvpair_value_uint64(elem, &intval) != 0) {
543 error = SET_ERROR(EINVAL);
548 error = SET_ERROR(EINVAL);
552 fname = strchr(propname, '@') + 1;
553 if (zfeature_lookup_name(fname, NULL) != 0) {
554 error = SET_ERROR(EINVAL);
558 has_feature = B_TRUE;
561 case ZPOOL_PROP_VERSION:
562 error = nvpair_value_uint64(elem, &intval);
564 (intval < spa_version(spa) ||
565 intval > SPA_VERSION_BEFORE_FEATURES ||
567 error = SET_ERROR(EINVAL);
570 case ZPOOL_PROP_DELEGATION:
571 case ZPOOL_PROP_AUTOREPLACE:
572 case ZPOOL_PROP_LISTSNAPS:
573 case ZPOOL_PROP_AUTOEXPAND:
574 error = nvpair_value_uint64(elem, &intval);
575 if (!error && intval > 1)
576 error = SET_ERROR(EINVAL);
579 case ZPOOL_PROP_BOOTFS:
581 * If the pool version is less than SPA_VERSION_BOOTFS,
582 * or the pool is still being created (version == 0),
583 * the bootfs property cannot be set.
585 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
586 error = SET_ERROR(ENOTSUP);
591 * Make sure the vdev config is bootable
593 if (!vdev_is_bootable(spa->spa_root_vdev)) {
594 error = SET_ERROR(ENOTSUP);
600 error = nvpair_value_string(elem, &strval);
606 if (strval == NULL || strval[0] == '\0') {
607 objnum = zpool_prop_default_numeric(
612 error = dmu_objset_hold(strval, FTAG, &os);
617 * Must be ZPL, and its property settings
618 * must be supported by GRUB (compression
619 * is not gzip, and large blocks or large
620 * dnodes are not used).
623 if (dmu_objset_type(os) != DMU_OST_ZFS) {
624 error = SET_ERROR(ENOTSUP);
626 dsl_prop_get_int_ds(dmu_objset_ds(os),
627 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
629 !BOOTFS_COMPRESS_VALID(propval)) {
630 error = SET_ERROR(ENOTSUP);
632 dsl_prop_get_int_ds(dmu_objset_ds(os),
633 zfs_prop_to_name(ZFS_PROP_DNODESIZE),
635 propval != ZFS_DNSIZE_LEGACY) {
636 error = SET_ERROR(ENOTSUP);
638 objnum = dmu_objset_id(os);
640 dmu_objset_rele(os, FTAG);
644 case ZPOOL_PROP_FAILUREMODE:
645 error = nvpair_value_uint64(elem, &intval);
646 if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
647 intval > ZIO_FAILURE_MODE_PANIC))
648 error = SET_ERROR(EINVAL);
651 * This is a special case which only occurs when
652 * the pool has completely failed. This allows
653 * the user to change the in-core failmode property
654 * without syncing it out to disk (I/Os might
655 * currently be blocked). We do this by returning
656 * EIO to the caller (spa_prop_set) to trick it
657 * into thinking we encountered a property validation
660 if (!error && spa_suspended(spa)) {
661 spa->spa_failmode = intval;
662 error = SET_ERROR(EIO);
666 case ZPOOL_PROP_CACHEFILE:
667 if ((error = nvpair_value_string(elem, &strval)) != 0)
670 if (strval[0] == '\0')
673 if (strcmp(strval, "none") == 0)
676 if (strval[0] != '/') {
677 error = SET_ERROR(EINVAL);
681 slash = strrchr(strval, '/');
682 ASSERT(slash != NULL);
684 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
685 strcmp(slash, "/..") == 0)
686 error = SET_ERROR(EINVAL);
689 case ZPOOL_PROP_COMMENT:
690 if ((error = nvpair_value_string(elem, &strval)) != 0)
692 for (check = strval; *check != '\0'; check++) {
694 * The kernel doesn't have an easy isprint()
695 * check. For this kernel check, we merely
696 * check ASCII apart from DEL. Fix this if
697 * there is an easy-to-use kernel isprint().
699 if (*check >= 0x7f) {
700 error = SET_ERROR(EINVAL);
704 if (strlen(strval) > ZPROP_MAX_COMMENT)
708 case ZPOOL_PROP_DEDUPDITTO:
709 if (spa_version(spa) < SPA_VERSION_DEDUP)
710 error = SET_ERROR(ENOTSUP);
712 error = nvpair_value_uint64(elem, &intval);
714 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
715 error = SET_ERROR(EINVAL);
723 if (!error && reset_bootfs) {
724 error = nvlist_remove(props,
725 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
728 error = nvlist_add_uint64(props,
729 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
737 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
740 spa_config_dirent_t *dp;
742 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
746 dp = kmem_alloc(sizeof (spa_config_dirent_t),
749 if (cachefile[0] == '\0')
750 dp->scd_path = spa_strdup(spa_config_path);
751 else if (strcmp(cachefile, "none") == 0)
754 dp->scd_path = spa_strdup(cachefile);
756 list_insert_head(&spa->spa_config_list, dp);
758 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
762 spa_prop_set(spa_t *spa, nvlist_t *nvp)
765 nvpair_t *elem = NULL;
766 boolean_t need_sync = B_FALSE;
768 if ((error = spa_prop_validate(spa, nvp)) != 0)
771 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
772 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
774 if (prop == ZPOOL_PROP_CACHEFILE ||
775 prop == ZPOOL_PROP_ALTROOT ||
776 prop == ZPOOL_PROP_READONLY)
779 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
782 if (prop == ZPOOL_PROP_VERSION) {
783 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
785 ASSERT(zpool_prop_feature(nvpair_name(elem)));
786 ver = SPA_VERSION_FEATURES;
790 /* Save time if the version is already set. */
791 if (ver == spa_version(spa))
795 * In addition to the pool directory object, we might
796 * create the pool properties object, the features for
797 * read object, the features for write object, or the
798 * feature descriptions object.
800 error = dsl_sync_task(spa->spa_name, NULL,
801 spa_sync_version, &ver,
802 6, ZFS_SPACE_CHECK_RESERVED);
813 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
814 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
821 * If the bootfs property value is dsobj, clear it.
824 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
826 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
827 VERIFY(zap_remove(spa->spa_meta_objset,
828 spa->spa_pool_props_object,
829 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
836 spa_change_guid_check(void *arg, dmu_tx_t *tx)
838 uint64_t *newguid = arg;
839 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
840 vdev_t *rvd = spa->spa_root_vdev;
843 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
844 int error = (spa_has_checkpoint(spa)) ?
845 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
846 return (SET_ERROR(error));
849 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
850 vdev_state = rvd->vdev_state;
851 spa_config_exit(spa, SCL_STATE, FTAG);
853 if (vdev_state != VDEV_STATE_HEALTHY)
854 return (SET_ERROR(ENXIO));
856 ASSERT3U(spa_guid(spa), !=, *newguid);
862 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
864 uint64_t *newguid = arg;
865 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
867 vdev_t *rvd = spa->spa_root_vdev;
869 oldguid = spa_guid(spa);
871 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
872 rvd->vdev_guid = *newguid;
873 rvd->vdev_guid_sum += (*newguid - oldguid);
874 vdev_config_dirty(rvd);
875 spa_config_exit(spa, SCL_STATE, FTAG);
877 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
882 * Change the GUID for the pool. This is done so that we can later
883 * re-import a pool built from a clone of our own vdevs. We will modify
884 * the root vdev's guid, our own pool guid, and then mark all of our
885 * vdevs dirty. Note that we must make sure that all our vdevs are
886 * online when we do this, or else any vdevs that weren't present
887 * would be orphaned from our pool. We are also going to issue a
888 * sysevent to update any watchers.
891 spa_change_guid(spa_t *spa)
896 mutex_enter(&spa->spa_vdev_top_lock);
897 mutex_enter(&spa_namespace_lock);
898 guid = spa_generate_guid(NULL);
900 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
901 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
904 spa_write_cachefile(spa, B_FALSE, B_TRUE);
905 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
908 mutex_exit(&spa_namespace_lock);
909 mutex_exit(&spa->spa_vdev_top_lock);
915 * ==========================================================================
916 * SPA state manipulation (open/create/destroy/import/export)
917 * ==========================================================================
921 spa_error_entry_compare(const void *a, const void *b)
923 const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
924 const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
927 ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
928 sizeof (zbookmark_phys_t));
930 return (AVL_ISIGN(ret));
934 * Utility function which retrieves copies of the current logs and
935 * re-initializes them in the process.
938 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
940 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
942 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
943 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
945 avl_create(&spa->spa_errlist_scrub,
946 spa_error_entry_compare, sizeof (spa_error_entry_t),
947 offsetof(spa_error_entry_t, se_avl));
948 avl_create(&spa->spa_errlist_last,
949 spa_error_entry_compare, sizeof (spa_error_entry_t),
950 offsetof(spa_error_entry_t, se_avl));
954 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
956 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
957 enum zti_modes mode = ztip->zti_mode;
958 uint_t value = ztip->zti_value;
959 uint_t count = ztip->zti_count;
960 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
963 boolean_t batch = B_FALSE;
965 if (mode == ZTI_MODE_NULL) {
967 tqs->stqs_taskq = NULL;
971 ASSERT3U(count, >, 0);
973 tqs->stqs_count = count;
974 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
978 ASSERT3U(value, >=, 1);
979 value = MAX(value, 1);
984 flags |= TASKQ_THREADS_CPU_PCT;
985 value = zio_taskq_batch_pct;
989 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
991 zio_type_name[t], zio_taskq_types[q], mode, value);
995 for (uint_t i = 0; i < count; i++) {
999 (void) snprintf(name, sizeof (name), "%s_%s_%u",
1000 zio_type_name[t], zio_taskq_types[q], i);
1002 (void) snprintf(name, sizeof (name), "%s_%s",
1003 zio_type_name[t], zio_taskq_types[q]);
1007 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
1009 flags |= TASKQ_DC_BATCH;
1011 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
1012 spa->spa_proc, zio_taskq_basedc, flags);
1015 pri_t pri = maxclsyspri;
1017 * The write issue taskq can be extremely CPU
1018 * intensive. Run it at slightly lower priority
1019 * than the other taskqs.
1021 * - numerically higher priorities are lower priorities;
1022 * - if priorities divided by four (RQ_PPQ) are equal
1023 * then a difference between them is insignificant.
1025 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1032 tq = taskq_create_proc(name, value, pri, 50,
1033 INT_MAX, spa->spa_proc, flags);
1038 tqs->stqs_taskq[i] = tq;
1043 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1045 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1047 if (tqs->stqs_taskq == NULL) {
1048 ASSERT0(tqs->stqs_count);
1052 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1053 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1054 taskq_destroy(tqs->stqs_taskq[i]);
1057 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1058 tqs->stqs_taskq = NULL;
1062 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1063 * Note that a type may have multiple discrete taskqs to avoid lock contention
1064 * on the taskq itself. In that case we choose which taskq at random by using
1065 * the low bits of gethrtime().
1068 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1069 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1071 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1074 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1075 ASSERT3U(tqs->stqs_count, !=, 0);
1077 if (tqs->stqs_count == 1) {
1078 tq = tqs->stqs_taskq[0];
1081 tq = tqs->stqs_taskq[cpu_ticks() % tqs->stqs_count];
1083 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1087 taskq_dispatch_ent(tq, func, arg, flags, ent);
1091 spa_create_zio_taskqs(spa_t *spa)
1093 for (int t = 0; t < ZIO_TYPES; t++) {
1094 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1095 spa_taskqs_init(spa, t, q);
1103 spa_thread(void *arg)
1105 callb_cpr_t cprinfo;
1108 user_t *pu = PTOU(curproc);
1110 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1113 ASSERT(curproc != &p0);
1114 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1115 "zpool-%s", spa->spa_name);
1116 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1119 /* bind this thread to the requested psrset */
1120 if (zio_taskq_psrset_bind != PS_NONE) {
1122 mutex_enter(&cpu_lock);
1123 mutex_enter(&pidlock);
1124 mutex_enter(&curproc->p_lock);
1126 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1127 0, NULL, NULL) == 0) {
1128 curthread->t_bind_pset = zio_taskq_psrset_bind;
1131 "Couldn't bind process for zfs pool \"%s\" to "
1132 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1135 mutex_exit(&curproc->p_lock);
1136 mutex_exit(&pidlock);
1137 mutex_exit(&cpu_lock);
1143 if (zio_taskq_sysdc) {
1144 sysdc_thread_enter(curthread, 100, 0);
1148 spa->spa_proc = curproc;
1149 spa->spa_did = curthread->t_did;
1151 spa_create_zio_taskqs(spa);
1153 mutex_enter(&spa->spa_proc_lock);
1154 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1156 spa->spa_proc_state = SPA_PROC_ACTIVE;
1157 cv_broadcast(&spa->spa_proc_cv);
1159 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1160 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1161 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1162 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1164 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1165 spa->spa_proc_state = SPA_PROC_GONE;
1166 spa->spa_proc = &p0;
1167 cv_broadcast(&spa->spa_proc_cv);
1168 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1170 mutex_enter(&curproc->p_lock);
1173 #endif /* SPA_PROCESS */
1177 * Activate an uninitialized pool.
1180 spa_activate(spa_t *spa, int mode)
1182 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1184 spa->spa_state = POOL_STATE_ACTIVE;
1185 spa->spa_mode = mode;
1187 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1188 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1190 /* Try to create a covering process */
1191 mutex_enter(&spa->spa_proc_lock);
1192 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1193 ASSERT(spa->spa_proc == &p0);
1197 /* Only create a process if we're going to be around a while. */
1198 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1199 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1201 spa->spa_proc_state = SPA_PROC_CREATED;
1202 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1203 cv_wait(&spa->spa_proc_cv,
1204 &spa->spa_proc_lock);
1206 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1207 ASSERT(spa->spa_proc != &p0);
1208 ASSERT(spa->spa_did != 0);
1212 "Couldn't create process for zfs pool \"%s\"\n",
1217 #endif /* SPA_PROCESS */
1218 mutex_exit(&spa->spa_proc_lock);
1220 /* If we didn't create a process, we need to create our taskqs. */
1221 ASSERT(spa->spa_proc == &p0);
1222 if (spa->spa_proc == &p0) {
1223 spa_create_zio_taskqs(spa);
1227 * Start TRIM thread.
1229 trim_thread_create(spa);
1231 for (size_t i = 0; i < TXG_SIZE; i++) {
1232 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL,
1236 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1237 offsetof(vdev_t, vdev_config_dirty_node));
1238 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1239 offsetof(objset_t, os_evicting_node));
1240 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1241 offsetof(vdev_t, vdev_state_dirty_node));
1243 txg_list_create(&spa->spa_vdev_txg_list, spa,
1244 offsetof(struct vdev, vdev_txg_node));
1246 avl_create(&spa->spa_errlist_scrub,
1247 spa_error_entry_compare, sizeof (spa_error_entry_t),
1248 offsetof(spa_error_entry_t, se_avl));
1249 avl_create(&spa->spa_errlist_last,
1250 spa_error_entry_compare, sizeof (spa_error_entry_t),
1251 offsetof(spa_error_entry_t, se_avl));
1255 * Opposite of spa_activate().
1258 spa_deactivate(spa_t *spa)
1260 ASSERT(spa->spa_sync_on == B_FALSE);
1261 ASSERT(spa->spa_dsl_pool == NULL);
1262 ASSERT(spa->spa_root_vdev == NULL);
1263 ASSERT(spa->spa_async_zio_root == NULL);
1264 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1267 * Stop TRIM thread in case spa_unload() wasn't called directly
1268 * before spa_deactivate().
1270 trim_thread_destroy(spa);
1272 spa_evicting_os_wait(spa);
1274 txg_list_destroy(&spa->spa_vdev_txg_list);
1276 list_destroy(&spa->spa_config_dirty_list);
1277 list_destroy(&spa->spa_evicting_os_list);
1278 list_destroy(&spa->spa_state_dirty_list);
1280 for (int t = 0; t < ZIO_TYPES; t++) {
1281 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1282 spa_taskqs_fini(spa, t, q);
1286 for (size_t i = 0; i < TXG_SIZE; i++) {
1287 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1288 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1289 spa->spa_txg_zio[i] = NULL;
1292 metaslab_class_destroy(spa->spa_normal_class);
1293 spa->spa_normal_class = NULL;
1295 metaslab_class_destroy(spa->spa_log_class);
1296 spa->spa_log_class = NULL;
1299 * If this was part of an import or the open otherwise failed, we may
1300 * still have errors left in the queues. Empty them just in case.
1302 spa_errlog_drain(spa);
1304 avl_destroy(&spa->spa_errlist_scrub);
1305 avl_destroy(&spa->spa_errlist_last);
1307 spa->spa_state = POOL_STATE_UNINITIALIZED;
1309 mutex_enter(&spa->spa_proc_lock);
1310 if (spa->spa_proc_state != SPA_PROC_NONE) {
1311 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1312 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1313 cv_broadcast(&spa->spa_proc_cv);
1314 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1315 ASSERT(spa->spa_proc != &p0);
1316 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1318 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1319 spa->spa_proc_state = SPA_PROC_NONE;
1321 ASSERT(spa->spa_proc == &p0);
1322 mutex_exit(&spa->spa_proc_lock);
1326 * We want to make sure spa_thread() has actually exited the ZFS
1327 * module, so that the module can't be unloaded out from underneath
1330 if (spa->spa_did != 0) {
1331 thread_join(spa->spa_did);
1334 #endif /* SPA_PROCESS */
1338 * Verify a pool configuration, and construct the vdev tree appropriately. This
1339 * will create all the necessary vdevs in the appropriate layout, with each vdev
1340 * in the CLOSED state. This will prep the pool before open/creation/import.
1341 * All vdev validation is done by the vdev_alloc() routine.
1344 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1345 uint_t id, int atype)
1351 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1354 if ((*vdp)->vdev_ops->vdev_op_leaf)
1357 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1360 if (error == ENOENT)
1366 return (SET_ERROR(EINVAL));
1369 for (int c = 0; c < children; c++) {
1371 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1379 ASSERT(*vdp != NULL);
1385 * Opposite of spa_load().
1388 spa_unload(spa_t *spa)
1392 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1394 spa_load_note(spa, "UNLOADING");
1399 trim_thread_destroy(spa);
1404 spa_async_suspend(spa);
1406 if (spa->spa_root_vdev) {
1407 vdev_initialize_stop_all(spa->spa_root_vdev,
1408 VDEV_INITIALIZE_ACTIVE);
1414 if (spa->spa_sync_on) {
1415 txg_sync_stop(spa->spa_dsl_pool);
1416 spa->spa_sync_on = B_FALSE;
1420 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1421 * to call it earlier, before we wait for async i/o to complete.
1422 * This ensures that there is no async metaslab prefetching, by
1423 * calling taskq_wait(mg_taskq).
1425 if (spa->spa_root_vdev != NULL) {
1426 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1427 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1428 vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1429 spa_config_exit(spa, SCL_ALL, spa);
1433 * Wait for any outstanding async I/O to complete.
1435 if (spa->spa_async_zio_root != NULL) {
1436 for (int i = 0; i < max_ncpus; i++)
1437 (void) zio_wait(spa->spa_async_zio_root[i]);
1438 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1439 spa->spa_async_zio_root = NULL;
1442 if (spa->spa_vdev_removal != NULL) {
1443 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1444 spa->spa_vdev_removal = NULL;
1447 if (spa->spa_condense_zthr != NULL) {
1448 ASSERT(!zthr_isrunning(spa->spa_condense_zthr));
1449 zthr_destroy(spa->spa_condense_zthr);
1450 spa->spa_condense_zthr = NULL;
1453 if (spa->spa_checkpoint_discard_zthr != NULL) {
1454 ASSERT(!zthr_isrunning(spa->spa_checkpoint_discard_zthr));
1455 zthr_destroy(spa->spa_checkpoint_discard_zthr);
1456 spa->spa_checkpoint_discard_zthr = NULL;
1459 spa_condense_fini(spa);
1461 bpobj_close(&spa->spa_deferred_bpobj);
1463 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1468 if (spa->spa_root_vdev)
1469 vdev_free(spa->spa_root_vdev);
1470 ASSERT(spa->spa_root_vdev == NULL);
1473 * Close the dsl pool.
1475 if (spa->spa_dsl_pool) {
1476 dsl_pool_close(spa->spa_dsl_pool);
1477 spa->spa_dsl_pool = NULL;
1478 spa->spa_meta_objset = NULL;
1484 * Drop and purge level 2 cache
1486 spa_l2cache_drop(spa);
1488 for (i = 0; i < spa->spa_spares.sav_count; i++)
1489 vdev_free(spa->spa_spares.sav_vdevs[i]);
1490 if (spa->spa_spares.sav_vdevs) {
1491 kmem_free(spa->spa_spares.sav_vdevs,
1492 spa->spa_spares.sav_count * sizeof (void *));
1493 spa->spa_spares.sav_vdevs = NULL;
1495 if (spa->spa_spares.sav_config) {
1496 nvlist_free(spa->spa_spares.sav_config);
1497 spa->spa_spares.sav_config = NULL;
1499 spa->spa_spares.sav_count = 0;
1501 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1502 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1503 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1505 if (spa->spa_l2cache.sav_vdevs) {
1506 kmem_free(spa->spa_l2cache.sav_vdevs,
1507 spa->spa_l2cache.sav_count * sizeof (void *));
1508 spa->spa_l2cache.sav_vdevs = NULL;
1510 if (spa->spa_l2cache.sav_config) {
1511 nvlist_free(spa->spa_l2cache.sav_config);
1512 spa->spa_l2cache.sav_config = NULL;
1514 spa->spa_l2cache.sav_count = 0;
1516 spa->spa_async_suspended = 0;
1518 spa->spa_indirect_vdevs_loaded = B_FALSE;
1520 if (spa->spa_comment != NULL) {
1521 spa_strfree(spa->spa_comment);
1522 spa->spa_comment = NULL;
1525 spa_config_exit(spa, SCL_ALL, spa);
1529 * Load (or re-load) the current list of vdevs describing the active spares for
1530 * this pool. When this is called, we have some form of basic information in
1531 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1532 * then re-generate a more complete list including status information.
1535 spa_load_spares(spa_t *spa)
1544 * zdb opens both the current state of the pool and the
1545 * checkpointed state (if present), with a different spa_t.
1547 * As spare vdevs are shared among open pools, we skip loading
1548 * them when we load the checkpointed state of the pool.
1550 if (!spa_writeable(spa))
1554 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1557 * First, close and free any existing spare vdevs.
1559 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1560 vd = spa->spa_spares.sav_vdevs[i];
1562 /* Undo the call to spa_activate() below */
1563 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1564 B_FALSE)) != NULL && tvd->vdev_isspare)
1565 spa_spare_remove(tvd);
1570 if (spa->spa_spares.sav_vdevs)
1571 kmem_free(spa->spa_spares.sav_vdevs,
1572 spa->spa_spares.sav_count * sizeof (void *));
1574 if (spa->spa_spares.sav_config == NULL)
1577 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1578 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1580 spa->spa_spares.sav_count = (int)nspares;
1581 spa->spa_spares.sav_vdevs = NULL;
1587 * Construct the array of vdevs, opening them to get status in the
1588 * process. For each spare, there is potentially two different vdev_t
1589 * structures associated with it: one in the list of spares (used only
1590 * for basic validation purposes) and one in the active vdev
1591 * configuration (if it's spared in). During this phase we open and
1592 * validate each vdev on the spare list. If the vdev also exists in the
1593 * active configuration, then we also mark this vdev as an active spare.
1595 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1597 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1598 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1599 VDEV_ALLOC_SPARE) == 0);
1602 spa->spa_spares.sav_vdevs[i] = vd;
1604 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1605 B_FALSE)) != NULL) {
1606 if (!tvd->vdev_isspare)
1610 * We only mark the spare active if we were successfully
1611 * able to load the vdev. Otherwise, importing a pool
1612 * with a bad active spare would result in strange
1613 * behavior, because multiple pool would think the spare
1614 * is actively in use.
1616 * There is a vulnerability here to an equally bizarre
1617 * circumstance, where a dead active spare is later
1618 * brought back to life (onlined or otherwise). Given
1619 * the rarity of this scenario, and the extra complexity
1620 * it adds, we ignore the possibility.
1622 if (!vdev_is_dead(tvd))
1623 spa_spare_activate(tvd);
1627 vd->vdev_aux = &spa->spa_spares;
1629 if (vdev_open(vd) != 0)
1632 if (vdev_validate_aux(vd) == 0)
1637 * Recompute the stashed list of spares, with status information
1640 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1641 DATA_TYPE_NVLIST_ARRAY) == 0);
1643 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1645 for (i = 0; i < spa->spa_spares.sav_count; i++)
1646 spares[i] = vdev_config_generate(spa,
1647 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1648 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1649 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1650 for (i = 0; i < spa->spa_spares.sav_count; i++)
1651 nvlist_free(spares[i]);
1652 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1656 * Load (or re-load) the current list of vdevs describing the active l2cache for
1657 * this pool. When this is called, we have some form of basic information in
1658 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1659 * then re-generate a more complete list including status information.
1660 * Devices which are already active have their details maintained, and are
1664 spa_load_l2cache(spa_t *spa)
1668 int i, j, oldnvdevs;
1670 vdev_t *vd, **oldvdevs, **newvdevs;
1671 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1675 * zdb opens both the current state of the pool and the
1676 * checkpointed state (if present), with a different spa_t.
1678 * As L2 caches are part of the ARC which is shared among open
1679 * pools, we skip loading them when we load the checkpointed
1680 * state of the pool.
1682 if (!spa_writeable(spa))
1686 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1688 if (sav->sav_config != NULL) {
1689 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1690 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1691 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1697 oldvdevs = sav->sav_vdevs;
1698 oldnvdevs = sav->sav_count;
1699 sav->sav_vdevs = NULL;
1703 * Process new nvlist of vdevs.
1705 for (i = 0; i < nl2cache; i++) {
1706 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1710 for (j = 0; j < oldnvdevs; j++) {
1712 if (vd != NULL && guid == vd->vdev_guid) {
1714 * Retain previous vdev for add/remove ops.
1722 if (newvdevs[i] == NULL) {
1726 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1727 VDEV_ALLOC_L2CACHE) == 0);
1732 * Commit this vdev as an l2cache device,
1733 * even if it fails to open.
1735 spa_l2cache_add(vd);
1740 spa_l2cache_activate(vd);
1742 if (vdev_open(vd) != 0)
1745 (void) vdev_validate_aux(vd);
1747 if (!vdev_is_dead(vd))
1748 l2arc_add_vdev(spa, vd);
1753 * Purge vdevs that were dropped
1755 for (i = 0; i < oldnvdevs; i++) {
1760 ASSERT(vd->vdev_isl2cache);
1762 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1763 pool != 0ULL && l2arc_vdev_present(vd))
1764 l2arc_remove_vdev(vd);
1765 vdev_clear_stats(vd);
1771 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1773 if (sav->sav_config == NULL)
1776 sav->sav_vdevs = newvdevs;
1777 sav->sav_count = (int)nl2cache;
1780 * Recompute the stashed list of l2cache devices, with status
1781 * information this time.
1783 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1784 DATA_TYPE_NVLIST_ARRAY) == 0);
1786 l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1787 for (i = 0; i < sav->sav_count; i++)
1788 l2cache[i] = vdev_config_generate(spa,
1789 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1790 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1791 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1793 for (i = 0; i < sav->sav_count; i++)
1794 nvlist_free(l2cache[i]);
1796 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1800 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1803 char *packed = NULL;
1808 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1812 nvsize = *(uint64_t *)db->db_data;
1813 dmu_buf_rele(db, FTAG);
1815 packed = kmem_alloc(nvsize, KM_SLEEP);
1816 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1819 error = nvlist_unpack(packed, nvsize, value, 0);
1820 kmem_free(packed, nvsize);
1826 * Concrete top-level vdevs that are not missing and are not logs. At every
1827 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1830 spa_healthy_core_tvds(spa_t *spa)
1832 vdev_t *rvd = spa->spa_root_vdev;
1835 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1836 vdev_t *vd = rvd->vdev_child[i];
1839 if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1847 * Checks to see if the given vdev could not be opened, in which case we post a
1848 * sysevent to notify the autoreplace code that the device has been removed.
1851 spa_check_removed(vdev_t *vd)
1853 for (uint64_t c = 0; c < vd->vdev_children; c++)
1854 spa_check_removed(vd->vdev_child[c]);
1856 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1857 vdev_is_concrete(vd)) {
1858 zfs_post_autoreplace(vd->vdev_spa, vd);
1859 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1864 spa_check_for_missing_logs(spa_t *spa)
1866 vdev_t *rvd = spa->spa_root_vdev;
1869 * If we're doing a normal import, then build up any additional
1870 * diagnostic information about missing log devices.
1871 * We'll pass this up to the user for further processing.
1873 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1874 nvlist_t **child, *nv;
1877 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1879 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1881 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1882 vdev_t *tvd = rvd->vdev_child[c];
1885 * We consider a device as missing only if it failed
1886 * to open (i.e. offline or faulted is not considered
1889 if (tvd->vdev_islog &&
1890 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1891 child[idx++] = vdev_config_generate(spa, tvd,
1892 B_FALSE, VDEV_CONFIG_MISSING);
1897 fnvlist_add_nvlist_array(nv,
1898 ZPOOL_CONFIG_CHILDREN, child, idx);
1899 fnvlist_add_nvlist(spa->spa_load_info,
1900 ZPOOL_CONFIG_MISSING_DEVICES, nv);
1902 for (uint64_t i = 0; i < idx; i++)
1903 nvlist_free(child[i]);
1906 kmem_free(child, rvd->vdev_children * sizeof (char **));
1909 spa_load_failed(spa, "some log devices are missing");
1910 vdev_dbgmsg_print_tree(rvd, 2);
1911 return (SET_ERROR(ENXIO));
1914 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1915 vdev_t *tvd = rvd->vdev_child[c];
1917 if (tvd->vdev_islog &&
1918 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1919 spa_set_log_state(spa, SPA_LOG_CLEAR);
1920 spa_load_note(spa, "some log devices are "
1921 "missing, ZIL is dropped.");
1922 vdev_dbgmsg_print_tree(rvd, 2);
1932 * Check for missing log devices
1935 spa_check_logs(spa_t *spa)
1937 boolean_t rv = B_FALSE;
1938 dsl_pool_t *dp = spa_get_dsl(spa);
1940 switch (spa->spa_log_state) {
1941 case SPA_LOG_MISSING:
1942 /* need to recheck in case slog has been restored */
1943 case SPA_LOG_UNKNOWN:
1944 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1945 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
1947 spa_set_log_state(spa, SPA_LOG_MISSING);
1954 spa_passivate_log(spa_t *spa)
1956 vdev_t *rvd = spa->spa_root_vdev;
1957 boolean_t slog_found = B_FALSE;
1959 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1961 if (!spa_has_slogs(spa))
1964 for (int c = 0; c < rvd->vdev_children; c++) {
1965 vdev_t *tvd = rvd->vdev_child[c];
1966 metaslab_group_t *mg = tvd->vdev_mg;
1968 if (tvd->vdev_islog) {
1969 metaslab_group_passivate(mg);
1970 slog_found = B_TRUE;
1974 return (slog_found);
1978 spa_activate_log(spa_t *spa)
1980 vdev_t *rvd = spa->spa_root_vdev;
1982 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1984 for (int c = 0; c < rvd->vdev_children; c++) {
1985 vdev_t *tvd = rvd->vdev_child[c];
1986 metaslab_group_t *mg = tvd->vdev_mg;
1988 if (tvd->vdev_islog)
1989 metaslab_group_activate(mg);
1994 spa_reset_logs(spa_t *spa)
1998 error = dmu_objset_find(spa_name(spa), zil_reset,
1999 NULL, DS_FIND_CHILDREN);
2002 * We successfully offlined the log device, sync out the
2003 * current txg so that the "stubby" block can be removed
2006 txg_wait_synced(spa->spa_dsl_pool, 0);
2012 spa_aux_check_removed(spa_aux_vdev_t *sav)
2016 for (i = 0; i < sav->sav_count; i++)
2017 spa_check_removed(sav->sav_vdevs[i]);
2021 spa_claim_notify(zio_t *zio)
2023 spa_t *spa = zio->io_spa;
2028 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2029 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2030 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2031 mutex_exit(&spa->spa_props_lock);
2034 typedef struct spa_load_error {
2035 uint64_t sle_meta_count;
2036 uint64_t sle_data_count;
2040 spa_load_verify_done(zio_t *zio)
2042 blkptr_t *bp = zio->io_bp;
2043 spa_load_error_t *sle = zio->io_private;
2044 dmu_object_type_t type = BP_GET_TYPE(bp);
2045 int error = zio->io_error;
2046 spa_t *spa = zio->io_spa;
2048 abd_free(zio->io_abd);
2050 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
2051 type != DMU_OT_INTENT_LOG)
2052 atomic_inc_64(&sle->sle_meta_count);
2054 atomic_inc_64(&sle->sle_data_count);
2057 mutex_enter(&spa->spa_scrub_lock);
2058 spa->spa_load_verify_ios--;
2059 cv_broadcast(&spa->spa_scrub_io_cv);
2060 mutex_exit(&spa->spa_scrub_lock);
2064 * Maximum number of concurrent scrub i/os to create while verifying
2065 * a pool while importing it.
2067 int spa_load_verify_maxinflight = 10000;
2068 boolean_t spa_load_verify_metadata = B_TRUE;
2069 boolean_t spa_load_verify_data = B_TRUE;
2071 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_maxinflight, CTLFLAG_RWTUN,
2072 &spa_load_verify_maxinflight, 0,
2073 "Maximum number of concurrent scrub I/Os to create while verifying a "
2074 "pool while importing it");
2076 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_metadata, CTLFLAG_RWTUN,
2077 &spa_load_verify_metadata, 0,
2078 "Check metadata on import?");
2080 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_data, CTLFLAG_RWTUN,
2081 &spa_load_verify_data, 0,
2082 "Check user data on import?");
2086 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2087 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2089 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2092 * Note: normally this routine will not be called if
2093 * spa_load_verify_metadata is not set. However, it may be useful
2094 * to manually set the flag after the traversal has begun.
2096 if (!spa_load_verify_metadata)
2098 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2102 size_t size = BP_GET_PSIZE(bp);
2104 mutex_enter(&spa->spa_scrub_lock);
2105 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
2106 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2107 spa->spa_load_verify_ios++;
2108 mutex_exit(&spa->spa_scrub_lock);
2110 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2111 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2112 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2113 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2119 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2121 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2122 return (SET_ERROR(ENAMETOOLONG));
2128 spa_load_verify(spa_t *spa)
2131 spa_load_error_t sle = { 0 };
2132 zpool_load_policy_t policy;
2133 boolean_t verify_ok = B_FALSE;
2136 zpool_get_load_policy(spa->spa_config, &policy);
2138 if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2141 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2142 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2143 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2145 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2149 rio = zio_root(spa, NULL, &sle,
2150 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2152 if (spa_load_verify_metadata) {
2153 if (spa->spa_extreme_rewind) {
2154 spa_load_note(spa, "performing a complete scan of the "
2155 "pool since extreme rewind is on. This may take "
2156 "a very long time.\n (spa_load_verify_data=%u, "
2157 "spa_load_verify_metadata=%u)",
2158 spa_load_verify_data, spa_load_verify_metadata);
2160 error = traverse_pool(spa, spa->spa_verify_min_txg,
2161 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2162 spa_load_verify_cb, rio);
2165 (void) zio_wait(rio);
2167 spa->spa_load_meta_errors = sle.sle_meta_count;
2168 spa->spa_load_data_errors = sle.sle_data_count;
2170 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2171 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2172 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2173 (u_longlong_t)sle.sle_data_count);
2176 if (spa_load_verify_dryrun ||
2177 (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2178 sle.sle_data_count <= policy.zlp_maxdata)) {
2182 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2183 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2185 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2186 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2187 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2188 VERIFY(nvlist_add_int64(spa->spa_load_info,
2189 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2190 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2191 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2193 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2196 if (spa_load_verify_dryrun)
2200 if (error != ENXIO && error != EIO)
2201 error = SET_ERROR(EIO);
2205 return (verify_ok ? 0 : EIO);
2209 * Find a value in the pool props object.
2212 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2214 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2215 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2219 * Find a value in the pool directory object.
2222 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2224 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2225 name, sizeof (uint64_t), 1, val);
2227 if (error != 0 && (error != ENOENT || log_enoent)) {
2228 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2229 "[error=%d]", name, error);
2236 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2238 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2239 return (SET_ERROR(err));
2243 spa_spawn_aux_threads(spa_t *spa)
2245 ASSERT(spa_writeable(spa));
2247 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2249 spa_start_indirect_condensing_thread(spa);
2251 ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2252 spa->spa_checkpoint_discard_zthr =
2253 zthr_create(spa_checkpoint_discard_thread_check,
2254 spa_checkpoint_discard_thread, spa);
2258 * Fix up config after a partly-completed split. This is done with the
2259 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2260 * pool have that entry in their config, but only the splitting one contains
2261 * a list of all the guids of the vdevs that are being split off.
2263 * This function determines what to do with that list: either rejoin
2264 * all the disks to the pool, or complete the splitting process. To attempt
2265 * the rejoin, each disk that is offlined is marked online again, and
2266 * we do a reopen() call. If the vdev label for every disk that was
2267 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2268 * then we call vdev_split() on each disk, and complete the split.
2270 * Otherwise we leave the config alone, with all the vdevs in place in
2271 * the original pool.
2274 spa_try_repair(spa_t *spa, nvlist_t *config)
2281 boolean_t attempt_reopen;
2283 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2286 /* check that the config is complete */
2287 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2288 &glist, &gcount) != 0)
2291 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2293 /* attempt to online all the vdevs & validate */
2294 attempt_reopen = B_TRUE;
2295 for (i = 0; i < gcount; i++) {
2296 if (glist[i] == 0) /* vdev is hole */
2299 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2300 if (vd[i] == NULL) {
2302 * Don't bother attempting to reopen the disks;
2303 * just do the split.
2305 attempt_reopen = B_FALSE;
2307 /* attempt to re-online it */
2308 vd[i]->vdev_offline = B_FALSE;
2312 if (attempt_reopen) {
2313 vdev_reopen(spa->spa_root_vdev);
2315 /* check each device to see what state it's in */
2316 for (extracted = 0, i = 0; i < gcount; i++) {
2317 if (vd[i] != NULL &&
2318 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2325 * If every disk has been moved to the new pool, or if we never
2326 * even attempted to look at them, then we split them off for
2329 if (!attempt_reopen || gcount == extracted) {
2330 for (i = 0; i < gcount; i++)
2333 vdev_reopen(spa->spa_root_vdev);
2336 kmem_free(vd, gcount * sizeof (vdev_t *));
2340 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2342 char *ereport = FM_EREPORT_ZFS_POOL;
2345 spa->spa_load_state = state;
2347 gethrestime(&spa->spa_loaded_ts);
2348 error = spa_load_impl(spa, type, &ereport);
2351 * Don't count references from objsets that are already closed
2352 * and are making their way through the eviction process.
2354 spa_evicting_os_wait(spa);
2355 spa->spa_minref = refcount_count(&spa->spa_refcount);
2357 if (error != EEXIST) {
2358 spa->spa_loaded_ts.tv_sec = 0;
2359 spa->spa_loaded_ts.tv_nsec = 0;
2361 if (error != EBADF) {
2362 zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2365 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2372 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2373 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2374 * spa's per-vdev ZAP list.
2377 vdev_count_verify_zaps(vdev_t *vd)
2379 spa_t *spa = vd->vdev_spa;
2381 if (vd->vdev_top_zap != 0) {
2383 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2384 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2386 if (vd->vdev_leaf_zap != 0) {
2388 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2389 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2392 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2393 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2400 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2404 uint64_t myhostid = 0;
2406 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2407 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2408 hostname = fnvlist_lookup_string(mos_config,
2409 ZPOOL_CONFIG_HOSTNAME);
2411 myhostid = zone_get_hostid(NULL);
2413 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2414 cmn_err(CE_WARN, "pool '%s' could not be "
2415 "loaded as it was last accessed by "
2416 "another system (host: %s hostid: 0x%llx). "
2417 "See: http://illumos.org/msg/ZFS-8000-EY",
2418 spa_name(spa), hostname, (u_longlong_t)hostid);
2419 spa_load_failed(spa, "hostid verification failed: pool "
2420 "last accessed by host: %s (hostid: 0x%llx)",
2421 hostname, (u_longlong_t)hostid);
2422 return (SET_ERROR(EBADF));
2430 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2433 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2440 * Versioning wasn't explicitly added to the label until later, so if
2441 * it's not present treat it as the initial version.
2443 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2444 &spa->spa_ubsync.ub_version) != 0)
2445 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2447 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2448 spa_load_failed(spa, "invalid config provided: '%s' missing",
2449 ZPOOL_CONFIG_POOL_GUID);
2450 return (SET_ERROR(EINVAL));
2454 * If we are doing an import, ensure that the pool is not already
2455 * imported by checking if its pool guid already exists in the
2458 * The only case that we allow an already imported pool to be
2459 * imported again, is when the pool is checkpointed and we want to
2460 * look at its checkpointed state from userland tools like zdb.
2463 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2464 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2465 spa_guid_exists(pool_guid, 0)) {
2467 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2468 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2469 spa_guid_exists(pool_guid, 0) &&
2470 !spa_importing_readonly_checkpoint(spa)) {
2472 spa_load_failed(spa, "a pool with guid %llu is already open",
2473 (u_longlong_t)pool_guid);
2474 return (SET_ERROR(EEXIST));
2477 spa->spa_config_guid = pool_guid;
2479 nvlist_free(spa->spa_load_info);
2480 spa->spa_load_info = fnvlist_alloc();
2482 ASSERT(spa->spa_comment == NULL);
2483 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2484 spa->spa_comment = spa_strdup(comment);
2486 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2487 &spa->spa_config_txg);
2489 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2490 spa->spa_config_splitting = fnvlist_dup(nvl);
2492 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2493 spa_load_failed(spa, "invalid config provided: '%s' missing",
2494 ZPOOL_CONFIG_VDEV_TREE);
2495 return (SET_ERROR(EINVAL));
2499 * Create "The Godfather" zio to hold all async IOs
2501 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2503 for (int i = 0; i < max_ncpus; i++) {
2504 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2505 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2506 ZIO_FLAG_GODFATHER);
2510 * Parse the configuration into a vdev tree. We explicitly set the
2511 * value that will be returned by spa_version() since parsing the
2512 * configuration requires knowing the version number.
2514 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2515 parse = (type == SPA_IMPORT_EXISTING ?
2516 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2517 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2518 spa_config_exit(spa, SCL_ALL, FTAG);
2521 spa_load_failed(spa, "unable to parse config [error=%d]",
2526 ASSERT(spa->spa_root_vdev == rvd);
2527 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2528 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2530 if (type != SPA_IMPORT_ASSEMBLE) {
2531 ASSERT(spa_guid(spa) == pool_guid);
2538 * Recursively open all vdevs in the vdev tree. This function is called twice:
2539 * first with the untrusted config, then with the trusted config.
2542 spa_ld_open_vdevs(spa_t *spa)
2547 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2548 * missing/unopenable for the root vdev to be still considered openable.
2550 if (spa->spa_trust_config) {
2551 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2552 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2553 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2554 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2555 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2557 spa->spa_missing_tvds_allowed = 0;
2560 spa->spa_missing_tvds_allowed =
2561 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2563 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2564 error = vdev_open(spa->spa_root_vdev);
2565 spa_config_exit(spa, SCL_ALL, FTAG);
2567 if (spa->spa_missing_tvds != 0) {
2568 spa_load_note(spa, "vdev tree has %lld missing top-level "
2569 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2570 if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2572 * Although theoretically we could allow users to open
2573 * incomplete pools in RW mode, we'd need to add a lot
2574 * of extra logic (e.g. adjust pool space to account
2575 * for missing vdevs).
2576 * This limitation also prevents users from accidentally
2577 * opening the pool in RW mode during data recovery and
2578 * damaging it further.
2580 spa_load_note(spa, "pools with missing top-level "
2581 "vdevs can only be opened in read-only mode.");
2582 error = SET_ERROR(ENXIO);
2584 spa_load_note(spa, "current settings allow for maximum "
2585 "%lld missing top-level vdevs at this stage.",
2586 (u_longlong_t)spa->spa_missing_tvds_allowed);
2590 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2593 if (spa->spa_missing_tvds != 0 || error != 0)
2594 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2600 * We need to validate the vdev labels against the configuration that
2601 * we have in hand. This function is called twice: first with an untrusted
2602 * config, then with a trusted config. The validation is more strict when the
2603 * config is trusted.
2606 spa_ld_validate_vdevs(spa_t *spa)
2609 vdev_t *rvd = spa->spa_root_vdev;
2611 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2612 error = vdev_validate(rvd);
2613 spa_config_exit(spa, SCL_ALL, FTAG);
2616 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2620 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2621 spa_load_failed(spa, "cannot open vdev tree after invalidating "
2623 vdev_dbgmsg_print_tree(rvd, 2);
2624 return (SET_ERROR(ENXIO));
2631 spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2633 spa->spa_state = POOL_STATE_ACTIVE;
2634 spa->spa_ubsync = spa->spa_uberblock;
2635 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2636 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2637 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2638 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2639 spa->spa_claim_max_txg = spa->spa_first_txg;
2640 spa->spa_prev_software_version = ub->ub_software_version;
2644 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2646 vdev_t *rvd = spa->spa_root_vdev;
2648 uberblock_t *ub = &spa->spa_uberblock;
2651 * If we are opening the checkpointed state of the pool by
2652 * rewinding to it, at this point we will have written the
2653 * checkpointed uberblock to the vdev labels, so searching
2654 * the labels will find the right uberblock. However, if
2655 * we are opening the checkpointed state read-only, we have
2656 * not modified the labels. Therefore, we must ignore the
2657 * labels and continue using the spa_uberblock that was set
2658 * by spa_ld_checkpoint_rewind.
2660 * Note that it would be fine to ignore the labels when
2661 * rewinding (opening writeable) as well. However, if we
2662 * crash just after writing the labels, we will end up
2663 * searching the labels. Doing so in the common case means
2664 * that this code path gets exercised normally, rather than
2665 * just in the edge case.
2667 if (ub->ub_checkpoint_txg != 0 &&
2668 spa_importing_readonly_checkpoint(spa)) {
2669 spa_ld_select_uberblock_done(spa, ub);
2674 * Find the best uberblock.
2676 vdev_uberblock_load(rvd, ub, &label);
2679 * If we weren't able to find a single valid uberblock, return failure.
2681 if (ub->ub_txg == 0) {
2683 spa_load_failed(spa, "no valid uberblock found");
2684 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2687 spa_load_note(spa, "using uberblock with txg=%llu",
2688 (u_longlong_t)ub->ub_txg);
2691 * If the pool has an unsupported version we can't open it.
2693 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2695 spa_load_failed(spa, "version %llu is not supported",
2696 (u_longlong_t)ub->ub_version);
2697 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2700 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2704 * If we weren't able to find what's necessary for reading the
2705 * MOS in the label, return failure.
2707 if (label == NULL) {
2708 spa_load_failed(spa, "label config unavailable");
2709 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2713 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
2716 spa_load_failed(spa, "invalid label: '%s' missing",
2717 ZPOOL_CONFIG_FEATURES_FOR_READ);
2718 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2723 * Update our in-core representation with the definitive values
2726 nvlist_free(spa->spa_label_features);
2727 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2733 * Look through entries in the label nvlist's features_for_read. If
2734 * there is a feature listed there which we don't understand then we
2735 * cannot open a pool.
2737 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2738 nvlist_t *unsup_feat;
2740 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2743 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2745 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2746 if (!zfeature_is_supported(nvpair_name(nvp))) {
2747 VERIFY(nvlist_add_string(unsup_feat,
2748 nvpair_name(nvp), "") == 0);
2752 if (!nvlist_empty(unsup_feat)) {
2753 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2754 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2755 nvlist_free(unsup_feat);
2756 spa_load_failed(spa, "some features are unsupported");
2757 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2761 nvlist_free(unsup_feat);
2764 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2765 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2766 spa_try_repair(spa, spa->spa_config);
2767 spa_config_exit(spa, SCL_ALL, FTAG);
2768 nvlist_free(spa->spa_config_splitting);
2769 spa->spa_config_splitting = NULL;
2773 * Initialize internal SPA structures.
2775 spa_ld_select_uberblock_done(spa, ub);
2781 spa_ld_open_rootbp(spa_t *spa)
2784 vdev_t *rvd = spa->spa_root_vdev;
2786 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2788 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
2789 "[error=%d]", error);
2790 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2792 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2798 spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
2799 boolean_t reloading)
2801 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
2802 nvlist_t *nv, *mos_config, *policy;
2803 int error = 0, copy_error;
2804 uint64_t healthy_tvds, healthy_tvds_mos;
2805 uint64_t mos_config_txg;
2807 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
2809 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2812 * If we're assembling a pool from a split, the config provided is
2813 * already trusted so there is nothing to do.
2815 if (type == SPA_IMPORT_ASSEMBLE)
2818 healthy_tvds = spa_healthy_core_tvds(spa);
2820 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
2822 spa_load_failed(spa, "unable to retrieve MOS config");
2823 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2827 * If we are doing an open, pool owner wasn't verified yet, thus do
2828 * the verification here.
2830 if (spa->spa_load_state == SPA_LOAD_OPEN) {
2831 error = spa_verify_host(spa, mos_config);
2833 nvlist_free(mos_config);
2838 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
2840 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2843 * Build a new vdev tree from the trusted config
2845 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
2848 * Vdev paths in the MOS may be obsolete. If the untrusted config was
2849 * obtained by scanning /dev/dsk, then it will have the right vdev
2850 * paths. We update the trusted MOS config with this information.
2851 * We first try to copy the paths with vdev_copy_path_strict, which
2852 * succeeds only when both configs have exactly the same vdev tree.
2853 * If that fails, we fall back to a more flexible method that has a
2854 * best effort policy.
2856 copy_error = vdev_copy_path_strict(rvd, mrvd);
2857 if (copy_error != 0 || spa_load_print_vdev_tree) {
2858 spa_load_note(spa, "provided vdev tree:");
2859 vdev_dbgmsg_print_tree(rvd, 2);
2860 spa_load_note(spa, "MOS vdev tree:");
2861 vdev_dbgmsg_print_tree(mrvd, 2);
2863 if (copy_error != 0) {
2864 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
2865 "back to vdev_copy_path_relaxed");
2866 vdev_copy_path_relaxed(rvd, mrvd);
2871 spa->spa_root_vdev = mrvd;
2873 spa_config_exit(spa, SCL_ALL, FTAG);
2876 * We will use spa_config if we decide to reload the spa or if spa_load
2877 * fails and we rewind. We must thus regenerate the config using the
2878 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
2879 * pass settings on how to load the pool and is not stored in the MOS.
2880 * We copy it over to our new, trusted config.
2882 mos_config_txg = fnvlist_lookup_uint64(mos_config,
2883 ZPOOL_CONFIG_POOL_TXG);
2884 nvlist_free(mos_config);
2885 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
2886 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
2888 fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
2889 spa_config_set(spa, mos_config);
2890 spa->spa_config_source = SPA_CONFIG_SRC_MOS;
2893 * Now that we got the config from the MOS, we should be more strict
2894 * in checking blkptrs and can make assumptions about the consistency
2895 * of the vdev tree. spa_trust_config must be set to true before opening
2896 * vdevs in order for them to be writeable.
2898 spa->spa_trust_config = B_TRUE;
2901 * Open and validate the new vdev tree
2903 error = spa_ld_open_vdevs(spa);
2907 error = spa_ld_validate_vdevs(spa);
2911 if (copy_error != 0 || spa_load_print_vdev_tree) {
2912 spa_load_note(spa, "final vdev tree:");
2913 vdev_dbgmsg_print_tree(rvd, 2);
2916 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
2917 !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
2919 * Sanity check to make sure that we are indeed loading the
2920 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
2921 * in the config provided and they happened to be the only ones
2922 * to have the latest uberblock, we could involuntarily perform
2923 * an extreme rewind.
2925 healthy_tvds_mos = spa_healthy_core_tvds(spa);
2926 if (healthy_tvds_mos - healthy_tvds >=
2927 SPA_SYNC_MIN_VDEVS) {
2928 spa_load_note(spa, "config provided misses too many "
2929 "top-level vdevs compared to MOS (%lld vs %lld). ",
2930 (u_longlong_t)healthy_tvds,
2931 (u_longlong_t)healthy_tvds_mos);
2932 spa_load_note(spa, "vdev tree:");
2933 vdev_dbgmsg_print_tree(rvd, 2);
2935 spa_load_failed(spa, "config was already "
2936 "provided from MOS. Aborting.");
2937 return (spa_vdev_err(rvd,
2938 VDEV_AUX_CORRUPT_DATA, EIO));
2940 spa_load_note(spa, "spa must be reloaded using MOS "
2942 return (SET_ERROR(EAGAIN));
2946 error = spa_check_for_missing_logs(spa);
2948 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2950 if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
2951 spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
2952 "guid sum (%llu != %llu)",
2953 (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
2954 (u_longlong_t)rvd->vdev_guid_sum);
2955 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
2963 spa_ld_open_indirect_vdev_metadata(spa_t *spa)
2966 vdev_t *rvd = spa->spa_root_vdev;
2969 * Everything that we read before spa_remove_init() must be stored
2970 * on concreted vdevs. Therefore we do this as early as possible.
2972 error = spa_remove_init(spa);
2974 spa_load_failed(spa, "spa_remove_init failed [error=%d]",
2976 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2980 * Retrieve information needed to condense indirect vdev mappings.
2982 error = spa_condense_init(spa);
2984 spa_load_failed(spa, "spa_condense_init failed [error=%d]",
2986 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
2993 spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
2996 vdev_t *rvd = spa->spa_root_vdev;
2998 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2999 boolean_t missing_feat_read = B_FALSE;
3000 nvlist_t *unsup_feat, *enabled_feat;
3002 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
3003 &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
3004 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3007 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
3008 &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
3009 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3012 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
3013 &spa->spa_feat_desc_obj, B_TRUE) != 0) {
3014 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3017 enabled_feat = fnvlist_alloc();
3018 unsup_feat = fnvlist_alloc();
3020 if (!spa_features_check(spa, B_FALSE,
3021 unsup_feat, enabled_feat))
3022 missing_feat_read = B_TRUE;
3024 if (spa_writeable(spa) ||
3025 spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3026 if (!spa_features_check(spa, B_TRUE,
3027 unsup_feat, enabled_feat)) {
3028 *missing_feat_writep = B_TRUE;
3032 fnvlist_add_nvlist(spa->spa_load_info,
3033 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3035 if (!nvlist_empty(unsup_feat)) {
3036 fnvlist_add_nvlist(spa->spa_load_info,
3037 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3040 fnvlist_free(enabled_feat);
3041 fnvlist_free(unsup_feat);
3043 if (!missing_feat_read) {
3044 fnvlist_add_boolean(spa->spa_load_info,
3045 ZPOOL_CONFIG_CAN_RDONLY);
3049 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3050 * twofold: to determine whether the pool is available for
3051 * import in read-write mode and (if it is not) whether the
3052 * pool is available for import in read-only mode. If the pool
3053 * is available for import in read-write mode, it is displayed
3054 * as available in userland; if it is not available for import
3055 * in read-only mode, it is displayed as unavailable in
3056 * userland. If the pool is available for import in read-only
3057 * mode but not read-write mode, it is displayed as unavailable
3058 * in userland with a special note that the pool is actually
3059 * available for open in read-only mode.
3061 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3062 * missing a feature for write, we must first determine whether
3063 * the pool can be opened read-only before returning to
3064 * userland in order to know whether to display the
3065 * abovementioned note.
3067 if (missing_feat_read || (*missing_feat_writep &&
3068 spa_writeable(spa))) {
3069 spa_load_failed(spa, "pool uses unsupported features");
3070 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3075 * Load refcounts for ZFS features from disk into an in-memory
3076 * cache during SPA initialization.
3078 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
3081 error = feature_get_refcount_from_disk(spa,
3082 &spa_feature_table[i], &refcount);
3084 spa->spa_feat_refcount_cache[i] = refcount;
3085 } else if (error == ENOTSUP) {
3086 spa->spa_feat_refcount_cache[i] =
3087 SPA_FEATURE_DISABLED;
3089 spa_load_failed(spa, "error getting refcount "
3090 "for feature %s [error=%d]",
3091 spa_feature_table[i].fi_guid, error);
3092 return (spa_vdev_err(rvd,
3093 VDEV_AUX_CORRUPT_DATA, EIO));
3098 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3099 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
3100 &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
3101 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3108 spa_ld_load_special_directories(spa_t *spa)
3111 vdev_t *rvd = spa->spa_root_vdev;
3113 spa->spa_is_initializing = B_TRUE;
3114 error = dsl_pool_open(spa->spa_dsl_pool);
3115 spa->spa_is_initializing = B_FALSE;
3117 spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3118 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3125 spa_ld_get_props(spa_t *spa)
3129 vdev_t *rvd = spa->spa_root_vdev;
3131 /* Grab the secret checksum salt from the MOS. */
3132 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3133 DMU_POOL_CHECKSUM_SALT, 1,
3134 sizeof (spa->spa_cksum_salt.zcs_bytes),
3135 spa->spa_cksum_salt.zcs_bytes);
3136 if (error == ENOENT) {
3137 /* Generate a new salt for subsequent use */
3138 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3139 sizeof (spa->spa_cksum_salt.zcs_bytes));
3140 } else if (error != 0) {
3141 spa_load_failed(spa, "unable to retrieve checksum salt from "
3142 "MOS [error=%d]", error);
3143 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3146 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3147 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3148 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3150 spa_load_failed(spa, "error opening deferred-frees bpobj "
3151 "[error=%d]", error);
3152 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3156 * Load the bit that tells us to use the new accounting function
3157 * (raid-z deflation). If we have an older pool, this will not
3160 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3161 if (error != 0 && error != ENOENT)
3162 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3164 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3165 &spa->spa_creation_version, B_FALSE);
3166 if (error != 0 && error != ENOENT)
3167 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3170 * Load the persistent error log. If we have an older pool, this will
3173 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3175 if (error != 0 && error != ENOENT)
3176 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3178 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3179 &spa->spa_errlog_scrub, B_FALSE);
3180 if (error != 0 && error != ENOENT)
3181 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3184 * Load the history object. If we have an older pool, this
3185 * will not be present.
3187 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3188 if (error != 0 && error != ENOENT)
3189 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3192 * Load the per-vdev ZAP map. If we have an older pool, this will not
3193 * be present; in this case, defer its creation to a later time to
3194 * avoid dirtying the MOS this early / out of sync context. See
3195 * spa_sync_config_object.
3198 /* The sentinel is only available in the MOS config. */
3199 nvlist_t *mos_config;
3200 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3201 spa_load_failed(spa, "unable to retrieve MOS config");
3202 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3205 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3206 &spa->spa_all_vdev_zaps, B_FALSE);
3208 if (error == ENOENT) {
3209 VERIFY(!nvlist_exists(mos_config,
3210 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3211 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3212 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3213 } else if (error != 0) {
3214 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3215 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3217 * An older version of ZFS overwrote the sentinel value, so
3218 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3219 * destruction to later; see spa_sync_config_object.
3221 spa->spa_avz_action = AVZ_ACTION_DESTROY;
3223 * We're assuming that no vdevs have had their ZAPs created
3224 * before this. Better be sure of it.
3226 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3228 nvlist_free(mos_config);
3230 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3232 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3234 if (error && error != ENOENT)
3235 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3238 uint64_t autoreplace;
3240 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3241 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3242 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3243 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3244 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3245 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3246 &spa->spa_dedup_ditto);
3248 spa->spa_autoreplace = (autoreplace != 0);
3252 * If we are importing a pool with missing top-level vdevs,
3253 * we enforce that the pool doesn't panic or get suspended on
3254 * error since the likelihood of missing data is extremely high.
3256 if (spa->spa_missing_tvds > 0 &&
3257 spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3258 spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3259 spa_load_note(spa, "forcing failmode to 'continue' "
3260 "as some top level vdevs are missing");
3261 spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3268 spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3271 vdev_t *rvd = spa->spa_root_vdev;
3274 * If we're assembling the pool from the split-off vdevs of
3275 * an existing pool, we don't want to attach the spares & cache
3280 * Load any hot spares for this pool.
3282 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3284 if (error != 0 && error != ENOENT)
3285 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3286 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3287 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3288 if (load_nvlist(spa, spa->spa_spares.sav_object,
3289 &spa->spa_spares.sav_config) != 0) {
3290 spa_load_failed(spa, "error loading spares nvlist");
3291 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3294 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3295 spa_load_spares(spa);
3296 spa_config_exit(spa, SCL_ALL, FTAG);
3297 } else if (error == 0) {
3298 spa->spa_spares.sav_sync = B_TRUE;
3302 * Load any level 2 ARC devices for this pool.
3304 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3305 &spa->spa_l2cache.sav_object, B_FALSE);
3306 if (error != 0 && error != ENOENT)
3307 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3308 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3309 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3310 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3311 &spa->spa_l2cache.sav_config) != 0) {
3312 spa_load_failed(spa, "error loading l2cache nvlist");
3313 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3316 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3317 spa_load_l2cache(spa);
3318 spa_config_exit(spa, SCL_ALL, FTAG);
3319 } else if (error == 0) {
3320 spa->spa_l2cache.sav_sync = B_TRUE;
3327 spa_ld_load_vdev_metadata(spa_t *spa)
3330 vdev_t *rvd = spa->spa_root_vdev;
3333 * If the 'autoreplace' property is set, then post a resource notifying
3334 * the ZFS DE that it should not issue any faults for unopenable
3335 * devices. We also iterate over the vdevs, and post a sysevent for any
3336 * unopenable vdevs so that the normal autoreplace handler can take
3339 if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3340 spa_check_removed(spa->spa_root_vdev);
3342 * For the import case, this is done in spa_import(), because
3343 * at this point we're using the spare definitions from
3344 * the MOS config, not necessarily from the userland config.
3346 if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3347 spa_aux_check_removed(&spa->spa_spares);
3348 spa_aux_check_removed(&spa->spa_l2cache);
3353 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3355 error = vdev_load(rvd);
3357 spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3358 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3362 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3364 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3365 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3366 spa_config_exit(spa, SCL_ALL, FTAG);
3372 spa_ld_load_dedup_tables(spa_t *spa)
3375 vdev_t *rvd = spa->spa_root_vdev;
3377 error = ddt_load(spa);
3379 spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3380 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3387 spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3389 vdev_t *rvd = spa->spa_root_vdev;
3391 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3392 boolean_t missing = spa_check_logs(spa);
3394 if (spa->spa_missing_tvds != 0) {
3395 spa_load_note(spa, "spa_check_logs failed "
3396 "so dropping the logs");
3398 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3399 spa_load_failed(spa, "spa_check_logs failed");
3400 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3410 spa_ld_verify_pool_data(spa_t *spa)
3413 vdev_t *rvd = spa->spa_root_vdev;
3416 * We've successfully opened the pool, verify that we're ready
3417 * to start pushing transactions.
3419 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3420 error = spa_load_verify(spa);
3422 spa_load_failed(spa, "spa_load_verify failed "
3423 "[error=%d]", error);
3424 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3433 spa_ld_claim_log_blocks(spa_t *spa)
3436 dsl_pool_t *dp = spa_get_dsl(spa);
3439 * Claim log blocks that haven't been committed yet.
3440 * This must all happen in a single txg.
3441 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3442 * invoked from zil_claim_log_block()'s i/o done callback.
3443 * Price of rollback is that we abandon the log.
3445 spa->spa_claiming = B_TRUE;
3447 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3448 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3449 zil_claim, tx, DS_FIND_CHILDREN);
3452 spa->spa_claiming = B_FALSE;
3454 spa_set_log_state(spa, SPA_LOG_GOOD);
3458 spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3459 boolean_t update_config_cache)
3461 vdev_t *rvd = spa->spa_root_vdev;
3462 int need_update = B_FALSE;
3465 * If the config cache is stale, or we have uninitialized
3466 * metaslabs (see spa_vdev_add()), then update the config.
3468 * If this is a verbatim import, trust the current
3469 * in-core spa_config and update the disk labels.
3471 if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
3472 spa->spa_load_state == SPA_LOAD_IMPORT ||
3473 spa->spa_load_state == SPA_LOAD_RECOVER ||
3474 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3475 need_update = B_TRUE;
3477 for (int c = 0; c < rvd->vdev_children; c++)
3478 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3479 need_update = B_TRUE;
3482 * Update the config cache asychronously in case we're the
3483 * root pool, in which case the config cache isn't writable yet.
3486 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3490 spa_ld_prepare_for_reload(spa_t *spa)
3492 int mode = spa->spa_mode;
3493 int async_suspended = spa->spa_async_suspended;
3496 spa_deactivate(spa);
3497 spa_activate(spa, mode);
3500 * We save the value of spa_async_suspended as it gets reset to 0 by
3501 * spa_unload(). We want to restore it back to the original value before
3502 * returning as we might be calling spa_async_resume() later.
3504 spa->spa_async_suspended = async_suspended;
3508 spa_ld_read_checkpoint_txg(spa_t *spa)
3510 uberblock_t checkpoint;
3513 ASSERT0(spa->spa_checkpoint_txg);
3514 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3516 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3517 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3518 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3520 if (error == ENOENT)
3526 ASSERT3U(checkpoint.ub_txg, !=, 0);
3527 ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3528 ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3529 spa->spa_checkpoint_txg = checkpoint.ub_txg;
3530 spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3536 spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
3540 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3541 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3544 * Never trust the config that is provided unless we are assembling
3545 * a pool following a split.
3546 * This means don't trust blkptrs and the vdev tree in general. This
3547 * also effectively puts the spa in read-only mode since
3548 * spa_writeable() checks for spa_trust_config to be true.
3549 * We will later load a trusted config from the MOS.
3551 if (type != SPA_IMPORT_ASSEMBLE)
3552 spa->spa_trust_config = B_FALSE;
3555 * Parse the config provided to create a vdev tree.
3557 error = spa_ld_parse_config(spa, type);
3562 * Now that we have the vdev tree, try to open each vdev. This involves
3563 * opening the underlying physical device, retrieving its geometry and
3564 * probing the vdev with a dummy I/O. The state of each vdev will be set
3565 * based on the success of those operations. After this we'll be ready
3566 * to read from the vdevs.
3568 error = spa_ld_open_vdevs(spa);
3573 * Read the label of each vdev and make sure that the GUIDs stored
3574 * there match the GUIDs in the config provided.
3575 * If we're assembling a new pool that's been split off from an
3576 * existing pool, the labels haven't yet been updated so we skip
3577 * validation for now.
3579 if (type != SPA_IMPORT_ASSEMBLE) {
3580 error = spa_ld_validate_vdevs(spa);
3586 * Read all vdev labels to find the best uberblock (i.e. latest,
3587 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3588 * get the list of features required to read blkptrs in the MOS from
3589 * the vdev label with the best uberblock and verify that our version
3590 * of zfs supports them all.
3592 error = spa_ld_select_uberblock(spa, type);
3597 * Pass that uberblock to the dsl_pool layer which will open the root
3598 * blkptr. This blkptr points to the latest version of the MOS and will
3599 * allow us to read its contents.
3601 error = spa_ld_open_rootbp(spa);
3609 spa_ld_checkpoint_rewind(spa_t *spa)
3611 uberblock_t checkpoint;
3614 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3615 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3617 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3618 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3619 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3622 spa_load_failed(spa, "unable to retrieve checkpointed "
3623 "uberblock from the MOS config [error=%d]", error);
3625 if (error == ENOENT)
3626 error = ZFS_ERR_NO_CHECKPOINT;
3631 ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
3632 ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
3635 * We need to update the txg and timestamp of the checkpointed
3636 * uberblock to be higher than the latest one. This ensures that
3637 * the checkpointed uberblock is selected if we were to close and
3638 * reopen the pool right after we've written it in the vdev labels.
3639 * (also see block comment in vdev_uberblock_compare)
3641 checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
3642 checkpoint.ub_timestamp = gethrestime_sec();
3645 * Set current uberblock to be the checkpointed uberblock.
3647 spa->spa_uberblock = checkpoint;
3650 * If we are doing a normal rewind, then the pool is open for
3651 * writing and we sync the "updated" checkpointed uberblock to
3652 * disk. Once this is done, we've basically rewound the whole
3653 * pool and there is no way back.
3655 * There are cases when we don't want to attempt and sync the
3656 * checkpointed uberblock to disk because we are opening a
3657 * pool as read-only. Specifically, verifying the checkpointed
3658 * state with zdb, and importing the checkpointed state to get
3659 * a "preview" of its content.
3661 if (spa_writeable(spa)) {
3662 vdev_t *rvd = spa->spa_root_vdev;
3664 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3665 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
3667 int children = rvd->vdev_children;
3668 int c0 = spa_get_random(children);
3670 for (int c = 0; c < children; c++) {
3671 vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
3673 /* Stop when revisiting the first vdev */
3674 if (c > 0 && svd[0] == vd)
3677 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
3678 !vdev_is_concrete(vd))
3681 svd[svdcount++] = vd;
3682 if (svdcount == SPA_SYNC_MIN_VDEVS)
3685 error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
3687 spa->spa_last_synced_guid = rvd->vdev_guid;
3688 spa_config_exit(spa, SCL_ALL, FTAG);
3691 spa_load_failed(spa, "failed to write checkpointed "
3692 "uberblock to the vdev labels [error=%d]", error);
3701 spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
3702 boolean_t *update_config_cache)
3707 * Parse the config for pool, open and validate vdevs,
3708 * select an uberblock, and use that uberblock to open
3711 error = spa_ld_mos_init(spa, type);
3716 * Retrieve the trusted config stored in the MOS and use it to create
3717 * a new, exact version of the vdev tree, then reopen all vdevs.
3719 error = spa_ld_trusted_config(spa, type, B_FALSE);
3720 if (error == EAGAIN) {
3721 if (update_config_cache != NULL)
3722 *update_config_cache = B_TRUE;
3725 * Redo the loading process with the trusted config if it is
3726 * too different from the untrusted config.
3728 spa_ld_prepare_for_reload(spa);
3729 spa_load_note(spa, "RELOADING");
3730 error = spa_ld_mos_init(spa, type);
3734 error = spa_ld_trusted_config(spa, type, B_TRUE);
3738 } else if (error != 0) {
3746 * Load an existing storage pool, using the config provided. This config
3747 * describes which vdevs are part of the pool and is later validated against
3748 * partial configs present in each vdev's label and an entire copy of the
3749 * config stored in the MOS.
3752 spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
3755 boolean_t missing_feat_write = B_FALSE;
3756 boolean_t checkpoint_rewind =
3757 (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3758 boolean_t update_config_cache = B_FALSE;
3760 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3761 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3763 spa_load_note(spa, "LOADING");
3765 error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
3770 * If we are rewinding to the checkpoint then we need to repeat
3771 * everything we've done so far in this function but this time
3772 * selecting the checkpointed uberblock and using that to open
3775 if (checkpoint_rewind) {
3777 * If we are rewinding to the checkpoint update config cache
3780 update_config_cache = B_TRUE;
3783 * Extract the checkpointed uberblock from the current MOS
3784 * and use this as the pool's uberblock from now on. If the
3785 * pool is imported as writeable we also write the checkpoint
3786 * uberblock to the labels, making the rewind permanent.
3788 error = spa_ld_checkpoint_rewind(spa);
3793 * Redo the loading process process again with the
3794 * checkpointed uberblock.
3796 spa_ld_prepare_for_reload(spa);
3797 spa_load_note(spa, "LOADING checkpointed uberblock");
3798 error = spa_ld_mos_with_trusted_config(spa, type, NULL);
3804 * Retrieve the checkpoint txg if the pool has a checkpoint.
3806 error = spa_ld_read_checkpoint_txg(spa);
3811 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
3812 * from the pool and their contents were re-mapped to other vdevs. Note
3813 * that everything that we read before this step must have been
3814 * rewritten on concrete vdevs after the last device removal was
3815 * initiated. Otherwise we could be reading from indirect vdevs before
3816 * we have loaded their mappings.
3818 error = spa_ld_open_indirect_vdev_metadata(spa);
3823 * Retrieve the full list of active features from the MOS and check if
3824 * they are all supported.
3826 error = spa_ld_check_features(spa, &missing_feat_write);
3831 * Load several special directories from the MOS needed by the dsl_pool
3834 error = spa_ld_load_special_directories(spa);
3839 * Retrieve pool properties from the MOS.
3841 error = spa_ld_get_props(spa);
3846 * Retrieve the list of auxiliary devices - cache devices and spares -
3849 error = spa_ld_open_aux_vdevs(spa, type);
3854 * Load the metadata for all vdevs. Also check if unopenable devices
3855 * should be autoreplaced.
3857 error = spa_ld_load_vdev_metadata(spa);
3861 error = spa_ld_load_dedup_tables(spa);
3866 * Verify the logs now to make sure we don't have any unexpected errors
3867 * when we claim log blocks later.
3869 error = spa_ld_verify_logs(spa, type, ereport);
3873 if (missing_feat_write) {
3874 ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
3877 * At this point, we know that we can open the pool in
3878 * read-only mode but not read-write mode. We now have enough
3879 * information and can return to userland.
3881 return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
3886 * Traverse the last txgs to make sure the pool was left off in a safe
3887 * state. When performing an extreme rewind, we verify the whole pool,
3888 * which can take a very long time.
3890 error = spa_ld_verify_pool_data(spa);
3895 * Calculate the deflated space for the pool. This must be done before
3896 * we write anything to the pool because we'd need to update the space
3897 * accounting using the deflated sizes.
3899 spa_update_dspace(spa);
3902 * We have now retrieved all the information we needed to open the
3903 * pool. If we are importing the pool in read-write mode, a few
3904 * additional steps must be performed to finish the import.
3906 if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
3907 spa->spa_load_max_txg == UINT64_MAX)) {
3908 uint64_t config_cache_txg = spa->spa_config_txg;
3910 ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
3913 * In case of a checkpoint rewind, log the original txg
3914 * of the checkpointed uberblock.
3916 if (checkpoint_rewind) {
3917 spa_history_log_internal(spa, "checkpoint rewind",
3918 NULL, "rewound state to txg=%llu",
3919 (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
3923 * Traverse the ZIL and claim all blocks.
3925 spa_ld_claim_log_blocks(spa);
3928 * Kick-off the syncing thread.
3930 spa->spa_sync_on = B_TRUE;
3931 txg_sync_start(spa->spa_dsl_pool);
3934 * Wait for all claims to sync. We sync up to the highest
3935 * claimed log block birth time so that claimed log blocks
3936 * don't appear to be from the future. spa_claim_max_txg
3937 * will have been set for us by ZIL traversal operations
3940 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
3943 * Check if we need to request an update of the config. On the
3944 * next sync, we would update the config stored in vdev labels
3945 * and the cachefile (by default /etc/zfs/zpool.cache).
3947 spa_ld_check_for_config_update(spa, config_cache_txg,
3948 update_config_cache);
3951 * Check all DTLs to see if anything needs resilvering.
3953 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
3954 vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
3955 spa_async_request(spa, SPA_ASYNC_RESILVER);
3958 * Log the fact that we booted up (so that we can detect if
3959 * we rebooted in the middle of an operation).
3961 spa_history_log_version(spa, "open");
3964 * Delete any inconsistent datasets.
3966 (void) dmu_objset_find(spa_name(spa),
3967 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
3970 * Clean up any stale temporary dataset userrefs.
3972 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
3974 spa_restart_removal(spa);
3976 spa_spawn_aux_threads(spa);
3978 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3979 vdev_initialize_restart(spa->spa_root_vdev);
3980 spa_config_exit(spa, SCL_CONFIG, FTAG);
3983 spa_load_note(spa, "LOADED");
3989 spa_load_retry(spa_t *spa, spa_load_state_t state)
3991 int mode = spa->spa_mode;
3994 spa_deactivate(spa);
3996 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
3998 spa_activate(spa, mode);
3999 spa_async_suspend(spa);
4001 spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
4002 (u_longlong_t)spa->spa_load_max_txg);
4004 return (spa_load(spa, state, SPA_IMPORT_EXISTING));
4008 * If spa_load() fails this function will try loading prior txg's. If
4009 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
4010 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
4011 * function will not rewind the pool and will return the same error as
4015 spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4018 nvlist_t *loadinfo = NULL;
4019 nvlist_t *config = NULL;
4020 int load_error, rewind_error;
4021 uint64_t safe_rewind_txg;
4024 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4025 spa->spa_load_max_txg = spa->spa_load_txg;
4026 spa_set_log_state(spa, SPA_LOG_CLEAR);
4028 spa->spa_load_max_txg = max_request;
4029 if (max_request != UINT64_MAX)
4030 spa->spa_extreme_rewind = B_TRUE;
4033 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
4034 if (load_error == 0)
4036 if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4038 * When attempting checkpoint-rewind on a pool with no
4039 * checkpoint, we should not attempt to load uberblocks
4040 * from previous txgs when spa_load fails.
4042 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4043 return (load_error);
4046 if (spa->spa_root_vdev != NULL)
4047 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4049 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4050 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4052 if (rewind_flags & ZPOOL_NEVER_REWIND) {
4053 nvlist_free(config);
4054 return (load_error);
4057 if (state == SPA_LOAD_RECOVER) {
4058 /* Price of rolling back is discarding txgs, including log */
4059 spa_set_log_state(spa, SPA_LOG_CLEAR);
4062 * If we aren't rolling back save the load info from our first
4063 * import attempt so that we can restore it after attempting
4066 loadinfo = spa->spa_load_info;
4067 spa->spa_load_info = fnvlist_alloc();
4070 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4071 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4072 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4073 TXG_INITIAL : safe_rewind_txg;
4076 * Continue as long as we're finding errors, we're still within
4077 * the acceptable rewind range, and we're still finding uberblocks
4079 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4080 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4081 if (spa->spa_load_max_txg < safe_rewind_txg)
4082 spa->spa_extreme_rewind = B_TRUE;
4083 rewind_error = spa_load_retry(spa, state);
4086 spa->spa_extreme_rewind = B_FALSE;
4087 spa->spa_load_max_txg = UINT64_MAX;
4089 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4090 spa_config_set(spa, config);
4092 nvlist_free(config);
4094 if (state == SPA_LOAD_RECOVER) {
4095 ASSERT3P(loadinfo, ==, NULL);
4096 return (rewind_error);
4098 /* Store the rewind info as part of the initial load info */
4099 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4100 spa->spa_load_info);
4102 /* Restore the initial load info */
4103 fnvlist_free(spa->spa_load_info);
4104 spa->spa_load_info = loadinfo;
4106 return (load_error);
4113 * The import case is identical to an open except that the configuration is sent
4114 * down from userland, instead of grabbed from the configuration cache. For the
4115 * case of an open, the pool configuration will exist in the
4116 * POOL_STATE_UNINITIALIZED state.
4118 * The stats information (gen/count/ustats) is used to gather vdev statistics at
4119 * the same time open the pool, without having to keep around the spa_t in some
4123 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4127 spa_load_state_t state = SPA_LOAD_OPEN;
4129 int locked = B_FALSE;
4130 int firstopen = B_FALSE;
4135 * As disgusting as this is, we need to support recursive calls to this
4136 * function because dsl_dir_open() is called during spa_load(), and ends
4137 * up calling spa_open() again. The real fix is to figure out how to
4138 * avoid dsl_dir_open() calling this in the first place.
4140 if (mutex_owner(&spa_namespace_lock) != curthread) {
4141 mutex_enter(&spa_namespace_lock);
4145 if ((spa = spa_lookup(pool)) == NULL) {
4147 mutex_exit(&spa_namespace_lock);
4148 return (SET_ERROR(ENOENT));
4151 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
4152 zpool_load_policy_t policy;
4156 zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
4158 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
4159 state = SPA_LOAD_RECOVER;
4161 spa_activate(spa, spa_mode_global);
4163 if (state != SPA_LOAD_RECOVER)
4164 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4165 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
4167 zfs_dbgmsg("spa_open_common: opening %s", pool);
4168 error = spa_load_best(spa, state, policy.zlp_txg,
4171 if (error == EBADF) {
4173 * If vdev_validate() returns failure (indicated by
4174 * EBADF), it indicates that one of the vdevs indicates
4175 * that the pool has been exported or destroyed. If
4176 * this is the case, the config cache is out of sync and
4177 * we should remove the pool from the namespace.
4180 spa_deactivate(spa);
4181 spa_write_cachefile(spa, B_TRUE, B_TRUE);
4184 mutex_exit(&spa_namespace_lock);
4185 return (SET_ERROR(ENOENT));
4190 * We can't open the pool, but we still have useful
4191 * information: the state of each vdev after the
4192 * attempted vdev_open(). Return this to the user.
4194 if (config != NULL && spa->spa_config) {
4195 VERIFY(nvlist_dup(spa->spa_config, config,
4197 VERIFY(nvlist_add_nvlist(*config,
4198 ZPOOL_CONFIG_LOAD_INFO,
4199 spa->spa_load_info) == 0);
4202 spa_deactivate(spa);
4203 spa->spa_last_open_failed = error;
4205 mutex_exit(&spa_namespace_lock);
4211 spa_open_ref(spa, tag);
4214 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4217 * If we've recovered the pool, pass back any information we
4218 * gathered while doing the load.
4220 if (state == SPA_LOAD_RECOVER) {
4221 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4222 spa->spa_load_info) == 0);
4226 spa->spa_last_open_failed = 0;
4227 spa->spa_last_ubsync_txg = 0;
4228 spa->spa_load_txg = 0;
4229 mutex_exit(&spa_namespace_lock);
4233 zvol_create_minors(spa->spa_name);
4244 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4247 return (spa_open_common(name, spapp, tag, policy, config));
4251 spa_open(const char *name, spa_t **spapp, void *tag)
4253 return (spa_open_common(name, spapp, tag, NULL, NULL));
4257 * Lookup the given spa_t, incrementing the inject count in the process,
4258 * preventing it from being exported or destroyed.
4261 spa_inject_addref(char *name)
4265 mutex_enter(&spa_namespace_lock);
4266 if ((spa = spa_lookup(name)) == NULL) {
4267 mutex_exit(&spa_namespace_lock);
4270 spa->spa_inject_ref++;
4271 mutex_exit(&spa_namespace_lock);
4277 spa_inject_delref(spa_t *spa)
4279 mutex_enter(&spa_namespace_lock);
4280 spa->spa_inject_ref--;
4281 mutex_exit(&spa_namespace_lock);
4285 * Add spares device information to the nvlist.
4288 spa_add_spares(spa_t *spa, nvlist_t *config)
4298 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4300 if (spa->spa_spares.sav_count == 0)
4303 VERIFY(nvlist_lookup_nvlist(config,
4304 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4305 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4306 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4308 VERIFY(nvlist_add_nvlist_array(nvroot,
4309 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4310 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4311 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4314 * Go through and find any spares which have since been
4315 * repurposed as an active spare. If this is the case, update
4316 * their status appropriately.
4318 for (i = 0; i < nspares; i++) {
4319 VERIFY(nvlist_lookup_uint64(spares[i],
4320 ZPOOL_CONFIG_GUID, &guid) == 0);
4321 if (spa_spare_exists(guid, &pool, NULL) &&
4323 VERIFY(nvlist_lookup_uint64_array(
4324 spares[i], ZPOOL_CONFIG_VDEV_STATS,
4325 (uint64_t **)&vs, &vsc) == 0);
4326 vs->vs_state = VDEV_STATE_CANT_OPEN;
4327 vs->vs_aux = VDEV_AUX_SPARED;
4334 * Add l2cache device information to the nvlist, including vdev stats.
4337 spa_add_l2cache(spa_t *spa, nvlist_t *config)
4340 uint_t i, j, nl2cache;
4347 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4349 if (spa->spa_l2cache.sav_count == 0)
4352 VERIFY(nvlist_lookup_nvlist(config,
4353 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4354 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4355 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4356 if (nl2cache != 0) {
4357 VERIFY(nvlist_add_nvlist_array(nvroot,
4358 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4359 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4360 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4363 * Update level 2 cache device stats.
4366 for (i = 0; i < nl2cache; i++) {
4367 VERIFY(nvlist_lookup_uint64(l2cache[i],
4368 ZPOOL_CONFIG_GUID, &guid) == 0);
4371 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4373 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4374 vd = spa->spa_l2cache.sav_vdevs[j];
4380 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4381 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4383 vdev_get_stats(vd, vs);
4389 spa_feature_stats_from_disk(spa_t *spa, nvlist_t *features)
4394 /* We may be unable to read features if pool is suspended. */
4395 if (spa_suspended(spa))
4398 if (spa->spa_feat_for_read_obj != 0) {
4399 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4400 spa->spa_feat_for_read_obj);
4401 zap_cursor_retrieve(&zc, &za) == 0;
4402 zap_cursor_advance(&zc)) {
4403 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4404 za.za_num_integers == 1);
4405 VERIFY0(nvlist_add_uint64(features, za.za_name,
4406 za.za_first_integer));
4408 zap_cursor_fini(&zc);
4411 if (spa->spa_feat_for_write_obj != 0) {
4412 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4413 spa->spa_feat_for_write_obj);
4414 zap_cursor_retrieve(&zc, &za) == 0;
4415 zap_cursor_advance(&zc)) {
4416 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4417 za.za_num_integers == 1);
4418 VERIFY0(nvlist_add_uint64(features, za.za_name,
4419 za.za_first_integer));
4421 zap_cursor_fini(&zc);
4426 spa_feature_stats_from_cache(spa_t *spa, nvlist_t *features)
4430 for (i = 0; i < SPA_FEATURES; i++) {
4431 zfeature_info_t feature = spa_feature_table[i];
4434 if (feature_get_refcount(spa, &feature, &refcount) != 0)
4437 VERIFY0(nvlist_add_uint64(features, feature.fi_guid, refcount));
4442 * Store a list of pool features and their reference counts in the
4445 * The first time this is called on a spa, allocate a new nvlist, fetch
4446 * the pool features and reference counts from disk, then save the list
4447 * in the spa. In subsequent calls on the same spa use the saved nvlist
4448 * and refresh its values from the cached reference counts. This
4449 * ensures we don't block here on I/O on a suspended pool so 'zpool
4450 * clear' can resume the pool.
4453 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4457 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4459 mutex_enter(&spa->spa_feat_stats_lock);
4460 features = spa->spa_feat_stats;
4462 if (features != NULL) {
4463 spa_feature_stats_from_cache(spa, features);
4465 VERIFY0(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP));
4466 spa->spa_feat_stats = features;
4467 spa_feature_stats_from_disk(spa, features);
4470 VERIFY0(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4473 mutex_exit(&spa->spa_feat_stats_lock);
4477 spa_get_stats(const char *name, nvlist_t **config,
4478 char *altroot, size_t buflen)
4484 error = spa_open_common(name, &spa, FTAG, NULL, config);
4488 * This still leaves a window of inconsistency where the spares
4489 * or l2cache devices could change and the config would be
4490 * self-inconsistent.
4492 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4494 if (*config != NULL) {
4495 uint64_t loadtimes[2];
4497 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4498 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4499 VERIFY(nvlist_add_uint64_array(*config,
4500 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4502 VERIFY(nvlist_add_uint64(*config,
4503 ZPOOL_CONFIG_ERRCOUNT,
4504 spa_get_errlog_size(spa)) == 0);
4506 if (spa_suspended(spa))
4507 VERIFY(nvlist_add_uint64(*config,
4508 ZPOOL_CONFIG_SUSPENDED,
4509 spa->spa_failmode) == 0);
4511 spa_add_spares(spa, *config);
4512 spa_add_l2cache(spa, *config);
4513 spa_add_feature_stats(spa, *config);
4518 * We want to get the alternate root even for faulted pools, so we cheat
4519 * and call spa_lookup() directly.
4523 mutex_enter(&spa_namespace_lock);
4524 spa = spa_lookup(name);
4526 spa_altroot(spa, altroot, buflen);
4530 mutex_exit(&spa_namespace_lock);
4532 spa_altroot(spa, altroot, buflen);
4537 spa_config_exit(spa, SCL_CONFIG, FTAG);
4538 spa_close(spa, FTAG);
4545 * Validate that the auxiliary device array is well formed. We must have an
4546 * array of nvlists, each which describes a valid leaf vdev. If this is an
4547 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4548 * specified, as long as they are well-formed.
4551 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4552 spa_aux_vdev_t *sav, const char *config, uint64_t version,
4553 vdev_labeltype_t label)
4560 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4563 * It's acceptable to have no devs specified.
4565 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4569 return (SET_ERROR(EINVAL));
4572 * Make sure the pool is formatted with a version that supports this
4575 if (spa_version(spa) < version)
4576 return (SET_ERROR(ENOTSUP));
4579 * Set the pending device list so we correctly handle device in-use
4582 sav->sav_pending = dev;
4583 sav->sav_npending = ndev;
4585 for (i = 0; i < ndev; i++) {
4586 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4590 if (!vd->vdev_ops->vdev_op_leaf) {
4592 error = SET_ERROR(EINVAL);
4597 * The L2ARC currently only supports disk devices in
4598 * kernel context. For user-level testing, we allow it.
4601 if ((strcmp(config, ZPOOL_CONFIG_L2CACHE) == 0) &&
4602 strcmp(vd->vdev_ops->vdev_op_type, VDEV_TYPE_DISK) != 0) {
4603 error = SET_ERROR(ENOTBLK);
4610 if ((error = vdev_open(vd)) == 0 &&
4611 (error = vdev_label_init(vd, crtxg, label)) == 0) {
4612 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4613 vd->vdev_guid) == 0);
4619 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
4626 sav->sav_pending = NULL;
4627 sav->sav_npending = 0;
4632 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
4636 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4638 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4639 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
4640 VDEV_LABEL_SPARE)) != 0) {
4644 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4645 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
4646 VDEV_LABEL_L2CACHE));
4650 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
4655 if (sav->sav_config != NULL) {
4661 * Generate new dev list by concatentating with the
4664 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
4665 &olddevs, &oldndevs) == 0);
4667 newdevs = kmem_alloc(sizeof (void *) *
4668 (ndevs + oldndevs), KM_SLEEP);
4669 for (i = 0; i < oldndevs; i++)
4670 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
4672 for (i = 0; i < ndevs; i++)
4673 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
4676 VERIFY(nvlist_remove(sav->sav_config, config,
4677 DATA_TYPE_NVLIST_ARRAY) == 0);
4679 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
4680 config, newdevs, ndevs + oldndevs) == 0);
4681 for (i = 0; i < oldndevs + ndevs; i++)
4682 nvlist_free(newdevs[i]);
4683 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
4686 * Generate a new dev list.
4688 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
4690 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
4696 * Stop and drop level 2 ARC devices
4699 spa_l2cache_drop(spa_t *spa)
4703 spa_aux_vdev_t *sav = &spa->spa_l2cache;
4705 for (i = 0; i < sav->sav_count; i++) {
4708 vd = sav->sav_vdevs[i];
4711 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
4712 pool != 0ULL && l2arc_vdev_present(vd))
4713 l2arc_remove_vdev(vd);
4721 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
4725 char *altroot = NULL;
4730 uint64_t txg = TXG_INITIAL;
4731 nvlist_t **spares, **l2cache;
4732 uint_t nspares, nl2cache;
4733 uint64_t version, obj;
4734 boolean_t has_features;
4738 if (nvlist_lookup_string(props,
4739 zpool_prop_to_name(ZPOOL_PROP_TNAME), &poolname) != 0)
4740 poolname = (char *)pool;
4743 * If this pool already exists, return failure.
4745 mutex_enter(&spa_namespace_lock);
4746 if (spa_lookup(poolname) != NULL) {
4747 mutex_exit(&spa_namespace_lock);
4748 return (SET_ERROR(EEXIST));
4752 * Allocate a new spa_t structure.
4754 nvl = fnvlist_alloc();
4755 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
4756 (void) nvlist_lookup_string(props,
4757 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4758 spa = spa_add(poolname, nvl, altroot);
4760 spa_activate(spa, spa_mode_global);
4762 if (props && (error = spa_prop_validate(spa, props))) {
4763 spa_deactivate(spa);
4765 mutex_exit(&spa_namespace_lock);
4770 * Temporary pool names should never be written to disk.
4772 if (poolname != pool)
4773 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
4775 has_features = B_FALSE;
4776 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
4777 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
4778 if (zpool_prop_feature(nvpair_name(elem)))
4779 has_features = B_TRUE;
4782 if (has_features || nvlist_lookup_uint64(props,
4783 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
4784 version = SPA_VERSION;
4786 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
4788 spa->spa_first_txg = txg;
4789 spa->spa_uberblock.ub_txg = txg - 1;
4790 spa->spa_uberblock.ub_version = version;
4791 spa->spa_ubsync = spa->spa_uberblock;
4792 spa->spa_load_state = SPA_LOAD_CREATE;
4793 spa->spa_removing_phys.sr_state = DSS_NONE;
4794 spa->spa_removing_phys.sr_removing_vdev = -1;
4795 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
4798 * Create "The Godfather" zio to hold all async IOs
4800 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
4802 for (int i = 0; i < max_ncpus; i++) {
4803 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
4804 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4805 ZIO_FLAG_GODFATHER);
4809 * Create the root vdev.
4811 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4813 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
4815 ASSERT(error != 0 || rvd != NULL);
4816 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
4818 if (error == 0 && !zfs_allocatable_devs(nvroot))
4819 error = SET_ERROR(EINVAL);
4822 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
4823 (error = spa_validate_aux(spa, nvroot, txg,
4824 VDEV_ALLOC_ADD)) == 0) {
4825 for (int c = 0; c < rvd->vdev_children; c++) {
4826 vdev_ashift_optimize(rvd->vdev_child[c]);
4827 vdev_metaslab_set_size(rvd->vdev_child[c]);
4828 vdev_expand(rvd->vdev_child[c], txg);
4832 spa_config_exit(spa, SCL_ALL, FTAG);
4836 spa_deactivate(spa);
4838 mutex_exit(&spa_namespace_lock);
4843 * Get the list of spares, if specified.
4845 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4846 &spares, &nspares) == 0) {
4847 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
4849 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4850 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4851 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4852 spa_load_spares(spa);
4853 spa_config_exit(spa, SCL_ALL, FTAG);
4854 spa->spa_spares.sav_sync = B_TRUE;
4858 * Get the list of level 2 cache devices, if specified.
4860 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4861 &l2cache, &nl2cache) == 0) {
4862 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
4863 NV_UNIQUE_NAME, KM_SLEEP) == 0);
4864 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4865 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4866 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4867 spa_load_l2cache(spa);
4868 spa_config_exit(spa, SCL_ALL, FTAG);
4869 spa->spa_l2cache.sav_sync = B_TRUE;
4872 spa->spa_is_initializing = B_TRUE;
4873 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
4874 spa->spa_meta_objset = dp->dp_meta_objset;
4875 spa->spa_is_initializing = B_FALSE;
4878 * Create DDTs (dedup tables).
4882 spa_update_dspace(spa);
4884 tx = dmu_tx_create_assigned(dp, txg);
4887 * Create the pool config object.
4889 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
4890 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
4891 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
4893 if (zap_add(spa->spa_meta_objset,
4894 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
4895 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
4896 cmn_err(CE_PANIC, "failed to add pool config");
4899 if (spa_version(spa) >= SPA_VERSION_FEATURES)
4900 spa_feature_create_zap_objects(spa, tx);
4902 if (zap_add(spa->spa_meta_objset,
4903 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
4904 sizeof (uint64_t), 1, &version, tx) != 0) {
4905 cmn_err(CE_PANIC, "failed to add pool version");
4908 /* Newly created pools with the right version are always deflated. */
4909 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
4910 spa->spa_deflate = TRUE;
4911 if (zap_add(spa->spa_meta_objset,
4912 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
4913 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
4914 cmn_err(CE_PANIC, "failed to add deflate");
4919 * Create the deferred-free bpobj. Turn off compression
4920 * because sync-to-convergence takes longer if the blocksize
4923 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
4924 dmu_object_set_compress(spa->spa_meta_objset, obj,
4925 ZIO_COMPRESS_OFF, tx);
4926 if (zap_add(spa->spa_meta_objset,
4927 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
4928 sizeof (uint64_t), 1, &obj, tx) != 0) {
4929 cmn_err(CE_PANIC, "failed to add bpobj");
4931 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
4932 spa->spa_meta_objset, obj));
4935 * Create the pool's history object.
4937 if (version >= SPA_VERSION_ZPOOL_HISTORY)
4938 spa_history_create_obj(spa, tx);
4941 * Generate some random noise for salted checksums to operate on.
4943 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
4944 sizeof (spa->spa_cksum_salt.zcs_bytes));
4947 * Set pool properties.
4949 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
4950 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
4951 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
4952 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
4954 if (props != NULL) {
4955 spa_configfile_set(spa, props, B_FALSE);
4956 spa_sync_props(props, tx);
4961 spa->spa_sync_on = B_TRUE;
4962 txg_sync_start(spa->spa_dsl_pool);
4965 * We explicitly wait for the first transaction to complete so that our
4966 * bean counters are appropriately updated.
4968 txg_wait_synced(spa->spa_dsl_pool, txg);
4970 spa_spawn_aux_threads(spa);
4972 spa_write_cachefile(spa, B_FALSE, B_TRUE);
4973 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
4975 spa_history_log_version(spa, "create");
4978 * Don't count references from objsets that are already closed
4979 * and are making their way through the eviction process.
4981 spa_evicting_os_wait(spa);
4982 spa->spa_minref = refcount_count(&spa->spa_refcount);
4983 spa->spa_load_state = SPA_LOAD_NONE;
4985 mutex_exit(&spa_namespace_lock);
4993 * Get the root pool information from the root disk, then import the root pool
4994 * during the system boot up time.
4996 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
4999 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
5002 nvlist_t *nvtop, *nvroot;
5005 if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
5009 * Add this top-level vdev to the child array.
5011 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5013 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5015 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
5018 * Put this pool's top-level vdevs into a root vdev.
5020 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5021 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5022 VDEV_TYPE_ROOT) == 0);
5023 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5024 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5025 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5029 * Replace the existing vdev_tree with the new root vdev in
5030 * this pool's configuration (remove the old, add the new).
5032 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5033 nvlist_free(nvroot);
5038 * Walk the vdev tree and see if we can find a device with "better"
5039 * configuration. A configuration is "better" if the label on that
5040 * device has a more recent txg.
5043 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
5045 for (int c = 0; c < vd->vdev_children; c++)
5046 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
5048 if (vd->vdev_ops->vdev_op_leaf) {
5052 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
5056 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
5060 * Do we have a better boot device?
5062 if (label_txg > *txg) {
5071 * Import a root pool.
5073 * For x86. devpath_list will consist of devid and/or physpath name of
5074 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
5075 * The GRUB "findroot" command will return the vdev we should boot.
5077 * For Sparc, devpath_list consists the physpath name of the booting device
5078 * no matter the rootpool is a single device pool or a mirrored pool.
5080 * "/pci@1f,0/ide@d/disk@0,0:a"
5083 spa_import_rootpool(char *devpath, char *devid)
5086 vdev_t *rvd, *bvd, *avd = NULL;
5087 nvlist_t *config, *nvtop;
5093 * Read the label from the boot device and generate a configuration.
5095 config = spa_generate_rootconf(devpath, devid, &guid);
5096 #if defined(_OBP) && defined(_KERNEL)
5097 if (config == NULL) {
5098 if (strstr(devpath, "/iscsi/ssd") != NULL) {
5100 get_iscsi_bootpath_phy(devpath);
5101 config = spa_generate_rootconf(devpath, devid, &guid);
5105 if (config == NULL) {
5106 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
5108 return (SET_ERROR(EIO));
5111 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5113 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
5115 mutex_enter(&spa_namespace_lock);
5116 if ((spa = spa_lookup(pname)) != NULL) {
5118 * Remove the existing root pool from the namespace so that we
5119 * can replace it with the correct config we just read in.
5124 spa = spa_add(pname, config, NULL);
5125 spa->spa_is_root = B_TRUE;
5126 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5127 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5128 &spa->spa_ubsync.ub_version) != 0)
5129 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5132 * Build up a vdev tree based on the boot device's label config.
5134 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5136 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5137 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5138 VDEV_ALLOC_ROOTPOOL);
5139 spa_config_exit(spa, SCL_ALL, FTAG);
5141 mutex_exit(&spa_namespace_lock);
5142 nvlist_free(config);
5143 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5149 * Get the boot vdev.
5151 if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
5152 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
5153 (u_longlong_t)guid);
5154 error = SET_ERROR(ENOENT);
5159 * Determine if there is a better boot device.
5162 spa_alt_rootvdev(rvd, &avd, &txg);
5164 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
5165 "try booting from '%s'", avd->vdev_path);
5166 error = SET_ERROR(EINVAL);
5171 * If the boot device is part of a spare vdev then ensure that
5172 * we're booting off the active spare.
5174 if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
5175 !bvd->vdev_isspare) {
5176 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
5177 "try booting from '%s'",
5179 vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
5180 error = SET_ERROR(EINVAL);
5186 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5188 spa_config_exit(spa, SCL_ALL, FTAG);
5189 mutex_exit(&spa_namespace_lock);
5191 nvlist_free(config);
5195 #else /* !illumos */
5197 extern int vdev_geom_read_pool_label(const char *name, nvlist_t ***configs,
5201 spa_generate_rootconf(const char *name)
5203 nvlist_t **configs, **tops;
5205 nvlist_t *best_cfg, *nvtop, *nvroot;
5214 if (vdev_geom_read_pool_label(name, &configs, &count) != 0)
5217 ASSERT3U(count, !=, 0);
5219 for (i = 0; i < count; i++) {
5222 VERIFY(nvlist_lookup_uint64(configs[i], ZPOOL_CONFIG_POOL_TXG,
5224 if (txg > best_txg) {
5226 best_cfg = configs[i];
5231 nvlist_lookup_uint64(best_cfg, ZPOOL_CONFIG_VDEV_CHILDREN, &nchildren);
5233 nvlist_lookup_uint64_array(best_cfg, ZPOOL_CONFIG_HOLE_ARRAY,
5236 tops = kmem_zalloc(nchildren * sizeof(void *), KM_SLEEP);
5237 for (i = 0; i < nchildren; i++) {
5240 if (configs[i] == NULL)
5242 VERIFY(nvlist_lookup_nvlist(configs[i], ZPOOL_CONFIG_VDEV_TREE,
5244 nvlist_dup(nvtop, &tops[i], KM_SLEEP);
5246 for (i = 0; holes != NULL && i < nholes; i++) {
5249 if (tops[holes[i]] != NULL)
5251 nvlist_alloc(&tops[holes[i]], NV_UNIQUE_NAME, KM_SLEEP);
5252 VERIFY(nvlist_add_string(tops[holes[i]], ZPOOL_CONFIG_TYPE,
5253 VDEV_TYPE_HOLE) == 0);
5254 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_ID,
5256 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_GUID,
5259 for (i = 0; i < nchildren; i++) {
5260 if (tops[i] != NULL)
5262 nvlist_alloc(&tops[i], NV_UNIQUE_NAME, KM_SLEEP);
5263 VERIFY(nvlist_add_string(tops[i], ZPOOL_CONFIG_TYPE,
5264 VDEV_TYPE_MISSING) == 0);
5265 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_ID,
5267 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_GUID,
5272 * Create pool config based on the best vdev config.
5274 nvlist_dup(best_cfg, &config, KM_SLEEP);
5277 * Put this pool's top-level vdevs into a root vdev.
5279 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5281 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5282 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5283 VDEV_TYPE_ROOT) == 0);
5284 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5285 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5286 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5287 tops, nchildren) == 0);
5290 * Replace the existing vdev_tree with the new root vdev in
5291 * this pool's configuration (remove the old, add the new).
5293 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5296 * Drop vdev config elements that should not be present at pool level.
5298 nvlist_remove(config, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64);
5299 nvlist_remove(config, ZPOOL_CONFIG_TOP_GUID, DATA_TYPE_UINT64);
5301 for (i = 0; i < count; i++)
5302 nvlist_free(configs[i]);
5303 kmem_free(configs, count * sizeof(void *));
5304 for (i = 0; i < nchildren; i++)
5305 nvlist_free(tops[i]);
5306 kmem_free(tops, nchildren * sizeof(void *));
5307 nvlist_free(nvroot);
5312 spa_import_rootpool(const char *name)
5315 vdev_t *rvd, *bvd, *avd = NULL;
5316 nvlist_t *config, *nvtop;
5322 * Read the label from the boot device and generate a configuration.
5324 config = spa_generate_rootconf(name);
5326 mutex_enter(&spa_namespace_lock);
5327 if (config != NULL) {
5328 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5329 &pname) == 0 && strcmp(name, pname) == 0);
5330 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg)
5333 if ((spa = spa_lookup(pname)) != NULL) {
5335 * The pool could already be imported,
5336 * e.g., after reboot -r.
5338 if (spa->spa_state == POOL_STATE_ACTIVE) {
5339 mutex_exit(&spa_namespace_lock);
5340 nvlist_free(config);
5345 * Remove the existing root pool from the namespace so
5346 * that we can replace it with the correct config
5351 spa = spa_add(pname, config, NULL);
5354 * Set spa_ubsync.ub_version as it can be used in vdev_alloc()
5355 * via spa_version().
5357 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5358 &spa->spa_ubsync.ub_version) != 0)
5359 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5360 } else if ((spa = spa_lookup(name)) == NULL) {
5361 mutex_exit(&spa_namespace_lock);
5362 nvlist_free(config);
5363 cmn_err(CE_NOTE, "Cannot find the pool label for '%s'",
5367 VERIFY(nvlist_dup(spa->spa_config, &config, KM_SLEEP) == 0);
5369 spa->spa_is_root = B_TRUE;
5370 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5373 * Build up a vdev tree based on the boot device's label config.
5375 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5377 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5378 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5379 VDEV_ALLOC_ROOTPOOL);
5380 spa_config_exit(spa, SCL_ALL, FTAG);
5382 mutex_exit(&spa_namespace_lock);
5383 nvlist_free(config);
5384 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5389 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5391 spa_config_exit(spa, SCL_ALL, FTAG);
5392 mutex_exit(&spa_namespace_lock);
5394 nvlist_free(config);
5398 #endif /* illumos */
5399 #endif /* _KERNEL */
5402 * Import a non-root pool into the system.
5405 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5408 char *altroot = NULL;
5409 spa_load_state_t state = SPA_LOAD_IMPORT;
5410 zpool_load_policy_t policy;
5411 uint64_t mode = spa_mode_global;
5412 uint64_t readonly = B_FALSE;
5415 nvlist_t **spares, **l2cache;
5416 uint_t nspares, nl2cache;
5419 * If a pool with this name exists, return failure.
5421 mutex_enter(&spa_namespace_lock);
5422 if (spa_lookup(pool) != NULL) {
5423 mutex_exit(&spa_namespace_lock);
5424 return (SET_ERROR(EEXIST));
5428 * Create and initialize the spa structure.
5430 (void) nvlist_lookup_string(props,
5431 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5432 (void) nvlist_lookup_uint64(props,
5433 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5436 spa = spa_add(pool, config, altroot);
5437 spa->spa_import_flags = flags;
5440 * Verbatim import - Take a pool and insert it into the namespace
5441 * as if it had been loaded at boot.
5443 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5445 spa_configfile_set(spa, props, B_FALSE);
5447 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5448 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5449 zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5450 mutex_exit(&spa_namespace_lock);
5454 spa_activate(spa, mode);
5457 * Don't start async tasks until we know everything is healthy.
5459 spa_async_suspend(spa);
5461 zpool_get_load_policy(config, &policy);
5462 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5463 state = SPA_LOAD_RECOVER;
5465 spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5467 if (state != SPA_LOAD_RECOVER) {
5468 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5469 zfs_dbgmsg("spa_import: importing %s", pool);
5471 zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5472 "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
5474 error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
5477 * Propagate anything learned while loading the pool and pass it
5478 * back to caller (i.e. rewind info, missing devices, etc).
5480 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5481 spa->spa_load_info) == 0);
5483 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5485 * Toss any existing sparelist, as it doesn't have any validity
5486 * anymore, and conflicts with spa_has_spare().
5488 if (spa->spa_spares.sav_config) {
5489 nvlist_free(spa->spa_spares.sav_config);
5490 spa->spa_spares.sav_config = NULL;
5491 spa_load_spares(spa);
5493 if (spa->spa_l2cache.sav_config) {
5494 nvlist_free(spa->spa_l2cache.sav_config);
5495 spa->spa_l2cache.sav_config = NULL;
5496 spa_load_l2cache(spa);
5499 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5502 error = spa_validate_aux(spa, nvroot, -1ULL,
5505 error = spa_validate_aux(spa, nvroot, -1ULL,
5506 VDEV_ALLOC_L2CACHE);
5507 spa_config_exit(spa, SCL_ALL, FTAG);
5510 spa_configfile_set(spa, props, B_FALSE);
5512 if (error != 0 || (props && spa_writeable(spa) &&
5513 (error = spa_prop_set(spa, props)))) {
5515 spa_deactivate(spa);
5517 mutex_exit(&spa_namespace_lock);
5521 spa_async_resume(spa);
5524 * Override any spares and level 2 cache devices as specified by
5525 * the user, as these may have correct device names/devids, etc.
5527 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5528 &spares, &nspares) == 0) {
5529 if (spa->spa_spares.sav_config)
5530 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5531 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5533 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5534 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5535 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5536 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5537 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5538 spa_load_spares(spa);
5539 spa_config_exit(spa, SCL_ALL, FTAG);
5540 spa->spa_spares.sav_sync = B_TRUE;
5542 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5543 &l2cache, &nl2cache) == 0) {
5544 if (spa->spa_l2cache.sav_config)
5545 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5546 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5548 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5549 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5550 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5551 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5552 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5553 spa_load_l2cache(spa);
5554 spa_config_exit(spa, SCL_ALL, FTAG);
5555 spa->spa_l2cache.sav_sync = B_TRUE;
5559 * Check for any removed devices.
5561 if (spa->spa_autoreplace) {
5562 spa_aux_check_removed(&spa->spa_spares);
5563 spa_aux_check_removed(&spa->spa_l2cache);
5566 if (spa_writeable(spa)) {
5568 * Update the config cache to include the newly-imported pool.
5570 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5574 * It's possible that the pool was expanded while it was exported.
5575 * We kick off an async task to handle this for us.
5577 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5579 spa_history_log_version(spa, "import");
5581 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5583 mutex_exit(&spa_namespace_lock);
5587 zvol_create_minors(pool);
5594 spa_tryimport(nvlist_t *tryconfig)
5596 nvlist_t *config = NULL;
5597 char *poolname, *cachefile;
5601 zpool_load_policy_t policy;
5603 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5606 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5610 * Create and initialize the spa structure.
5612 mutex_enter(&spa_namespace_lock);
5613 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
5614 spa_activate(spa, FREAD);
5617 * Rewind pool if a max txg was provided.
5619 zpool_get_load_policy(spa->spa_config, &policy);
5620 if (policy.zlp_txg != UINT64_MAX) {
5621 spa->spa_load_max_txg = policy.zlp_txg;
5622 spa->spa_extreme_rewind = B_TRUE;
5623 zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
5624 poolname, (longlong_t)policy.zlp_txg);
5626 zfs_dbgmsg("spa_tryimport: importing %s", poolname);
5629 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
5631 zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
5632 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5634 spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
5637 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
5640 * If 'tryconfig' was at least parsable, return the current config.
5642 if (spa->spa_root_vdev != NULL) {
5643 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5644 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
5646 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5648 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
5649 spa->spa_uberblock.ub_timestamp) == 0);
5650 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5651 spa->spa_load_info) == 0);
5654 * If the bootfs property exists on this pool then we
5655 * copy it out so that external consumers can tell which
5656 * pools are bootable.
5658 if ((!error || error == EEXIST) && spa->spa_bootfs) {
5659 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5662 * We have to play games with the name since the
5663 * pool was opened as TRYIMPORT_NAME.
5665 if (dsl_dsobj_to_dsname(spa_name(spa),
5666 spa->spa_bootfs, tmpname) == 0) {
5668 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5670 cp = strchr(tmpname, '/');
5672 (void) strlcpy(dsname, tmpname,
5675 (void) snprintf(dsname, MAXPATHLEN,
5676 "%s/%s", poolname, ++cp);
5678 VERIFY(nvlist_add_string(config,
5679 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
5680 kmem_free(dsname, MAXPATHLEN);
5682 kmem_free(tmpname, MAXPATHLEN);
5686 * Add the list of hot spares and level 2 cache devices.
5688 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5689 spa_add_spares(spa, config);
5690 spa_add_l2cache(spa, config);
5691 spa_config_exit(spa, SCL_CONFIG, FTAG);
5695 spa_deactivate(spa);
5697 mutex_exit(&spa_namespace_lock);
5703 * Pool export/destroy
5705 * The act of destroying or exporting a pool is very simple. We make sure there
5706 * is no more pending I/O and any references to the pool are gone. Then, we
5707 * update the pool state and sync all the labels to disk, removing the
5708 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
5709 * we don't sync the labels or remove the configuration cache.
5712 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
5713 boolean_t force, boolean_t hardforce)
5720 if (!(spa_mode_global & FWRITE))
5721 return (SET_ERROR(EROFS));
5723 mutex_enter(&spa_namespace_lock);
5724 if ((spa = spa_lookup(pool)) == NULL) {
5725 mutex_exit(&spa_namespace_lock);
5726 return (SET_ERROR(ENOENT));
5730 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5731 * reacquire the namespace lock, and see if we can export.
5733 spa_open_ref(spa, FTAG);
5734 mutex_exit(&spa_namespace_lock);
5735 spa_async_suspend(spa);
5736 mutex_enter(&spa_namespace_lock);
5737 spa_close(spa, FTAG);
5740 * The pool will be in core if it's openable,
5741 * in which case we can modify its state.
5743 if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
5746 * Objsets may be open only because they're dirty, so we
5747 * have to force it to sync before checking spa_refcnt.
5749 txg_wait_synced(spa->spa_dsl_pool, 0);
5750 spa_evicting_os_wait(spa);
5753 * A pool cannot be exported or destroyed if there are active
5754 * references. If we are resetting a pool, allow references by
5755 * fault injection handlers.
5757 if (!spa_refcount_zero(spa) ||
5758 (spa->spa_inject_ref != 0 &&
5759 new_state != POOL_STATE_UNINITIALIZED)) {
5760 spa_async_resume(spa);
5761 mutex_exit(&spa_namespace_lock);
5762 return (SET_ERROR(EBUSY));
5766 * A pool cannot be exported if it has an active shared spare.
5767 * This is to prevent other pools stealing the active spare
5768 * from an exported pool. At user's own will, such pool can
5769 * be forcedly exported.
5771 if (!force && new_state == POOL_STATE_EXPORTED &&
5772 spa_has_active_shared_spare(spa)) {
5773 spa_async_resume(spa);
5774 mutex_exit(&spa_namespace_lock);
5775 return (SET_ERROR(EXDEV));
5779 * We're about to export or destroy this pool. Make sure
5780 * we stop all initializtion activity here before we
5781 * set the spa_final_txg. This will ensure that all
5782 * dirty data resulting from the initialization is
5783 * committed to disk before we unload the pool.
5785 if (spa->spa_root_vdev != NULL) {
5786 vdev_initialize_stop_all(spa->spa_root_vdev,
5787 VDEV_INITIALIZE_ACTIVE);
5791 * We want this to be reflected on every label,
5792 * so mark them all dirty. spa_unload() will do the
5793 * final sync that pushes these changes out.
5795 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
5796 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5797 spa->spa_state = new_state;
5798 spa->spa_final_txg = spa_last_synced_txg(spa) +
5800 vdev_config_dirty(spa->spa_root_vdev);
5801 spa_config_exit(spa, SCL_ALL, FTAG);
5805 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
5807 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
5809 spa_deactivate(spa);
5812 if (oldconfig && spa->spa_config)
5813 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
5815 if (new_state != POOL_STATE_UNINITIALIZED) {
5817 spa_write_cachefile(spa, B_TRUE, B_TRUE);
5820 mutex_exit(&spa_namespace_lock);
5826 * Destroy a storage pool.
5829 spa_destroy(char *pool)
5831 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
5836 * Export a storage pool.
5839 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
5840 boolean_t hardforce)
5842 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
5847 * Similar to spa_export(), this unloads the spa_t without actually removing it
5848 * from the namespace in any way.
5851 spa_reset(char *pool)
5853 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
5858 * ==========================================================================
5859 * Device manipulation
5860 * ==========================================================================
5864 * Add a device to a storage pool.
5867 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
5871 vdev_t *rvd = spa->spa_root_vdev;
5873 nvlist_t **spares, **l2cache;
5874 uint_t nspares, nl2cache;
5876 ASSERT(spa_writeable(spa));
5878 txg = spa_vdev_enter(spa);
5880 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
5881 VDEV_ALLOC_ADD)) != 0)
5882 return (spa_vdev_exit(spa, NULL, txg, error));
5884 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
5886 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
5890 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
5894 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
5895 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5897 if (vd->vdev_children != 0 &&
5898 (error = vdev_create(vd, txg, B_FALSE)) != 0)
5899 return (spa_vdev_exit(spa, vd, txg, error));
5902 * We must validate the spares and l2cache devices after checking the
5903 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
5905 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
5906 return (spa_vdev_exit(spa, vd, txg, error));
5909 * If we are in the middle of a device removal, we can only add
5910 * devices which match the existing devices in the pool.
5911 * If we are in the middle of a removal, or have some indirect
5912 * vdevs, we can not add raidz toplevels.
5914 if (spa->spa_vdev_removal != NULL ||
5915 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
5916 for (int c = 0; c < vd->vdev_children; c++) {
5917 tvd = vd->vdev_child[c];
5918 if (spa->spa_vdev_removal != NULL &&
5919 tvd->vdev_ashift != spa->spa_max_ashift) {
5920 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5922 /* Fail if top level vdev is raidz */
5923 if (tvd->vdev_ops == &vdev_raidz_ops) {
5924 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5927 * Need the top level mirror to be
5928 * a mirror of leaf vdevs only
5930 if (tvd->vdev_ops == &vdev_mirror_ops) {
5931 for (uint64_t cid = 0;
5932 cid < tvd->vdev_children; cid++) {
5933 vdev_t *cvd = tvd->vdev_child[cid];
5934 if (!cvd->vdev_ops->vdev_op_leaf) {
5935 return (spa_vdev_exit(spa, vd,
5943 for (int c = 0; c < vd->vdev_children; c++) {
5946 * Set the vdev id to the first hole, if one exists.
5948 for (id = 0; id < rvd->vdev_children; id++) {
5949 if (rvd->vdev_child[id]->vdev_ishole) {
5950 vdev_free(rvd->vdev_child[id]);
5954 tvd = vd->vdev_child[c];
5955 vdev_remove_child(vd, tvd);
5957 vdev_add_child(rvd, tvd);
5958 vdev_config_dirty(tvd);
5962 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
5963 ZPOOL_CONFIG_SPARES);
5964 spa_load_spares(spa);
5965 spa->spa_spares.sav_sync = B_TRUE;
5968 if (nl2cache != 0) {
5969 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
5970 ZPOOL_CONFIG_L2CACHE);
5971 spa_load_l2cache(spa);
5972 spa->spa_l2cache.sav_sync = B_TRUE;
5976 * We have to be careful when adding new vdevs to an existing pool.
5977 * If other threads start allocating from these vdevs before we
5978 * sync the config cache, and we lose power, then upon reboot we may
5979 * fail to open the pool because there are DVAs that the config cache
5980 * can't translate. Therefore, we first add the vdevs without
5981 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
5982 * and then let spa_config_update() initialize the new metaslabs.
5984 * spa_load() checks for added-but-not-initialized vdevs, so that
5985 * if we lose power at any point in this sequence, the remaining
5986 * steps will be completed the next time we load the pool.
5988 (void) spa_vdev_exit(spa, vd, txg, 0);
5990 mutex_enter(&spa_namespace_lock);
5991 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5992 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
5993 mutex_exit(&spa_namespace_lock);
5999 * Attach a device to a mirror. The arguments are the path to any device
6000 * in the mirror, and the nvroot for the new device. If the path specifies
6001 * a device that is not mirrored, we automatically insert the mirror vdev.
6003 * If 'replacing' is specified, the new device is intended to replace the
6004 * existing device; in this case the two devices are made into their own
6005 * mirror using the 'replacing' vdev, which is functionally identical to
6006 * the mirror vdev (it actually reuses all the same ops) but has a few
6007 * extra rules: you can't attach to it after it's been created, and upon
6008 * completion of resilvering, the first disk (the one being replaced)
6009 * is automatically detached.
6012 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
6014 uint64_t txg, dtl_max_txg;
6015 vdev_t *rvd = spa->spa_root_vdev;
6016 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
6018 char *oldvdpath, *newvdpath;
6022 ASSERT(spa_writeable(spa));
6024 txg = spa_vdev_enter(spa);
6026 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
6028 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6029 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6030 error = (spa_has_checkpoint(spa)) ?
6031 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6032 return (spa_vdev_exit(spa, NULL, txg, error));
6035 if (spa->spa_vdev_removal != NULL)
6036 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6039 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6041 if (!oldvd->vdev_ops->vdev_op_leaf)
6042 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6044 pvd = oldvd->vdev_parent;
6046 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
6047 VDEV_ALLOC_ATTACH)) != 0)
6048 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6050 if (newrootvd->vdev_children != 1)
6051 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6053 newvd = newrootvd->vdev_child[0];
6055 if (!newvd->vdev_ops->vdev_op_leaf)
6056 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6058 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
6059 return (spa_vdev_exit(spa, newrootvd, txg, error));
6062 * Spares can't replace logs
6064 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
6065 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6069 * For attach, the only allowable parent is a mirror or the root
6072 if (pvd->vdev_ops != &vdev_mirror_ops &&
6073 pvd->vdev_ops != &vdev_root_ops)
6074 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6076 pvops = &vdev_mirror_ops;
6079 * Active hot spares can only be replaced by inactive hot
6082 if (pvd->vdev_ops == &vdev_spare_ops &&
6083 oldvd->vdev_isspare &&
6084 !spa_has_spare(spa, newvd->vdev_guid))
6085 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6088 * If the source is a hot spare, and the parent isn't already a
6089 * spare, then we want to create a new hot spare. Otherwise, we
6090 * want to create a replacing vdev. The user is not allowed to
6091 * attach to a spared vdev child unless the 'isspare' state is
6092 * the same (spare replaces spare, non-spare replaces
6095 if (pvd->vdev_ops == &vdev_replacing_ops &&
6096 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6097 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6098 } else if (pvd->vdev_ops == &vdev_spare_ops &&
6099 newvd->vdev_isspare != oldvd->vdev_isspare) {
6100 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6103 if (newvd->vdev_isspare)
6104 pvops = &vdev_spare_ops;
6106 pvops = &vdev_replacing_ops;
6110 * Make sure the new device is big enough.
6112 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6113 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6116 * The new device cannot have a higher alignment requirement
6117 * than the top-level vdev.
6119 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6120 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6123 * If this is an in-place replacement, update oldvd's path and devid
6124 * to make it distinguishable from newvd, and unopenable from now on.
6126 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6127 spa_strfree(oldvd->vdev_path);
6128 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6130 (void) sprintf(oldvd->vdev_path, "%s/%s",
6131 newvd->vdev_path, "old");
6132 if (oldvd->vdev_devid != NULL) {
6133 spa_strfree(oldvd->vdev_devid);
6134 oldvd->vdev_devid = NULL;
6138 /* mark the device being resilvered */
6139 newvd->vdev_resilver_txg = txg;
6142 * If the parent is not a mirror, or if we're replacing, insert the new
6143 * mirror/replacing/spare vdev above oldvd.
6145 if (pvd->vdev_ops != pvops)
6146 pvd = vdev_add_parent(oldvd, pvops);
6148 ASSERT(pvd->vdev_top->vdev_parent == rvd);
6149 ASSERT(pvd->vdev_ops == pvops);
6150 ASSERT(oldvd->vdev_parent == pvd);
6153 * Extract the new device from its root and add it to pvd.
6155 vdev_remove_child(newrootvd, newvd);
6156 newvd->vdev_id = pvd->vdev_children;
6157 newvd->vdev_crtxg = oldvd->vdev_crtxg;
6158 vdev_add_child(pvd, newvd);
6160 tvd = newvd->vdev_top;
6161 ASSERT(pvd->vdev_top == tvd);
6162 ASSERT(tvd->vdev_parent == rvd);
6164 vdev_config_dirty(tvd);
6167 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6168 * for any dmu_sync-ed blocks. It will propagate upward when
6169 * spa_vdev_exit() calls vdev_dtl_reassess().
6171 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6173 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6174 dtl_max_txg - TXG_INITIAL);
6176 if (newvd->vdev_isspare) {
6177 spa_spare_activate(newvd);
6178 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6181 oldvdpath = spa_strdup(oldvd->vdev_path);
6182 newvdpath = spa_strdup(newvd->vdev_path);
6183 newvd_isspare = newvd->vdev_isspare;
6186 * Mark newvd's DTL dirty in this txg.
6188 vdev_dirty(tvd, VDD_DTL, newvd, txg);
6191 * Schedule the resilver to restart in the future. We do this to
6192 * ensure that dmu_sync-ed blocks have been stitched into the
6193 * respective datasets.
6195 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
6197 if (spa->spa_bootfs)
6198 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6200 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6205 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6207 spa_history_log_internal(spa, "vdev attach", NULL,
6208 "%s vdev=%s %s vdev=%s",
6209 replacing && newvd_isspare ? "spare in" :
6210 replacing ? "replace" : "attach", newvdpath,
6211 replacing ? "for" : "to", oldvdpath);
6213 spa_strfree(oldvdpath);
6214 spa_strfree(newvdpath);
6220 * Detach a device from a mirror or replacing vdev.
6222 * If 'replace_done' is specified, only detach if the parent
6223 * is a replacing vdev.
6226 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6230 vdev_t *rvd = spa->spa_root_vdev;
6231 vdev_t *vd, *pvd, *cvd, *tvd;
6232 boolean_t unspare = B_FALSE;
6233 uint64_t unspare_guid = 0;
6236 ASSERT(spa_writeable(spa));
6238 txg = spa_vdev_enter(spa);
6240 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6243 * Besides being called directly from the userland through the
6244 * ioctl interface, spa_vdev_detach() can be potentially called
6245 * at the end of spa_vdev_resilver_done().
6247 * In the regular case, when we have a checkpoint this shouldn't
6248 * happen as we never empty the DTLs of a vdev during the scrub
6249 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6250 * should never get here when we have a checkpoint.
6252 * That said, even in a case when we checkpoint the pool exactly
6253 * as spa_vdev_resilver_done() calls this function everything
6254 * should be fine as the resilver will return right away.
6256 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6257 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6258 error = (spa_has_checkpoint(spa)) ?
6259 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6260 return (spa_vdev_exit(spa, NULL, txg, error));
6264 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6266 if (!vd->vdev_ops->vdev_op_leaf)
6267 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6269 pvd = vd->vdev_parent;
6272 * If the parent/child relationship is not as expected, don't do it.
6273 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6274 * vdev that's replacing B with C. The user's intent in replacing
6275 * is to go from M(A,B) to M(A,C). If the user decides to cancel
6276 * the replace by detaching C, the expected behavior is to end up
6277 * M(A,B). But suppose that right after deciding to detach C,
6278 * the replacement of B completes. We would have M(A,C), and then
6279 * ask to detach C, which would leave us with just A -- not what
6280 * the user wanted. To prevent this, we make sure that the
6281 * parent/child relationship hasn't changed -- in this example,
6282 * that C's parent is still the replacing vdev R.
6284 if (pvd->vdev_guid != pguid && pguid != 0)
6285 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6288 * Only 'replacing' or 'spare' vdevs can be replaced.
6290 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6291 pvd->vdev_ops != &vdev_spare_ops)
6292 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6294 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6295 spa_version(spa) >= SPA_VERSION_SPARES);
6298 * Only mirror, replacing, and spare vdevs support detach.
6300 if (pvd->vdev_ops != &vdev_replacing_ops &&
6301 pvd->vdev_ops != &vdev_mirror_ops &&
6302 pvd->vdev_ops != &vdev_spare_ops)
6303 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6306 * If this device has the only valid copy of some data,
6307 * we cannot safely detach it.
6309 if (vdev_dtl_required(vd))
6310 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6312 ASSERT(pvd->vdev_children >= 2);
6315 * If we are detaching the second disk from a replacing vdev, then
6316 * check to see if we changed the original vdev's path to have "/old"
6317 * at the end in spa_vdev_attach(). If so, undo that change now.
6319 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
6320 vd->vdev_path != NULL) {
6321 size_t len = strlen(vd->vdev_path);
6323 for (int c = 0; c < pvd->vdev_children; c++) {
6324 cvd = pvd->vdev_child[c];
6326 if (cvd == vd || cvd->vdev_path == NULL)
6329 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
6330 strcmp(cvd->vdev_path + len, "/old") == 0) {
6331 spa_strfree(cvd->vdev_path);
6332 cvd->vdev_path = spa_strdup(vd->vdev_path);
6339 * If we are detaching the original disk from a spare, then it implies
6340 * that the spare should become a real disk, and be removed from the
6341 * active spare list for the pool.
6343 if (pvd->vdev_ops == &vdev_spare_ops &&
6345 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
6349 * Erase the disk labels so the disk can be used for other things.
6350 * This must be done after all other error cases are handled,
6351 * but before we disembowel vd (so we can still do I/O to it).
6352 * But if we can't do it, don't treat the error as fatal --
6353 * it may be that the unwritability of the disk is the reason
6354 * it's being detached!
6356 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
6359 * Remove vd from its parent and compact the parent's children.
6361 vdev_remove_child(pvd, vd);
6362 vdev_compact_children(pvd);
6365 * Remember one of the remaining children so we can get tvd below.
6367 cvd = pvd->vdev_child[pvd->vdev_children - 1];
6370 * If we need to remove the remaining child from the list of hot spares,
6371 * do it now, marking the vdev as no longer a spare in the process.
6372 * We must do this before vdev_remove_parent(), because that can
6373 * change the GUID if it creates a new toplevel GUID. For a similar
6374 * reason, we must remove the spare now, in the same txg as the detach;
6375 * otherwise someone could attach a new sibling, change the GUID, and
6376 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
6379 ASSERT(cvd->vdev_isspare);
6380 spa_spare_remove(cvd);
6381 unspare_guid = cvd->vdev_guid;
6382 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
6383 cvd->vdev_unspare = B_TRUE;
6387 * If the parent mirror/replacing vdev only has one child,
6388 * the parent is no longer needed. Remove it from the tree.
6390 if (pvd->vdev_children == 1) {
6391 if (pvd->vdev_ops == &vdev_spare_ops)
6392 cvd->vdev_unspare = B_FALSE;
6393 vdev_remove_parent(cvd);
6398 * We don't set tvd until now because the parent we just removed
6399 * may have been the previous top-level vdev.
6401 tvd = cvd->vdev_top;
6402 ASSERT(tvd->vdev_parent == rvd);
6405 * Reevaluate the parent vdev state.
6407 vdev_propagate_state(cvd);
6410 * If the 'autoexpand' property is set on the pool then automatically
6411 * try to expand the size of the pool. For example if the device we
6412 * just detached was smaller than the others, it may be possible to
6413 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
6414 * first so that we can obtain the updated sizes of the leaf vdevs.
6416 if (spa->spa_autoexpand) {
6418 vdev_expand(tvd, txg);
6421 vdev_config_dirty(tvd);
6424 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
6425 * vd->vdev_detached is set and free vd's DTL object in syncing context.
6426 * But first make sure we're not on any *other* txg's DTL list, to
6427 * prevent vd from being accessed after it's freed.
6429 vdpath = spa_strdup(vd->vdev_path);
6430 for (int t = 0; t < TXG_SIZE; t++)
6431 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
6432 vd->vdev_detached = B_TRUE;
6433 vdev_dirty(tvd, VDD_DTL, vd, txg);
6435 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
6437 /* hang on to the spa before we release the lock */
6438 spa_open_ref(spa, FTAG);
6440 error = spa_vdev_exit(spa, vd, txg, 0);
6442 spa_history_log_internal(spa, "detach", NULL,
6444 spa_strfree(vdpath);
6447 * If this was the removal of the original device in a hot spare vdev,
6448 * then we want to go through and remove the device from the hot spare
6449 * list of every other pool.
6452 spa_t *altspa = NULL;
6454 mutex_enter(&spa_namespace_lock);
6455 while ((altspa = spa_next(altspa)) != NULL) {
6456 if (altspa->spa_state != POOL_STATE_ACTIVE ||
6460 spa_open_ref(altspa, FTAG);
6461 mutex_exit(&spa_namespace_lock);
6462 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
6463 mutex_enter(&spa_namespace_lock);
6464 spa_close(altspa, FTAG);
6466 mutex_exit(&spa_namespace_lock);
6468 /* search the rest of the vdevs for spares to remove */
6469 spa_vdev_resilver_done(spa);
6472 /* all done with the spa; OK to release */
6473 mutex_enter(&spa_namespace_lock);
6474 spa_close(spa, FTAG);
6475 mutex_exit(&spa_namespace_lock);
6481 spa_vdev_initialize(spa_t *spa, uint64_t guid, uint64_t cmd_type)
6484 * We hold the namespace lock through the whole function
6485 * to prevent any changes to the pool while we're starting or
6486 * stopping initialization. The config and state locks are held so that
6487 * we can properly assess the vdev state before we commit to
6488 * the initializing operation.
6490 mutex_enter(&spa_namespace_lock);
6491 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6493 /* Look up vdev and ensure it's a leaf. */
6494 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6495 if (vd == NULL || vd->vdev_detached) {
6496 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6497 mutex_exit(&spa_namespace_lock);
6498 return (SET_ERROR(ENODEV));
6499 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6500 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6501 mutex_exit(&spa_namespace_lock);
6502 return (SET_ERROR(EINVAL));
6503 } else if (!vdev_writeable(vd)) {
6504 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6505 mutex_exit(&spa_namespace_lock);
6506 return (SET_ERROR(EROFS));
6508 mutex_enter(&vd->vdev_initialize_lock);
6509 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6512 * When we activate an initialize action we check to see
6513 * if the vdev_initialize_thread is NULL. We do this instead
6514 * of using the vdev_initialize_state since there might be
6515 * a previous initialization process which has completed but
6516 * the thread is not exited.
6518 if (cmd_type == POOL_INITIALIZE_DO &&
6519 (vd->vdev_initialize_thread != NULL ||
6520 vd->vdev_top->vdev_removing)) {
6521 mutex_exit(&vd->vdev_initialize_lock);
6522 mutex_exit(&spa_namespace_lock);
6523 return (SET_ERROR(EBUSY));
6524 } else if (cmd_type == POOL_INITIALIZE_CANCEL &&
6525 (vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE &&
6526 vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED)) {
6527 mutex_exit(&vd->vdev_initialize_lock);
6528 mutex_exit(&spa_namespace_lock);
6529 return (SET_ERROR(ESRCH));
6530 } else if (cmd_type == POOL_INITIALIZE_SUSPEND &&
6531 vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE) {
6532 mutex_exit(&vd->vdev_initialize_lock);
6533 mutex_exit(&spa_namespace_lock);
6534 return (SET_ERROR(ESRCH));
6538 case POOL_INITIALIZE_DO:
6539 vdev_initialize(vd);
6541 case POOL_INITIALIZE_CANCEL:
6542 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED);
6544 case POOL_INITIALIZE_SUSPEND:
6545 vdev_initialize_stop(vd, VDEV_INITIALIZE_SUSPENDED);
6548 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6550 mutex_exit(&vd->vdev_initialize_lock);
6552 /* Sync out the initializing state */
6553 txg_wait_synced(spa->spa_dsl_pool, 0);
6554 mutex_exit(&spa_namespace_lock);
6561 * Split a set of devices from their mirrors, and create a new pool from them.
6564 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6565 nvlist_t *props, boolean_t exp)
6568 uint64_t txg, *glist;
6570 uint_t c, children, lastlog;
6571 nvlist_t **child, *nvl, *tmp;
6573 char *altroot = NULL;
6574 vdev_t *rvd, **vml = NULL; /* vdev modify list */
6575 boolean_t activate_slog;
6577 ASSERT(spa_writeable(spa));
6579 txg = spa_vdev_enter(spa);
6581 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6582 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6583 error = (spa_has_checkpoint(spa)) ?
6584 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6585 return (spa_vdev_exit(spa, NULL, txg, error));
6588 /* clear the log and flush everything up to now */
6589 activate_slog = spa_passivate_log(spa);
6590 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6591 error = spa_reset_logs(spa);
6592 txg = spa_vdev_config_enter(spa);
6595 spa_activate_log(spa);
6598 return (spa_vdev_exit(spa, NULL, txg, error));
6600 /* check new spa name before going any further */
6601 if (spa_lookup(newname) != NULL)
6602 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
6605 * scan through all the children to ensure they're all mirrors
6607 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
6608 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
6610 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6612 /* first, check to ensure we've got the right child count */
6613 rvd = spa->spa_root_vdev;
6615 for (c = 0; c < rvd->vdev_children; c++) {
6616 vdev_t *vd = rvd->vdev_child[c];
6618 /* don't count the holes & logs as children */
6619 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
6627 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
6628 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6630 /* next, ensure no spare or cache devices are part of the split */
6631 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
6632 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
6633 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6635 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
6636 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
6638 /* then, loop over each vdev and validate it */
6639 for (c = 0; c < children; c++) {
6640 uint64_t is_hole = 0;
6642 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
6646 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
6647 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
6650 error = SET_ERROR(EINVAL);
6655 /* which disk is going to be split? */
6656 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
6658 error = SET_ERROR(EINVAL);
6662 /* look it up in the spa */
6663 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
6664 if (vml[c] == NULL) {
6665 error = SET_ERROR(ENODEV);
6669 /* make sure there's nothing stopping the split */
6670 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
6671 vml[c]->vdev_islog ||
6672 !vdev_is_concrete(vml[c]) ||
6673 vml[c]->vdev_isspare ||
6674 vml[c]->vdev_isl2cache ||
6675 !vdev_writeable(vml[c]) ||
6676 vml[c]->vdev_children != 0 ||
6677 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
6678 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
6679 error = SET_ERROR(EINVAL);
6683 if (vdev_dtl_required(vml[c])) {
6684 error = SET_ERROR(EBUSY);
6688 /* we need certain info from the top level */
6689 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
6690 vml[c]->vdev_top->vdev_ms_array) == 0);
6691 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
6692 vml[c]->vdev_top->vdev_ms_shift) == 0);
6693 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
6694 vml[c]->vdev_top->vdev_asize) == 0);
6695 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
6696 vml[c]->vdev_top->vdev_ashift) == 0);
6698 /* transfer per-vdev ZAPs */
6699 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
6700 VERIFY0(nvlist_add_uint64(child[c],
6701 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
6703 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
6704 VERIFY0(nvlist_add_uint64(child[c],
6705 ZPOOL_CONFIG_VDEV_TOP_ZAP,
6706 vml[c]->vdev_parent->vdev_top_zap));
6710 kmem_free(vml, children * sizeof (vdev_t *));
6711 kmem_free(glist, children * sizeof (uint64_t));
6712 return (spa_vdev_exit(spa, NULL, txg, error));
6715 /* stop writers from using the disks */
6716 for (c = 0; c < children; c++) {
6718 vml[c]->vdev_offline = B_TRUE;
6720 vdev_reopen(spa->spa_root_vdev);
6723 * Temporarily record the splitting vdevs in the spa config. This
6724 * will disappear once the config is regenerated.
6726 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6727 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
6728 glist, children) == 0);
6729 kmem_free(glist, children * sizeof (uint64_t));
6731 mutex_enter(&spa->spa_props_lock);
6732 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
6734 mutex_exit(&spa->spa_props_lock);
6735 spa->spa_config_splitting = nvl;
6736 vdev_config_dirty(spa->spa_root_vdev);
6738 /* configure and create the new pool */
6739 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
6740 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6741 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
6742 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6743 spa_version(spa)) == 0);
6744 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
6745 spa->spa_config_txg) == 0);
6746 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
6747 spa_generate_guid(NULL)) == 0);
6748 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
6749 (void) nvlist_lookup_string(props,
6750 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
6752 /* add the new pool to the namespace */
6753 newspa = spa_add(newname, config, altroot);
6754 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
6755 newspa->spa_config_txg = spa->spa_config_txg;
6756 spa_set_log_state(newspa, SPA_LOG_CLEAR);
6758 /* release the spa config lock, retaining the namespace lock */
6759 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6761 if (zio_injection_enabled)
6762 zio_handle_panic_injection(spa, FTAG, 1);
6764 spa_activate(newspa, spa_mode_global);
6765 spa_async_suspend(newspa);
6767 for (c = 0; c < children; c++) {
6768 if (vml[c] != NULL) {
6770 * Temporarily stop the initializing activity. We set
6771 * the state to ACTIVE so that we know to resume
6772 * the initializing once the split has completed.
6774 mutex_enter(&vml[c]->vdev_initialize_lock);
6775 vdev_initialize_stop(vml[c], VDEV_INITIALIZE_ACTIVE);
6776 mutex_exit(&vml[c]->vdev_initialize_lock);
6781 /* mark that we are creating new spa by splitting */
6782 newspa->spa_splitting_newspa = B_TRUE;
6784 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
6786 /* create the new pool from the disks of the original pool */
6787 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
6789 newspa->spa_splitting_newspa = B_FALSE;
6794 /* if that worked, generate a real config for the new pool */
6795 if (newspa->spa_root_vdev != NULL) {
6796 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
6797 NV_UNIQUE_NAME, KM_SLEEP) == 0);
6798 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
6799 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
6800 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
6805 if (props != NULL) {
6806 spa_configfile_set(newspa, props, B_FALSE);
6807 error = spa_prop_set(newspa, props);
6812 /* flush everything */
6813 txg = spa_vdev_config_enter(newspa);
6814 vdev_config_dirty(newspa->spa_root_vdev);
6815 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
6817 if (zio_injection_enabled)
6818 zio_handle_panic_injection(spa, FTAG, 2);
6820 spa_async_resume(newspa);
6822 /* finally, update the original pool's config */
6823 txg = spa_vdev_config_enter(spa);
6824 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
6825 error = dmu_tx_assign(tx, TXG_WAIT);
6828 for (c = 0; c < children; c++) {
6829 if (vml[c] != NULL) {
6832 spa_history_log_internal(spa, "detach", tx,
6833 "vdev=%s", vml[c]->vdev_path);
6838 spa->spa_avz_action = AVZ_ACTION_REBUILD;
6839 vdev_config_dirty(spa->spa_root_vdev);
6840 spa->spa_config_splitting = NULL;
6844 (void) spa_vdev_exit(spa, NULL, txg, 0);
6846 if (zio_injection_enabled)
6847 zio_handle_panic_injection(spa, FTAG, 3);
6849 /* split is complete; log a history record */
6850 spa_history_log_internal(newspa, "split", NULL,
6851 "from pool %s", spa_name(spa));
6853 kmem_free(vml, children * sizeof (vdev_t *));
6855 /* if we're not going to mount the filesystems in userland, export */
6857 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
6864 spa_deactivate(newspa);
6867 txg = spa_vdev_config_enter(spa);
6869 /* re-online all offlined disks */
6870 for (c = 0; c < children; c++) {
6872 vml[c]->vdev_offline = B_FALSE;
6875 /* restart initializing disks as necessary */
6876 spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
6878 vdev_reopen(spa->spa_root_vdev);
6880 nvlist_free(spa->spa_config_splitting);
6881 spa->spa_config_splitting = NULL;
6882 (void) spa_vdev_exit(spa, NULL, txg, error);
6884 kmem_free(vml, children * sizeof (vdev_t *));
6889 * Find any device that's done replacing, or a vdev marked 'unspare' that's
6890 * currently spared, so we can detach it.
6893 spa_vdev_resilver_done_hunt(vdev_t *vd)
6895 vdev_t *newvd, *oldvd;
6897 for (int c = 0; c < vd->vdev_children; c++) {
6898 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
6904 * Check for a completed replacement. We always consider the first
6905 * vdev in the list to be the oldest vdev, and the last one to be
6906 * the newest (see spa_vdev_attach() for how that works). In
6907 * the case where the newest vdev is faulted, we will not automatically
6908 * remove it after a resilver completes. This is OK as it will require
6909 * user intervention to determine which disk the admin wishes to keep.
6911 if (vd->vdev_ops == &vdev_replacing_ops) {
6912 ASSERT(vd->vdev_children > 1);
6914 newvd = vd->vdev_child[vd->vdev_children - 1];
6915 oldvd = vd->vdev_child[0];
6917 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
6918 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6919 !vdev_dtl_required(oldvd))
6924 * Check for a completed resilver with the 'unspare' flag set.
6926 if (vd->vdev_ops == &vdev_spare_ops) {
6927 vdev_t *first = vd->vdev_child[0];
6928 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
6930 if (last->vdev_unspare) {
6933 } else if (first->vdev_unspare) {
6940 if (oldvd != NULL &&
6941 vdev_dtl_empty(newvd, DTL_MISSING) &&
6942 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6943 !vdev_dtl_required(oldvd))
6947 * If there are more than two spares attached to a disk,
6948 * and those spares are not required, then we want to
6949 * attempt to free them up now so that they can be used
6950 * by other pools. Once we're back down to a single
6951 * disk+spare, we stop removing them.
6953 if (vd->vdev_children > 2) {
6954 newvd = vd->vdev_child[1];
6956 if (newvd->vdev_isspare && last->vdev_isspare &&
6957 vdev_dtl_empty(last, DTL_MISSING) &&
6958 vdev_dtl_empty(last, DTL_OUTAGE) &&
6959 !vdev_dtl_required(newvd))
6968 spa_vdev_resilver_done(spa_t *spa)
6970 vdev_t *vd, *pvd, *ppvd;
6971 uint64_t guid, sguid, pguid, ppguid;
6973 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6975 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
6976 pvd = vd->vdev_parent;
6977 ppvd = pvd->vdev_parent;
6978 guid = vd->vdev_guid;
6979 pguid = pvd->vdev_guid;
6980 ppguid = ppvd->vdev_guid;
6983 * If we have just finished replacing a hot spared device, then
6984 * we need to detach the parent's first child (the original hot
6987 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
6988 ppvd->vdev_children == 2) {
6989 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
6990 sguid = ppvd->vdev_child[1]->vdev_guid;
6992 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
6994 spa_config_exit(spa, SCL_ALL, FTAG);
6995 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
6997 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
6999 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7002 spa_config_exit(spa, SCL_ALL, FTAG);
7006 * Update the stored path or FRU for this vdev.
7009 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
7013 boolean_t sync = B_FALSE;
7015 ASSERT(spa_writeable(spa));
7017 spa_vdev_state_enter(spa, SCL_ALL);
7019 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
7020 return (spa_vdev_state_exit(spa, NULL, ENOENT));
7022 if (!vd->vdev_ops->vdev_op_leaf)
7023 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
7026 if (strcmp(value, vd->vdev_path) != 0) {
7027 spa_strfree(vd->vdev_path);
7028 vd->vdev_path = spa_strdup(value);
7032 if (vd->vdev_fru == NULL) {
7033 vd->vdev_fru = spa_strdup(value);
7035 } else if (strcmp(value, vd->vdev_fru) != 0) {
7036 spa_strfree(vd->vdev_fru);
7037 vd->vdev_fru = spa_strdup(value);
7042 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
7046 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
7048 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
7052 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
7054 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
7058 * ==========================================================================
7060 * ==========================================================================
7063 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
7065 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7067 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7068 return (SET_ERROR(EBUSY));
7070 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
7074 spa_scan_stop(spa_t *spa)
7076 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7077 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7078 return (SET_ERROR(EBUSY));
7079 return (dsl_scan_cancel(spa->spa_dsl_pool));
7083 spa_scan(spa_t *spa, pool_scan_func_t func)
7085 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7087 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
7088 return (SET_ERROR(ENOTSUP));
7091 * If a resilver was requested, but there is no DTL on a
7092 * writeable leaf device, we have nothing to do.
7094 if (func == POOL_SCAN_RESILVER &&
7095 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
7096 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
7100 return (dsl_scan(spa->spa_dsl_pool, func));
7104 * ==========================================================================
7105 * SPA async task processing
7106 * ==========================================================================
7110 spa_async_remove(spa_t *spa, vdev_t *vd)
7112 if (vd->vdev_remove_wanted) {
7113 vd->vdev_remove_wanted = B_FALSE;
7114 vd->vdev_delayed_close = B_FALSE;
7115 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
7118 * We want to clear the stats, but we don't want to do a full
7119 * vdev_clear() as that will cause us to throw away
7120 * degraded/faulted state as well as attempt to reopen the
7121 * device, all of which is a waste.
7123 vd->vdev_stat.vs_read_errors = 0;
7124 vd->vdev_stat.vs_write_errors = 0;
7125 vd->vdev_stat.vs_checksum_errors = 0;
7127 vdev_state_dirty(vd->vdev_top);
7128 /* Tell userspace that the vdev is gone. */
7129 zfs_post_remove(spa, vd);
7132 for (int c = 0; c < vd->vdev_children; c++)
7133 spa_async_remove(spa, vd->vdev_child[c]);
7137 spa_async_probe(spa_t *spa, vdev_t *vd)
7139 if (vd->vdev_probe_wanted) {
7140 vd->vdev_probe_wanted = B_FALSE;
7141 vdev_reopen(vd); /* vdev_open() does the actual probe */
7144 for (int c = 0; c < vd->vdev_children; c++)
7145 spa_async_probe(spa, vd->vdev_child[c]);
7149 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
7155 if (!spa->spa_autoexpand)
7158 for (int c = 0; c < vd->vdev_children; c++) {
7159 vdev_t *cvd = vd->vdev_child[c];
7160 spa_async_autoexpand(spa, cvd);
7163 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
7166 physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
7167 (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
7169 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7170 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
7172 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
7173 ESC_ZFS_VDEV_AUTOEXPAND, attr, &eid, DDI_SLEEP);
7176 kmem_free(physpath, MAXPATHLEN);
7180 spa_async_thread(void *arg)
7182 spa_t *spa = (spa_t *)arg;
7185 ASSERT(spa->spa_sync_on);
7187 mutex_enter(&spa->spa_async_lock);
7188 tasks = spa->spa_async_tasks;
7189 spa->spa_async_tasks &= SPA_ASYNC_REMOVE;
7190 mutex_exit(&spa->spa_async_lock);
7193 * See if the config needs to be updated.
7195 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
7196 uint64_t old_space, new_space;
7198 mutex_enter(&spa_namespace_lock);
7199 old_space = metaslab_class_get_space(spa_normal_class(spa));
7200 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
7201 new_space = metaslab_class_get_space(spa_normal_class(spa));
7202 mutex_exit(&spa_namespace_lock);
7205 * If the pool grew as a result of the config update,
7206 * then log an internal history event.
7208 if (new_space != old_space) {
7209 spa_history_log_internal(spa, "vdev online", NULL,
7210 "pool '%s' size: %llu(+%llu)",
7211 spa_name(spa), new_space, new_space - old_space);
7215 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
7216 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7217 spa_async_autoexpand(spa, spa->spa_root_vdev);
7218 spa_config_exit(spa, SCL_CONFIG, FTAG);
7222 * See if any devices need to be probed.
7224 if (tasks & SPA_ASYNC_PROBE) {
7225 spa_vdev_state_enter(spa, SCL_NONE);
7226 spa_async_probe(spa, spa->spa_root_vdev);
7227 (void) spa_vdev_state_exit(spa, NULL, 0);
7231 * If any devices are done replacing, detach them.
7233 if (tasks & SPA_ASYNC_RESILVER_DONE)
7234 spa_vdev_resilver_done(spa);
7237 * Kick off a resilver.
7239 if (tasks & SPA_ASYNC_RESILVER)
7240 dsl_resilver_restart(spa->spa_dsl_pool, 0);
7242 if (tasks & SPA_ASYNC_INITIALIZE_RESTART) {
7243 mutex_enter(&spa_namespace_lock);
7244 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7245 vdev_initialize_restart(spa->spa_root_vdev);
7246 spa_config_exit(spa, SCL_CONFIG, FTAG);
7247 mutex_exit(&spa_namespace_lock);
7251 * Let the world know that we're done.
7253 mutex_enter(&spa->spa_async_lock);
7254 spa->spa_async_thread = NULL;
7255 cv_broadcast(&spa->spa_async_cv);
7256 mutex_exit(&spa->spa_async_lock);
7261 spa_async_thread_vd(void *arg)
7266 mutex_enter(&spa->spa_async_lock);
7267 tasks = spa->spa_async_tasks;
7269 spa->spa_async_tasks &= ~SPA_ASYNC_REMOVE;
7270 mutex_exit(&spa->spa_async_lock);
7273 * See if any devices need to be marked REMOVED.
7275 if (tasks & SPA_ASYNC_REMOVE) {
7276 spa_vdev_state_enter(spa, SCL_NONE);
7277 spa_async_remove(spa, spa->spa_root_vdev);
7278 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
7279 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
7280 for (int i = 0; i < spa->spa_spares.sav_count; i++)
7281 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
7282 (void) spa_vdev_state_exit(spa, NULL, 0);
7286 * Let the world know that we're done.
7288 mutex_enter(&spa->spa_async_lock);
7289 tasks = spa->spa_async_tasks;
7290 if ((tasks & SPA_ASYNC_REMOVE) != 0)
7292 spa->spa_async_thread_vd = NULL;
7293 cv_broadcast(&spa->spa_async_cv);
7294 mutex_exit(&spa->spa_async_lock);
7299 spa_async_suspend(spa_t *spa)
7301 mutex_enter(&spa->spa_async_lock);
7302 spa->spa_async_suspended++;
7303 while (spa->spa_async_thread != NULL ||
7304 spa->spa_async_thread_vd != NULL)
7305 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
7306 mutex_exit(&spa->spa_async_lock);
7308 spa_vdev_remove_suspend(spa);
7310 zthr_t *condense_thread = spa->spa_condense_zthr;
7311 if (condense_thread != NULL && zthr_isrunning(condense_thread))
7312 VERIFY0(zthr_cancel(condense_thread));
7314 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7315 if (discard_thread != NULL && zthr_isrunning(discard_thread))
7316 VERIFY0(zthr_cancel(discard_thread));
7320 spa_async_resume(spa_t *spa)
7322 mutex_enter(&spa->spa_async_lock);
7323 ASSERT(spa->spa_async_suspended != 0);
7324 spa->spa_async_suspended--;
7325 mutex_exit(&spa->spa_async_lock);
7326 spa_restart_removal(spa);
7328 zthr_t *condense_thread = spa->spa_condense_zthr;
7329 if (condense_thread != NULL && !zthr_isrunning(condense_thread))
7330 zthr_resume(condense_thread);
7332 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7333 if (discard_thread != NULL && !zthr_isrunning(discard_thread))
7334 zthr_resume(discard_thread);
7338 spa_async_tasks_pending(spa_t *spa)
7340 uint_t non_config_tasks;
7342 boolean_t config_task_suspended;
7344 non_config_tasks = spa->spa_async_tasks & ~(SPA_ASYNC_CONFIG_UPDATE |
7346 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
7347 if (spa->spa_ccw_fail_time == 0) {
7348 config_task_suspended = B_FALSE;
7350 config_task_suspended =
7351 (gethrtime() - spa->spa_ccw_fail_time) <
7352 (zfs_ccw_retry_interval * NANOSEC);
7355 return (non_config_tasks || (config_task && !config_task_suspended));
7359 spa_async_dispatch(spa_t *spa)
7361 mutex_enter(&spa->spa_async_lock);
7362 if (spa_async_tasks_pending(spa) &&
7363 !spa->spa_async_suspended &&
7364 spa->spa_async_thread == NULL &&
7366 spa->spa_async_thread = thread_create(NULL, 0,
7367 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
7368 mutex_exit(&spa->spa_async_lock);
7372 spa_async_dispatch_vd(spa_t *spa)
7374 mutex_enter(&spa->spa_async_lock);
7375 if ((spa->spa_async_tasks & SPA_ASYNC_REMOVE) != 0 &&
7376 !spa->spa_async_suspended &&
7377 spa->spa_async_thread_vd == NULL &&
7379 spa->spa_async_thread_vd = thread_create(NULL, 0,
7380 spa_async_thread_vd, spa, 0, &p0, TS_RUN, maxclsyspri);
7381 mutex_exit(&spa->spa_async_lock);
7385 spa_async_request(spa_t *spa, int task)
7387 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
7388 mutex_enter(&spa->spa_async_lock);
7389 spa->spa_async_tasks |= task;
7390 mutex_exit(&spa->spa_async_lock);
7391 spa_async_dispatch_vd(spa);
7395 * ==========================================================================
7396 * SPA syncing routines
7397 * ==========================================================================
7401 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7404 bpobj_enqueue(bpo, bp, tx);
7409 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7413 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
7414 BP_GET_PSIZE(bp), zio->io_flags));
7419 * Note: this simple function is not inlined to make it easier to dtrace the
7420 * amount of time spent syncing frees.
7423 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
7425 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7426 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
7427 VERIFY(zio_wait(zio) == 0);
7431 * Note: this simple function is not inlined to make it easier to dtrace the
7432 * amount of time spent syncing deferred frees.
7435 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
7437 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7438 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
7439 spa_free_sync_cb, zio, tx), ==, 0);
7440 VERIFY0(zio_wait(zio));
7445 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
7447 char *packed = NULL;
7452 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
7455 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
7456 * information. This avoids the dmu_buf_will_dirty() path and
7457 * saves us a pre-read to get data we don't actually care about.
7459 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
7460 packed = kmem_alloc(bufsize, KM_SLEEP);
7462 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
7464 bzero(packed + nvsize, bufsize - nvsize);
7466 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
7468 kmem_free(packed, bufsize);
7470 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
7471 dmu_buf_will_dirty(db, tx);
7472 *(uint64_t *)db->db_data = nvsize;
7473 dmu_buf_rele(db, FTAG);
7477 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
7478 const char *config, const char *entry)
7488 * Update the MOS nvlist describing the list of available devices.
7489 * spa_validate_aux() will have already made sure this nvlist is
7490 * valid and the vdevs are labeled appropriately.
7492 if (sav->sav_object == 0) {
7493 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
7494 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
7495 sizeof (uint64_t), tx);
7496 VERIFY(zap_update(spa->spa_meta_objset,
7497 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
7498 &sav->sav_object, tx) == 0);
7501 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7502 if (sav->sav_count == 0) {
7503 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
7505 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
7506 for (i = 0; i < sav->sav_count; i++)
7507 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
7508 B_FALSE, VDEV_CONFIG_L2CACHE);
7509 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
7510 sav->sav_count) == 0);
7511 for (i = 0; i < sav->sav_count; i++)
7512 nvlist_free(list[i]);
7513 kmem_free(list, sav->sav_count * sizeof (void *));
7516 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
7517 nvlist_free(nvroot);
7519 sav->sav_sync = B_FALSE;
7523 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
7524 * The all-vdev ZAP must be empty.
7527 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
7529 spa_t *spa = vd->vdev_spa;
7530 if (vd->vdev_top_zap != 0) {
7531 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7532 vd->vdev_top_zap, tx));
7534 if (vd->vdev_leaf_zap != 0) {
7535 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7536 vd->vdev_leaf_zap, tx));
7538 for (uint64_t i = 0; i < vd->vdev_children; i++) {
7539 spa_avz_build(vd->vdev_child[i], avz, tx);
7544 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
7549 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
7550 * its config may not be dirty but we still need to build per-vdev ZAPs.
7551 * Similarly, if the pool is being assembled (e.g. after a split), we
7552 * need to rebuild the AVZ although the config may not be dirty.
7554 if (list_is_empty(&spa->spa_config_dirty_list) &&
7555 spa->spa_avz_action == AVZ_ACTION_NONE)
7558 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7560 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
7561 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
7562 spa->spa_all_vdev_zaps != 0);
7564 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
7565 /* Make and build the new AVZ */
7566 uint64_t new_avz = zap_create(spa->spa_meta_objset,
7567 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7568 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7570 /* Diff old AVZ with new one */
7574 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7575 spa->spa_all_vdev_zaps);
7576 zap_cursor_retrieve(&zc, &za) == 0;
7577 zap_cursor_advance(&zc)) {
7578 uint64_t vdzap = za.za_first_integer;
7579 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
7582 * ZAP is listed in old AVZ but not in new one;
7585 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
7590 zap_cursor_fini(&zc);
7592 /* Destroy the old AVZ */
7593 VERIFY0(zap_destroy(spa->spa_meta_objset,
7594 spa->spa_all_vdev_zaps, tx));
7596 /* Replace the old AVZ in the dir obj with the new one */
7597 VERIFY0(zap_update(spa->spa_meta_objset,
7598 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
7599 sizeof (new_avz), 1, &new_avz, tx));
7601 spa->spa_all_vdev_zaps = new_avz;
7602 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
7606 /* Walk through the AVZ and destroy all listed ZAPs */
7607 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7608 spa->spa_all_vdev_zaps);
7609 zap_cursor_retrieve(&zc, &za) == 0;
7610 zap_cursor_advance(&zc)) {
7611 uint64_t zap = za.za_first_integer;
7612 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
7615 zap_cursor_fini(&zc);
7617 /* Destroy and unlink the AVZ itself */
7618 VERIFY0(zap_destroy(spa->spa_meta_objset,
7619 spa->spa_all_vdev_zaps, tx));
7620 VERIFY0(zap_remove(spa->spa_meta_objset,
7621 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
7622 spa->spa_all_vdev_zaps = 0;
7625 if (spa->spa_all_vdev_zaps == 0) {
7626 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
7627 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
7628 DMU_POOL_VDEV_ZAP_MAP, tx);
7630 spa->spa_avz_action = AVZ_ACTION_NONE;
7632 /* Create ZAPs for vdevs that don't have them. */
7633 vdev_construct_zaps(spa->spa_root_vdev, tx);
7635 config = spa_config_generate(spa, spa->spa_root_vdev,
7636 dmu_tx_get_txg(tx), B_FALSE);
7639 * If we're upgrading the spa version then make sure that
7640 * the config object gets updated with the correct version.
7642 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
7643 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7644 spa->spa_uberblock.ub_version);
7646 spa_config_exit(spa, SCL_STATE, FTAG);
7648 nvlist_free(spa->spa_config_syncing);
7649 spa->spa_config_syncing = config;
7651 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
7655 spa_sync_version(void *arg, dmu_tx_t *tx)
7657 uint64_t *versionp = arg;
7658 uint64_t version = *versionp;
7659 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7662 * Setting the version is special cased when first creating the pool.
7664 ASSERT(tx->tx_txg != TXG_INITIAL);
7666 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
7667 ASSERT(version >= spa_version(spa));
7669 spa->spa_uberblock.ub_version = version;
7670 vdev_config_dirty(spa->spa_root_vdev);
7671 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
7675 * Set zpool properties.
7678 spa_sync_props(void *arg, dmu_tx_t *tx)
7680 nvlist_t *nvp = arg;
7681 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7682 objset_t *mos = spa->spa_meta_objset;
7683 nvpair_t *elem = NULL;
7685 mutex_enter(&spa->spa_props_lock);
7687 while ((elem = nvlist_next_nvpair(nvp, elem))) {
7689 char *strval, *fname;
7691 const char *propname;
7692 zprop_type_t proptype;
7695 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
7696 case ZPOOL_PROP_INVAL:
7698 * We checked this earlier in spa_prop_validate().
7700 ASSERT(zpool_prop_feature(nvpair_name(elem)));
7702 fname = strchr(nvpair_name(elem), '@') + 1;
7703 VERIFY0(zfeature_lookup_name(fname, &fid));
7705 spa_feature_enable(spa, fid, tx);
7706 spa_history_log_internal(spa, "set", tx,
7707 "%s=enabled", nvpair_name(elem));
7710 case ZPOOL_PROP_VERSION:
7711 intval = fnvpair_value_uint64(elem);
7713 * The version is synced seperatly before other
7714 * properties and should be correct by now.
7716 ASSERT3U(spa_version(spa), >=, intval);
7719 case ZPOOL_PROP_ALTROOT:
7721 * 'altroot' is a non-persistent property. It should
7722 * have been set temporarily at creation or import time.
7724 ASSERT(spa->spa_root != NULL);
7727 case ZPOOL_PROP_READONLY:
7728 case ZPOOL_PROP_CACHEFILE:
7730 * 'readonly' and 'cachefile' are also non-persisitent
7734 case ZPOOL_PROP_COMMENT:
7735 strval = fnvpair_value_string(elem);
7736 if (spa->spa_comment != NULL)
7737 spa_strfree(spa->spa_comment);
7738 spa->spa_comment = spa_strdup(strval);
7740 * We need to dirty the configuration on all the vdevs
7741 * so that their labels get updated. It's unnecessary
7742 * to do this for pool creation since the vdev's
7743 * configuratoin has already been dirtied.
7745 if (tx->tx_txg != TXG_INITIAL)
7746 vdev_config_dirty(spa->spa_root_vdev);
7747 spa_history_log_internal(spa, "set", tx,
7748 "%s=%s", nvpair_name(elem), strval);
7752 * Set pool property values in the poolprops mos object.
7754 if (spa->spa_pool_props_object == 0) {
7755 spa->spa_pool_props_object =
7756 zap_create_link(mos, DMU_OT_POOL_PROPS,
7757 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
7761 /* normalize the property name */
7762 propname = zpool_prop_to_name(prop);
7763 proptype = zpool_prop_get_type(prop);
7765 if (nvpair_type(elem) == DATA_TYPE_STRING) {
7766 ASSERT(proptype == PROP_TYPE_STRING);
7767 strval = fnvpair_value_string(elem);
7768 VERIFY0(zap_update(mos,
7769 spa->spa_pool_props_object, propname,
7770 1, strlen(strval) + 1, strval, tx));
7771 spa_history_log_internal(spa, "set", tx,
7772 "%s=%s", nvpair_name(elem), strval);
7773 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
7774 intval = fnvpair_value_uint64(elem);
7776 if (proptype == PROP_TYPE_INDEX) {
7778 VERIFY0(zpool_prop_index_to_string(
7779 prop, intval, &unused));
7781 VERIFY0(zap_update(mos,
7782 spa->spa_pool_props_object, propname,
7783 8, 1, &intval, tx));
7784 spa_history_log_internal(spa, "set", tx,
7785 "%s=%lld", nvpair_name(elem), intval);
7787 ASSERT(0); /* not allowed */
7791 case ZPOOL_PROP_DELEGATION:
7792 spa->spa_delegation = intval;
7794 case ZPOOL_PROP_BOOTFS:
7795 spa->spa_bootfs = intval;
7797 case ZPOOL_PROP_FAILUREMODE:
7798 spa->spa_failmode = intval;
7800 case ZPOOL_PROP_AUTOEXPAND:
7801 spa->spa_autoexpand = intval;
7802 if (tx->tx_txg != TXG_INITIAL)
7803 spa_async_request(spa,
7804 SPA_ASYNC_AUTOEXPAND);
7806 case ZPOOL_PROP_DEDUPDITTO:
7807 spa->spa_dedup_ditto = intval;
7816 mutex_exit(&spa->spa_props_lock);
7820 * Perform one-time upgrade on-disk changes. spa_version() does not
7821 * reflect the new version this txg, so there must be no changes this
7822 * txg to anything that the upgrade code depends on after it executes.
7823 * Therefore this must be called after dsl_pool_sync() does the sync
7827 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
7829 dsl_pool_t *dp = spa->spa_dsl_pool;
7831 ASSERT(spa->spa_sync_pass == 1);
7833 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
7835 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
7836 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
7837 dsl_pool_create_origin(dp, tx);
7839 /* Keeping the origin open increases spa_minref */
7840 spa->spa_minref += 3;
7843 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
7844 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
7845 dsl_pool_upgrade_clones(dp, tx);
7848 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
7849 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
7850 dsl_pool_upgrade_dir_clones(dp, tx);
7852 /* Keeping the freedir open increases spa_minref */
7853 spa->spa_minref += 3;
7856 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
7857 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7858 spa_feature_create_zap_objects(spa, tx);
7862 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
7863 * when possibility to use lz4 compression for metadata was added
7864 * Old pools that have this feature enabled must be upgraded to have
7865 * this feature active
7867 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7868 boolean_t lz4_en = spa_feature_is_enabled(spa,
7869 SPA_FEATURE_LZ4_COMPRESS);
7870 boolean_t lz4_ac = spa_feature_is_active(spa,
7871 SPA_FEATURE_LZ4_COMPRESS);
7873 if (lz4_en && !lz4_ac)
7874 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
7878 * If we haven't written the salt, do so now. Note that the
7879 * feature may not be activated yet, but that's fine since
7880 * the presence of this ZAP entry is backwards compatible.
7882 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7883 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
7884 VERIFY0(zap_add(spa->spa_meta_objset,
7885 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
7886 sizeof (spa->spa_cksum_salt.zcs_bytes),
7887 spa->spa_cksum_salt.zcs_bytes, tx));
7890 rrw_exit(&dp->dp_config_rwlock, FTAG);
7894 vdev_indirect_state_sync_verify(vdev_t *vd)
7896 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
7897 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
7899 if (vd->vdev_ops == &vdev_indirect_ops) {
7900 ASSERT(vim != NULL);
7901 ASSERT(vib != NULL);
7904 if (vdev_obsolete_sm_object(vd) != 0) {
7905 ASSERT(vd->vdev_obsolete_sm != NULL);
7906 ASSERT(vd->vdev_removing ||
7907 vd->vdev_ops == &vdev_indirect_ops);
7908 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
7909 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
7911 ASSERT3U(vdev_obsolete_sm_object(vd), ==,
7912 space_map_object(vd->vdev_obsolete_sm));
7913 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
7914 space_map_allocated(vd->vdev_obsolete_sm));
7916 ASSERT(vd->vdev_obsolete_segments != NULL);
7919 * Since frees / remaps to an indirect vdev can only
7920 * happen in syncing context, the obsolete segments
7921 * tree must be empty when we start syncing.
7923 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
7927 * Sync the specified transaction group. New blocks may be dirtied as
7928 * part of the process, so we iterate until it converges.
7931 spa_sync(spa_t *spa, uint64_t txg)
7933 dsl_pool_t *dp = spa->spa_dsl_pool;
7934 objset_t *mos = spa->spa_meta_objset;
7935 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
7936 vdev_t *rvd = spa->spa_root_vdev;
7940 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
7941 zfs_vdev_queue_depth_pct / 100;
7943 VERIFY(spa_writeable(spa));
7946 * Wait for i/os issued in open context that need to complete
7947 * before this txg syncs.
7949 (void) zio_wait(spa->spa_txg_zio[txg & TXG_MASK]);
7950 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL,
7954 * Lock out configuration changes.
7956 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7958 spa->spa_syncing_txg = txg;
7959 spa->spa_sync_pass = 0;
7961 for (int i = 0; i < spa->spa_alloc_count; i++) {
7962 mutex_enter(&spa->spa_alloc_locks[i]);
7963 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
7964 mutex_exit(&spa->spa_alloc_locks[i]);
7968 * If there are any pending vdev state changes, convert them
7969 * into config changes that go out with this transaction group.
7971 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7972 while (list_head(&spa->spa_state_dirty_list) != NULL) {
7974 * We need the write lock here because, for aux vdevs,
7975 * calling vdev_config_dirty() modifies sav_config.
7976 * This is ugly and will become unnecessary when we
7977 * eliminate the aux vdev wart by integrating all vdevs
7978 * into the root vdev tree.
7980 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7981 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
7982 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
7983 vdev_state_clean(vd);
7984 vdev_config_dirty(vd);
7986 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7987 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
7989 spa_config_exit(spa, SCL_STATE, FTAG);
7991 tx = dmu_tx_create_assigned(dp, txg);
7993 spa->spa_sync_starttime = gethrtime();
7995 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
7996 spa->spa_sync_starttime + spa->spa_deadman_synctime));
7997 #else /* !illumos */
7999 callout_schedule(&spa->spa_deadman_cycid,
8000 hz * spa->spa_deadman_synctime / NANOSEC);
8002 #endif /* illumos */
8005 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
8006 * set spa_deflate if we have no raid-z vdevs.
8008 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
8009 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
8012 for (i = 0; i < rvd->vdev_children; i++) {
8013 vd = rvd->vdev_child[i];
8014 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
8017 if (i == rvd->vdev_children) {
8018 spa->spa_deflate = TRUE;
8019 VERIFY(0 == zap_add(spa->spa_meta_objset,
8020 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
8021 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
8026 * Set the top-level vdev's max queue depth. Evaluate each
8027 * top-level's async write queue depth in case it changed.
8028 * The max queue depth will not change in the middle of syncing
8031 uint64_t slots_per_allocator = 0;
8032 for (int c = 0; c < rvd->vdev_children; c++) {
8033 vdev_t *tvd = rvd->vdev_child[c];
8034 metaslab_group_t *mg = tvd->vdev_mg;
8036 if (mg == NULL || mg->mg_class != spa_normal_class(spa) ||
8037 !metaslab_group_initialized(mg))
8041 * It is safe to do a lock-free check here because only async
8042 * allocations look at mg_max_alloc_queue_depth, and async
8043 * allocations all happen from spa_sync().
8045 for (int i = 0; i < spa->spa_alloc_count; i++)
8046 ASSERT0(refcount_count(&(mg->mg_alloc_queue_depth[i])));
8047 mg->mg_max_alloc_queue_depth = max_queue_depth;
8049 for (int i = 0; i < spa->spa_alloc_count; i++) {
8050 mg->mg_cur_max_alloc_queue_depth[i] =
8051 zfs_vdev_def_queue_depth;
8053 slots_per_allocator += zfs_vdev_def_queue_depth;
8055 metaslab_class_t *mc = spa_normal_class(spa);
8056 for (int i = 0; i < spa->spa_alloc_count; i++) {
8057 ASSERT0(refcount_count(&mc->mc_alloc_slots[i]));
8058 mc->mc_alloc_max_slots[i] = slots_per_allocator;
8060 mc->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8062 for (int c = 0; c < rvd->vdev_children; c++) {
8063 vdev_t *vd = rvd->vdev_child[c];
8064 vdev_indirect_state_sync_verify(vd);
8066 if (vdev_indirect_should_condense(vd)) {
8067 spa_condense_indirect_start_sync(vd, tx);
8073 * Iterate to convergence.
8076 int pass = ++spa->spa_sync_pass;
8078 spa_sync_config_object(spa, tx);
8079 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
8080 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
8081 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
8082 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
8083 spa_errlog_sync(spa, txg);
8084 dsl_pool_sync(dp, txg);
8086 if (pass < zfs_sync_pass_deferred_free) {
8087 spa_sync_frees(spa, free_bpl, tx);
8090 * We can not defer frees in pass 1, because
8091 * we sync the deferred frees later in pass 1.
8093 ASSERT3U(pass, >, 1);
8094 bplist_iterate(free_bpl, bpobj_enqueue_cb,
8095 &spa->spa_deferred_bpobj, tx);
8099 dsl_scan_sync(dp, tx);
8101 if (spa->spa_vdev_removal != NULL)
8104 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
8109 spa_sync_upgrades(spa, tx);
8111 spa->spa_uberblock.ub_rootbp.blk_birth);
8113 * Note: We need to check if the MOS is dirty
8114 * because we could have marked the MOS dirty
8115 * without updating the uberblock (e.g. if we
8116 * have sync tasks but no dirty user data). We
8117 * need to check the uberblock's rootbp because
8118 * it is updated if we have synced out dirty
8119 * data (though in this case the MOS will most
8120 * likely also be dirty due to second order
8121 * effects, we don't want to rely on that here).
8123 if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
8124 !dmu_objset_is_dirty(mos, txg)) {
8126 * Nothing changed on the first pass,
8127 * therefore this TXG is a no-op. Avoid
8128 * syncing deferred frees, so that we
8129 * can keep this TXG as a no-op.
8131 ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
8133 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8134 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
8135 ASSERT(txg_list_empty(&dp->dp_early_sync_tasks,
8139 spa_sync_deferred_frees(spa, tx);
8142 } while (dmu_objset_is_dirty(mos, txg));
8144 if (!list_is_empty(&spa->spa_config_dirty_list)) {
8146 * Make sure that the number of ZAPs for all the vdevs matches
8147 * the number of ZAPs in the per-vdev ZAP list. This only gets
8148 * called if the config is dirty; otherwise there may be
8149 * outstanding AVZ operations that weren't completed in
8150 * spa_sync_config_object.
8152 uint64_t all_vdev_zap_entry_count;
8153 ASSERT0(zap_count(spa->spa_meta_objset,
8154 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
8155 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
8156 all_vdev_zap_entry_count);
8159 if (spa->spa_vdev_removal != NULL) {
8160 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
8164 * Rewrite the vdev configuration (which includes the uberblock)
8165 * to commit the transaction group.
8167 * If there are no dirty vdevs, we sync the uberblock to a few
8168 * random top-level vdevs that are known to be visible in the
8169 * config cache (see spa_vdev_add() for a complete description).
8170 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
8174 * We hold SCL_STATE to prevent vdev open/close/etc.
8175 * while we're attempting to write the vdev labels.
8177 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8179 if (list_is_empty(&spa->spa_config_dirty_list)) {
8180 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
8182 int children = rvd->vdev_children;
8183 int c0 = spa_get_random(children);
8185 for (int c = 0; c < children; c++) {
8186 vd = rvd->vdev_child[(c0 + c) % children];
8188 /* Stop when revisiting the first vdev */
8189 if (c > 0 && svd[0] == vd)
8192 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
8193 !vdev_is_concrete(vd))
8196 svd[svdcount++] = vd;
8197 if (svdcount == SPA_SYNC_MIN_VDEVS)
8200 error = vdev_config_sync(svd, svdcount, txg);
8202 error = vdev_config_sync(rvd->vdev_child,
8203 rvd->vdev_children, txg);
8207 spa->spa_last_synced_guid = rvd->vdev_guid;
8209 spa_config_exit(spa, SCL_STATE, FTAG);
8213 zio_suspend(spa, NULL);
8214 zio_resume_wait(spa);
8219 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
8220 #else /* !illumos */
8222 callout_drain(&spa->spa_deadman_cycid);
8224 #endif /* illumos */
8227 * Clear the dirty config list.
8229 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
8230 vdev_config_clean(vd);
8233 * Now that the new config has synced transactionally,
8234 * let it become visible to the config cache.
8236 if (spa->spa_config_syncing != NULL) {
8237 spa_config_set(spa, spa->spa_config_syncing);
8238 spa->spa_config_txg = txg;
8239 spa->spa_config_syncing = NULL;
8242 dsl_pool_sync_done(dp, txg);
8244 for (int i = 0; i < spa->spa_alloc_count; i++) {
8245 mutex_enter(&spa->spa_alloc_locks[i]);
8246 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8247 mutex_exit(&spa->spa_alloc_locks[i]);
8251 * Update usable space statistics.
8253 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
8255 vdev_sync_done(vd, txg);
8257 spa_update_dspace(spa);
8260 * It had better be the case that we didn't dirty anything
8261 * since vdev_config_sync().
8263 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8264 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8265 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
8267 while (zfs_pause_spa_sync)
8270 spa->spa_sync_pass = 0;
8273 * Update the last synced uberblock here. We want to do this at
8274 * the end of spa_sync() so that consumers of spa_last_synced_txg()
8275 * will be guaranteed that all the processing associated with
8276 * that txg has been completed.
8278 spa->spa_ubsync = spa->spa_uberblock;
8279 spa_config_exit(spa, SCL_CONFIG, FTAG);
8281 spa_handle_ignored_writes(spa);
8284 * If any async tasks have been requested, kick them off.
8286 spa_async_dispatch(spa);
8287 spa_async_dispatch_vd(spa);
8291 * Sync all pools. We don't want to hold the namespace lock across these
8292 * operations, so we take a reference on the spa_t and drop the lock during the
8296 spa_sync_allpools(void)
8299 mutex_enter(&spa_namespace_lock);
8300 while ((spa = spa_next(spa)) != NULL) {
8301 if (spa_state(spa) != POOL_STATE_ACTIVE ||
8302 !spa_writeable(spa) || spa_suspended(spa))
8304 spa_open_ref(spa, FTAG);
8305 mutex_exit(&spa_namespace_lock);
8306 txg_wait_synced(spa_get_dsl(spa), 0);
8307 mutex_enter(&spa_namespace_lock);
8308 spa_close(spa, FTAG);
8310 mutex_exit(&spa_namespace_lock);
8314 * ==========================================================================
8315 * Miscellaneous routines
8316 * ==========================================================================
8320 * Remove all pools in the system.
8328 * Remove all cached state. All pools should be closed now,
8329 * so every spa in the AVL tree should be unreferenced.
8331 mutex_enter(&spa_namespace_lock);
8332 while ((spa = spa_next(NULL)) != NULL) {
8334 * Stop async tasks. The async thread may need to detach
8335 * a device that's been replaced, which requires grabbing
8336 * spa_namespace_lock, so we must drop it here.
8338 spa_open_ref(spa, FTAG);
8339 mutex_exit(&spa_namespace_lock);
8340 spa_async_suspend(spa);
8341 mutex_enter(&spa_namespace_lock);
8342 spa_close(spa, FTAG);
8344 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
8346 spa_deactivate(spa);
8350 mutex_exit(&spa_namespace_lock);
8354 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
8359 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
8363 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
8364 vd = spa->spa_l2cache.sav_vdevs[i];
8365 if (vd->vdev_guid == guid)
8369 for (i = 0; i < spa->spa_spares.sav_count; i++) {
8370 vd = spa->spa_spares.sav_vdevs[i];
8371 if (vd->vdev_guid == guid)
8380 spa_upgrade(spa_t *spa, uint64_t version)
8382 ASSERT(spa_writeable(spa));
8384 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
8387 * This should only be called for a non-faulted pool, and since a
8388 * future version would result in an unopenable pool, this shouldn't be
8391 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
8392 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
8394 spa->spa_uberblock.ub_version = version;
8395 vdev_config_dirty(spa->spa_root_vdev);
8397 spa_config_exit(spa, SCL_ALL, FTAG);
8399 txg_wait_synced(spa_get_dsl(spa), 0);
8403 spa_has_spare(spa_t *spa, uint64_t guid)
8407 spa_aux_vdev_t *sav = &spa->spa_spares;
8409 for (i = 0; i < sav->sav_count; i++)
8410 if (sav->sav_vdevs[i]->vdev_guid == guid)
8413 for (i = 0; i < sav->sav_npending; i++) {
8414 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
8415 &spareguid) == 0 && spareguid == guid)
8423 * Check if a pool has an active shared spare device.
8424 * Note: reference count of an active spare is 2, as a spare and as a replace
8427 spa_has_active_shared_spare(spa_t *spa)
8431 spa_aux_vdev_t *sav = &spa->spa_spares;
8433 for (i = 0; i < sav->sav_count; i++) {
8434 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
8435 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
8444 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8446 sysevent_t *ev = NULL;
8448 sysevent_attr_list_t *attr = NULL;
8449 sysevent_value_t value;
8451 ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
8455 value.value_type = SE_DATA_TYPE_STRING;
8456 value.value.sv_string = spa_name(spa);
8457 if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
8460 value.value_type = SE_DATA_TYPE_UINT64;
8461 value.value.sv_uint64 = spa_guid(spa);
8462 if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
8466 value.value_type = SE_DATA_TYPE_UINT64;
8467 value.value.sv_uint64 = vd->vdev_guid;
8468 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
8472 if (vd->vdev_path) {
8473 value.value_type = SE_DATA_TYPE_STRING;
8474 value.value.sv_string = vd->vdev_path;
8475 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
8476 &value, SE_SLEEP) != 0)
8481 if (hist_nvl != NULL) {
8482 fnvlist_merge((nvlist_t *)attr, hist_nvl);
8485 if (sysevent_attach_attributes(ev, attr) != 0)
8491 sysevent_free_attr(attr);
8498 spa_event_post(sysevent_t *ev)
8503 (void) log_sysevent(ev, SE_SLEEP, &eid);
8509 spa_event_discard(sysevent_t *ev)
8517 * Post a sysevent corresponding to the given event. The 'name' must be one of
8518 * the event definitions in sys/sysevent/eventdefs.h. The payload will be
8519 * filled in from the spa and (optionally) the vdev and history nvl. This
8520 * doesn't do anything in the userland libzpool, as we don't want consumers to
8521 * misinterpret ztest or zdb as real changes.
8524 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8526 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));