4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25 * Copyright (c) 2015, Nexenta Systems, Inc. All rights reserved.
26 * Copyright (c) 2013 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
27 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28 * Copyright 2013 Saso Kiselkov. All rights reserved.
29 * Copyright (c) 2014 Integros [integros.com]
30 * Copyright 2016 Toomas Soome <tsoome@me.com>
31 * Copyright 2017 Joyent, Inc.
32 * Copyright (c) 2017 Datto Inc.
33 * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
37 * SPA: Storage Pool Allocator
39 * This file contains all the routines used when modifying on-disk SPA state.
40 * This includes opening, importing, destroying, exporting a pool, and syncing a
44 #include <sys/zfs_context.h>
45 #include <sys/fm/fs/zfs.h>
46 #include <sys/spa_impl.h>
48 #include <sys/zio_checksum.h>
50 #include <sys/dmu_tx.h>
54 #include <sys/vdev_impl.h>
55 #include <sys/vdev_removal.h>
56 #include <sys/vdev_indirect_mapping.h>
57 #include <sys/vdev_indirect_births.h>
58 #include <sys/vdev_initialize.h>
59 #include <sys/metaslab.h>
60 #include <sys/metaslab_impl.h>
61 #include <sys/uberblock_impl.h>
64 #include <sys/bpobj.h>
65 #include <sys/dmu_traverse.h>
66 #include <sys/dmu_objset.h>
67 #include <sys/unique.h>
68 #include <sys/dsl_pool.h>
69 #include <sys/dsl_dataset.h>
70 #include <sys/dsl_dir.h>
71 #include <sys/dsl_prop.h>
72 #include <sys/dsl_synctask.h>
73 #include <sys/fs/zfs.h>
75 #include <sys/callb.h>
76 #include <sys/spa_boot.h>
77 #include <sys/zfs_ioctl.h>
78 #include <sys/dsl_scan.h>
79 #include <sys/dmu_send.h>
80 #include <sys/dsl_destroy.h>
81 #include <sys/dsl_userhold.h>
82 #include <sys/zfeature.h>
84 #include <sys/trim_map.h>
88 #include <sys/callb.h>
89 #include <sys/cpupart.h>
94 #include "zfs_comutil.h"
96 /* Check hostid on import? */
97 static int check_hostid = 1;
100 * The interval, in seconds, at which failed configuration cache file writes
103 int zfs_ccw_retry_interval = 300;
105 SYSCTL_DECL(_vfs_zfs);
106 SYSCTL_INT(_vfs_zfs, OID_AUTO, check_hostid, CTLFLAG_RWTUN, &check_hostid, 0,
107 "Check hostid on import?");
108 TUNABLE_INT("vfs.zfs.ccw_retry_interval", &zfs_ccw_retry_interval);
109 SYSCTL_INT(_vfs_zfs, OID_AUTO, ccw_retry_interval, CTLFLAG_RW,
110 &zfs_ccw_retry_interval, 0,
111 "Configuration cache file write, retry after failure, interval (seconds)");
113 typedef enum zti_modes {
114 ZTI_MODE_FIXED, /* value is # of threads (min 1) */
115 ZTI_MODE_BATCH, /* cpu-intensive; value is ignored */
116 ZTI_MODE_NULL, /* don't create a taskq */
120 #define ZTI_P(n, q) { ZTI_MODE_FIXED, (n), (q) }
121 #define ZTI_BATCH { ZTI_MODE_BATCH, 0, 1 }
122 #define ZTI_NULL { ZTI_MODE_NULL, 0, 0 }
124 #define ZTI_N(n) ZTI_P(n, 1)
125 #define ZTI_ONE ZTI_N(1)
127 typedef struct zio_taskq_info {
128 zti_modes_t zti_mode;
133 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
134 "issue", "issue_high", "intr", "intr_high"
138 * This table defines the taskq settings for each ZFS I/O type. When
139 * initializing a pool, we use this table to create an appropriately sized
140 * taskq. Some operations are low volume and therefore have a small, static
141 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
142 * macros. Other operations process a large amount of data; the ZTI_BATCH
143 * macro causes us to create a taskq oriented for throughput. Some operations
144 * are so high frequency and short-lived that the taskq itself can become a a
145 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
146 * additional degree of parallelism specified by the number of threads per-
147 * taskq and the number of taskqs; when dispatching an event in this case, the
148 * particular taskq is chosen at random.
150 * The different taskq priorities are to handle the different contexts (issue
151 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
152 * need to be handled with minimum delay.
154 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
155 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
156 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* NULL */
157 { ZTI_N(8), ZTI_NULL, ZTI_P(12, 8), ZTI_NULL }, /* READ */
158 { ZTI_BATCH, ZTI_N(5), ZTI_N(8), ZTI_N(5) }, /* WRITE */
159 { ZTI_P(12, 8), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* FREE */
160 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* CLAIM */
161 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* IOCTL */
164 static void spa_sync_version(void *arg, dmu_tx_t *tx);
165 static void spa_sync_props(void *arg, dmu_tx_t *tx);
166 static boolean_t spa_has_active_shared_spare(spa_t *spa);
167 static int spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport);
168 static void spa_vdev_resilver_done(spa_t *spa);
170 uint_t zio_taskq_batch_pct = 75; /* 1 thread per cpu in pset */
172 id_t zio_taskq_psrset_bind = PS_NONE;
175 boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
176 uint_t zio_taskq_basedc = 80; /* base duty cycle */
179 boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
180 extern int zfs_sync_pass_deferred_free;
183 * Report any spa_load_verify errors found, but do not fail spa_load.
184 * This is used by zdb to analyze non-idle pools.
186 boolean_t spa_load_verify_dryrun = B_FALSE;
189 * This (illegal) pool name is used when temporarily importing a spa_t in order
190 * to get the vdev stats associated with the imported devices.
192 #define TRYIMPORT_NAME "$import"
195 * For debugging purposes: print out vdev tree during pool import.
197 int spa_load_print_vdev_tree = B_FALSE;
200 * A non-zero value for zfs_max_missing_tvds means that we allow importing
201 * pools with missing top-level vdevs. This is strictly intended for advanced
202 * pool recovery cases since missing data is almost inevitable. Pools with
203 * missing devices can only be imported read-only for safety reasons, and their
204 * fail-mode will be automatically set to "continue".
206 * With 1 missing vdev we should be able to import the pool and mount all
207 * datasets. User data that was not modified after the missing device has been
208 * added should be recoverable. This means that snapshots created prior to the
209 * addition of that device should be completely intact.
211 * With 2 missing vdevs, some datasets may fail to mount since there are
212 * dataset statistics that are stored as regular metadata. Some data might be
213 * recoverable if those vdevs were added recently.
215 * With 3 or more missing vdevs, the pool is severely damaged and MOS entries
216 * may be missing entirely. Chances of data recovery are very low. Note that
217 * there are also risks of performing an inadvertent rewind as we might be
218 * missing all the vdevs with the latest uberblocks.
220 uint64_t zfs_max_missing_tvds = 0;
223 * The parameters below are similar to zfs_max_missing_tvds but are only
224 * intended for a preliminary open of the pool with an untrusted config which
225 * might be incomplete or out-dated.
227 * We are more tolerant for pools opened from a cachefile since we could have
228 * an out-dated cachefile where a device removal was not registered.
229 * We could have set the limit arbitrarily high but in the case where devices
230 * are really missing we would want to return the proper error codes; we chose
231 * SPA_DVAS_PER_BP - 1 so that some copies of the MOS would still be available
232 * and we get a chance to retrieve the trusted config.
234 uint64_t zfs_max_missing_tvds_cachefile = SPA_DVAS_PER_BP - 1;
237 * In the case where config was assembled by scanning device paths (/dev/dsks
238 * by default) we are less tolerant since all the existing devices should have
239 * been detected and we want spa_load to return the right error codes.
241 uint64_t zfs_max_missing_tvds_scan = 0;
244 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_print_vdev_tree, CTLFLAG_RWTUN,
245 &spa_load_print_vdev_tree, 0,
246 "print out vdev tree during pool import");
247 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds, CTLFLAG_RWTUN,
248 &zfs_max_missing_tvds, 0,
249 "allow importing pools with missing top-level vdevs");
250 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_cachefile, CTLFLAG_RWTUN,
251 &zfs_max_missing_tvds_cachefile, 0,
252 "allow importing pools with missing top-level vdevs in cache file");
253 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, max_missing_tvds_scan, CTLFLAG_RWTUN,
254 &zfs_max_missing_tvds_scan, 0,
255 "allow importing pools with missing top-level vdevs during scan");
258 * Debugging aid that pauses spa_sync() towards the end.
260 boolean_t zfs_pause_spa_sync = B_FALSE;
263 * ==========================================================================
264 * SPA properties routines
265 * ==========================================================================
269 * Add a (source=src, propname=propval) list to an nvlist.
272 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
273 uint64_t intval, zprop_source_t src)
275 const char *propname = zpool_prop_to_name(prop);
278 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
279 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
282 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
284 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
286 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
287 nvlist_free(propval);
291 * Get property values from the spa configuration.
294 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
296 vdev_t *rvd = spa->spa_root_vdev;
297 dsl_pool_t *pool = spa->spa_dsl_pool;
298 uint64_t size, alloc, cap, version;
299 zprop_source_t src = ZPROP_SRC_NONE;
300 spa_config_dirent_t *dp;
301 metaslab_class_t *mc = spa_normal_class(spa);
303 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
306 alloc = metaslab_class_get_alloc(spa_normal_class(spa));
307 size = metaslab_class_get_space(spa_normal_class(spa));
308 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
309 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
310 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
311 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
313 spa_prop_add_list(*nvp, ZPOOL_PROP_CHECKPOINT, NULL,
314 spa->spa_checkpoint_info.sci_dspace, src);
316 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
317 metaslab_class_fragmentation(mc), src);
318 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
319 metaslab_class_expandable_space(mc), src);
320 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
321 (spa_mode(spa) == FREAD), src);
323 cap = (size == 0) ? 0 : (alloc * 100 / size);
324 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
326 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
327 ddt_get_pool_dedup_ratio(spa), src);
329 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
330 rvd->vdev_state, src);
332 version = spa_version(spa);
333 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
334 src = ZPROP_SRC_DEFAULT;
336 src = ZPROP_SRC_LOCAL;
337 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
342 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
343 * when opening pools before this version freedir will be NULL.
345 if (pool->dp_free_dir != NULL) {
346 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
347 dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes,
350 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
354 if (pool->dp_leak_dir != NULL) {
355 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
356 dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
359 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
364 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
366 if (spa->spa_comment != NULL) {
367 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
371 if (spa->spa_root != NULL)
372 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
375 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
376 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
377 MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
379 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
380 SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
383 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
384 if (dp->scd_path == NULL) {
385 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
386 "none", 0, ZPROP_SRC_LOCAL);
387 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
388 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
389 dp->scd_path, 0, ZPROP_SRC_LOCAL);
395 * Get zpool property values.
398 spa_prop_get(spa_t *spa, nvlist_t **nvp)
400 objset_t *mos = spa->spa_meta_objset;
405 VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
407 mutex_enter(&spa->spa_props_lock);
410 * Get properties from the spa config.
412 spa_prop_get_config(spa, nvp);
414 /* If no pool property object, no more prop to get. */
415 if (mos == NULL || spa->spa_pool_props_object == 0) {
416 mutex_exit(&spa->spa_props_lock);
421 * Get properties from the MOS pool property object.
423 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
424 (err = zap_cursor_retrieve(&zc, &za)) == 0;
425 zap_cursor_advance(&zc)) {
428 zprop_source_t src = ZPROP_SRC_DEFAULT;
431 if ((prop = zpool_name_to_prop(za.za_name)) == ZPOOL_PROP_INVAL)
434 switch (za.za_integer_length) {
436 /* integer property */
437 if (za.za_first_integer !=
438 zpool_prop_default_numeric(prop))
439 src = ZPROP_SRC_LOCAL;
441 if (prop == ZPOOL_PROP_BOOTFS) {
443 dsl_dataset_t *ds = NULL;
445 dp = spa_get_dsl(spa);
446 dsl_pool_config_enter(dp, FTAG);
447 err = dsl_dataset_hold_obj(dp,
448 za.za_first_integer, FTAG, &ds);
450 dsl_pool_config_exit(dp, FTAG);
454 strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
456 dsl_dataset_name(ds, strval);
457 dsl_dataset_rele(ds, FTAG);
458 dsl_pool_config_exit(dp, FTAG);
461 intval = za.za_first_integer;
464 spa_prop_add_list(*nvp, prop, strval, intval, src);
467 kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
472 /* string property */
473 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
474 err = zap_lookup(mos, spa->spa_pool_props_object,
475 za.za_name, 1, za.za_num_integers, strval);
477 kmem_free(strval, za.za_num_integers);
480 spa_prop_add_list(*nvp, prop, strval, 0, src);
481 kmem_free(strval, za.za_num_integers);
488 zap_cursor_fini(&zc);
489 mutex_exit(&spa->spa_props_lock);
491 if (err && err != ENOENT) {
501 * Validate the given pool properties nvlist and modify the list
502 * for the property values to be set.
505 spa_prop_validate(spa_t *spa, nvlist_t *props)
508 int error = 0, reset_bootfs = 0;
510 boolean_t has_feature = B_FALSE;
513 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
515 char *strval, *slash, *check, *fname;
516 const char *propname = nvpair_name(elem);
517 zpool_prop_t prop = zpool_name_to_prop(propname);
520 case ZPOOL_PROP_INVAL:
521 if (!zpool_prop_feature(propname)) {
522 error = SET_ERROR(EINVAL);
527 * Sanitize the input.
529 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
530 error = SET_ERROR(EINVAL);
534 if (nvpair_value_uint64(elem, &intval) != 0) {
535 error = SET_ERROR(EINVAL);
540 error = SET_ERROR(EINVAL);
544 fname = strchr(propname, '@') + 1;
545 if (zfeature_lookup_name(fname, NULL) != 0) {
546 error = SET_ERROR(EINVAL);
550 has_feature = B_TRUE;
553 case ZPOOL_PROP_VERSION:
554 error = nvpair_value_uint64(elem, &intval);
556 (intval < spa_version(spa) ||
557 intval > SPA_VERSION_BEFORE_FEATURES ||
559 error = SET_ERROR(EINVAL);
562 case ZPOOL_PROP_DELEGATION:
563 case ZPOOL_PROP_AUTOREPLACE:
564 case ZPOOL_PROP_LISTSNAPS:
565 case ZPOOL_PROP_AUTOEXPAND:
566 error = nvpair_value_uint64(elem, &intval);
567 if (!error && intval > 1)
568 error = SET_ERROR(EINVAL);
571 case ZPOOL_PROP_BOOTFS:
573 * If the pool version is less than SPA_VERSION_BOOTFS,
574 * or the pool is still being created (version == 0),
575 * the bootfs property cannot be set.
577 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
578 error = SET_ERROR(ENOTSUP);
583 * Make sure the vdev config is bootable
585 if (!vdev_is_bootable(spa->spa_root_vdev)) {
586 error = SET_ERROR(ENOTSUP);
592 error = nvpair_value_string(elem, &strval);
598 if (strval == NULL || strval[0] == '\0') {
599 objnum = zpool_prop_default_numeric(
604 error = dmu_objset_hold(strval, FTAG, &os);
609 * Must be ZPL, and its property settings
610 * must be supported by GRUB (compression
611 * is not gzip, and large blocks are not used).
614 if (dmu_objset_type(os) != DMU_OST_ZFS) {
615 error = SET_ERROR(ENOTSUP);
617 dsl_prop_get_int_ds(dmu_objset_ds(os),
618 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
620 !BOOTFS_COMPRESS_VALID(propval)) {
621 error = SET_ERROR(ENOTSUP);
623 objnum = dmu_objset_id(os);
625 dmu_objset_rele(os, FTAG);
629 case ZPOOL_PROP_FAILUREMODE:
630 error = nvpair_value_uint64(elem, &intval);
631 if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
632 intval > ZIO_FAILURE_MODE_PANIC))
633 error = SET_ERROR(EINVAL);
636 * This is a special case which only occurs when
637 * the pool has completely failed. This allows
638 * the user to change the in-core failmode property
639 * without syncing it out to disk (I/Os might
640 * currently be blocked). We do this by returning
641 * EIO to the caller (spa_prop_set) to trick it
642 * into thinking we encountered a property validation
645 if (!error && spa_suspended(spa)) {
646 spa->spa_failmode = intval;
647 error = SET_ERROR(EIO);
651 case ZPOOL_PROP_CACHEFILE:
652 if ((error = nvpair_value_string(elem, &strval)) != 0)
655 if (strval[0] == '\0')
658 if (strcmp(strval, "none") == 0)
661 if (strval[0] != '/') {
662 error = SET_ERROR(EINVAL);
666 slash = strrchr(strval, '/');
667 ASSERT(slash != NULL);
669 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
670 strcmp(slash, "/..") == 0)
671 error = SET_ERROR(EINVAL);
674 case ZPOOL_PROP_COMMENT:
675 if ((error = nvpair_value_string(elem, &strval)) != 0)
677 for (check = strval; *check != '\0'; check++) {
679 * The kernel doesn't have an easy isprint()
680 * check. For this kernel check, we merely
681 * check ASCII apart from DEL. Fix this if
682 * there is an easy-to-use kernel isprint().
684 if (*check >= 0x7f) {
685 error = SET_ERROR(EINVAL);
689 if (strlen(strval) > ZPROP_MAX_COMMENT)
693 case ZPOOL_PROP_DEDUPDITTO:
694 if (spa_version(spa) < SPA_VERSION_DEDUP)
695 error = SET_ERROR(ENOTSUP);
697 error = nvpair_value_uint64(elem, &intval);
699 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
700 error = SET_ERROR(EINVAL);
708 if (!error && reset_bootfs) {
709 error = nvlist_remove(props,
710 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
713 error = nvlist_add_uint64(props,
714 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
722 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
725 spa_config_dirent_t *dp;
727 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
731 dp = kmem_alloc(sizeof (spa_config_dirent_t),
734 if (cachefile[0] == '\0')
735 dp->scd_path = spa_strdup(spa_config_path);
736 else if (strcmp(cachefile, "none") == 0)
739 dp->scd_path = spa_strdup(cachefile);
741 list_insert_head(&spa->spa_config_list, dp);
743 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
747 spa_prop_set(spa_t *spa, nvlist_t *nvp)
750 nvpair_t *elem = NULL;
751 boolean_t need_sync = B_FALSE;
753 if ((error = spa_prop_validate(spa, nvp)) != 0)
756 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
757 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
759 if (prop == ZPOOL_PROP_CACHEFILE ||
760 prop == ZPOOL_PROP_ALTROOT ||
761 prop == ZPOOL_PROP_READONLY)
764 if (prop == ZPOOL_PROP_VERSION || prop == ZPOOL_PROP_INVAL) {
767 if (prop == ZPOOL_PROP_VERSION) {
768 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
770 ASSERT(zpool_prop_feature(nvpair_name(elem)));
771 ver = SPA_VERSION_FEATURES;
775 /* Save time if the version is already set. */
776 if (ver == spa_version(spa))
780 * In addition to the pool directory object, we might
781 * create the pool properties object, the features for
782 * read object, the features for write object, or the
783 * feature descriptions object.
785 error = dsl_sync_task(spa->spa_name, NULL,
786 spa_sync_version, &ver,
787 6, ZFS_SPACE_CHECK_RESERVED);
798 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
799 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
806 * If the bootfs property value is dsobj, clear it.
809 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
811 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
812 VERIFY(zap_remove(spa->spa_meta_objset,
813 spa->spa_pool_props_object,
814 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
821 spa_change_guid_check(void *arg, dmu_tx_t *tx)
823 uint64_t *newguid = arg;
824 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
825 vdev_t *rvd = spa->spa_root_vdev;
828 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
829 int error = (spa_has_checkpoint(spa)) ?
830 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
831 return (SET_ERROR(error));
834 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
835 vdev_state = rvd->vdev_state;
836 spa_config_exit(spa, SCL_STATE, FTAG);
838 if (vdev_state != VDEV_STATE_HEALTHY)
839 return (SET_ERROR(ENXIO));
841 ASSERT3U(spa_guid(spa), !=, *newguid);
847 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
849 uint64_t *newguid = arg;
850 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
852 vdev_t *rvd = spa->spa_root_vdev;
854 oldguid = spa_guid(spa);
856 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
857 rvd->vdev_guid = *newguid;
858 rvd->vdev_guid_sum += (*newguid - oldguid);
859 vdev_config_dirty(rvd);
860 spa_config_exit(spa, SCL_STATE, FTAG);
862 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
867 * Change the GUID for the pool. This is done so that we can later
868 * re-import a pool built from a clone of our own vdevs. We will modify
869 * the root vdev's guid, our own pool guid, and then mark all of our
870 * vdevs dirty. Note that we must make sure that all our vdevs are
871 * online when we do this, or else any vdevs that weren't present
872 * would be orphaned from our pool. We are also going to issue a
873 * sysevent to update any watchers.
876 spa_change_guid(spa_t *spa)
881 mutex_enter(&spa->spa_vdev_top_lock);
882 mutex_enter(&spa_namespace_lock);
883 guid = spa_generate_guid(NULL);
885 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
886 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
889 spa_write_cachefile(spa, B_FALSE, B_TRUE);
890 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
893 mutex_exit(&spa_namespace_lock);
894 mutex_exit(&spa->spa_vdev_top_lock);
900 * ==========================================================================
901 * SPA state manipulation (open/create/destroy/import/export)
902 * ==========================================================================
906 spa_error_entry_compare(const void *a, const void *b)
908 spa_error_entry_t *sa = (spa_error_entry_t *)a;
909 spa_error_entry_t *sb = (spa_error_entry_t *)b;
912 ret = bcmp(&sa->se_bookmark, &sb->se_bookmark,
913 sizeof (zbookmark_phys_t));
924 * Utility function which retrieves copies of the current logs and
925 * re-initializes them in the process.
928 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
930 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
932 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
933 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
935 avl_create(&spa->spa_errlist_scrub,
936 spa_error_entry_compare, sizeof (spa_error_entry_t),
937 offsetof(spa_error_entry_t, se_avl));
938 avl_create(&spa->spa_errlist_last,
939 spa_error_entry_compare, sizeof (spa_error_entry_t),
940 offsetof(spa_error_entry_t, se_avl));
944 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
946 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
947 enum zti_modes mode = ztip->zti_mode;
948 uint_t value = ztip->zti_value;
949 uint_t count = ztip->zti_count;
950 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
953 boolean_t batch = B_FALSE;
955 if (mode == ZTI_MODE_NULL) {
957 tqs->stqs_taskq = NULL;
961 ASSERT3U(count, >, 0);
963 tqs->stqs_count = count;
964 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
968 ASSERT3U(value, >=, 1);
969 value = MAX(value, 1);
974 flags |= TASKQ_THREADS_CPU_PCT;
975 value = zio_taskq_batch_pct;
979 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
981 zio_type_name[t], zio_taskq_types[q], mode, value);
985 for (uint_t i = 0; i < count; i++) {
989 (void) snprintf(name, sizeof (name), "%s_%s_%u",
990 zio_type_name[t], zio_taskq_types[q], i);
992 (void) snprintf(name, sizeof (name), "%s_%s",
993 zio_type_name[t], zio_taskq_types[q]);
997 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
999 flags |= TASKQ_DC_BATCH;
1001 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
1002 spa->spa_proc, zio_taskq_basedc, flags);
1005 pri_t pri = maxclsyspri;
1007 * The write issue taskq can be extremely CPU
1008 * intensive. Run it at slightly lower priority
1009 * than the other taskqs.
1011 * - numerically higher priorities are lower priorities;
1012 * - if priorities divided by four (RQ_PPQ) are equal
1013 * then a difference between them is insignificant.
1015 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1022 tq = taskq_create_proc(name, value, pri, 50,
1023 INT_MAX, spa->spa_proc, flags);
1028 tqs->stqs_taskq[i] = tq;
1033 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1035 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1037 if (tqs->stqs_taskq == NULL) {
1038 ASSERT0(tqs->stqs_count);
1042 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1043 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1044 taskq_destroy(tqs->stqs_taskq[i]);
1047 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1048 tqs->stqs_taskq = NULL;
1052 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1053 * Note that a type may have multiple discrete taskqs to avoid lock contention
1054 * on the taskq itself. In that case we choose which taskq at random by using
1055 * the low bits of gethrtime().
1058 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1059 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1061 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1064 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1065 ASSERT3U(tqs->stqs_count, !=, 0);
1067 if (tqs->stqs_count == 1) {
1068 tq = tqs->stqs_taskq[0];
1071 tq = tqs->stqs_taskq[cpu_ticks() % tqs->stqs_count];
1073 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1077 taskq_dispatch_ent(tq, func, arg, flags, ent);
1081 spa_create_zio_taskqs(spa_t *spa)
1083 for (int t = 0; t < ZIO_TYPES; t++) {
1084 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1085 spa_taskqs_init(spa, t, q);
1093 spa_thread(void *arg)
1095 callb_cpr_t cprinfo;
1098 user_t *pu = PTOU(curproc);
1100 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1103 ASSERT(curproc != &p0);
1104 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1105 "zpool-%s", spa->spa_name);
1106 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1109 /* bind this thread to the requested psrset */
1110 if (zio_taskq_psrset_bind != PS_NONE) {
1112 mutex_enter(&cpu_lock);
1113 mutex_enter(&pidlock);
1114 mutex_enter(&curproc->p_lock);
1116 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1117 0, NULL, NULL) == 0) {
1118 curthread->t_bind_pset = zio_taskq_psrset_bind;
1121 "Couldn't bind process for zfs pool \"%s\" to "
1122 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1125 mutex_exit(&curproc->p_lock);
1126 mutex_exit(&pidlock);
1127 mutex_exit(&cpu_lock);
1133 if (zio_taskq_sysdc) {
1134 sysdc_thread_enter(curthread, 100, 0);
1138 spa->spa_proc = curproc;
1139 spa->spa_did = curthread->t_did;
1141 spa_create_zio_taskqs(spa);
1143 mutex_enter(&spa->spa_proc_lock);
1144 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1146 spa->spa_proc_state = SPA_PROC_ACTIVE;
1147 cv_broadcast(&spa->spa_proc_cv);
1149 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1150 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1151 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1152 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1154 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1155 spa->spa_proc_state = SPA_PROC_GONE;
1156 spa->spa_proc = &p0;
1157 cv_broadcast(&spa->spa_proc_cv);
1158 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1160 mutex_enter(&curproc->p_lock);
1163 #endif /* SPA_PROCESS */
1167 * Activate an uninitialized pool.
1170 spa_activate(spa_t *spa, int mode)
1172 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1174 spa->spa_state = POOL_STATE_ACTIVE;
1175 spa->spa_mode = mode;
1177 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1178 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1180 /* Try to create a covering process */
1181 mutex_enter(&spa->spa_proc_lock);
1182 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1183 ASSERT(spa->spa_proc == &p0);
1187 /* Only create a process if we're going to be around a while. */
1188 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1189 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1191 spa->spa_proc_state = SPA_PROC_CREATED;
1192 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1193 cv_wait(&spa->spa_proc_cv,
1194 &spa->spa_proc_lock);
1196 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1197 ASSERT(spa->spa_proc != &p0);
1198 ASSERT(spa->spa_did != 0);
1202 "Couldn't create process for zfs pool \"%s\"\n",
1207 #endif /* SPA_PROCESS */
1208 mutex_exit(&spa->spa_proc_lock);
1210 /* If we didn't create a process, we need to create our taskqs. */
1211 ASSERT(spa->spa_proc == &p0);
1212 if (spa->spa_proc == &p0) {
1213 spa_create_zio_taskqs(spa);
1217 * Start TRIM thread.
1219 trim_thread_create(spa);
1221 for (size_t i = 0; i < TXG_SIZE; i++) {
1222 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL,
1226 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1227 offsetof(vdev_t, vdev_config_dirty_node));
1228 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1229 offsetof(objset_t, os_evicting_node));
1230 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1231 offsetof(vdev_t, vdev_state_dirty_node));
1233 txg_list_create(&spa->spa_vdev_txg_list, spa,
1234 offsetof(struct vdev, vdev_txg_node));
1236 avl_create(&spa->spa_errlist_scrub,
1237 spa_error_entry_compare, sizeof (spa_error_entry_t),
1238 offsetof(spa_error_entry_t, se_avl));
1239 avl_create(&spa->spa_errlist_last,
1240 spa_error_entry_compare, sizeof (spa_error_entry_t),
1241 offsetof(spa_error_entry_t, se_avl));
1245 * Opposite of spa_activate().
1248 spa_deactivate(spa_t *spa)
1250 ASSERT(spa->spa_sync_on == B_FALSE);
1251 ASSERT(spa->spa_dsl_pool == NULL);
1252 ASSERT(spa->spa_root_vdev == NULL);
1253 ASSERT(spa->spa_async_zio_root == NULL);
1254 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1257 * Stop TRIM thread in case spa_unload() wasn't called directly
1258 * before spa_deactivate().
1260 trim_thread_destroy(spa);
1262 spa_evicting_os_wait(spa);
1264 txg_list_destroy(&spa->spa_vdev_txg_list);
1266 list_destroy(&spa->spa_config_dirty_list);
1267 list_destroy(&spa->spa_evicting_os_list);
1268 list_destroy(&spa->spa_state_dirty_list);
1270 for (int t = 0; t < ZIO_TYPES; t++) {
1271 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1272 spa_taskqs_fini(spa, t, q);
1276 for (size_t i = 0; i < TXG_SIZE; i++) {
1277 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1278 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1279 spa->spa_txg_zio[i] = NULL;
1282 metaslab_class_destroy(spa->spa_normal_class);
1283 spa->spa_normal_class = NULL;
1285 metaslab_class_destroy(spa->spa_log_class);
1286 spa->spa_log_class = NULL;
1289 * If this was part of an import or the open otherwise failed, we may
1290 * still have errors left in the queues. Empty them just in case.
1292 spa_errlog_drain(spa);
1294 avl_destroy(&spa->spa_errlist_scrub);
1295 avl_destroy(&spa->spa_errlist_last);
1297 spa->spa_state = POOL_STATE_UNINITIALIZED;
1299 mutex_enter(&spa->spa_proc_lock);
1300 if (spa->spa_proc_state != SPA_PROC_NONE) {
1301 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1302 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1303 cv_broadcast(&spa->spa_proc_cv);
1304 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1305 ASSERT(spa->spa_proc != &p0);
1306 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1308 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1309 spa->spa_proc_state = SPA_PROC_NONE;
1311 ASSERT(spa->spa_proc == &p0);
1312 mutex_exit(&spa->spa_proc_lock);
1316 * We want to make sure spa_thread() has actually exited the ZFS
1317 * module, so that the module can't be unloaded out from underneath
1320 if (spa->spa_did != 0) {
1321 thread_join(spa->spa_did);
1324 #endif /* SPA_PROCESS */
1328 * Verify a pool configuration, and construct the vdev tree appropriately. This
1329 * will create all the necessary vdevs in the appropriate layout, with each vdev
1330 * in the CLOSED state. This will prep the pool before open/creation/import.
1331 * All vdev validation is done by the vdev_alloc() routine.
1334 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1335 uint_t id, int atype)
1341 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1344 if ((*vdp)->vdev_ops->vdev_op_leaf)
1347 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1350 if (error == ENOENT)
1356 return (SET_ERROR(EINVAL));
1359 for (int c = 0; c < children; c++) {
1361 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1369 ASSERT(*vdp != NULL);
1375 * Opposite of spa_load().
1378 spa_unload(spa_t *spa)
1382 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1384 spa_load_note(spa, "UNLOADING");
1389 trim_thread_destroy(spa);
1394 spa_async_suspend(spa);
1396 if (spa->spa_root_vdev) {
1397 vdev_initialize_stop_all(spa->spa_root_vdev,
1398 VDEV_INITIALIZE_ACTIVE);
1404 if (spa->spa_sync_on) {
1405 txg_sync_stop(spa->spa_dsl_pool);
1406 spa->spa_sync_on = B_FALSE;
1410 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1411 * to call it earlier, before we wait for async i/o to complete.
1412 * This ensures that there is no async metaslab prefetching, by
1413 * calling taskq_wait(mg_taskq).
1415 if (spa->spa_root_vdev != NULL) {
1416 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1417 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1418 vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1419 spa_config_exit(spa, SCL_ALL, spa);
1423 * Wait for any outstanding async I/O to complete.
1425 if (spa->spa_async_zio_root != NULL) {
1426 for (int i = 0; i < max_ncpus; i++)
1427 (void) zio_wait(spa->spa_async_zio_root[i]);
1428 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1429 spa->spa_async_zio_root = NULL;
1432 if (spa->spa_vdev_removal != NULL) {
1433 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1434 spa->spa_vdev_removal = NULL;
1437 if (spa->spa_condense_zthr != NULL) {
1438 ASSERT(!zthr_isrunning(spa->spa_condense_zthr));
1439 zthr_destroy(spa->spa_condense_zthr);
1440 spa->spa_condense_zthr = NULL;
1443 if (spa->spa_checkpoint_discard_zthr != NULL) {
1444 ASSERT(!zthr_isrunning(spa->spa_checkpoint_discard_zthr));
1445 zthr_destroy(spa->spa_checkpoint_discard_zthr);
1446 spa->spa_checkpoint_discard_zthr = NULL;
1449 spa_condense_fini(spa);
1451 bpobj_close(&spa->spa_deferred_bpobj);
1453 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1458 if (spa->spa_root_vdev)
1459 vdev_free(spa->spa_root_vdev);
1460 ASSERT(spa->spa_root_vdev == NULL);
1463 * Close the dsl pool.
1465 if (spa->spa_dsl_pool) {
1466 dsl_pool_close(spa->spa_dsl_pool);
1467 spa->spa_dsl_pool = NULL;
1468 spa->spa_meta_objset = NULL;
1474 * Drop and purge level 2 cache
1476 spa_l2cache_drop(spa);
1478 for (i = 0; i < spa->spa_spares.sav_count; i++)
1479 vdev_free(spa->spa_spares.sav_vdevs[i]);
1480 if (spa->spa_spares.sav_vdevs) {
1481 kmem_free(spa->spa_spares.sav_vdevs,
1482 spa->spa_spares.sav_count * sizeof (void *));
1483 spa->spa_spares.sav_vdevs = NULL;
1485 if (spa->spa_spares.sav_config) {
1486 nvlist_free(spa->spa_spares.sav_config);
1487 spa->spa_spares.sav_config = NULL;
1489 spa->spa_spares.sav_count = 0;
1491 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1492 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1493 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1495 if (spa->spa_l2cache.sav_vdevs) {
1496 kmem_free(spa->spa_l2cache.sav_vdevs,
1497 spa->spa_l2cache.sav_count * sizeof (void *));
1498 spa->spa_l2cache.sav_vdevs = NULL;
1500 if (spa->spa_l2cache.sav_config) {
1501 nvlist_free(spa->spa_l2cache.sav_config);
1502 spa->spa_l2cache.sav_config = NULL;
1504 spa->spa_l2cache.sav_count = 0;
1506 spa->spa_async_suspended = 0;
1508 spa->spa_indirect_vdevs_loaded = B_FALSE;
1510 if (spa->spa_comment != NULL) {
1511 spa_strfree(spa->spa_comment);
1512 spa->spa_comment = NULL;
1515 spa_config_exit(spa, SCL_ALL, spa);
1519 * Load (or re-load) the current list of vdevs describing the active spares for
1520 * this pool. When this is called, we have some form of basic information in
1521 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1522 * then re-generate a more complete list including status information.
1525 spa_load_spares(spa_t *spa)
1534 * zdb opens both the current state of the pool and the
1535 * checkpointed state (if present), with a different spa_t.
1537 * As spare vdevs are shared among open pools, we skip loading
1538 * them when we load the checkpointed state of the pool.
1540 if (!spa_writeable(spa))
1544 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1547 * First, close and free any existing spare vdevs.
1549 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1550 vd = spa->spa_spares.sav_vdevs[i];
1552 /* Undo the call to spa_activate() below */
1553 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1554 B_FALSE)) != NULL && tvd->vdev_isspare)
1555 spa_spare_remove(tvd);
1560 if (spa->spa_spares.sav_vdevs)
1561 kmem_free(spa->spa_spares.sav_vdevs,
1562 spa->spa_spares.sav_count * sizeof (void *));
1564 if (spa->spa_spares.sav_config == NULL)
1567 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1568 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1570 spa->spa_spares.sav_count = (int)nspares;
1571 spa->spa_spares.sav_vdevs = NULL;
1577 * Construct the array of vdevs, opening them to get status in the
1578 * process. For each spare, there is potentially two different vdev_t
1579 * structures associated with it: one in the list of spares (used only
1580 * for basic validation purposes) and one in the active vdev
1581 * configuration (if it's spared in). During this phase we open and
1582 * validate each vdev on the spare list. If the vdev also exists in the
1583 * active configuration, then we also mark this vdev as an active spare.
1585 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1587 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1588 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1589 VDEV_ALLOC_SPARE) == 0);
1592 spa->spa_spares.sav_vdevs[i] = vd;
1594 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1595 B_FALSE)) != NULL) {
1596 if (!tvd->vdev_isspare)
1600 * We only mark the spare active if we were successfully
1601 * able to load the vdev. Otherwise, importing a pool
1602 * with a bad active spare would result in strange
1603 * behavior, because multiple pool would think the spare
1604 * is actively in use.
1606 * There is a vulnerability here to an equally bizarre
1607 * circumstance, where a dead active spare is later
1608 * brought back to life (onlined or otherwise). Given
1609 * the rarity of this scenario, and the extra complexity
1610 * it adds, we ignore the possibility.
1612 if (!vdev_is_dead(tvd))
1613 spa_spare_activate(tvd);
1617 vd->vdev_aux = &spa->spa_spares;
1619 if (vdev_open(vd) != 0)
1622 if (vdev_validate_aux(vd) == 0)
1627 * Recompute the stashed list of spares, with status information
1630 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1631 DATA_TYPE_NVLIST_ARRAY) == 0);
1633 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1635 for (i = 0; i < spa->spa_spares.sav_count; i++)
1636 spares[i] = vdev_config_generate(spa,
1637 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1638 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1639 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1640 for (i = 0; i < spa->spa_spares.sav_count; i++)
1641 nvlist_free(spares[i]);
1642 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1646 * Load (or re-load) the current list of vdevs describing the active l2cache for
1647 * this pool. When this is called, we have some form of basic information in
1648 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1649 * then re-generate a more complete list including status information.
1650 * Devices which are already active have their details maintained, and are
1654 spa_load_l2cache(spa_t *spa)
1658 int i, j, oldnvdevs;
1660 vdev_t *vd, **oldvdevs, **newvdevs;
1661 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1665 * zdb opens both the current state of the pool and the
1666 * checkpointed state (if present), with a different spa_t.
1668 * As L2 caches are part of the ARC which is shared among open
1669 * pools, we skip loading them when we load the checkpointed
1670 * state of the pool.
1672 if (!spa_writeable(spa))
1676 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1678 if (sav->sav_config != NULL) {
1679 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1680 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1681 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1687 oldvdevs = sav->sav_vdevs;
1688 oldnvdevs = sav->sav_count;
1689 sav->sav_vdevs = NULL;
1693 * Process new nvlist of vdevs.
1695 for (i = 0; i < nl2cache; i++) {
1696 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1700 for (j = 0; j < oldnvdevs; j++) {
1702 if (vd != NULL && guid == vd->vdev_guid) {
1704 * Retain previous vdev for add/remove ops.
1712 if (newvdevs[i] == NULL) {
1716 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1717 VDEV_ALLOC_L2CACHE) == 0);
1722 * Commit this vdev as an l2cache device,
1723 * even if it fails to open.
1725 spa_l2cache_add(vd);
1730 spa_l2cache_activate(vd);
1732 if (vdev_open(vd) != 0)
1735 (void) vdev_validate_aux(vd);
1737 if (!vdev_is_dead(vd))
1738 l2arc_add_vdev(spa, vd);
1743 * Purge vdevs that were dropped
1745 for (i = 0; i < oldnvdevs; i++) {
1750 ASSERT(vd->vdev_isl2cache);
1752 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1753 pool != 0ULL && l2arc_vdev_present(vd))
1754 l2arc_remove_vdev(vd);
1755 vdev_clear_stats(vd);
1761 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1763 if (sav->sav_config == NULL)
1766 sav->sav_vdevs = newvdevs;
1767 sav->sav_count = (int)nl2cache;
1770 * Recompute the stashed list of l2cache devices, with status
1771 * information this time.
1773 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1774 DATA_TYPE_NVLIST_ARRAY) == 0);
1776 l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1777 for (i = 0; i < sav->sav_count; i++)
1778 l2cache[i] = vdev_config_generate(spa,
1779 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1780 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1781 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1783 for (i = 0; i < sav->sav_count; i++)
1784 nvlist_free(l2cache[i]);
1786 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1790 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1793 char *packed = NULL;
1798 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1802 nvsize = *(uint64_t *)db->db_data;
1803 dmu_buf_rele(db, FTAG);
1805 packed = kmem_alloc(nvsize, KM_SLEEP);
1806 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1809 error = nvlist_unpack(packed, nvsize, value, 0);
1810 kmem_free(packed, nvsize);
1816 * Concrete top-level vdevs that are not missing and are not logs. At every
1817 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1820 spa_healthy_core_tvds(spa_t *spa)
1822 vdev_t *rvd = spa->spa_root_vdev;
1825 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1826 vdev_t *vd = rvd->vdev_child[i];
1829 if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1837 * Checks to see if the given vdev could not be opened, in which case we post a
1838 * sysevent to notify the autoreplace code that the device has been removed.
1841 spa_check_removed(vdev_t *vd)
1843 for (uint64_t c = 0; c < vd->vdev_children; c++)
1844 spa_check_removed(vd->vdev_child[c]);
1846 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1847 vdev_is_concrete(vd)) {
1848 zfs_post_autoreplace(vd->vdev_spa, vd);
1849 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1854 spa_check_for_missing_logs(spa_t *spa)
1856 vdev_t *rvd = spa->spa_root_vdev;
1859 * If we're doing a normal import, then build up any additional
1860 * diagnostic information about missing log devices.
1861 * We'll pass this up to the user for further processing.
1863 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1864 nvlist_t **child, *nv;
1867 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1869 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1871 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1872 vdev_t *tvd = rvd->vdev_child[c];
1875 * We consider a device as missing only if it failed
1876 * to open (i.e. offline or faulted is not considered
1879 if (tvd->vdev_islog &&
1880 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1881 child[idx++] = vdev_config_generate(spa, tvd,
1882 B_FALSE, VDEV_CONFIG_MISSING);
1887 fnvlist_add_nvlist_array(nv,
1888 ZPOOL_CONFIG_CHILDREN, child, idx);
1889 fnvlist_add_nvlist(spa->spa_load_info,
1890 ZPOOL_CONFIG_MISSING_DEVICES, nv);
1892 for (uint64_t i = 0; i < idx; i++)
1893 nvlist_free(child[i]);
1896 kmem_free(child, rvd->vdev_children * sizeof (char **));
1899 spa_load_failed(spa, "some log devices are missing");
1900 vdev_dbgmsg_print_tree(rvd, 2);
1901 return (SET_ERROR(ENXIO));
1904 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1905 vdev_t *tvd = rvd->vdev_child[c];
1907 if (tvd->vdev_islog &&
1908 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1909 spa_set_log_state(spa, SPA_LOG_CLEAR);
1910 spa_load_note(spa, "some log devices are "
1911 "missing, ZIL is dropped.");
1912 vdev_dbgmsg_print_tree(rvd, 2);
1922 * Check for missing log devices
1925 spa_check_logs(spa_t *spa)
1927 boolean_t rv = B_FALSE;
1928 dsl_pool_t *dp = spa_get_dsl(spa);
1930 switch (spa->spa_log_state) {
1931 case SPA_LOG_MISSING:
1932 /* need to recheck in case slog has been restored */
1933 case SPA_LOG_UNKNOWN:
1934 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1935 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
1937 spa_set_log_state(spa, SPA_LOG_MISSING);
1944 spa_passivate_log(spa_t *spa)
1946 vdev_t *rvd = spa->spa_root_vdev;
1947 boolean_t slog_found = B_FALSE;
1949 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1951 if (!spa_has_slogs(spa))
1954 for (int c = 0; c < rvd->vdev_children; c++) {
1955 vdev_t *tvd = rvd->vdev_child[c];
1956 metaslab_group_t *mg = tvd->vdev_mg;
1958 if (tvd->vdev_islog) {
1959 metaslab_group_passivate(mg);
1960 slog_found = B_TRUE;
1964 return (slog_found);
1968 spa_activate_log(spa_t *spa)
1970 vdev_t *rvd = spa->spa_root_vdev;
1972 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1974 for (int c = 0; c < rvd->vdev_children; c++) {
1975 vdev_t *tvd = rvd->vdev_child[c];
1976 metaslab_group_t *mg = tvd->vdev_mg;
1978 if (tvd->vdev_islog)
1979 metaslab_group_activate(mg);
1984 spa_reset_logs(spa_t *spa)
1988 error = dmu_objset_find(spa_name(spa), zil_reset,
1989 NULL, DS_FIND_CHILDREN);
1992 * We successfully offlined the log device, sync out the
1993 * current txg so that the "stubby" block can be removed
1996 txg_wait_synced(spa->spa_dsl_pool, 0);
2002 spa_aux_check_removed(spa_aux_vdev_t *sav)
2006 for (i = 0; i < sav->sav_count; i++)
2007 spa_check_removed(sav->sav_vdevs[i]);
2011 spa_claim_notify(zio_t *zio)
2013 spa_t *spa = zio->io_spa;
2018 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2019 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2020 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2021 mutex_exit(&spa->spa_props_lock);
2024 typedef struct spa_load_error {
2025 uint64_t sle_meta_count;
2026 uint64_t sle_data_count;
2030 spa_load_verify_done(zio_t *zio)
2032 blkptr_t *bp = zio->io_bp;
2033 spa_load_error_t *sle = zio->io_private;
2034 dmu_object_type_t type = BP_GET_TYPE(bp);
2035 int error = zio->io_error;
2036 spa_t *spa = zio->io_spa;
2038 abd_free(zio->io_abd);
2040 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
2041 type != DMU_OT_INTENT_LOG)
2042 atomic_inc_64(&sle->sle_meta_count);
2044 atomic_inc_64(&sle->sle_data_count);
2047 mutex_enter(&spa->spa_scrub_lock);
2048 spa->spa_load_verify_ios--;
2049 cv_broadcast(&spa->spa_scrub_io_cv);
2050 mutex_exit(&spa->spa_scrub_lock);
2054 * Maximum number of concurrent scrub i/os to create while verifying
2055 * a pool while importing it.
2057 int spa_load_verify_maxinflight = 10000;
2058 boolean_t spa_load_verify_metadata = B_TRUE;
2059 boolean_t spa_load_verify_data = B_TRUE;
2061 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_maxinflight, CTLFLAG_RWTUN,
2062 &spa_load_verify_maxinflight, 0,
2063 "Maximum number of concurrent scrub I/Os to create while verifying a "
2064 "pool while importing it");
2066 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_metadata, CTLFLAG_RWTUN,
2067 &spa_load_verify_metadata, 0,
2068 "Check metadata on import?");
2070 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_data, CTLFLAG_RWTUN,
2071 &spa_load_verify_data, 0,
2072 "Check user data on import?");
2076 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2077 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2079 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2082 * Note: normally this routine will not be called if
2083 * spa_load_verify_metadata is not set. However, it may be useful
2084 * to manually set the flag after the traversal has begun.
2086 if (!spa_load_verify_metadata)
2088 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2092 size_t size = BP_GET_PSIZE(bp);
2094 mutex_enter(&spa->spa_scrub_lock);
2095 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
2096 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2097 spa->spa_load_verify_ios++;
2098 mutex_exit(&spa->spa_scrub_lock);
2100 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2101 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2102 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2103 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2109 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2111 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2112 return (SET_ERROR(ENAMETOOLONG));
2118 spa_load_verify(spa_t *spa)
2121 spa_load_error_t sle = { 0 };
2122 zpool_load_policy_t policy;
2123 boolean_t verify_ok = B_FALSE;
2126 zpool_get_load_policy(spa->spa_config, &policy);
2128 if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2131 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2132 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2133 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2135 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2139 rio = zio_root(spa, NULL, &sle,
2140 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2142 if (spa_load_verify_metadata) {
2143 if (spa->spa_extreme_rewind) {
2144 spa_load_note(spa, "performing a complete scan of the "
2145 "pool since extreme rewind is on. This may take "
2146 "a very long time.\n (spa_load_verify_data=%u, "
2147 "spa_load_verify_metadata=%u)",
2148 spa_load_verify_data, spa_load_verify_metadata);
2150 error = traverse_pool(spa, spa->spa_verify_min_txg,
2151 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2152 spa_load_verify_cb, rio);
2155 (void) zio_wait(rio);
2157 spa->spa_load_meta_errors = sle.sle_meta_count;
2158 spa->spa_load_data_errors = sle.sle_data_count;
2160 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2161 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2162 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2163 (u_longlong_t)sle.sle_data_count);
2166 if (spa_load_verify_dryrun ||
2167 (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2168 sle.sle_data_count <= policy.zlp_maxdata)) {
2172 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2173 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2175 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2176 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2177 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2178 VERIFY(nvlist_add_int64(spa->spa_load_info,
2179 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2180 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2181 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2183 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2186 if (spa_load_verify_dryrun)
2190 if (error != ENXIO && error != EIO)
2191 error = SET_ERROR(EIO);
2195 return (verify_ok ? 0 : EIO);
2199 * Find a value in the pool props object.
2202 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2204 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2205 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2209 * Find a value in the pool directory object.
2212 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2214 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2215 name, sizeof (uint64_t), 1, val);
2217 if (error != 0 && (error != ENOENT || log_enoent)) {
2218 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2219 "[error=%d]", name, error);
2226 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2228 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2229 return (SET_ERROR(err));
2233 spa_spawn_aux_threads(spa_t *spa)
2235 ASSERT(spa_writeable(spa));
2237 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2239 spa_start_indirect_condensing_thread(spa);
2241 ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2242 spa->spa_checkpoint_discard_zthr =
2243 zthr_create(spa_checkpoint_discard_thread_check,
2244 spa_checkpoint_discard_thread, spa);
2248 * Fix up config after a partly-completed split. This is done with the
2249 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2250 * pool have that entry in their config, but only the splitting one contains
2251 * a list of all the guids of the vdevs that are being split off.
2253 * This function determines what to do with that list: either rejoin
2254 * all the disks to the pool, or complete the splitting process. To attempt
2255 * the rejoin, each disk that is offlined is marked online again, and
2256 * we do a reopen() call. If the vdev label for every disk that was
2257 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2258 * then we call vdev_split() on each disk, and complete the split.
2260 * Otherwise we leave the config alone, with all the vdevs in place in
2261 * the original pool.
2264 spa_try_repair(spa_t *spa, nvlist_t *config)
2271 boolean_t attempt_reopen;
2273 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2276 /* check that the config is complete */
2277 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2278 &glist, &gcount) != 0)
2281 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2283 /* attempt to online all the vdevs & validate */
2284 attempt_reopen = B_TRUE;
2285 for (i = 0; i < gcount; i++) {
2286 if (glist[i] == 0) /* vdev is hole */
2289 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2290 if (vd[i] == NULL) {
2292 * Don't bother attempting to reopen the disks;
2293 * just do the split.
2295 attempt_reopen = B_FALSE;
2297 /* attempt to re-online it */
2298 vd[i]->vdev_offline = B_FALSE;
2302 if (attempt_reopen) {
2303 vdev_reopen(spa->spa_root_vdev);
2305 /* check each device to see what state it's in */
2306 for (extracted = 0, i = 0; i < gcount; i++) {
2307 if (vd[i] != NULL &&
2308 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2315 * If every disk has been moved to the new pool, or if we never
2316 * even attempted to look at them, then we split them off for
2319 if (!attempt_reopen || gcount == extracted) {
2320 for (i = 0; i < gcount; i++)
2323 vdev_reopen(spa->spa_root_vdev);
2326 kmem_free(vd, gcount * sizeof (vdev_t *));
2330 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2332 char *ereport = FM_EREPORT_ZFS_POOL;
2335 spa->spa_load_state = state;
2337 gethrestime(&spa->spa_loaded_ts);
2338 error = spa_load_impl(spa, type, &ereport);
2341 * Don't count references from objsets that are already closed
2342 * and are making their way through the eviction process.
2344 spa_evicting_os_wait(spa);
2345 spa->spa_minref = refcount_count(&spa->spa_refcount);
2347 if (error != EEXIST) {
2348 spa->spa_loaded_ts.tv_sec = 0;
2349 spa->spa_loaded_ts.tv_nsec = 0;
2351 if (error != EBADF) {
2352 zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2355 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2362 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2363 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2364 * spa's per-vdev ZAP list.
2367 vdev_count_verify_zaps(vdev_t *vd)
2369 spa_t *spa = vd->vdev_spa;
2371 if (vd->vdev_top_zap != 0) {
2373 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2374 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2376 if (vd->vdev_leaf_zap != 0) {
2378 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2379 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2382 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2383 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2390 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2394 uint64_t myhostid = 0;
2396 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2397 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2398 hostname = fnvlist_lookup_string(mos_config,
2399 ZPOOL_CONFIG_HOSTNAME);
2401 myhostid = zone_get_hostid(NULL);
2403 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2404 cmn_err(CE_WARN, "pool '%s' could not be "
2405 "loaded as it was last accessed by "
2406 "another system (host: %s hostid: 0x%llx). "
2407 "See: http://illumos.org/msg/ZFS-8000-EY",
2408 spa_name(spa), hostname, (u_longlong_t)hostid);
2409 spa_load_failed(spa, "hostid verification failed: pool "
2410 "last accessed by host: %s (hostid: 0x%llx)",
2411 hostname, (u_longlong_t)hostid);
2412 return (SET_ERROR(EBADF));
2420 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2423 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2430 * Versioning wasn't explicitly added to the label until later, so if
2431 * it's not present treat it as the initial version.
2433 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2434 &spa->spa_ubsync.ub_version) != 0)
2435 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2437 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2438 spa_load_failed(spa, "invalid config provided: '%s' missing",
2439 ZPOOL_CONFIG_POOL_GUID);
2440 return (SET_ERROR(EINVAL));
2444 * If we are doing an import, ensure that the pool is not already
2445 * imported by checking if its pool guid already exists in the
2448 * The only case that we allow an already imported pool to be
2449 * imported again, is when the pool is checkpointed and we want to
2450 * look at its checkpointed state from userland tools like zdb.
2453 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2454 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2455 spa_guid_exists(pool_guid, 0)) {
2457 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2458 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2459 spa_guid_exists(pool_guid, 0) &&
2460 !spa_importing_readonly_checkpoint(spa)) {
2462 spa_load_failed(spa, "a pool with guid %llu is already open",
2463 (u_longlong_t)pool_guid);
2464 return (SET_ERROR(EEXIST));
2467 spa->spa_config_guid = pool_guid;
2469 nvlist_free(spa->spa_load_info);
2470 spa->spa_load_info = fnvlist_alloc();
2472 ASSERT(spa->spa_comment == NULL);
2473 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2474 spa->spa_comment = spa_strdup(comment);
2476 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2477 &spa->spa_config_txg);
2479 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2480 spa->spa_config_splitting = fnvlist_dup(nvl);
2482 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2483 spa_load_failed(spa, "invalid config provided: '%s' missing",
2484 ZPOOL_CONFIG_VDEV_TREE);
2485 return (SET_ERROR(EINVAL));
2489 * Create "The Godfather" zio to hold all async IOs
2491 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2493 for (int i = 0; i < max_ncpus; i++) {
2494 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2495 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2496 ZIO_FLAG_GODFATHER);
2500 * Parse the configuration into a vdev tree. We explicitly set the
2501 * value that will be returned by spa_version() since parsing the
2502 * configuration requires knowing the version number.
2504 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2505 parse = (type == SPA_IMPORT_EXISTING ?
2506 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2507 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2508 spa_config_exit(spa, SCL_ALL, FTAG);
2511 spa_load_failed(spa, "unable to parse config [error=%d]",
2516 ASSERT(spa->spa_root_vdev == rvd);
2517 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2518 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2520 if (type != SPA_IMPORT_ASSEMBLE) {
2521 ASSERT(spa_guid(spa) == pool_guid);
2528 * Recursively open all vdevs in the vdev tree. This function is called twice:
2529 * first with the untrusted config, then with the trusted config.
2532 spa_ld_open_vdevs(spa_t *spa)
2537 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2538 * missing/unopenable for the root vdev to be still considered openable.
2540 if (spa->spa_trust_config) {
2541 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2542 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2543 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2544 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2545 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2547 spa->spa_missing_tvds_allowed = 0;
2550 spa->spa_missing_tvds_allowed =
2551 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2553 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2554 error = vdev_open(spa->spa_root_vdev);
2555 spa_config_exit(spa, SCL_ALL, FTAG);
2557 if (spa->spa_missing_tvds != 0) {
2558 spa_load_note(spa, "vdev tree has %lld missing top-level "
2559 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2560 if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2562 * Although theoretically we could allow users to open
2563 * incomplete pools in RW mode, we'd need to add a lot
2564 * of extra logic (e.g. adjust pool space to account
2565 * for missing vdevs).
2566 * This limitation also prevents users from accidentally
2567 * opening the pool in RW mode during data recovery and
2568 * damaging it further.
2570 spa_load_note(spa, "pools with missing top-level "
2571 "vdevs can only be opened in read-only mode.");
2572 error = SET_ERROR(ENXIO);
2574 spa_load_note(spa, "current settings allow for maximum "
2575 "%lld missing top-level vdevs at this stage.",
2576 (u_longlong_t)spa->spa_missing_tvds_allowed);
2580 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2583 if (spa->spa_missing_tvds != 0 || error != 0)
2584 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2590 * We need to validate the vdev labels against the configuration that
2591 * we have in hand. This function is called twice: first with an untrusted
2592 * config, then with a trusted config. The validation is more strict when the
2593 * config is trusted.
2596 spa_ld_validate_vdevs(spa_t *spa)
2599 vdev_t *rvd = spa->spa_root_vdev;
2601 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2602 error = vdev_validate(rvd);
2603 spa_config_exit(spa, SCL_ALL, FTAG);
2606 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2610 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2611 spa_load_failed(spa, "cannot open vdev tree after invalidating "
2613 vdev_dbgmsg_print_tree(rvd, 2);
2614 return (SET_ERROR(ENXIO));
2621 spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2623 spa->spa_state = POOL_STATE_ACTIVE;
2624 spa->spa_ubsync = spa->spa_uberblock;
2625 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2626 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2627 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2628 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2629 spa->spa_claim_max_txg = spa->spa_first_txg;
2630 spa->spa_prev_software_version = ub->ub_software_version;
2634 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2636 vdev_t *rvd = spa->spa_root_vdev;
2638 uberblock_t *ub = &spa->spa_uberblock;
2641 * If we are opening the checkpointed state of the pool by
2642 * rewinding to it, at this point we will have written the
2643 * checkpointed uberblock to the vdev labels, so searching
2644 * the labels will find the right uberblock. However, if
2645 * we are opening the checkpointed state read-only, we have
2646 * not modified the labels. Therefore, we must ignore the
2647 * labels and continue using the spa_uberblock that was set
2648 * by spa_ld_checkpoint_rewind.
2650 * Note that it would be fine to ignore the labels when
2651 * rewinding (opening writeable) as well. However, if we
2652 * crash just after writing the labels, we will end up
2653 * searching the labels. Doing so in the common case means
2654 * that this code path gets exercised normally, rather than
2655 * just in the edge case.
2657 if (ub->ub_checkpoint_txg != 0 &&
2658 spa_importing_readonly_checkpoint(spa)) {
2659 spa_ld_select_uberblock_done(spa, ub);
2664 * Find the best uberblock.
2666 vdev_uberblock_load(rvd, ub, &label);
2669 * If we weren't able to find a single valid uberblock, return failure.
2671 if (ub->ub_txg == 0) {
2673 spa_load_failed(spa, "no valid uberblock found");
2674 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2677 spa_load_note(spa, "using uberblock with txg=%llu",
2678 (u_longlong_t)ub->ub_txg);
2681 * If the pool has an unsupported version we can't open it.
2683 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2685 spa_load_failed(spa, "version %llu is not supported",
2686 (u_longlong_t)ub->ub_version);
2687 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2690 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2694 * If we weren't able to find what's necessary for reading the
2695 * MOS in the label, return failure.
2697 if (label == NULL) {
2698 spa_load_failed(spa, "label config unavailable");
2699 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2703 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
2706 spa_load_failed(spa, "invalid label: '%s' missing",
2707 ZPOOL_CONFIG_FEATURES_FOR_READ);
2708 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2713 * Update our in-core representation with the definitive values
2716 nvlist_free(spa->spa_label_features);
2717 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2723 * Look through entries in the label nvlist's features_for_read. If
2724 * there is a feature listed there which we don't understand then we
2725 * cannot open a pool.
2727 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2728 nvlist_t *unsup_feat;
2730 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2733 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2735 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2736 if (!zfeature_is_supported(nvpair_name(nvp))) {
2737 VERIFY(nvlist_add_string(unsup_feat,
2738 nvpair_name(nvp), "") == 0);
2742 if (!nvlist_empty(unsup_feat)) {
2743 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2744 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2745 nvlist_free(unsup_feat);
2746 spa_load_failed(spa, "some features are unsupported");
2747 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2751 nvlist_free(unsup_feat);
2754 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2755 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2756 spa_try_repair(spa, spa->spa_config);
2757 spa_config_exit(spa, SCL_ALL, FTAG);
2758 nvlist_free(spa->spa_config_splitting);
2759 spa->spa_config_splitting = NULL;
2763 * Initialize internal SPA structures.
2765 spa_ld_select_uberblock_done(spa, ub);
2771 spa_ld_open_rootbp(spa_t *spa)
2774 vdev_t *rvd = spa->spa_root_vdev;
2776 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2778 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
2779 "[error=%d]", error);
2780 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2782 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2788 spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
2789 boolean_t reloading)
2791 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
2792 nvlist_t *nv, *mos_config, *policy;
2793 int error = 0, copy_error;
2794 uint64_t healthy_tvds, healthy_tvds_mos;
2795 uint64_t mos_config_txg;
2797 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
2799 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2802 * If we're assembling a pool from a split, the config provided is
2803 * already trusted so there is nothing to do.
2805 if (type == SPA_IMPORT_ASSEMBLE)
2808 healthy_tvds = spa_healthy_core_tvds(spa);
2810 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
2812 spa_load_failed(spa, "unable to retrieve MOS config");
2813 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2817 * If we are doing an open, pool owner wasn't verified yet, thus do
2818 * the verification here.
2820 if (spa->spa_load_state == SPA_LOAD_OPEN) {
2821 error = spa_verify_host(spa, mos_config);
2823 nvlist_free(mos_config);
2828 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
2830 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2833 * Build a new vdev tree from the trusted config
2835 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
2838 * Vdev paths in the MOS may be obsolete. If the untrusted config was
2839 * obtained by scanning /dev/dsk, then it will have the right vdev
2840 * paths. We update the trusted MOS config with this information.
2841 * We first try to copy the paths with vdev_copy_path_strict, which
2842 * succeeds only when both configs have exactly the same vdev tree.
2843 * If that fails, we fall back to a more flexible method that has a
2844 * best effort policy.
2846 copy_error = vdev_copy_path_strict(rvd, mrvd);
2847 if (copy_error != 0 || spa_load_print_vdev_tree) {
2848 spa_load_note(spa, "provided vdev tree:");
2849 vdev_dbgmsg_print_tree(rvd, 2);
2850 spa_load_note(spa, "MOS vdev tree:");
2851 vdev_dbgmsg_print_tree(mrvd, 2);
2853 if (copy_error != 0) {
2854 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
2855 "back to vdev_copy_path_relaxed");
2856 vdev_copy_path_relaxed(rvd, mrvd);
2861 spa->spa_root_vdev = mrvd;
2863 spa_config_exit(spa, SCL_ALL, FTAG);
2866 * We will use spa_config if we decide to reload the spa or if spa_load
2867 * fails and we rewind. We must thus regenerate the config using the
2868 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
2869 * pass settings on how to load the pool and is not stored in the MOS.
2870 * We copy it over to our new, trusted config.
2872 mos_config_txg = fnvlist_lookup_uint64(mos_config,
2873 ZPOOL_CONFIG_POOL_TXG);
2874 nvlist_free(mos_config);
2875 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
2876 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
2878 fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
2879 spa_config_set(spa, mos_config);
2880 spa->spa_config_source = SPA_CONFIG_SRC_MOS;
2883 * Now that we got the config from the MOS, we should be more strict
2884 * in checking blkptrs and can make assumptions about the consistency
2885 * of the vdev tree. spa_trust_config must be set to true before opening
2886 * vdevs in order for them to be writeable.
2888 spa->spa_trust_config = B_TRUE;
2891 * Open and validate the new vdev tree
2893 error = spa_ld_open_vdevs(spa);
2897 error = spa_ld_validate_vdevs(spa);
2901 if (copy_error != 0 || spa_load_print_vdev_tree) {
2902 spa_load_note(spa, "final vdev tree:");
2903 vdev_dbgmsg_print_tree(rvd, 2);
2906 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
2907 !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
2909 * Sanity check to make sure that we are indeed loading the
2910 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
2911 * in the config provided and they happened to be the only ones
2912 * to have the latest uberblock, we could involuntarily perform
2913 * an extreme rewind.
2915 healthy_tvds_mos = spa_healthy_core_tvds(spa);
2916 if (healthy_tvds_mos - healthy_tvds >=
2917 SPA_SYNC_MIN_VDEVS) {
2918 spa_load_note(spa, "config provided misses too many "
2919 "top-level vdevs compared to MOS (%lld vs %lld). ",
2920 (u_longlong_t)healthy_tvds,
2921 (u_longlong_t)healthy_tvds_mos);
2922 spa_load_note(spa, "vdev tree:");
2923 vdev_dbgmsg_print_tree(rvd, 2);
2925 spa_load_failed(spa, "config was already "
2926 "provided from MOS. Aborting.");
2927 return (spa_vdev_err(rvd,
2928 VDEV_AUX_CORRUPT_DATA, EIO));
2930 spa_load_note(spa, "spa must be reloaded using MOS "
2932 return (SET_ERROR(EAGAIN));
2936 error = spa_check_for_missing_logs(spa);
2938 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2940 if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
2941 spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
2942 "guid sum (%llu != %llu)",
2943 (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
2944 (u_longlong_t)rvd->vdev_guid_sum);
2945 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
2953 spa_ld_open_indirect_vdev_metadata(spa_t *spa)
2956 vdev_t *rvd = spa->spa_root_vdev;
2959 * Everything that we read before spa_remove_init() must be stored
2960 * on concreted vdevs. Therefore we do this as early as possible.
2962 error = spa_remove_init(spa);
2964 spa_load_failed(spa, "spa_remove_init failed [error=%d]",
2966 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2970 * Retrieve information needed to condense indirect vdev mappings.
2972 error = spa_condense_init(spa);
2974 spa_load_failed(spa, "spa_condense_init failed [error=%d]",
2976 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
2983 spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
2986 vdev_t *rvd = spa->spa_root_vdev;
2988 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2989 boolean_t missing_feat_read = B_FALSE;
2990 nvlist_t *unsup_feat, *enabled_feat;
2992 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
2993 &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
2994 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2997 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
2998 &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
2999 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3002 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
3003 &spa->spa_feat_desc_obj, B_TRUE) != 0) {
3004 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3007 enabled_feat = fnvlist_alloc();
3008 unsup_feat = fnvlist_alloc();
3010 if (!spa_features_check(spa, B_FALSE,
3011 unsup_feat, enabled_feat))
3012 missing_feat_read = B_TRUE;
3014 if (spa_writeable(spa) ||
3015 spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3016 if (!spa_features_check(spa, B_TRUE,
3017 unsup_feat, enabled_feat)) {
3018 *missing_feat_writep = B_TRUE;
3022 fnvlist_add_nvlist(spa->spa_load_info,
3023 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3025 if (!nvlist_empty(unsup_feat)) {
3026 fnvlist_add_nvlist(spa->spa_load_info,
3027 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3030 fnvlist_free(enabled_feat);
3031 fnvlist_free(unsup_feat);
3033 if (!missing_feat_read) {
3034 fnvlist_add_boolean(spa->spa_load_info,
3035 ZPOOL_CONFIG_CAN_RDONLY);
3039 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3040 * twofold: to determine whether the pool is available for
3041 * import in read-write mode and (if it is not) whether the
3042 * pool is available for import in read-only mode. If the pool
3043 * is available for import in read-write mode, it is displayed
3044 * as available in userland; if it is not available for import
3045 * in read-only mode, it is displayed as unavailable in
3046 * userland. If the pool is available for import in read-only
3047 * mode but not read-write mode, it is displayed as unavailable
3048 * in userland with a special note that the pool is actually
3049 * available for open in read-only mode.
3051 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3052 * missing a feature for write, we must first determine whether
3053 * the pool can be opened read-only before returning to
3054 * userland in order to know whether to display the
3055 * abovementioned note.
3057 if (missing_feat_read || (*missing_feat_writep &&
3058 spa_writeable(spa))) {
3059 spa_load_failed(spa, "pool uses unsupported features");
3060 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3065 * Load refcounts for ZFS features from disk into an in-memory
3066 * cache during SPA initialization.
3068 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
3071 error = feature_get_refcount_from_disk(spa,
3072 &spa_feature_table[i], &refcount);
3074 spa->spa_feat_refcount_cache[i] = refcount;
3075 } else if (error == ENOTSUP) {
3076 spa->spa_feat_refcount_cache[i] =
3077 SPA_FEATURE_DISABLED;
3079 spa_load_failed(spa, "error getting refcount "
3080 "for feature %s [error=%d]",
3081 spa_feature_table[i].fi_guid, error);
3082 return (spa_vdev_err(rvd,
3083 VDEV_AUX_CORRUPT_DATA, EIO));
3088 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3089 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
3090 &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
3091 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3098 spa_ld_load_special_directories(spa_t *spa)
3101 vdev_t *rvd = spa->spa_root_vdev;
3103 spa->spa_is_initializing = B_TRUE;
3104 error = dsl_pool_open(spa->spa_dsl_pool);
3105 spa->spa_is_initializing = B_FALSE;
3107 spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3108 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3115 spa_ld_get_props(spa_t *spa)
3119 vdev_t *rvd = spa->spa_root_vdev;
3121 /* Grab the secret checksum salt from the MOS. */
3122 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3123 DMU_POOL_CHECKSUM_SALT, 1,
3124 sizeof (spa->spa_cksum_salt.zcs_bytes),
3125 spa->spa_cksum_salt.zcs_bytes);
3126 if (error == ENOENT) {
3127 /* Generate a new salt for subsequent use */
3128 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3129 sizeof (spa->spa_cksum_salt.zcs_bytes));
3130 } else if (error != 0) {
3131 spa_load_failed(spa, "unable to retrieve checksum salt from "
3132 "MOS [error=%d]", error);
3133 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3136 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3137 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3138 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3140 spa_load_failed(spa, "error opening deferred-frees bpobj "
3141 "[error=%d]", error);
3142 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3146 * Load the bit that tells us to use the new accounting function
3147 * (raid-z deflation). If we have an older pool, this will not
3150 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3151 if (error != 0 && error != ENOENT)
3152 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3154 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3155 &spa->spa_creation_version, B_FALSE);
3156 if (error != 0 && error != ENOENT)
3157 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3160 * Load the persistent error log. If we have an older pool, this will
3163 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3165 if (error != 0 && error != ENOENT)
3166 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3168 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3169 &spa->spa_errlog_scrub, B_FALSE);
3170 if (error != 0 && error != ENOENT)
3171 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3174 * Load the history object. If we have an older pool, this
3175 * will not be present.
3177 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3178 if (error != 0 && error != ENOENT)
3179 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3182 * Load the per-vdev ZAP map. If we have an older pool, this will not
3183 * be present; in this case, defer its creation to a later time to
3184 * avoid dirtying the MOS this early / out of sync context. See
3185 * spa_sync_config_object.
3188 /* The sentinel is only available in the MOS config. */
3189 nvlist_t *mos_config;
3190 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3191 spa_load_failed(spa, "unable to retrieve MOS config");
3192 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3195 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3196 &spa->spa_all_vdev_zaps, B_FALSE);
3198 if (error == ENOENT) {
3199 VERIFY(!nvlist_exists(mos_config,
3200 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3201 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3202 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3203 } else if (error != 0) {
3204 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3205 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3207 * An older version of ZFS overwrote the sentinel value, so
3208 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3209 * destruction to later; see spa_sync_config_object.
3211 spa->spa_avz_action = AVZ_ACTION_DESTROY;
3213 * We're assuming that no vdevs have had their ZAPs created
3214 * before this. Better be sure of it.
3216 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3218 nvlist_free(mos_config);
3220 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3222 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3224 if (error && error != ENOENT)
3225 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3228 uint64_t autoreplace;
3230 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3231 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3232 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3233 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3234 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3235 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3236 &spa->spa_dedup_ditto);
3238 spa->spa_autoreplace = (autoreplace != 0);
3242 * If we are importing a pool with missing top-level vdevs,
3243 * we enforce that the pool doesn't panic or get suspended on
3244 * error since the likelihood of missing data is extremely high.
3246 if (spa->spa_missing_tvds > 0 &&
3247 spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3248 spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3249 spa_load_note(spa, "forcing failmode to 'continue' "
3250 "as some top level vdevs are missing");
3251 spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3258 spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3261 vdev_t *rvd = spa->spa_root_vdev;
3264 * If we're assembling the pool from the split-off vdevs of
3265 * an existing pool, we don't want to attach the spares & cache
3270 * Load any hot spares for this pool.
3272 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3274 if (error != 0 && error != ENOENT)
3275 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3276 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3277 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3278 if (load_nvlist(spa, spa->spa_spares.sav_object,
3279 &spa->spa_spares.sav_config) != 0) {
3280 spa_load_failed(spa, "error loading spares nvlist");
3281 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3284 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3285 spa_load_spares(spa);
3286 spa_config_exit(spa, SCL_ALL, FTAG);
3287 } else if (error == 0) {
3288 spa->spa_spares.sav_sync = B_TRUE;
3292 * Load any level 2 ARC devices for this pool.
3294 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3295 &spa->spa_l2cache.sav_object, B_FALSE);
3296 if (error != 0 && error != ENOENT)
3297 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3298 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3299 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3300 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3301 &spa->spa_l2cache.sav_config) != 0) {
3302 spa_load_failed(spa, "error loading l2cache nvlist");
3303 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3306 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3307 spa_load_l2cache(spa);
3308 spa_config_exit(spa, SCL_ALL, FTAG);
3309 } else if (error == 0) {
3310 spa->spa_l2cache.sav_sync = B_TRUE;
3317 spa_ld_load_vdev_metadata(spa_t *spa)
3320 vdev_t *rvd = spa->spa_root_vdev;
3323 * If the 'autoreplace' property is set, then post a resource notifying
3324 * the ZFS DE that it should not issue any faults for unopenable
3325 * devices. We also iterate over the vdevs, and post a sysevent for any
3326 * unopenable vdevs so that the normal autoreplace handler can take
3329 if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3330 spa_check_removed(spa->spa_root_vdev);
3332 * For the import case, this is done in spa_import(), because
3333 * at this point we're using the spare definitions from
3334 * the MOS config, not necessarily from the userland config.
3336 if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3337 spa_aux_check_removed(&spa->spa_spares);
3338 spa_aux_check_removed(&spa->spa_l2cache);
3343 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3345 error = vdev_load(rvd);
3347 spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3348 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3352 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3354 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3355 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3356 spa_config_exit(spa, SCL_ALL, FTAG);
3362 spa_ld_load_dedup_tables(spa_t *spa)
3365 vdev_t *rvd = spa->spa_root_vdev;
3367 error = ddt_load(spa);
3369 spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3370 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3377 spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3379 vdev_t *rvd = spa->spa_root_vdev;
3381 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3382 boolean_t missing = spa_check_logs(spa);
3384 if (spa->spa_missing_tvds != 0) {
3385 spa_load_note(spa, "spa_check_logs failed "
3386 "so dropping the logs");
3388 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3389 spa_load_failed(spa, "spa_check_logs failed");
3390 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3400 spa_ld_verify_pool_data(spa_t *spa)
3403 vdev_t *rvd = spa->spa_root_vdev;
3406 * We've successfully opened the pool, verify that we're ready
3407 * to start pushing transactions.
3409 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3410 error = spa_load_verify(spa);
3412 spa_load_failed(spa, "spa_load_verify failed "
3413 "[error=%d]", error);
3414 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3423 spa_ld_claim_log_blocks(spa_t *spa)
3426 dsl_pool_t *dp = spa_get_dsl(spa);
3429 * Claim log blocks that haven't been committed yet.
3430 * This must all happen in a single txg.
3431 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3432 * invoked from zil_claim_log_block()'s i/o done callback.
3433 * Price of rollback is that we abandon the log.
3435 spa->spa_claiming = B_TRUE;
3437 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3438 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3439 zil_claim, tx, DS_FIND_CHILDREN);
3442 spa->spa_claiming = B_FALSE;
3444 spa_set_log_state(spa, SPA_LOG_GOOD);
3448 spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3449 boolean_t update_config_cache)
3451 vdev_t *rvd = spa->spa_root_vdev;
3452 int need_update = B_FALSE;
3455 * If the config cache is stale, or we have uninitialized
3456 * metaslabs (see spa_vdev_add()), then update the config.
3458 * If this is a verbatim import, trust the current
3459 * in-core spa_config and update the disk labels.
3461 if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
3462 spa->spa_load_state == SPA_LOAD_IMPORT ||
3463 spa->spa_load_state == SPA_LOAD_RECOVER ||
3464 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3465 need_update = B_TRUE;
3467 for (int c = 0; c < rvd->vdev_children; c++)
3468 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3469 need_update = B_TRUE;
3472 * Update the config cache asychronously in case we're the
3473 * root pool, in which case the config cache isn't writable yet.
3476 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3480 spa_ld_prepare_for_reload(spa_t *spa)
3482 int mode = spa->spa_mode;
3483 int async_suspended = spa->spa_async_suspended;
3486 spa_deactivate(spa);
3487 spa_activate(spa, mode);
3490 * We save the value of spa_async_suspended as it gets reset to 0 by
3491 * spa_unload(). We want to restore it back to the original value before
3492 * returning as we might be calling spa_async_resume() later.
3494 spa->spa_async_suspended = async_suspended;
3498 spa_ld_read_checkpoint_txg(spa_t *spa)
3500 uberblock_t checkpoint;
3503 ASSERT0(spa->spa_checkpoint_txg);
3504 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3506 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3507 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3508 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3510 if (error == ENOENT)
3516 ASSERT3U(checkpoint.ub_txg, !=, 0);
3517 ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3518 ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3519 spa->spa_checkpoint_txg = checkpoint.ub_txg;
3520 spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3526 spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
3530 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3531 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3534 * Never trust the config that is provided unless we are assembling
3535 * a pool following a split.
3536 * This means don't trust blkptrs and the vdev tree in general. This
3537 * also effectively puts the spa in read-only mode since
3538 * spa_writeable() checks for spa_trust_config to be true.
3539 * We will later load a trusted config from the MOS.
3541 if (type != SPA_IMPORT_ASSEMBLE)
3542 spa->spa_trust_config = B_FALSE;
3545 * Parse the config provided to create a vdev tree.
3547 error = spa_ld_parse_config(spa, type);
3552 * Now that we have the vdev tree, try to open each vdev. This involves
3553 * opening the underlying physical device, retrieving its geometry and
3554 * probing the vdev with a dummy I/O. The state of each vdev will be set
3555 * based on the success of those operations. After this we'll be ready
3556 * to read from the vdevs.
3558 error = spa_ld_open_vdevs(spa);
3563 * Read the label of each vdev and make sure that the GUIDs stored
3564 * there match the GUIDs in the config provided.
3565 * If we're assembling a new pool that's been split off from an
3566 * existing pool, the labels haven't yet been updated so we skip
3567 * validation for now.
3569 if (type != SPA_IMPORT_ASSEMBLE) {
3570 error = spa_ld_validate_vdevs(spa);
3576 * Read all vdev labels to find the best uberblock (i.e. latest,
3577 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3578 * get the list of features required to read blkptrs in the MOS from
3579 * the vdev label with the best uberblock and verify that our version
3580 * of zfs supports them all.
3582 error = spa_ld_select_uberblock(spa, type);
3587 * Pass that uberblock to the dsl_pool layer which will open the root
3588 * blkptr. This blkptr points to the latest version of the MOS and will
3589 * allow us to read its contents.
3591 error = spa_ld_open_rootbp(spa);
3599 spa_ld_checkpoint_rewind(spa_t *spa)
3601 uberblock_t checkpoint;
3604 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3605 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3607 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3608 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3609 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3612 spa_load_failed(spa, "unable to retrieve checkpointed "
3613 "uberblock from the MOS config [error=%d]", error);
3615 if (error == ENOENT)
3616 error = ZFS_ERR_NO_CHECKPOINT;
3621 ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
3622 ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
3625 * We need to update the txg and timestamp of the checkpointed
3626 * uberblock to be higher than the latest one. This ensures that
3627 * the checkpointed uberblock is selected if we were to close and
3628 * reopen the pool right after we've written it in the vdev labels.
3629 * (also see block comment in vdev_uberblock_compare)
3631 checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
3632 checkpoint.ub_timestamp = gethrestime_sec();
3635 * Set current uberblock to be the checkpointed uberblock.
3637 spa->spa_uberblock = checkpoint;
3640 * If we are doing a normal rewind, then the pool is open for
3641 * writing and we sync the "updated" checkpointed uberblock to
3642 * disk. Once this is done, we've basically rewound the whole
3643 * pool and there is no way back.
3645 * There are cases when we don't want to attempt and sync the
3646 * checkpointed uberblock to disk because we are opening a
3647 * pool as read-only. Specifically, verifying the checkpointed
3648 * state with zdb, and importing the checkpointed state to get
3649 * a "preview" of its content.
3651 if (spa_writeable(spa)) {
3652 vdev_t *rvd = spa->spa_root_vdev;
3654 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3655 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
3657 int children = rvd->vdev_children;
3658 int c0 = spa_get_random(children);
3660 for (int c = 0; c < children; c++) {
3661 vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
3663 /* Stop when revisiting the first vdev */
3664 if (c > 0 && svd[0] == vd)
3667 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
3668 !vdev_is_concrete(vd))
3671 svd[svdcount++] = vd;
3672 if (svdcount == SPA_SYNC_MIN_VDEVS)
3675 error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
3677 spa->spa_last_synced_guid = rvd->vdev_guid;
3678 spa_config_exit(spa, SCL_ALL, FTAG);
3681 spa_load_failed(spa, "failed to write checkpointed "
3682 "uberblock to the vdev labels [error=%d]", error);
3691 spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
3692 boolean_t *update_config_cache)
3697 * Parse the config for pool, open and validate vdevs,
3698 * select an uberblock, and use that uberblock to open
3701 error = spa_ld_mos_init(spa, type);
3706 * Retrieve the trusted config stored in the MOS and use it to create
3707 * a new, exact version of the vdev tree, then reopen all vdevs.
3709 error = spa_ld_trusted_config(spa, type, B_FALSE);
3710 if (error == EAGAIN) {
3711 if (update_config_cache != NULL)
3712 *update_config_cache = B_TRUE;
3715 * Redo the loading process with the trusted config if it is
3716 * too different from the untrusted config.
3718 spa_ld_prepare_for_reload(spa);
3719 spa_load_note(spa, "RELOADING");
3720 error = spa_ld_mos_init(spa, type);
3724 error = spa_ld_trusted_config(spa, type, B_TRUE);
3728 } else if (error != 0) {
3736 * Load an existing storage pool, using the config provided. This config
3737 * describes which vdevs are part of the pool and is later validated against
3738 * partial configs present in each vdev's label and an entire copy of the
3739 * config stored in the MOS.
3742 spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
3745 boolean_t missing_feat_write = B_FALSE;
3746 boolean_t checkpoint_rewind =
3747 (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3748 boolean_t update_config_cache = B_FALSE;
3750 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3751 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3753 spa_load_note(spa, "LOADING");
3755 error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
3760 * If we are rewinding to the checkpoint then we need to repeat
3761 * everything we've done so far in this function but this time
3762 * selecting the checkpointed uberblock and using that to open
3765 if (checkpoint_rewind) {
3767 * If we are rewinding to the checkpoint update config cache
3770 update_config_cache = B_TRUE;
3773 * Extract the checkpointed uberblock from the current MOS
3774 * and use this as the pool's uberblock from now on. If the
3775 * pool is imported as writeable we also write the checkpoint
3776 * uberblock to the labels, making the rewind permanent.
3778 error = spa_ld_checkpoint_rewind(spa);
3783 * Redo the loading process process again with the
3784 * checkpointed uberblock.
3786 spa_ld_prepare_for_reload(spa);
3787 spa_load_note(spa, "LOADING checkpointed uberblock");
3788 error = spa_ld_mos_with_trusted_config(spa, type, NULL);
3794 * Retrieve the checkpoint txg if the pool has a checkpoint.
3796 error = spa_ld_read_checkpoint_txg(spa);
3801 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
3802 * from the pool and their contents were re-mapped to other vdevs. Note
3803 * that everything that we read before this step must have been
3804 * rewritten on concrete vdevs after the last device removal was
3805 * initiated. Otherwise we could be reading from indirect vdevs before
3806 * we have loaded their mappings.
3808 error = spa_ld_open_indirect_vdev_metadata(spa);
3813 * Retrieve the full list of active features from the MOS and check if
3814 * they are all supported.
3816 error = spa_ld_check_features(spa, &missing_feat_write);
3821 * Load several special directories from the MOS needed by the dsl_pool
3824 error = spa_ld_load_special_directories(spa);
3829 * Retrieve pool properties from the MOS.
3831 error = spa_ld_get_props(spa);
3836 * Retrieve the list of auxiliary devices - cache devices and spares -
3839 error = spa_ld_open_aux_vdevs(spa, type);
3844 * Load the metadata for all vdevs. Also check if unopenable devices
3845 * should be autoreplaced.
3847 error = spa_ld_load_vdev_metadata(spa);
3851 error = spa_ld_load_dedup_tables(spa);
3856 * Verify the logs now to make sure we don't have any unexpected errors
3857 * when we claim log blocks later.
3859 error = spa_ld_verify_logs(spa, type, ereport);
3863 if (missing_feat_write) {
3864 ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
3867 * At this point, we know that we can open the pool in
3868 * read-only mode but not read-write mode. We now have enough
3869 * information and can return to userland.
3871 return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
3876 * Traverse the last txgs to make sure the pool was left off in a safe
3877 * state. When performing an extreme rewind, we verify the whole pool,
3878 * which can take a very long time.
3880 error = spa_ld_verify_pool_data(spa);
3885 * Calculate the deflated space for the pool. This must be done before
3886 * we write anything to the pool because we'd need to update the space
3887 * accounting using the deflated sizes.
3889 spa_update_dspace(spa);
3892 * We have now retrieved all the information we needed to open the
3893 * pool. If we are importing the pool in read-write mode, a few
3894 * additional steps must be performed to finish the import.
3896 if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
3897 spa->spa_load_max_txg == UINT64_MAX)) {
3898 uint64_t config_cache_txg = spa->spa_config_txg;
3900 ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
3903 * In case of a checkpoint rewind, log the original txg
3904 * of the checkpointed uberblock.
3906 if (checkpoint_rewind) {
3907 spa_history_log_internal(spa, "checkpoint rewind",
3908 NULL, "rewound state to txg=%llu",
3909 (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
3913 * Traverse the ZIL and claim all blocks.
3915 spa_ld_claim_log_blocks(spa);
3918 * Kick-off the syncing thread.
3920 spa->spa_sync_on = B_TRUE;
3921 txg_sync_start(spa->spa_dsl_pool);
3924 * Wait for all claims to sync. We sync up to the highest
3925 * claimed log block birth time so that claimed log blocks
3926 * don't appear to be from the future. spa_claim_max_txg
3927 * will have been set for us by ZIL traversal operations
3930 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
3933 * Check if we need to request an update of the config. On the
3934 * next sync, we would update the config stored in vdev labels
3935 * and the cachefile (by default /etc/zfs/zpool.cache).
3937 spa_ld_check_for_config_update(spa, config_cache_txg,
3938 update_config_cache);
3941 * Check all DTLs to see if anything needs resilvering.
3943 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
3944 vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
3945 spa_async_request(spa, SPA_ASYNC_RESILVER);
3948 * Log the fact that we booted up (so that we can detect if
3949 * we rebooted in the middle of an operation).
3951 spa_history_log_version(spa, "open");
3954 * Delete any inconsistent datasets.
3956 (void) dmu_objset_find(spa_name(spa),
3957 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
3960 * Clean up any stale temporary dataset userrefs.
3962 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
3964 spa_restart_removal(spa);
3966 spa_spawn_aux_threads(spa);
3968 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3969 vdev_initialize_restart(spa->spa_root_vdev);
3970 spa_config_exit(spa, SCL_CONFIG, FTAG);
3973 spa_load_note(spa, "LOADED");
3979 spa_load_retry(spa_t *spa, spa_load_state_t state)
3981 int mode = spa->spa_mode;
3984 spa_deactivate(spa);
3986 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
3988 spa_activate(spa, mode);
3989 spa_async_suspend(spa);
3991 spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
3992 (u_longlong_t)spa->spa_load_max_txg);
3994 return (spa_load(spa, state, SPA_IMPORT_EXISTING));
3998 * If spa_load() fails this function will try loading prior txg's. If
3999 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
4000 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
4001 * function will not rewind the pool and will return the same error as
4005 spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4008 nvlist_t *loadinfo = NULL;
4009 nvlist_t *config = NULL;
4010 int load_error, rewind_error;
4011 uint64_t safe_rewind_txg;
4014 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4015 spa->spa_load_max_txg = spa->spa_load_txg;
4016 spa_set_log_state(spa, SPA_LOG_CLEAR);
4018 spa->spa_load_max_txg = max_request;
4019 if (max_request != UINT64_MAX)
4020 spa->spa_extreme_rewind = B_TRUE;
4023 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
4024 if (load_error == 0)
4026 if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4028 * When attempting checkpoint-rewind on a pool with no
4029 * checkpoint, we should not attempt to load uberblocks
4030 * from previous txgs when spa_load fails.
4032 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4033 return (load_error);
4036 if (spa->spa_root_vdev != NULL)
4037 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4039 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4040 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4042 if (rewind_flags & ZPOOL_NEVER_REWIND) {
4043 nvlist_free(config);
4044 return (load_error);
4047 if (state == SPA_LOAD_RECOVER) {
4048 /* Price of rolling back is discarding txgs, including log */
4049 spa_set_log_state(spa, SPA_LOG_CLEAR);
4052 * If we aren't rolling back save the load info from our first
4053 * import attempt so that we can restore it after attempting
4056 loadinfo = spa->spa_load_info;
4057 spa->spa_load_info = fnvlist_alloc();
4060 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4061 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4062 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4063 TXG_INITIAL : safe_rewind_txg;
4066 * Continue as long as we're finding errors, we're still within
4067 * the acceptable rewind range, and we're still finding uberblocks
4069 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4070 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4071 if (spa->spa_load_max_txg < safe_rewind_txg)
4072 spa->spa_extreme_rewind = B_TRUE;
4073 rewind_error = spa_load_retry(spa, state);
4076 spa->spa_extreme_rewind = B_FALSE;
4077 spa->spa_load_max_txg = UINT64_MAX;
4079 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4080 spa_config_set(spa, config);
4082 nvlist_free(config);
4084 if (state == SPA_LOAD_RECOVER) {
4085 ASSERT3P(loadinfo, ==, NULL);
4086 return (rewind_error);
4088 /* Store the rewind info as part of the initial load info */
4089 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4090 spa->spa_load_info);
4092 /* Restore the initial load info */
4093 fnvlist_free(spa->spa_load_info);
4094 spa->spa_load_info = loadinfo;
4096 return (load_error);
4103 * The import case is identical to an open except that the configuration is sent
4104 * down from userland, instead of grabbed from the configuration cache. For the
4105 * case of an open, the pool configuration will exist in the
4106 * POOL_STATE_UNINITIALIZED state.
4108 * The stats information (gen/count/ustats) is used to gather vdev statistics at
4109 * the same time open the pool, without having to keep around the spa_t in some
4113 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4117 spa_load_state_t state = SPA_LOAD_OPEN;
4119 int locked = B_FALSE;
4120 int firstopen = B_FALSE;
4125 * As disgusting as this is, we need to support recursive calls to this
4126 * function because dsl_dir_open() is called during spa_load(), and ends
4127 * up calling spa_open() again. The real fix is to figure out how to
4128 * avoid dsl_dir_open() calling this in the first place.
4130 if (mutex_owner(&spa_namespace_lock) != curthread) {
4131 mutex_enter(&spa_namespace_lock);
4135 if ((spa = spa_lookup(pool)) == NULL) {
4137 mutex_exit(&spa_namespace_lock);
4138 return (SET_ERROR(ENOENT));
4141 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
4142 zpool_load_policy_t policy;
4146 zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
4148 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
4149 state = SPA_LOAD_RECOVER;
4151 spa_activate(spa, spa_mode_global);
4153 if (state != SPA_LOAD_RECOVER)
4154 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4155 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
4157 zfs_dbgmsg("spa_open_common: opening %s", pool);
4158 error = spa_load_best(spa, state, policy.zlp_txg,
4161 if (error == EBADF) {
4163 * If vdev_validate() returns failure (indicated by
4164 * EBADF), it indicates that one of the vdevs indicates
4165 * that the pool has been exported or destroyed. If
4166 * this is the case, the config cache is out of sync and
4167 * we should remove the pool from the namespace.
4170 spa_deactivate(spa);
4171 spa_write_cachefile(spa, B_TRUE, B_TRUE);
4174 mutex_exit(&spa_namespace_lock);
4175 return (SET_ERROR(ENOENT));
4180 * We can't open the pool, but we still have useful
4181 * information: the state of each vdev after the
4182 * attempted vdev_open(). Return this to the user.
4184 if (config != NULL && spa->spa_config) {
4185 VERIFY(nvlist_dup(spa->spa_config, config,
4187 VERIFY(nvlist_add_nvlist(*config,
4188 ZPOOL_CONFIG_LOAD_INFO,
4189 spa->spa_load_info) == 0);
4192 spa_deactivate(spa);
4193 spa->spa_last_open_failed = error;
4195 mutex_exit(&spa_namespace_lock);
4201 spa_open_ref(spa, tag);
4204 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4207 * If we've recovered the pool, pass back any information we
4208 * gathered while doing the load.
4210 if (state == SPA_LOAD_RECOVER) {
4211 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4212 spa->spa_load_info) == 0);
4216 spa->spa_last_open_failed = 0;
4217 spa->spa_last_ubsync_txg = 0;
4218 spa->spa_load_txg = 0;
4219 mutex_exit(&spa_namespace_lock);
4223 zvol_create_minors(spa->spa_name);
4234 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4237 return (spa_open_common(name, spapp, tag, policy, config));
4241 spa_open(const char *name, spa_t **spapp, void *tag)
4243 return (spa_open_common(name, spapp, tag, NULL, NULL));
4247 * Lookup the given spa_t, incrementing the inject count in the process,
4248 * preventing it from being exported or destroyed.
4251 spa_inject_addref(char *name)
4255 mutex_enter(&spa_namespace_lock);
4256 if ((spa = spa_lookup(name)) == NULL) {
4257 mutex_exit(&spa_namespace_lock);
4260 spa->spa_inject_ref++;
4261 mutex_exit(&spa_namespace_lock);
4267 spa_inject_delref(spa_t *spa)
4269 mutex_enter(&spa_namespace_lock);
4270 spa->spa_inject_ref--;
4271 mutex_exit(&spa_namespace_lock);
4275 * Add spares device information to the nvlist.
4278 spa_add_spares(spa_t *spa, nvlist_t *config)
4288 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4290 if (spa->spa_spares.sav_count == 0)
4293 VERIFY(nvlist_lookup_nvlist(config,
4294 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4295 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4296 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4298 VERIFY(nvlist_add_nvlist_array(nvroot,
4299 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4300 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4301 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4304 * Go through and find any spares which have since been
4305 * repurposed as an active spare. If this is the case, update
4306 * their status appropriately.
4308 for (i = 0; i < nspares; i++) {
4309 VERIFY(nvlist_lookup_uint64(spares[i],
4310 ZPOOL_CONFIG_GUID, &guid) == 0);
4311 if (spa_spare_exists(guid, &pool, NULL) &&
4313 VERIFY(nvlist_lookup_uint64_array(
4314 spares[i], ZPOOL_CONFIG_VDEV_STATS,
4315 (uint64_t **)&vs, &vsc) == 0);
4316 vs->vs_state = VDEV_STATE_CANT_OPEN;
4317 vs->vs_aux = VDEV_AUX_SPARED;
4324 * Add l2cache device information to the nvlist, including vdev stats.
4327 spa_add_l2cache(spa_t *spa, nvlist_t *config)
4330 uint_t i, j, nl2cache;
4337 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4339 if (spa->spa_l2cache.sav_count == 0)
4342 VERIFY(nvlist_lookup_nvlist(config,
4343 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4344 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4345 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4346 if (nl2cache != 0) {
4347 VERIFY(nvlist_add_nvlist_array(nvroot,
4348 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4349 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4350 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4353 * Update level 2 cache device stats.
4356 for (i = 0; i < nl2cache; i++) {
4357 VERIFY(nvlist_lookup_uint64(l2cache[i],
4358 ZPOOL_CONFIG_GUID, &guid) == 0);
4361 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4363 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4364 vd = spa->spa_l2cache.sav_vdevs[j];
4370 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4371 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4373 vdev_get_stats(vd, vs);
4379 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4385 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4386 VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4388 /* We may be unable to read features if pool is suspended. */
4389 if (spa_suspended(spa))
4392 if (spa->spa_feat_for_read_obj != 0) {
4393 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4394 spa->spa_feat_for_read_obj);
4395 zap_cursor_retrieve(&zc, &za) == 0;
4396 zap_cursor_advance(&zc)) {
4397 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4398 za.za_num_integers == 1);
4399 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4400 za.za_first_integer));
4402 zap_cursor_fini(&zc);
4405 if (spa->spa_feat_for_write_obj != 0) {
4406 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4407 spa->spa_feat_for_write_obj);
4408 zap_cursor_retrieve(&zc, &za) == 0;
4409 zap_cursor_advance(&zc)) {
4410 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4411 za.za_num_integers == 1);
4412 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4413 za.za_first_integer));
4415 zap_cursor_fini(&zc);
4419 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4421 nvlist_free(features);
4425 spa_get_stats(const char *name, nvlist_t **config,
4426 char *altroot, size_t buflen)
4432 error = spa_open_common(name, &spa, FTAG, NULL, config);
4436 * This still leaves a window of inconsistency where the spares
4437 * or l2cache devices could change and the config would be
4438 * self-inconsistent.
4440 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4442 if (*config != NULL) {
4443 uint64_t loadtimes[2];
4445 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4446 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4447 VERIFY(nvlist_add_uint64_array(*config,
4448 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4450 VERIFY(nvlist_add_uint64(*config,
4451 ZPOOL_CONFIG_ERRCOUNT,
4452 spa_get_errlog_size(spa)) == 0);
4454 if (spa_suspended(spa))
4455 VERIFY(nvlist_add_uint64(*config,
4456 ZPOOL_CONFIG_SUSPENDED,
4457 spa->spa_failmode) == 0);
4459 spa_add_spares(spa, *config);
4460 spa_add_l2cache(spa, *config);
4461 spa_add_feature_stats(spa, *config);
4466 * We want to get the alternate root even for faulted pools, so we cheat
4467 * and call spa_lookup() directly.
4471 mutex_enter(&spa_namespace_lock);
4472 spa = spa_lookup(name);
4474 spa_altroot(spa, altroot, buflen);
4478 mutex_exit(&spa_namespace_lock);
4480 spa_altroot(spa, altroot, buflen);
4485 spa_config_exit(spa, SCL_CONFIG, FTAG);
4486 spa_close(spa, FTAG);
4493 * Validate that the auxiliary device array is well formed. We must have an
4494 * array of nvlists, each which describes a valid leaf vdev. If this is an
4495 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4496 * specified, as long as they are well-formed.
4499 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4500 spa_aux_vdev_t *sav, const char *config, uint64_t version,
4501 vdev_labeltype_t label)
4508 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4511 * It's acceptable to have no devs specified.
4513 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4517 return (SET_ERROR(EINVAL));
4520 * Make sure the pool is formatted with a version that supports this
4523 if (spa_version(spa) < version)
4524 return (SET_ERROR(ENOTSUP));
4527 * Set the pending device list so we correctly handle device in-use
4530 sav->sav_pending = dev;
4531 sav->sav_npending = ndev;
4533 for (i = 0; i < ndev; i++) {
4534 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4538 if (!vd->vdev_ops->vdev_op_leaf) {
4540 error = SET_ERROR(EINVAL);
4545 * The L2ARC currently only supports disk devices in
4546 * kernel context. For user-level testing, we allow it.
4549 if ((strcmp(config, ZPOOL_CONFIG_L2CACHE) == 0) &&
4550 strcmp(vd->vdev_ops->vdev_op_type, VDEV_TYPE_DISK) != 0) {
4551 error = SET_ERROR(ENOTBLK);
4558 if ((error = vdev_open(vd)) == 0 &&
4559 (error = vdev_label_init(vd, crtxg, label)) == 0) {
4560 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4561 vd->vdev_guid) == 0);
4567 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
4574 sav->sav_pending = NULL;
4575 sav->sav_npending = 0;
4580 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
4584 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4586 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4587 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
4588 VDEV_LABEL_SPARE)) != 0) {
4592 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4593 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
4594 VDEV_LABEL_L2CACHE));
4598 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
4603 if (sav->sav_config != NULL) {
4609 * Generate new dev list by concatentating with the
4612 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
4613 &olddevs, &oldndevs) == 0);
4615 newdevs = kmem_alloc(sizeof (void *) *
4616 (ndevs + oldndevs), KM_SLEEP);
4617 for (i = 0; i < oldndevs; i++)
4618 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
4620 for (i = 0; i < ndevs; i++)
4621 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
4624 VERIFY(nvlist_remove(sav->sav_config, config,
4625 DATA_TYPE_NVLIST_ARRAY) == 0);
4627 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
4628 config, newdevs, ndevs + oldndevs) == 0);
4629 for (i = 0; i < oldndevs + ndevs; i++)
4630 nvlist_free(newdevs[i]);
4631 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
4634 * Generate a new dev list.
4636 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
4638 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
4644 * Stop and drop level 2 ARC devices
4647 spa_l2cache_drop(spa_t *spa)
4651 spa_aux_vdev_t *sav = &spa->spa_l2cache;
4653 for (i = 0; i < sav->sav_count; i++) {
4656 vd = sav->sav_vdevs[i];
4659 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
4660 pool != 0ULL && l2arc_vdev_present(vd))
4661 l2arc_remove_vdev(vd);
4669 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
4673 char *altroot = NULL;
4678 uint64_t txg = TXG_INITIAL;
4679 nvlist_t **spares, **l2cache;
4680 uint_t nspares, nl2cache;
4681 uint64_t version, obj;
4682 boolean_t has_features;
4686 if (nvlist_lookup_string(props,
4687 zpool_prop_to_name(ZPOOL_PROP_TNAME), &poolname) != 0)
4688 poolname = (char *)pool;
4691 * If this pool already exists, return failure.
4693 mutex_enter(&spa_namespace_lock);
4694 if (spa_lookup(poolname) != NULL) {
4695 mutex_exit(&spa_namespace_lock);
4696 return (SET_ERROR(EEXIST));
4700 * Allocate a new spa_t structure.
4702 nvl = fnvlist_alloc();
4703 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
4704 (void) nvlist_lookup_string(props,
4705 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4706 spa = spa_add(poolname, nvl, altroot);
4708 spa_activate(spa, spa_mode_global);
4710 if (props && (error = spa_prop_validate(spa, props))) {
4711 spa_deactivate(spa);
4713 mutex_exit(&spa_namespace_lock);
4718 * Temporary pool names should never be written to disk.
4720 if (poolname != pool)
4721 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
4723 has_features = B_FALSE;
4724 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
4725 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
4726 if (zpool_prop_feature(nvpair_name(elem)))
4727 has_features = B_TRUE;
4730 if (has_features || nvlist_lookup_uint64(props,
4731 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
4732 version = SPA_VERSION;
4734 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
4736 spa->spa_first_txg = txg;
4737 spa->spa_uberblock.ub_txg = txg - 1;
4738 spa->spa_uberblock.ub_version = version;
4739 spa->spa_ubsync = spa->spa_uberblock;
4740 spa->spa_load_state = SPA_LOAD_CREATE;
4741 spa->spa_removing_phys.sr_state = DSS_NONE;
4742 spa->spa_removing_phys.sr_removing_vdev = -1;
4743 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
4744 spa->spa_indirect_vdevs_loaded = B_TRUE;
4747 * Create "The Godfather" zio to hold all async IOs
4749 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
4751 for (int i = 0; i < max_ncpus; i++) {
4752 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
4753 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4754 ZIO_FLAG_GODFATHER);
4758 * Create the root vdev.
4760 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4762 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
4764 ASSERT(error != 0 || rvd != NULL);
4765 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
4767 if (error == 0 && !zfs_allocatable_devs(nvroot))
4768 error = SET_ERROR(EINVAL);
4771 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
4772 (error = spa_validate_aux(spa, nvroot, txg,
4773 VDEV_ALLOC_ADD)) == 0) {
4774 for (int c = 0; c < rvd->vdev_children; c++) {
4775 vdev_ashift_optimize(rvd->vdev_child[c]);
4776 vdev_metaslab_set_size(rvd->vdev_child[c]);
4777 vdev_expand(rvd->vdev_child[c], txg);
4781 spa_config_exit(spa, SCL_ALL, FTAG);
4785 spa_deactivate(spa);
4787 mutex_exit(&spa_namespace_lock);
4792 * Get the list of spares, if specified.
4794 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4795 &spares, &nspares) == 0) {
4796 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
4798 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4799 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4800 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4801 spa_load_spares(spa);
4802 spa_config_exit(spa, SCL_ALL, FTAG);
4803 spa->spa_spares.sav_sync = B_TRUE;
4807 * Get the list of level 2 cache devices, if specified.
4809 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4810 &l2cache, &nl2cache) == 0) {
4811 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
4812 NV_UNIQUE_NAME, KM_SLEEP) == 0);
4813 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4814 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4815 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4816 spa_load_l2cache(spa);
4817 spa_config_exit(spa, SCL_ALL, FTAG);
4818 spa->spa_l2cache.sav_sync = B_TRUE;
4821 spa->spa_is_initializing = B_TRUE;
4822 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
4823 spa->spa_meta_objset = dp->dp_meta_objset;
4824 spa->spa_is_initializing = B_FALSE;
4827 * Create DDTs (dedup tables).
4831 spa_update_dspace(spa);
4833 tx = dmu_tx_create_assigned(dp, txg);
4836 * Create the pool config object.
4838 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
4839 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
4840 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
4842 if (zap_add(spa->spa_meta_objset,
4843 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
4844 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
4845 cmn_err(CE_PANIC, "failed to add pool config");
4848 if (spa_version(spa) >= SPA_VERSION_FEATURES)
4849 spa_feature_create_zap_objects(spa, tx);
4851 if (zap_add(spa->spa_meta_objset,
4852 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
4853 sizeof (uint64_t), 1, &version, tx) != 0) {
4854 cmn_err(CE_PANIC, "failed to add pool version");
4857 /* Newly created pools with the right version are always deflated. */
4858 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
4859 spa->spa_deflate = TRUE;
4860 if (zap_add(spa->spa_meta_objset,
4861 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
4862 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
4863 cmn_err(CE_PANIC, "failed to add deflate");
4868 * Create the deferred-free bpobj. Turn off compression
4869 * because sync-to-convergence takes longer if the blocksize
4872 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
4873 dmu_object_set_compress(spa->spa_meta_objset, obj,
4874 ZIO_COMPRESS_OFF, tx);
4875 if (zap_add(spa->spa_meta_objset,
4876 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
4877 sizeof (uint64_t), 1, &obj, tx) != 0) {
4878 cmn_err(CE_PANIC, "failed to add bpobj");
4880 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
4881 spa->spa_meta_objset, obj));
4884 * Create the pool's history object.
4886 if (version >= SPA_VERSION_ZPOOL_HISTORY)
4887 spa_history_create_obj(spa, tx);
4890 * Generate some random noise for salted checksums to operate on.
4892 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
4893 sizeof (spa->spa_cksum_salt.zcs_bytes));
4896 * Set pool properties.
4898 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
4899 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
4900 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
4901 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
4903 if (props != NULL) {
4904 spa_configfile_set(spa, props, B_FALSE);
4905 spa_sync_props(props, tx);
4910 spa->spa_sync_on = B_TRUE;
4911 txg_sync_start(spa->spa_dsl_pool);
4914 * We explicitly wait for the first transaction to complete so that our
4915 * bean counters are appropriately updated.
4917 txg_wait_synced(spa->spa_dsl_pool, txg);
4919 spa_spawn_aux_threads(spa);
4921 spa_write_cachefile(spa, B_FALSE, B_TRUE);
4922 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
4924 spa_history_log_version(spa, "create");
4927 * Don't count references from objsets that are already closed
4928 * and are making their way through the eviction process.
4930 spa_evicting_os_wait(spa);
4931 spa->spa_minref = refcount_count(&spa->spa_refcount);
4932 spa->spa_load_state = SPA_LOAD_NONE;
4934 mutex_exit(&spa_namespace_lock);
4942 * Get the root pool information from the root disk, then import the root pool
4943 * during the system boot up time.
4945 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
4948 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
4951 nvlist_t *nvtop, *nvroot;
4954 if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
4958 * Add this top-level vdev to the child array.
4960 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4962 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4964 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
4967 * Put this pool's top-level vdevs into a root vdev.
4969 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4970 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
4971 VDEV_TYPE_ROOT) == 0);
4972 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
4973 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
4974 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
4978 * Replace the existing vdev_tree with the new root vdev in
4979 * this pool's configuration (remove the old, add the new).
4981 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
4982 nvlist_free(nvroot);
4987 * Walk the vdev tree and see if we can find a device with "better"
4988 * configuration. A configuration is "better" if the label on that
4989 * device has a more recent txg.
4992 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
4994 for (int c = 0; c < vd->vdev_children; c++)
4995 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
4997 if (vd->vdev_ops->vdev_op_leaf) {
5001 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
5005 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
5009 * Do we have a better boot device?
5011 if (label_txg > *txg) {
5020 * Import a root pool.
5022 * For x86. devpath_list will consist of devid and/or physpath name of
5023 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
5024 * The GRUB "findroot" command will return the vdev we should boot.
5026 * For Sparc, devpath_list consists the physpath name of the booting device
5027 * no matter the rootpool is a single device pool or a mirrored pool.
5029 * "/pci@1f,0/ide@d/disk@0,0:a"
5032 spa_import_rootpool(char *devpath, char *devid)
5035 vdev_t *rvd, *bvd, *avd = NULL;
5036 nvlist_t *config, *nvtop;
5042 * Read the label from the boot device and generate a configuration.
5044 config = spa_generate_rootconf(devpath, devid, &guid);
5045 #if defined(_OBP) && defined(_KERNEL)
5046 if (config == NULL) {
5047 if (strstr(devpath, "/iscsi/ssd") != NULL) {
5049 get_iscsi_bootpath_phy(devpath);
5050 config = spa_generate_rootconf(devpath, devid, &guid);
5054 if (config == NULL) {
5055 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
5057 return (SET_ERROR(EIO));
5060 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5062 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
5064 mutex_enter(&spa_namespace_lock);
5065 if ((spa = spa_lookup(pname)) != NULL) {
5067 * Remove the existing root pool from the namespace so that we
5068 * can replace it with the correct config we just read in.
5073 spa = spa_add(pname, config, NULL);
5074 spa->spa_is_root = B_TRUE;
5075 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5076 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5077 &spa->spa_ubsync.ub_version) != 0)
5078 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5081 * Build up a vdev tree based on the boot device's label config.
5083 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5085 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5086 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5087 VDEV_ALLOC_ROOTPOOL);
5088 spa_config_exit(spa, SCL_ALL, FTAG);
5090 mutex_exit(&spa_namespace_lock);
5091 nvlist_free(config);
5092 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5098 * Get the boot vdev.
5100 if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
5101 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
5102 (u_longlong_t)guid);
5103 error = SET_ERROR(ENOENT);
5108 * Determine if there is a better boot device.
5111 spa_alt_rootvdev(rvd, &avd, &txg);
5113 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
5114 "try booting from '%s'", avd->vdev_path);
5115 error = SET_ERROR(EINVAL);
5120 * If the boot device is part of a spare vdev then ensure that
5121 * we're booting off the active spare.
5123 if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
5124 !bvd->vdev_isspare) {
5125 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
5126 "try booting from '%s'",
5128 vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
5129 error = SET_ERROR(EINVAL);
5135 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5137 spa_config_exit(spa, SCL_ALL, FTAG);
5138 mutex_exit(&spa_namespace_lock);
5140 nvlist_free(config);
5144 #else /* !illumos */
5146 extern int vdev_geom_read_pool_label(const char *name, nvlist_t ***configs,
5150 spa_generate_rootconf(const char *name)
5152 nvlist_t **configs, **tops;
5154 nvlist_t *best_cfg, *nvtop, *nvroot;
5163 if (vdev_geom_read_pool_label(name, &configs, &count) != 0)
5166 ASSERT3U(count, !=, 0);
5168 for (i = 0; i < count; i++) {
5171 VERIFY(nvlist_lookup_uint64(configs[i], ZPOOL_CONFIG_POOL_TXG,
5173 if (txg > best_txg) {
5175 best_cfg = configs[i];
5180 nvlist_lookup_uint64(best_cfg, ZPOOL_CONFIG_VDEV_CHILDREN, &nchildren);
5182 nvlist_lookup_uint64_array(best_cfg, ZPOOL_CONFIG_HOLE_ARRAY,
5185 tops = kmem_zalloc(nchildren * sizeof(void *), KM_SLEEP);
5186 for (i = 0; i < nchildren; i++) {
5189 if (configs[i] == NULL)
5191 VERIFY(nvlist_lookup_nvlist(configs[i], ZPOOL_CONFIG_VDEV_TREE,
5193 nvlist_dup(nvtop, &tops[i], KM_SLEEP);
5195 for (i = 0; holes != NULL && i < nholes; i++) {
5198 if (tops[holes[i]] != NULL)
5200 nvlist_alloc(&tops[holes[i]], NV_UNIQUE_NAME, KM_SLEEP);
5201 VERIFY(nvlist_add_string(tops[holes[i]], ZPOOL_CONFIG_TYPE,
5202 VDEV_TYPE_HOLE) == 0);
5203 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_ID,
5205 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_GUID,
5208 for (i = 0; i < nchildren; i++) {
5209 if (tops[i] != NULL)
5211 nvlist_alloc(&tops[i], NV_UNIQUE_NAME, KM_SLEEP);
5212 VERIFY(nvlist_add_string(tops[i], ZPOOL_CONFIG_TYPE,
5213 VDEV_TYPE_MISSING) == 0);
5214 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_ID,
5216 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_GUID,
5221 * Create pool config based on the best vdev config.
5223 nvlist_dup(best_cfg, &config, KM_SLEEP);
5226 * Put this pool's top-level vdevs into a root vdev.
5228 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5230 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5231 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5232 VDEV_TYPE_ROOT) == 0);
5233 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5234 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5235 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5236 tops, nchildren) == 0);
5239 * Replace the existing vdev_tree with the new root vdev in
5240 * this pool's configuration (remove the old, add the new).
5242 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5245 * Drop vdev config elements that should not be present at pool level.
5247 nvlist_remove(config, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64);
5248 nvlist_remove(config, ZPOOL_CONFIG_TOP_GUID, DATA_TYPE_UINT64);
5250 for (i = 0; i < count; i++)
5251 nvlist_free(configs[i]);
5252 kmem_free(configs, count * sizeof(void *));
5253 for (i = 0; i < nchildren; i++)
5254 nvlist_free(tops[i]);
5255 kmem_free(tops, nchildren * sizeof(void *));
5256 nvlist_free(nvroot);
5261 spa_import_rootpool(const char *name)
5264 vdev_t *rvd, *bvd, *avd = NULL;
5265 nvlist_t *config, *nvtop;
5271 * Read the label from the boot device and generate a configuration.
5273 config = spa_generate_rootconf(name);
5275 mutex_enter(&spa_namespace_lock);
5276 if (config != NULL) {
5277 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5278 &pname) == 0 && strcmp(name, pname) == 0);
5279 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg)
5282 if ((spa = spa_lookup(pname)) != NULL) {
5284 * The pool could already be imported,
5285 * e.g., after reboot -r.
5287 if (spa->spa_state == POOL_STATE_ACTIVE) {
5288 mutex_exit(&spa_namespace_lock);
5289 nvlist_free(config);
5294 * Remove the existing root pool from the namespace so
5295 * that we can replace it with the correct config
5300 spa = spa_add(pname, config, NULL);
5303 * Set spa_ubsync.ub_version as it can be used in vdev_alloc()
5304 * via spa_version().
5306 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5307 &spa->spa_ubsync.ub_version) != 0)
5308 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5309 } else if ((spa = spa_lookup(name)) == NULL) {
5310 mutex_exit(&spa_namespace_lock);
5311 nvlist_free(config);
5312 cmn_err(CE_NOTE, "Cannot find the pool label for '%s'",
5316 VERIFY(nvlist_dup(spa->spa_config, &config, KM_SLEEP) == 0);
5318 spa->spa_is_root = B_TRUE;
5319 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5322 * Build up a vdev tree based on the boot device's label config.
5324 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5326 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5327 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5328 VDEV_ALLOC_ROOTPOOL);
5329 spa_config_exit(spa, SCL_ALL, FTAG);
5331 mutex_exit(&spa_namespace_lock);
5332 nvlist_free(config);
5333 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5338 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5340 spa_config_exit(spa, SCL_ALL, FTAG);
5341 mutex_exit(&spa_namespace_lock);
5343 nvlist_free(config);
5347 #endif /* illumos */
5348 #endif /* _KERNEL */
5351 * Import a non-root pool into the system.
5354 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5357 char *altroot = NULL;
5358 spa_load_state_t state = SPA_LOAD_IMPORT;
5359 zpool_load_policy_t policy;
5360 uint64_t mode = spa_mode_global;
5361 uint64_t readonly = B_FALSE;
5364 nvlist_t **spares, **l2cache;
5365 uint_t nspares, nl2cache;
5368 * If a pool with this name exists, return failure.
5370 mutex_enter(&spa_namespace_lock);
5371 if (spa_lookup(pool) != NULL) {
5372 mutex_exit(&spa_namespace_lock);
5373 return (SET_ERROR(EEXIST));
5377 * Create and initialize the spa structure.
5379 (void) nvlist_lookup_string(props,
5380 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5381 (void) nvlist_lookup_uint64(props,
5382 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5385 spa = spa_add(pool, config, altroot);
5386 spa->spa_import_flags = flags;
5389 * Verbatim import - Take a pool and insert it into the namespace
5390 * as if it had been loaded at boot.
5392 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5394 spa_configfile_set(spa, props, B_FALSE);
5396 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5397 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5398 zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5399 mutex_exit(&spa_namespace_lock);
5403 spa_activate(spa, mode);
5406 * Don't start async tasks until we know everything is healthy.
5408 spa_async_suspend(spa);
5410 zpool_get_load_policy(config, &policy);
5411 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5412 state = SPA_LOAD_RECOVER;
5414 spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5416 if (state != SPA_LOAD_RECOVER) {
5417 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5418 zfs_dbgmsg("spa_import: importing %s", pool);
5420 zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5421 "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
5423 error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
5426 * Propagate anything learned while loading the pool and pass it
5427 * back to caller (i.e. rewind info, missing devices, etc).
5429 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5430 spa->spa_load_info) == 0);
5432 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5434 * Toss any existing sparelist, as it doesn't have any validity
5435 * anymore, and conflicts with spa_has_spare().
5437 if (spa->spa_spares.sav_config) {
5438 nvlist_free(spa->spa_spares.sav_config);
5439 spa->spa_spares.sav_config = NULL;
5440 spa_load_spares(spa);
5442 if (spa->spa_l2cache.sav_config) {
5443 nvlist_free(spa->spa_l2cache.sav_config);
5444 spa->spa_l2cache.sav_config = NULL;
5445 spa_load_l2cache(spa);
5448 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5451 error = spa_validate_aux(spa, nvroot, -1ULL,
5454 error = spa_validate_aux(spa, nvroot, -1ULL,
5455 VDEV_ALLOC_L2CACHE);
5456 spa_config_exit(spa, SCL_ALL, FTAG);
5459 spa_configfile_set(spa, props, B_FALSE);
5461 if (error != 0 || (props && spa_writeable(spa) &&
5462 (error = spa_prop_set(spa, props)))) {
5464 spa_deactivate(spa);
5466 mutex_exit(&spa_namespace_lock);
5470 spa_async_resume(spa);
5473 * Override any spares and level 2 cache devices as specified by
5474 * the user, as these may have correct device names/devids, etc.
5476 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5477 &spares, &nspares) == 0) {
5478 if (spa->spa_spares.sav_config)
5479 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5480 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5482 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5483 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5484 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5485 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5486 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5487 spa_load_spares(spa);
5488 spa_config_exit(spa, SCL_ALL, FTAG);
5489 spa->spa_spares.sav_sync = B_TRUE;
5491 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5492 &l2cache, &nl2cache) == 0) {
5493 if (spa->spa_l2cache.sav_config)
5494 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5495 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5497 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5498 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5499 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5500 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5501 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5502 spa_load_l2cache(spa);
5503 spa_config_exit(spa, SCL_ALL, FTAG);
5504 spa->spa_l2cache.sav_sync = B_TRUE;
5508 * Check for any removed devices.
5510 if (spa->spa_autoreplace) {
5511 spa_aux_check_removed(&spa->spa_spares);
5512 spa_aux_check_removed(&spa->spa_l2cache);
5515 if (spa_writeable(spa)) {
5517 * Update the config cache to include the newly-imported pool.
5519 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5523 * It's possible that the pool was expanded while it was exported.
5524 * We kick off an async task to handle this for us.
5526 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5528 spa_history_log_version(spa, "import");
5530 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5532 mutex_exit(&spa_namespace_lock);
5536 zvol_create_minors(pool);
5543 spa_tryimport(nvlist_t *tryconfig)
5545 nvlist_t *config = NULL;
5546 char *poolname, *cachefile;
5550 zpool_load_policy_t policy;
5552 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5555 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5559 * Create and initialize the spa structure.
5561 mutex_enter(&spa_namespace_lock);
5562 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
5563 spa_activate(spa, FREAD);
5566 * Rewind pool if a max txg was provided.
5568 zpool_get_load_policy(spa->spa_config, &policy);
5569 if (policy.zlp_txg != UINT64_MAX) {
5570 spa->spa_load_max_txg = policy.zlp_txg;
5571 spa->spa_extreme_rewind = B_TRUE;
5572 zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
5573 poolname, (longlong_t)policy.zlp_txg);
5575 zfs_dbgmsg("spa_tryimport: importing %s", poolname);
5578 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
5580 zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
5581 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5583 spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
5586 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
5589 * If 'tryconfig' was at least parsable, return the current config.
5591 if (spa->spa_root_vdev != NULL) {
5592 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5593 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
5595 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5597 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
5598 spa->spa_uberblock.ub_timestamp) == 0);
5599 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5600 spa->spa_load_info) == 0);
5603 * If the bootfs property exists on this pool then we
5604 * copy it out so that external consumers can tell which
5605 * pools are bootable.
5607 if ((!error || error == EEXIST) && spa->spa_bootfs) {
5608 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5611 * We have to play games with the name since the
5612 * pool was opened as TRYIMPORT_NAME.
5614 if (dsl_dsobj_to_dsname(spa_name(spa),
5615 spa->spa_bootfs, tmpname) == 0) {
5617 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5619 cp = strchr(tmpname, '/');
5621 (void) strlcpy(dsname, tmpname,
5624 (void) snprintf(dsname, MAXPATHLEN,
5625 "%s/%s", poolname, ++cp);
5627 VERIFY(nvlist_add_string(config,
5628 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
5629 kmem_free(dsname, MAXPATHLEN);
5631 kmem_free(tmpname, MAXPATHLEN);
5635 * Add the list of hot spares and level 2 cache devices.
5637 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5638 spa_add_spares(spa, config);
5639 spa_add_l2cache(spa, config);
5640 spa_config_exit(spa, SCL_CONFIG, FTAG);
5644 spa_deactivate(spa);
5646 mutex_exit(&spa_namespace_lock);
5652 * Pool export/destroy
5654 * The act of destroying or exporting a pool is very simple. We make sure there
5655 * is no more pending I/O and any references to the pool are gone. Then, we
5656 * update the pool state and sync all the labels to disk, removing the
5657 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
5658 * we don't sync the labels or remove the configuration cache.
5661 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
5662 boolean_t force, boolean_t hardforce)
5669 if (!(spa_mode_global & FWRITE))
5670 return (SET_ERROR(EROFS));
5672 mutex_enter(&spa_namespace_lock);
5673 if ((spa = spa_lookup(pool)) == NULL) {
5674 mutex_exit(&spa_namespace_lock);
5675 return (SET_ERROR(ENOENT));
5679 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5680 * reacquire the namespace lock, and see if we can export.
5682 spa_open_ref(spa, FTAG);
5683 mutex_exit(&spa_namespace_lock);
5684 spa_async_suspend(spa);
5685 mutex_enter(&spa_namespace_lock);
5686 spa_close(spa, FTAG);
5689 * The pool will be in core if it's openable,
5690 * in which case we can modify its state.
5692 if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
5695 * Objsets may be open only because they're dirty, so we
5696 * have to force it to sync before checking spa_refcnt.
5698 txg_wait_synced(spa->spa_dsl_pool, 0);
5699 spa_evicting_os_wait(spa);
5702 * A pool cannot be exported or destroyed if there are active
5703 * references. If we are resetting a pool, allow references by
5704 * fault injection handlers.
5706 if (!spa_refcount_zero(spa) ||
5707 (spa->spa_inject_ref != 0 &&
5708 new_state != POOL_STATE_UNINITIALIZED)) {
5709 spa_async_resume(spa);
5710 mutex_exit(&spa_namespace_lock);
5711 return (SET_ERROR(EBUSY));
5715 * A pool cannot be exported if it has an active shared spare.
5716 * This is to prevent other pools stealing the active spare
5717 * from an exported pool. At user's own will, such pool can
5718 * be forcedly exported.
5720 if (!force && new_state == POOL_STATE_EXPORTED &&
5721 spa_has_active_shared_spare(spa)) {
5722 spa_async_resume(spa);
5723 mutex_exit(&spa_namespace_lock);
5724 return (SET_ERROR(EXDEV));
5728 * We're about to export or destroy this pool. Make sure
5729 * we stop all initializtion activity here before we
5730 * set the spa_final_txg. This will ensure that all
5731 * dirty data resulting from the initialization is
5732 * committed to disk before we unload the pool.
5734 if (spa->spa_root_vdev != NULL) {
5735 vdev_initialize_stop_all(spa->spa_root_vdev,
5736 VDEV_INITIALIZE_ACTIVE);
5740 * We want this to be reflected on every label,
5741 * so mark them all dirty. spa_unload() will do the
5742 * final sync that pushes these changes out.
5744 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
5745 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5746 spa->spa_state = new_state;
5747 spa->spa_final_txg = spa_last_synced_txg(spa) +
5749 vdev_config_dirty(spa->spa_root_vdev);
5750 spa_config_exit(spa, SCL_ALL, FTAG);
5754 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
5756 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
5758 spa_deactivate(spa);
5761 if (oldconfig && spa->spa_config)
5762 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
5764 if (new_state != POOL_STATE_UNINITIALIZED) {
5766 spa_write_cachefile(spa, B_TRUE, B_TRUE);
5769 mutex_exit(&spa_namespace_lock);
5775 * Destroy a storage pool.
5778 spa_destroy(char *pool)
5780 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
5785 * Export a storage pool.
5788 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
5789 boolean_t hardforce)
5791 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
5796 * Similar to spa_export(), this unloads the spa_t without actually removing it
5797 * from the namespace in any way.
5800 spa_reset(char *pool)
5802 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
5807 * ==========================================================================
5808 * Device manipulation
5809 * ==========================================================================
5813 * Add a device to a storage pool.
5816 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
5820 vdev_t *rvd = spa->spa_root_vdev;
5822 nvlist_t **spares, **l2cache;
5823 uint_t nspares, nl2cache;
5825 ASSERT(spa_writeable(spa));
5827 txg = spa_vdev_enter(spa);
5829 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
5830 VDEV_ALLOC_ADD)) != 0)
5831 return (spa_vdev_exit(spa, NULL, txg, error));
5833 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
5835 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
5839 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
5843 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
5844 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5846 if (vd->vdev_children != 0 &&
5847 (error = vdev_create(vd, txg, B_FALSE)) != 0)
5848 return (spa_vdev_exit(spa, vd, txg, error));
5851 * We must validate the spares and l2cache devices after checking the
5852 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
5854 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
5855 return (spa_vdev_exit(spa, vd, txg, error));
5858 * If we are in the middle of a device removal, we can only add
5859 * devices which match the existing devices in the pool.
5860 * If we are in the middle of a removal, or have some indirect
5861 * vdevs, we can not add raidz toplevels.
5863 if (spa->spa_vdev_removal != NULL ||
5864 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
5865 for (int c = 0; c < vd->vdev_children; c++) {
5866 tvd = vd->vdev_child[c];
5867 if (spa->spa_vdev_removal != NULL &&
5868 tvd->vdev_ashift != spa->spa_max_ashift) {
5869 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5871 /* Fail if top level vdev is raidz */
5872 if (tvd->vdev_ops == &vdev_raidz_ops) {
5873 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5876 * Need the top level mirror to be
5877 * a mirror of leaf vdevs only
5879 if (tvd->vdev_ops == &vdev_mirror_ops) {
5880 for (uint64_t cid = 0;
5881 cid < tvd->vdev_children; cid++) {
5882 vdev_t *cvd = tvd->vdev_child[cid];
5883 if (!cvd->vdev_ops->vdev_op_leaf) {
5884 return (spa_vdev_exit(spa, vd,
5892 for (int c = 0; c < vd->vdev_children; c++) {
5895 * Set the vdev id to the first hole, if one exists.
5897 for (id = 0; id < rvd->vdev_children; id++) {
5898 if (rvd->vdev_child[id]->vdev_ishole) {
5899 vdev_free(rvd->vdev_child[id]);
5903 tvd = vd->vdev_child[c];
5904 vdev_remove_child(vd, tvd);
5906 vdev_add_child(rvd, tvd);
5907 vdev_config_dirty(tvd);
5911 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
5912 ZPOOL_CONFIG_SPARES);
5913 spa_load_spares(spa);
5914 spa->spa_spares.sav_sync = B_TRUE;
5917 if (nl2cache != 0) {
5918 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
5919 ZPOOL_CONFIG_L2CACHE);
5920 spa_load_l2cache(spa);
5921 spa->spa_l2cache.sav_sync = B_TRUE;
5925 * We have to be careful when adding new vdevs to an existing pool.
5926 * If other threads start allocating from these vdevs before we
5927 * sync the config cache, and we lose power, then upon reboot we may
5928 * fail to open the pool because there are DVAs that the config cache
5929 * can't translate. Therefore, we first add the vdevs without
5930 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
5931 * and then let spa_config_update() initialize the new metaslabs.
5933 * spa_load() checks for added-but-not-initialized vdevs, so that
5934 * if we lose power at any point in this sequence, the remaining
5935 * steps will be completed the next time we load the pool.
5937 (void) spa_vdev_exit(spa, vd, txg, 0);
5939 mutex_enter(&spa_namespace_lock);
5940 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5941 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
5942 mutex_exit(&spa_namespace_lock);
5948 * Attach a device to a mirror. The arguments are the path to any device
5949 * in the mirror, and the nvroot for the new device. If the path specifies
5950 * a device that is not mirrored, we automatically insert the mirror vdev.
5952 * If 'replacing' is specified, the new device is intended to replace the
5953 * existing device; in this case the two devices are made into their own
5954 * mirror using the 'replacing' vdev, which is functionally identical to
5955 * the mirror vdev (it actually reuses all the same ops) but has a few
5956 * extra rules: you can't attach to it after it's been created, and upon
5957 * completion of resilvering, the first disk (the one being replaced)
5958 * is automatically detached.
5961 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
5963 uint64_t txg, dtl_max_txg;
5964 vdev_t *rvd = spa->spa_root_vdev;
5965 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
5967 char *oldvdpath, *newvdpath;
5971 ASSERT(spa_writeable(spa));
5973 txg = spa_vdev_enter(spa);
5975 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
5977 ASSERT(MUTEX_HELD(&spa_namespace_lock));
5978 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
5979 error = (spa_has_checkpoint(spa)) ?
5980 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
5981 return (spa_vdev_exit(spa, NULL, txg, error));
5984 if (spa->spa_vdev_removal != NULL)
5985 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5988 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5990 if (!oldvd->vdev_ops->vdev_op_leaf)
5991 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5993 pvd = oldvd->vdev_parent;
5995 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
5996 VDEV_ALLOC_ATTACH)) != 0)
5997 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5999 if (newrootvd->vdev_children != 1)
6000 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6002 newvd = newrootvd->vdev_child[0];
6004 if (!newvd->vdev_ops->vdev_op_leaf)
6005 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6007 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
6008 return (spa_vdev_exit(spa, newrootvd, txg, error));
6011 * Spares can't replace logs
6013 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
6014 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6018 * For attach, the only allowable parent is a mirror or the root
6021 if (pvd->vdev_ops != &vdev_mirror_ops &&
6022 pvd->vdev_ops != &vdev_root_ops)
6023 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6025 pvops = &vdev_mirror_ops;
6028 * Active hot spares can only be replaced by inactive hot
6031 if (pvd->vdev_ops == &vdev_spare_ops &&
6032 oldvd->vdev_isspare &&
6033 !spa_has_spare(spa, newvd->vdev_guid))
6034 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6037 * If the source is a hot spare, and the parent isn't already a
6038 * spare, then we want to create a new hot spare. Otherwise, we
6039 * want to create a replacing vdev. The user is not allowed to
6040 * attach to a spared vdev child unless the 'isspare' state is
6041 * the same (spare replaces spare, non-spare replaces
6044 if (pvd->vdev_ops == &vdev_replacing_ops &&
6045 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6046 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6047 } else if (pvd->vdev_ops == &vdev_spare_ops &&
6048 newvd->vdev_isspare != oldvd->vdev_isspare) {
6049 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6052 if (newvd->vdev_isspare)
6053 pvops = &vdev_spare_ops;
6055 pvops = &vdev_replacing_ops;
6059 * Make sure the new device is big enough.
6061 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6062 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6065 * The new device cannot have a higher alignment requirement
6066 * than the top-level vdev.
6068 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6069 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6072 * If this is an in-place replacement, update oldvd's path and devid
6073 * to make it distinguishable from newvd, and unopenable from now on.
6075 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6076 spa_strfree(oldvd->vdev_path);
6077 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6079 (void) sprintf(oldvd->vdev_path, "%s/%s",
6080 newvd->vdev_path, "old");
6081 if (oldvd->vdev_devid != NULL) {
6082 spa_strfree(oldvd->vdev_devid);
6083 oldvd->vdev_devid = NULL;
6087 /* mark the device being resilvered */
6088 newvd->vdev_resilver_txg = txg;
6091 * If the parent is not a mirror, or if we're replacing, insert the new
6092 * mirror/replacing/spare vdev above oldvd.
6094 if (pvd->vdev_ops != pvops)
6095 pvd = vdev_add_parent(oldvd, pvops);
6097 ASSERT(pvd->vdev_top->vdev_parent == rvd);
6098 ASSERT(pvd->vdev_ops == pvops);
6099 ASSERT(oldvd->vdev_parent == pvd);
6102 * Extract the new device from its root and add it to pvd.
6104 vdev_remove_child(newrootvd, newvd);
6105 newvd->vdev_id = pvd->vdev_children;
6106 newvd->vdev_crtxg = oldvd->vdev_crtxg;
6107 vdev_add_child(pvd, newvd);
6109 tvd = newvd->vdev_top;
6110 ASSERT(pvd->vdev_top == tvd);
6111 ASSERT(tvd->vdev_parent == rvd);
6113 vdev_config_dirty(tvd);
6116 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6117 * for any dmu_sync-ed blocks. It will propagate upward when
6118 * spa_vdev_exit() calls vdev_dtl_reassess().
6120 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6122 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6123 dtl_max_txg - TXG_INITIAL);
6125 if (newvd->vdev_isspare) {
6126 spa_spare_activate(newvd);
6127 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6130 oldvdpath = spa_strdup(oldvd->vdev_path);
6131 newvdpath = spa_strdup(newvd->vdev_path);
6132 newvd_isspare = newvd->vdev_isspare;
6135 * Mark newvd's DTL dirty in this txg.
6137 vdev_dirty(tvd, VDD_DTL, newvd, txg);
6140 * Schedule the resilver to restart in the future. We do this to
6141 * ensure that dmu_sync-ed blocks have been stitched into the
6142 * respective datasets.
6144 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
6146 if (spa->spa_bootfs)
6147 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6149 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6154 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6156 spa_history_log_internal(spa, "vdev attach", NULL,
6157 "%s vdev=%s %s vdev=%s",
6158 replacing && newvd_isspare ? "spare in" :
6159 replacing ? "replace" : "attach", newvdpath,
6160 replacing ? "for" : "to", oldvdpath);
6162 spa_strfree(oldvdpath);
6163 spa_strfree(newvdpath);
6169 * Detach a device from a mirror or replacing vdev.
6171 * If 'replace_done' is specified, only detach if the parent
6172 * is a replacing vdev.
6175 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6179 vdev_t *rvd = spa->spa_root_vdev;
6180 vdev_t *vd, *pvd, *cvd, *tvd;
6181 boolean_t unspare = B_FALSE;
6182 uint64_t unspare_guid = 0;
6185 ASSERT(spa_writeable(spa));
6187 txg = spa_vdev_enter(spa);
6189 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6192 * Besides being called directly from the userland through the
6193 * ioctl interface, spa_vdev_detach() can be potentially called
6194 * at the end of spa_vdev_resilver_done().
6196 * In the regular case, when we have a checkpoint this shouldn't
6197 * happen as we never empty the DTLs of a vdev during the scrub
6198 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6199 * should never get here when we have a checkpoint.
6201 * That said, even in a case when we checkpoint the pool exactly
6202 * as spa_vdev_resilver_done() calls this function everything
6203 * should be fine as the resilver will return right away.
6205 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6206 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6207 error = (spa_has_checkpoint(spa)) ?
6208 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6209 return (spa_vdev_exit(spa, NULL, txg, error));
6213 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6215 if (!vd->vdev_ops->vdev_op_leaf)
6216 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6218 pvd = vd->vdev_parent;
6221 * If the parent/child relationship is not as expected, don't do it.
6222 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6223 * vdev that's replacing B with C. The user's intent in replacing
6224 * is to go from M(A,B) to M(A,C). If the user decides to cancel
6225 * the replace by detaching C, the expected behavior is to end up
6226 * M(A,B). But suppose that right after deciding to detach C,
6227 * the replacement of B completes. We would have M(A,C), and then
6228 * ask to detach C, which would leave us with just A -- not what
6229 * the user wanted. To prevent this, we make sure that the
6230 * parent/child relationship hasn't changed -- in this example,
6231 * that C's parent is still the replacing vdev R.
6233 if (pvd->vdev_guid != pguid && pguid != 0)
6234 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6237 * Only 'replacing' or 'spare' vdevs can be replaced.
6239 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6240 pvd->vdev_ops != &vdev_spare_ops)
6241 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6243 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6244 spa_version(spa) >= SPA_VERSION_SPARES);
6247 * Only mirror, replacing, and spare vdevs support detach.
6249 if (pvd->vdev_ops != &vdev_replacing_ops &&
6250 pvd->vdev_ops != &vdev_mirror_ops &&
6251 pvd->vdev_ops != &vdev_spare_ops)
6252 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6255 * If this device has the only valid copy of some data,
6256 * we cannot safely detach it.
6258 if (vdev_dtl_required(vd))
6259 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6261 ASSERT(pvd->vdev_children >= 2);
6264 * If we are detaching the second disk from a replacing vdev, then
6265 * check to see if we changed the original vdev's path to have "/old"
6266 * at the end in spa_vdev_attach(). If so, undo that change now.
6268 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
6269 vd->vdev_path != NULL) {
6270 size_t len = strlen(vd->vdev_path);
6272 for (int c = 0; c < pvd->vdev_children; c++) {
6273 cvd = pvd->vdev_child[c];
6275 if (cvd == vd || cvd->vdev_path == NULL)
6278 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
6279 strcmp(cvd->vdev_path + len, "/old") == 0) {
6280 spa_strfree(cvd->vdev_path);
6281 cvd->vdev_path = spa_strdup(vd->vdev_path);
6288 * If we are detaching the original disk from a spare, then it implies
6289 * that the spare should become a real disk, and be removed from the
6290 * active spare list for the pool.
6292 if (pvd->vdev_ops == &vdev_spare_ops &&
6294 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
6298 * Erase the disk labels so the disk can be used for other things.
6299 * This must be done after all other error cases are handled,
6300 * but before we disembowel vd (so we can still do I/O to it).
6301 * But if we can't do it, don't treat the error as fatal --
6302 * it may be that the unwritability of the disk is the reason
6303 * it's being detached!
6305 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
6308 * Remove vd from its parent and compact the parent's children.
6310 vdev_remove_child(pvd, vd);
6311 vdev_compact_children(pvd);
6314 * Remember one of the remaining children so we can get tvd below.
6316 cvd = pvd->vdev_child[pvd->vdev_children - 1];
6319 * If we need to remove the remaining child from the list of hot spares,
6320 * do it now, marking the vdev as no longer a spare in the process.
6321 * We must do this before vdev_remove_parent(), because that can
6322 * change the GUID if it creates a new toplevel GUID. For a similar
6323 * reason, we must remove the spare now, in the same txg as the detach;
6324 * otherwise someone could attach a new sibling, change the GUID, and
6325 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
6328 ASSERT(cvd->vdev_isspare);
6329 spa_spare_remove(cvd);
6330 unspare_guid = cvd->vdev_guid;
6331 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
6332 cvd->vdev_unspare = B_TRUE;
6336 * If the parent mirror/replacing vdev only has one child,
6337 * the parent is no longer needed. Remove it from the tree.
6339 if (pvd->vdev_children == 1) {
6340 if (pvd->vdev_ops == &vdev_spare_ops)
6341 cvd->vdev_unspare = B_FALSE;
6342 vdev_remove_parent(cvd);
6347 * We don't set tvd until now because the parent we just removed
6348 * may have been the previous top-level vdev.
6350 tvd = cvd->vdev_top;
6351 ASSERT(tvd->vdev_parent == rvd);
6354 * Reevaluate the parent vdev state.
6356 vdev_propagate_state(cvd);
6359 * If the 'autoexpand' property is set on the pool then automatically
6360 * try to expand the size of the pool. For example if the device we
6361 * just detached was smaller than the others, it may be possible to
6362 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
6363 * first so that we can obtain the updated sizes of the leaf vdevs.
6365 if (spa->spa_autoexpand) {
6367 vdev_expand(tvd, txg);
6370 vdev_config_dirty(tvd);
6373 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
6374 * vd->vdev_detached is set and free vd's DTL object in syncing context.
6375 * But first make sure we're not on any *other* txg's DTL list, to
6376 * prevent vd from being accessed after it's freed.
6378 vdpath = spa_strdup(vd->vdev_path);
6379 for (int t = 0; t < TXG_SIZE; t++)
6380 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
6381 vd->vdev_detached = B_TRUE;
6382 vdev_dirty(tvd, VDD_DTL, vd, txg);
6384 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
6386 /* hang on to the spa before we release the lock */
6387 spa_open_ref(spa, FTAG);
6389 error = spa_vdev_exit(spa, vd, txg, 0);
6391 spa_history_log_internal(spa, "detach", NULL,
6393 spa_strfree(vdpath);
6396 * If this was the removal of the original device in a hot spare vdev,
6397 * then we want to go through and remove the device from the hot spare
6398 * list of every other pool.
6401 spa_t *altspa = NULL;
6403 mutex_enter(&spa_namespace_lock);
6404 while ((altspa = spa_next(altspa)) != NULL) {
6405 if (altspa->spa_state != POOL_STATE_ACTIVE ||
6409 spa_open_ref(altspa, FTAG);
6410 mutex_exit(&spa_namespace_lock);
6411 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
6412 mutex_enter(&spa_namespace_lock);
6413 spa_close(altspa, FTAG);
6415 mutex_exit(&spa_namespace_lock);
6417 /* search the rest of the vdevs for spares to remove */
6418 spa_vdev_resilver_done(spa);
6421 /* all done with the spa; OK to release */
6422 mutex_enter(&spa_namespace_lock);
6423 spa_close(spa, FTAG);
6424 mutex_exit(&spa_namespace_lock);
6430 spa_vdev_initialize(spa_t *spa, uint64_t guid, uint64_t cmd_type)
6433 * We hold the namespace lock through the whole function
6434 * to prevent any changes to the pool while we're starting or
6435 * stopping initialization. The config and state locks are held so that
6436 * we can properly assess the vdev state before we commit to
6437 * the initializing operation.
6439 mutex_enter(&spa_namespace_lock);
6440 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6442 /* Look up vdev and ensure it's a leaf. */
6443 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6444 if (vd == NULL || vd->vdev_detached) {
6445 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6446 mutex_exit(&spa_namespace_lock);
6447 return (SET_ERROR(ENODEV));
6448 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6449 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6450 mutex_exit(&spa_namespace_lock);
6451 return (SET_ERROR(EINVAL));
6452 } else if (!vdev_writeable(vd)) {
6453 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6454 mutex_exit(&spa_namespace_lock);
6455 return (SET_ERROR(EROFS));
6457 mutex_enter(&vd->vdev_initialize_lock);
6458 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6461 * When we activate an initialize action we check to see
6462 * if the vdev_initialize_thread is NULL. We do this instead
6463 * of using the vdev_initialize_state since there might be
6464 * a previous initialization process which has completed but
6465 * the thread is not exited.
6467 if (cmd_type == POOL_INITIALIZE_DO &&
6468 (vd->vdev_initialize_thread != NULL ||
6469 vd->vdev_top->vdev_removing)) {
6470 mutex_exit(&vd->vdev_initialize_lock);
6471 mutex_exit(&spa_namespace_lock);
6472 return (SET_ERROR(EBUSY));
6473 } else if (cmd_type == POOL_INITIALIZE_CANCEL &&
6474 (vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE &&
6475 vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED)) {
6476 mutex_exit(&vd->vdev_initialize_lock);
6477 mutex_exit(&spa_namespace_lock);
6478 return (SET_ERROR(ESRCH));
6479 } else if (cmd_type == POOL_INITIALIZE_SUSPEND &&
6480 vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE) {
6481 mutex_exit(&vd->vdev_initialize_lock);
6482 mutex_exit(&spa_namespace_lock);
6483 return (SET_ERROR(ESRCH));
6487 case POOL_INITIALIZE_DO:
6488 vdev_initialize(vd);
6490 case POOL_INITIALIZE_CANCEL:
6491 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED);
6493 case POOL_INITIALIZE_SUSPEND:
6494 vdev_initialize_stop(vd, VDEV_INITIALIZE_SUSPENDED);
6497 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6499 mutex_exit(&vd->vdev_initialize_lock);
6501 /* Sync out the initializing state */
6502 txg_wait_synced(spa->spa_dsl_pool, 0);
6503 mutex_exit(&spa_namespace_lock);
6510 * Split a set of devices from their mirrors, and create a new pool from them.
6513 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6514 nvlist_t *props, boolean_t exp)
6517 uint64_t txg, *glist;
6519 uint_t c, children, lastlog;
6520 nvlist_t **child, *nvl, *tmp;
6522 char *altroot = NULL;
6523 vdev_t *rvd, **vml = NULL; /* vdev modify list */
6524 boolean_t activate_slog;
6526 ASSERT(spa_writeable(spa));
6528 txg = spa_vdev_enter(spa);
6530 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6531 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6532 error = (spa_has_checkpoint(spa)) ?
6533 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6534 return (spa_vdev_exit(spa, NULL, txg, error));
6537 /* clear the log and flush everything up to now */
6538 activate_slog = spa_passivate_log(spa);
6539 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6540 error = spa_reset_logs(spa);
6541 txg = spa_vdev_config_enter(spa);
6544 spa_activate_log(spa);
6547 return (spa_vdev_exit(spa, NULL, txg, error));
6549 /* check new spa name before going any further */
6550 if (spa_lookup(newname) != NULL)
6551 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
6554 * scan through all the children to ensure they're all mirrors
6556 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
6557 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
6559 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6561 /* first, check to ensure we've got the right child count */
6562 rvd = spa->spa_root_vdev;
6564 for (c = 0; c < rvd->vdev_children; c++) {
6565 vdev_t *vd = rvd->vdev_child[c];
6567 /* don't count the holes & logs as children */
6568 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
6576 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
6577 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6579 /* next, ensure no spare or cache devices are part of the split */
6580 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
6581 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
6582 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6584 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
6585 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
6587 /* then, loop over each vdev and validate it */
6588 for (c = 0; c < children; c++) {
6589 uint64_t is_hole = 0;
6591 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
6595 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
6596 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
6599 error = SET_ERROR(EINVAL);
6604 /* which disk is going to be split? */
6605 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
6607 error = SET_ERROR(EINVAL);
6611 /* look it up in the spa */
6612 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
6613 if (vml[c] == NULL) {
6614 error = SET_ERROR(ENODEV);
6618 /* make sure there's nothing stopping the split */
6619 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
6620 vml[c]->vdev_islog ||
6621 !vdev_is_concrete(vml[c]) ||
6622 vml[c]->vdev_isspare ||
6623 vml[c]->vdev_isl2cache ||
6624 !vdev_writeable(vml[c]) ||
6625 vml[c]->vdev_children != 0 ||
6626 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
6627 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
6628 error = SET_ERROR(EINVAL);
6632 if (vdev_dtl_required(vml[c])) {
6633 error = SET_ERROR(EBUSY);
6637 /* we need certain info from the top level */
6638 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
6639 vml[c]->vdev_top->vdev_ms_array) == 0);
6640 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
6641 vml[c]->vdev_top->vdev_ms_shift) == 0);
6642 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
6643 vml[c]->vdev_top->vdev_asize) == 0);
6644 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
6645 vml[c]->vdev_top->vdev_ashift) == 0);
6647 /* transfer per-vdev ZAPs */
6648 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
6649 VERIFY0(nvlist_add_uint64(child[c],
6650 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
6652 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
6653 VERIFY0(nvlist_add_uint64(child[c],
6654 ZPOOL_CONFIG_VDEV_TOP_ZAP,
6655 vml[c]->vdev_parent->vdev_top_zap));
6659 kmem_free(vml, children * sizeof (vdev_t *));
6660 kmem_free(glist, children * sizeof (uint64_t));
6661 return (spa_vdev_exit(spa, NULL, txg, error));
6664 /* stop writers from using the disks */
6665 for (c = 0; c < children; c++) {
6667 vml[c]->vdev_offline = B_TRUE;
6669 vdev_reopen(spa->spa_root_vdev);
6672 * Temporarily record the splitting vdevs in the spa config. This
6673 * will disappear once the config is regenerated.
6675 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6676 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
6677 glist, children) == 0);
6678 kmem_free(glist, children * sizeof (uint64_t));
6680 mutex_enter(&spa->spa_props_lock);
6681 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
6683 mutex_exit(&spa->spa_props_lock);
6684 spa->spa_config_splitting = nvl;
6685 vdev_config_dirty(spa->spa_root_vdev);
6687 /* configure and create the new pool */
6688 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
6689 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6690 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
6691 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6692 spa_version(spa)) == 0);
6693 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
6694 spa->spa_config_txg) == 0);
6695 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
6696 spa_generate_guid(NULL)) == 0);
6697 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
6698 (void) nvlist_lookup_string(props,
6699 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
6701 /* add the new pool to the namespace */
6702 newspa = spa_add(newname, config, altroot);
6703 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
6704 newspa->spa_config_txg = spa->spa_config_txg;
6705 spa_set_log_state(newspa, SPA_LOG_CLEAR);
6707 /* release the spa config lock, retaining the namespace lock */
6708 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6710 if (zio_injection_enabled)
6711 zio_handle_panic_injection(spa, FTAG, 1);
6713 spa_activate(newspa, spa_mode_global);
6714 spa_async_suspend(newspa);
6716 for (c = 0; c < children; c++) {
6717 if (vml[c] != NULL) {
6719 * Temporarily stop the initializing activity. We set
6720 * the state to ACTIVE so that we know to resume
6721 * the initializing once the split has completed.
6723 mutex_enter(&vml[c]->vdev_initialize_lock);
6724 vdev_initialize_stop(vml[c], VDEV_INITIALIZE_ACTIVE);
6725 mutex_exit(&vml[c]->vdev_initialize_lock);
6730 /* mark that we are creating new spa by splitting */
6731 newspa->spa_splitting_newspa = B_TRUE;
6733 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
6735 /* create the new pool from the disks of the original pool */
6736 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
6738 newspa->spa_splitting_newspa = B_FALSE;
6743 /* if that worked, generate a real config for the new pool */
6744 if (newspa->spa_root_vdev != NULL) {
6745 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
6746 NV_UNIQUE_NAME, KM_SLEEP) == 0);
6747 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
6748 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
6749 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
6754 if (props != NULL) {
6755 spa_configfile_set(newspa, props, B_FALSE);
6756 error = spa_prop_set(newspa, props);
6761 /* flush everything */
6762 txg = spa_vdev_config_enter(newspa);
6763 vdev_config_dirty(newspa->spa_root_vdev);
6764 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
6766 if (zio_injection_enabled)
6767 zio_handle_panic_injection(spa, FTAG, 2);
6769 spa_async_resume(newspa);
6771 /* finally, update the original pool's config */
6772 txg = spa_vdev_config_enter(spa);
6773 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
6774 error = dmu_tx_assign(tx, TXG_WAIT);
6777 for (c = 0; c < children; c++) {
6778 if (vml[c] != NULL) {
6781 spa_history_log_internal(spa, "detach", tx,
6782 "vdev=%s", vml[c]->vdev_path);
6787 spa->spa_avz_action = AVZ_ACTION_REBUILD;
6788 vdev_config_dirty(spa->spa_root_vdev);
6789 spa->spa_config_splitting = NULL;
6793 (void) spa_vdev_exit(spa, NULL, txg, 0);
6795 if (zio_injection_enabled)
6796 zio_handle_panic_injection(spa, FTAG, 3);
6798 /* split is complete; log a history record */
6799 spa_history_log_internal(newspa, "split", NULL,
6800 "from pool %s", spa_name(spa));
6802 kmem_free(vml, children * sizeof (vdev_t *));
6804 /* if we're not going to mount the filesystems in userland, export */
6806 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
6813 spa_deactivate(newspa);
6816 txg = spa_vdev_config_enter(spa);
6818 /* re-online all offlined disks */
6819 for (c = 0; c < children; c++) {
6821 vml[c]->vdev_offline = B_FALSE;
6824 /* restart initializing disks as necessary */
6825 spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
6827 vdev_reopen(spa->spa_root_vdev);
6829 nvlist_free(spa->spa_config_splitting);
6830 spa->spa_config_splitting = NULL;
6831 (void) spa_vdev_exit(spa, NULL, txg, error);
6833 kmem_free(vml, children * sizeof (vdev_t *));
6838 * Find any device that's done replacing, or a vdev marked 'unspare' that's
6839 * currently spared, so we can detach it.
6842 spa_vdev_resilver_done_hunt(vdev_t *vd)
6844 vdev_t *newvd, *oldvd;
6846 for (int c = 0; c < vd->vdev_children; c++) {
6847 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
6853 * Check for a completed replacement. We always consider the first
6854 * vdev in the list to be the oldest vdev, and the last one to be
6855 * the newest (see spa_vdev_attach() for how that works). In
6856 * the case where the newest vdev is faulted, we will not automatically
6857 * remove it after a resilver completes. This is OK as it will require
6858 * user intervention to determine which disk the admin wishes to keep.
6860 if (vd->vdev_ops == &vdev_replacing_ops) {
6861 ASSERT(vd->vdev_children > 1);
6863 newvd = vd->vdev_child[vd->vdev_children - 1];
6864 oldvd = vd->vdev_child[0];
6866 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
6867 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6868 !vdev_dtl_required(oldvd))
6873 * Check for a completed resilver with the 'unspare' flag set.
6875 if (vd->vdev_ops == &vdev_spare_ops) {
6876 vdev_t *first = vd->vdev_child[0];
6877 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
6879 if (last->vdev_unspare) {
6882 } else if (first->vdev_unspare) {
6889 if (oldvd != NULL &&
6890 vdev_dtl_empty(newvd, DTL_MISSING) &&
6891 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6892 !vdev_dtl_required(oldvd))
6896 * If there are more than two spares attached to a disk,
6897 * and those spares are not required, then we want to
6898 * attempt to free them up now so that they can be used
6899 * by other pools. Once we're back down to a single
6900 * disk+spare, we stop removing them.
6902 if (vd->vdev_children > 2) {
6903 newvd = vd->vdev_child[1];
6905 if (newvd->vdev_isspare && last->vdev_isspare &&
6906 vdev_dtl_empty(last, DTL_MISSING) &&
6907 vdev_dtl_empty(last, DTL_OUTAGE) &&
6908 !vdev_dtl_required(newvd))
6917 spa_vdev_resilver_done(spa_t *spa)
6919 vdev_t *vd, *pvd, *ppvd;
6920 uint64_t guid, sguid, pguid, ppguid;
6922 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6924 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
6925 pvd = vd->vdev_parent;
6926 ppvd = pvd->vdev_parent;
6927 guid = vd->vdev_guid;
6928 pguid = pvd->vdev_guid;
6929 ppguid = ppvd->vdev_guid;
6932 * If we have just finished replacing a hot spared device, then
6933 * we need to detach the parent's first child (the original hot
6936 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
6937 ppvd->vdev_children == 2) {
6938 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
6939 sguid = ppvd->vdev_child[1]->vdev_guid;
6941 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
6943 spa_config_exit(spa, SCL_ALL, FTAG);
6944 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
6946 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
6948 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6951 spa_config_exit(spa, SCL_ALL, FTAG);
6955 * Update the stored path or FRU for this vdev.
6958 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
6962 boolean_t sync = B_FALSE;
6964 ASSERT(spa_writeable(spa));
6966 spa_vdev_state_enter(spa, SCL_ALL);
6968 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
6969 return (spa_vdev_state_exit(spa, NULL, ENOENT));
6971 if (!vd->vdev_ops->vdev_op_leaf)
6972 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
6975 if (strcmp(value, vd->vdev_path) != 0) {
6976 spa_strfree(vd->vdev_path);
6977 vd->vdev_path = spa_strdup(value);
6981 if (vd->vdev_fru == NULL) {
6982 vd->vdev_fru = spa_strdup(value);
6984 } else if (strcmp(value, vd->vdev_fru) != 0) {
6985 spa_strfree(vd->vdev_fru);
6986 vd->vdev_fru = spa_strdup(value);
6991 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
6995 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
6997 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
7001 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
7003 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
7007 * ==========================================================================
7009 * ==========================================================================
7012 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
7014 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7016 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7017 return (SET_ERROR(EBUSY));
7019 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
7023 spa_scan_stop(spa_t *spa)
7025 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7026 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7027 return (SET_ERROR(EBUSY));
7028 return (dsl_scan_cancel(spa->spa_dsl_pool));
7032 spa_scan(spa_t *spa, pool_scan_func_t func)
7034 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7036 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
7037 return (SET_ERROR(ENOTSUP));
7040 * If a resilver was requested, but there is no DTL on a
7041 * writeable leaf device, we have nothing to do.
7043 if (func == POOL_SCAN_RESILVER &&
7044 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
7045 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
7049 return (dsl_scan(spa->spa_dsl_pool, func));
7053 * ==========================================================================
7054 * SPA async task processing
7055 * ==========================================================================
7059 spa_async_remove(spa_t *spa, vdev_t *vd)
7061 if (vd->vdev_remove_wanted) {
7062 vd->vdev_remove_wanted = B_FALSE;
7063 vd->vdev_delayed_close = B_FALSE;
7064 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
7067 * We want to clear the stats, but we don't want to do a full
7068 * vdev_clear() as that will cause us to throw away
7069 * degraded/faulted state as well as attempt to reopen the
7070 * device, all of which is a waste.
7072 vd->vdev_stat.vs_read_errors = 0;
7073 vd->vdev_stat.vs_write_errors = 0;
7074 vd->vdev_stat.vs_checksum_errors = 0;
7076 vdev_state_dirty(vd->vdev_top);
7077 /* Tell userspace that the vdev is gone. */
7078 zfs_post_remove(spa, vd);
7081 for (int c = 0; c < vd->vdev_children; c++)
7082 spa_async_remove(spa, vd->vdev_child[c]);
7086 spa_async_probe(spa_t *spa, vdev_t *vd)
7088 if (vd->vdev_probe_wanted) {
7089 vd->vdev_probe_wanted = B_FALSE;
7090 vdev_reopen(vd); /* vdev_open() does the actual probe */
7093 for (int c = 0; c < vd->vdev_children; c++)
7094 spa_async_probe(spa, vd->vdev_child[c]);
7098 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
7104 if (!spa->spa_autoexpand)
7107 for (int c = 0; c < vd->vdev_children; c++) {
7108 vdev_t *cvd = vd->vdev_child[c];
7109 spa_async_autoexpand(spa, cvd);
7112 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
7115 physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
7116 (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
7118 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7119 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
7121 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
7122 ESC_ZFS_VDEV_AUTOEXPAND, attr, &eid, DDI_SLEEP);
7125 kmem_free(physpath, MAXPATHLEN);
7129 spa_async_thread(void *arg)
7131 spa_t *spa = (spa_t *)arg;
7134 ASSERT(spa->spa_sync_on);
7136 mutex_enter(&spa->spa_async_lock);
7137 tasks = spa->spa_async_tasks;
7138 spa->spa_async_tasks &= SPA_ASYNC_REMOVE;
7139 mutex_exit(&spa->spa_async_lock);
7142 * See if the config needs to be updated.
7144 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
7145 uint64_t old_space, new_space;
7147 mutex_enter(&spa_namespace_lock);
7148 old_space = metaslab_class_get_space(spa_normal_class(spa));
7149 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
7150 new_space = metaslab_class_get_space(spa_normal_class(spa));
7151 mutex_exit(&spa_namespace_lock);
7154 * If the pool grew as a result of the config update,
7155 * then log an internal history event.
7157 if (new_space != old_space) {
7158 spa_history_log_internal(spa, "vdev online", NULL,
7159 "pool '%s' size: %llu(+%llu)",
7160 spa_name(spa), new_space, new_space - old_space);
7164 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
7165 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7166 spa_async_autoexpand(spa, spa->spa_root_vdev);
7167 spa_config_exit(spa, SCL_CONFIG, FTAG);
7171 * See if any devices need to be probed.
7173 if (tasks & SPA_ASYNC_PROBE) {
7174 spa_vdev_state_enter(spa, SCL_NONE);
7175 spa_async_probe(spa, spa->spa_root_vdev);
7176 (void) spa_vdev_state_exit(spa, NULL, 0);
7180 * If any devices are done replacing, detach them.
7182 if (tasks & SPA_ASYNC_RESILVER_DONE)
7183 spa_vdev_resilver_done(spa);
7186 * Kick off a resilver.
7188 if (tasks & SPA_ASYNC_RESILVER)
7189 dsl_resilver_restart(spa->spa_dsl_pool, 0);
7191 if (tasks & SPA_ASYNC_INITIALIZE_RESTART) {
7192 mutex_enter(&spa_namespace_lock);
7193 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7194 vdev_initialize_restart(spa->spa_root_vdev);
7195 spa_config_exit(spa, SCL_CONFIG, FTAG);
7196 mutex_exit(&spa_namespace_lock);
7200 * Let the world know that we're done.
7202 mutex_enter(&spa->spa_async_lock);
7203 spa->spa_async_thread = NULL;
7204 cv_broadcast(&spa->spa_async_cv);
7205 mutex_exit(&spa->spa_async_lock);
7210 spa_async_thread_vd(void *arg)
7215 mutex_enter(&spa->spa_async_lock);
7216 tasks = spa->spa_async_tasks;
7218 spa->spa_async_tasks &= ~SPA_ASYNC_REMOVE;
7219 mutex_exit(&spa->spa_async_lock);
7222 * See if any devices need to be marked REMOVED.
7224 if (tasks & SPA_ASYNC_REMOVE) {
7225 spa_vdev_state_enter(spa, SCL_NONE);
7226 spa_async_remove(spa, spa->spa_root_vdev);
7227 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
7228 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
7229 for (int i = 0; i < spa->spa_spares.sav_count; i++)
7230 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
7231 (void) spa_vdev_state_exit(spa, NULL, 0);
7235 * Let the world know that we're done.
7237 mutex_enter(&spa->spa_async_lock);
7238 tasks = spa->spa_async_tasks;
7239 if ((tasks & SPA_ASYNC_REMOVE) != 0)
7241 spa->spa_async_thread_vd = NULL;
7242 cv_broadcast(&spa->spa_async_cv);
7243 mutex_exit(&spa->spa_async_lock);
7248 spa_async_suspend(spa_t *spa)
7250 mutex_enter(&spa->spa_async_lock);
7251 spa->spa_async_suspended++;
7252 while (spa->spa_async_thread != NULL ||
7253 spa->spa_async_thread_vd != NULL)
7254 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
7255 mutex_exit(&spa->spa_async_lock);
7257 spa_vdev_remove_suspend(spa);
7259 zthr_t *condense_thread = spa->spa_condense_zthr;
7260 if (condense_thread != NULL && zthr_isrunning(condense_thread))
7261 VERIFY0(zthr_cancel(condense_thread));
7263 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7264 if (discard_thread != NULL && zthr_isrunning(discard_thread))
7265 VERIFY0(zthr_cancel(discard_thread));
7269 spa_async_resume(spa_t *spa)
7271 mutex_enter(&spa->spa_async_lock);
7272 ASSERT(spa->spa_async_suspended != 0);
7273 spa->spa_async_suspended--;
7274 mutex_exit(&spa->spa_async_lock);
7275 spa_restart_removal(spa);
7277 zthr_t *condense_thread = spa->spa_condense_zthr;
7278 if (condense_thread != NULL && !zthr_isrunning(condense_thread))
7279 zthr_resume(condense_thread);
7281 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7282 if (discard_thread != NULL && !zthr_isrunning(discard_thread))
7283 zthr_resume(discard_thread);
7287 spa_async_tasks_pending(spa_t *spa)
7289 uint_t non_config_tasks;
7291 boolean_t config_task_suspended;
7293 non_config_tasks = spa->spa_async_tasks & ~(SPA_ASYNC_CONFIG_UPDATE |
7295 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
7296 if (spa->spa_ccw_fail_time == 0) {
7297 config_task_suspended = B_FALSE;
7299 config_task_suspended =
7300 (gethrtime() - spa->spa_ccw_fail_time) <
7301 (zfs_ccw_retry_interval * NANOSEC);
7304 return (non_config_tasks || (config_task && !config_task_suspended));
7308 spa_async_dispatch(spa_t *spa)
7310 mutex_enter(&spa->spa_async_lock);
7311 if (spa_async_tasks_pending(spa) &&
7312 !spa->spa_async_suspended &&
7313 spa->spa_async_thread == NULL &&
7315 spa->spa_async_thread = thread_create(NULL, 0,
7316 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
7317 mutex_exit(&spa->spa_async_lock);
7321 spa_async_dispatch_vd(spa_t *spa)
7323 mutex_enter(&spa->spa_async_lock);
7324 if ((spa->spa_async_tasks & SPA_ASYNC_REMOVE) != 0 &&
7325 !spa->spa_async_suspended &&
7326 spa->spa_async_thread_vd == NULL &&
7328 spa->spa_async_thread_vd = thread_create(NULL, 0,
7329 spa_async_thread_vd, spa, 0, &p0, TS_RUN, maxclsyspri);
7330 mutex_exit(&spa->spa_async_lock);
7334 spa_async_request(spa_t *spa, int task)
7336 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
7337 mutex_enter(&spa->spa_async_lock);
7338 spa->spa_async_tasks |= task;
7339 mutex_exit(&spa->spa_async_lock);
7340 spa_async_dispatch_vd(spa);
7344 * ==========================================================================
7345 * SPA syncing routines
7346 * ==========================================================================
7350 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7353 bpobj_enqueue(bpo, bp, tx);
7358 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7362 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
7363 BP_GET_PSIZE(bp), zio->io_flags));
7368 * Note: this simple function is not inlined to make it easier to dtrace the
7369 * amount of time spent syncing frees.
7372 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
7374 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7375 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
7376 VERIFY(zio_wait(zio) == 0);
7380 * Note: this simple function is not inlined to make it easier to dtrace the
7381 * amount of time spent syncing deferred frees.
7384 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
7386 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7387 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
7388 spa_free_sync_cb, zio, tx), ==, 0);
7389 VERIFY0(zio_wait(zio));
7394 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
7396 char *packed = NULL;
7401 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
7404 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
7405 * information. This avoids the dmu_buf_will_dirty() path and
7406 * saves us a pre-read to get data we don't actually care about.
7408 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
7409 packed = kmem_alloc(bufsize, KM_SLEEP);
7411 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
7413 bzero(packed + nvsize, bufsize - nvsize);
7415 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
7417 kmem_free(packed, bufsize);
7419 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
7420 dmu_buf_will_dirty(db, tx);
7421 *(uint64_t *)db->db_data = nvsize;
7422 dmu_buf_rele(db, FTAG);
7426 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
7427 const char *config, const char *entry)
7437 * Update the MOS nvlist describing the list of available devices.
7438 * spa_validate_aux() will have already made sure this nvlist is
7439 * valid and the vdevs are labeled appropriately.
7441 if (sav->sav_object == 0) {
7442 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
7443 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
7444 sizeof (uint64_t), tx);
7445 VERIFY(zap_update(spa->spa_meta_objset,
7446 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
7447 &sav->sav_object, tx) == 0);
7450 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7451 if (sav->sav_count == 0) {
7452 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
7454 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
7455 for (i = 0; i < sav->sav_count; i++)
7456 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
7457 B_FALSE, VDEV_CONFIG_L2CACHE);
7458 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
7459 sav->sav_count) == 0);
7460 for (i = 0; i < sav->sav_count; i++)
7461 nvlist_free(list[i]);
7462 kmem_free(list, sav->sav_count * sizeof (void *));
7465 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
7466 nvlist_free(nvroot);
7468 sav->sav_sync = B_FALSE;
7472 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
7473 * The all-vdev ZAP must be empty.
7476 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
7478 spa_t *spa = vd->vdev_spa;
7479 if (vd->vdev_top_zap != 0) {
7480 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7481 vd->vdev_top_zap, tx));
7483 if (vd->vdev_leaf_zap != 0) {
7484 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7485 vd->vdev_leaf_zap, tx));
7487 for (uint64_t i = 0; i < vd->vdev_children; i++) {
7488 spa_avz_build(vd->vdev_child[i], avz, tx);
7493 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
7498 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
7499 * its config may not be dirty but we still need to build per-vdev ZAPs.
7500 * Similarly, if the pool is being assembled (e.g. after a split), we
7501 * need to rebuild the AVZ although the config may not be dirty.
7503 if (list_is_empty(&spa->spa_config_dirty_list) &&
7504 spa->spa_avz_action == AVZ_ACTION_NONE)
7507 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7509 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
7510 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
7511 spa->spa_all_vdev_zaps != 0);
7513 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
7514 /* Make and build the new AVZ */
7515 uint64_t new_avz = zap_create(spa->spa_meta_objset,
7516 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7517 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7519 /* Diff old AVZ with new one */
7523 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7524 spa->spa_all_vdev_zaps);
7525 zap_cursor_retrieve(&zc, &za) == 0;
7526 zap_cursor_advance(&zc)) {
7527 uint64_t vdzap = za.za_first_integer;
7528 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
7531 * ZAP is listed in old AVZ but not in new one;
7534 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
7539 zap_cursor_fini(&zc);
7541 /* Destroy the old AVZ */
7542 VERIFY0(zap_destroy(spa->spa_meta_objset,
7543 spa->spa_all_vdev_zaps, tx));
7545 /* Replace the old AVZ in the dir obj with the new one */
7546 VERIFY0(zap_update(spa->spa_meta_objset,
7547 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
7548 sizeof (new_avz), 1, &new_avz, tx));
7550 spa->spa_all_vdev_zaps = new_avz;
7551 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
7555 /* Walk through the AVZ and destroy all listed ZAPs */
7556 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7557 spa->spa_all_vdev_zaps);
7558 zap_cursor_retrieve(&zc, &za) == 0;
7559 zap_cursor_advance(&zc)) {
7560 uint64_t zap = za.za_first_integer;
7561 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
7564 zap_cursor_fini(&zc);
7566 /* Destroy and unlink the AVZ itself */
7567 VERIFY0(zap_destroy(spa->spa_meta_objset,
7568 spa->spa_all_vdev_zaps, tx));
7569 VERIFY0(zap_remove(spa->spa_meta_objset,
7570 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
7571 spa->spa_all_vdev_zaps = 0;
7574 if (spa->spa_all_vdev_zaps == 0) {
7575 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
7576 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
7577 DMU_POOL_VDEV_ZAP_MAP, tx);
7579 spa->spa_avz_action = AVZ_ACTION_NONE;
7581 /* Create ZAPs for vdevs that don't have them. */
7582 vdev_construct_zaps(spa->spa_root_vdev, tx);
7584 config = spa_config_generate(spa, spa->spa_root_vdev,
7585 dmu_tx_get_txg(tx), B_FALSE);
7588 * If we're upgrading the spa version then make sure that
7589 * the config object gets updated with the correct version.
7591 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
7592 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7593 spa->spa_uberblock.ub_version);
7595 spa_config_exit(spa, SCL_STATE, FTAG);
7597 nvlist_free(spa->spa_config_syncing);
7598 spa->spa_config_syncing = config;
7600 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
7604 spa_sync_version(void *arg, dmu_tx_t *tx)
7606 uint64_t *versionp = arg;
7607 uint64_t version = *versionp;
7608 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7611 * Setting the version is special cased when first creating the pool.
7613 ASSERT(tx->tx_txg != TXG_INITIAL);
7615 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
7616 ASSERT(version >= spa_version(spa));
7618 spa->spa_uberblock.ub_version = version;
7619 vdev_config_dirty(spa->spa_root_vdev);
7620 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
7624 * Set zpool properties.
7627 spa_sync_props(void *arg, dmu_tx_t *tx)
7629 nvlist_t *nvp = arg;
7630 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7631 objset_t *mos = spa->spa_meta_objset;
7632 nvpair_t *elem = NULL;
7634 mutex_enter(&spa->spa_props_lock);
7636 while ((elem = nvlist_next_nvpair(nvp, elem))) {
7638 char *strval, *fname;
7640 const char *propname;
7641 zprop_type_t proptype;
7644 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
7645 case ZPOOL_PROP_INVAL:
7647 * We checked this earlier in spa_prop_validate().
7649 ASSERT(zpool_prop_feature(nvpair_name(elem)));
7651 fname = strchr(nvpair_name(elem), '@') + 1;
7652 VERIFY0(zfeature_lookup_name(fname, &fid));
7654 spa_feature_enable(spa, fid, tx);
7655 spa_history_log_internal(spa, "set", tx,
7656 "%s=enabled", nvpair_name(elem));
7659 case ZPOOL_PROP_VERSION:
7660 intval = fnvpair_value_uint64(elem);
7662 * The version is synced seperatly before other
7663 * properties and should be correct by now.
7665 ASSERT3U(spa_version(spa), >=, intval);
7668 case ZPOOL_PROP_ALTROOT:
7670 * 'altroot' is a non-persistent property. It should
7671 * have been set temporarily at creation or import time.
7673 ASSERT(spa->spa_root != NULL);
7676 case ZPOOL_PROP_READONLY:
7677 case ZPOOL_PROP_CACHEFILE:
7679 * 'readonly' and 'cachefile' are also non-persisitent
7683 case ZPOOL_PROP_COMMENT:
7684 strval = fnvpair_value_string(elem);
7685 if (spa->spa_comment != NULL)
7686 spa_strfree(spa->spa_comment);
7687 spa->spa_comment = spa_strdup(strval);
7689 * We need to dirty the configuration on all the vdevs
7690 * so that their labels get updated. It's unnecessary
7691 * to do this for pool creation since the vdev's
7692 * configuratoin has already been dirtied.
7694 if (tx->tx_txg != TXG_INITIAL)
7695 vdev_config_dirty(spa->spa_root_vdev);
7696 spa_history_log_internal(spa, "set", tx,
7697 "%s=%s", nvpair_name(elem), strval);
7701 * Set pool property values in the poolprops mos object.
7703 if (spa->spa_pool_props_object == 0) {
7704 spa->spa_pool_props_object =
7705 zap_create_link(mos, DMU_OT_POOL_PROPS,
7706 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
7710 /* normalize the property name */
7711 propname = zpool_prop_to_name(prop);
7712 proptype = zpool_prop_get_type(prop);
7714 if (nvpair_type(elem) == DATA_TYPE_STRING) {
7715 ASSERT(proptype == PROP_TYPE_STRING);
7716 strval = fnvpair_value_string(elem);
7717 VERIFY0(zap_update(mos,
7718 spa->spa_pool_props_object, propname,
7719 1, strlen(strval) + 1, strval, tx));
7720 spa_history_log_internal(spa, "set", tx,
7721 "%s=%s", nvpair_name(elem), strval);
7722 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
7723 intval = fnvpair_value_uint64(elem);
7725 if (proptype == PROP_TYPE_INDEX) {
7727 VERIFY0(zpool_prop_index_to_string(
7728 prop, intval, &unused));
7730 VERIFY0(zap_update(mos,
7731 spa->spa_pool_props_object, propname,
7732 8, 1, &intval, tx));
7733 spa_history_log_internal(spa, "set", tx,
7734 "%s=%lld", nvpair_name(elem), intval);
7736 ASSERT(0); /* not allowed */
7740 case ZPOOL_PROP_DELEGATION:
7741 spa->spa_delegation = intval;
7743 case ZPOOL_PROP_BOOTFS:
7744 spa->spa_bootfs = intval;
7746 case ZPOOL_PROP_FAILUREMODE:
7747 spa->spa_failmode = intval;
7749 case ZPOOL_PROP_AUTOEXPAND:
7750 spa->spa_autoexpand = intval;
7751 if (tx->tx_txg != TXG_INITIAL)
7752 spa_async_request(spa,
7753 SPA_ASYNC_AUTOEXPAND);
7755 case ZPOOL_PROP_DEDUPDITTO:
7756 spa->spa_dedup_ditto = intval;
7765 mutex_exit(&spa->spa_props_lock);
7769 * Perform one-time upgrade on-disk changes. spa_version() does not
7770 * reflect the new version this txg, so there must be no changes this
7771 * txg to anything that the upgrade code depends on after it executes.
7772 * Therefore this must be called after dsl_pool_sync() does the sync
7776 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
7778 dsl_pool_t *dp = spa->spa_dsl_pool;
7780 ASSERT(spa->spa_sync_pass == 1);
7782 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
7784 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
7785 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
7786 dsl_pool_create_origin(dp, tx);
7788 /* Keeping the origin open increases spa_minref */
7789 spa->spa_minref += 3;
7792 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
7793 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
7794 dsl_pool_upgrade_clones(dp, tx);
7797 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
7798 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
7799 dsl_pool_upgrade_dir_clones(dp, tx);
7801 /* Keeping the freedir open increases spa_minref */
7802 spa->spa_minref += 3;
7805 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
7806 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7807 spa_feature_create_zap_objects(spa, tx);
7811 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
7812 * when possibility to use lz4 compression for metadata was added
7813 * Old pools that have this feature enabled must be upgraded to have
7814 * this feature active
7816 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7817 boolean_t lz4_en = spa_feature_is_enabled(spa,
7818 SPA_FEATURE_LZ4_COMPRESS);
7819 boolean_t lz4_ac = spa_feature_is_active(spa,
7820 SPA_FEATURE_LZ4_COMPRESS);
7822 if (lz4_en && !lz4_ac)
7823 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
7827 * If we haven't written the salt, do so now. Note that the
7828 * feature may not be activated yet, but that's fine since
7829 * the presence of this ZAP entry is backwards compatible.
7831 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7832 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
7833 VERIFY0(zap_add(spa->spa_meta_objset,
7834 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
7835 sizeof (spa->spa_cksum_salt.zcs_bytes),
7836 spa->spa_cksum_salt.zcs_bytes, tx));
7839 rrw_exit(&dp->dp_config_rwlock, FTAG);
7843 vdev_indirect_state_sync_verify(vdev_t *vd)
7845 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
7846 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
7848 if (vd->vdev_ops == &vdev_indirect_ops) {
7849 ASSERT(vim != NULL);
7850 ASSERT(vib != NULL);
7853 if (vdev_obsolete_sm_object(vd) != 0) {
7854 ASSERT(vd->vdev_obsolete_sm != NULL);
7855 ASSERT(vd->vdev_removing ||
7856 vd->vdev_ops == &vdev_indirect_ops);
7857 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
7858 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
7860 ASSERT3U(vdev_obsolete_sm_object(vd), ==,
7861 space_map_object(vd->vdev_obsolete_sm));
7862 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
7863 space_map_allocated(vd->vdev_obsolete_sm));
7865 ASSERT(vd->vdev_obsolete_segments != NULL);
7868 * Since frees / remaps to an indirect vdev can only
7869 * happen in syncing context, the obsolete segments
7870 * tree must be empty when we start syncing.
7872 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
7876 * Sync the specified transaction group. New blocks may be dirtied as
7877 * part of the process, so we iterate until it converges.
7880 spa_sync(spa_t *spa, uint64_t txg)
7882 dsl_pool_t *dp = spa->spa_dsl_pool;
7883 objset_t *mos = spa->spa_meta_objset;
7884 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
7885 vdev_t *rvd = spa->spa_root_vdev;
7889 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
7890 zfs_vdev_queue_depth_pct / 100;
7892 VERIFY(spa_writeable(spa));
7895 * Wait for i/os issued in open context that need to complete
7896 * before this txg syncs.
7898 (void) zio_wait(spa->spa_txg_zio[txg & TXG_MASK]);
7899 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL,
7903 * Lock out configuration changes.
7905 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7907 spa->spa_syncing_txg = txg;
7908 spa->spa_sync_pass = 0;
7910 for (int i = 0; i < spa->spa_alloc_count; i++) {
7911 mutex_enter(&spa->spa_alloc_locks[i]);
7912 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
7913 mutex_exit(&spa->spa_alloc_locks[i]);
7917 * If there are any pending vdev state changes, convert them
7918 * into config changes that go out with this transaction group.
7920 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7921 while (list_head(&spa->spa_state_dirty_list) != NULL) {
7923 * We need the write lock here because, for aux vdevs,
7924 * calling vdev_config_dirty() modifies sav_config.
7925 * This is ugly and will become unnecessary when we
7926 * eliminate the aux vdev wart by integrating all vdevs
7927 * into the root vdev tree.
7929 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7930 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
7931 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
7932 vdev_state_clean(vd);
7933 vdev_config_dirty(vd);
7935 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7936 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
7938 spa_config_exit(spa, SCL_STATE, FTAG);
7940 tx = dmu_tx_create_assigned(dp, txg);
7942 spa->spa_sync_starttime = gethrtime();
7944 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
7945 spa->spa_sync_starttime + spa->spa_deadman_synctime));
7946 #else /* !illumos */
7948 callout_schedule(&spa->spa_deadman_cycid,
7949 hz * spa->spa_deadman_synctime / NANOSEC);
7951 #endif /* illumos */
7954 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
7955 * set spa_deflate if we have no raid-z vdevs.
7957 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
7958 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
7961 for (i = 0; i < rvd->vdev_children; i++) {
7962 vd = rvd->vdev_child[i];
7963 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
7966 if (i == rvd->vdev_children) {
7967 spa->spa_deflate = TRUE;
7968 VERIFY(0 == zap_add(spa->spa_meta_objset,
7969 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
7970 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
7975 * Set the top-level vdev's max queue depth. Evaluate each
7976 * top-level's async write queue depth in case it changed.
7977 * The max queue depth will not change in the middle of syncing
7980 uint64_t slots_per_allocator = 0;
7981 for (int c = 0; c < rvd->vdev_children; c++) {
7982 vdev_t *tvd = rvd->vdev_child[c];
7983 metaslab_group_t *mg = tvd->vdev_mg;
7985 if (mg == NULL || mg->mg_class != spa_normal_class(spa) ||
7986 !metaslab_group_initialized(mg))
7990 * It is safe to do a lock-free check here because only async
7991 * allocations look at mg_max_alloc_queue_depth, and async
7992 * allocations all happen from spa_sync().
7994 for (int i = 0; i < spa->spa_alloc_count; i++)
7995 ASSERT0(refcount_count(&(mg->mg_alloc_queue_depth[i])));
7996 mg->mg_max_alloc_queue_depth = max_queue_depth;
7998 for (int i = 0; i < spa->spa_alloc_count; i++) {
7999 mg->mg_cur_max_alloc_queue_depth[i] =
8000 zfs_vdev_def_queue_depth;
8002 slots_per_allocator += zfs_vdev_def_queue_depth;
8004 metaslab_class_t *mc = spa_normal_class(spa);
8005 for (int i = 0; i < spa->spa_alloc_count; i++) {
8006 ASSERT0(refcount_count(&mc->mc_alloc_slots[i]));
8007 mc->mc_alloc_max_slots[i] = slots_per_allocator;
8009 mc->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8011 for (int c = 0; c < rvd->vdev_children; c++) {
8012 vdev_t *vd = rvd->vdev_child[c];
8013 vdev_indirect_state_sync_verify(vd);
8015 if (vdev_indirect_should_condense(vd)) {
8016 spa_condense_indirect_start_sync(vd, tx);
8022 * Iterate to convergence.
8025 int pass = ++spa->spa_sync_pass;
8027 spa_sync_config_object(spa, tx);
8028 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
8029 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
8030 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
8031 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
8032 spa_errlog_sync(spa, txg);
8033 dsl_pool_sync(dp, txg);
8035 if (pass < zfs_sync_pass_deferred_free) {
8036 spa_sync_frees(spa, free_bpl, tx);
8039 * We can not defer frees in pass 1, because
8040 * we sync the deferred frees later in pass 1.
8042 ASSERT3U(pass, >, 1);
8043 bplist_iterate(free_bpl, bpobj_enqueue_cb,
8044 &spa->spa_deferred_bpobj, tx);
8048 dsl_scan_sync(dp, tx);
8050 if (spa->spa_vdev_removal != NULL)
8053 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
8058 spa_sync_upgrades(spa, tx);
8060 spa->spa_uberblock.ub_rootbp.blk_birth);
8062 * Note: We need to check if the MOS is dirty
8063 * because we could have marked the MOS dirty
8064 * without updating the uberblock (e.g. if we
8065 * have sync tasks but no dirty user data). We
8066 * need to check the uberblock's rootbp because
8067 * it is updated if we have synced out dirty
8068 * data (though in this case the MOS will most
8069 * likely also be dirty due to second order
8070 * effects, we don't want to rely on that here).
8072 if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
8073 !dmu_objset_is_dirty(mos, txg)) {
8075 * Nothing changed on the first pass,
8076 * therefore this TXG is a no-op. Avoid
8077 * syncing deferred frees, so that we
8078 * can keep this TXG as a no-op.
8080 ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
8082 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8083 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
8084 ASSERT(txg_list_empty(&dp->dp_early_sync_tasks,
8088 spa_sync_deferred_frees(spa, tx);
8091 } while (dmu_objset_is_dirty(mos, txg));
8093 if (!list_is_empty(&spa->spa_config_dirty_list)) {
8095 * Make sure that the number of ZAPs for all the vdevs matches
8096 * the number of ZAPs in the per-vdev ZAP list. This only gets
8097 * called if the config is dirty; otherwise there may be
8098 * outstanding AVZ operations that weren't completed in
8099 * spa_sync_config_object.
8101 uint64_t all_vdev_zap_entry_count;
8102 ASSERT0(zap_count(spa->spa_meta_objset,
8103 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
8104 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
8105 all_vdev_zap_entry_count);
8108 if (spa->spa_vdev_removal != NULL) {
8109 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
8113 * Rewrite the vdev configuration (which includes the uberblock)
8114 * to commit the transaction group.
8116 * If there are no dirty vdevs, we sync the uberblock to a few
8117 * random top-level vdevs that are known to be visible in the
8118 * config cache (see spa_vdev_add() for a complete description).
8119 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
8123 * We hold SCL_STATE to prevent vdev open/close/etc.
8124 * while we're attempting to write the vdev labels.
8126 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8128 if (list_is_empty(&spa->spa_config_dirty_list)) {
8129 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
8131 int children = rvd->vdev_children;
8132 int c0 = spa_get_random(children);
8134 for (int c = 0; c < children; c++) {
8135 vd = rvd->vdev_child[(c0 + c) % children];
8137 /* Stop when revisiting the first vdev */
8138 if (c > 0 && svd[0] == vd)
8141 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
8142 !vdev_is_concrete(vd))
8145 svd[svdcount++] = vd;
8146 if (svdcount == SPA_SYNC_MIN_VDEVS)
8149 error = vdev_config_sync(svd, svdcount, txg);
8151 error = vdev_config_sync(rvd->vdev_child,
8152 rvd->vdev_children, txg);
8156 spa->spa_last_synced_guid = rvd->vdev_guid;
8158 spa_config_exit(spa, SCL_STATE, FTAG);
8162 zio_suspend(spa, NULL);
8163 zio_resume_wait(spa);
8168 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
8169 #else /* !illumos */
8171 callout_drain(&spa->spa_deadman_cycid);
8173 #endif /* illumos */
8176 * Clear the dirty config list.
8178 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
8179 vdev_config_clean(vd);
8182 * Now that the new config has synced transactionally,
8183 * let it become visible to the config cache.
8185 if (spa->spa_config_syncing != NULL) {
8186 spa_config_set(spa, spa->spa_config_syncing);
8187 spa->spa_config_txg = txg;
8188 spa->spa_config_syncing = NULL;
8191 dsl_pool_sync_done(dp, txg);
8193 for (int i = 0; i < spa->spa_alloc_count; i++) {
8194 mutex_enter(&spa->spa_alloc_locks[i]);
8195 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8196 mutex_exit(&spa->spa_alloc_locks[i]);
8200 * Update usable space statistics.
8202 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
8204 vdev_sync_done(vd, txg);
8206 spa_update_dspace(spa);
8209 * It had better be the case that we didn't dirty anything
8210 * since vdev_config_sync().
8212 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8213 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8214 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
8216 while (zfs_pause_spa_sync)
8219 spa->spa_sync_pass = 0;
8222 * Update the last synced uberblock here. We want to do this at
8223 * the end of spa_sync() so that consumers of spa_last_synced_txg()
8224 * will be guaranteed that all the processing associated with
8225 * that txg has been completed.
8227 spa->spa_ubsync = spa->spa_uberblock;
8228 spa_config_exit(spa, SCL_CONFIG, FTAG);
8230 spa_handle_ignored_writes(spa);
8233 * If any async tasks have been requested, kick them off.
8235 spa_async_dispatch(spa);
8236 spa_async_dispatch_vd(spa);
8240 * Sync all pools. We don't want to hold the namespace lock across these
8241 * operations, so we take a reference on the spa_t and drop the lock during the
8245 spa_sync_allpools(void)
8248 mutex_enter(&spa_namespace_lock);
8249 while ((spa = spa_next(spa)) != NULL) {
8250 if (spa_state(spa) != POOL_STATE_ACTIVE ||
8251 !spa_writeable(spa) || spa_suspended(spa))
8253 spa_open_ref(spa, FTAG);
8254 mutex_exit(&spa_namespace_lock);
8255 txg_wait_synced(spa_get_dsl(spa), 0);
8256 mutex_enter(&spa_namespace_lock);
8257 spa_close(spa, FTAG);
8259 mutex_exit(&spa_namespace_lock);
8263 * ==========================================================================
8264 * Miscellaneous routines
8265 * ==========================================================================
8269 * Remove all pools in the system.
8277 * Remove all cached state. All pools should be closed now,
8278 * so every spa in the AVL tree should be unreferenced.
8280 mutex_enter(&spa_namespace_lock);
8281 while ((spa = spa_next(NULL)) != NULL) {
8283 * Stop async tasks. The async thread may need to detach
8284 * a device that's been replaced, which requires grabbing
8285 * spa_namespace_lock, so we must drop it here.
8287 spa_open_ref(spa, FTAG);
8288 mutex_exit(&spa_namespace_lock);
8289 spa_async_suspend(spa);
8290 mutex_enter(&spa_namespace_lock);
8291 spa_close(spa, FTAG);
8293 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
8295 spa_deactivate(spa);
8299 mutex_exit(&spa_namespace_lock);
8303 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
8308 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
8312 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
8313 vd = spa->spa_l2cache.sav_vdevs[i];
8314 if (vd->vdev_guid == guid)
8318 for (i = 0; i < spa->spa_spares.sav_count; i++) {
8319 vd = spa->spa_spares.sav_vdevs[i];
8320 if (vd->vdev_guid == guid)
8329 spa_upgrade(spa_t *spa, uint64_t version)
8331 ASSERT(spa_writeable(spa));
8333 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
8336 * This should only be called for a non-faulted pool, and since a
8337 * future version would result in an unopenable pool, this shouldn't be
8340 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
8341 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
8343 spa->spa_uberblock.ub_version = version;
8344 vdev_config_dirty(spa->spa_root_vdev);
8346 spa_config_exit(spa, SCL_ALL, FTAG);
8348 txg_wait_synced(spa_get_dsl(spa), 0);
8352 spa_has_spare(spa_t *spa, uint64_t guid)
8356 spa_aux_vdev_t *sav = &spa->spa_spares;
8358 for (i = 0; i < sav->sav_count; i++)
8359 if (sav->sav_vdevs[i]->vdev_guid == guid)
8362 for (i = 0; i < sav->sav_npending; i++) {
8363 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
8364 &spareguid) == 0 && spareguid == guid)
8372 * Check if a pool has an active shared spare device.
8373 * Note: reference count of an active spare is 2, as a spare and as a replace
8376 spa_has_active_shared_spare(spa_t *spa)
8380 spa_aux_vdev_t *sav = &spa->spa_spares;
8382 for (i = 0; i < sav->sav_count; i++) {
8383 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
8384 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
8393 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8395 sysevent_t *ev = NULL;
8397 sysevent_attr_list_t *attr = NULL;
8398 sysevent_value_t value;
8400 ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
8404 value.value_type = SE_DATA_TYPE_STRING;
8405 value.value.sv_string = spa_name(spa);
8406 if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
8409 value.value_type = SE_DATA_TYPE_UINT64;
8410 value.value.sv_uint64 = spa_guid(spa);
8411 if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
8415 value.value_type = SE_DATA_TYPE_UINT64;
8416 value.value.sv_uint64 = vd->vdev_guid;
8417 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
8421 if (vd->vdev_path) {
8422 value.value_type = SE_DATA_TYPE_STRING;
8423 value.value.sv_string = vd->vdev_path;
8424 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
8425 &value, SE_SLEEP) != 0)
8430 if (hist_nvl != NULL) {
8431 fnvlist_merge((nvlist_t *)attr, hist_nvl);
8434 if (sysevent_attach_attributes(ev, attr) != 0)
8440 sysevent_free_attr(attr);
8447 spa_event_post(sysevent_t *ev)
8452 (void) log_sysevent(ev, SE_SLEEP, &eid);
8458 spa_event_discard(sysevent_t *ev)
8466 * Post a sysevent corresponding to the given event. The 'name' must be one of
8467 * the event definitions in sys/sysevent/eventdefs.h. The payload will be
8468 * filled in from the spa and (optionally) the vdev and history nvl. This
8469 * doesn't do anything in the userland libzpool, as we don't want consumers to
8470 * misinterpret ztest or zdb as real changes.
8473 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8475 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));