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/metaslab.h>
59 #include <sys/metaslab_impl.h>
60 #include <sys/uberblock_impl.h>
63 #include <sys/bpobj.h>
64 #include <sys/dmu_traverse.h>
65 #include <sys/dmu_objset.h>
66 #include <sys/unique.h>
67 #include <sys/dsl_pool.h>
68 #include <sys/dsl_dataset.h>
69 #include <sys/dsl_dir.h>
70 #include <sys/dsl_prop.h>
71 #include <sys/dsl_synctask.h>
72 #include <sys/fs/zfs.h>
74 #include <sys/callb.h>
75 #include <sys/spa_boot.h>
76 #include <sys/zfs_ioctl.h>
77 #include <sys/dsl_scan.h>
78 #include <sys/dmu_send.h>
79 #include <sys/dsl_destroy.h>
80 #include <sys/dsl_userhold.h>
81 #include <sys/zfeature.h>
83 #include <sys/trim_map.h>
87 #include <sys/callb.h>
88 #include <sys/cpupart.h>
93 #include "zfs_comutil.h"
95 /* Check hostid on import? */
96 static int check_hostid = 1;
99 * The interval, in seconds, at which failed configuration cache file writes
102 int zfs_ccw_retry_interval = 300;
104 SYSCTL_DECL(_vfs_zfs);
105 SYSCTL_INT(_vfs_zfs, OID_AUTO, check_hostid, CTLFLAG_RWTUN, &check_hostid, 0,
106 "Check hostid on import?");
107 TUNABLE_INT("vfs.zfs.ccw_retry_interval", &zfs_ccw_retry_interval);
108 SYSCTL_INT(_vfs_zfs, OID_AUTO, ccw_retry_interval, CTLFLAG_RW,
109 &zfs_ccw_retry_interval, 0,
110 "Configuration cache file write, retry after failure, interval (seconds)");
112 typedef enum zti_modes {
113 ZTI_MODE_FIXED, /* value is # of threads (min 1) */
114 ZTI_MODE_BATCH, /* cpu-intensive; value is ignored */
115 ZTI_MODE_NULL, /* don't create a taskq */
119 #define ZTI_P(n, q) { ZTI_MODE_FIXED, (n), (q) }
120 #define ZTI_BATCH { ZTI_MODE_BATCH, 0, 1 }
121 #define ZTI_NULL { ZTI_MODE_NULL, 0, 0 }
123 #define ZTI_N(n) ZTI_P(n, 1)
124 #define ZTI_ONE ZTI_N(1)
126 typedef struct zio_taskq_info {
127 zti_modes_t zti_mode;
132 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
133 "issue", "issue_high", "intr", "intr_high"
137 * This table defines the taskq settings for each ZFS I/O type. When
138 * initializing a pool, we use this table to create an appropriately sized
139 * taskq. Some operations are low volume and therefore have a small, static
140 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
141 * macros. Other operations process a large amount of data; the ZTI_BATCH
142 * macro causes us to create a taskq oriented for throughput. Some operations
143 * are so high frequency and short-lived that the taskq itself can become a a
144 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
145 * additional degree of parallelism specified by the number of threads per-
146 * taskq and the number of taskqs; when dispatching an event in this case, the
147 * particular taskq is chosen at random.
149 * The different taskq priorities are to handle the different contexts (issue
150 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
151 * need to be handled with minimum delay.
153 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
154 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
155 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* NULL */
156 { ZTI_N(8), ZTI_NULL, ZTI_P(12, 8), ZTI_NULL }, /* READ */
157 { ZTI_BATCH, ZTI_N(5), ZTI_N(8), ZTI_N(5) }, /* WRITE */
158 { ZTI_P(12, 8), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* FREE */
159 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* CLAIM */
160 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* IOCTL */
163 static void spa_sync_version(void *arg, dmu_tx_t *tx);
164 static void spa_sync_props(void *arg, dmu_tx_t *tx);
165 static boolean_t spa_has_active_shared_spare(spa_t *spa);
166 static int spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport,
167 boolean_t reloading);
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;
236 * In the case where config was assembled by scanning device paths (/dev/dsks
237 * by default) we are less tolerant since all the existing devices should have
238 * been detected and we want spa_load to return the right error codes.
240 uint64_t zfs_max_missing_tvds_scan = 0;
243 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_print_vdev_tree, CTLFLAG_RWTUN,
244 &spa_load_print_vdev_tree, 0,
245 "print out vdev tree during pool import");
246 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds, CTLFLAG_RWTUN,
247 &zfs_max_missing_tvds, 0,
248 "allow importing pools with missing top-level vdevs");
249 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_cachefile, CTLFLAG_RWTUN,
250 &zfs_max_missing_tvds_cachefile, 0,
251 "allow importing pools with missing top-level vdevs in cache file");
252 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_scan, CTLFLAG_RWTUN,
253 &zfs_max_missing_tvds_scan, 0,
254 "allow importing pools with missing top-level vdevs during scan");
257 * ==========================================================================
258 * SPA properties routines
259 * ==========================================================================
263 * Add a (source=src, propname=propval) list to an nvlist.
266 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
267 uint64_t intval, zprop_source_t src)
269 const char *propname = zpool_prop_to_name(prop);
272 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
273 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
276 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
278 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
280 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
281 nvlist_free(propval);
285 * Get property values from the spa configuration.
288 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
290 vdev_t *rvd = spa->spa_root_vdev;
291 dsl_pool_t *pool = spa->spa_dsl_pool;
292 uint64_t size, alloc, cap, version;
293 zprop_source_t src = ZPROP_SRC_NONE;
294 spa_config_dirent_t *dp;
295 metaslab_class_t *mc = spa_normal_class(spa);
297 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
300 alloc = metaslab_class_get_alloc(spa_normal_class(spa));
301 size = metaslab_class_get_space(spa_normal_class(spa));
302 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
303 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
304 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
305 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
308 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
309 metaslab_class_fragmentation(mc), src);
310 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
311 metaslab_class_expandable_space(mc), src);
312 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
313 (spa_mode(spa) == FREAD), src);
315 cap = (size == 0) ? 0 : (alloc * 100 / size);
316 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
318 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
319 ddt_get_pool_dedup_ratio(spa), src);
321 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
322 rvd->vdev_state, src);
324 version = spa_version(spa);
325 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
326 src = ZPROP_SRC_DEFAULT;
328 src = ZPROP_SRC_LOCAL;
329 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
334 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
335 * when opening pools before this version freedir will be NULL.
337 if (pool->dp_free_dir != NULL) {
338 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
339 dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
342 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
346 if (pool->dp_leak_dir != NULL) {
347 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
348 dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
351 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
356 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
358 if (spa->spa_comment != NULL) {
359 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
363 if (spa->spa_root != NULL)
364 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
367 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
368 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
369 MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
371 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
372 SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
375 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
376 if (dp->scd_path == NULL) {
377 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
378 "none", 0, ZPROP_SRC_LOCAL);
379 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
380 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
381 dp->scd_path, 0, ZPROP_SRC_LOCAL);
387 * Get zpool property values.
390 spa_prop_get(spa_t *spa, nvlist_t **nvp)
392 objset_t *mos = spa->spa_meta_objset;
397 VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
399 mutex_enter(&spa->spa_props_lock);
402 * Get properties from the spa config.
404 spa_prop_get_config(spa, nvp);
406 /* If no pool property object, no more prop to get. */
407 if (mos == NULL || spa->spa_pool_props_object == 0) {
408 mutex_exit(&spa->spa_props_lock);
413 * Get properties from the MOS pool property object.
415 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
416 (err = zap_cursor_retrieve(&zc, &za)) == 0;
417 zap_cursor_advance(&zc)) {
420 zprop_source_t src = ZPROP_SRC_DEFAULT;
423 if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
426 switch (za.za_integer_length) {
428 /* integer property */
429 if (za.za_first_integer !=
430 zpool_prop_default_numeric(prop))
431 src = ZPROP_SRC_LOCAL;
433 if (prop == ZPOOL_PROP_BOOTFS) {
435 dsl_dataset_t *ds = NULL;
437 dp = spa_get_dsl(spa);
438 dsl_pool_config_enter(dp, FTAG);
439 if (err = dsl_dataset_hold_obj(dp,
440 za.za_first_integer, FTAG, &ds)) {
441 dsl_pool_config_exit(dp, FTAG);
445 strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
447 dsl_dataset_name(ds, strval);
448 dsl_dataset_rele(ds, FTAG);
449 dsl_pool_config_exit(dp, FTAG);
452 intval = za.za_first_integer;
455 spa_prop_add_list(*nvp, prop, strval, intval, src);
458 kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
463 /* string property */
464 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
465 err = zap_lookup(mos, spa->spa_pool_props_object,
466 za.za_name, 1, za.za_num_integers, strval);
468 kmem_free(strval, za.za_num_integers);
471 spa_prop_add_list(*nvp, prop, strval, 0, src);
472 kmem_free(strval, za.za_num_integers);
479 zap_cursor_fini(&zc);
480 mutex_exit(&spa->spa_props_lock);
482 if (err && err != ENOENT) {
492 * Validate the given pool properties nvlist and modify the list
493 * for the property values to be set.
496 spa_prop_validate(spa_t *spa, nvlist_t *props)
499 int error = 0, reset_bootfs = 0;
501 boolean_t has_feature = B_FALSE;
504 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
506 char *strval, *slash, *check, *fname;
507 const char *propname = nvpair_name(elem);
508 zpool_prop_t prop = zpool_name_to_prop(propname);
511 case ZPOOL_PROP_INVAL:
512 if (!zpool_prop_feature(propname)) {
513 error = SET_ERROR(EINVAL);
518 * Sanitize the input.
520 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
521 error = SET_ERROR(EINVAL);
525 if (nvpair_value_uint64(elem, &intval) != 0) {
526 error = SET_ERROR(EINVAL);
531 error = SET_ERROR(EINVAL);
535 fname = strchr(propname, '@') + 1;
536 if (zfeature_lookup_name(fname, NULL) != 0) {
537 error = SET_ERROR(EINVAL);
541 has_feature = B_TRUE;
544 case ZPOOL_PROP_VERSION:
545 error = nvpair_value_uint64(elem, &intval);
547 (intval < spa_version(spa) ||
548 intval > SPA_VERSION_BEFORE_FEATURES ||
550 error = SET_ERROR(EINVAL);
553 case ZPOOL_PROP_DELEGATION:
554 case ZPOOL_PROP_AUTOREPLACE:
555 case ZPOOL_PROP_LISTSNAPS:
556 case ZPOOL_PROP_AUTOEXPAND:
557 error = nvpair_value_uint64(elem, &intval);
558 if (!error && intval > 1)
559 error = SET_ERROR(EINVAL);
562 case ZPOOL_PROP_BOOTFS:
564 * If the pool version is less than SPA_VERSION_BOOTFS,
565 * or the pool is still being created (version == 0),
566 * the bootfs property cannot be set.
568 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
569 error = SET_ERROR(ENOTSUP);
574 * Make sure the vdev config is bootable
576 if (!vdev_is_bootable(spa->spa_root_vdev)) {
577 error = SET_ERROR(ENOTSUP);
583 error = nvpair_value_string(elem, &strval);
589 if (strval == NULL || strval[0] == '\0') {
590 objnum = zpool_prop_default_numeric(
595 if (error = dmu_objset_hold(strval, FTAG, &os))
599 * Must be ZPL, and its property settings
600 * must be supported by GRUB (compression
601 * is not gzip, and large blocks are not used).
604 if (dmu_objset_type(os) != DMU_OST_ZFS) {
605 error = SET_ERROR(ENOTSUP);
607 dsl_prop_get_int_ds(dmu_objset_ds(os),
608 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
610 !BOOTFS_COMPRESS_VALID(propval)) {
611 error = SET_ERROR(ENOTSUP);
613 objnum = dmu_objset_id(os);
615 dmu_objset_rele(os, FTAG);
619 case ZPOOL_PROP_FAILUREMODE:
620 error = nvpair_value_uint64(elem, &intval);
621 if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
622 intval > ZIO_FAILURE_MODE_PANIC))
623 error = SET_ERROR(EINVAL);
626 * This is a special case which only occurs when
627 * the pool has completely failed. This allows
628 * the user to change the in-core failmode property
629 * without syncing it out to disk (I/Os might
630 * currently be blocked). We do this by returning
631 * EIO to the caller (spa_prop_set) to trick it
632 * into thinking we encountered a property validation
635 if (!error && spa_suspended(spa)) {
636 spa->spa_failmode = intval;
637 error = SET_ERROR(EIO);
641 case ZPOOL_PROP_CACHEFILE:
642 if ((error = nvpair_value_string(elem, &strval)) != 0)
645 if (strval[0] == '\0')
648 if (strcmp(strval, "none") == 0)
651 if (strval[0] != '/') {
652 error = SET_ERROR(EINVAL);
656 slash = strrchr(strval, '/');
657 ASSERT(slash != NULL);
659 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
660 strcmp(slash, "/..") == 0)
661 error = SET_ERROR(EINVAL);
664 case ZPOOL_PROP_COMMENT:
665 if ((error = nvpair_value_string(elem, &strval)) != 0)
667 for (check = strval; *check != '\0'; check++) {
669 * The kernel doesn't have an easy isprint()
670 * check. For this kernel check, we merely
671 * check ASCII apart from DEL. Fix this if
672 * there is an easy-to-use kernel isprint().
674 if (*check >= 0x7f) {
675 error = SET_ERROR(EINVAL);
679 if (strlen(strval) > ZPROP_MAX_COMMENT)
683 case ZPOOL_PROP_DEDUPDITTO:
684 if (spa_version(spa) < SPA_VERSION_DEDUP)
685 error = SET_ERROR(ENOTSUP);
687 error = nvpair_value_uint64(elem, &intval);
689 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
690 error = SET_ERROR(EINVAL);
698 if (!error && reset_bootfs) {
699 error = nvlist_remove(props,
700 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
703 error = nvlist_add_uint64(props,
704 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
712 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
715 spa_config_dirent_t *dp;
717 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
721 dp = kmem_alloc(sizeof (spa_config_dirent_t),
724 if (cachefile[0] == '\0')
725 dp->scd_path = spa_strdup(spa_config_path);
726 else if (strcmp(cachefile, "none") == 0)
729 dp->scd_path = spa_strdup(cachefile);
731 list_insert_head(&spa->spa_config_list, dp);
733 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
737 spa_prop_set(spa_t *spa, nvlist_t *nvp)
740 nvpair_t *elem = NULL;
741 boolean_t need_sync = B_FALSE;
743 if ((error = spa_prop_validate(spa, nvp)) != 0)
746 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
747 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
749 if (prop == ZPOOL_PROP_CACHEFILE ||
750 prop == ZPOOL_PROP_ALTROOT ||
751 prop == ZPOOL_PROP_READONLY)
754 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
757 if (prop == ZPOOL_PROP_VERSION) {
758 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
760 ASSERT(zpool_prop_feature(nvpair_name(elem)));
761 ver = SPA_VERSION_FEATURES;
765 /* Save time if the version is already set. */
766 if (ver == spa_version(spa))
770 * In addition to the pool directory object, we might
771 * create the pool properties object, the features for
772 * read object, the features for write object, or the
773 * feature descriptions object.
775 error = dsl_sync_task(spa->spa_name, NULL,
776 spa_sync_version, &ver,
777 6, ZFS_SPACE_CHECK_RESERVED);
788 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
789 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
796 * If the bootfs property value is dsobj, clear it.
799 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
801 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
802 VERIFY(zap_remove(spa->spa_meta_objset,
803 spa->spa_pool_props_object,
804 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
811 spa_change_guid_check(void *arg, dmu_tx_t *tx)
813 uint64_t *newguid = arg;
814 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
815 vdev_t *rvd = spa->spa_root_vdev;
818 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
819 vdev_state = rvd->vdev_state;
820 spa_config_exit(spa, SCL_STATE, FTAG);
822 if (vdev_state != VDEV_STATE_HEALTHY)
823 return (SET_ERROR(ENXIO));
825 ASSERT3U(spa_guid(spa), !=, *newguid);
831 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
833 uint64_t *newguid = arg;
834 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
836 vdev_t *rvd = spa->spa_root_vdev;
838 oldguid = spa_guid(spa);
840 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
841 rvd->vdev_guid = *newguid;
842 rvd->vdev_guid_sum += (*newguid - oldguid);
843 vdev_config_dirty(rvd);
844 spa_config_exit(spa, SCL_STATE, FTAG);
846 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
851 * Change the GUID for the pool. This is done so that we can later
852 * re-import a pool built from a clone of our own vdevs. We will modify
853 * the root vdev's guid, our own pool guid, and then mark all of our
854 * vdevs dirty. Note that we must make sure that all our vdevs are
855 * online when we do this, or else any vdevs that weren't present
856 * would be orphaned from our pool. We are also going to issue a
857 * sysevent to update any watchers.
860 spa_change_guid(spa_t *spa)
865 mutex_enter(&spa->spa_vdev_top_lock);
866 mutex_enter(&spa_namespace_lock);
867 guid = spa_generate_guid(NULL);
869 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
870 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
873 spa_write_cachefile(spa, B_FALSE, B_TRUE);
874 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
877 mutex_exit(&spa_namespace_lock);
878 mutex_exit(&spa->spa_vdev_top_lock);
884 * ==========================================================================
885 * SPA state manipulation (open/create/destroy/import/export)
886 * ==========================================================================
890 spa_error_entry_compare(const void *a, const void *b)
892 spa_error_entry_t *sa = (spa_error_entry_t *)a;
893 spa_error_entry_t *sb = (spa_error_entry_t *)b;
896 ret = bcmp(&sa->se_bookmark, &sb->se_bookmark,
897 sizeof (zbookmark_phys_t));
908 * Utility function which retrieves copies of the current logs and
909 * re-initializes them in the process.
912 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
914 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
916 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
917 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
919 avl_create(&spa->spa_errlist_scrub,
920 spa_error_entry_compare, sizeof (spa_error_entry_t),
921 offsetof(spa_error_entry_t, se_avl));
922 avl_create(&spa->spa_errlist_last,
923 spa_error_entry_compare, sizeof (spa_error_entry_t),
924 offsetof(spa_error_entry_t, se_avl));
928 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
930 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
931 enum zti_modes mode = ztip->zti_mode;
932 uint_t value = ztip->zti_value;
933 uint_t count = ztip->zti_count;
934 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
937 boolean_t batch = B_FALSE;
939 if (mode == ZTI_MODE_NULL) {
941 tqs->stqs_taskq = NULL;
945 ASSERT3U(count, >, 0);
947 tqs->stqs_count = count;
948 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
952 ASSERT3U(value, >=, 1);
953 value = MAX(value, 1);
958 flags |= TASKQ_THREADS_CPU_PCT;
959 value = zio_taskq_batch_pct;
963 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
965 zio_type_name[t], zio_taskq_types[q], mode, value);
969 for (uint_t i = 0; i < count; i++) {
973 (void) snprintf(name, sizeof (name), "%s_%s_%u",
974 zio_type_name[t], zio_taskq_types[q], i);
976 (void) snprintf(name, sizeof (name), "%s_%s",
977 zio_type_name[t], zio_taskq_types[q]);
981 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
983 flags |= TASKQ_DC_BATCH;
985 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
986 spa->spa_proc, zio_taskq_basedc, flags);
989 pri_t pri = maxclsyspri;
991 * The write issue taskq can be extremely CPU
992 * intensive. Run it at slightly lower priority
993 * than the other taskqs.
995 * - numerically higher priorities are lower priorities;
996 * - if priorities divided by four (RQ_PPQ) are equal
997 * then a difference between them is insignificant.
999 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1006 tq = taskq_create_proc(name, value, pri, 50,
1007 INT_MAX, spa->spa_proc, flags);
1012 tqs->stqs_taskq[i] = tq;
1017 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1019 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1021 if (tqs->stqs_taskq == NULL) {
1022 ASSERT0(tqs->stqs_count);
1026 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1027 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1028 taskq_destroy(tqs->stqs_taskq[i]);
1031 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1032 tqs->stqs_taskq = NULL;
1036 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1037 * Note that a type may have multiple discrete taskqs to avoid lock contention
1038 * on the taskq itself. In that case we choose which taskq at random by using
1039 * the low bits of gethrtime().
1042 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1043 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1045 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1048 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1049 ASSERT3U(tqs->stqs_count, !=, 0);
1051 if (tqs->stqs_count == 1) {
1052 tq = tqs->stqs_taskq[0];
1055 tq = tqs->stqs_taskq[cpu_ticks() % tqs->stqs_count];
1057 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1061 taskq_dispatch_ent(tq, func, arg, flags, ent);
1065 spa_create_zio_taskqs(spa_t *spa)
1067 for (int t = 0; t < ZIO_TYPES; t++) {
1068 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1069 spa_taskqs_init(spa, t, q);
1077 spa_thread(void *arg)
1079 callb_cpr_t cprinfo;
1082 user_t *pu = PTOU(curproc);
1084 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1087 ASSERT(curproc != &p0);
1088 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1089 "zpool-%s", spa->spa_name);
1090 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1093 /* bind this thread to the requested psrset */
1094 if (zio_taskq_psrset_bind != PS_NONE) {
1096 mutex_enter(&cpu_lock);
1097 mutex_enter(&pidlock);
1098 mutex_enter(&curproc->p_lock);
1100 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1101 0, NULL, NULL) == 0) {
1102 curthread->t_bind_pset = zio_taskq_psrset_bind;
1105 "Couldn't bind process for zfs pool \"%s\" to "
1106 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1109 mutex_exit(&curproc->p_lock);
1110 mutex_exit(&pidlock);
1111 mutex_exit(&cpu_lock);
1117 if (zio_taskq_sysdc) {
1118 sysdc_thread_enter(curthread, 100, 0);
1122 spa->spa_proc = curproc;
1123 spa->spa_did = curthread->t_did;
1125 spa_create_zio_taskqs(spa);
1127 mutex_enter(&spa->spa_proc_lock);
1128 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1130 spa->spa_proc_state = SPA_PROC_ACTIVE;
1131 cv_broadcast(&spa->spa_proc_cv);
1133 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1134 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1135 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1136 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1138 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1139 spa->spa_proc_state = SPA_PROC_GONE;
1140 spa->spa_proc = &p0;
1141 cv_broadcast(&spa->spa_proc_cv);
1142 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1144 mutex_enter(&curproc->p_lock);
1147 #endif /* SPA_PROCESS */
1151 * Activate an uninitialized pool.
1154 spa_activate(spa_t *spa, int mode)
1156 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1158 spa->spa_state = POOL_STATE_ACTIVE;
1159 spa->spa_mode = mode;
1161 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1162 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1164 /* Try to create a covering process */
1165 mutex_enter(&spa->spa_proc_lock);
1166 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1167 ASSERT(spa->spa_proc == &p0);
1171 /* Only create a process if we're going to be around a while. */
1172 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1173 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1175 spa->spa_proc_state = SPA_PROC_CREATED;
1176 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1177 cv_wait(&spa->spa_proc_cv,
1178 &spa->spa_proc_lock);
1180 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1181 ASSERT(spa->spa_proc != &p0);
1182 ASSERT(spa->spa_did != 0);
1186 "Couldn't create process for zfs pool \"%s\"\n",
1191 #endif /* SPA_PROCESS */
1192 mutex_exit(&spa->spa_proc_lock);
1194 /* If we didn't create a process, we need to create our taskqs. */
1195 ASSERT(spa->spa_proc == &p0);
1196 if (spa->spa_proc == &p0) {
1197 spa_create_zio_taskqs(spa);
1201 * Start TRIM thread.
1203 trim_thread_create(spa);
1205 for (size_t i = 0; i < TXG_SIZE; i++)
1206 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL, 0);
1208 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1209 offsetof(vdev_t, vdev_config_dirty_node));
1210 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1211 offsetof(objset_t, os_evicting_node));
1212 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1213 offsetof(vdev_t, vdev_state_dirty_node));
1215 txg_list_create(&spa->spa_vdev_txg_list, spa,
1216 offsetof(struct vdev, vdev_txg_node));
1218 avl_create(&spa->spa_errlist_scrub,
1219 spa_error_entry_compare, sizeof (spa_error_entry_t),
1220 offsetof(spa_error_entry_t, se_avl));
1221 avl_create(&spa->spa_errlist_last,
1222 spa_error_entry_compare, sizeof (spa_error_entry_t),
1223 offsetof(spa_error_entry_t, se_avl));
1227 * Opposite of spa_activate().
1230 spa_deactivate(spa_t *spa)
1232 ASSERT(spa->spa_sync_on == B_FALSE);
1233 ASSERT(spa->spa_dsl_pool == NULL);
1234 ASSERT(spa->spa_root_vdev == NULL);
1235 ASSERT(spa->spa_async_zio_root == NULL);
1236 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1239 * Stop TRIM thread in case spa_unload() wasn't called directly
1240 * before spa_deactivate().
1242 trim_thread_destroy(spa);
1244 spa_evicting_os_wait(spa);
1246 txg_list_destroy(&spa->spa_vdev_txg_list);
1248 list_destroy(&spa->spa_config_dirty_list);
1249 list_destroy(&spa->spa_evicting_os_list);
1250 list_destroy(&spa->spa_state_dirty_list);
1252 for (int t = 0; t < ZIO_TYPES; t++) {
1253 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1254 spa_taskqs_fini(spa, t, q);
1258 for (size_t i = 0; i < TXG_SIZE; i++) {
1259 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1260 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1261 spa->spa_txg_zio[i] = NULL;
1264 metaslab_class_destroy(spa->spa_normal_class);
1265 spa->spa_normal_class = NULL;
1267 metaslab_class_destroy(spa->spa_log_class);
1268 spa->spa_log_class = NULL;
1271 * If this was part of an import or the open otherwise failed, we may
1272 * still have errors left in the queues. Empty them just in case.
1274 spa_errlog_drain(spa);
1276 avl_destroy(&spa->spa_errlist_scrub);
1277 avl_destroy(&spa->spa_errlist_last);
1279 spa->spa_state = POOL_STATE_UNINITIALIZED;
1281 mutex_enter(&spa->spa_proc_lock);
1282 if (spa->spa_proc_state != SPA_PROC_NONE) {
1283 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1284 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1285 cv_broadcast(&spa->spa_proc_cv);
1286 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1287 ASSERT(spa->spa_proc != &p0);
1288 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1290 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1291 spa->spa_proc_state = SPA_PROC_NONE;
1293 ASSERT(spa->spa_proc == &p0);
1294 mutex_exit(&spa->spa_proc_lock);
1298 * We want to make sure spa_thread() has actually exited the ZFS
1299 * module, so that the module can't be unloaded out from underneath
1302 if (spa->spa_did != 0) {
1303 thread_join(spa->spa_did);
1306 #endif /* SPA_PROCESS */
1310 * Verify a pool configuration, and construct the vdev tree appropriately. This
1311 * will create all the necessary vdevs in the appropriate layout, with each vdev
1312 * in the CLOSED state. This will prep the pool before open/creation/import.
1313 * All vdev validation is done by the vdev_alloc() routine.
1316 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1317 uint_t id, int atype)
1323 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1326 if ((*vdp)->vdev_ops->vdev_op_leaf)
1329 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1332 if (error == ENOENT)
1338 return (SET_ERROR(EINVAL));
1341 for (int c = 0; c < children; c++) {
1343 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1351 ASSERT(*vdp != NULL);
1357 * Opposite of spa_load().
1360 spa_unload(spa_t *spa)
1364 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1366 spa_load_note(spa, "UNLOADING");
1371 trim_thread_destroy(spa);
1376 spa_async_suspend(spa);
1381 if (spa->spa_sync_on) {
1382 txg_sync_stop(spa->spa_dsl_pool);
1383 spa->spa_sync_on = B_FALSE;
1387 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1388 * to call it earlier, before we wait for async i/o to complete.
1389 * This ensures that there is no async metaslab prefetching, by
1390 * calling taskq_wait(mg_taskq).
1392 if (spa->spa_root_vdev != NULL) {
1393 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1394 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1395 vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1396 spa_config_exit(spa, SCL_ALL, FTAG);
1400 * Wait for any outstanding async I/O to complete.
1402 if (spa->spa_async_zio_root != NULL) {
1403 for (int i = 0; i < max_ncpus; i++)
1404 (void) zio_wait(spa->spa_async_zio_root[i]);
1405 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1406 spa->spa_async_zio_root = NULL;
1409 if (spa->spa_vdev_removal != NULL) {
1410 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1411 spa->spa_vdev_removal = NULL;
1414 if (spa->spa_condense_zthr != NULL) {
1415 ASSERT(!zthr_isrunning(spa->spa_condense_zthr));
1416 zthr_destroy(spa->spa_condense_zthr);
1417 spa->spa_condense_zthr = NULL;
1420 spa_condense_fini(spa);
1422 bpobj_close(&spa->spa_deferred_bpobj);
1424 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1429 if (spa->spa_root_vdev)
1430 vdev_free(spa->spa_root_vdev);
1431 ASSERT(spa->spa_root_vdev == NULL);
1434 * Close the dsl pool.
1436 if (spa->spa_dsl_pool) {
1437 dsl_pool_close(spa->spa_dsl_pool);
1438 spa->spa_dsl_pool = NULL;
1439 spa->spa_meta_objset = NULL;
1445 * Drop and purge level 2 cache
1447 spa_l2cache_drop(spa);
1449 for (i = 0; i < spa->spa_spares.sav_count; i++)
1450 vdev_free(spa->spa_spares.sav_vdevs[i]);
1451 if (spa->spa_spares.sav_vdevs) {
1452 kmem_free(spa->spa_spares.sav_vdevs,
1453 spa->spa_spares.sav_count * sizeof (void *));
1454 spa->spa_spares.sav_vdevs = NULL;
1456 if (spa->spa_spares.sav_config) {
1457 nvlist_free(spa->spa_spares.sav_config);
1458 spa->spa_spares.sav_config = NULL;
1460 spa->spa_spares.sav_count = 0;
1462 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1463 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1464 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1466 if (spa->spa_l2cache.sav_vdevs) {
1467 kmem_free(spa->spa_l2cache.sav_vdevs,
1468 spa->spa_l2cache.sav_count * sizeof (void *));
1469 spa->spa_l2cache.sav_vdevs = NULL;
1471 if (spa->spa_l2cache.sav_config) {
1472 nvlist_free(spa->spa_l2cache.sav_config);
1473 spa->spa_l2cache.sav_config = NULL;
1475 spa->spa_l2cache.sav_count = 0;
1477 spa->spa_async_suspended = 0;
1479 spa->spa_indirect_vdevs_loaded = B_FALSE;
1481 if (spa->spa_comment != NULL) {
1482 spa_strfree(spa->spa_comment);
1483 spa->spa_comment = NULL;
1486 spa_config_exit(spa, SCL_ALL, FTAG);
1490 * Load (or re-load) the current list of vdevs describing the active spares for
1491 * this pool. When this is called, we have some form of basic information in
1492 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1493 * then re-generate a more complete list including status information.
1496 spa_load_spares(spa_t *spa)
1503 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1506 * First, close and free any existing spare vdevs.
1508 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1509 vd = spa->spa_spares.sav_vdevs[i];
1511 /* Undo the call to spa_activate() below */
1512 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1513 B_FALSE)) != NULL && tvd->vdev_isspare)
1514 spa_spare_remove(tvd);
1519 if (spa->spa_spares.sav_vdevs)
1520 kmem_free(spa->spa_spares.sav_vdevs,
1521 spa->spa_spares.sav_count * sizeof (void *));
1523 if (spa->spa_spares.sav_config == NULL)
1526 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1527 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1529 spa->spa_spares.sav_count = (int)nspares;
1530 spa->spa_spares.sav_vdevs = NULL;
1536 * Construct the array of vdevs, opening them to get status in the
1537 * process. For each spare, there is potentially two different vdev_t
1538 * structures associated with it: one in the list of spares (used only
1539 * for basic validation purposes) and one in the active vdev
1540 * configuration (if it's spared in). During this phase we open and
1541 * validate each vdev on the spare list. If the vdev also exists in the
1542 * active configuration, then we also mark this vdev as an active spare.
1544 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1546 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1547 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1548 VDEV_ALLOC_SPARE) == 0);
1551 spa->spa_spares.sav_vdevs[i] = vd;
1553 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1554 B_FALSE)) != NULL) {
1555 if (!tvd->vdev_isspare)
1559 * We only mark the spare active if we were successfully
1560 * able to load the vdev. Otherwise, importing a pool
1561 * with a bad active spare would result in strange
1562 * behavior, because multiple pool would think the spare
1563 * is actively in use.
1565 * There is a vulnerability here to an equally bizarre
1566 * circumstance, where a dead active spare is later
1567 * brought back to life (onlined or otherwise). Given
1568 * the rarity of this scenario, and the extra complexity
1569 * it adds, we ignore the possibility.
1571 if (!vdev_is_dead(tvd))
1572 spa_spare_activate(tvd);
1576 vd->vdev_aux = &spa->spa_spares;
1578 if (vdev_open(vd) != 0)
1581 if (vdev_validate_aux(vd) == 0)
1586 * Recompute the stashed list of spares, with status information
1589 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1590 DATA_TYPE_NVLIST_ARRAY) == 0);
1592 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1594 for (i = 0; i < spa->spa_spares.sav_count; i++)
1595 spares[i] = vdev_config_generate(spa,
1596 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1597 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1598 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1599 for (i = 0; i < spa->spa_spares.sav_count; i++)
1600 nvlist_free(spares[i]);
1601 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1605 * Load (or re-load) the current list of vdevs describing the active l2cache for
1606 * this pool. When this is called, we have some form of basic information in
1607 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1608 * then re-generate a more complete list including status information.
1609 * Devices which are already active have their details maintained, and are
1613 spa_load_l2cache(spa_t *spa)
1617 int i, j, oldnvdevs;
1619 vdev_t *vd, **oldvdevs, **newvdevs;
1620 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1622 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1624 if (sav->sav_config != NULL) {
1625 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1626 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1627 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1633 oldvdevs = sav->sav_vdevs;
1634 oldnvdevs = sav->sav_count;
1635 sav->sav_vdevs = NULL;
1639 * Process new nvlist of vdevs.
1641 for (i = 0; i < nl2cache; i++) {
1642 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1646 for (j = 0; j < oldnvdevs; j++) {
1648 if (vd != NULL && guid == vd->vdev_guid) {
1650 * Retain previous vdev for add/remove ops.
1658 if (newvdevs[i] == NULL) {
1662 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1663 VDEV_ALLOC_L2CACHE) == 0);
1668 * Commit this vdev as an l2cache device,
1669 * even if it fails to open.
1671 spa_l2cache_add(vd);
1676 spa_l2cache_activate(vd);
1678 if (vdev_open(vd) != 0)
1681 (void) vdev_validate_aux(vd);
1683 if (!vdev_is_dead(vd))
1684 l2arc_add_vdev(spa, vd);
1689 * Purge vdevs that were dropped
1691 for (i = 0; i < oldnvdevs; i++) {
1696 ASSERT(vd->vdev_isl2cache);
1698 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1699 pool != 0ULL && l2arc_vdev_present(vd))
1700 l2arc_remove_vdev(vd);
1701 vdev_clear_stats(vd);
1707 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1709 if (sav->sav_config == NULL)
1712 sav->sav_vdevs = newvdevs;
1713 sav->sav_count = (int)nl2cache;
1716 * Recompute the stashed list of l2cache devices, with status
1717 * information this time.
1719 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1720 DATA_TYPE_NVLIST_ARRAY) == 0);
1722 l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1723 for (i = 0; i < sav->sav_count; i++)
1724 l2cache[i] = vdev_config_generate(spa,
1725 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1726 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1727 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1729 for (i = 0; i < sav->sav_count; i++)
1730 nvlist_free(l2cache[i]);
1732 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1736 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1739 char *packed = NULL;
1744 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1748 nvsize = *(uint64_t *)db->db_data;
1749 dmu_buf_rele(db, FTAG);
1751 packed = kmem_alloc(nvsize, KM_SLEEP);
1752 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1755 error = nvlist_unpack(packed, nvsize, value, 0);
1756 kmem_free(packed, nvsize);
1762 * Concrete top-level vdevs that are not missing and are not logs. At every
1763 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1766 spa_healthy_core_tvds(spa_t *spa)
1768 vdev_t *rvd = spa->spa_root_vdev;
1771 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1772 vdev_t *vd = rvd->vdev_child[i];
1775 if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1783 * Checks to see if the given vdev could not be opened, in which case we post a
1784 * sysevent to notify the autoreplace code that the device has been removed.
1787 spa_check_removed(vdev_t *vd)
1789 for (uint64_t c = 0; c < vd->vdev_children; c++)
1790 spa_check_removed(vd->vdev_child[c]);
1792 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1793 vdev_is_concrete(vd)) {
1794 zfs_post_autoreplace(vd->vdev_spa, vd);
1795 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1800 spa_check_for_missing_logs(spa_t *spa)
1802 vdev_t *rvd = spa->spa_root_vdev;
1805 * If we're doing a normal import, then build up any additional
1806 * diagnostic information about missing log devices.
1807 * We'll pass this up to the user for further processing.
1809 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1810 nvlist_t **child, *nv;
1813 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1815 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1817 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1818 vdev_t *tvd = rvd->vdev_child[c];
1821 * We consider a device as missing only if it failed
1822 * to open (i.e. offline or faulted is not considered
1825 if (tvd->vdev_islog &&
1826 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1827 child[idx++] = vdev_config_generate(spa, tvd,
1828 B_FALSE, VDEV_CONFIG_MISSING);
1833 fnvlist_add_nvlist_array(nv,
1834 ZPOOL_CONFIG_CHILDREN, child, idx);
1835 fnvlist_add_nvlist(spa->spa_load_info,
1836 ZPOOL_CONFIG_MISSING_DEVICES, nv);
1838 for (uint64_t i = 0; i < idx; i++)
1839 nvlist_free(child[i]);
1842 kmem_free(child, rvd->vdev_children * sizeof (char **));
1845 spa_load_failed(spa, "some log devices are missing");
1846 return (SET_ERROR(ENXIO));
1849 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1850 vdev_t *tvd = rvd->vdev_child[c];
1852 if (tvd->vdev_islog &&
1853 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1854 spa_set_log_state(spa, SPA_LOG_CLEAR);
1855 spa_load_note(spa, "some log devices are "
1856 "missing, ZIL is dropped.");
1866 * Check for missing log devices
1869 spa_check_logs(spa_t *spa)
1871 boolean_t rv = B_FALSE;
1872 dsl_pool_t *dp = spa_get_dsl(spa);
1874 switch (spa->spa_log_state) {
1875 case SPA_LOG_MISSING:
1876 /* need to recheck in case slog has been restored */
1877 case SPA_LOG_UNKNOWN:
1878 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1879 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
1881 spa_set_log_state(spa, SPA_LOG_MISSING);
1888 spa_passivate_log(spa_t *spa)
1890 vdev_t *rvd = spa->spa_root_vdev;
1891 boolean_t slog_found = B_FALSE;
1893 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1895 if (!spa_has_slogs(spa))
1898 for (int c = 0; c < rvd->vdev_children; c++) {
1899 vdev_t *tvd = rvd->vdev_child[c];
1900 metaslab_group_t *mg = tvd->vdev_mg;
1902 if (tvd->vdev_islog) {
1903 metaslab_group_passivate(mg);
1904 slog_found = B_TRUE;
1908 return (slog_found);
1912 spa_activate_log(spa_t *spa)
1914 vdev_t *rvd = spa->spa_root_vdev;
1916 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1918 for (int c = 0; c < rvd->vdev_children; c++) {
1919 vdev_t *tvd = rvd->vdev_child[c];
1920 metaslab_group_t *mg = tvd->vdev_mg;
1922 if (tvd->vdev_islog)
1923 metaslab_group_activate(mg);
1928 spa_reset_logs(spa_t *spa)
1932 error = dmu_objset_find(spa_name(spa), zil_reset,
1933 NULL, DS_FIND_CHILDREN);
1936 * We successfully offlined the log device, sync out the
1937 * current txg so that the "stubby" block can be removed
1940 txg_wait_synced(spa->spa_dsl_pool, 0);
1946 spa_aux_check_removed(spa_aux_vdev_t *sav)
1950 for (i = 0; i < sav->sav_count; i++)
1951 spa_check_removed(sav->sav_vdevs[i]);
1955 spa_claim_notify(zio_t *zio)
1957 spa_t *spa = zio->io_spa;
1962 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
1963 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
1964 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
1965 mutex_exit(&spa->spa_props_lock);
1968 typedef struct spa_load_error {
1969 uint64_t sle_meta_count;
1970 uint64_t sle_data_count;
1974 spa_load_verify_done(zio_t *zio)
1976 blkptr_t *bp = zio->io_bp;
1977 spa_load_error_t *sle = zio->io_private;
1978 dmu_object_type_t type = BP_GET_TYPE(bp);
1979 int error = zio->io_error;
1980 spa_t *spa = zio->io_spa;
1982 abd_free(zio->io_abd);
1984 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
1985 type != DMU_OT_INTENT_LOG)
1986 atomic_inc_64(&sle->sle_meta_count);
1988 atomic_inc_64(&sle->sle_data_count);
1991 mutex_enter(&spa->spa_scrub_lock);
1992 spa->spa_scrub_inflight--;
1993 cv_broadcast(&spa->spa_scrub_io_cv);
1994 mutex_exit(&spa->spa_scrub_lock);
1998 * Maximum number of concurrent scrub i/os to create while verifying
1999 * a pool while importing it.
2001 int spa_load_verify_maxinflight = 10000;
2002 boolean_t spa_load_verify_metadata = B_TRUE;
2003 boolean_t spa_load_verify_data = B_TRUE;
2005 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_maxinflight, CTLFLAG_RWTUN,
2006 &spa_load_verify_maxinflight, 0,
2007 "Maximum number of concurrent scrub I/Os to create while verifying a "
2008 "pool while importing it");
2010 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_metadata, CTLFLAG_RWTUN,
2011 &spa_load_verify_metadata, 0,
2012 "Check metadata on import?");
2014 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_data, CTLFLAG_RWTUN,
2015 &spa_load_verify_data, 0,
2016 "Check user data on import?");
2020 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2021 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2023 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2026 * Note: normally this routine will not be called if
2027 * spa_load_verify_metadata is not set. However, it may be useful
2028 * to manually set the flag after the traversal has begun.
2030 if (!spa_load_verify_metadata)
2032 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2036 size_t size = BP_GET_PSIZE(bp);
2038 mutex_enter(&spa->spa_scrub_lock);
2039 while (spa->spa_scrub_inflight >= spa_load_verify_maxinflight)
2040 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2041 spa->spa_scrub_inflight++;
2042 mutex_exit(&spa->spa_scrub_lock);
2044 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2045 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2046 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2047 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2053 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2055 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2056 return (SET_ERROR(ENAMETOOLONG));
2062 spa_load_verify(spa_t *spa)
2065 spa_load_error_t sle = { 0 };
2066 zpool_rewind_policy_t policy;
2067 boolean_t verify_ok = B_FALSE;
2070 zpool_get_rewind_policy(spa->spa_config, &policy);
2072 if (policy.zrp_request & ZPOOL_NEVER_REWIND)
2075 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2076 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2077 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2079 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2083 rio = zio_root(spa, NULL, &sle,
2084 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2086 if (spa_load_verify_metadata) {
2087 if (spa->spa_extreme_rewind) {
2088 spa_load_note(spa, "performing a complete scan of the "
2089 "pool since extreme rewind is on. This may take "
2090 "a very long time.\n (spa_load_verify_data=%u, "
2091 "spa_load_verify_metadata=%u)",
2092 spa_load_verify_data, spa_load_verify_metadata);
2094 error = traverse_pool(spa, spa->spa_verify_min_txg,
2095 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2096 spa_load_verify_cb, rio);
2099 (void) zio_wait(rio);
2101 spa->spa_load_meta_errors = sle.sle_meta_count;
2102 spa->spa_load_data_errors = sle.sle_data_count;
2104 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2105 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2106 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2107 (u_longlong_t)sle.sle_data_count);
2110 if (spa_load_verify_dryrun ||
2111 (!error && sle.sle_meta_count <= policy.zrp_maxmeta &&
2112 sle.sle_data_count <= policy.zrp_maxdata)) {
2116 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2117 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2119 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2120 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2121 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2122 VERIFY(nvlist_add_int64(spa->spa_load_info,
2123 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2124 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2125 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2127 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2130 if (spa_load_verify_dryrun)
2134 if (error != ENXIO && error != EIO)
2135 error = SET_ERROR(EIO);
2139 return (verify_ok ? 0 : EIO);
2143 * Find a value in the pool props object.
2146 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2148 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2149 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2153 * Find a value in the pool directory object.
2156 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2158 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2159 name, sizeof (uint64_t), 1, val);
2161 if (error != 0 && (error != ENOENT || log_enoent)) {
2162 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2163 "[error=%d]", name, error);
2170 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2172 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2173 return (SET_ERROR(err));
2177 spa_spawn_aux_threads(spa_t *spa)
2179 ASSERT(spa_writeable(spa));
2181 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2183 spa_start_indirect_condensing_thread(spa);
2187 * Fix up config after a partly-completed split. This is done with the
2188 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2189 * pool have that entry in their config, but only the splitting one contains
2190 * a list of all the guids of the vdevs that are being split off.
2192 * This function determines what to do with that list: either rejoin
2193 * all the disks to the pool, or complete the splitting process. To attempt
2194 * the rejoin, each disk that is offlined is marked online again, and
2195 * we do a reopen() call. If the vdev label for every disk that was
2196 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2197 * then we call vdev_split() on each disk, and complete the split.
2199 * Otherwise we leave the config alone, with all the vdevs in place in
2200 * the original pool.
2203 spa_try_repair(spa_t *spa, nvlist_t *config)
2210 boolean_t attempt_reopen;
2212 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2215 /* check that the config is complete */
2216 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2217 &glist, &gcount) != 0)
2220 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2222 /* attempt to online all the vdevs & validate */
2223 attempt_reopen = B_TRUE;
2224 for (i = 0; i < gcount; i++) {
2225 if (glist[i] == 0) /* vdev is hole */
2228 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2229 if (vd[i] == NULL) {
2231 * Don't bother attempting to reopen the disks;
2232 * just do the split.
2234 attempt_reopen = B_FALSE;
2236 /* attempt to re-online it */
2237 vd[i]->vdev_offline = B_FALSE;
2241 if (attempt_reopen) {
2242 vdev_reopen(spa->spa_root_vdev);
2244 /* check each device to see what state it's in */
2245 for (extracted = 0, i = 0; i < gcount; i++) {
2246 if (vd[i] != NULL &&
2247 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2254 * If every disk has been moved to the new pool, or if we never
2255 * even attempted to look at them, then we split them off for
2258 if (!attempt_reopen || gcount == extracted) {
2259 for (i = 0; i < gcount; i++)
2262 vdev_reopen(spa->spa_root_vdev);
2265 kmem_free(vd, gcount * sizeof (vdev_t *));
2269 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2271 char *ereport = FM_EREPORT_ZFS_POOL;
2274 spa->spa_load_state = state;
2276 gethrestime(&spa->spa_loaded_ts);
2277 error = spa_load_impl(spa, type, &ereport, B_FALSE);
2280 * Don't count references from objsets that are already closed
2281 * and are making their way through the eviction process.
2283 spa_evicting_os_wait(spa);
2284 spa->spa_minref = refcount_count(&spa->spa_refcount);
2286 if (error != EEXIST) {
2287 spa->spa_loaded_ts.tv_sec = 0;
2288 spa->spa_loaded_ts.tv_nsec = 0;
2290 if (error != EBADF) {
2291 zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2294 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2301 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2302 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2303 * spa's per-vdev ZAP list.
2306 vdev_count_verify_zaps(vdev_t *vd)
2308 spa_t *spa = vd->vdev_spa;
2310 if (vd->vdev_top_zap != 0) {
2312 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2313 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2315 if (vd->vdev_leaf_zap != 0) {
2317 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2318 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2321 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2322 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2329 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2333 uint64_t myhostid = 0;
2335 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2336 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2337 hostname = fnvlist_lookup_string(mos_config,
2338 ZPOOL_CONFIG_HOSTNAME);
2340 myhostid = zone_get_hostid(NULL);
2342 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2343 cmn_err(CE_WARN, "pool '%s' could not be "
2344 "loaded as it was last accessed by "
2345 "another system (host: %s hostid: 0x%llx). "
2346 "See: http://illumos.org/msg/ZFS-8000-EY",
2347 spa_name(spa), hostname, (u_longlong_t)hostid);
2348 spa_load_failed(spa, "hostid verification failed: pool "
2349 "last accessed by host: %s (hostid: 0x%llx)",
2350 hostname, (u_longlong_t)hostid);
2351 return (SET_ERROR(EBADF));
2359 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2362 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2369 * Versioning wasn't explicitly added to the label until later, so if
2370 * it's not present treat it as the initial version.
2372 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2373 &spa->spa_ubsync.ub_version) != 0)
2374 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2376 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2377 spa_load_failed(spa, "invalid config provided: '%s' missing",
2378 ZPOOL_CONFIG_POOL_GUID);
2379 return (SET_ERROR(EINVAL));
2382 if ((spa->spa_load_state == SPA_LOAD_IMPORT || spa->spa_load_state ==
2383 SPA_LOAD_TRYIMPORT) && spa_guid_exists(pool_guid, 0)) {
2384 spa_load_failed(spa, "a pool with guid %llu is already open",
2385 (u_longlong_t)pool_guid);
2386 return (SET_ERROR(EEXIST));
2389 spa->spa_config_guid = pool_guid;
2391 nvlist_free(spa->spa_load_info);
2392 spa->spa_load_info = fnvlist_alloc();
2394 ASSERT(spa->spa_comment == NULL);
2395 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2396 spa->spa_comment = spa_strdup(comment);
2398 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2399 &spa->spa_config_txg);
2401 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2402 spa->spa_config_splitting = fnvlist_dup(nvl);
2404 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2405 spa_load_failed(spa, "invalid config provided: '%s' missing",
2406 ZPOOL_CONFIG_VDEV_TREE);
2407 return (SET_ERROR(EINVAL));
2411 * Create "The Godfather" zio to hold all async IOs
2413 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2415 for (int i = 0; i < max_ncpus; i++) {
2416 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2417 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2418 ZIO_FLAG_GODFATHER);
2422 * Parse the configuration into a vdev tree. We explicitly set the
2423 * value that will be returned by spa_version() since parsing the
2424 * configuration requires knowing the version number.
2426 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2427 parse = (type == SPA_IMPORT_EXISTING ?
2428 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2429 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2430 spa_config_exit(spa, SCL_ALL, FTAG);
2433 spa_load_failed(spa, "unable to parse config [error=%d]",
2438 ASSERT(spa->spa_root_vdev == rvd);
2439 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2440 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2442 if (type != SPA_IMPORT_ASSEMBLE) {
2443 ASSERT(spa_guid(spa) == pool_guid);
2450 * Recursively open all vdevs in the vdev tree. This function is called twice:
2451 * first with the untrusted config, then with the trusted config.
2454 spa_ld_open_vdevs(spa_t *spa)
2459 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2460 * missing/unopenable for the root vdev to be still considered openable.
2462 if (spa->spa_trust_config) {
2463 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2464 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2465 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2466 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2467 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2469 spa->spa_missing_tvds_allowed = 0;
2472 spa->spa_missing_tvds_allowed =
2473 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2475 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2476 error = vdev_open(spa->spa_root_vdev);
2477 spa_config_exit(spa, SCL_ALL, FTAG);
2479 if (spa->spa_missing_tvds != 0) {
2480 spa_load_note(spa, "vdev tree has %lld missing top-level "
2481 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2482 if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2484 * Although theoretically we could allow users to open
2485 * incomplete pools in RW mode, we'd need to add a lot
2486 * of extra logic (e.g. adjust pool space to account
2487 * for missing vdevs).
2488 * This limitation also prevents users from accidentally
2489 * opening the pool in RW mode during data recovery and
2490 * damaging it further.
2492 spa_load_note(spa, "pools with missing top-level "
2493 "vdevs can only be opened in read-only mode.");
2494 error = SET_ERROR(ENXIO);
2496 spa_load_note(spa, "current settings allow for maximum "
2497 "%lld missing top-level vdevs at this stage.",
2498 (u_longlong_t)spa->spa_missing_tvds_allowed);
2502 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2505 if (spa->spa_missing_tvds != 0 || error != 0)
2506 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2512 * We need to validate the vdev labels against the configuration that
2513 * we have in hand. This function is called twice: first with an untrusted
2514 * config, then with a trusted config. The validation is more strict when the
2515 * config is trusted.
2518 spa_ld_validate_vdevs(spa_t *spa)
2521 vdev_t *rvd = spa->spa_root_vdev;
2523 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2524 error = vdev_validate(rvd);
2525 spa_config_exit(spa, SCL_ALL, FTAG);
2528 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2532 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2533 spa_load_failed(spa, "cannot open vdev tree after invalidating "
2535 vdev_dbgmsg_print_tree(rvd, 2);
2536 return (SET_ERROR(ENXIO));
2543 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2545 vdev_t *rvd = spa->spa_root_vdev;
2547 uberblock_t *ub = &spa->spa_uberblock;
2550 * Find the best uberblock.
2552 vdev_uberblock_load(rvd, ub, &label);
2555 * If we weren't able to find a single valid uberblock, return failure.
2557 if (ub->ub_txg == 0) {
2559 spa_load_failed(spa, "no valid uberblock found");
2560 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2563 spa_load_note(spa, "using uberblock with txg=%llu",
2564 (u_longlong_t)ub->ub_txg);
2567 * If the pool has an unsupported version we can't open it.
2569 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2571 spa_load_failed(spa, "version %llu is not supported",
2572 (u_longlong_t)ub->ub_version);
2573 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2576 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2580 * If we weren't able to find what's necessary for reading the
2581 * MOS in the label, return failure.
2583 if (label == NULL) {
2584 spa_load_failed(spa, "label config unavailable");
2585 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2589 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
2592 spa_load_failed(spa, "invalid label: '%s' missing",
2593 ZPOOL_CONFIG_FEATURES_FOR_READ);
2594 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2599 * Update our in-core representation with the definitive values
2602 nvlist_free(spa->spa_label_features);
2603 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2609 * Look through entries in the label nvlist's features_for_read. If
2610 * there is a feature listed there which we don't understand then we
2611 * cannot open a pool.
2613 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2614 nvlist_t *unsup_feat;
2616 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2619 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2621 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2622 if (!zfeature_is_supported(nvpair_name(nvp))) {
2623 VERIFY(nvlist_add_string(unsup_feat,
2624 nvpair_name(nvp), "") == 0);
2628 if (!nvlist_empty(unsup_feat)) {
2629 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2630 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2631 nvlist_free(unsup_feat);
2632 spa_load_failed(spa, "some features are unsupported");
2633 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2637 nvlist_free(unsup_feat);
2640 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2641 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2642 spa_try_repair(spa, spa->spa_config);
2643 spa_config_exit(spa, SCL_ALL, FTAG);
2644 nvlist_free(spa->spa_config_splitting);
2645 spa->spa_config_splitting = NULL;
2649 * Initialize internal SPA structures.
2651 spa->spa_state = POOL_STATE_ACTIVE;
2652 spa->spa_ubsync = spa->spa_uberblock;
2653 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2654 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2655 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2656 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2657 spa->spa_claim_max_txg = spa->spa_first_txg;
2658 spa->spa_prev_software_version = ub->ub_software_version;
2664 spa_ld_open_rootbp(spa_t *spa)
2667 vdev_t *rvd = spa->spa_root_vdev;
2669 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2671 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
2672 "[error=%d]", error);
2673 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2675 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2681 spa_ld_load_trusted_config(spa_t *spa, spa_import_type_t type,
2682 boolean_t reloading)
2684 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
2685 nvlist_t *nv, *mos_config, *policy;
2686 int error = 0, copy_error;
2687 uint64_t healthy_tvds, healthy_tvds_mos;
2688 uint64_t mos_config_txg;
2690 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
2692 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2695 * If we're assembling a pool from a split, the config provided is
2696 * already trusted so there is nothing to do.
2698 if (type == SPA_IMPORT_ASSEMBLE)
2701 healthy_tvds = spa_healthy_core_tvds(spa);
2703 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
2705 spa_load_failed(spa, "unable to retrieve MOS config");
2706 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2710 * If we are doing an open, pool owner wasn't verified yet, thus do
2711 * the verification here.
2713 if (spa->spa_load_state == SPA_LOAD_OPEN) {
2714 error = spa_verify_host(spa, mos_config);
2716 nvlist_free(mos_config);
2721 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
2723 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2726 * Build a new vdev tree from the trusted config
2728 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
2731 * Vdev paths in the MOS may be obsolete. If the untrusted config was
2732 * obtained by scanning /dev/dsk, then it will have the right vdev
2733 * paths. We update the trusted MOS config with this information.
2734 * We first try to copy the paths with vdev_copy_path_strict, which
2735 * succeeds only when both configs have exactly the same vdev tree.
2736 * If that fails, we fall back to a more flexible method that has a
2737 * best effort policy.
2739 copy_error = vdev_copy_path_strict(rvd, mrvd);
2740 if (copy_error != 0 || spa_load_print_vdev_tree) {
2741 spa_load_note(spa, "provided vdev tree:");
2742 vdev_dbgmsg_print_tree(rvd, 2);
2743 spa_load_note(spa, "MOS vdev tree:");
2744 vdev_dbgmsg_print_tree(mrvd, 2);
2746 if (copy_error != 0) {
2747 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
2748 "back to vdev_copy_path_relaxed");
2749 vdev_copy_path_relaxed(rvd, mrvd);
2754 spa->spa_root_vdev = mrvd;
2756 spa_config_exit(spa, SCL_ALL, FTAG);
2759 * We will use spa_config if we decide to reload the spa or if spa_load
2760 * fails and we rewind. We must thus regenerate the config using the
2761 * MOS information with the updated paths. Rewind policy is an import
2762 * setting and is not in the MOS. We copy it over to our new, trusted
2765 mos_config_txg = fnvlist_lookup_uint64(mos_config,
2766 ZPOOL_CONFIG_POOL_TXG);
2767 nvlist_free(mos_config);
2768 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
2769 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_REWIND_POLICY,
2771 fnvlist_add_nvlist(mos_config, ZPOOL_REWIND_POLICY, policy);
2772 spa_config_set(spa, mos_config);
2773 spa->spa_config_source = SPA_CONFIG_SRC_MOS;
2776 * Now that we got the config from the MOS, we should be more strict
2777 * in checking blkptrs and can make assumptions about the consistency
2778 * of the vdev tree. spa_trust_config must be set to true before opening
2779 * vdevs in order for them to be writeable.
2781 spa->spa_trust_config = B_TRUE;
2784 * Open and validate the new vdev tree
2786 error = spa_ld_open_vdevs(spa);
2790 error = spa_ld_validate_vdevs(spa);
2794 if (copy_error != 0 || spa_load_print_vdev_tree) {
2795 spa_load_note(spa, "final vdev tree:");
2796 vdev_dbgmsg_print_tree(rvd, 2);
2799 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
2800 !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
2802 * Sanity check to make sure that we are indeed loading the
2803 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
2804 * in the config provided and they happened to be the only ones
2805 * to have the latest uberblock, we could involuntarily perform
2806 * an extreme rewind.
2808 healthy_tvds_mos = spa_healthy_core_tvds(spa);
2809 if (healthy_tvds_mos - healthy_tvds >=
2810 SPA_SYNC_MIN_VDEVS) {
2811 spa_load_note(spa, "config provided misses too many "
2812 "top-level vdevs compared to MOS (%lld vs %lld). ",
2813 (u_longlong_t)healthy_tvds,
2814 (u_longlong_t)healthy_tvds_mos);
2815 spa_load_note(spa, "vdev tree:");
2816 vdev_dbgmsg_print_tree(rvd, 2);
2818 spa_load_failed(spa, "config was already "
2819 "provided from MOS. Aborting.");
2820 return (spa_vdev_err(rvd,
2821 VDEV_AUX_CORRUPT_DATA, EIO));
2823 spa_load_note(spa, "spa must be reloaded using MOS "
2825 return (SET_ERROR(EAGAIN));
2829 error = spa_check_for_missing_logs(spa);
2831 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2833 if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
2834 spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
2835 "guid sum (%llu != %llu)",
2836 (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
2837 (u_longlong_t)rvd->vdev_guid_sum);
2838 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
2846 spa_ld_open_indirect_vdev_metadata(spa_t *spa)
2849 vdev_t *rvd = spa->spa_root_vdev;
2852 * Everything that we read before spa_remove_init() must be stored
2853 * on concreted vdevs. Therefore we do this as early as possible.
2855 error = spa_remove_init(spa);
2857 spa_load_failed(spa, "spa_remove_init failed [error=%d]",
2859 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2863 * Retrieve information needed to condense indirect vdev mappings.
2865 error = spa_condense_init(spa);
2867 spa_load_failed(spa, "spa_condense_init failed [error=%d]",
2869 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
2876 spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
2879 vdev_t *rvd = spa->spa_root_vdev;
2881 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2882 boolean_t missing_feat_read = B_FALSE;
2883 nvlist_t *unsup_feat, *enabled_feat;
2885 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
2886 &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
2887 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2890 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
2891 &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
2892 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2895 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
2896 &spa->spa_feat_desc_obj, B_TRUE) != 0) {
2897 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2900 enabled_feat = fnvlist_alloc();
2901 unsup_feat = fnvlist_alloc();
2903 if (!spa_features_check(spa, B_FALSE,
2904 unsup_feat, enabled_feat))
2905 missing_feat_read = B_TRUE;
2907 if (spa_writeable(spa) ||
2908 spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
2909 if (!spa_features_check(spa, B_TRUE,
2910 unsup_feat, enabled_feat)) {
2911 *missing_feat_writep = B_TRUE;
2915 fnvlist_add_nvlist(spa->spa_load_info,
2916 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
2918 if (!nvlist_empty(unsup_feat)) {
2919 fnvlist_add_nvlist(spa->spa_load_info,
2920 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
2923 fnvlist_free(enabled_feat);
2924 fnvlist_free(unsup_feat);
2926 if (!missing_feat_read) {
2927 fnvlist_add_boolean(spa->spa_load_info,
2928 ZPOOL_CONFIG_CAN_RDONLY);
2932 * If the state is SPA_LOAD_TRYIMPORT, our objective is
2933 * twofold: to determine whether the pool is available for
2934 * import in read-write mode and (if it is not) whether the
2935 * pool is available for import in read-only mode. If the pool
2936 * is available for import in read-write mode, it is displayed
2937 * as available in userland; if it is not available for import
2938 * in read-only mode, it is displayed as unavailable in
2939 * userland. If the pool is available for import in read-only
2940 * mode but not read-write mode, it is displayed as unavailable
2941 * in userland with a special note that the pool is actually
2942 * available for open in read-only mode.
2944 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
2945 * missing a feature for write, we must first determine whether
2946 * the pool can be opened read-only before returning to
2947 * userland in order to know whether to display the
2948 * abovementioned note.
2950 if (missing_feat_read || (*missing_feat_writep &&
2951 spa_writeable(spa))) {
2952 spa_load_failed(spa, "pool uses unsupported features");
2953 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2958 * Load refcounts for ZFS features from disk into an in-memory
2959 * cache during SPA initialization.
2961 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
2964 error = feature_get_refcount_from_disk(spa,
2965 &spa_feature_table[i], &refcount);
2967 spa->spa_feat_refcount_cache[i] = refcount;
2968 } else if (error == ENOTSUP) {
2969 spa->spa_feat_refcount_cache[i] =
2970 SPA_FEATURE_DISABLED;
2972 spa_load_failed(spa, "error getting refcount "
2973 "for feature %s [error=%d]",
2974 spa_feature_table[i].fi_guid, error);
2975 return (spa_vdev_err(rvd,
2976 VDEV_AUX_CORRUPT_DATA, EIO));
2981 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
2982 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
2983 &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
2984 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2991 spa_ld_load_special_directories(spa_t *spa)
2994 vdev_t *rvd = spa->spa_root_vdev;
2996 spa->spa_is_initializing = B_TRUE;
2997 error = dsl_pool_open(spa->spa_dsl_pool);
2998 spa->spa_is_initializing = B_FALSE;
3000 spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3001 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3008 spa_ld_get_props(spa_t *spa)
3012 vdev_t *rvd = spa->spa_root_vdev;
3014 /* Grab the secret checksum salt from the MOS. */
3015 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3016 DMU_POOL_CHECKSUM_SALT, 1,
3017 sizeof (spa->spa_cksum_salt.zcs_bytes),
3018 spa->spa_cksum_salt.zcs_bytes);
3019 if (error == ENOENT) {
3020 /* Generate a new salt for subsequent use */
3021 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3022 sizeof (spa->spa_cksum_salt.zcs_bytes));
3023 } else if (error != 0) {
3024 spa_load_failed(spa, "unable to retrieve checksum salt from "
3025 "MOS [error=%d]", error);
3026 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3029 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3030 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3031 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3033 spa_load_failed(spa, "error opening deferred-frees bpobj "
3034 "[error=%d]", error);
3035 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3039 * Load the bit that tells us to use the new accounting function
3040 * (raid-z deflation). If we have an older pool, this will not
3043 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3044 if (error != 0 && error != ENOENT)
3045 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3047 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3048 &spa->spa_creation_version, B_FALSE);
3049 if (error != 0 && error != ENOENT)
3050 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3053 * Load the persistent error log. If we have an older pool, this will
3056 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3058 if (error != 0 && error != ENOENT)
3059 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3061 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3062 &spa->spa_errlog_scrub, B_FALSE);
3063 if (error != 0 && error != ENOENT)
3064 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3067 * Load the history object. If we have an older pool, this
3068 * will not be present.
3070 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3071 if (error != 0 && error != ENOENT)
3072 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3075 * Load the per-vdev ZAP map. If we have an older pool, this will not
3076 * be present; in this case, defer its creation to a later time to
3077 * avoid dirtying the MOS this early / out of sync context. See
3078 * spa_sync_config_object.
3081 /* The sentinel is only available in the MOS config. */
3082 nvlist_t *mos_config;
3083 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3084 spa_load_failed(spa, "unable to retrieve MOS config");
3085 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3088 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3089 &spa->spa_all_vdev_zaps, B_FALSE);
3091 if (error == ENOENT) {
3092 VERIFY(!nvlist_exists(mos_config,
3093 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3094 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3095 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3096 } else if (error != 0) {
3097 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3098 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3100 * An older version of ZFS overwrote the sentinel value, so
3101 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3102 * destruction to later; see spa_sync_config_object.
3104 spa->spa_avz_action = AVZ_ACTION_DESTROY;
3106 * We're assuming that no vdevs have had their ZAPs created
3107 * before this. Better be sure of it.
3109 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3111 nvlist_free(mos_config);
3113 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3115 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3117 if (error && error != ENOENT)
3118 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3121 uint64_t autoreplace;
3123 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3124 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3125 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3126 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3127 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3128 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3129 &spa->spa_dedup_ditto);
3131 spa->spa_autoreplace = (autoreplace != 0);
3135 * If we are importing a pool with missing top-level vdevs,
3136 * we enforce that the pool doesn't panic or get suspended on
3137 * error since the likelihood of missing data is extremely high.
3139 if (spa->spa_missing_tvds > 0 &&
3140 spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3141 spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3142 spa_load_note(spa, "forcing failmode to 'continue' "
3143 "as some top level vdevs are missing");
3144 spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3151 spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3154 vdev_t *rvd = spa->spa_root_vdev;
3157 * If we're assembling the pool from the split-off vdevs of
3158 * an existing pool, we don't want to attach the spares & cache
3163 * Load any hot spares for this pool.
3165 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3167 if (error != 0 && error != ENOENT)
3168 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3169 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3170 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3171 if (load_nvlist(spa, spa->spa_spares.sav_object,
3172 &spa->spa_spares.sav_config) != 0) {
3173 spa_load_failed(spa, "error loading spares nvlist");
3174 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3177 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3178 spa_load_spares(spa);
3179 spa_config_exit(spa, SCL_ALL, FTAG);
3180 } else if (error == 0) {
3181 spa->spa_spares.sav_sync = B_TRUE;
3185 * Load any level 2 ARC devices for this pool.
3187 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3188 &spa->spa_l2cache.sav_object, B_FALSE);
3189 if (error != 0 && error != ENOENT)
3190 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3191 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3192 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3193 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3194 &spa->spa_l2cache.sav_config) != 0) {
3195 spa_load_failed(spa, "error loading l2cache nvlist");
3196 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3199 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3200 spa_load_l2cache(spa);
3201 spa_config_exit(spa, SCL_ALL, FTAG);
3202 } else if (error == 0) {
3203 spa->spa_l2cache.sav_sync = B_TRUE;
3210 spa_ld_load_vdev_metadata(spa_t *spa)
3213 vdev_t *rvd = spa->spa_root_vdev;
3216 * If the 'autoreplace' property is set, then post a resource notifying
3217 * the ZFS DE that it should not issue any faults for unopenable
3218 * devices. We also iterate over the vdevs, and post a sysevent for any
3219 * unopenable vdevs so that the normal autoreplace handler can take
3222 if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3223 spa_check_removed(spa->spa_root_vdev);
3225 * For the import case, this is done in spa_import(), because
3226 * at this point we're using the spare definitions from
3227 * the MOS config, not necessarily from the userland config.
3229 if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3230 spa_aux_check_removed(&spa->spa_spares);
3231 spa_aux_check_removed(&spa->spa_l2cache);
3236 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3238 error = vdev_load(rvd);
3240 spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3241 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3245 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3247 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3248 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3249 spa_config_exit(spa, SCL_ALL, FTAG);
3255 spa_ld_load_dedup_tables(spa_t *spa)
3258 vdev_t *rvd = spa->spa_root_vdev;
3260 error = ddt_load(spa);
3262 spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3263 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3270 spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3272 vdev_t *rvd = spa->spa_root_vdev;
3274 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3275 boolean_t missing = spa_check_logs(spa);
3277 if (spa->spa_missing_tvds != 0) {
3278 spa_load_note(spa, "spa_check_logs failed "
3279 "so dropping the logs");
3281 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3282 spa_load_failed(spa, "spa_check_logs failed");
3283 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3293 spa_ld_verify_pool_data(spa_t *spa)
3296 vdev_t *rvd = spa->spa_root_vdev;
3299 * We've successfully opened the pool, verify that we're ready
3300 * to start pushing transactions.
3302 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3303 error = spa_load_verify(spa);
3305 spa_load_failed(spa, "spa_load_verify failed "
3306 "[error=%d]", error);
3307 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3316 spa_ld_claim_log_blocks(spa_t *spa)
3319 dsl_pool_t *dp = spa_get_dsl(spa);
3322 * Claim log blocks that haven't been committed yet.
3323 * This must all happen in a single txg.
3324 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3325 * invoked from zil_claim_log_block()'s i/o done callback.
3326 * Price of rollback is that we abandon the log.
3328 spa->spa_claiming = B_TRUE;
3330 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3331 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3332 zil_claim, tx, DS_FIND_CHILDREN);
3335 spa->spa_claiming = B_FALSE;
3337 spa_set_log_state(spa, SPA_LOG_GOOD);
3341 spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3342 boolean_t reloading)
3344 vdev_t *rvd = spa->spa_root_vdev;
3345 int need_update = B_FALSE;
3348 * If the config cache is stale, or we have uninitialized
3349 * metaslabs (see spa_vdev_add()), then update the config.
3351 * If this is a verbatim import, trust the current
3352 * in-core spa_config and update the disk labels.
3354 if (reloading || config_cache_txg != spa->spa_config_txg ||
3355 spa->spa_load_state == SPA_LOAD_IMPORT ||
3356 spa->spa_load_state == SPA_LOAD_RECOVER ||
3357 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3358 need_update = B_TRUE;
3360 for (int c = 0; c < rvd->vdev_children; c++)
3361 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3362 need_update = B_TRUE;
3365 * Update the config cache asychronously in case we're the
3366 * root pool, in which case the config cache isn't writable yet.
3369 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3373 spa_ld_prepare_for_reload(spa_t *spa)
3375 int mode = spa->spa_mode;
3376 int async_suspended = spa->spa_async_suspended;
3379 spa_deactivate(spa);
3380 spa_activate(spa, mode);
3383 * We save the value of spa_async_suspended as it gets reset to 0 by
3384 * spa_unload(). We want to restore it back to the original value before
3385 * returning as we might be calling spa_async_resume() later.
3387 spa->spa_async_suspended = async_suspended;
3391 * Load an existing storage pool, using the config provided. This config
3392 * describes which vdevs are part of the pool and is later validated against
3393 * partial configs present in each vdev's label and an entire copy of the
3394 * config stored in the MOS.
3397 spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport,
3398 boolean_t reloading)
3401 boolean_t missing_feat_write = B_FALSE;
3403 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3404 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3407 * Never trust the config that is provided unless we are assembling
3408 * a pool following a split.
3409 * This means don't trust blkptrs and the vdev tree in general. This
3410 * also effectively puts the spa in read-only mode since
3411 * spa_writeable() checks for spa_trust_config to be true.
3412 * We will later load a trusted config from the MOS.
3414 if (type != SPA_IMPORT_ASSEMBLE)
3415 spa->spa_trust_config = B_FALSE;
3418 spa_load_note(spa, "RELOADING");
3420 spa_load_note(spa, "LOADING");
3423 * Parse the config provided to create a vdev tree.
3425 error = spa_ld_parse_config(spa, type);
3430 * Now that we have the vdev tree, try to open each vdev. This involves
3431 * opening the underlying physical device, retrieving its geometry and
3432 * probing the vdev with a dummy I/O. The state of each vdev will be set
3433 * based on the success of those operations. After this we'll be ready
3434 * to read from the vdevs.
3436 error = spa_ld_open_vdevs(spa);
3441 * Read the label of each vdev and make sure that the GUIDs stored
3442 * there match the GUIDs in the config provided.
3443 * If we're assembling a new pool that's been split off from an
3444 * existing pool, the labels haven't yet been updated so we skip
3445 * validation for now.
3447 if (type != SPA_IMPORT_ASSEMBLE) {
3448 error = spa_ld_validate_vdevs(spa);
3454 * Read vdev labels to find the best uberblock (i.e. latest, unless
3455 * spa_load_max_txg is set) and store it in spa_uberblock. We get the
3456 * list of features required to read blkptrs in the MOS from the vdev
3457 * label with the best uberblock and verify that our version of zfs
3458 * supports them all.
3460 error = spa_ld_select_uberblock(spa, type);
3465 * Pass that uberblock to the dsl_pool layer which will open the root
3466 * blkptr. This blkptr points to the latest version of the MOS and will
3467 * allow us to read its contents.
3469 error = spa_ld_open_rootbp(spa);
3474 * Retrieve the trusted config stored in the MOS and use it to create
3475 * a new, exact version of the vdev tree, then reopen all vdevs.
3477 error = spa_ld_load_trusted_config(spa, type, reloading);
3478 if (error == EAGAIN) {
3481 * Redo the loading process with the trusted config if it is
3482 * too different from the untrusted config.
3484 spa_ld_prepare_for_reload(spa);
3485 return (spa_load_impl(spa, type, ereport, B_TRUE));
3486 } else if (error != 0) {
3491 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
3492 * from the pool and their contents were re-mapped to other vdevs. Note
3493 * that everything that we read before this step must have been
3494 * rewritten on concrete vdevs after the last device removal was
3495 * initiated. Otherwise we could be reading from indirect vdevs before
3496 * we have loaded their mappings.
3498 error = spa_ld_open_indirect_vdev_metadata(spa);
3503 * Retrieve the full list of active features from the MOS and check if
3504 * they are all supported.
3506 error = spa_ld_check_features(spa, &missing_feat_write);
3511 * Load several special directories from the MOS needed by the dsl_pool
3514 error = spa_ld_load_special_directories(spa);
3519 * Retrieve pool properties from the MOS.
3521 error = spa_ld_get_props(spa);
3526 * Retrieve the list of auxiliary devices - cache devices and spares -
3529 error = spa_ld_open_aux_vdevs(spa, type);
3534 * Load the metadata for all vdevs. Also check if unopenable devices
3535 * should be autoreplaced.
3537 error = spa_ld_load_vdev_metadata(spa);
3541 error = spa_ld_load_dedup_tables(spa);
3546 * Verify the logs now to make sure we don't have any unexpected errors
3547 * when we claim log blocks later.
3549 error = spa_ld_verify_logs(spa, type, ereport);
3553 if (missing_feat_write) {
3554 ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
3557 * At this point, we know that we can open the pool in
3558 * read-only mode but not read-write mode. We now have enough
3559 * information and can return to userland.
3561 return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
3566 * Traverse the last txgs to make sure the pool was left off in a safe
3567 * state. When performing an extreme rewind, we verify the whole pool,
3568 * which can take a very long time.
3570 error = spa_ld_verify_pool_data(spa);
3575 * Calculate the deflated space for the pool. This must be done before
3576 * we write anything to the pool because we'd need to update the space
3577 * accounting using the deflated sizes.
3579 spa_update_dspace(spa);
3582 * We have now retrieved all the information we needed to open the
3583 * pool. If we are importing the pool in read-write mode, a few
3584 * additional steps must be performed to finish the import.
3586 if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
3587 spa->spa_load_max_txg == UINT64_MAX)) {
3588 uint64_t config_cache_txg = spa->spa_config_txg;
3590 ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
3593 * Traverse the ZIL and claim all blocks.
3595 spa_ld_claim_log_blocks(spa);
3598 * Kick-off the syncing thread.
3600 spa->spa_sync_on = B_TRUE;
3601 txg_sync_start(spa->spa_dsl_pool);
3604 * Wait for all claims to sync. We sync up to the highest
3605 * claimed log block birth time so that claimed log blocks
3606 * don't appear to be from the future. spa_claim_max_txg
3607 * will have been set for us by ZIL traversal operations
3610 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
3613 * Check if we need to request an update of the config. On the
3614 * next sync, we would update the config stored in vdev labels
3615 * and the cachefile (by default /etc/zfs/zpool.cache).
3617 spa_ld_check_for_config_update(spa, config_cache_txg,
3621 * Check all DTLs to see if anything needs resilvering.
3623 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
3624 vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
3625 spa_async_request(spa, SPA_ASYNC_RESILVER);
3628 * Log the fact that we booted up (so that we can detect if
3629 * we rebooted in the middle of an operation).
3631 spa_history_log_version(spa, "open");
3634 * Delete any inconsistent datasets.
3636 (void) dmu_objset_find(spa_name(spa),
3637 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
3640 * Clean up any stale temporary dataset userrefs.
3642 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
3644 spa_restart_removal(spa);
3646 spa_spawn_aux_threads(spa);
3649 spa_load_note(spa, "LOADED");
3655 spa_load_retry(spa_t *spa, spa_load_state_t state)
3657 int mode = spa->spa_mode;
3660 spa_deactivate(spa);
3662 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
3664 spa_activate(spa, mode);
3665 spa_async_suspend(spa);
3667 spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
3668 (u_longlong_t)spa->spa_load_max_txg);
3670 return (spa_load(spa, state, SPA_IMPORT_EXISTING));
3674 * If spa_load() fails this function will try loading prior txg's. If
3675 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
3676 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
3677 * function will not rewind the pool and will return the same error as
3681 spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
3684 nvlist_t *loadinfo = NULL;
3685 nvlist_t *config = NULL;
3686 int load_error, rewind_error;
3687 uint64_t safe_rewind_txg;
3690 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
3691 spa->spa_load_max_txg = spa->spa_load_txg;
3692 spa_set_log_state(spa, SPA_LOG_CLEAR);
3694 spa->spa_load_max_txg = max_request;
3695 if (max_request != UINT64_MAX)
3696 spa->spa_extreme_rewind = B_TRUE;
3699 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
3700 if (load_error == 0)
3703 if (spa->spa_root_vdev != NULL)
3704 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
3706 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
3707 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
3709 if (rewind_flags & ZPOOL_NEVER_REWIND) {
3710 nvlist_free(config);
3711 return (load_error);
3714 if (state == SPA_LOAD_RECOVER) {
3715 /* Price of rolling back is discarding txgs, including log */
3716 spa_set_log_state(spa, SPA_LOG_CLEAR);
3719 * If we aren't rolling back save the load info from our first
3720 * import attempt so that we can restore it after attempting
3723 loadinfo = spa->spa_load_info;
3724 spa->spa_load_info = fnvlist_alloc();
3727 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
3728 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
3729 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
3730 TXG_INITIAL : safe_rewind_txg;
3733 * Continue as long as we're finding errors, we're still within
3734 * the acceptable rewind range, and we're still finding uberblocks
3736 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
3737 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
3738 if (spa->spa_load_max_txg < safe_rewind_txg)
3739 spa->spa_extreme_rewind = B_TRUE;
3740 rewind_error = spa_load_retry(spa, state);
3743 spa->spa_extreme_rewind = B_FALSE;
3744 spa->spa_load_max_txg = UINT64_MAX;
3746 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
3747 spa_config_set(spa, config);
3749 nvlist_free(config);
3751 if (state == SPA_LOAD_RECOVER) {
3752 ASSERT3P(loadinfo, ==, NULL);
3753 return (rewind_error);
3755 /* Store the rewind info as part of the initial load info */
3756 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
3757 spa->spa_load_info);
3759 /* Restore the initial load info */
3760 fnvlist_free(spa->spa_load_info);
3761 spa->spa_load_info = loadinfo;
3763 return (load_error);
3770 * The import case is identical to an open except that the configuration is sent
3771 * down from userland, instead of grabbed from the configuration cache. For the
3772 * case of an open, the pool configuration will exist in the
3773 * POOL_STATE_UNINITIALIZED state.
3775 * The stats information (gen/count/ustats) is used to gather vdev statistics at
3776 * the same time open the pool, without having to keep around the spa_t in some
3780 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
3784 spa_load_state_t state = SPA_LOAD_OPEN;
3786 int locked = B_FALSE;
3787 int firstopen = B_FALSE;
3792 * As disgusting as this is, we need to support recursive calls to this
3793 * function because dsl_dir_open() is called during spa_load(), and ends
3794 * up calling spa_open() again. The real fix is to figure out how to
3795 * avoid dsl_dir_open() calling this in the first place.
3797 if (mutex_owner(&spa_namespace_lock) != curthread) {
3798 mutex_enter(&spa_namespace_lock);
3802 if ((spa = spa_lookup(pool)) == NULL) {
3804 mutex_exit(&spa_namespace_lock);
3805 return (SET_ERROR(ENOENT));
3808 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
3809 zpool_rewind_policy_t policy;
3813 zpool_get_rewind_policy(nvpolicy ? nvpolicy : spa->spa_config,
3815 if (policy.zrp_request & ZPOOL_DO_REWIND)
3816 state = SPA_LOAD_RECOVER;
3818 spa_activate(spa, spa_mode_global);
3820 if (state != SPA_LOAD_RECOVER)
3821 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
3822 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
3824 zfs_dbgmsg("spa_open_common: opening %s", pool);
3825 error = spa_load_best(spa, state, policy.zrp_txg,
3826 policy.zrp_request);
3828 if (error == EBADF) {
3830 * If vdev_validate() returns failure (indicated by
3831 * EBADF), it indicates that one of the vdevs indicates
3832 * that the pool has been exported or destroyed. If
3833 * this is the case, the config cache is out of sync and
3834 * we should remove the pool from the namespace.
3837 spa_deactivate(spa);
3838 spa_write_cachefile(spa, B_TRUE, B_TRUE);
3841 mutex_exit(&spa_namespace_lock);
3842 return (SET_ERROR(ENOENT));
3847 * We can't open the pool, but we still have useful
3848 * information: the state of each vdev after the
3849 * attempted vdev_open(). Return this to the user.
3851 if (config != NULL && spa->spa_config) {
3852 VERIFY(nvlist_dup(spa->spa_config, config,
3854 VERIFY(nvlist_add_nvlist(*config,
3855 ZPOOL_CONFIG_LOAD_INFO,
3856 spa->spa_load_info) == 0);
3859 spa_deactivate(spa);
3860 spa->spa_last_open_failed = error;
3862 mutex_exit(&spa_namespace_lock);
3868 spa_open_ref(spa, tag);
3871 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
3874 * If we've recovered the pool, pass back any information we
3875 * gathered while doing the load.
3877 if (state == SPA_LOAD_RECOVER) {
3878 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
3879 spa->spa_load_info) == 0);
3883 spa->spa_last_open_failed = 0;
3884 spa->spa_last_ubsync_txg = 0;
3885 spa->spa_load_txg = 0;
3886 mutex_exit(&spa_namespace_lock);
3890 zvol_create_minors(spa->spa_name);
3901 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
3904 return (spa_open_common(name, spapp, tag, policy, config));
3908 spa_open(const char *name, spa_t **spapp, void *tag)
3910 return (spa_open_common(name, spapp, tag, NULL, NULL));
3914 * Lookup the given spa_t, incrementing the inject count in the process,
3915 * preventing it from being exported or destroyed.
3918 spa_inject_addref(char *name)
3922 mutex_enter(&spa_namespace_lock);
3923 if ((spa = spa_lookup(name)) == NULL) {
3924 mutex_exit(&spa_namespace_lock);
3927 spa->spa_inject_ref++;
3928 mutex_exit(&spa_namespace_lock);
3934 spa_inject_delref(spa_t *spa)
3936 mutex_enter(&spa_namespace_lock);
3937 spa->spa_inject_ref--;
3938 mutex_exit(&spa_namespace_lock);
3942 * Add spares device information to the nvlist.
3945 spa_add_spares(spa_t *spa, nvlist_t *config)
3955 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3957 if (spa->spa_spares.sav_count == 0)
3960 VERIFY(nvlist_lookup_nvlist(config,
3961 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3962 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
3963 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3965 VERIFY(nvlist_add_nvlist_array(nvroot,
3966 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3967 VERIFY(nvlist_lookup_nvlist_array(nvroot,
3968 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3971 * Go through and find any spares which have since been
3972 * repurposed as an active spare. If this is the case, update
3973 * their status appropriately.
3975 for (i = 0; i < nspares; i++) {
3976 VERIFY(nvlist_lookup_uint64(spares[i],
3977 ZPOOL_CONFIG_GUID, &guid) == 0);
3978 if (spa_spare_exists(guid, &pool, NULL) &&
3980 VERIFY(nvlist_lookup_uint64_array(
3981 spares[i], ZPOOL_CONFIG_VDEV_STATS,
3982 (uint64_t **)&vs, &vsc) == 0);
3983 vs->vs_state = VDEV_STATE_CANT_OPEN;
3984 vs->vs_aux = VDEV_AUX_SPARED;
3991 * Add l2cache device information to the nvlist, including vdev stats.
3994 spa_add_l2cache(spa_t *spa, nvlist_t *config)
3997 uint_t i, j, nl2cache;
4004 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4006 if (spa->spa_l2cache.sav_count == 0)
4009 VERIFY(nvlist_lookup_nvlist(config,
4010 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4011 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4012 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4013 if (nl2cache != 0) {
4014 VERIFY(nvlist_add_nvlist_array(nvroot,
4015 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4016 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4017 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4020 * Update level 2 cache device stats.
4023 for (i = 0; i < nl2cache; i++) {
4024 VERIFY(nvlist_lookup_uint64(l2cache[i],
4025 ZPOOL_CONFIG_GUID, &guid) == 0);
4028 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4030 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4031 vd = spa->spa_l2cache.sav_vdevs[j];
4037 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4038 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4040 vdev_get_stats(vd, vs);
4046 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4052 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4053 VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4055 /* We may be unable to read features if pool is suspended. */
4056 if (spa_suspended(spa))
4059 if (spa->spa_feat_for_read_obj != 0) {
4060 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4061 spa->spa_feat_for_read_obj);
4062 zap_cursor_retrieve(&zc, &za) == 0;
4063 zap_cursor_advance(&zc)) {
4064 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4065 za.za_num_integers == 1);
4066 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4067 za.za_first_integer));
4069 zap_cursor_fini(&zc);
4072 if (spa->spa_feat_for_write_obj != 0) {
4073 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4074 spa->spa_feat_for_write_obj);
4075 zap_cursor_retrieve(&zc, &za) == 0;
4076 zap_cursor_advance(&zc)) {
4077 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4078 za.za_num_integers == 1);
4079 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4080 za.za_first_integer));
4082 zap_cursor_fini(&zc);
4086 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4088 nvlist_free(features);
4092 spa_get_stats(const char *name, nvlist_t **config,
4093 char *altroot, size_t buflen)
4099 error = spa_open_common(name, &spa, FTAG, NULL, config);
4103 * This still leaves a window of inconsistency where the spares
4104 * or l2cache devices could change and the config would be
4105 * self-inconsistent.
4107 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4109 if (*config != NULL) {
4110 uint64_t loadtimes[2];
4112 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4113 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4114 VERIFY(nvlist_add_uint64_array(*config,
4115 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4117 VERIFY(nvlist_add_uint64(*config,
4118 ZPOOL_CONFIG_ERRCOUNT,
4119 spa_get_errlog_size(spa)) == 0);
4121 if (spa_suspended(spa))
4122 VERIFY(nvlist_add_uint64(*config,
4123 ZPOOL_CONFIG_SUSPENDED,
4124 spa->spa_failmode) == 0);
4126 spa_add_spares(spa, *config);
4127 spa_add_l2cache(spa, *config);
4128 spa_add_feature_stats(spa, *config);
4133 * We want to get the alternate root even for faulted pools, so we cheat
4134 * and call spa_lookup() directly.
4138 mutex_enter(&spa_namespace_lock);
4139 spa = spa_lookup(name);
4141 spa_altroot(spa, altroot, buflen);
4145 mutex_exit(&spa_namespace_lock);
4147 spa_altroot(spa, altroot, buflen);
4152 spa_config_exit(spa, SCL_CONFIG, FTAG);
4153 spa_close(spa, FTAG);
4160 * Validate that the auxiliary device array is well formed. We must have an
4161 * array of nvlists, each which describes a valid leaf vdev. If this is an
4162 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4163 * specified, as long as they are well-formed.
4166 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4167 spa_aux_vdev_t *sav, const char *config, uint64_t version,
4168 vdev_labeltype_t label)
4175 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4178 * It's acceptable to have no devs specified.
4180 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4184 return (SET_ERROR(EINVAL));
4187 * Make sure the pool is formatted with a version that supports this
4190 if (spa_version(spa) < version)
4191 return (SET_ERROR(ENOTSUP));
4194 * Set the pending device list so we correctly handle device in-use
4197 sav->sav_pending = dev;
4198 sav->sav_npending = ndev;
4200 for (i = 0; i < ndev; i++) {
4201 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4205 if (!vd->vdev_ops->vdev_op_leaf) {
4207 error = SET_ERROR(EINVAL);
4212 * The L2ARC currently only supports disk devices in
4213 * kernel context. For user-level testing, we allow it.
4216 if ((strcmp(config, ZPOOL_CONFIG_L2CACHE) == 0) &&
4217 strcmp(vd->vdev_ops->vdev_op_type, VDEV_TYPE_DISK) != 0) {
4218 error = SET_ERROR(ENOTBLK);
4225 if ((error = vdev_open(vd)) == 0 &&
4226 (error = vdev_label_init(vd, crtxg, label)) == 0) {
4227 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4228 vd->vdev_guid) == 0);
4234 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
4241 sav->sav_pending = NULL;
4242 sav->sav_npending = 0;
4247 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
4251 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4253 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4254 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
4255 VDEV_LABEL_SPARE)) != 0) {
4259 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4260 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
4261 VDEV_LABEL_L2CACHE));
4265 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
4270 if (sav->sav_config != NULL) {
4276 * Generate new dev list by concatentating with the
4279 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
4280 &olddevs, &oldndevs) == 0);
4282 newdevs = kmem_alloc(sizeof (void *) *
4283 (ndevs + oldndevs), KM_SLEEP);
4284 for (i = 0; i < oldndevs; i++)
4285 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
4287 for (i = 0; i < ndevs; i++)
4288 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
4291 VERIFY(nvlist_remove(sav->sav_config, config,
4292 DATA_TYPE_NVLIST_ARRAY) == 0);
4294 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
4295 config, newdevs, ndevs + oldndevs) == 0);
4296 for (i = 0; i < oldndevs + ndevs; i++)
4297 nvlist_free(newdevs[i]);
4298 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
4301 * Generate a new dev list.
4303 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
4305 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
4311 * Stop and drop level 2 ARC devices
4314 spa_l2cache_drop(spa_t *spa)
4318 spa_aux_vdev_t *sav = &spa->spa_l2cache;
4320 for (i = 0; i < sav->sav_count; i++) {
4323 vd = sav->sav_vdevs[i];
4326 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
4327 pool != 0ULL && l2arc_vdev_present(vd))
4328 l2arc_remove_vdev(vd);
4336 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
4340 char *altroot = NULL;
4345 uint64_t txg = TXG_INITIAL;
4346 nvlist_t **spares, **l2cache;
4347 uint_t nspares, nl2cache;
4348 uint64_t version, obj;
4349 boolean_t has_features;
4352 * If this pool already exists, return failure.
4354 mutex_enter(&spa_namespace_lock);
4355 if (spa_lookup(pool) != NULL) {
4356 mutex_exit(&spa_namespace_lock);
4357 return (SET_ERROR(EEXIST));
4361 * Allocate a new spa_t structure.
4363 (void) nvlist_lookup_string(props,
4364 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4365 spa = spa_add(pool, NULL, altroot);
4366 spa_activate(spa, spa_mode_global);
4368 if (props && (error = spa_prop_validate(spa, props))) {
4369 spa_deactivate(spa);
4371 mutex_exit(&spa_namespace_lock);
4375 has_features = B_FALSE;
4376 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
4377 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
4378 if (zpool_prop_feature(nvpair_name(elem)))
4379 has_features = B_TRUE;
4382 if (has_features || nvlist_lookup_uint64(props,
4383 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
4384 version = SPA_VERSION;
4386 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
4388 spa->spa_first_txg = txg;
4389 spa->spa_uberblock.ub_txg = txg - 1;
4390 spa->spa_uberblock.ub_version = version;
4391 spa->spa_ubsync = spa->spa_uberblock;
4392 spa->spa_load_state = SPA_LOAD_CREATE;
4393 spa->spa_removing_phys.sr_state = DSS_NONE;
4394 spa->spa_removing_phys.sr_removing_vdev = -1;
4395 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
4398 * Create "The Godfather" zio to hold all async IOs
4400 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
4402 for (int i = 0; i < max_ncpus; i++) {
4403 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
4404 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4405 ZIO_FLAG_GODFATHER);
4409 * Create the root vdev.
4411 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4413 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
4415 ASSERT(error != 0 || rvd != NULL);
4416 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
4418 if (error == 0 && !zfs_allocatable_devs(nvroot))
4419 error = SET_ERROR(EINVAL);
4422 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
4423 (error = spa_validate_aux(spa, nvroot, txg,
4424 VDEV_ALLOC_ADD)) == 0) {
4425 for (int c = 0; c < rvd->vdev_children; c++) {
4426 vdev_ashift_optimize(rvd->vdev_child[c]);
4427 vdev_metaslab_set_size(rvd->vdev_child[c]);
4428 vdev_expand(rvd->vdev_child[c], txg);
4432 spa_config_exit(spa, SCL_ALL, FTAG);
4436 spa_deactivate(spa);
4438 mutex_exit(&spa_namespace_lock);
4443 * Get the list of spares, if specified.
4445 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4446 &spares, &nspares) == 0) {
4447 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
4449 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4450 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4451 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4452 spa_load_spares(spa);
4453 spa_config_exit(spa, SCL_ALL, FTAG);
4454 spa->spa_spares.sav_sync = B_TRUE;
4458 * Get the list of level 2 cache devices, if specified.
4460 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4461 &l2cache, &nl2cache) == 0) {
4462 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
4463 NV_UNIQUE_NAME, KM_SLEEP) == 0);
4464 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4465 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4466 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4467 spa_load_l2cache(spa);
4468 spa_config_exit(spa, SCL_ALL, FTAG);
4469 spa->spa_l2cache.sav_sync = B_TRUE;
4472 spa->spa_is_initializing = B_TRUE;
4473 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
4474 spa->spa_meta_objset = dp->dp_meta_objset;
4475 spa->spa_is_initializing = B_FALSE;
4478 * Create DDTs (dedup tables).
4482 spa_update_dspace(spa);
4484 tx = dmu_tx_create_assigned(dp, txg);
4487 * Create the pool config object.
4489 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
4490 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
4491 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
4493 if (zap_add(spa->spa_meta_objset,
4494 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
4495 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
4496 cmn_err(CE_PANIC, "failed to add pool config");
4499 if (spa_version(spa) >= SPA_VERSION_FEATURES)
4500 spa_feature_create_zap_objects(spa, tx);
4502 if (zap_add(spa->spa_meta_objset,
4503 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
4504 sizeof (uint64_t), 1, &version, tx) != 0) {
4505 cmn_err(CE_PANIC, "failed to add pool version");
4508 /* Newly created pools with the right version are always deflated. */
4509 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
4510 spa->spa_deflate = TRUE;
4511 if (zap_add(spa->spa_meta_objset,
4512 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
4513 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
4514 cmn_err(CE_PANIC, "failed to add deflate");
4519 * Create the deferred-free bpobj. Turn off compression
4520 * because sync-to-convergence takes longer if the blocksize
4523 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
4524 dmu_object_set_compress(spa->spa_meta_objset, obj,
4525 ZIO_COMPRESS_OFF, tx);
4526 if (zap_add(spa->spa_meta_objset,
4527 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
4528 sizeof (uint64_t), 1, &obj, tx) != 0) {
4529 cmn_err(CE_PANIC, "failed to add bpobj");
4531 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
4532 spa->spa_meta_objset, obj));
4535 * Create the pool's history object.
4537 if (version >= SPA_VERSION_ZPOOL_HISTORY)
4538 spa_history_create_obj(spa, tx);
4541 * Generate some random noise for salted checksums to operate on.
4543 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
4544 sizeof (spa->spa_cksum_salt.zcs_bytes));
4547 * Set pool properties.
4549 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
4550 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
4551 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
4552 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
4554 if (props != NULL) {
4555 spa_configfile_set(spa, props, B_FALSE);
4556 spa_sync_props(props, tx);
4561 spa->spa_sync_on = B_TRUE;
4562 txg_sync_start(spa->spa_dsl_pool);
4565 * We explicitly wait for the first transaction to complete so that our
4566 * bean counters are appropriately updated.
4568 txg_wait_synced(spa->spa_dsl_pool, txg);
4570 spa_spawn_aux_threads(spa);
4572 spa_write_cachefile(spa, B_FALSE, B_TRUE);
4573 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
4575 spa_history_log_version(spa, "create");
4578 * Don't count references from objsets that are already closed
4579 * and are making their way through the eviction process.
4581 spa_evicting_os_wait(spa);
4582 spa->spa_minref = refcount_count(&spa->spa_refcount);
4583 spa->spa_load_state = SPA_LOAD_NONE;
4585 mutex_exit(&spa_namespace_lock);
4593 * Get the root pool information from the root disk, then import the root pool
4594 * during the system boot up time.
4596 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
4599 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
4602 nvlist_t *nvtop, *nvroot;
4605 if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
4609 * Add this top-level vdev to the child array.
4611 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4613 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4615 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
4618 * Put this pool's top-level vdevs into a root vdev.
4620 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4621 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
4622 VDEV_TYPE_ROOT) == 0);
4623 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
4624 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
4625 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
4629 * Replace the existing vdev_tree with the new root vdev in
4630 * this pool's configuration (remove the old, add the new).
4632 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
4633 nvlist_free(nvroot);
4638 * Walk the vdev tree and see if we can find a device with "better"
4639 * configuration. A configuration is "better" if the label on that
4640 * device has a more recent txg.
4643 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
4645 for (int c = 0; c < vd->vdev_children; c++)
4646 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
4648 if (vd->vdev_ops->vdev_op_leaf) {
4652 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
4656 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
4660 * Do we have a better boot device?
4662 if (label_txg > *txg) {
4671 * Import a root pool.
4673 * For x86. devpath_list will consist of devid and/or physpath name of
4674 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
4675 * The GRUB "findroot" command will return the vdev we should boot.
4677 * For Sparc, devpath_list consists the physpath name of the booting device
4678 * no matter the rootpool is a single device pool or a mirrored pool.
4680 * "/pci@1f,0/ide@d/disk@0,0:a"
4683 spa_import_rootpool(char *devpath, char *devid)
4686 vdev_t *rvd, *bvd, *avd = NULL;
4687 nvlist_t *config, *nvtop;
4693 * Read the label from the boot device and generate a configuration.
4695 config = spa_generate_rootconf(devpath, devid, &guid);
4696 #if defined(_OBP) && defined(_KERNEL)
4697 if (config == NULL) {
4698 if (strstr(devpath, "/iscsi/ssd") != NULL) {
4700 get_iscsi_bootpath_phy(devpath);
4701 config = spa_generate_rootconf(devpath, devid, &guid);
4705 if (config == NULL) {
4706 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
4708 return (SET_ERROR(EIO));
4711 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
4713 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
4715 mutex_enter(&spa_namespace_lock);
4716 if ((spa = spa_lookup(pname)) != NULL) {
4718 * Remove the existing root pool from the namespace so that we
4719 * can replace it with the correct config we just read in.
4724 spa = spa_add(pname, config, NULL);
4725 spa->spa_is_root = B_TRUE;
4726 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
4727 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
4728 &spa->spa_ubsync.ub_version) != 0)
4729 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
4732 * Build up a vdev tree based on the boot device's label config.
4734 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4736 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4737 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
4738 VDEV_ALLOC_ROOTPOOL);
4739 spa_config_exit(spa, SCL_ALL, FTAG);
4741 mutex_exit(&spa_namespace_lock);
4742 nvlist_free(config);
4743 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
4749 * Get the boot vdev.
4751 if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
4752 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
4753 (u_longlong_t)guid);
4754 error = SET_ERROR(ENOENT);
4759 * Determine if there is a better boot device.
4762 spa_alt_rootvdev(rvd, &avd, &txg);
4764 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
4765 "try booting from '%s'", avd->vdev_path);
4766 error = SET_ERROR(EINVAL);
4771 * If the boot device is part of a spare vdev then ensure that
4772 * we're booting off the active spare.
4774 if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
4775 !bvd->vdev_isspare) {
4776 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
4777 "try booting from '%s'",
4779 vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
4780 error = SET_ERROR(EINVAL);
4786 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4788 spa_config_exit(spa, SCL_ALL, FTAG);
4789 mutex_exit(&spa_namespace_lock);
4791 nvlist_free(config);
4795 #else /* !illumos */
4797 extern int vdev_geom_read_pool_label(const char *name, nvlist_t ***configs,
4801 spa_generate_rootconf(const char *name)
4803 nvlist_t **configs, **tops;
4805 nvlist_t *best_cfg, *nvtop, *nvroot;
4814 if (vdev_geom_read_pool_label(name, &configs, &count) != 0)
4817 ASSERT3U(count, !=, 0);
4819 for (i = 0; i < count; i++) {
4822 VERIFY(nvlist_lookup_uint64(configs[i], ZPOOL_CONFIG_POOL_TXG,
4824 if (txg > best_txg) {
4826 best_cfg = configs[i];
4831 nvlist_lookup_uint64(best_cfg, ZPOOL_CONFIG_VDEV_CHILDREN, &nchildren);
4833 nvlist_lookup_uint64_array(best_cfg, ZPOOL_CONFIG_HOLE_ARRAY,
4836 tops = kmem_zalloc(nchildren * sizeof(void *), KM_SLEEP);
4837 for (i = 0; i < nchildren; i++) {
4840 if (configs[i] == NULL)
4842 VERIFY(nvlist_lookup_nvlist(configs[i], ZPOOL_CONFIG_VDEV_TREE,
4844 nvlist_dup(nvtop, &tops[i], KM_SLEEP);
4846 for (i = 0; holes != NULL && i < nholes; i++) {
4849 if (tops[holes[i]] != NULL)
4851 nvlist_alloc(&tops[holes[i]], NV_UNIQUE_NAME, KM_SLEEP);
4852 VERIFY(nvlist_add_string(tops[holes[i]], ZPOOL_CONFIG_TYPE,
4853 VDEV_TYPE_HOLE) == 0);
4854 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_ID,
4856 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_GUID,
4859 for (i = 0; i < nchildren; i++) {
4860 if (tops[i] != NULL)
4862 nvlist_alloc(&tops[i], NV_UNIQUE_NAME, KM_SLEEP);
4863 VERIFY(nvlist_add_string(tops[i], ZPOOL_CONFIG_TYPE,
4864 VDEV_TYPE_MISSING) == 0);
4865 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_ID,
4867 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_GUID,
4872 * Create pool config based on the best vdev config.
4874 nvlist_dup(best_cfg, &config, KM_SLEEP);
4877 * Put this pool's top-level vdevs into a root vdev.
4879 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4881 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4882 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
4883 VDEV_TYPE_ROOT) == 0);
4884 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
4885 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
4886 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
4887 tops, nchildren) == 0);
4890 * Replace the existing vdev_tree with the new root vdev in
4891 * this pool's configuration (remove the old, add the new).
4893 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
4896 * Drop vdev config elements that should not be present at pool level.
4898 nvlist_remove(config, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64);
4899 nvlist_remove(config, ZPOOL_CONFIG_TOP_GUID, DATA_TYPE_UINT64);
4901 for (i = 0; i < count; i++)
4902 nvlist_free(configs[i]);
4903 kmem_free(configs, count * sizeof(void *));
4904 for (i = 0; i < nchildren; i++)
4905 nvlist_free(tops[i]);
4906 kmem_free(tops, nchildren * sizeof(void *));
4907 nvlist_free(nvroot);
4912 spa_import_rootpool(const char *name)
4915 vdev_t *rvd, *bvd, *avd = NULL;
4916 nvlist_t *config, *nvtop;
4922 * Read the label from the boot device and generate a configuration.
4924 config = spa_generate_rootconf(name);
4926 mutex_enter(&spa_namespace_lock);
4927 if (config != NULL) {
4928 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
4929 &pname) == 0 && strcmp(name, pname) == 0);
4930 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg)
4933 if ((spa = spa_lookup(pname)) != NULL) {
4935 * The pool could already be imported,
4936 * e.g., after reboot -r.
4938 if (spa->spa_state == POOL_STATE_ACTIVE) {
4939 mutex_exit(&spa_namespace_lock);
4940 nvlist_free(config);
4945 * Remove the existing root pool from the namespace so
4946 * that we can replace it with the correct config
4951 spa = spa_add(pname, config, NULL);
4954 * Set spa_ubsync.ub_version as it can be used in vdev_alloc()
4955 * via spa_version().
4957 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
4958 &spa->spa_ubsync.ub_version) != 0)
4959 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
4960 } else if ((spa = spa_lookup(name)) == NULL) {
4961 mutex_exit(&spa_namespace_lock);
4962 nvlist_free(config);
4963 cmn_err(CE_NOTE, "Cannot find the pool label for '%s'",
4967 VERIFY(nvlist_dup(spa->spa_config, &config, KM_SLEEP) == 0);
4969 spa->spa_is_root = B_TRUE;
4970 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
4973 * Build up a vdev tree based on the boot device's label config.
4975 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4977 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4978 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
4979 VDEV_ALLOC_ROOTPOOL);
4980 spa_config_exit(spa, SCL_ALL, FTAG);
4982 mutex_exit(&spa_namespace_lock);
4983 nvlist_free(config);
4984 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
4989 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4991 spa_config_exit(spa, SCL_ALL, FTAG);
4992 mutex_exit(&spa_namespace_lock);
4994 nvlist_free(config);
4998 #endif /* illumos */
4999 #endif /* _KERNEL */
5002 * Import a non-root pool into the system.
5005 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5008 char *altroot = NULL;
5009 spa_load_state_t state = SPA_LOAD_IMPORT;
5010 zpool_rewind_policy_t policy;
5011 uint64_t mode = spa_mode_global;
5012 uint64_t readonly = B_FALSE;
5015 nvlist_t **spares, **l2cache;
5016 uint_t nspares, nl2cache;
5019 * If a pool with this name exists, return failure.
5021 mutex_enter(&spa_namespace_lock);
5022 if (spa_lookup(pool) != NULL) {
5023 mutex_exit(&spa_namespace_lock);
5024 return (SET_ERROR(EEXIST));
5028 * Create and initialize the spa structure.
5030 (void) nvlist_lookup_string(props,
5031 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5032 (void) nvlist_lookup_uint64(props,
5033 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5036 spa = spa_add(pool, config, altroot);
5037 spa->spa_import_flags = flags;
5040 * Verbatim import - Take a pool and insert it into the namespace
5041 * as if it had been loaded at boot.
5043 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5045 spa_configfile_set(spa, props, B_FALSE);
5047 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5048 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5049 zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5050 mutex_exit(&spa_namespace_lock);
5054 spa_activate(spa, mode);
5057 * Don't start async tasks until we know everything is healthy.
5059 spa_async_suspend(spa);
5061 zpool_get_rewind_policy(config, &policy);
5062 if (policy.zrp_request & ZPOOL_DO_REWIND)
5063 state = SPA_LOAD_RECOVER;
5065 spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5067 if (state != SPA_LOAD_RECOVER) {
5068 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5069 zfs_dbgmsg("spa_import: importing %s", pool);
5071 zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5072 "(RECOVERY MODE)", pool, (longlong_t)policy.zrp_txg);
5074 error = spa_load_best(spa, state, policy.zrp_txg, policy.zrp_request);
5077 * Propagate anything learned while loading the pool and pass it
5078 * back to caller (i.e. rewind info, missing devices, etc).
5080 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5081 spa->spa_load_info) == 0);
5083 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5085 * Toss any existing sparelist, as it doesn't have any validity
5086 * anymore, and conflicts with spa_has_spare().
5088 if (spa->spa_spares.sav_config) {
5089 nvlist_free(spa->spa_spares.sav_config);
5090 spa->spa_spares.sav_config = NULL;
5091 spa_load_spares(spa);
5093 if (spa->spa_l2cache.sav_config) {
5094 nvlist_free(spa->spa_l2cache.sav_config);
5095 spa->spa_l2cache.sav_config = NULL;
5096 spa_load_l2cache(spa);
5099 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5102 error = spa_validate_aux(spa, nvroot, -1ULL,
5105 error = spa_validate_aux(spa, nvroot, -1ULL,
5106 VDEV_ALLOC_L2CACHE);
5107 spa_config_exit(spa, SCL_ALL, FTAG);
5110 spa_configfile_set(spa, props, B_FALSE);
5112 if (error != 0 || (props && spa_writeable(spa) &&
5113 (error = spa_prop_set(spa, props)))) {
5115 spa_deactivate(spa);
5117 mutex_exit(&spa_namespace_lock);
5121 spa_async_resume(spa);
5124 * Override any spares and level 2 cache devices as specified by
5125 * the user, as these may have correct device names/devids, etc.
5127 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5128 &spares, &nspares) == 0) {
5129 if (spa->spa_spares.sav_config)
5130 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5131 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5133 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5134 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5135 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5136 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5137 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5138 spa_load_spares(spa);
5139 spa_config_exit(spa, SCL_ALL, FTAG);
5140 spa->spa_spares.sav_sync = B_TRUE;
5142 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5143 &l2cache, &nl2cache) == 0) {
5144 if (spa->spa_l2cache.sav_config)
5145 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5146 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5148 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5149 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5150 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5151 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5152 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5153 spa_load_l2cache(spa);
5154 spa_config_exit(spa, SCL_ALL, FTAG);
5155 spa->spa_l2cache.sav_sync = B_TRUE;
5159 * Check for any removed devices.
5161 if (spa->spa_autoreplace) {
5162 spa_aux_check_removed(&spa->spa_spares);
5163 spa_aux_check_removed(&spa->spa_l2cache);
5166 if (spa_writeable(spa)) {
5168 * Update the config cache to include the newly-imported pool.
5170 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5174 * It's possible that the pool was expanded while it was exported.
5175 * We kick off an async task to handle this for us.
5177 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5179 spa_history_log_version(spa, "import");
5181 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5183 mutex_exit(&spa_namespace_lock);
5187 zvol_create_minors(pool);
5194 spa_tryimport(nvlist_t *tryconfig)
5196 nvlist_t *config = NULL;
5197 char *poolname, *cachefile;
5201 zpool_rewind_policy_t policy;
5203 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5206 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5210 * Create and initialize the spa structure.
5212 mutex_enter(&spa_namespace_lock);
5213 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
5214 spa_activate(spa, FREAD);
5217 * Rewind pool if a max txg was provided. Note that even though we
5218 * retrieve the complete rewind policy, only the rewind txg is relevant
5221 zpool_get_rewind_policy(spa->spa_config, &policy);
5222 if (policy.zrp_txg != UINT64_MAX) {
5223 spa->spa_load_max_txg = policy.zrp_txg;
5224 spa->spa_extreme_rewind = B_TRUE;
5225 zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
5226 poolname, (longlong_t)policy.zrp_txg);
5228 zfs_dbgmsg("spa_tryimport: importing %s", poolname);
5231 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
5233 zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
5234 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5236 spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
5239 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
5242 * If 'tryconfig' was at least parsable, return the current config.
5244 if (spa->spa_root_vdev != NULL) {
5245 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5246 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
5248 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5250 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
5251 spa->spa_uberblock.ub_timestamp) == 0);
5252 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5253 spa->spa_load_info) == 0);
5256 * If the bootfs property exists on this pool then we
5257 * copy it out so that external consumers can tell which
5258 * pools are bootable.
5260 if ((!error || error == EEXIST) && spa->spa_bootfs) {
5261 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5264 * We have to play games with the name since the
5265 * pool was opened as TRYIMPORT_NAME.
5267 if (dsl_dsobj_to_dsname(spa_name(spa),
5268 spa->spa_bootfs, tmpname) == 0) {
5270 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5272 cp = strchr(tmpname, '/');
5274 (void) strlcpy(dsname, tmpname,
5277 (void) snprintf(dsname, MAXPATHLEN,
5278 "%s/%s", poolname, ++cp);
5280 VERIFY(nvlist_add_string(config,
5281 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
5282 kmem_free(dsname, MAXPATHLEN);
5284 kmem_free(tmpname, MAXPATHLEN);
5288 * Add the list of hot spares and level 2 cache devices.
5290 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5291 spa_add_spares(spa, config);
5292 spa_add_l2cache(spa, config);
5293 spa_config_exit(spa, SCL_CONFIG, FTAG);
5297 spa_deactivate(spa);
5299 mutex_exit(&spa_namespace_lock);
5305 * Pool export/destroy
5307 * The act of destroying or exporting a pool is very simple. We make sure there
5308 * is no more pending I/O and any references to the pool are gone. Then, we
5309 * update the pool state and sync all the labels to disk, removing the
5310 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
5311 * we don't sync the labels or remove the configuration cache.
5314 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
5315 boolean_t force, boolean_t hardforce)
5322 if (!(spa_mode_global & FWRITE))
5323 return (SET_ERROR(EROFS));
5325 mutex_enter(&spa_namespace_lock);
5326 if ((spa = spa_lookup(pool)) == NULL) {
5327 mutex_exit(&spa_namespace_lock);
5328 return (SET_ERROR(ENOENT));
5332 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5333 * reacquire the namespace lock, and see if we can export.
5335 spa_open_ref(spa, FTAG);
5336 mutex_exit(&spa_namespace_lock);
5337 spa_async_suspend(spa);
5338 mutex_enter(&spa_namespace_lock);
5339 spa_close(spa, FTAG);
5342 * The pool will be in core if it's openable,
5343 * in which case we can modify its state.
5345 if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
5347 * Objsets may be open only because they're dirty, so we
5348 * have to force it to sync before checking spa_refcnt.
5350 txg_wait_synced(spa->spa_dsl_pool, 0);
5351 spa_evicting_os_wait(spa);
5354 * A pool cannot be exported or destroyed if there are active
5355 * references. If we are resetting a pool, allow references by
5356 * fault injection handlers.
5358 if (!spa_refcount_zero(spa) ||
5359 (spa->spa_inject_ref != 0 &&
5360 new_state != POOL_STATE_UNINITIALIZED)) {
5361 spa_async_resume(spa);
5362 mutex_exit(&spa_namespace_lock);
5363 return (SET_ERROR(EBUSY));
5367 * A pool cannot be exported if it has an active shared spare.
5368 * This is to prevent other pools stealing the active spare
5369 * from an exported pool. At user's own will, such pool can
5370 * be forcedly exported.
5372 if (!force && new_state == POOL_STATE_EXPORTED &&
5373 spa_has_active_shared_spare(spa)) {
5374 spa_async_resume(spa);
5375 mutex_exit(&spa_namespace_lock);
5376 return (SET_ERROR(EXDEV));
5380 * We want this to be reflected on every label,
5381 * so mark them all dirty. spa_unload() will do the
5382 * final sync that pushes these changes out.
5384 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
5385 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5386 spa->spa_state = new_state;
5387 spa->spa_final_txg = spa_last_synced_txg(spa) +
5389 vdev_config_dirty(spa->spa_root_vdev);
5390 spa_config_exit(spa, SCL_ALL, FTAG);
5394 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
5396 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
5398 spa_deactivate(spa);
5401 if (oldconfig && spa->spa_config)
5402 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
5404 if (new_state != POOL_STATE_UNINITIALIZED) {
5406 spa_write_cachefile(spa, B_TRUE, B_TRUE);
5409 mutex_exit(&spa_namespace_lock);
5415 * Destroy a storage pool.
5418 spa_destroy(char *pool)
5420 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
5425 * Export a storage pool.
5428 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
5429 boolean_t hardforce)
5431 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
5436 * Similar to spa_export(), this unloads the spa_t without actually removing it
5437 * from the namespace in any way.
5440 spa_reset(char *pool)
5442 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
5447 * ==========================================================================
5448 * Device manipulation
5449 * ==========================================================================
5453 * Add a device to a storage pool.
5456 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
5460 vdev_t *rvd = spa->spa_root_vdev;
5462 nvlist_t **spares, **l2cache;
5463 uint_t nspares, nl2cache;
5465 ASSERT(spa_writeable(spa));
5467 txg = spa_vdev_enter(spa);
5469 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
5470 VDEV_ALLOC_ADD)) != 0)
5471 return (spa_vdev_exit(spa, NULL, txg, error));
5473 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
5475 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
5479 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
5483 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
5484 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5486 if (vd->vdev_children != 0 &&
5487 (error = vdev_create(vd, txg, B_FALSE)) != 0)
5488 return (spa_vdev_exit(spa, vd, txg, error));
5491 * We must validate the spares and l2cache devices after checking the
5492 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
5494 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
5495 return (spa_vdev_exit(spa, vd, txg, error));
5498 * If we are in the middle of a device removal, we can only add
5499 * devices which match the existing devices in the pool.
5500 * If we are in the middle of a removal, or have some indirect
5501 * vdevs, we can not add raidz toplevels.
5503 if (spa->spa_vdev_removal != NULL ||
5504 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
5505 for (int c = 0; c < vd->vdev_children; c++) {
5506 tvd = vd->vdev_child[c];
5507 if (spa->spa_vdev_removal != NULL &&
5509 spa->spa_vdev_removal->svr_vdev->vdev_ashift) {
5510 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5512 /* Fail if top level vdev is raidz */
5513 if (tvd->vdev_ops == &vdev_raidz_ops) {
5514 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5517 * Need the top level mirror to be
5518 * a mirror of leaf vdevs only
5520 if (tvd->vdev_ops == &vdev_mirror_ops) {
5521 for (uint64_t cid = 0;
5522 cid < tvd->vdev_children; cid++) {
5523 vdev_t *cvd = tvd->vdev_child[cid];
5524 if (!cvd->vdev_ops->vdev_op_leaf) {
5525 return (spa_vdev_exit(spa, vd,
5533 for (int c = 0; c < vd->vdev_children; c++) {
5536 * Set the vdev id to the first hole, if one exists.
5538 for (id = 0; id < rvd->vdev_children; id++) {
5539 if (rvd->vdev_child[id]->vdev_ishole) {
5540 vdev_free(rvd->vdev_child[id]);
5544 tvd = vd->vdev_child[c];
5545 vdev_remove_child(vd, tvd);
5547 vdev_add_child(rvd, tvd);
5548 vdev_config_dirty(tvd);
5552 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
5553 ZPOOL_CONFIG_SPARES);
5554 spa_load_spares(spa);
5555 spa->spa_spares.sav_sync = B_TRUE;
5558 if (nl2cache != 0) {
5559 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
5560 ZPOOL_CONFIG_L2CACHE);
5561 spa_load_l2cache(spa);
5562 spa->spa_l2cache.sav_sync = B_TRUE;
5566 * We have to be careful when adding new vdevs to an existing pool.
5567 * If other threads start allocating from these vdevs before we
5568 * sync the config cache, and we lose power, then upon reboot we may
5569 * fail to open the pool because there are DVAs that the config cache
5570 * can't translate. Therefore, we first add the vdevs without
5571 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
5572 * and then let spa_config_update() initialize the new metaslabs.
5574 * spa_load() checks for added-but-not-initialized vdevs, so that
5575 * if we lose power at any point in this sequence, the remaining
5576 * steps will be completed the next time we load the pool.
5578 (void) spa_vdev_exit(spa, vd, txg, 0);
5580 mutex_enter(&spa_namespace_lock);
5581 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5582 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
5583 mutex_exit(&spa_namespace_lock);
5589 * Attach a device to a mirror. The arguments are the path to any device
5590 * in the mirror, and the nvroot for the new device. If the path specifies
5591 * a device that is not mirrored, we automatically insert the mirror vdev.
5593 * If 'replacing' is specified, the new device is intended to replace the
5594 * existing device; in this case the two devices are made into their own
5595 * mirror using the 'replacing' vdev, which is functionally identical to
5596 * the mirror vdev (it actually reuses all the same ops) but has a few
5597 * extra rules: you can't attach to it after it's been created, and upon
5598 * completion of resilvering, the first disk (the one being replaced)
5599 * is automatically detached.
5602 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
5604 uint64_t txg, dtl_max_txg;
5605 vdev_t *rvd = spa->spa_root_vdev;
5606 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
5608 char *oldvdpath, *newvdpath;
5612 ASSERT(spa_writeable(spa));
5614 txg = spa_vdev_enter(spa);
5616 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
5618 if (spa->spa_vdev_removal != NULL ||
5619 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
5620 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5624 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5626 if (!oldvd->vdev_ops->vdev_op_leaf)
5627 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5629 pvd = oldvd->vdev_parent;
5631 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
5632 VDEV_ALLOC_ATTACH)) != 0)
5633 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5635 if (newrootvd->vdev_children != 1)
5636 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
5638 newvd = newrootvd->vdev_child[0];
5640 if (!newvd->vdev_ops->vdev_op_leaf)
5641 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
5643 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
5644 return (spa_vdev_exit(spa, newrootvd, txg, error));
5647 * Spares can't replace logs
5649 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
5650 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5654 * For attach, the only allowable parent is a mirror or the root
5657 if (pvd->vdev_ops != &vdev_mirror_ops &&
5658 pvd->vdev_ops != &vdev_root_ops)
5659 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5661 pvops = &vdev_mirror_ops;
5664 * Active hot spares can only be replaced by inactive hot
5667 if (pvd->vdev_ops == &vdev_spare_ops &&
5668 oldvd->vdev_isspare &&
5669 !spa_has_spare(spa, newvd->vdev_guid))
5670 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5673 * If the source is a hot spare, and the parent isn't already a
5674 * spare, then we want to create a new hot spare. Otherwise, we
5675 * want to create a replacing vdev. The user is not allowed to
5676 * attach to a spared vdev child unless the 'isspare' state is
5677 * the same (spare replaces spare, non-spare replaces
5680 if (pvd->vdev_ops == &vdev_replacing_ops &&
5681 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
5682 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5683 } else if (pvd->vdev_ops == &vdev_spare_ops &&
5684 newvd->vdev_isspare != oldvd->vdev_isspare) {
5685 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5688 if (newvd->vdev_isspare)
5689 pvops = &vdev_spare_ops;
5691 pvops = &vdev_replacing_ops;
5695 * Make sure the new device is big enough.
5697 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
5698 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
5701 * The new device cannot have a higher alignment requirement
5702 * than the top-level vdev.
5704 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
5705 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
5708 * If this is an in-place replacement, update oldvd's path and devid
5709 * to make it distinguishable from newvd, and unopenable from now on.
5711 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
5712 spa_strfree(oldvd->vdev_path);
5713 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
5715 (void) sprintf(oldvd->vdev_path, "%s/%s",
5716 newvd->vdev_path, "old");
5717 if (oldvd->vdev_devid != NULL) {
5718 spa_strfree(oldvd->vdev_devid);
5719 oldvd->vdev_devid = NULL;
5723 /* mark the device being resilvered */
5724 newvd->vdev_resilver_txg = txg;
5727 * If the parent is not a mirror, or if we're replacing, insert the new
5728 * mirror/replacing/spare vdev above oldvd.
5730 if (pvd->vdev_ops != pvops)
5731 pvd = vdev_add_parent(oldvd, pvops);
5733 ASSERT(pvd->vdev_top->vdev_parent == rvd);
5734 ASSERT(pvd->vdev_ops == pvops);
5735 ASSERT(oldvd->vdev_parent == pvd);
5738 * Extract the new device from its root and add it to pvd.
5740 vdev_remove_child(newrootvd, newvd);
5741 newvd->vdev_id = pvd->vdev_children;
5742 newvd->vdev_crtxg = oldvd->vdev_crtxg;
5743 vdev_add_child(pvd, newvd);
5745 tvd = newvd->vdev_top;
5746 ASSERT(pvd->vdev_top == tvd);
5747 ASSERT(tvd->vdev_parent == rvd);
5749 vdev_config_dirty(tvd);
5752 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
5753 * for any dmu_sync-ed blocks. It will propagate upward when
5754 * spa_vdev_exit() calls vdev_dtl_reassess().
5756 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
5758 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
5759 dtl_max_txg - TXG_INITIAL);
5761 if (newvd->vdev_isspare) {
5762 spa_spare_activate(newvd);
5763 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
5766 oldvdpath = spa_strdup(oldvd->vdev_path);
5767 newvdpath = spa_strdup(newvd->vdev_path);
5768 newvd_isspare = newvd->vdev_isspare;
5771 * Mark newvd's DTL dirty in this txg.
5773 vdev_dirty(tvd, VDD_DTL, newvd, txg);
5776 * Schedule the resilver to restart in the future. We do this to
5777 * ensure that dmu_sync-ed blocks have been stitched into the
5778 * respective datasets.
5780 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
5782 if (spa->spa_bootfs)
5783 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
5785 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
5790 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
5792 spa_history_log_internal(spa, "vdev attach", NULL,
5793 "%s vdev=%s %s vdev=%s",
5794 replacing && newvd_isspare ? "spare in" :
5795 replacing ? "replace" : "attach", newvdpath,
5796 replacing ? "for" : "to", oldvdpath);
5798 spa_strfree(oldvdpath);
5799 spa_strfree(newvdpath);
5805 * Detach a device from a mirror or replacing vdev.
5807 * If 'replace_done' is specified, only detach if the parent
5808 * is a replacing vdev.
5811 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
5815 vdev_t *rvd = spa->spa_root_vdev;
5816 vdev_t *vd, *pvd, *cvd, *tvd;
5817 boolean_t unspare = B_FALSE;
5818 uint64_t unspare_guid = 0;
5821 ASSERT(spa_writeable(spa));
5823 txg = spa_vdev_enter(spa);
5825 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
5828 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5830 if (!vd->vdev_ops->vdev_op_leaf)
5831 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5833 pvd = vd->vdev_parent;
5836 * If the parent/child relationship is not as expected, don't do it.
5837 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
5838 * vdev that's replacing B with C. The user's intent in replacing
5839 * is to go from M(A,B) to M(A,C). If the user decides to cancel
5840 * the replace by detaching C, the expected behavior is to end up
5841 * M(A,B). But suppose that right after deciding to detach C,
5842 * the replacement of B completes. We would have M(A,C), and then
5843 * ask to detach C, which would leave us with just A -- not what
5844 * the user wanted. To prevent this, we make sure that the
5845 * parent/child relationship hasn't changed -- in this example,
5846 * that C's parent is still the replacing vdev R.
5848 if (pvd->vdev_guid != pguid && pguid != 0)
5849 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5852 * Only 'replacing' or 'spare' vdevs can be replaced.
5854 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
5855 pvd->vdev_ops != &vdev_spare_ops)
5856 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5858 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
5859 spa_version(spa) >= SPA_VERSION_SPARES);
5862 * Only mirror, replacing, and spare vdevs support detach.
5864 if (pvd->vdev_ops != &vdev_replacing_ops &&
5865 pvd->vdev_ops != &vdev_mirror_ops &&
5866 pvd->vdev_ops != &vdev_spare_ops)
5867 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5870 * If this device has the only valid copy of some data,
5871 * we cannot safely detach it.
5873 if (vdev_dtl_required(vd))
5874 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5876 ASSERT(pvd->vdev_children >= 2);
5879 * If we are detaching the second disk from a replacing vdev, then
5880 * check to see if we changed the original vdev's path to have "/old"
5881 * at the end in spa_vdev_attach(). If so, undo that change now.
5883 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
5884 vd->vdev_path != NULL) {
5885 size_t len = strlen(vd->vdev_path);
5887 for (int c = 0; c < pvd->vdev_children; c++) {
5888 cvd = pvd->vdev_child[c];
5890 if (cvd == vd || cvd->vdev_path == NULL)
5893 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
5894 strcmp(cvd->vdev_path + len, "/old") == 0) {
5895 spa_strfree(cvd->vdev_path);
5896 cvd->vdev_path = spa_strdup(vd->vdev_path);
5903 * If we are detaching the original disk from a spare, then it implies
5904 * that the spare should become a real disk, and be removed from the
5905 * active spare list for the pool.
5907 if (pvd->vdev_ops == &vdev_spare_ops &&
5909 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
5913 * Erase the disk labels so the disk can be used for other things.
5914 * This must be done after all other error cases are handled,
5915 * but before we disembowel vd (so we can still do I/O to it).
5916 * But if we can't do it, don't treat the error as fatal --
5917 * it may be that the unwritability of the disk is the reason
5918 * it's being detached!
5920 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
5923 * Remove vd from its parent and compact the parent's children.
5925 vdev_remove_child(pvd, vd);
5926 vdev_compact_children(pvd);
5929 * Remember one of the remaining children so we can get tvd below.
5931 cvd = pvd->vdev_child[pvd->vdev_children - 1];
5934 * If we need to remove the remaining child from the list of hot spares,
5935 * do it now, marking the vdev as no longer a spare in the process.
5936 * We must do this before vdev_remove_parent(), because that can
5937 * change the GUID if it creates a new toplevel GUID. For a similar
5938 * reason, we must remove the spare now, in the same txg as the detach;
5939 * otherwise someone could attach a new sibling, change the GUID, and
5940 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
5943 ASSERT(cvd->vdev_isspare);
5944 spa_spare_remove(cvd);
5945 unspare_guid = cvd->vdev_guid;
5946 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
5947 cvd->vdev_unspare = B_TRUE;
5951 * If the parent mirror/replacing vdev only has one child,
5952 * the parent is no longer needed. Remove it from the tree.
5954 if (pvd->vdev_children == 1) {
5955 if (pvd->vdev_ops == &vdev_spare_ops)
5956 cvd->vdev_unspare = B_FALSE;
5957 vdev_remove_parent(cvd);
5962 * We don't set tvd until now because the parent we just removed
5963 * may have been the previous top-level vdev.
5965 tvd = cvd->vdev_top;
5966 ASSERT(tvd->vdev_parent == rvd);
5969 * Reevaluate the parent vdev state.
5971 vdev_propagate_state(cvd);
5974 * If the 'autoexpand' property is set on the pool then automatically
5975 * try to expand the size of the pool. For example if the device we
5976 * just detached was smaller than the others, it may be possible to
5977 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
5978 * first so that we can obtain the updated sizes of the leaf vdevs.
5980 if (spa->spa_autoexpand) {
5982 vdev_expand(tvd, txg);
5985 vdev_config_dirty(tvd);
5988 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
5989 * vd->vdev_detached is set and free vd's DTL object in syncing context.
5990 * But first make sure we're not on any *other* txg's DTL list, to
5991 * prevent vd from being accessed after it's freed.
5993 vdpath = spa_strdup(vd->vdev_path);
5994 for (int t = 0; t < TXG_SIZE; t++)
5995 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
5996 vd->vdev_detached = B_TRUE;
5997 vdev_dirty(tvd, VDD_DTL, vd, txg);
5999 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
6001 /* hang on to the spa before we release the lock */
6002 spa_open_ref(spa, FTAG);
6004 error = spa_vdev_exit(spa, vd, txg, 0);
6006 spa_history_log_internal(spa, "detach", NULL,
6008 spa_strfree(vdpath);
6011 * If this was the removal of the original device in a hot spare vdev,
6012 * then we want to go through and remove the device from the hot spare
6013 * list of every other pool.
6016 spa_t *altspa = NULL;
6018 mutex_enter(&spa_namespace_lock);
6019 while ((altspa = spa_next(altspa)) != NULL) {
6020 if (altspa->spa_state != POOL_STATE_ACTIVE ||
6024 spa_open_ref(altspa, FTAG);
6025 mutex_exit(&spa_namespace_lock);
6026 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
6027 mutex_enter(&spa_namespace_lock);
6028 spa_close(altspa, FTAG);
6030 mutex_exit(&spa_namespace_lock);
6032 /* search the rest of the vdevs for spares to remove */
6033 spa_vdev_resilver_done(spa);
6036 /* all done with the spa; OK to release */
6037 mutex_enter(&spa_namespace_lock);
6038 spa_close(spa, FTAG);
6039 mutex_exit(&spa_namespace_lock);
6045 * Split a set of devices from their mirrors, and create a new pool from them.
6048 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6049 nvlist_t *props, boolean_t exp)
6052 uint64_t txg, *glist;
6054 uint_t c, children, lastlog;
6055 nvlist_t **child, *nvl, *tmp;
6057 char *altroot = NULL;
6058 vdev_t *rvd, **vml = NULL; /* vdev modify list */
6059 boolean_t activate_slog;
6061 ASSERT(spa_writeable(spa));
6063 txg = spa_vdev_enter(spa);
6065 /* clear the log and flush everything up to now */
6066 activate_slog = spa_passivate_log(spa);
6067 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6068 error = spa_reset_logs(spa);
6069 txg = spa_vdev_config_enter(spa);
6072 spa_activate_log(spa);
6075 return (spa_vdev_exit(spa, NULL, txg, error));
6077 /* check new spa name before going any further */
6078 if (spa_lookup(newname) != NULL)
6079 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
6082 * scan through all the children to ensure they're all mirrors
6084 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
6085 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
6087 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6089 /* first, check to ensure we've got the right child count */
6090 rvd = spa->spa_root_vdev;
6092 for (c = 0; c < rvd->vdev_children; c++) {
6093 vdev_t *vd = rvd->vdev_child[c];
6095 /* don't count the holes & logs as children */
6096 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
6104 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
6105 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6107 /* next, ensure no spare or cache devices are part of the split */
6108 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
6109 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
6110 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6112 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
6113 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
6115 /* then, loop over each vdev and validate it */
6116 for (c = 0; c < children; c++) {
6117 uint64_t is_hole = 0;
6119 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
6123 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
6124 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
6127 error = SET_ERROR(EINVAL);
6132 /* which disk is going to be split? */
6133 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
6135 error = SET_ERROR(EINVAL);
6139 /* look it up in the spa */
6140 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
6141 if (vml[c] == NULL) {
6142 error = SET_ERROR(ENODEV);
6146 /* make sure there's nothing stopping the split */
6147 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
6148 vml[c]->vdev_islog ||
6149 !vdev_is_concrete(vml[c]) ||
6150 vml[c]->vdev_isspare ||
6151 vml[c]->vdev_isl2cache ||
6152 !vdev_writeable(vml[c]) ||
6153 vml[c]->vdev_children != 0 ||
6154 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
6155 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
6156 error = SET_ERROR(EINVAL);
6160 if (vdev_dtl_required(vml[c])) {
6161 error = SET_ERROR(EBUSY);
6165 /* we need certain info from the top level */
6166 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
6167 vml[c]->vdev_top->vdev_ms_array) == 0);
6168 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
6169 vml[c]->vdev_top->vdev_ms_shift) == 0);
6170 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
6171 vml[c]->vdev_top->vdev_asize) == 0);
6172 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
6173 vml[c]->vdev_top->vdev_ashift) == 0);
6175 /* transfer per-vdev ZAPs */
6176 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
6177 VERIFY0(nvlist_add_uint64(child[c],
6178 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
6180 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
6181 VERIFY0(nvlist_add_uint64(child[c],
6182 ZPOOL_CONFIG_VDEV_TOP_ZAP,
6183 vml[c]->vdev_parent->vdev_top_zap));
6187 kmem_free(vml, children * sizeof (vdev_t *));
6188 kmem_free(glist, children * sizeof (uint64_t));
6189 return (spa_vdev_exit(spa, NULL, txg, error));
6192 /* stop writers from using the disks */
6193 for (c = 0; c < children; c++) {
6195 vml[c]->vdev_offline = B_TRUE;
6197 vdev_reopen(spa->spa_root_vdev);
6200 * Temporarily record the splitting vdevs in the spa config. This
6201 * will disappear once the config is regenerated.
6203 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6204 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
6205 glist, children) == 0);
6206 kmem_free(glist, children * sizeof (uint64_t));
6208 mutex_enter(&spa->spa_props_lock);
6209 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
6211 mutex_exit(&spa->spa_props_lock);
6212 spa->spa_config_splitting = nvl;
6213 vdev_config_dirty(spa->spa_root_vdev);
6215 /* configure and create the new pool */
6216 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
6217 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6218 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
6219 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6220 spa_version(spa)) == 0);
6221 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
6222 spa->spa_config_txg) == 0);
6223 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
6224 spa_generate_guid(NULL)) == 0);
6225 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
6226 (void) nvlist_lookup_string(props,
6227 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
6229 /* add the new pool to the namespace */
6230 newspa = spa_add(newname, config, altroot);
6231 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
6232 newspa->spa_config_txg = spa->spa_config_txg;
6233 spa_set_log_state(newspa, SPA_LOG_CLEAR);
6235 /* release the spa config lock, retaining the namespace lock */
6236 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6238 if (zio_injection_enabled)
6239 zio_handle_panic_injection(spa, FTAG, 1);
6241 spa_activate(newspa, spa_mode_global);
6242 spa_async_suspend(newspa);
6245 /* mark that we are creating new spa by splitting */
6246 newspa->spa_splitting_newspa = B_TRUE;
6248 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
6250 /* create the new pool from the disks of the original pool */
6251 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
6253 newspa->spa_splitting_newspa = B_FALSE;
6258 /* if that worked, generate a real config for the new pool */
6259 if (newspa->spa_root_vdev != NULL) {
6260 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
6261 NV_UNIQUE_NAME, KM_SLEEP) == 0);
6262 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
6263 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
6264 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
6269 if (props != NULL) {
6270 spa_configfile_set(newspa, props, B_FALSE);
6271 error = spa_prop_set(newspa, props);
6276 /* flush everything */
6277 txg = spa_vdev_config_enter(newspa);
6278 vdev_config_dirty(newspa->spa_root_vdev);
6279 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
6281 if (zio_injection_enabled)
6282 zio_handle_panic_injection(spa, FTAG, 2);
6284 spa_async_resume(newspa);
6286 /* finally, update the original pool's config */
6287 txg = spa_vdev_config_enter(spa);
6288 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
6289 error = dmu_tx_assign(tx, TXG_WAIT);
6292 for (c = 0; c < children; c++) {
6293 if (vml[c] != NULL) {
6296 spa_history_log_internal(spa, "detach", tx,
6297 "vdev=%s", vml[c]->vdev_path);
6302 spa->spa_avz_action = AVZ_ACTION_REBUILD;
6303 vdev_config_dirty(spa->spa_root_vdev);
6304 spa->spa_config_splitting = NULL;
6308 (void) spa_vdev_exit(spa, NULL, txg, 0);
6310 if (zio_injection_enabled)
6311 zio_handle_panic_injection(spa, FTAG, 3);
6313 /* split is complete; log a history record */
6314 spa_history_log_internal(newspa, "split", NULL,
6315 "from pool %s", spa_name(spa));
6317 kmem_free(vml, children * sizeof (vdev_t *));
6319 /* if we're not going to mount the filesystems in userland, export */
6321 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
6328 spa_deactivate(newspa);
6331 txg = spa_vdev_config_enter(spa);
6333 /* re-online all offlined disks */
6334 for (c = 0; c < children; c++) {
6336 vml[c]->vdev_offline = B_FALSE;
6338 vdev_reopen(spa->spa_root_vdev);
6340 nvlist_free(spa->spa_config_splitting);
6341 spa->spa_config_splitting = NULL;
6342 (void) spa_vdev_exit(spa, NULL, txg, error);
6344 kmem_free(vml, children * sizeof (vdev_t *));
6349 * Find any device that's done replacing, or a vdev marked 'unspare' that's
6350 * currently spared, so we can detach it.
6353 spa_vdev_resilver_done_hunt(vdev_t *vd)
6355 vdev_t *newvd, *oldvd;
6357 for (int c = 0; c < vd->vdev_children; c++) {
6358 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
6364 * Check for a completed replacement. We always consider the first
6365 * vdev in the list to be the oldest vdev, and the last one to be
6366 * the newest (see spa_vdev_attach() for how that works). In
6367 * the case where the newest vdev is faulted, we will not automatically
6368 * remove it after a resilver completes. This is OK as it will require
6369 * user intervention to determine which disk the admin wishes to keep.
6371 if (vd->vdev_ops == &vdev_replacing_ops) {
6372 ASSERT(vd->vdev_children > 1);
6374 newvd = vd->vdev_child[vd->vdev_children - 1];
6375 oldvd = vd->vdev_child[0];
6377 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
6378 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6379 !vdev_dtl_required(oldvd))
6384 * Check for a completed resilver with the 'unspare' flag set.
6386 if (vd->vdev_ops == &vdev_spare_ops) {
6387 vdev_t *first = vd->vdev_child[0];
6388 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
6390 if (last->vdev_unspare) {
6393 } else if (first->vdev_unspare) {
6400 if (oldvd != NULL &&
6401 vdev_dtl_empty(newvd, DTL_MISSING) &&
6402 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6403 !vdev_dtl_required(oldvd))
6407 * If there are more than two spares attached to a disk,
6408 * and those spares are not required, then we want to
6409 * attempt to free them up now so that they can be used
6410 * by other pools. Once we're back down to a single
6411 * disk+spare, we stop removing them.
6413 if (vd->vdev_children > 2) {
6414 newvd = vd->vdev_child[1];
6416 if (newvd->vdev_isspare && last->vdev_isspare &&
6417 vdev_dtl_empty(last, DTL_MISSING) &&
6418 vdev_dtl_empty(last, DTL_OUTAGE) &&
6419 !vdev_dtl_required(newvd))
6428 spa_vdev_resilver_done(spa_t *spa)
6430 vdev_t *vd, *pvd, *ppvd;
6431 uint64_t guid, sguid, pguid, ppguid;
6433 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6435 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
6436 pvd = vd->vdev_parent;
6437 ppvd = pvd->vdev_parent;
6438 guid = vd->vdev_guid;
6439 pguid = pvd->vdev_guid;
6440 ppguid = ppvd->vdev_guid;
6443 * If we have just finished replacing a hot spared device, then
6444 * we need to detach the parent's first child (the original hot
6447 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
6448 ppvd->vdev_children == 2) {
6449 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
6450 sguid = ppvd->vdev_child[1]->vdev_guid;
6452 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
6454 spa_config_exit(spa, SCL_ALL, FTAG);
6455 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
6457 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
6459 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6462 spa_config_exit(spa, SCL_ALL, FTAG);
6466 * Update the stored path or FRU for this vdev.
6469 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
6473 boolean_t sync = B_FALSE;
6475 ASSERT(spa_writeable(spa));
6477 spa_vdev_state_enter(spa, SCL_ALL);
6479 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
6480 return (spa_vdev_state_exit(spa, NULL, ENOENT));
6482 if (!vd->vdev_ops->vdev_op_leaf)
6483 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
6486 if (strcmp(value, vd->vdev_path) != 0) {
6487 spa_strfree(vd->vdev_path);
6488 vd->vdev_path = spa_strdup(value);
6492 if (vd->vdev_fru == NULL) {
6493 vd->vdev_fru = spa_strdup(value);
6495 } else if (strcmp(value, vd->vdev_fru) != 0) {
6496 spa_strfree(vd->vdev_fru);
6497 vd->vdev_fru = spa_strdup(value);
6502 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
6506 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
6508 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
6512 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
6514 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
6518 * ==========================================================================
6520 * ==========================================================================
6523 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
6525 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6527 if (dsl_scan_resilvering(spa->spa_dsl_pool))
6528 return (SET_ERROR(EBUSY));
6530 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
6534 spa_scan_stop(spa_t *spa)
6536 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6537 if (dsl_scan_resilvering(spa->spa_dsl_pool))
6538 return (SET_ERROR(EBUSY));
6539 return (dsl_scan_cancel(spa->spa_dsl_pool));
6543 spa_scan(spa_t *spa, pool_scan_func_t func)
6545 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6547 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
6548 return (SET_ERROR(ENOTSUP));
6551 * If a resilver was requested, but there is no DTL on a
6552 * writeable leaf device, we have nothing to do.
6554 if (func == POOL_SCAN_RESILVER &&
6555 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
6556 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
6560 return (dsl_scan(spa->spa_dsl_pool, func));
6564 * ==========================================================================
6565 * SPA async task processing
6566 * ==========================================================================
6570 spa_async_remove(spa_t *spa, vdev_t *vd)
6572 if (vd->vdev_remove_wanted) {
6573 vd->vdev_remove_wanted = B_FALSE;
6574 vd->vdev_delayed_close = B_FALSE;
6575 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
6578 * We want to clear the stats, but we don't want to do a full
6579 * vdev_clear() as that will cause us to throw away
6580 * degraded/faulted state as well as attempt to reopen the
6581 * device, all of which is a waste.
6583 vd->vdev_stat.vs_read_errors = 0;
6584 vd->vdev_stat.vs_write_errors = 0;
6585 vd->vdev_stat.vs_checksum_errors = 0;
6587 vdev_state_dirty(vd->vdev_top);
6588 /* Tell userspace that the vdev is gone. */
6589 zfs_post_remove(spa, vd);
6592 for (int c = 0; c < vd->vdev_children; c++)
6593 spa_async_remove(spa, vd->vdev_child[c]);
6597 spa_async_probe(spa_t *spa, vdev_t *vd)
6599 if (vd->vdev_probe_wanted) {
6600 vd->vdev_probe_wanted = B_FALSE;
6601 vdev_reopen(vd); /* vdev_open() does the actual probe */
6604 for (int c = 0; c < vd->vdev_children; c++)
6605 spa_async_probe(spa, vd->vdev_child[c]);
6609 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
6615 if (!spa->spa_autoexpand)
6618 for (int c = 0; c < vd->vdev_children; c++) {
6619 vdev_t *cvd = vd->vdev_child[c];
6620 spa_async_autoexpand(spa, cvd);
6623 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
6626 physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
6627 (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
6629 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6630 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
6632 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
6633 ESC_ZFS_VDEV_AUTOEXPAND, attr, &eid, DDI_SLEEP);
6636 kmem_free(physpath, MAXPATHLEN);
6640 spa_async_thread(void *arg)
6642 spa_t *spa = (spa_t *)arg;
6645 ASSERT(spa->spa_sync_on);
6647 mutex_enter(&spa->spa_async_lock);
6648 tasks = spa->spa_async_tasks;
6649 spa->spa_async_tasks &= SPA_ASYNC_REMOVE;
6650 mutex_exit(&spa->spa_async_lock);
6653 * See if the config needs to be updated.
6655 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
6656 uint64_t old_space, new_space;
6658 mutex_enter(&spa_namespace_lock);
6659 old_space = metaslab_class_get_space(spa_normal_class(spa));
6660 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
6661 new_space = metaslab_class_get_space(spa_normal_class(spa));
6662 mutex_exit(&spa_namespace_lock);
6665 * If the pool grew as a result of the config update,
6666 * then log an internal history event.
6668 if (new_space != old_space) {
6669 spa_history_log_internal(spa, "vdev online", NULL,
6670 "pool '%s' size: %llu(+%llu)",
6671 spa_name(spa), new_space, new_space - old_space);
6675 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
6676 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6677 spa_async_autoexpand(spa, spa->spa_root_vdev);
6678 spa_config_exit(spa, SCL_CONFIG, FTAG);
6682 * See if any devices need to be probed.
6684 if (tasks & SPA_ASYNC_PROBE) {
6685 spa_vdev_state_enter(spa, SCL_NONE);
6686 spa_async_probe(spa, spa->spa_root_vdev);
6687 (void) spa_vdev_state_exit(spa, NULL, 0);
6691 * If any devices are done replacing, detach them.
6693 if (tasks & SPA_ASYNC_RESILVER_DONE)
6694 spa_vdev_resilver_done(spa);
6697 * Kick off a resilver.
6699 if (tasks & SPA_ASYNC_RESILVER)
6700 dsl_resilver_restart(spa->spa_dsl_pool, 0);
6703 * Let the world know that we're done.
6705 mutex_enter(&spa->spa_async_lock);
6706 spa->spa_async_thread = NULL;
6707 cv_broadcast(&spa->spa_async_cv);
6708 mutex_exit(&spa->spa_async_lock);
6713 spa_async_thread_vd(void *arg)
6718 mutex_enter(&spa->spa_async_lock);
6719 tasks = spa->spa_async_tasks;
6721 spa->spa_async_tasks &= ~SPA_ASYNC_REMOVE;
6722 mutex_exit(&spa->spa_async_lock);
6725 * See if any devices need to be marked REMOVED.
6727 if (tasks & SPA_ASYNC_REMOVE) {
6728 spa_vdev_state_enter(spa, SCL_NONE);
6729 spa_async_remove(spa, spa->spa_root_vdev);
6730 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
6731 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
6732 for (int i = 0; i < spa->spa_spares.sav_count; i++)
6733 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
6734 (void) spa_vdev_state_exit(spa, NULL, 0);
6738 * Let the world know that we're done.
6740 mutex_enter(&spa->spa_async_lock);
6741 tasks = spa->spa_async_tasks;
6742 if ((tasks & SPA_ASYNC_REMOVE) != 0)
6744 spa->spa_async_thread_vd = NULL;
6745 cv_broadcast(&spa->spa_async_cv);
6746 mutex_exit(&spa->spa_async_lock);
6751 spa_async_suspend(spa_t *spa)
6753 mutex_enter(&spa->spa_async_lock);
6754 spa->spa_async_suspended++;
6755 while (spa->spa_async_thread != NULL ||
6756 spa->spa_async_thread_vd != NULL)
6757 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
6758 mutex_exit(&spa->spa_async_lock);
6760 spa_vdev_remove_suspend(spa);
6762 zthr_t *condense_thread = spa->spa_condense_zthr;
6763 if (condense_thread != NULL && zthr_isrunning(condense_thread))
6764 VERIFY0(zthr_cancel(condense_thread));
6768 spa_async_resume(spa_t *spa)
6770 mutex_enter(&spa->spa_async_lock);
6771 ASSERT(spa->spa_async_suspended != 0);
6772 spa->spa_async_suspended--;
6773 mutex_exit(&spa->spa_async_lock);
6774 spa_restart_removal(spa);
6776 zthr_t *condense_thread = spa->spa_condense_zthr;
6777 if (condense_thread != NULL && !zthr_isrunning(condense_thread))
6778 zthr_resume(condense_thread);
6782 spa_async_tasks_pending(spa_t *spa)
6784 uint_t non_config_tasks;
6786 boolean_t config_task_suspended;
6788 non_config_tasks = spa->spa_async_tasks & ~(SPA_ASYNC_CONFIG_UPDATE |
6790 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
6791 if (spa->spa_ccw_fail_time == 0) {
6792 config_task_suspended = B_FALSE;
6794 config_task_suspended =
6795 (gethrtime() - spa->spa_ccw_fail_time) <
6796 (zfs_ccw_retry_interval * NANOSEC);
6799 return (non_config_tasks || (config_task && !config_task_suspended));
6803 spa_async_dispatch(spa_t *spa)
6805 mutex_enter(&spa->spa_async_lock);
6806 if (spa_async_tasks_pending(spa) &&
6807 !spa->spa_async_suspended &&
6808 spa->spa_async_thread == NULL &&
6810 spa->spa_async_thread = thread_create(NULL, 0,
6811 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
6812 mutex_exit(&spa->spa_async_lock);
6816 spa_async_dispatch_vd(spa_t *spa)
6818 mutex_enter(&spa->spa_async_lock);
6819 if ((spa->spa_async_tasks & SPA_ASYNC_REMOVE) != 0 &&
6820 !spa->spa_async_suspended &&
6821 spa->spa_async_thread_vd == NULL &&
6823 spa->spa_async_thread_vd = thread_create(NULL, 0,
6824 spa_async_thread_vd, spa, 0, &p0, TS_RUN, maxclsyspri);
6825 mutex_exit(&spa->spa_async_lock);
6829 spa_async_request(spa_t *spa, int task)
6831 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
6832 mutex_enter(&spa->spa_async_lock);
6833 spa->spa_async_tasks |= task;
6834 mutex_exit(&spa->spa_async_lock);
6835 spa_async_dispatch_vd(spa);
6839 * ==========================================================================
6840 * SPA syncing routines
6841 * ==========================================================================
6845 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6848 bpobj_enqueue(bpo, bp, tx);
6853 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6857 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
6858 BP_GET_PSIZE(bp), zio->io_flags));
6863 * Note: this simple function is not inlined to make it easier to dtrace the
6864 * amount of time spent syncing frees.
6867 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
6869 zio_t *zio = zio_root(spa, NULL, NULL, 0);
6870 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
6871 VERIFY(zio_wait(zio) == 0);
6875 * Note: this simple function is not inlined to make it easier to dtrace the
6876 * amount of time spent syncing deferred frees.
6879 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
6881 zio_t *zio = zio_root(spa, NULL, NULL, 0);
6882 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
6883 spa_free_sync_cb, zio, tx), ==, 0);
6884 VERIFY0(zio_wait(zio));
6889 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
6891 char *packed = NULL;
6896 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
6899 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
6900 * information. This avoids the dmu_buf_will_dirty() path and
6901 * saves us a pre-read to get data we don't actually care about.
6903 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
6904 packed = kmem_alloc(bufsize, KM_SLEEP);
6906 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
6908 bzero(packed + nvsize, bufsize - nvsize);
6910 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
6912 kmem_free(packed, bufsize);
6914 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
6915 dmu_buf_will_dirty(db, tx);
6916 *(uint64_t *)db->db_data = nvsize;
6917 dmu_buf_rele(db, FTAG);
6921 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
6922 const char *config, const char *entry)
6932 * Update the MOS nvlist describing the list of available devices.
6933 * spa_validate_aux() will have already made sure this nvlist is
6934 * valid and the vdevs are labeled appropriately.
6936 if (sav->sav_object == 0) {
6937 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
6938 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
6939 sizeof (uint64_t), tx);
6940 VERIFY(zap_update(spa->spa_meta_objset,
6941 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
6942 &sav->sav_object, tx) == 0);
6945 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6946 if (sav->sav_count == 0) {
6947 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
6949 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
6950 for (i = 0; i < sav->sav_count; i++)
6951 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
6952 B_FALSE, VDEV_CONFIG_L2CACHE);
6953 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
6954 sav->sav_count) == 0);
6955 for (i = 0; i < sav->sav_count; i++)
6956 nvlist_free(list[i]);
6957 kmem_free(list, sav->sav_count * sizeof (void *));
6960 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
6961 nvlist_free(nvroot);
6963 sav->sav_sync = B_FALSE;
6967 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
6968 * The all-vdev ZAP must be empty.
6971 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
6973 spa_t *spa = vd->vdev_spa;
6974 if (vd->vdev_top_zap != 0) {
6975 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
6976 vd->vdev_top_zap, tx));
6978 if (vd->vdev_leaf_zap != 0) {
6979 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
6980 vd->vdev_leaf_zap, tx));
6982 for (uint64_t i = 0; i < vd->vdev_children; i++) {
6983 spa_avz_build(vd->vdev_child[i], avz, tx);
6988 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
6993 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
6994 * its config may not be dirty but we still need to build per-vdev ZAPs.
6995 * Similarly, if the pool is being assembled (e.g. after a split), we
6996 * need to rebuild the AVZ although the config may not be dirty.
6998 if (list_is_empty(&spa->spa_config_dirty_list) &&
6999 spa->spa_avz_action == AVZ_ACTION_NONE)
7002 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7004 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
7005 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
7006 spa->spa_all_vdev_zaps != 0);
7008 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
7009 /* Make and build the new AVZ */
7010 uint64_t new_avz = zap_create(spa->spa_meta_objset,
7011 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7012 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7014 /* Diff old AVZ with new one */
7018 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7019 spa->spa_all_vdev_zaps);
7020 zap_cursor_retrieve(&zc, &za) == 0;
7021 zap_cursor_advance(&zc)) {
7022 uint64_t vdzap = za.za_first_integer;
7023 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
7026 * ZAP is listed in old AVZ but not in new one;
7029 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
7034 zap_cursor_fini(&zc);
7036 /* Destroy the old AVZ */
7037 VERIFY0(zap_destroy(spa->spa_meta_objset,
7038 spa->spa_all_vdev_zaps, tx));
7040 /* Replace the old AVZ in the dir obj with the new one */
7041 VERIFY0(zap_update(spa->spa_meta_objset,
7042 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
7043 sizeof (new_avz), 1, &new_avz, tx));
7045 spa->spa_all_vdev_zaps = new_avz;
7046 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
7050 /* Walk through the AVZ and destroy all listed ZAPs */
7051 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7052 spa->spa_all_vdev_zaps);
7053 zap_cursor_retrieve(&zc, &za) == 0;
7054 zap_cursor_advance(&zc)) {
7055 uint64_t zap = za.za_first_integer;
7056 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
7059 zap_cursor_fini(&zc);
7061 /* Destroy and unlink the AVZ itself */
7062 VERIFY0(zap_destroy(spa->spa_meta_objset,
7063 spa->spa_all_vdev_zaps, tx));
7064 VERIFY0(zap_remove(spa->spa_meta_objset,
7065 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
7066 spa->spa_all_vdev_zaps = 0;
7069 if (spa->spa_all_vdev_zaps == 0) {
7070 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
7071 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
7072 DMU_POOL_VDEV_ZAP_MAP, tx);
7074 spa->spa_avz_action = AVZ_ACTION_NONE;
7076 /* Create ZAPs for vdevs that don't have them. */
7077 vdev_construct_zaps(spa->spa_root_vdev, tx);
7079 config = spa_config_generate(spa, spa->spa_root_vdev,
7080 dmu_tx_get_txg(tx), B_FALSE);
7083 * If we're upgrading the spa version then make sure that
7084 * the config object gets updated with the correct version.
7086 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
7087 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7088 spa->spa_uberblock.ub_version);
7090 spa_config_exit(spa, SCL_STATE, FTAG);
7092 nvlist_free(spa->spa_config_syncing);
7093 spa->spa_config_syncing = config;
7095 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
7099 spa_sync_version(void *arg, dmu_tx_t *tx)
7101 uint64_t *versionp = arg;
7102 uint64_t version = *versionp;
7103 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7106 * Setting the version is special cased when first creating the pool.
7108 ASSERT(tx->tx_txg != TXG_INITIAL);
7110 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
7111 ASSERT(version >= spa_version(spa));
7113 spa->spa_uberblock.ub_version = version;
7114 vdev_config_dirty(spa->spa_root_vdev);
7115 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
7119 * Set zpool properties.
7122 spa_sync_props(void *arg, dmu_tx_t *tx)
7124 nvlist_t *nvp = arg;
7125 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7126 objset_t *mos = spa->spa_meta_objset;
7127 nvpair_t *elem = NULL;
7129 mutex_enter(&spa->spa_props_lock);
7131 while ((elem = nvlist_next_nvpair(nvp, elem))) {
7133 char *strval, *fname;
7135 const char *propname;
7136 zprop_type_t proptype;
7139 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
7140 case ZPOOL_PROP_INVAL:
7142 * We checked this earlier in spa_prop_validate().
7144 ASSERT(zpool_prop_feature(nvpair_name(elem)));
7146 fname = strchr(nvpair_name(elem), '@') + 1;
7147 VERIFY0(zfeature_lookup_name(fname, &fid));
7149 spa_feature_enable(spa, fid, tx);
7150 spa_history_log_internal(spa, "set", tx,
7151 "%s=enabled", nvpair_name(elem));
7154 case ZPOOL_PROP_VERSION:
7155 intval = fnvpair_value_uint64(elem);
7157 * The version is synced seperatly before other
7158 * properties and should be correct by now.
7160 ASSERT3U(spa_version(spa), >=, intval);
7163 case ZPOOL_PROP_ALTROOT:
7165 * 'altroot' is a non-persistent property. It should
7166 * have been set temporarily at creation or import time.
7168 ASSERT(spa->spa_root != NULL);
7171 case ZPOOL_PROP_READONLY:
7172 case ZPOOL_PROP_CACHEFILE:
7174 * 'readonly' and 'cachefile' are also non-persisitent
7178 case ZPOOL_PROP_COMMENT:
7179 strval = fnvpair_value_string(elem);
7180 if (spa->spa_comment != NULL)
7181 spa_strfree(spa->spa_comment);
7182 spa->spa_comment = spa_strdup(strval);
7184 * We need to dirty the configuration on all the vdevs
7185 * so that their labels get updated. It's unnecessary
7186 * to do this for pool creation since the vdev's
7187 * configuratoin has already been dirtied.
7189 if (tx->tx_txg != TXG_INITIAL)
7190 vdev_config_dirty(spa->spa_root_vdev);
7191 spa_history_log_internal(spa, "set", tx,
7192 "%s=%s", nvpair_name(elem), strval);
7196 * Set pool property values in the poolprops mos object.
7198 if (spa->spa_pool_props_object == 0) {
7199 spa->spa_pool_props_object =
7200 zap_create_link(mos, DMU_OT_POOL_PROPS,
7201 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
7205 /* normalize the property name */
7206 propname = zpool_prop_to_name(prop);
7207 proptype = zpool_prop_get_type(prop);
7209 if (nvpair_type(elem) == DATA_TYPE_STRING) {
7210 ASSERT(proptype == PROP_TYPE_STRING);
7211 strval = fnvpair_value_string(elem);
7212 VERIFY0(zap_update(mos,
7213 spa->spa_pool_props_object, propname,
7214 1, strlen(strval) + 1, strval, tx));
7215 spa_history_log_internal(spa, "set", tx,
7216 "%s=%s", nvpair_name(elem), strval);
7217 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
7218 intval = fnvpair_value_uint64(elem);
7220 if (proptype == PROP_TYPE_INDEX) {
7222 VERIFY0(zpool_prop_index_to_string(
7223 prop, intval, &unused));
7225 VERIFY0(zap_update(mos,
7226 spa->spa_pool_props_object, propname,
7227 8, 1, &intval, tx));
7228 spa_history_log_internal(spa, "set", tx,
7229 "%s=%lld", nvpair_name(elem), intval);
7231 ASSERT(0); /* not allowed */
7235 case ZPOOL_PROP_DELEGATION:
7236 spa->spa_delegation = intval;
7238 case ZPOOL_PROP_BOOTFS:
7239 spa->spa_bootfs = intval;
7241 case ZPOOL_PROP_FAILUREMODE:
7242 spa->spa_failmode = intval;
7244 case ZPOOL_PROP_AUTOEXPAND:
7245 spa->spa_autoexpand = intval;
7246 if (tx->tx_txg != TXG_INITIAL)
7247 spa_async_request(spa,
7248 SPA_ASYNC_AUTOEXPAND);
7250 case ZPOOL_PROP_DEDUPDITTO:
7251 spa->spa_dedup_ditto = intval;
7260 mutex_exit(&spa->spa_props_lock);
7264 * Perform one-time upgrade on-disk changes. spa_version() does not
7265 * reflect the new version this txg, so there must be no changes this
7266 * txg to anything that the upgrade code depends on after it executes.
7267 * Therefore this must be called after dsl_pool_sync() does the sync
7271 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
7273 dsl_pool_t *dp = spa->spa_dsl_pool;
7275 ASSERT(spa->spa_sync_pass == 1);
7277 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
7279 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
7280 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
7281 dsl_pool_create_origin(dp, tx);
7283 /* Keeping the origin open increases spa_minref */
7284 spa->spa_minref += 3;
7287 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
7288 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
7289 dsl_pool_upgrade_clones(dp, tx);
7292 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
7293 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
7294 dsl_pool_upgrade_dir_clones(dp, tx);
7296 /* Keeping the freedir open increases spa_minref */
7297 spa->spa_minref += 3;
7300 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
7301 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7302 spa_feature_create_zap_objects(spa, tx);
7306 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
7307 * when possibility to use lz4 compression for metadata was added
7308 * Old pools that have this feature enabled must be upgraded to have
7309 * this feature active
7311 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7312 boolean_t lz4_en = spa_feature_is_enabled(spa,
7313 SPA_FEATURE_LZ4_COMPRESS);
7314 boolean_t lz4_ac = spa_feature_is_active(spa,
7315 SPA_FEATURE_LZ4_COMPRESS);
7317 if (lz4_en && !lz4_ac)
7318 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
7322 * If we haven't written the salt, do so now. Note that the
7323 * feature may not be activated yet, but that's fine since
7324 * the presence of this ZAP entry is backwards compatible.
7326 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7327 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
7328 VERIFY0(zap_add(spa->spa_meta_objset,
7329 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
7330 sizeof (spa->spa_cksum_salt.zcs_bytes),
7331 spa->spa_cksum_salt.zcs_bytes, tx));
7334 rrw_exit(&dp->dp_config_rwlock, FTAG);
7338 vdev_indirect_state_sync_verify(vdev_t *vd)
7340 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
7341 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
7343 if (vd->vdev_ops == &vdev_indirect_ops) {
7344 ASSERT(vim != NULL);
7345 ASSERT(vib != NULL);
7348 if (vdev_obsolete_sm_object(vd) != 0) {
7349 ASSERT(vd->vdev_obsolete_sm != NULL);
7350 ASSERT(vd->vdev_removing ||
7351 vd->vdev_ops == &vdev_indirect_ops);
7352 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
7353 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
7355 ASSERT3U(vdev_obsolete_sm_object(vd), ==,
7356 space_map_object(vd->vdev_obsolete_sm));
7357 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
7358 space_map_allocated(vd->vdev_obsolete_sm));
7360 ASSERT(vd->vdev_obsolete_segments != NULL);
7363 * Since frees / remaps to an indirect vdev can only
7364 * happen in syncing context, the obsolete segments
7365 * tree must be empty when we start syncing.
7367 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
7371 * Sync the specified transaction group. New blocks may be dirtied as
7372 * part of the process, so we iterate until it converges.
7375 spa_sync(spa_t *spa, uint64_t txg)
7377 dsl_pool_t *dp = spa->spa_dsl_pool;
7378 objset_t *mos = spa->spa_meta_objset;
7379 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
7380 vdev_t *rvd = spa->spa_root_vdev;
7384 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
7385 zfs_vdev_queue_depth_pct / 100;
7387 VERIFY(spa_writeable(spa));
7390 * Wait for i/os issued in open context that need to complete
7391 * before this txg syncs.
7393 VERIFY0(zio_wait(spa->spa_txg_zio[txg & TXG_MASK]));
7394 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL, 0);
7397 * Lock out configuration changes.
7399 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7401 spa->spa_syncing_txg = txg;
7402 spa->spa_sync_pass = 0;
7404 mutex_enter(&spa->spa_alloc_lock);
7405 VERIFY0(avl_numnodes(&spa->spa_alloc_tree));
7406 mutex_exit(&spa->spa_alloc_lock);
7409 * If there are any pending vdev state changes, convert them
7410 * into config changes that go out with this transaction group.
7412 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7413 while (list_head(&spa->spa_state_dirty_list) != NULL) {
7415 * We need the write lock here because, for aux vdevs,
7416 * calling vdev_config_dirty() modifies sav_config.
7417 * This is ugly and will become unnecessary when we
7418 * eliminate the aux vdev wart by integrating all vdevs
7419 * into the root vdev tree.
7421 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7422 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
7423 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
7424 vdev_state_clean(vd);
7425 vdev_config_dirty(vd);
7427 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7428 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
7430 spa_config_exit(spa, SCL_STATE, FTAG);
7432 tx = dmu_tx_create_assigned(dp, txg);
7434 spa->spa_sync_starttime = gethrtime();
7436 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
7437 spa->spa_sync_starttime + spa->spa_deadman_synctime));
7438 #else /* !illumos */
7440 callout_schedule(&spa->spa_deadman_cycid,
7441 hz * spa->spa_deadman_synctime / NANOSEC);
7443 #endif /* illumos */
7446 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
7447 * set spa_deflate if we have no raid-z vdevs.
7449 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
7450 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
7453 for (i = 0; i < rvd->vdev_children; i++) {
7454 vd = rvd->vdev_child[i];
7455 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
7458 if (i == rvd->vdev_children) {
7459 spa->spa_deflate = TRUE;
7460 VERIFY(0 == zap_add(spa->spa_meta_objset,
7461 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
7462 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
7467 * Set the top-level vdev's max queue depth. Evaluate each
7468 * top-level's async write queue depth in case it changed.
7469 * The max queue depth will not change in the middle of syncing
7472 uint64_t queue_depth_total = 0;
7473 for (int c = 0; c < rvd->vdev_children; c++) {
7474 vdev_t *tvd = rvd->vdev_child[c];
7475 metaslab_group_t *mg = tvd->vdev_mg;
7477 if (mg == NULL || mg->mg_class != spa_normal_class(spa) ||
7478 !metaslab_group_initialized(mg))
7482 * It is safe to do a lock-free check here because only async
7483 * allocations look at mg_max_alloc_queue_depth, and async
7484 * allocations all happen from spa_sync().
7486 ASSERT0(refcount_count(&mg->mg_alloc_queue_depth));
7487 mg->mg_max_alloc_queue_depth = max_queue_depth;
7488 queue_depth_total += mg->mg_max_alloc_queue_depth;
7490 metaslab_class_t *mc = spa_normal_class(spa);
7491 ASSERT0(refcount_count(&mc->mc_alloc_slots));
7492 mc->mc_alloc_max_slots = queue_depth_total;
7493 mc->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
7495 ASSERT3U(mc->mc_alloc_max_slots, <=,
7496 max_queue_depth * rvd->vdev_children);
7498 for (int c = 0; c < rvd->vdev_children; c++) {
7499 vdev_t *vd = rvd->vdev_child[c];
7500 vdev_indirect_state_sync_verify(vd);
7502 if (vdev_indirect_should_condense(vd)) {
7503 spa_condense_indirect_start_sync(vd, tx);
7509 * Iterate to convergence.
7512 int pass = ++spa->spa_sync_pass;
7514 spa_sync_config_object(spa, tx);
7515 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
7516 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
7517 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
7518 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
7519 spa_errlog_sync(spa, txg);
7520 dsl_pool_sync(dp, txg);
7522 if (pass < zfs_sync_pass_deferred_free) {
7523 spa_sync_frees(spa, free_bpl, tx);
7526 * We can not defer frees in pass 1, because
7527 * we sync the deferred frees later in pass 1.
7529 ASSERT3U(pass, >, 1);
7530 bplist_iterate(free_bpl, bpobj_enqueue_cb,
7531 &spa->spa_deferred_bpobj, tx);
7535 dsl_scan_sync(dp, tx);
7537 if (spa->spa_vdev_removal != NULL)
7540 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
7545 spa_sync_upgrades(spa, tx);
7547 spa->spa_uberblock.ub_rootbp.blk_birth);
7549 * Note: We need to check if the MOS is dirty
7550 * because we could have marked the MOS dirty
7551 * without updating the uberblock (e.g. if we
7552 * have sync tasks but no dirty user data). We
7553 * need to check the uberblock's rootbp because
7554 * it is updated if we have synced out dirty
7555 * data (though in this case the MOS will most
7556 * likely also be dirty due to second order
7557 * effects, we don't want to rely on that here).
7559 if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
7560 !dmu_objset_is_dirty(mos, txg)) {
7562 * Nothing changed on the first pass,
7563 * therefore this TXG is a no-op. Avoid
7564 * syncing deferred frees, so that we
7565 * can keep this TXG as a no-op.
7567 ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
7569 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
7570 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
7573 spa_sync_deferred_frees(spa, tx);
7576 } while (dmu_objset_is_dirty(mos, txg));
7578 if (!list_is_empty(&spa->spa_config_dirty_list)) {
7580 * Make sure that the number of ZAPs for all the vdevs matches
7581 * the number of ZAPs in the per-vdev ZAP list. This only gets
7582 * called if the config is dirty; otherwise there may be
7583 * outstanding AVZ operations that weren't completed in
7584 * spa_sync_config_object.
7586 uint64_t all_vdev_zap_entry_count;
7587 ASSERT0(zap_count(spa->spa_meta_objset,
7588 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
7589 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
7590 all_vdev_zap_entry_count);
7593 if (spa->spa_vdev_removal != NULL) {
7594 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
7598 * Rewrite the vdev configuration (which includes the uberblock)
7599 * to commit the transaction group.
7601 * If there are no dirty vdevs, we sync the uberblock to a few
7602 * random top-level vdevs that are known to be visible in the
7603 * config cache (see spa_vdev_add() for a complete description).
7604 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
7608 * We hold SCL_STATE to prevent vdev open/close/etc.
7609 * while we're attempting to write the vdev labels.
7611 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7613 if (list_is_empty(&spa->spa_config_dirty_list)) {
7614 vdev_t *svd[SPA_SYNC_MIN_VDEVS];
7616 int children = rvd->vdev_children;
7617 int c0 = spa_get_random(children);
7619 for (int c = 0; c < children; c++) {
7620 vd = rvd->vdev_child[(c0 + c) % children];
7621 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
7622 !vdev_is_concrete(vd))
7624 svd[svdcount++] = vd;
7625 if (svdcount == SPA_SYNC_MIN_VDEVS)
7628 error = vdev_config_sync(svd, svdcount, txg);
7630 error = vdev_config_sync(rvd->vdev_child,
7631 rvd->vdev_children, txg);
7635 spa->spa_last_synced_guid = rvd->vdev_guid;
7637 spa_config_exit(spa, SCL_STATE, FTAG);
7641 zio_suspend(spa, NULL);
7642 zio_resume_wait(spa);
7647 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
7648 #else /* !illumos */
7650 callout_drain(&spa->spa_deadman_cycid);
7652 #endif /* illumos */
7655 * Clear the dirty config list.
7657 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
7658 vdev_config_clean(vd);
7661 * Now that the new config has synced transactionally,
7662 * let it become visible to the config cache.
7664 if (spa->spa_config_syncing != NULL) {
7665 spa_config_set(spa, spa->spa_config_syncing);
7666 spa->spa_config_txg = txg;
7667 spa->spa_config_syncing = NULL;
7670 dsl_pool_sync_done(dp, txg);
7672 mutex_enter(&spa->spa_alloc_lock);
7673 VERIFY0(avl_numnodes(&spa->spa_alloc_tree));
7674 mutex_exit(&spa->spa_alloc_lock);
7677 * Update usable space statistics.
7679 while (vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
7680 vdev_sync_done(vd, txg);
7682 spa_update_dspace(spa);
7685 * It had better be the case that we didn't dirty anything
7686 * since vdev_config_sync().
7688 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
7689 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
7690 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
7692 spa->spa_sync_pass = 0;
7695 * Update the last synced uberblock here. We want to do this at
7696 * the end of spa_sync() so that consumers of spa_last_synced_txg()
7697 * will be guaranteed that all the processing associated with
7698 * that txg has been completed.
7700 spa->spa_ubsync = spa->spa_uberblock;
7701 spa_config_exit(spa, SCL_CONFIG, FTAG);
7703 spa_handle_ignored_writes(spa);
7706 * If any async tasks have been requested, kick them off.
7708 spa_async_dispatch(spa);
7709 spa_async_dispatch_vd(spa);
7713 * Sync all pools. We don't want to hold the namespace lock across these
7714 * operations, so we take a reference on the spa_t and drop the lock during the
7718 spa_sync_allpools(void)
7721 mutex_enter(&spa_namespace_lock);
7722 while ((spa = spa_next(spa)) != NULL) {
7723 if (spa_state(spa) != POOL_STATE_ACTIVE ||
7724 !spa_writeable(spa) || spa_suspended(spa))
7726 spa_open_ref(spa, FTAG);
7727 mutex_exit(&spa_namespace_lock);
7728 txg_wait_synced(spa_get_dsl(spa), 0);
7729 mutex_enter(&spa_namespace_lock);
7730 spa_close(spa, FTAG);
7732 mutex_exit(&spa_namespace_lock);
7736 * ==========================================================================
7737 * Miscellaneous routines
7738 * ==========================================================================
7742 * Remove all pools in the system.
7750 * Remove all cached state. All pools should be closed now,
7751 * so every spa in the AVL tree should be unreferenced.
7753 mutex_enter(&spa_namespace_lock);
7754 while ((spa = spa_next(NULL)) != NULL) {
7756 * Stop async tasks. The async thread may need to detach
7757 * a device that's been replaced, which requires grabbing
7758 * spa_namespace_lock, so we must drop it here.
7760 spa_open_ref(spa, FTAG);
7761 mutex_exit(&spa_namespace_lock);
7762 spa_async_suspend(spa);
7763 mutex_enter(&spa_namespace_lock);
7764 spa_close(spa, FTAG);
7766 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
7768 spa_deactivate(spa);
7772 mutex_exit(&spa_namespace_lock);
7776 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
7781 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
7785 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
7786 vd = spa->spa_l2cache.sav_vdevs[i];
7787 if (vd->vdev_guid == guid)
7791 for (i = 0; i < spa->spa_spares.sav_count; i++) {
7792 vd = spa->spa_spares.sav_vdevs[i];
7793 if (vd->vdev_guid == guid)
7802 spa_upgrade(spa_t *spa, uint64_t version)
7804 ASSERT(spa_writeable(spa));
7806 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7809 * This should only be called for a non-faulted pool, and since a
7810 * future version would result in an unopenable pool, this shouldn't be
7813 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
7814 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
7816 spa->spa_uberblock.ub_version = version;
7817 vdev_config_dirty(spa->spa_root_vdev);
7819 spa_config_exit(spa, SCL_ALL, FTAG);
7821 txg_wait_synced(spa_get_dsl(spa), 0);
7825 spa_has_spare(spa_t *spa, uint64_t guid)
7829 spa_aux_vdev_t *sav = &spa->spa_spares;
7831 for (i = 0; i < sav->sav_count; i++)
7832 if (sav->sav_vdevs[i]->vdev_guid == guid)
7835 for (i = 0; i < sav->sav_npending; i++) {
7836 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
7837 &spareguid) == 0 && spareguid == guid)
7845 * Check if a pool has an active shared spare device.
7846 * Note: reference count of an active spare is 2, as a spare and as a replace
7849 spa_has_active_shared_spare(spa_t *spa)
7853 spa_aux_vdev_t *sav = &spa->spa_spares;
7855 for (i = 0; i < sav->sav_count; i++) {
7856 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
7857 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
7866 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
7868 sysevent_t *ev = NULL;
7870 sysevent_attr_list_t *attr = NULL;
7871 sysevent_value_t value;
7873 ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
7877 value.value_type = SE_DATA_TYPE_STRING;
7878 value.value.sv_string = spa_name(spa);
7879 if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
7882 value.value_type = SE_DATA_TYPE_UINT64;
7883 value.value.sv_uint64 = spa_guid(spa);
7884 if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
7888 value.value_type = SE_DATA_TYPE_UINT64;
7889 value.value.sv_uint64 = vd->vdev_guid;
7890 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
7894 if (vd->vdev_path) {
7895 value.value_type = SE_DATA_TYPE_STRING;
7896 value.value.sv_string = vd->vdev_path;
7897 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
7898 &value, SE_SLEEP) != 0)
7903 if (hist_nvl != NULL) {
7904 fnvlist_merge((nvlist_t *)attr, hist_nvl);
7907 if (sysevent_attach_attributes(ev, attr) != 0)
7913 sysevent_free_attr(attr);
7920 spa_event_post(sysevent_t *ev)
7925 (void) log_sysevent(ev, SE_SLEEP, &eid);
7931 spa_event_discard(sysevent_t *ev)
7939 * Post a sysevent corresponding to the given event. The 'name' must be one of
7940 * the event definitions in sys/sysevent/eventdefs.h. The payload will be
7941 * filled in from the spa and (optionally) the vdev and history nvl. This
7942 * doesn't do anything in the userland libzpool, as we don't want consumers to
7943 * misinterpret ztest or zdb as real changes.
7946 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
7948 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));