4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25 * Copyright (c) 2015, Nexenta Systems, Inc. All rights reserved.
26 * Copyright (c) 2013 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
27 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28 * Copyright 2013 Saso Kiselkov. All rights reserved.
29 * Copyright (c) 2014 Integros [integros.com]
30 * Copyright 2016 Toomas Soome <tsoome@me.com>
31 * Copyright 2018 Joyent, Inc.
32 * Copyright (c) 2017 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 const spa_error_entry_t *sa = (const spa_error_entry_t *)a;
909 const spa_error_entry_t *sb = (const spa_error_entry_t *)b;
912 ret = memcmp(&sa->se_bookmark, &sb->se_bookmark,
913 sizeof (zbookmark_phys_t));
915 return (AVL_ISIGN(ret));
919 * Utility function which retrieves copies of the current logs and
920 * re-initializes them in the process.
923 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
925 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
927 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
928 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
930 avl_create(&spa->spa_errlist_scrub,
931 spa_error_entry_compare, sizeof (spa_error_entry_t),
932 offsetof(spa_error_entry_t, se_avl));
933 avl_create(&spa->spa_errlist_last,
934 spa_error_entry_compare, sizeof (spa_error_entry_t),
935 offsetof(spa_error_entry_t, se_avl));
939 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
941 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
942 enum zti_modes mode = ztip->zti_mode;
943 uint_t value = ztip->zti_value;
944 uint_t count = ztip->zti_count;
945 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
948 boolean_t batch = B_FALSE;
950 if (mode == ZTI_MODE_NULL) {
952 tqs->stqs_taskq = NULL;
956 ASSERT3U(count, >, 0);
958 tqs->stqs_count = count;
959 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
963 ASSERT3U(value, >=, 1);
964 value = MAX(value, 1);
969 flags |= TASKQ_THREADS_CPU_PCT;
970 value = zio_taskq_batch_pct;
974 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
976 zio_type_name[t], zio_taskq_types[q], mode, value);
980 for (uint_t i = 0; i < count; i++) {
984 (void) snprintf(name, sizeof (name), "%s_%s_%u",
985 zio_type_name[t], zio_taskq_types[q], i);
987 (void) snprintf(name, sizeof (name), "%s_%s",
988 zio_type_name[t], zio_taskq_types[q]);
992 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
994 flags |= TASKQ_DC_BATCH;
996 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
997 spa->spa_proc, zio_taskq_basedc, flags);
1000 pri_t pri = maxclsyspri;
1002 * The write issue taskq can be extremely CPU
1003 * intensive. Run it at slightly lower priority
1004 * than the other taskqs.
1006 * - numerically higher priorities are lower priorities;
1007 * - if priorities divided by four (RQ_PPQ) are equal
1008 * then a difference between them is insignificant.
1010 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1017 tq = taskq_create_proc(name, value, pri, 50,
1018 INT_MAX, spa->spa_proc, flags);
1023 tqs->stqs_taskq[i] = tq;
1028 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1030 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1032 if (tqs->stqs_taskq == NULL) {
1033 ASSERT0(tqs->stqs_count);
1037 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1038 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1039 taskq_destroy(tqs->stqs_taskq[i]);
1042 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1043 tqs->stqs_taskq = NULL;
1047 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1048 * Note that a type may have multiple discrete taskqs to avoid lock contention
1049 * on the taskq itself. In that case we choose which taskq at random by using
1050 * the low bits of gethrtime().
1053 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1054 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1056 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1059 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1060 ASSERT3U(tqs->stqs_count, !=, 0);
1062 if (tqs->stqs_count == 1) {
1063 tq = tqs->stqs_taskq[0];
1066 tq = tqs->stqs_taskq[cpu_ticks() % tqs->stqs_count];
1068 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1072 taskq_dispatch_ent(tq, func, arg, flags, ent);
1076 spa_create_zio_taskqs(spa_t *spa)
1078 for (int t = 0; t < ZIO_TYPES; t++) {
1079 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1080 spa_taskqs_init(spa, t, q);
1088 spa_thread(void *arg)
1090 callb_cpr_t cprinfo;
1093 user_t *pu = PTOU(curproc);
1095 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1098 ASSERT(curproc != &p0);
1099 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1100 "zpool-%s", spa->spa_name);
1101 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1104 /* bind this thread to the requested psrset */
1105 if (zio_taskq_psrset_bind != PS_NONE) {
1107 mutex_enter(&cpu_lock);
1108 mutex_enter(&pidlock);
1109 mutex_enter(&curproc->p_lock);
1111 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1112 0, NULL, NULL) == 0) {
1113 curthread->t_bind_pset = zio_taskq_psrset_bind;
1116 "Couldn't bind process for zfs pool \"%s\" to "
1117 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1120 mutex_exit(&curproc->p_lock);
1121 mutex_exit(&pidlock);
1122 mutex_exit(&cpu_lock);
1128 if (zio_taskq_sysdc) {
1129 sysdc_thread_enter(curthread, 100, 0);
1133 spa->spa_proc = curproc;
1134 spa->spa_did = curthread->t_did;
1136 spa_create_zio_taskqs(spa);
1138 mutex_enter(&spa->spa_proc_lock);
1139 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1141 spa->spa_proc_state = SPA_PROC_ACTIVE;
1142 cv_broadcast(&spa->spa_proc_cv);
1144 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1145 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1146 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1147 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1149 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1150 spa->spa_proc_state = SPA_PROC_GONE;
1151 spa->spa_proc = &p0;
1152 cv_broadcast(&spa->spa_proc_cv);
1153 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1155 mutex_enter(&curproc->p_lock);
1158 #endif /* SPA_PROCESS */
1162 * Activate an uninitialized pool.
1165 spa_activate(spa_t *spa, int mode)
1167 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1169 spa->spa_state = POOL_STATE_ACTIVE;
1170 spa->spa_mode = mode;
1172 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1173 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1175 /* Try to create a covering process */
1176 mutex_enter(&spa->spa_proc_lock);
1177 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1178 ASSERT(spa->spa_proc == &p0);
1182 /* Only create a process if we're going to be around a while. */
1183 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1184 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1186 spa->spa_proc_state = SPA_PROC_CREATED;
1187 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1188 cv_wait(&spa->spa_proc_cv,
1189 &spa->spa_proc_lock);
1191 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1192 ASSERT(spa->spa_proc != &p0);
1193 ASSERT(spa->spa_did != 0);
1197 "Couldn't create process for zfs pool \"%s\"\n",
1202 #endif /* SPA_PROCESS */
1203 mutex_exit(&spa->spa_proc_lock);
1205 /* If we didn't create a process, we need to create our taskqs. */
1206 ASSERT(spa->spa_proc == &p0);
1207 if (spa->spa_proc == &p0) {
1208 spa_create_zio_taskqs(spa);
1212 * Start TRIM thread.
1214 trim_thread_create(spa);
1216 for (size_t i = 0; i < TXG_SIZE; i++) {
1217 spa->spa_txg_zio[i] = zio_root(spa, NULL, NULL,
1221 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1222 offsetof(vdev_t, vdev_config_dirty_node));
1223 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1224 offsetof(objset_t, os_evicting_node));
1225 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1226 offsetof(vdev_t, vdev_state_dirty_node));
1228 txg_list_create(&spa->spa_vdev_txg_list, spa,
1229 offsetof(struct vdev, vdev_txg_node));
1231 avl_create(&spa->spa_errlist_scrub,
1232 spa_error_entry_compare, sizeof (spa_error_entry_t),
1233 offsetof(spa_error_entry_t, se_avl));
1234 avl_create(&spa->spa_errlist_last,
1235 spa_error_entry_compare, sizeof (spa_error_entry_t),
1236 offsetof(spa_error_entry_t, se_avl));
1240 * Opposite of spa_activate().
1243 spa_deactivate(spa_t *spa)
1245 ASSERT(spa->spa_sync_on == B_FALSE);
1246 ASSERT(spa->spa_dsl_pool == NULL);
1247 ASSERT(spa->spa_root_vdev == NULL);
1248 ASSERT(spa->spa_async_zio_root == NULL);
1249 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1252 * Stop TRIM thread in case spa_unload() wasn't called directly
1253 * before spa_deactivate().
1255 trim_thread_destroy(spa);
1257 spa_evicting_os_wait(spa);
1259 txg_list_destroy(&spa->spa_vdev_txg_list);
1261 list_destroy(&spa->spa_config_dirty_list);
1262 list_destroy(&spa->spa_evicting_os_list);
1263 list_destroy(&spa->spa_state_dirty_list);
1265 for (int t = 0; t < ZIO_TYPES; t++) {
1266 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1267 spa_taskqs_fini(spa, t, q);
1271 for (size_t i = 0; i < TXG_SIZE; i++) {
1272 ASSERT3P(spa->spa_txg_zio[i], !=, NULL);
1273 VERIFY0(zio_wait(spa->spa_txg_zio[i]));
1274 spa->spa_txg_zio[i] = NULL;
1277 metaslab_class_destroy(spa->spa_normal_class);
1278 spa->spa_normal_class = NULL;
1280 metaslab_class_destroy(spa->spa_log_class);
1281 spa->spa_log_class = NULL;
1284 * If this was part of an import or the open otherwise failed, we may
1285 * still have errors left in the queues. Empty them just in case.
1287 spa_errlog_drain(spa);
1289 avl_destroy(&spa->spa_errlist_scrub);
1290 avl_destroy(&spa->spa_errlist_last);
1292 spa->spa_state = POOL_STATE_UNINITIALIZED;
1294 mutex_enter(&spa->spa_proc_lock);
1295 if (spa->spa_proc_state != SPA_PROC_NONE) {
1296 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1297 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1298 cv_broadcast(&spa->spa_proc_cv);
1299 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1300 ASSERT(spa->spa_proc != &p0);
1301 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1303 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1304 spa->spa_proc_state = SPA_PROC_NONE;
1306 ASSERT(spa->spa_proc == &p0);
1307 mutex_exit(&spa->spa_proc_lock);
1311 * We want to make sure spa_thread() has actually exited the ZFS
1312 * module, so that the module can't be unloaded out from underneath
1315 if (spa->spa_did != 0) {
1316 thread_join(spa->spa_did);
1319 #endif /* SPA_PROCESS */
1323 * Verify a pool configuration, and construct the vdev tree appropriately. This
1324 * will create all the necessary vdevs in the appropriate layout, with each vdev
1325 * in the CLOSED state. This will prep the pool before open/creation/import.
1326 * All vdev validation is done by the vdev_alloc() routine.
1329 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1330 uint_t id, int atype)
1336 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1339 if ((*vdp)->vdev_ops->vdev_op_leaf)
1342 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1345 if (error == ENOENT)
1351 return (SET_ERROR(EINVAL));
1354 for (int c = 0; c < children; c++) {
1356 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1364 ASSERT(*vdp != NULL);
1370 * Opposite of spa_load().
1373 spa_unload(spa_t *spa)
1377 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1379 spa_load_note(spa, "UNLOADING");
1384 trim_thread_destroy(spa);
1389 spa_async_suspend(spa);
1391 if (spa->spa_root_vdev) {
1392 vdev_initialize_stop_all(spa->spa_root_vdev,
1393 VDEV_INITIALIZE_ACTIVE);
1399 if (spa->spa_sync_on) {
1400 txg_sync_stop(spa->spa_dsl_pool);
1401 spa->spa_sync_on = B_FALSE;
1405 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1406 * to call it earlier, before we wait for async i/o to complete.
1407 * This ensures that there is no async metaslab prefetching, by
1408 * calling taskq_wait(mg_taskq).
1410 if (spa->spa_root_vdev != NULL) {
1411 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1412 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1413 vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1414 spa_config_exit(spa, SCL_ALL, spa);
1418 * Wait for any outstanding async I/O to complete.
1420 if (spa->spa_async_zio_root != NULL) {
1421 for (int i = 0; i < max_ncpus; i++)
1422 (void) zio_wait(spa->spa_async_zio_root[i]);
1423 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1424 spa->spa_async_zio_root = NULL;
1427 if (spa->spa_vdev_removal != NULL) {
1428 spa_vdev_removal_destroy(spa->spa_vdev_removal);
1429 spa->spa_vdev_removal = NULL;
1432 if (spa->spa_condense_zthr != NULL) {
1433 ASSERT(!zthr_isrunning(spa->spa_condense_zthr));
1434 zthr_destroy(spa->spa_condense_zthr);
1435 spa->spa_condense_zthr = NULL;
1438 if (spa->spa_checkpoint_discard_zthr != NULL) {
1439 ASSERT(!zthr_isrunning(spa->spa_checkpoint_discard_zthr));
1440 zthr_destroy(spa->spa_checkpoint_discard_zthr);
1441 spa->spa_checkpoint_discard_zthr = NULL;
1444 spa_condense_fini(spa);
1446 bpobj_close(&spa->spa_deferred_bpobj);
1448 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1453 if (spa->spa_root_vdev)
1454 vdev_free(spa->spa_root_vdev);
1455 ASSERT(spa->spa_root_vdev == NULL);
1458 * Close the dsl pool.
1460 if (spa->spa_dsl_pool) {
1461 dsl_pool_close(spa->spa_dsl_pool);
1462 spa->spa_dsl_pool = NULL;
1463 spa->spa_meta_objset = NULL;
1469 * Drop and purge level 2 cache
1471 spa_l2cache_drop(spa);
1473 for (i = 0; i < spa->spa_spares.sav_count; i++)
1474 vdev_free(spa->spa_spares.sav_vdevs[i]);
1475 if (spa->spa_spares.sav_vdevs) {
1476 kmem_free(spa->spa_spares.sav_vdevs,
1477 spa->spa_spares.sav_count * sizeof (void *));
1478 spa->spa_spares.sav_vdevs = NULL;
1480 if (spa->spa_spares.sav_config) {
1481 nvlist_free(spa->spa_spares.sav_config);
1482 spa->spa_spares.sav_config = NULL;
1484 spa->spa_spares.sav_count = 0;
1486 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1487 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1488 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1490 if (spa->spa_l2cache.sav_vdevs) {
1491 kmem_free(spa->spa_l2cache.sav_vdevs,
1492 spa->spa_l2cache.sav_count * sizeof (void *));
1493 spa->spa_l2cache.sav_vdevs = NULL;
1495 if (spa->spa_l2cache.sav_config) {
1496 nvlist_free(spa->spa_l2cache.sav_config);
1497 spa->spa_l2cache.sav_config = NULL;
1499 spa->spa_l2cache.sav_count = 0;
1501 spa->spa_async_suspended = 0;
1503 spa->spa_indirect_vdevs_loaded = B_FALSE;
1505 if (spa->spa_comment != NULL) {
1506 spa_strfree(spa->spa_comment);
1507 spa->spa_comment = NULL;
1510 spa_config_exit(spa, SCL_ALL, spa);
1514 * Load (or re-load) the current list of vdevs describing the active spares for
1515 * this pool. When this is called, we have some form of basic information in
1516 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1517 * then re-generate a more complete list including status information.
1520 spa_load_spares(spa_t *spa)
1529 * zdb opens both the current state of the pool and the
1530 * checkpointed state (if present), with a different spa_t.
1532 * As spare vdevs are shared among open pools, we skip loading
1533 * them when we load the checkpointed state of the pool.
1535 if (!spa_writeable(spa))
1539 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1542 * First, close and free any existing spare vdevs.
1544 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1545 vd = spa->spa_spares.sav_vdevs[i];
1547 /* Undo the call to spa_activate() below */
1548 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1549 B_FALSE)) != NULL && tvd->vdev_isspare)
1550 spa_spare_remove(tvd);
1555 if (spa->spa_spares.sav_vdevs)
1556 kmem_free(spa->spa_spares.sav_vdevs,
1557 spa->spa_spares.sav_count * sizeof (void *));
1559 if (spa->spa_spares.sav_config == NULL)
1562 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1563 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1565 spa->spa_spares.sav_count = (int)nspares;
1566 spa->spa_spares.sav_vdevs = NULL;
1572 * Construct the array of vdevs, opening them to get status in the
1573 * process. For each spare, there is potentially two different vdev_t
1574 * structures associated with it: one in the list of spares (used only
1575 * for basic validation purposes) and one in the active vdev
1576 * configuration (if it's spared in). During this phase we open and
1577 * validate each vdev on the spare list. If the vdev also exists in the
1578 * active configuration, then we also mark this vdev as an active spare.
1580 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1582 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1583 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1584 VDEV_ALLOC_SPARE) == 0);
1587 spa->spa_spares.sav_vdevs[i] = vd;
1589 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1590 B_FALSE)) != NULL) {
1591 if (!tvd->vdev_isspare)
1595 * We only mark the spare active if we were successfully
1596 * able to load the vdev. Otherwise, importing a pool
1597 * with a bad active spare would result in strange
1598 * behavior, because multiple pool would think the spare
1599 * is actively in use.
1601 * There is a vulnerability here to an equally bizarre
1602 * circumstance, where a dead active spare is later
1603 * brought back to life (onlined or otherwise). Given
1604 * the rarity of this scenario, and the extra complexity
1605 * it adds, we ignore the possibility.
1607 if (!vdev_is_dead(tvd))
1608 spa_spare_activate(tvd);
1612 vd->vdev_aux = &spa->spa_spares;
1614 if (vdev_open(vd) != 0)
1617 if (vdev_validate_aux(vd) == 0)
1622 * Recompute the stashed list of spares, with status information
1625 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1626 DATA_TYPE_NVLIST_ARRAY) == 0);
1628 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1630 for (i = 0; i < spa->spa_spares.sav_count; i++)
1631 spares[i] = vdev_config_generate(spa,
1632 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1633 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1634 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1635 for (i = 0; i < spa->spa_spares.sav_count; i++)
1636 nvlist_free(spares[i]);
1637 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1641 * Load (or re-load) the current list of vdevs describing the active l2cache for
1642 * this pool. When this is called, we have some form of basic information in
1643 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1644 * then re-generate a more complete list including status information.
1645 * Devices which are already active have their details maintained, and are
1649 spa_load_l2cache(spa_t *spa)
1653 int i, j, oldnvdevs;
1655 vdev_t *vd, **oldvdevs, **newvdevs;
1656 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1660 * zdb opens both the current state of the pool and the
1661 * checkpointed state (if present), with a different spa_t.
1663 * As L2 caches are part of the ARC which is shared among open
1664 * pools, we skip loading them when we load the checkpointed
1665 * state of the pool.
1667 if (!spa_writeable(spa))
1671 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1673 if (sav->sav_config != NULL) {
1674 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1675 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1676 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1682 oldvdevs = sav->sav_vdevs;
1683 oldnvdevs = sav->sav_count;
1684 sav->sav_vdevs = NULL;
1688 * Process new nvlist of vdevs.
1690 for (i = 0; i < nl2cache; i++) {
1691 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1695 for (j = 0; j < oldnvdevs; j++) {
1697 if (vd != NULL && guid == vd->vdev_guid) {
1699 * Retain previous vdev for add/remove ops.
1707 if (newvdevs[i] == NULL) {
1711 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1712 VDEV_ALLOC_L2CACHE) == 0);
1717 * Commit this vdev as an l2cache device,
1718 * even if it fails to open.
1720 spa_l2cache_add(vd);
1725 spa_l2cache_activate(vd);
1727 if (vdev_open(vd) != 0)
1730 (void) vdev_validate_aux(vd);
1732 if (!vdev_is_dead(vd))
1733 l2arc_add_vdev(spa, vd);
1738 * Purge vdevs that were dropped
1740 for (i = 0; i < oldnvdevs; i++) {
1745 ASSERT(vd->vdev_isl2cache);
1747 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1748 pool != 0ULL && l2arc_vdev_present(vd))
1749 l2arc_remove_vdev(vd);
1750 vdev_clear_stats(vd);
1756 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1758 if (sav->sav_config == NULL)
1761 sav->sav_vdevs = newvdevs;
1762 sav->sav_count = (int)nl2cache;
1765 * Recompute the stashed list of l2cache devices, with status
1766 * information this time.
1768 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1769 DATA_TYPE_NVLIST_ARRAY) == 0);
1771 l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1772 for (i = 0; i < sav->sav_count; i++)
1773 l2cache[i] = vdev_config_generate(spa,
1774 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1775 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1776 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1778 for (i = 0; i < sav->sav_count; i++)
1779 nvlist_free(l2cache[i]);
1781 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1785 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1788 char *packed = NULL;
1793 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1797 nvsize = *(uint64_t *)db->db_data;
1798 dmu_buf_rele(db, FTAG);
1800 packed = kmem_alloc(nvsize, KM_SLEEP);
1801 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1804 error = nvlist_unpack(packed, nvsize, value, 0);
1805 kmem_free(packed, nvsize);
1811 * Concrete top-level vdevs that are not missing and are not logs. At every
1812 * spa_sync we write new uberblocks to at least SPA_SYNC_MIN_VDEVS core tvds.
1815 spa_healthy_core_tvds(spa_t *spa)
1817 vdev_t *rvd = spa->spa_root_vdev;
1820 for (uint64_t i = 0; i < rvd->vdev_children; i++) {
1821 vdev_t *vd = rvd->vdev_child[i];
1824 if (vdev_is_concrete(vd) && !vdev_is_dead(vd))
1832 * Checks to see if the given vdev could not be opened, in which case we post a
1833 * sysevent to notify the autoreplace code that the device has been removed.
1836 spa_check_removed(vdev_t *vd)
1838 for (uint64_t c = 0; c < vd->vdev_children; c++)
1839 spa_check_removed(vd->vdev_child[c]);
1841 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1842 vdev_is_concrete(vd)) {
1843 zfs_post_autoreplace(vd->vdev_spa, vd);
1844 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1849 spa_check_for_missing_logs(spa_t *spa)
1851 vdev_t *rvd = spa->spa_root_vdev;
1854 * If we're doing a normal import, then build up any additional
1855 * diagnostic information about missing log devices.
1856 * We'll pass this up to the user for further processing.
1858 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1859 nvlist_t **child, *nv;
1862 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1864 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1866 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1867 vdev_t *tvd = rvd->vdev_child[c];
1870 * We consider a device as missing only if it failed
1871 * to open (i.e. offline or faulted is not considered
1874 if (tvd->vdev_islog &&
1875 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1876 child[idx++] = vdev_config_generate(spa, tvd,
1877 B_FALSE, VDEV_CONFIG_MISSING);
1882 fnvlist_add_nvlist_array(nv,
1883 ZPOOL_CONFIG_CHILDREN, child, idx);
1884 fnvlist_add_nvlist(spa->spa_load_info,
1885 ZPOOL_CONFIG_MISSING_DEVICES, nv);
1887 for (uint64_t i = 0; i < idx; i++)
1888 nvlist_free(child[i]);
1891 kmem_free(child, rvd->vdev_children * sizeof (char **));
1894 spa_load_failed(spa, "some log devices are missing");
1895 vdev_dbgmsg_print_tree(rvd, 2);
1896 return (SET_ERROR(ENXIO));
1899 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
1900 vdev_t *tvd = rvd->vdev_child[c];
1902 if (tvd->vdev_islog &&
1903 tvd->vdev_state == VDEV_STATE_CANT_OPEN) {
1904 spa_set_log_state(spa, SPA_LOG_CLEAR);
1905 spa_load_note(spa, "some log devices are "
1906 "missing, ZIL is dropped.");
1907 vdev_dbgmsg_print_tree(rvd, 2);
1917 * Check for missing log devices
1920 spa_check_logs(spa_t *spa)
1922 boolean_t rv = B_FALSE;
1923 dsl_pool_t *dp = spa_get_dsl(spa);
1925 switch (spa->spa_log_state) {
1926 case SPA_LOG_MISSING:
1927 /* need to recheck in case slog has been restored */
1928 case SPA_LOG_UNKNOWN:
1929 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1930 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
1932 spa_set_log_state(spa, SPA_LOG_MISSING);
1939 spa_passivate_log(spa_t *spa)
1941 vdev_t *rvd = spa->spa_root_vdev;
1942 boolean_t slog_found = B_FALSE;
1944 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1946 if (!spa_has_slogs(spa))
1949 for (int c = 0; c < rvd->vdev_children; c++) {
1950 vdev_t *tvd = rvd->vdev_child[c];
1951 metaslab_group_t *mg = tvd->vdev_mg;
1953 if (tvd->vdev_islog) {
1954 metaslab_group_passivate(mg);
1955 slog_found = B_TRUE;
1959 return (slog_found);
1963 spa_activate_log(spa_t *spa)
1965 vdev_t *rvd = spa->spa_root_vdev;
1967 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1969 for (int c = 0; c < rvd->vdev_children; c++) {
1970 vdev_t *tvd = rvd->vdev_child[c];
1971 metaslab_group_t *mg = tvd->vdev_mg;
1973 if (tvd->vdev_islog)
1974 metaslab_group_activate(mg);
1979 spa_reset_logs(spa_t *spa)
1983 error = dmu_objset_find(spa_name(spa), zil_reset,
1984 NULL, DS_FIND_CHILDREN);
1987 * We successfully offlined the log device, sync out the
1988 * current txg so that the "stubby" block can be removed
1991 txg_wait_synced(spa->spa_dsl_pool, 0);
1997 spa_aux_check_removed(spa_aux_vdev_t *sav)
2001 for (i = 0; i < sav->sav_count; i++)
2002 spa_check_removed(sav->sav_vdevs[i]);
2006 spa_claim_notify(zio_t *zio)
2008 spa_t *spa = zio->io_spa;
2013 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2014 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2015 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2016 mutex_exit(&spa->spa_props_lock);
2019 typedef struct spa_load_error {
2020 uint64_t sle_meta_count;
2021 uint64_t sle_data_count;
2025 spa_load_verify_done(zio_t *zio)
2027 blkptr_t *bp = zio->io_bp;
2028 spa_load_error_t *sle = zio->io_private;
2029 dmu_object_type_t type = BP_GET_TYPE(bp);
2030 int error = zio->io_error;
2031 spa_t *spa = zio->io_spa;
2033 abd_free(zio->io_abd);
2035 if ((BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type)) &&
2036 type != DMU_OT_INTENT_LOG)
2037 atomic_inc_64(&sle->sle_meta_count);
2039 atomic_inc_64(&sle->sle_data_count);
2042 mutex_enter(&spa->spa_scrub_lock);
2043 spa->spa_load_verify_ios--;
2044 cv_broadcast(&spa->spa_scrub_io_cv);
2045 mutex_exit(&spa->spa_scrub_lock);
2049 * Maximum number of concurrent scrub i/os to create while verifying
2050 * a pool while importing it.
2052 int spa_load_verify_maxinflight = 10000;
2053 boolean_t spa_load_verify_metadata = B_TRUE;
2054 boolean_t spa_load_verify_data = B_TRUE;
2056 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_maxinflight, CTLFLAG_RWTUN,
2057 &spa_load_verify_maxinflight, 0,
2058 "Maximum number of concurrent scrub I/Os to create while verifying a "
2059 "pool while importing it");
2061 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_metadata, CTLFLAG_RWTUN,
2062 &spa_load_verify_metadata, 0,
2063 "Check metadata on import?");
2065 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_load_verify_data, CTLFLAG_RWTUN,
2066 &spa_load_verify_data, 0,
2067 "Check user data on import?");
2071 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2072 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2074 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2077 * Note: normally this routine will not be called if
2078 * spa_load_verify_metadata is not set. However, it may be useful
2079 * to manually set the flag after the traversal has begun.
2081 if (!spa_load_verify_metadata)
2083 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2087 size_t size = BP_GET_PSIZE(bp);
2089 mutex_enter(&spa->spa_scrub_lock);
2090 while (spa->spa_load_verify_ios >= spa_load_verify_maxinflight)
2091 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2092 spa->spa_load_verify_ios++;
2093 mutex_exit(&spa->spa_scrub_lock);
2095 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2096 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2097 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2098 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2104 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2106 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2107 return (SET_ERROR(ENAMETOOLONG));
2113 spa_load_verify(spa_t *spa)
2116 spa_load_error_t sle = { 0 };
2117 zpool_load_policy_t policy;
2118 boolean_t verify_ok = B_FALSE;
2121 zpool_get_load_policy(spa->spa_config, &policy);
2123 if (policy.zlp_rewind & ZPOOL_NEVER_REWIND)
2126 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2127 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2128 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2130 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2134 rio = zio_root(spa, NULL, &sle,
2135 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2137 if (spa_load_verify_metadata) {
2138 if (spa->spa_extreme_rewind) {
2139 spa_load_note(spa, "performing a complete scan of the "
2140 "pool since extreme rewind is on. This may take "
2141 "a very long time.\n (spa_load_verify_data=%u, "
2142 "spa_load_verify_metadata=%u)",
2143 spa_load_verify_data, spa_load_verify_metadata);
2145 error = traverse_pool(spa, spa->spa_verify_min_txg,
2146 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2147 spa_load_verify_cb, rio);
2150 (void) zio_wait(rio);
2152 spa->spa_load_meta_errors = sle.sle_meta_count;
2153 spa->spa_load_data_errors = sle.sle_data_count;
2155 if (sle.sle_meta_count != 0 || sle.sle_data_count != 0) {
2156 spa_load_note(spa, "spa_load_verify found %llu metadata errors "
2157 "and %llu data errors", (u_longlong_t)sle.sle_meta_count,
2158 (u_longlong_t)sle.sle_data_count);
2161 if (spa_load_verify_dryrun ||
2162 (!error && sle.sle_meta_count <= policy.zlp_maxmeta &&
2163 sle.sle_data_count <= policy.zlp_maxdata)) {
2167 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2168 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2170 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2171 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2172 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2173 VERIFY(nvlist_add_int64(spa->spa_load_info,
2174 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2175 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2176 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2178 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2181 if (spa_load_verify_dryrun)
2185 if (error != ENXIO && error != EIO)
2186 error = SET_ERROR(EIO);
2190 return (verify_ok ? 0 : EIO);
2194 * Find a value in the pool props object.
2197 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2199 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2200 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2204 * Find a value in the pool directory object.
2207 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val, boolean_t log_enoent)
2209 int error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2210 name, sizeof (uint64_t), 1, val);
2212 if (error != 0 && (error != ENOENT || log_enoent)) {
2213 spa_load_failed(spa, "couldn't get '%s' value in MOS directory "
2214 "[error=%d]", name, error);
2221 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2223 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2224 return (SET_ERROR(err));
2228 spa_spawn_aux_threads(spa_t *spa)
2230 ASSERT(spa_writeable(spa));
2232 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2234 spa_start_indirect_condensing_thread(spa);
2236 ASSERT3P(spa->spa_checkpoint_discard_zthr, ==, NULL);
2237 spa->spa_checkpoint_discard_zthr =
2238 zthr_create(spa_checkpoint_discard_thread_check,
2239 spa_checkpoint_discard_thread, spa);
2243 * Fix up config after a partly-completed split. This is done with the
2244 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2245 * pool have that entry in their config, but only the splitting one contains
2246 * a list of all the guids of the vdevs that are being split off.
2248 * This function determines what to do with that list: either rejoin
2249 * all the disks to the pool, or complete the splitting process. To attempt
2250 * the rejoin, each disk that is offlined is marked online again, and
2251 * we do a reopen() call. If the vdev label for every disk that was
2252 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2253 * then we call vdev_split() on each disk, and complete the split.
2255 * Otherwise we leave the config alone, with all the vdevs in place in
2256 * the original pool.
2259 spa_try_repair(spa_t *spa, nvlist_t *config)
2266 boolean_t attempt_reopen;
2268 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2271 /* check that the config is complete */
2272 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2273 &glist, &gcount) != 0)
2276 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2278 /* attempt to online all the vdevs & validate */
2279 attempt_reopen = B_TRUE;
2280 for (i = 0; i < gcount; i++) {
2281 if (glist[i] == 0) /* vdev is hole */
2284 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2285 if (vd[i] == NULL) {
2287 * Don't bother attempting to reopen the disks;
2288 * just do the split.
2290 attempt_reopen = B_FALSE;
2292 /* attempt to re-online it */
2293 vd[i]->vdev_offline = B_FALSE;
2297 if (attempt_reopen) {
2298 vdev_reopen(spa->spa_root_vdev);
2300 /* check each device to see what state it's in */
2301 for (extracted = 0, i = 0; i < gcount; i++) {
2302 if (vd[i] != NULL &&
2303 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2310 * If every disk has been moved to the new pool, or if we never
2311 * even attempted to look at them, then we split them off for
2314 if (!attempt_reopen || gcount == extracted) {
2315 for (i = 0; i < gcount; i++)
2318 vdev_reopen(spa->spa_root_vdev);
2321 kmem_free(vd, gcount * sizeof (vdev_t *));
2325 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type)
2327 char *ereport = FM_EREPORT_ZFS_POOL;
2330 spa->spa_load_state = state;
2332 gethrestime(&spa->spa_loaded_ts);
2333 error = spa_load_impl(spa, type, &ereport);
2336 * Don't count references from objsets that are already closed
2337 * and are making their way through the eviction process.
2339 spa_evicting_os_wait(spa);
2340 spa->spa_minref = refcount_count(&spa->spa_refcount);
2342 if (error != EEXIST) {
2343 spa->spa_loaded_ts.tv_sec = 0;
2344 spa->spa_loaded_ts.tv_nsec = 0;
2346 if (error != EBADF) {
2347 zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2350 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2357 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2358 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2359 * spa's per-vdev ZAP list.
2362 vdev_count_verify_zaps(vdev_t *vd)
2364 spa_t *spa = vd->vdev_spa;
2366 if (vd->vdev_top_zap != 0) {
2368 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2369 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2371 if (vd->vdev_leaf_zap != 0) {
2373 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2374 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2377 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2378 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2385 spa_verify_host(spa_t *spa, nvlist_t *mos_config)
2389 uint64_t myhostid = 0;
2391 if (!spa_is_root(spa) && nvlist_lookup_uint64(mos_config,
2392 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2393 hostname = fnvlist_lookup_string(mos_config,
2394 ZPOOL_CONFIG_HOSTNAME);
2396 myhostid = zone_get_hostid(NULL);
2398 if (hostid != 0 && myhostid != 0 && hostid != myhostid) {
2399 cmn_err(CE_WARN, "pool '%s' could not be "
2400 "loaded as it was last accessed by "
2401 "another system (host: %s hostid: 0x%llx). "
2402 "See: http://illumos.org/msg/ZFS-8000-EY",
2403 spa_name(spa), hostname, (u_longlong_t)hostid);
2404 spa_load_failed(spa, "hostid verification failed: pool "
2405 "last accessed by host: %s (hostid: 0x%llx)",
2406 hostname, (u_longlong_t)hostid);
2407 return (SET_ERROR(EBADF));
2415 spa_ld_parse_config(spa_t *spa, spa_import_type_t type)
2418 nvlist_t *nvtree, *nvl, *config = spa->spa_config;
2425 * Versioning wasn't explicitly added to the label until later, so if
2426 * it's not present treat it as the initial version.
2428 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2429 &spa->spa_ubsync.ub_version) != 0)
2430 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2432 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid)) {
2433 spa_load_failed(spa, "invalid config provided: '%s' missing",
2434 ZPOOL_CONFIG_POOL_GUID);
2435 return (SET_ERROR(EINVAL));
2439 * If we are doing an import, ensure that the pool is not already
2440 * imported by checking if its pool guid already exists in the
2443 * The only case that we allow an already imported pool to be
2444 * imported again, is when the pool is checkpointed and we want to
2445 * look at its checkpointed state from userland tools like zdb.
2448 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2449 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2450 spa_guid_exists(pool_guid, 0)) {
2452 if ((spa->spa_load_state == SPA_LOAD_IMPORT ||
2453 spa->spa_load_state == SPA_LOAD_TRYIMPORT) &&
2454 spa_guid_exists(pool_guid, 0) &&
2455 !spa_importing_readonly_checkpoint(spa)) {
2457 spa_load_failed(spa, "a pool with guid %llu is already open",
2458 (u_longlong_t)pool_guid);
2459 return (SET_ERROR(EEXIST));
2462 spa->spa_config_guid = pool_guid;
2464 nvlist_free(spa->spa_load_info);
2465 spa->spa_load_info = fnvlist_alloc();
2467 ASSERT(spa->spa_comment == NULL);
2468 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2469 spa->spa_comment = spa_strdup(comment);
2471 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2472 &spa->spa_config_txg);
2474 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) == 0)
2475 spa->spa_config_splitting = fnvlist_dup(nvl);
2477 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvtree)) {
2478 spa_load_failed(spa, "invalid config provided: '%s' missing",
2479 ZPOOL_CONFIG_VDEV_TREE);
2480 return (SET_ERROR(EINVAL));
2484 * Create "The Godfather" zio to hold all async IOs
2486 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2488 for (int i = 0; i < max_ncpus; i++) {
2489 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2490 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2491 ZIO_FLAG_GODFATHER);
2495 * Parse the configuration into a vdev tree. We explicitly set the
2496 * value that will be returned by spa_version() since parsing the
2497 * configuration requires knowing the version number.
2499 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2500 parse = (type == SPA_IMPORT_EXISTING ?
2501 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2502 error = spa_config_parse(spa, &rvd, nvtree, NULL, 0, parse);
2503 spa_config_exit(spa, SCL_ALL, FTAG);
2506 spa_load_failed(spa, "unable to parse config [error=%d]",
2511 ASSERT(spa->spa_root_vdev == rvd);
2512 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2513 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2515 if (type != SPA_IMPORT_ASSEMBLE) {
2516 ASSERT(spa_guid(spa) == pool_guid);
2523 * Recursively open all vdevs in the vdev tree. This function is called twice:
2524 * first with the untrusted config, then with the trusted config.
2527 spa_ld_open_vdevs(spa_t *spa)
2532 * spa_missing_tvds_allowed defines how many top-level vdevs can be
2533 * missing/unopenable for the root vdev to be still considered openable.
2535 if (spa->spa_trust_config) {
2536 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds;
2537 } else if (spa->spa_config_source == SPA_CONFIG_SRC_CACHEFILE) {
2538 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_cachefile;
2539 } else if (spa->spa_config_source == SPA_CONFIG_SRC_SCAN) {
2540 spa->spa_missing_tvds_allowed = zfs_max_missing_tvds_scan;
2542 spa->spa_missing_tvds_allowed = 0;
2545 spa->spa_missing_tvds_allowed =
2546 MAX(zfs_max_missing_tvds, spa->spa_missing_tvds_allowed);
2548 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2549 error = vdev_open(spa->spa_root_vdev);
2550 spa_config_exit(spa, SCL_ALL, FTAG);
2552 if (spa->spa_missing_tvds != 0) {
2553 spa_load_note(spa, "vdev tree has %lld missing top-level "
2554 "vdevs.", (u_longlong_t)spa->spa_missing_tvds);
2555 if (spa->spa_trust_config && (spa->spa_mode & FWRITE)) {
2557 * Although theoretically we could allow users to open
2558 * incomplete pools in RW mode, we'd need to add a lot
2559 * of extra logic (e.g. adjust pool space to account
2560 * for missing vdevs).
2561 * This limitation also prevents users from accidentally
2562 * opening the pool in RW mode during data recovery and
2563 * damaging it further.
2565 spa_load_note(spa, "pools with missing top-level "
2566 "vdevs can only be opened in read-only mode.");
2567 error = SET_ERROR(ENXIO);
2569 spa_load_note(spa, "current settings allow for maximum "
2570 "%lld missing top-level vdevs at this stage.",
2571 (u_longlong_t)spa->spa_missing_tvds_allowed);
2575 spa_load_failed(spa, "unable to open vdev tree [error=%d]",
2578 if (spa->spa_missing_tvds != 0 || error != 0)
2579 vdev_dbgmsg_print_tree(spa->spa_root_vdev, 2);
2585 * We need to validate the vdev labels against the configuration that
2586 * we have in hand. This function is called twice: first with an untrusted
2587 * config, then with a trusted config. The validation is more strict when the
2588 * config is trusted.
2591 spa_ld_validate_vdevs(spa_t *spa)
2594 vdev_t *rvd = spa->spa_root_vdev;
2596 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2597 error = vdev_validate(rvd);
2598 spa_config_exit(spa, SCL_ALL, FTAG);
2601 spa_load_failed(spa, "vdev_validate failed [error=%d]", error);
2605 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN) {
2606 spa_load_failed(spa, "cannot open vdev tree after invalidating "
2608 vdev_dbgmsg_print_tree(rvd, 2);
2609 return (SET_ERROR(ENXIO));
2616 spa_ld_select_uberblock_done(spa_t *spa, uberblock_t *ub)
2618 spa->spa_state = POOL_STATE_ACTIVE;
2619 spa->spa_ubsync = spa->spa_uberblock;
2620 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2621 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2622 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2623 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2624 spa->spa_claim_max_txg = spa->spa_first_txg;
2625 spa->spa_prev_software_version = ub->ub_software_version;
2629 spa_ld_select_uberblock(spa_t *spa, spa_import_type_t type)
2631 vdev_t *rvd = spa->spa_root_vdev;
2633 uberblock_t *ub = &spa->spa_uberblock;
2636 * If we are opening the checkpointed state of the pool by
2637 * rewinding to it, at this point we will have written the
2638 * checkpointed uberblock to the vdev labels, so searching
2639 * the labels will find the right uberblock. However, if
2640 * we are opening the checkpointed state read-only, we have
2641 * not modified the labels. Therefore, we must ignore the
2642 * labels and continue using the spa_uberblock that was set
2643 * by spa_ld_checkpoint_rewind.
2645 * Note that it would be fine to ignore the labels when
2646 * rewinding (opening writeable) as well. However, if we
2647 * crash just after writing the labels, we will end up
2648 * searching the labels. Doing so in the common case means
2649 * that this code path gets exercised normally, rather than
2650 * just in the edge case.
2652 if (ub->ub_checkpoint_txg != 0 &&
2653 spa_importing_readonly_checkpoint(spa)) {
2654 spa_ld_select_uberblock_done(spa, ub);
2659 * Find the best uberblock.
2661 vdev_uberblock_load(rvd, ub, &label);
2664 * If we weren't able to find a single valid uberblock, return failure.
2666 if (ub->ub_txg == 0) {
2668 spa_load_failed(spa, "no valid uberblock found");
2669 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2672 spa_load_note(spa, "using uberblock with txg=%llu",
2673 (u_longlong_t)ub->ub_txg);
2676 * If the pool has an unsupported version we can't open it.
2678 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2680 spa_load_failed(spa, "version %llu is not supported",
2681 (u_longlong_t)ub->ub_version);
2682 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2685 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2689 * If we weren't able to find what's necessary for reading the
2690 * MOS in the label, return failure.
2692 if (label == NULL) {
2693 spa_load_failed(spa, "label config unavailable");
2694 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2698 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_FEATURES_FOR_READ,
2701 spa_load_failed(spa, "invalid label: '%s' missing",
2702 ZPOOL_CONFIG_FEATURES_FOR_READ);
2703 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2708 * Update our in-core representation with the definitive values
2711 nvlist_free(spa->spa_label_features);
2712 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2718 * Look through entries in the label nvlist's features_for_read. If
2719 * there is a feature listed there which we don't understand then we
2720 * cannot open a pool.
2722 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2723 nvlist_t *unsup_feat;
2725 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2728 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2730 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2731 if (!zfeature_is_supported(nvpair_name(nvp))) {
2732 VERIFY(nvlist_add_string(unsup_feat,
2733 nvpair_name(nvp), "") == 0);
2737 if (!nvlist_empty(unsup_feat)) {
2738 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2739 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2740 nvlist_free(unsup_feat);
2741 spa_load_failed(spa, "some features are unsupported");
2742 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2746 nvlist_free(unsup_feat);
2749 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2750 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2751 spa_try_repair(spa, spa->spa_config);
2752 spa_config_exit(spa, SCL_ALL, FTAG);
2753 nvlist_free(spa->spa_config_splitting);
2754 spa->spa_config_splitting = NULL;
2758 * Initialize internal SPA structures.
2760 spa_ld_select_uberblock_done(spa, ub);
2766 spa_ld_open_rootbp(spa_t *spa)
2769 vdev_t *rvd = spa->spa_root_vdev;
2771 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2773 spa_load_failed(spa, "unable to open rootbp in dsl_pool_init "
2774 "[error=%d]", error);
2775 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2777 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2783 spa_ld_trusted_config(spa_t *spa, spa_import_type_t type,
2784 boolean_t reloading)
2786 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
2787 nvlist_t *nv, *mos_config, *policy;
2788 int error = 0, copy_error;
2789 uint64_t healthy_tvds, healthy_tvds_mos;
2790 uint64_t mos_config_txg;
2792 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object, B_TRUE)
2794 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2797 * If we're assembling a pool from a split, the config provided is
2798 * already trusted so there is nothing to do.
2800 if (type == SPA_IMPORT_ASSEMBLE)
2803 healthy_tvds = spa_healthy_core_tvds(spa);
2805 if (load_nvlist(spa, spa->spa_config_object, &mos_config)
2807 spa_load_failed(spa, "unable to retrieve MOS config");
2808 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2812 * If we are doing an open, pool owner wasn't verified yet, thus do
2813 * the verification here.
2815 if (spa->spa_load_state == SPA_LOAD_OPEN) {
2816 error = spa_verify_host(spa, mos_config);
2818 nvlist_free(mos_config);
2823 nv = fnvlist_lookup_nvlist(mos_config, ZPOOL_CONFIG_VDEV_TREE);
2825 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2828 * Build a new vdev tree from the trusted config
2830 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
2833 * Vdev paths in the MOS may be obsolete. If the untrusted config was
2834 * obtained by scanning /dev/dsk, then it will have the right vdev
2835 * paths. We update the trusted MOS config with this information.
2836 * We first try to copy the paths with vdev_copy_path_strict, which
2837 * succeeds only when both configs have exactly the same vdev tree.
2838 * If that fails, we fall back to a more flexible method that has a
2839 * best effort policy.
2841 copy_error = vdev_copy_path_strict(rvd, mrvd);
2842 if (copy_error != 0 || spa_load_print_vdev_tree) {
2843 spa_load_note(spa, "provided vdev tree:");
2844 vdev_dbgmsg_print_tree(rvd, 2);
2845 spa_load_note(spa, "MOS vdev tree:");
2846 vdev_dbgmsg_print_tree(mrvd, 2);
2848 if (copy_error != 0) {
2849 spa_load_note(spa, "vdev_copy_path_strict failed, falling "
2850 "back to vdev_copy_path_relaxed");
2851 vdev_copy_path_relaxed(rvd, mrvd);
2856 spa->spa_root_vdev = mrvd;
2858 spa_config_exit(spa, SCL_ALL, FTAG);
2861 * We will use spa_config if we decide to reload the spa or if spa_load
2862 * fails and we rewind. We must thus regenerate the config using the
2863 * MOS information with the updated paths. ZPOOL_LOAD_POLICY is used to
2864 * pass settings on how to load the pool and is not stored in the MOS.
2865 * We copy it over to our new, trusted config.
2867 mos_config_txg = fnvlist_lookup_uint64(mos_config,
2868 ZPOOL_CONFIG_POOL_TXG);
2869 nvlist_free(mos_config);
2870 mos_config = spa_config_generate(spa, NULL, mos_config_txg, B_FALSE);
2871 if (nvlist_lookup_nvlist(spa->spa_config, ZPOOL_LOAD_POLICY,
2873 fnvlist_add_nvlist(mos_config, ZPOOL_LOAD_POLICY, policy);
2874 spa_config_set(spa, mos_config);
2875 spa->spa_config_source = SPA_CONFIG_SRC_MOS;
2878 * Now that we got the config from the MOS, we should be more strict
2879 * in checking blkptrs and can make assumptions about the consistency
2880 * of the vdev tree. spa_trust_config must be set to true before opening
2881 * vdevs in order for them to be writeable.
2883 spa->spa_trust_config = B_TRUE;
2886 * Open and validate the new vdev tree
2888 error = spa_ld_open_vdevs(spa);
2892 error = spa_ld_validate_vdevs(spa);
2896 if (copy_error != 0 || spa_load_print_vdev_tree) {
2897 spa_load_note(spa, "final vdev tree:");
2898 vdev_dbgmsg_print_tree(rvd, 2);
2901 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT &&
2902 !spa->spa_extreme_rewind && zfs_max_missing_tvds == 0) {
2904 * Sanity check to make sure that we are indeed loading the
2905 * latest uberblock. If we missed SPA_SYNC_MIN_VDEVS tvds
2906 * in the config provided and they happened to be the only ones
2907 * to have the latest uberblock, we could involuntarily perform
2908 * an extreme rewind.
2910 healthy_tvds_mos = spa_healthy_core_tvds(spa);
2911 if (healthy_tvds_mos - healthy_tvds >=
2912 SPA_SYNC_MIN_VDEVS) {
2913 spa_load_note(spa, "config provided misses too many "
2914 "top-level vdevs compared to MOS (%lld vs %lld). ",
2915 (u_longlong_t)healthy_tvds,
2916 (u_longlong_t)healthy_tvds_mos);
2917 spa_load_note(spa, "vdev tree:");
2918 vdev_dbgmsg_print_tree(rvd, 2);
2920 spa_load_failed(spa, "config was already "
2921 "provided from MOS. Aborting.");
2922 return (spa_vdev_err(rvd,
2923 VDEV_AUX_CORRUPT_DATA, EIO));
2925 spa_load_note(spa, "spa must be reloaded using MOS "
2927 return (SET_ERROR(EAGAIN));
2931 error = spa_check_for_missing_logs(spa);
2933 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2935 if (rvd->vdev_guid_sum != spa->spa_uberblock.ub_guid_sum) {
2936 spa_load_failed(spa, "uberblock guid sum doesn't match MOS "
2937 "guid sum (%llu != %llu)",
2938 (u_longlong_t)spa->spa_uberblock.ub_guid_sum,
2939 (u_longlong_t)rvd->vdev_guid_sum);
2940 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
2948 spa_ld_open_indirect_vdev_metadata(spa_t *spa)
2951 vdev_t *rvd = spa->spa_root_vdev;
2954 * Everything that we read before spa_remove_init() must be stored
2955 * on concreted vdevs. Therefore we do this as early as possible.
2957 error = spa_remove_init(spa);
2959 spa_load_failed(spa, "spa_remove_init failed [error=%d]",
2961 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2965 * Retrieve information needed to condense indirect vdev mappings.
2967 error = spa_condense_init(spa);
2969 spa_load_failed(spa, "spa_condense_init failed [error=%d]",
2971 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
2978 spa_ld_check_features(spa_t *spa, boolean_t *missing_feat_writep)
2981 vdev_t *rvd = spa->spa_root_vdev;
2983 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2984 boolean_t missing_feat_read = B_FALSE;
2985 nvlist_t *unsup_feat, *enabled_feat;
2987 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
2988 &spa->spa_feat_for_read_obj, B_TRUE) != 0) {
2989 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2992 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
2993 &spa->spa_feat_for_write_obj, B_TRUE) != 0) {
2994 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2997 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
2998 &spa->spa_feat_desc_obj, B_TRUE) != 0) {
2999 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3002 enabled_feat = fnvlist_alloc();
3003 unsup_feat = fnvlist_alloc();
3005 if (!spa_features_check(spa, B_FALSE,
3006 unsup_feat, enabled_feat))
3007 missing_feat_read = B_TRUE;
3009 if (spa_writeable(spa) ||
3010 spa->spa_load_state == SPA_LOAD_TRYIMPORT) {
3011 if (!spa_features_check(spa, B_TRUE,
3012 unsup_feat, enabled_feat)) {
3013 *missing_feat_writep = B_TRUE;
3017 fnvlist_add_nvlist(spa->spa_load_info,
3018 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
3020 if (!nvlist_empty(unsup_feat)) {
3021 fnvlist_add_nvlist(spa->spa_load_info,
3022 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
3025 fnvlist_free(enabled_feat);
3026 fnvlist_free(unsup_feat);
3028 if (!missing_feat_read) {
3029 fnvlist_add_boolean(spa->spa_load_info,
3030 ZPOOL_CONFIG_CAN_RDONLY);
3034 * If the state is SPA_LOAD_TRYIMPORT, our objective is
3035 * twofold: to determine whether the pool is available for
3036 * import in read-write mode and (if it is not) whether the
3037 * pool is available for import in read-only mode. If the pool
3038 * is available for import in read-write mode, it is displayed
3039 * as available in userland; if it is not available for import
3040 * in read-only mode, it is displayed as unavailable in
3041 * userland. If the pool is available for import in read-only
3042 * mode but not read-write mode, it is displayed as unavailable
3043 * in userland with a special note that the pool is actually
3044 * available for open in read-only mode.
3046 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
3047 * missing a feature for write, we must first determine whether
3048 * the pool can be opened read-only before returning to
3049 * userland in order to know whether to display the
3050 * abovementioned note.
3052 if (missing_feat_read || (*missing_feat_writep &&
3053 spa_writeable(spa))) {
3054 spa_load_failed(spa, "pool uses unsupported features");
3055 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
3060 * Load refcounts for ZFS features from disk into an in-memory
3061 * cache during SPA initialization.
3063 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
3066 error = feature_get_refcount_from_disk(spa,
3067 &spa_feature_table[i], &refcount);
3069 spa->spa_feat_refcount_cache[i] = refcount;
3070 } else if (error == ENOTSUP) {
3071 spa->spa_feat_refcount_cache[i] =
3072 SPA_FEATURE_DISABLED;
3074 spa_load_failed(spa, "error getting refcount "
3075 "for feature %s [error=%d]",
3076 spa_feature_table[i].fi_guid, error);
3077 return (spa_vdev_err(rvd,
3078 VDEV_AUX_CORRUPT_DATA, EIO));
3083 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
3084 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
3085 &spa->spa_feat_enabled_txg_obj, B_TRUE) != 0)
3086 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3093 spa_ld_load_special_directories(spa_t *spa)
3096 vdev_t *rvd = spa->spa_root_vdev;
3098 spa->spa_is_initializing = B_TRUE;
3099 error = dsl_pool_open(spa->spa_dsl_pool);
3100 spa->spa_is_initializing = B_FALSE;
3102 spa_load_failed(spa, "dsl_pool_open failed [error=%d]", error);
3103 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3110 spa_ld_get_props(spa_t *spa)
3114 vdev_t *rvd = spa->spa_root_vdev;
3116 /* Grab the secret checksum salt from the MOS. */
3117 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3118 DMU_POOL_CHECKSUM_SALT, 1,
3119 sizeof (spa->spa_cksum_salt.zcs_bytes),
3120 spa->spa_cksum_salt.zcs_bytes);
3121 if (error == ENOENT) {
3122 /* Generate a new salt for subsequent use */
3123 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
3124 sizeof (spa->spa_cksum_salt.zcs_bytes));
3125 } else if (error != 0) {
3126 spa_load_failed(spa, "unable to retrieve checksum salt from "
3127 "MOS [error=%d]", error);
3128 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3131 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj, B_TRUE) != 0)
3132 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3133 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
3135 spa_load_failed(spa, "error opening deferred-frees bpobj "
3136 "[error=%d]", error);
3137 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3141 * Load the bit that tells us to use the new accounting function
3142 * (raid-z deflation). If we have an older pool, this will not
3145 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate, B_FALSE);
3146 if (error != 0 && error != ENOENT)
3147 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3149 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
3150 &spa->spa_creation_version, B_FALSE);
3151 if (error != 0 && error != ENOENT)
3152 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3155 * Load the persistent error log. If we have an older pool, this will
3158 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last,
3160 if (error != 0 && error != ENOENT)
3161 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3163 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
3164 &spa->spa_errlog_scrub, B_FALSE);
3165 if (error != 0 && error != ENOENT)
3166 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3169 * Load the history object. If we have an older pool, this
3170 * will not be present.
3172 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history, B_FALSE);
3173 if (error != 0 && error != ENOENT)
3174 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3177 * Load the per-vdev ZAP map. If we have an older pool, this will not
3178 * be present; in this case, defer its creation to a later time to
3179 * avoid dirtying the MOS this early / out of sync context. See
3180 * spa_sync_config_object.
3183 /* The sentinel is only available in the MOS config. */
3184 nvlist_t *mos_config;
3185 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0) {
3186 spa_load_failed(spa, "unable to retrieve MOS config");
3187 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3190 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
3191 &spa->spa_all_vdev_zaps, B_FALSE);
3193 if (error == ENOENT) {
3194 VERIFY(!nvlist_exists(mos_config,
3195 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
3196 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
3197 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3198 } else if (error != 0) {
3199 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3200 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
3202 * An older version of ZFS overwrote the sentinel value, so
3203 * we have orphaned per-vdev ZAPs in the MOS. Defer their
3204 * destruction to later; see spa_sync_config_object.
3206 spa->spa_avz_action = AVZ_ACTION_DESTROY;
3208 * We're assuming that no vdevs have had their ZAPs created
3209 * before this. Better be sure of it.
3211 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
3213 nvlist_free(mos_config);
3215 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
3217 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object,
3219 if (error && error != ENOENT)
3220 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3223 uint64_t autoreplace;
3225 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
3226 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
3227 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
3228 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
3229 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
3230 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
3231 &spa->spa_dedup_ditto);
3233 spa->spa_autoreplace = (autoreplace != 0);
3237 * If we are importing a pool with missing top-level vdevs,
3238 * we enforce that the pool doesn't panic or get suspended on
3239 * error since the likelihood of missing data is extremely high.
3241 if (spa->spa_missing_tvds > 0 &&
3242 spa->spa_failmode != ZIO_FAILURE_MODE_CONTINUE &&
3243 spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3244 spa_load_note(spa, "forcing failmode to 'continue' "
3245 "as some top level vdevs are missing");
3246 spa->spa_failmode = ZIO_FAILURE_MODE_CONTINUE;
3253 spa_ld_open_aux_vdevs(spa_t *spa, spa_import_type_t type)
3256 vdev_t *rvd = spa->spa_root_vdev;
3259 * If we're assembling the pool from the split-off vdevs of
3260 * an existing pool, we don't want to attach the spares & cache
3265 * Load any hot spares for this pool.
3267 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object,
3269 if (error != 0 && error != ENOENT)
3270 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3271 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3272 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
3273 if (load_nvlist(spa, spa->spa_spares.sav_object,
3274 &spa->spa_spares.sav_config) != 0) {
3275 spa_load_failed(spa, "error loading spares nvlist");
3276 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3279 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3280 spa_load_spares(spa);
3281 spa_config_exit(spa, SCL_ALL, FTAG);
3282 } else if (error == 0) {
3283 spa->spa_spares.sav_sync = B_TRUE;
3287 * Load any level 2 ARC devices for this pool.
3289 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
3290 &spa->spa_l2cache.sav_object, B_FALSE);
3291 if (error != 0 && error != ENOENT)
3292 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3293 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
3294 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
3295 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
3296 &spa->spa_l2cache.sav_config) != 0) {
3297 spa_load_failed(spa, "error loading l2cache nvlist");
3298 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3301 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3302 spa_load_l2cache(spa);
3303 spa_config_exit(spa, SCL_ALL, FTAG);
3304 } else if (error == 0) {
3305 spa->spa_l2cache.sav_sync = B_TRUE;
3312 spa_ld_load_vdev_metadata(spa_t *spa)
3315 vdev_t *rvd = spa->spa_root_vdev;
3318 * If the 'autoreplace' property is set, then post a resource notifying
3319 * the ZFS DE that it should not issue any faults for unopenable
3320 * devices. We also iterate over the vdevs, and post a sysevent for any
3321 * unopenable vdevs so that the normal autoreplace handler can take
3324 if (spa->spa_autoreplace && spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3325 spa_check_removed(spa->spa_root_vdev);
3327 * For the import case, this is done in spa_import(), because
3328 * at this point we're using the spare definitions from
3329 * the MOS config, not necessarily from the userland config.
3331 if (spa->spa_load_state != SPA_LOAD_IMPORT) {
3332 spa_aux_check_removed(&spa->spa_spares);
3333 spa_aux_check_removed(&spa->spa_l2cache);
3338 * Load the vdev metadata such as metaslabs, DTLs, spacemap object, etc.
3340 error = vdev_load(rvd);
3342 spa_load_failed(spa, "vdev_load failed [error=%d]", error);
3343 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, error));
3347 * Propagate the leaf DTLs we just loaded all the way up the vdev tree.
3349 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3350 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3351 spa_config_exit(spa, SCL_ALL, FTAG);
3357 spa_ld_load_dedup_tables(spa_t *spa)
3360 vdev_t *rvd = spa->spa_root_vdev;
3362 error = ddt_load(spa);
3364 spa_load_failed(spa, "ddt_load failed [error=%d]", error);
3365 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3372 spa_ld_verify_logs(spa_t *spa, spa_import_type_t type, char **ereport)
3374 vdev_t *rvd = spa->spa_root_vdev;
3376 if (type != SPA_IMPORT_ASSEMBLE && spa_writeable(spa)) {
3377 boolean_t missing = spa_check_logs(spa);
3379 if (spa->spa_missing_tvds != 0) {
3380 spa_load_note(spa, "spa_check_logs failed "
3381 "so dropping the logs");
3383 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3384 spa_load_failed(spa, "spa_check_logs failed");
3385 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG,
3395 spa_ld_verify_pool_data(spa_t *spa)
3398 vdev_t *rvd = spa->spa_root_vdev;
3401 * We've successfully opened the pool, verify that we're ready
3402 * to start pushing transactions.
3404 if (spa->spa_load_state != SPA_LOAD_TRYIMPORT) {
3405 error = spa_load_verify(spa);
3407 spa_load_failed(spa, "spa_load_verify failed "
3408 "[error=%d]", error);
3409 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3418 spa_ld_claim_log_blocks(spa_t *spa)
3421 dsl_pool_t *dp = spa_get_dsl(spa);
3424 * Claim log blocks that haven't been committed yet.
3425 * This must all happen in a single txg.
3426 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3427 * invoked from zil_claim_log_block()'s i/o done callback.
3428 * Price of rollback is that we abandon the log.
3430 spa->spa_claiming = B_TRUE;
3432 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3433 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3434 zil_claim, tx, DS_FIND_CHILDREN);
3437 spa->spa_claiming = B_FALSE;
3439 spa_set_log_state(spa, SPA_LOG_GOOD);
3443 spa_ld_check_for_config_update(spa_t *spa, uint64_t config_cache_txg,
3444 boolean_t update_config_cache)
3446 vdev_t *rvd = spa->spa_root_vdev;
3447 int need_update = B_FALSE;
3450 * If the config cache is stale, or we have uninitialized
3451 * metaslabs (see spa_vdev_add()), then update the config.
3453 * If this is a verbatim import, trust the current
3454 * in-core spa_config and update the disk labels.
3456 if (update_config_cache || config_cache_txg != spa->spa_config_txg ||
3457 spa->spa_load_state == SPA_LOAD_IMPORT ||
3458 spa->spa_load_state == SPA_LOAD_RECOVER ||
3459 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3460 need_update = B_TRUE;
3462 for (int c = 0; c < rvd->vdev_children; c++)
3463 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3464 need_update = B_TRUE;
3467 * Update the config cache asychronously in case we're the
3468 * root pool, in which case the config cache isn't writable yet.
3471 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3475 spa_ld_prepare_for_reload(spa_t *spa)
3477 int mode = spa->spa_mode;
3478 int async_suspended = spa->spa_async_suspended;
3481 spa_deactivate(spa);
3482 spa_activate(spa, mode);
3485 * We save the value of spa_async_suspended as it gets reset to 0 by
3486 * spa_unload(). We want to restore it back to the original value before
3487 * returning as we might be calling spa_async_resume() later.
3489 spa->spa_async_suspended = async_suspended;
3493 spa_ld_read_checkpoint_txg(spa_t *spa)
3495 uberblock_t checkpoint;
3498 ASSERT0(spa->spa_checkpoint_txg);
3499 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3501 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3502 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3503 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3505 if (error == ENOENT)
3511 ASSERT3U(checkpoint.ub_txg, !=, 0);
3512 ASSERT3U(checkpoint.ub_checkpoint_txg, !=, 0);
3513 ASSERT3U(checkpoint.ub_timestamp, !=, 0);
3514 spa->spa_checkpoint_txg = checkpoint.ub_txg;
3515 spa->spa_checkpoint_info.sci_timestamp = checkpoint.ub_timestamp;
3521 spa_ld_mos_init(spa_t *spa, spa_import_type_t type)
3525 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3526 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3529 * Never trust the config that is provided unless we are assembling
3530 * a pool following a split.
3531 * This means don't trust blkptrs and the vdev tree in general. This
3532 * also effectively puts the spa in read-only mode since
3533 * spa_writeable() checks for spa_trust_config to be true.
3534 * We will later load a trusted config from the MOS.
3536 if (type != SPA_IMPORT_ASSEMBLE)
3537 spa->spa_trust_config = B_FALSE;
3540 * Parse the config provided to create a vdev tree.
3542 error = spa_ld_parse_config(spa, type);
3547 * Now that we have the vdev tree, try to open each vdev. This involves
3548 * opening the underlying physical device, retrieving its geometry and
3549 * probing the vdev with a dummy I/O. The state of each vdev will be set
3550 * based on the success of those operations. After this we'll be ready
3551 * to read from the vdevs.
3553 error = spa_ld_open_vdevs(spa);
3558 * Read the label of each vdev and make sure that the GUIDs stored
3559 * there match the GUIDs in the config provided.
3560 * If we're assembling a new pool that's been split off from an
3561 * existing pool, the labels haven't yet been updated so we skip
3562 * validation for now.
3564 if (type != SPA_IMPORT_ASSEMBLE) {
3565 error = spa_ld_validate_vdevs(spa);
3571 * Read all vdev labels to find the best uberblock (i.e. latest,
3572 * unless spa_load_max_txg is set) and store it in spa_uberblock. We
3573 * get the list of features required to read blkptrs in the MOS from
3574 * the vdev label with the best uberblock and verify that our version
3575 * of zfs supports them all.
3577 error = spa_ld_select_uberblock(spa, type);
3582 * Pass that uberblock to the dsl_pool layer which will open the root
3583 * blkptr. This blkptr points to the latest version of the MOS and will
3584 * allow us to read its contents.
3586 error = spa_ld_open_rootbp(spa);
3594 spa_ld_checkpoint_rewind(spa_t *spa)
3596 uberblock_t checkpoint;
3599 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3600 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3602 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
3603 DMU_POOL_ZPOOL_CHECKPOINT, sizeof (uint64_t),
3604 sizeof (uberblock_t) / sizeof (uint64_t), &checkpoint);
3607 spa_load_failed(spa, "unable to retrieve checkpointed "
3608 "uberblock from the MOS config [error=%d]", error);
3610 if (error == ENOENT)
3611 error = ZFS_ERR_NO_CHECKPOINT;
3616 ASSERT3U(checkpoint.ub_txg, <, spa->spa_uberblock.ub_txg);
3617 ASSERT3U(checkpoint.ub_txg, ==, checkpoint.ub_checkpoint_txg);
3620 * We need to update the txg and timestamp of the checkpointed
3621 * uberblock to be higher than the latest one. This ensures that
3622 * the checkpointed uberblock is selected if we were to close and
3623 * reopen the pool right after we've written it in the vdev labels.
3624 * (also see block comment in vdev_uberblock_compare)
3626 checkpoint.ub_txg = spa->spa_uberblock.ub_txg + 1;
3627 checkpoint.ub_timestamp = gethrestime_sec();
3630 * Set current uberblock to be the checkpointed uberblock.
3632 spa->spa_uberblock = checkpoint;
3635 * If we are doing a normal rewind, then the pool is open for
3636 * writing and we sync the "updated" checkpointed uberblock to
3637 * disk. Once this is done, we've basically rewound the whole
3638 * pool and there is no way back.
3640 * There are cases when we don't want to attempt and sync the
3641 * checkpointed uberblock to disk because we are opening a
3642 * pool as read-only. Specifically, verifying the checkpointed
3643 * state with zdb, and importing the checkpointed state to get
3644 * a "preview" of its content.
3646 if (spa_writeable(spa)) {
3647 vdev_t *rvd = spa->spa_root_vdev;
3649 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3650 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
3652 int children = rvd->vdev_children;
3653 int c0 = spa_get_random(children);
3655 for (int c = 0; c < children; c++) {
3656 vdev_t *vd = rvd->vdev_child[(c0 + c) % children];
3658 /* Stop when revisiting the first vdev */
3659 if (c > 0 && svd[0] == vd)
3662 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
3663 !vdev_is_concrete(vd))
3666 svd[svdcount++] = vd;
3667 if (svdcount == SPA_SYNC_MIN_VDEVS)
3670 error = vdev_config_sync(svd, svdcount, spa->spa_first_txg);
3672 spa->spa_last_synced_guid = rvd->vdev_guid;
3673 spa_config_exit(spa, SCL_ALL, FTAG);
3676 spa_load_failed(spa, "failed to write checkpointed "
3677 "uberblock to the vdev labels [error=%d]", error);
3686 spa_ld_mos_with_trusted_config(spa_t *spa, spa_import_type_t type,
3687 boolean_t *update_config_cache)
3692 * Parse the config for pool, open and validate vdevs,
3693 * select an uberblock, and use that uberblock to open
3696 error = spa_ld_mos_init(spa, type);
3701 * Retrieve the trusted config stored in the MOS and use it to create
3702 * a new, exact version of the vdev tree, then reopen all vdevs.
3704 error = spa_ld_trusted_config(spa, type, B_FALSE);
3705 if (error == EAGAIN) {
3706 if (update_config_cache != NULL)
3707 *update_config_cache = B_TRUE;
3710 * Redo the loading process with the trusted config if it is
3711 * too different from the untrusted config.
3713 spa_ld_prepare_for_reload(spa);
3714 spa_load_note(spa, "RELOADING");
3715 error = spa_ld_mos_init(spa, type);
3719 error = spa_ld_trusted_config(spa, type, B_TRUE);
3723 } else if (error != 0) {
3731 * Load an existing storage pool, using the config provided. This config
3732 * describes which vdevs are part of the pool and is later validated against
3733 * partial configs present in each vdev's label and an entire copy of the
3734 * config stored in the MOS.
3737 spa_load_impl(spa_t *spa, spa_import_type_t type, char **ereport)
3740 boolean_t missing_feat_write = B_FALSE;
3741 boolean_t checkpoint_rewind =
3742 (spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
3743 boolean_t update_config_cache = B_FALSE;
3745 ASSERT(MUTEX_HELD(&spa_namespace_lock));
3746 ASSERT(spa->spa_config_source != SPA_CONFIG_SRC_NONE);
3748 spa_load_note(spa, "LOADING");
3750 error = spa_ld_mos_with_trusted_config(spa, type, &update_config_cache);
3755 * If we are rewinding to the checkpoint then we need to repeat
3756 * everything we've done so far in this function but this time
3757 * selecting the checkpointed uberblock and using that to open
3760 if (checkpoint_rewind) {
3762 * If we are rewinding to the checkpoint update config cache
3765 update_config_cache = B_TRUE;
3768 * Extract the checkpointed uberblock from the current MOS
3769 * and use this as the pool's uberblock from now on. If the
3770 * pool is imported as writeable we also write the checkpoint
3771 * uberblock to the labels, making the rewind permanent.
3773 error = spa_ld_checkpoint_rewind(spa);
3778 * Redo the loading process process again with the
3779 * checkpointed uberblock.
3781 spa_ld_prepare_for_reload(spa);
3782 spa_load_note(spa, "LOADING checkpointed uberblock");
3783 error = spa_ld_mos_with_trusted_config(spa, type, NULL);
3789 * Retrieve the checkpoint txg if the pool has a checkpoint.
3791 error = spa_ld_read_checkpoint_txg(spa);
3796 * Retrieve the mapping of indirect vdevs. Those vdevs were removed
3797 * from the pool and their contents were re-mapped to other vdevs. Note
3798 * that everything that we read before this step must have been
3799 * rewritten on concrete vdevs after the last device removal was
3800 * initiated. Otherwise we could be reading from indirect vdevs before
3801 * we have loaded their mappings.
3803 error = spa_ld_open_indirect_vdev_metadata(spa);
3808 * Retrieve the full list of active features from the MOS and check if
3809 * they are all supported.
3811 error = spa_ld_check_features(spa, &missing_feat_write);
3816 * Load several special directories from the MOS needed by the dsl_pool
3819 error = spa_ld_load_special_directories(spa);
3824 * Retrieve pool properties from the MOS.
3826 error = spa_ld_get_props(spa);
3831 * Retrieve the list of auxiliary devices - cache devices and spares -
3834 error = spa_ld_open_aux_vdevs(spa, type);
3839 * Load the metadata for all vdevs. Also check if unopenable devices
3840 * should be autoreplaced.
3842 error = spa_ld_load_vdev_metadata(spa);
3846 error = spa_ld_load_dedup_tables(spa);
3851 * Verify the logs now to make sure we don't have any unexpected errors
3852 * when we claim log blocks later.
3854 error = spa_ld_verify_logs(spa, type, ereport);
3858 if (missing_feat_write) {
3859 ASSERT(spa->spa_load_state == SPA_LOAD_TRYIMPORT);
3862 * At this point, we know that we can open the pool in
3863 * read-only mode but not read-write mode. We now have enough
3864 * information and can return to userland.
3866 return (spa_vdev_err(spa->spa_root_vdev, VDEV_AUX_UNSUP_FEAT,
3871 * Traverse the last txgs to make sure the pool was left off in a safe
3872 * state. When performing an extreme rewind, we verify the whole pool,
3873 * which can take a very long time.
3875 error = spa_ld_verify_pool_data(spa);
3880 * Calculate the deflated space for the pool. This must be done before
3881 * we write anything to the pool because we'd need to update the space
3882 * accounting using the deflated sizes.
3884 spa_update_dspace(spa);
3887 * We have now retrieved all the information we needed to open the
3888 * pool. If we are importing the pool in read-write mode, a few
3889 * additional steps must be performed to finish the import.
3891 if (spa_writeable(spa) && (spa->spa_load_state == SPA_LOAD_RECOVER ||
3892 spa->spa_load_max_txg == UINT64_MAX)) {
3893 uint64_t config_cache_txg = spa->spa_config_txg;
3895 ASSERT(spa->spa_load_state != SPA_LOAD_TRYIMPORT);
3898 * In case of a checkpoint rewind, log the original txg
3899 * of the checkpointed uberblock.
3901 if (checkpoint_rewind) {
3902 spa_history_log_internal(spa, "checkpoint rewind",
3903 NULL, "rewound state to txg=%llu",
3904 (u_longlong_t)spa->spa_uberblock.ub_checkpoint_txg);
3908 * Traverse the ZIL and claim all blocks.
3910 spa_ld_claim_log_blocks(spa);
3913 * Kick-off the syncing thread.
3915 spa->spa_sync_on = B_TRUE;
3916 txg_sync_start(spa->spa_dsl_pool);
3919 * Wait for all claims to sync. We sync up to the highest
3920 * claimed log block birth time so that claimed log blocks
3921 * don't appear to be from the future. spa_claim_max_txg
3922 * will have been set for us by ZIL traversal operations
3925 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
3928 * Check if we need to request an update of the config. On the
3929 * next sync, we would update the config stored in vdev labels
3930 * and the cachefile (by default /etc/zfs/zpool.cache).
3932 spa_ld_check_for_config_update(spa, config_cache_txg,
3933 update_config_cache);
3936 * Check all DTLs to see if anything needs resilvering.
3938 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
3939 vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL))
3940 spa_async_request(spa, SPA_ASYNC_RESILVER);
3943 * Log the fact that we booted up (so that we can detect if
3944 * we rebooted in the middle of an operation).
3946 spa_history_log_version(spa, "open");
3949 * Delete any inconsistent datasets.
3951 (void) dmu_objset_find(spa_name(spa),
3952 dsl_destroy_inconsistent, NULL, DS_FIND_CHILDREN);
3955 * Clean up any stale temporary dataset userrefs.
3957 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
3959 spa_restart_removal(spa);
3961 spa_spawn_aux_threads(spa);
3963 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3964 vdev_initialize_restart(spa->spa_root_vdev);
3965 spa_config_exit(spa, SCL_CONFIG, FTAG);
3968 spa_load_note(spa, "LOADED");
3974 spa_load_retry(spa_t *spa, spa_load_state_t state)
3976 int mode = spa->spa_mode;
3979 spa_deactivate(spa);
3981 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
3983 spa_activate(spa, mode);
3984 spa_async_suspend(spa);
3986 spa_load_note(spa, "spa_load_retry: rewind, max txg: %llu",
3987 (u_longlong_t)spa->spa_load_max_txg);
3989 return (spa_load(spa, state, SPA_IMPORT_EXISTING));
3993 * If spa_load() fails this function will try loading prior txg's. If
3994 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
3995 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
3996 * function will not rewind the pool and will return the same error as
4000 spa_load_best(spa_t *spa, spa_load_state_t state, uint64_t max_request,
4003 nvlist_t *loadinfo = NULL;
4004 nvlist_t *config = NULL;
4005 int load_error, rewind_error;
4006 uint64_t safe_rewind_txg;
4009 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
4010 spa->spa_load_max_txg = spa->spa_load_txg;
4011 spa_set_log_state(spa, SPA_LOG_CLEAR);
4013 spa->spa_load_max_txg = max_request;
4014 if (max_request != UINT64_MAX)
4015 spa->spa_extreme_rewind = B_TRUE;
4018 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING);
4019 if (load_error == 0)
4021 if (load_error == ZFS_ERR_NO_CHECKPOINT) {
4023 * When attempting checkpoint-rewind on a pool with no
4024 * checkpoint, we should not attempt to load uberblocks
4025 * from previous txgs when spa_load fails.
4027 ASSERT(spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT);
4028 return (load_error);
4031 if (spa->spa_root_vdev != NULL)
4032 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4034 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
4035 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
4037 if (rewind_flags & ZPOOL_NEVER_REWIND) {
4038 nvlist_free(config);
4039 return (load_error);
4042 if (state == SPA_LOAD_RECOVER) {
4043 /* Price of rolling back is discarding txgs, including log */
4044 spa_set_log_state(spa, SPA_LOG_CLEAR);
4047 * If we aren't rolling back save the load info from our first
4048 * import attempt so that we can restore it after attempting
4051 loadinfo = spa->spa_load_info;
4052 spa->spa_load_info = fnvlist_alloc();
4055 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
4056 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
4057 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
4058 TXG_INITIAL : safe_rewind_txg;
4061 * Continue as long as we're finding errors, we're still within
4062 * the acceptable rewind range, and we're still finding uberblocks
4064 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
4065 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
4066 if (spa->spa_load_max_txg < safe_rewind_txg)
4067 spa->spa_extreme_rewind = B_TRUE;
4068 rewind_error = spa_load_retry(spa, state);
4071 spa->spa_extreme_rewind = B_FALSE;
4072 spa->spa_load_max_txg = UINT64_MAX;
4074 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
4075 spa_config_set(spa, config);
4077 nvlist_free(config);
4079 if (state == SPA_LOAD_RECOVER) {
4080 ASSERT3P(loadinfo, ==, NULL);
4081 return (rewind_error);
4083 /* Store the rewind info as part of the initial load info */
4084 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
4085 spa->spa_load_info);
4087 /* Restore the initial load info */
4088 fnvlist_free(spa->spa_load_info);
4089 spa->spa_load_info = loadinfo;
4091 return (load_error);
4098 * The import case is identical to an open except that the configuration is sent
4099 * down from userland, instead of grabbed from the configuration cache. For the
4100 * case of an open, the pool configuration will exist in the
4101 * POOL_STATE_UNINITIALIZED state.
4103 * The stats information (gen/count/ustats) is used to gather vdev statistics at
4104 * the same time open the pool, without having to keep around the spa_t in some
4108 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
4112 spa_load_state_t state = SPA_LOAD_OPEN;
4114 int locked = B_FALSE;
4115 int firstopen = B_FALSE;
4120 * As disgusting as this is, we need to support recursive calls to this
4121 * function because dsl_dir_open() is called during spa_load(), and ends
4122 * up calling spa_open() again. The real fix is to figure out how to
4123 * avoid dsl_dir_open() calling this in the first place.
4125 if (mutex_owner(&spa_namespace_lock) != curthread) {
4126 mutex_enter(&spa_namespace_lock);
4130 if ((spa = spa_lookup(pool)) == NULL) {
4132 mutex_exit(&spa_namespace_lock);
4133 return (SET_ERROR(ENOENT));
4136 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
4137 zpool_load_policy_t policy;
4141 zpool_get_load_policy(nvpolicy ? nvpolicy : spa->spa_config,
4143 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
4144 state = SPA_LOAD_RECOVER;
4146 spa_activate(spa, spa_mode_global);
4148 if (state != SPA_LOAD_RECOVER)
4149 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4150 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
4152 zfs_dbgmsg("spa_open_common: opening %s", pool);
4153 error = spa_load_best(spa, state, policy.zlp_txg,
4156 if (error == EBADF) {
4158 * If vdev_validate() returns failure (indicated by
4159 * EBADF), it indicates that one of the vdevs indicates
4160 * that the pool has been exported or destroyed. If
4161 * this is the case, the config cache is out of sync and
4162 * we should remove the pool from the namespace.
4165 spa_deactivate(spa);
4166 spa_write_cachefile(spa, B_TRUE, B_TRUE);
4169 mutex_exit(&spa_namespace_lock);
4170 return (SET_ERROR(ENOENT));
4175 * We can't open the pool, but we still have useful
4176 * information: the state of each vdev after the
4177 * attempted vdev_open(). Return this to the user.
4179 if (config != NULL && spa->spa_config) {
4180 VERIFY(nvlist_dup(spa->spa_config, config,
4182 VERIFY(nvlist_add_nvlist(*config,
4183 ZPOOL_CONFIG_LOAD_INFO,
4184 spa->spa_load_info) == 0);
4187 spa_deactivate(spa);
4188 spa->spa_last_open_failed = error;
4190 mutex_exit(&spa_namespace_lock);
4196 spa_open_ref(spa, tag);
4199 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4202 * If we've recovered the pool, pass back any information we
4203 * gathered while doing the load.
4205 if (state == SPA_LOAD_RECOVER) {
4206 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
4207 spa->spa_load_info) == 0);
4211 spa->spa_last_open_failed = 0;
4212 spa->spa_last_ubsync_txg = 0;
4213 spa->spa_load_txg = 0;
4214 mutex_exit(&spa_namespace_lock);
4218 zvol_create_minors(spa->spa_name);
4229 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
4232 return (spa_open_common(name, spapp, tag, policy, config));
4236 spa_open(const char *name, spa_t **spapp, void *tag)
4238 return (spa_open_common(name, spapp, tag, NULL, NULL));
4242 * Lookup the given spa_t, incrementing the inject count in the process,
4243 * preventing it from being exported or destroyed.
4246 spa_inject_addref(char *name)
4250 mutex_enter(&spa_namespace_lock);
4251 if ((spa = spa_lookup(name)) == NULL) {
4252 mutex_exit(&spa_namespace_lock);
4255 spa->spa_inject_ref++;
4256 mutex_exit(&spa_namespace_lock);
4262 spa_inject_delref(spa_t *spa)
4264 mutex_enter(&spa_namespace_lock);
4265 spa->spa_inject_ref--;
4266 mutex_exit(&spa_namespace_lock);
4270 * Add spares device information to the nvlist.
4273 spa_add_spares(spa_t *spa, nvlist_t *config)
4283 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4285 if (spa->spa_spares.sav_count == 0)
4288 VERIFY(nvlist_lookup_nvlist(config,
4289 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4290 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
4291 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4293 VERIFY(nvlist_add_nvlist_array(nvroot,
4294 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4295 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4296 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
4299 * Go through and find any spares which have since been
4300 * repurposed as an active spare. If this is the case, update
4301 * their status appropriately.
4303 for (i = 0; i < nspares; i++) {
4304 VERIFY(nvlist_lookup_uint64(spares[i],
4305 ZPOOL_CONFIG_GUID, &guid) == 0);
4306 if (spa_spare_exists(guid, &pool, NULL) &&
4308 VERIFY(nvlist_lookup_uint64_array(
4309 spares[i], ZPOOL_CONFIG_VDEV_STATS,
4310 (uint64_t **)&vs, &vsc) == 0);
4311 vs->vs_state = VDEV_STATE_CANT_OPEN;
4312 vs->vs_aux = VDEV_AUX_SPARED;
4319 * Add l2cache device information to the nvlist, including vdev stats.
4322 spa_add_l2cache(spa_t *spa, nvlist_t *config)
4325 uint_t i, j, nl2cache;
4332 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4334 if (spa->spa_l2cache.sav_count == 0)
4337 VERIFY(nvlist_lookup_nvlist(config,
4338 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4339 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
4340 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4341 if (nl2cache != 0) {
4342 VERIFY(nvlist_add_nvlist_array(nvroot,
4343 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4344 VERIFY(nvlist_lookup_nvlist_array(nvroot,
4345 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
4348 * Update level 2 cache device stats.
4351 for (i = 0; i < nl2cache; i++) {
4352 VERIFY(nvlist_lookup_uint64(l2cache[i],
4353 ZPOOL_CONFIG_GUID, &guid) == 0);
4356 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
4358 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
4359 vd = spa->spa_l2cache.sav_vdevs[j];
4365 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
4366 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
4368 vdev_get_stats(vd, vs);
4374 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
4380 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
4381 VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4383 /* We may be unable to read features if pool is suspended. */
4384 if (spa_suspended(spa))
4387 if (spa->spa_feat_for_read_obj != 0) {
4388 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4389 spa->spa_feat_for_read_obj);
4390 zap_cursor_retrieve(&zc, &za) == 0;
4391 zap_cursor_advance(&zc)) {
4392 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4393 za.za_num_integers == 1);
4394 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4395 za.za_first_integer));
4397 zap_cursor_fini(&zc);
4400 if (spa->spa_feat_for_write_obj != 0) {
4401 for (zap_cursor_init(&zc, spa->spa_meta_objset,
4402 spa->spa_feat_for_write_obj);
4403 zap_cursor_retrieve(&zc, &za) == 0;
4404 zap_cursor_advance(&zc)) {
4405 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
4406 za.za_num_integers == 1);
4407 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
4408 za.za_first_integer));
4410 zap_cursor_fini(&zc);
4414 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
4416 nvlist_free(features);
4420 spa_get_stats(const char *name, nvlist_t **config,
4421 char *altroot, size_t buflen)
4427 error = spa_open_common(name, &spa, FTAG, NULL, config);
4431 * This still leaves a window of inconsistency where the spares
4432 * or l2cache devices could change and the config would be
4433 * self-inconsistent.
4435 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4437 if (*config != NULL) {
4438 uint64_t loadtimes[2];
4440 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
4441 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
4442 VERIFY(nvlist_add_uint64_array(*config,
4443 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
4445 VERIFY(nvlist_add_uint64(*config,
4446 ZPOOL_CONFIG_ERRCOUNT,
4447 spa_get_errlog_size(spa)) == 0);
4449 if (spa_suspended(spa))
4450 VERIFY(nvlist_add_uint64(*config,
4451 ZPOOL_CONFIG_SUSPENDED,
4452 spa->spa_failmode) == 0);
4454 spa_add_spares(spa, *config);
4455 spa_add_l2cache(spa, *config);
4456 spa_add_feature_stats(spa, *config);
4461 * We want to get the alternate root even for faulted pools, so we cheat
4462 * and call spa_lookup() directly.
4466 mutex_enter(&spa_namespace_lock);
4467 spa = spa_lookup(name);
4469 spa_altroot(spa, altroot, buflen);
4473 mutex_exit(&spa_namespace_lock);
4475 spa_altroot(spa, altroot, buflen);
4480 spa_config_exit(spa, SCL_CONFIG, FTAG);
4481 spa_close(spa, FTAG);
4488 * Validate that the auxiliary device array is well formed. We must have an
4489 * array of nvlists, each which describes a valid leaf vdev. If this is an
4490 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
4491 * specified, as long as they are well-formed.
4494 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
4495 spa_aux_vdev_t *sav, const char *config, uint64_t version,
4496 vdev_labeltype_t label)
4503 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4506 * It's acceptable to have no devs specified.
4508 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
4512 return (SET_ERROR(EINVAL));
4515 * Make sure the pool is formatted with a version that supports this
4518 if (spa_version(spa) < version)
4519 return (SET_ERROR(ENOTSUP));
4522 * Set the pending device list so we correctly handle device in-use
4525 sav->sav_pending = dev;
4526 sav->sav_npending = ndev;
4528 for (i = 0; i < ndev; i++) {
4529 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
4533 if (!vd->vdev_ops->vdev_op_leaf) {
4535 error = SET_ERROR(EINVAL);
4540 * The L2ARC currently only supports disk devices in
4541 * kernel context. For user-level testing, we allow it.
4544 if ((strcmp(config, ZPOOL_CONFIG_L2CACHE) == 0) &&
4545 strcmp(vd->vdev_ops->vdev_op_type, VDEV_TYPE_DISK) != 0) {
4546 error = SET_ERROR(ENOTBLK);
4553 if ((error = vdev_open(vd)) == 0 &&
4554 (error = vdev_label_init(vd, crtxg, label)) == 0) {
4555 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
4556 vd->vdev_guid) == 0);
4562 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
4569 sav->sav_pending = NULL;
4570 sav->sav_npending = 0;
4575 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
4579 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4581 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4582 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
4583 VDEV_LABEL_SPARE)) != 0) {
4587 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
4588 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
4589 VDEV_LABEL_L2CACHE));
4593 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
4598 if (sav->sav_config != NULL) {
4604 * Generate new dev list by concatentating with the
4607 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
4608 &olddevs, &oldndevs) == 0);
4610 newdevs = kmem_alloc(sizeof (void *) *
4611 (ndevs + oldndevs), KM_SLEEP);
4612 for (i = 0; i < oldndevs; i++)
4613 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
4615 for (i = 0; i < ndevs; i++)
4616 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
4619 VERIFY(nvlist_remove(sav->sav_config, config,
4620 DATA_TYPE_NVLIST_ARRAY) == 0);
4622 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
4623 config, newdevs, ndevs + oldndevs) == 0);
4624 for (i = 0; i < oldndevs + ndevs; i++)
4625 nvlist_free(newdevs[i]);
4626 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
4629 * Generate a new dev list.
4631 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
4633 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
4639 * Stop and drop level 2 ARC devices
4642 spa_l2cache_drop(spa_t *spa)
4646 spa_aux_vdev_t *sav = &spa->spa_l2cache;
4648 for (i = 0; i < sav->sav_count; i++) {
4651 vd = sav->sav_vdevs[i];
4654 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
4655 pool != 0ULL && l2arc_vdev_present(vd))
4656 l2arc_remove_vdev(vd);
4664 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
4668 char *altroot = NULL;
4673 uint64_t txg = TXG_INITIAL;
4674 nvlist_t **spares, **l2cache;
4675 uint_t nspares, nl2cache;
4676 uint64_t version, obj;
4677 boolean_t has_features;
4681 if (nvlist_lookup_string(props,
4682 zpool_prop_to_name(ZPOOL_PROP_TNAME), &poolname) != 0)
4683 poolname = (char *)pool;
4686 * If this pool already exists, return failure.
4688 mutex_enter(&spa_namespace_lock);
4689 if (spa_lookup(poolname) != NULL) {
4690 mutex_exit(&spa_namespace_lock);
4691 return (SET_ERROR(EEXIST));
4695 * Allocate a new spa_t structure.
4697 nvl = fnvlist_alloc();
4698 fnvlist_add_string(nvl, ZPOOL_CONFIG_POOL_NAME, pool);
4699 (void) nvlist_lookup_string(props,
4700 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4701 spa = spa_add(poolname, nvl, altroot);
4703 spa_activate(spa, spa_mode_global);
4705 if (props && (error = spa_prop_validate(spa, props))) {
4706 spa_deactivate(spa);
4708 mutex_exit(&spa_namespace_lock);
4713 * Temporary pool names should never be written to disk.
4715 if (poolname != pool)
4716 spa->spa_import_flags |= ZFS_IMPORT_TEMP_NAME;
4718 has_features = B_FALSE;
4719 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
4720 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
4721 if (zpool_prop_feature(nvpair_name(elem)))
4722 has_features = B_TRUE;
4725 if (has_features || nvlist_lookup_uint64(props,
4726 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
4727 version = SPA_VERSION;
4729 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
4731 spa->spa_first_txg = txg;
4732 spa->spa_uberblock.ub_txg = txg - 1;
4733 spa->spa_uberblock.ub_version = version;
4734 spa->spa_ubsync = spa->spa_uberblock;
4735 spa->spa_load_state = SPA_LOAD_CREATE;
4736 spa->spa_removing_phys.sr_state = DSS_NONE;
4737 spa->spa_removing_phys.sr_removing_vdev = -1;
4738 spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
4739 spa->spa_indirect_vdevs_loaded = B_TRUE;
4742 * Create "The Godfather" zio to hold all async IOs
4744 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
4746 for (int i = 0; i < max_ncpus; i++) {
4747 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
4748 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
4749 ZIO_FLAG_GODFATHER);
4753 * Create the root vdev.
4755 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4757 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
4759 ASSERT(error != 0 || rvd != NULL);
4760 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
4762 if (error == 0 && !zfs_allocatable_devs(nvroot))
4763 error = SET_ERROR(EINVAL);
4766 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
4767 (error = spa_validate_aux(spa, nvroot, txg,
4768 VDEV_ALLOC_ADD)) == 0) {
4769 for (int c = 0; c < rvd->vdev_children; c++) {
4770 vdev_ashift_optimize(rvd->vdev_child[c]);
4771 vdev_metaslab_set_size(rvd->vdev_child[c]);
4772 vdev_expand(rvd->vdev_child[c], txg);
4776 spa_config_exit(spa, SCL_ALL, FTAG);
4780 spa_deactivate(spa);
4782 mutex_exit(&spa_namespace_lock);
4787 * Get the list of spares, if specified.
4789 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4790 &spares, &nspares) == 0) {
4791 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
4793 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4794 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4795 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4796 spa_load_spares(spa);
4797 spa_config_exit(spa, SCL_ALL, FTAG);
4798 spa->spa_spares.sav_sync = B_TRUE;
4802 * Get the list of level 2 cache devices, if specified.
4804 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4805 &l2cache, &nl2cache) == 0) {
4806 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
4807 NV_UNIQUE_NAME, KM_SLEEP) == 0);
4808 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4809 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4810 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4811 spa_load_l2cache(spa);
4812 spa_config_exit(spa, SCL_ALL, FTAG);
4813 spa->spa_l2cache.sav_sync = B_TRUE;
4816 spa->spa_is_initializing = B_TRUE;
4817 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
4818 spa->spa_meta_objset = dp->dp_meta_objset;
4819 spa->spa_is_initializing = B_FALSE;
4822 * Create DDTs (dedup tables).
4826 spa_update_dspace(spa);
4828 tx = dmu_tx_create_assigned(dp, txg);
4831 * Create the pool config object.
4833 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
4834 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
4835 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
4837 if (zap_add(spa->spa_meta_objset,
4838 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
4839 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
4840 cmn_err(CE_PANIC, "failed to add pool config");
4843 if (spa_version(spa) >= SPA_VERSION_FEATURES)
4844 spa_feature_create_zap_objects(spa, tx);
4846 if (zap_add(spa->spa_meta_objset,
4847 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
4848 sizeof (uint64_t), 1, &version, tx) != 0) {
4849 cmn_err(CE_PANIC, "failed to add pool version");
4852 /* Newly created pools with the right version are always deflated. */
4853 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
4854 spa->spa_deflate = TRUE;
4855 if (zap_add(spa->spa_meta_objset,
4856 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
4857 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
4858 cmn_err(CE_PANIC, "failed to add deflate");
4863 * Create the deferred-free bpobj. Turn off compression
4864 * because sync-to-convergence takes longer if the blocksize
4867 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
4868 dmu_object_set_compress(spa->spa_meta_objset, obj,
4869 ZIO_COMPRESS_OFF, tx);
4870 if (zap_add(spa->spa_meta_objset,
4871 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
4872 sizeof (uint64_t), 1, &obj, tx) != 0) {
4873 cmn_err(CE_PANIC, "failed to add bpobj");
4875 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
4876 spa->spa_meta_objset, obj));
4879 * Create the pool's history object.
4881 if (version >= SPA_VERSION_ZPOOL_HISTORY)
4882 spa_history_create_obj(spa, tx);
4885 * Generate some random noise for salted checksums to operate on.
4887 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
4888 sizeof (spa->spa_cksum_salt.zcs_bytes));
4891 * Set pool properties.
4893 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
4894 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
4895 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
4896 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
4898 if (props != NULL) {
4899 spa_configfile_set(spa, props, B_FALSE);
4900 spa_sync_props(props, tx);
4905 spa->spa_sync_on = B_TRUE;
4906 txg_sync_start(spa->spa_dsl_pool);
4909 * We explicitly wait for the first transaction to complete so that our
4910 * bean counters are appropriately updated.
4912 txg_wait_synced(spa->spa_dsl_pool, txg);
4914 spa_spawn_aux_threads(spa);
4916 spa_write_cachefile(spa, B_FALSE, B_TRUE);
4917 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
4919 spa_history_log_version(spa, "create");
4922 * Don't count references from objsets that are already closed
4923 * and are making their way through the eviction process.
4925 spa_evicting_os_wait(spa);
4926 spa->spa_minref = refcount_count(&spa->spa_refcount);
4927 spa->spa_load_state = SPA_LOAD_NONE;
4929 mutex_exit(&spa_namespace_lock);
4937 * Get the root pool information from the root disk, then import the root pool
4938 * during the system boot up time.
4940 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
4943 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
4946 nvlist_t *nvtop, *nvroot;
4949 if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
4953 * Add this top-level vdev to the child array.
4955 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4957 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4959 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
4962 * Put this pool's top-level vdevs into a root vdev.
4964 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4965 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
4966 VDEV_TYPE_ROOT) == 0);
4967 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
4968 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
4969 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
4973 * Replace the existing vdev_tree with the new root vdev in
4974 * this pool's configuration (remove the old, add the new).
4976 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
4977 nvlist_free(nvroot);
4982 * Walk the vdev tree and see if we can find a device with "better"
4983 * configuration. A configuration is "better" if the label on that
4984 * device has a more recent txg.
4987 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
4989 for (int c = 0; c < vd->vdev_children; c++)
4990 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
4992 if (vd->vdev_ops->vdev_op_leaf) {
4996 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
5000 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
5004 * Do we have a better boot device?
5006 if (label_txg > *txg) {
5015 * Import a root pool.
5017 * For x86. devpath_list will consist of devid and/or physpath name of
5018 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
5019 * The GRUB "findroot" command will return the vdev we should boot.
5021 * For Sparc, devpath_list consists the physpath name of the booting device
5022 * no matter the rootpool is a single device pool or a mirrored pool.
5024 * "/pci@1f,0/ide@d/disk@0,0:a"
5027 spa_import_rootpool(char *devpath, char *devid)
5030 vdev_t *rvd, *bvd, *avd = NULL;
5031 nvlist_t *config, *nvtop;
5037 * Read the label from the boot device and generate a configuration.
5039 config = spa_generate_rootconf(devpath, devid, &guid);
5040 #if defined(_OBP) && defined(_KERNEL)
5041 if (config == NULL) {
5042 if (strstr(devpath, "/iscsi/ssd") != NULL) {
5044 get_iscsi_bootpath_phy(devpath);
5045 config = spa_generate_rootconf(devpath, devid, &guid);
5049 if (config == NULL) {
5050 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
5052 return (SET_ERROR(EIO));
5055 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5057 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
5059 mutex_enter(&spa_namespace_lock);
5060 if ((spa = spa_lookup(pname)) != NULL) {
5062 * Remove the existing root pool from the namespace so that we
5063 * can replace it with the correct config we just read in.
5068 spa = spa_add(pname, config, NULL);
5069 spa->spa_is_root = B_TRUE;
5070 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5071 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5072 &spa->spa_ubsync.ub_version) != 0)
5073 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5076 * Build up a vdev tree based on the boot device's label config.
5078 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5080 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5081 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5082 VDEV_ALLOC_ROOTPOOL);
5083 spa_config_exit(spa, SCL_ALL, FTAG);
5085 mutex_exit(&spa_namespace_lock);
5086 nvlist_free(config);
5087 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5093 * Get the boot vdev.
5095 if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
5096 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
5097 (u_longlong_t)guid);
5098 error = SET_ERROR(ENOENT);
5103 * Determine if there is a better boot device.
5106 spa_alt_rootvdev(rvd, &avd, &txg);
5108 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
5109 "try booting from '%s'", avd->vdev_path);
5110 error = SET_ERROR(EINVAL);
5115 * If the boot device is part of a spare vdev then ensure that
5116 * we're booting off the active spare.
5118 if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
5119 !bvd->vdev_isspare) {
5120 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
5121 "try booting from '%s'",
5123 vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
5124 error = SET_ERROR(EINVAL);
5130 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5132 spa_config_exit(spa, SCL_ALL, FTAG);
5133 mutex_exit(&spa_namespace_lock);
5135 nvlist_free(config);
5139 #else /* !illumos */
5141 extern int vdev_geom_read_pool_label(const char *name, nvlist_t ***configs,
5145 spa_generate_rootconf(const char *name)
5147 nvlist_t **configs, **tops;
5149 nvlist_t *best_cfg, *nvtop, *nvroot;
5158 if (vdev_geom_read_pool_label(name, &configs, &count) != 0)
5161 ASSERT3U(count, !=, 0);
5163 for (i = 0; i < count; i++) {
5166 VERIFY(nvlist_lookup_uint64(configs[i], ZPOOL_CONFIG_POOL_TXG,
5168 if (txg > best_txg) {
5170 best_cfg = configs[i];
5175 nvlist_lookup_uint64(best_cfg, ZPOOL_CONFIG_VDEV_CHILDREN, &nchildren);
5177 nvlist_lookup_uint64_array(best_cfg, ZPOOL_CONFIG_HOLE_ARRAY,
5180 tops = kmem_zalloc(nchildren * sizeof(void *), KM_SLEEP);
5181 for (i = 0; i < nchildren; i++) {
5184 if (configs[i] == NULL)
5186 VERIFY(nvlist_lookup_nvlist(configs[i], ZPOOL_CONFIG_VDEV_TREE,
5188 nvlist_dup(nvtop, &tops[i], KM_SLEEP);
5190 for (i = 0; holes != NULL && i < nholes; i++) {
5193 if (tops[holes[i]] != NULL)
5195 nvlist_alloc(&tops[holes[i]], NV_UNIQUE_NAME, KM_SLEEP);
5196 VERIFY(nvlist_add_string(tops[holes[i]], ZPOOL_CONFIG_TYPE,
5197 VDEV_TYPE_HOLE) == 0);
5198 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_ID,
5200 VERIFY(nvlist_add_uint64(tops[holes[i]], ZPOOL_CONFIG_GUID,
5203 for (i = 0; i < nchildren; i++) {
5204 if (tops[i] != NULL)
5206 nvlist_alloc(&tops[i], NV_UNIQUE_NAME, KM_SLEEP);
5207 VERIFY(nvlist_add_string(tops[i], ZPOOL_CONFIG_TYPE,
5208 VDEV_TYPE_MISSING) == 0);
5209 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_ID,
5211 VERIFY(nvlist_add_uint64(tops[i], ZPOOL_CONFIG_GUID,
5216 * Create pool config based on the best vdev config.
5218 nvlist_dup(best_cfg, &config, KM_SLEEP);
5221 * Put this pool's top-level vdevs into a root vdev.
5223 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5225 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5226 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
5227 VDEV_TYPE_ROOT) == 0);
5228 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
5229 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
5230 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
5231 tops, nchildren) == 0);
5234 * Replace the existing vdev_tree with the new root vdev in
5235 * this pool's configuration (remove the old, add the new).
5237 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
5240 * Drop vdev config elements that should not be present at pool level.
5242 nvlist_remove(config, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64);
5243 nvlist_remove(config, ZPOOL_CONFIG_TOP_GUID, DATA_TYPE_UINT64);
5245 for (i = 0; i < count; i++)
5246 nvlist_free(configs[i]);
5247 kmem_free(configs, count * sizeof(void *));
5248 for (i = 0; i < nchildren; i++)
5249 nvlist_free(tops[i]);
5250 kmem_free(tops, nchildren * sizeof(void *));
5251 nvlist_free(nvroot);
5256 spa_import_rootpool(const char *name)
5259 vdev_t *rvd, *bvd, *avd = NULL;
5260 nvlist_t *config, *nvtop;
5266 * Read the label from the boot device and generate a configuration.
5268 config = spa_generate_rootconf(name);
5270 mutex_enter(&spa_namespace_lock);
5271 if (config != NULL) {
5272 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
5273 &pname) == 0 && strcmp(name, pname) == 0);
5274 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg)
5277 if ((spa = spa_lookup(pname)) != NULL) {
5279 * The pool could already be imported,
5280 * e.g., after reboot -r.
5282 if (spa->spa_state == POOL_STATE_ACTIVE) {
5283 mutex_exit(&spa_namespace_lock);
5284 nvlist_free(config);
5289 * Remove the existing root pool from the namespace so
5290 * that we can replace it with the correct config
5295 spa = spa_add(pname, config, NULL);
5298 * Set spa_ubsync.ub_version as it can be used in vdev_alloc()
5299 * via spa_version().
5301 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
5302 &spa->spa_ubsync.ub_version) != 0)
5303 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
5304 } else if ((spa = spa_lookup(name)) == NULL) {
5305 mutex_exit(&spa_namespace_lock);
5306 nvlist_free(config);
5307 cmn_err(CE_NOTE, "Cannot find the pool label for '%s'",
5311 VERIFY(nvlist_dup(spa->spa_config, &config, KM_SLEEP) == 0);
5313 spa->spa_is_root = B_TRUE;
5314 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
5317 * Build up a vdev tree based on the boot device's label config.
5319 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5321 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5322 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
5323 VDEV_ALLOC_ROOTPOOL);
5324 spa_config_exit(spa, SCL_ALL, FTAG);
5326 mutex_exit(&spa_namespace_lock);
5327 nvlist_free(config);
5328 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
5333 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5335 spa_config_exit(spa, SCL_ALL, FTAG);
5336 mutex_exit(&spa_namespace_lock);
5338 nvlist_free(config);
5342 #endif /* illumos */
5343 #endif /* _KERNEL */
5346 * Import a non-root pool into the system.
5349 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
5352 char *altroot = NULL;
5353 spa_load_state_t state = SPA_LOAD_IMPORT;
5354 zpool_load_policy_t policy;
5355 uint64_t mode = spa_mode_global;
5356 uint64_t readonly = B_FALSE;
5359 nvlist_t **spares, **l2cache;
5360 uint_t nspares, nl2cache;
5363 * If a pool with this name exists, return failure.
5365 mutex_enter(&spa_namespace_lock);
5366 if (spa_lookup(pool) != NULL) {
5367 mutex_exit(&spa_namespace_lock);
5368 return (SET_ERROR(EEXIST));
5372 * Create and initialize the spa structure.
5374 (void) nvlist_lookup_string(props,
5375 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5376 (void) nvlist_lookup_uint64(props,
5377 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
5380 spa = spa_add(pool, config, altroot);
5381 spa->spa_import_flags = flags;
5384 * Verbatim import - Take a pool and insert it into the namespace
5385 * as if it had been loaded at boot.
5387 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
5389 spa_configfile_set(spa, props, B_FALSE);
5391 spa_write_cachefile(spa, B_FALSE, B_TRUE);
5392 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5393 zfs_dbgmsg("spa_import: verbatim import of %s", pool);
5394 mutex_exit(&spa_namespace_lock);
5398 spa_activate(spa, mode);
5401 * Don't start async tasks until we know everything is healthy.
5403 spa_async_suspend(spa);
5405 zpool_get_load_policy(config, &policy);
5406 if (policy.zlp_rewind & ZPOOL_DO_REWIND)
5407 state = SPA_LOAD_RECOVER;
5409 spa->spa_config_source = SPA_CONFIG_SRC_TRYIMPORT;
5411 if (state != SPA_LOAD_RECOVER) {
5412 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
5413 zfs_dbgmsg("spa_import: importing %s", pool);
5415 zfs_dbgmsg("spa_import: importing %s, max_txg=%lld "
5416 "(RECOVERY MODE)", pool, (longlong_t)policy.zlp_txg);
5418 error = spa_load_best(spa, state, policy.zlp_txg, policy.zlp_rewind);
5421 * Propagate anything learned while loading the pool and pass it
5422 * back to caller (i.e. rewind info, missing devices, etc).
5424 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5425 spa->spa_load_info) == 0);
5427 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5429 * Toss any existing sparelist, as it doesn't have any validity
5430 * anymore, and conflicts with spa_has_spare().
5432 if (spa->spa_spares.sav_config) {
5433 nvlist_free(spa->spa_spares.sav_config);
5434 spa->spa_spares.sav_config = NULL;
5435 spa_load_spares(spa);
5437 if (spa->spa_l2cache.sav_config) {
5438 nvlist_free(spa->spa_l2cache.sav_config);
5439 spa->spa_l2cache.sav_config = NULL;
5440 spa_load_l2cache(spa);
5443 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
5446 error = spa_validate_aux(spa, nvroot, -1ULL,
5449 error = spa_validate_aux(spa, nvroot, -1ULL,
5450 VDEV_ALLOC_L2CACHE);
5451 spa_config_exit(spa, SCL_ALL, FTAG);
5454 spa_configfile_set(spa, props, B_FALSE);
5456 if (error != 0 || (props && spa_writeable(spa) &&
5457 (error = spa_prop_set(spa, props)))) {
5459 spa_deactivate(spa);
5461 mutex_exit(&spa_namespace_lock);
5465 spa_async_resume(spa);
5468 * Override any spares and level 2 cache devices as specified by
5469 * the user, as these may have correct device names/devids, etc.
5471 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
5472 &spares, &nspares) == 0) {
5473 if (spa->spa_spares.sav_config)
5474 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
5475 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
5477 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
5478 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5479 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
5480 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
5481 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5482 spa_load_spares(spa);
5483 spa_config_exit(spa, SCL_ALL, FTAG);
5484 spa->spa_spares.sav_sync = B_TRUE;
5486 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
5487 &l2cache, &nl2cache) == 0) {
5488 if (spa->spa_l2cache.sav_config)
5489 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
5490 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
5492 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
5493 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5494 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
5495 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
5496 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5497 spa_load_l2cache(spa);
5498 spa_config_exit(spa, SCL_ALL, FTAG);
5499 spa->spa_l2cache.sav_sync = B_TRUE;
5503 * Check for any removed devices.
5505 if (spa->spa_autoreplace) {
5506 spa_aux_check_removed(&spa->spa_spares);
5507 spa_aux_check_removed(&spa->spa_l2cache);
5510 if (spa_writeable(spa)) {
5512 * Update the config cache to include the newly-imported pool.
5514 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5518 * It's possible that the pool was expanded while it was exported.
5519 * We kick off an async task to handle this for us.
5521 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
5523 spa_history_log_version(spa, "import");
5525 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
5527 mutex_exit(&spa_namespace_lock);
5531 zvol_create_minors(pool);
5538 spa_tryimport(nvlist_t *tryconfig)
5540 nvlist_t *config = NULL;
5541 char *poolname, *cachefile;
5545 zpool_load_policy_t policy;
5547 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
5550 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
5554 * Create and initialize the spa structure.
5556 mutex_enter(&spa_namespace_lock);
5557 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
5558 spa_activate(spa, FREAD);
5561 * Rewind pool if a max txg was provided.
5563 zpool_get_load_policy(spa->spa_config, &policy);
5564 if (policy.zlp_txg != UINT64_MAX) {
5565 spa->spa_load_max_txg = policy.zlp_txg;
5566 spa->spa_extreme_rewind = B_TRUE;
5567 zfs_dbgmsg("spa_tryimport: importing %s, max_txg=%lld",
5568 poolname, (longlong_t)policy.zlp_txg);
5570 zfs_dbgmsg("spa_tryimport: importing %s", poolname);
5573 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_CACHEFILE, &cachefile)
5575 zfs_dbgmsg("spa_tryimport: using cachefile '%s'", cachefile);
5576 spa->spa_config_source = SPA_CONFIG_SRC_CACHEFILE;
5578 spa->spa_config_source = SPA_CONFIG_SRC_SCAN;
5581 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING);
5584 * If 'tryconfig' was at least parsable, return the current config.
5586 if (spa->spa_root_vdev != NULL) {
5587 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
5588 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
5590 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5592 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
5593 spa->spa_uberblock.ub_timestamp) == 0);
5594 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
5595 spa->spa_load_info) == 0);
5598 * If the bootfs property exists on this pool then we
5599 * copy it out so that external consumers can tell which
5600 * pools are bootable.
5602 if ((!error || error == EEXIST) && spa->spa_bootfs) {
5603 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5606 * We have to play games with the name since the
5607 * pool was opened as TRYIMPORT_NAME.
5609 if (dsl_dsobj_to_dsname(spa_name(spa),
5610 spa->spa_bootfs, tmpname) == 0) {
5612 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5614 cp = strchr(tmpname, '/');
5616 (void) strlcpy(dsname, tmpname,
5619 (void) snprintf(dsname, MAXPATHLEN,
5620 "%s/%s", poolname, ++cp);
5622 VERIFY(nvlist_add_string(config,
5623 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
5624 kmem_free(dsname, MAXPATHLEN);
5626 kmem_free(tmpname, MAXPATHLEN);
5630 * Add the list of hot spares and level 2 cache devices.
5632 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5633 spa_add_spares(spa, config);
5634 spa_add_l2cache(spa, config);
5635 spa_config_exit(spa, SCL_CONFIG, FTAG);
5639 spa_deactivate(spa);
5641 mutex_exit(&spa_namespace_lock);
5647 * Pool export/destroy
5649 * The act of destroying or exporting a pool is very simple. We make sure there
5650 * is no more pending I/O and any references to the pool are gone. Then, we
5651 * update the pool state and sync all the labels to disk, removing the
5652 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
5653 * we don't sync the labels or remove the configuration cache.
5656 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
5657 boolean_t force, boolean_t hardforce)
5664 if (!(spa_mode_global & FWRITE))
5665 return (SET_ERROR(EROFS));
5667 mutex_enter(&spa_namespace_lock);
5668 if ((spa = spa_lookup(pool)) == NULL) {
5669 mutex_exit(&spa_namespace_lock);
5670 return (SET_ERROR(ENOENT));
5674 * Put a hold on the pool, drop the namespace lock, stop async tasks,
5675 * reacquire the namespace lock, and see if we can export.
5677 spa_open_ref(spa, FTAG);
5678 mutex_exit(&spa_namespace_lock);
5679 spa_async_suspend(spa);
5680 mutex_enter(&spa_namespace_lock);
5681 spa_close(spa, FTAG);
5684 * The pool will be in core if it's openable,
5685 * in which case we can modify its state.
5687 if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
5690 * Objsets may be open only because they're dirty, so we
5691 * have to force it to sync before checking spa_refcnt.
5693 txg_wait_synced(spa->spa_dsl_pool, 0);
5694 spa_evicting_os_wait(spa);
5697 * A pool cannot be exported or destroyed if there are active
5698 * references. If we are resetting a pool, allow references by
5699 * fault injection handlers.
5701 if (!spa_refcount_zero(spa) ||
5702 (spa->spa_inject_ref != 0 &&
5703 new_state != POOL_STATE_UNINITIALIZED)) {
5704 spa_async_resume(spa);
5705 mutex_exit(&spa_namespace_lock);
5706 return (SET_ERROR(EBUSY));
5710 * A pool cannot be exported if it has an active shared spare.
5711 * This is to prevent other pools stealing the active spare
5712 * from an exported pool. At user's own will, such pool can
5713 * be forcedly exported.
5715 if (!force && new_state == POOL_STATE_EXPORTED &&
5716 spa_has_active_shared_spare(spa)) {
5717 spa_async_resume(spa);
5718 mutex_exit(&spa_namespace_lock);
5719 return (SET_ERROR(EXDEV));
5723 * We're about to export or destroy this pool. Make sure
5724 * we stop all initializtion activity here before we
5725 * set the spa_final_txg. This will ensure that all
5726 * dirty data resulting from the initialization is
5727 * committed to disk before we unload the pool.
5729 if (spa->spa_root_vdev != NULL) {
5730 vdev_initialize_stop_all(spa->spa_root_vdev,
5731 VDEV_INITIALIZE_ACTIVE);
5735 * We want this to be reflected on every label,
5736 * so mark them all dirty. spa_unload() will do the
5737 * final sync that pushes these changes out.
5739 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
5740 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
5741 spa->spa_state = new_state;
5742 spa->spa_final_txg = spa_last_synced_txg(spa) +
5744 vdev_config_dirty(spa->spa_root_vdev);
5745 spa_config_exit(spa, SCL_ALL, FTAG);
5749 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
5751 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
5753 spa_deactivate(spa);
5756 if (oldconfig && spa->spa_config)
5757 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
5759 if (new_state != POOL_STATE_UNINITIALIZED) {
5761 spa_write_cachefile(spa, B_TRUE, B_TRUE);
5764 mutex_exit(&spa_namespace_lock);
5770 * Destroy a storage pool.
5773 spa_destroy(char *pool)
5775 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
5780 * Export a storage pool.
5783 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
5784 boolean_t hardforce)
5786 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
5791 * Similar to spa_export(), this unloads the spa_t without actually removing it
5792 * from the namespace in any way.
5795 spa_reset(char *pool)
5797 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
5802 * ==========================================================================
5803 * Device manipulation
5804 * ==========================================================================
5808 * Add a device to a storage pool.
5811 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
5815 vdev_t *rvd = spa->spa_root_vdev;
5817 nvlist_t **spares, **l2cache;
5818 uint_t nspares, nl2cache;
5820 ASSERT(spa_writeable(spa));
5822 txg = spa_vdev_enter(spa);
5824 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
5825 VDEV_ALLOC_ADD)) != 0)
5826 return (spa_vdev_exit(spa, NULL, txg, error));
5828 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
5830 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
5834 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
5838 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
5839 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5841 if (vd->vdev_children != 0 &&
5842 (error = vdev_create(vd, txg, B_FALSE)) != 0)
5843 return (spa_vdev_exit(spa, vd, txg, error));
5846 * We must validate the spares and l2cache devices after checking the
5847 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
5849 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
5850 return (spa_vdev_exit(spa, vd, txg, error));
5853 * If we are in the middle of a device removal, we can only add
5854 * devices which match the existing devices in the pool.
5855 * If we are in the middle of a removal, or have some indirect
5856 * vdevs, we can not add raidz toplevels.
5858 if (spa->spa_vdev_removal != NULL ||
5859 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
5860 for (int c = 0; c < vd->vdev_children; c++) {
5861 tvd = vd->vdev_child[c];
5862 if (spa->spa_vdev_removal != NULL &&
5863 tvd->vdev_ashift != spa->spa_max_ashift) {
5864 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5866 /* Fail if top level vdev is raidz */
5867 if (tvd->vdev_ops == &vdev_raidz_ops) {
5868 return (spa_vdev_exit(spa, vd, txg, EINVAL));
5871 * Need the top level mirror to be
5872 * a mirror of leaf vdevs only
5874 if (tvd->vdev_ops == &vdev_mirror_ops) {
5875 for (uint64_t cid = 0;
5876 cid < tvd->vdev_children; cid++) {
5877 vdev_t *cvd = tvd->vdev_child[cid];
5878 if (!cvd->vdev_ops->vdev_op_leaf) {
5879 return (spa_vdev_exit(spa, vd,
5887 for (int c = 0; c < vd->vdev_children; c++) {
5890 * Set the vdev id to the first hole, if one exists.
5892 for (id = 0; id < rvd->vdev_children; id++) {
5893 if (rvd->vdev_child[id]->vdev_ishole) {
5894 vdev_free(rvd->vdev_child[id]);
5898 tvd = vd->vdev_child[c];
5899 vdev_remove_child(vd, tvd);
5901 vdev_add_child(rvd, tvd);
5902 vdev_config_dirty(tvd);
5906 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
5907 ZPOOL_CONFIG_SPARES);
5908 spa_load_spares(spa);
5909 spa->spa_spares.sav_sync = B_TRUE;
5912 if (nl2cache != 0) {
5913 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
5914 ZPOOL_CONFIG_L2CACHE);
5915 spa_load_l2cache(spa);
5916 spa->spa_l2cache.sav_sync = B_TRUE;
5920 * We have to be careful when adding new vdevs to an existing pool.
5921 * If other threads start allocating from these vdevs before we
5922 * sync the config cache, and we lose power, then upon reboot we may
5923 * fail to open the pool because there are DVAs that the config cache
5924 * can't translate. Therefore, we first add the vdevs without
5925 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
5926 * and then let spa_config_update() initialize the new metaslabs.
5928 * spa_load() checks for added-but-not-initialized vdevs, so that
5929 * if we lose power at any point in this sequence, the remaining
5930 * steps will be completed the next time we load the pool.
5932 (void) spa_vdev_exit(spa, vd, txg, 0);
5934 mutex_enter(&spa_namespace_lock);
5935 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5936 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
5937 mutex_exit(&spa_namespace_lock);
5943 * Attach a device to a mirror. The arguments are the path to any device
5944 * in the mirror, and the nvroot for the new device. If the path specifies
5945 * a device that is not mirrored, we automatically insert the mirror vdev.
5947 * If 'replacing' is specified, the new device is intended to replace the
5948 * existing device; in this case the two devices are made into their own
5949 * mirror using the 'replacing' vdev, which is functionally identical to
5950 * the mirror vdev (it actually reuses all the same ops) but has a few
5951 * extra rules: you can't attach to it after it's been created, and upon
5952 * completion of resilvering, the first disk (the one being replaced)
5953 * is automatically detached.
5956 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
5958 uint64_t txg, dtl_max_txg;
5959 vdev_t *rvd = spa->spa_root_vdev;
5960 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
5962 char *oldvdpath, *newvdpath;
5966 ASSERT(spa_writeable(spa));
5968 txg = spa_vdev_enter(spa);
5970 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
5972 ASSERT(MUTEX_HELD(&spa_namespace_lock));
5973 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
5974 error = (spa_has_checkpoint(spa)) ?
5975 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
5976 return (spa_vdev_exit(spa, NULL, txg, error));
5979 if (spa->spa_vdev_removal != NULL)
5980 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5983 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5985 if (!oldvd->vdev_ops->vdev_op_leaf)
5986 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5988 pvd = oldvd->vdev_parent;
5990 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
5991 VDEV_ALLOC_ATTACH)) != 0)
5992 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5994 if (newrootvd->vdev_children != 1)
5995 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
5997 newvd = newrootvd->vdev_child[0];
5999 if (!newvd->vdev_ops->vdev_op_leaf)
6000 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
6002 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
6003 return (spa_vdev_exit(spa, newrootvd, txg, error));
6006 * Spares can't replace logs
6008 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
6009 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6013 * For attach, the only allowable parent is a mirror or the root
6016 if (pvd->vdev_ops != &vdev_mirror_ops &&
6017 pvd->vdev_ops != &vdev_root_ops)
6018 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6020 pvops = &vdev_mirror_ops;
6023 * Active hot spares can only be replaced by inactive hot
6026 if (pvd->vdev_ops == &vdev_spare_ops &&
6027 oldvd->vdev_isspare &&
6028 !spa_has_spare(spa, newvd->vdev_guid))
6029 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6032 * If the source is a hot spare, and the parent isn't already a
6033 * spare, then we want to create a new hot spare. Otherwise, we
6034 * want to create a replacing vdev. The user is not allowed to
6035 * attach to a spared vdev child unless the 'isspare' state is
6036 * the same (spare replaces spare, non-spare replaces
6039 if (pvd->vdev_ops == &vdev_replacing_ops &&
6040 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
6041 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6042 } else if (pvd->vdev_ops == &vdev_spare_ops &&
6043 newvd->vdev_isspare != oldvd->vdev_isspare) {
6044 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
6047 if (newvd->vdev_isspare)
6048 pvops = &vdev_spare_ops;
6050 pvops = &vdev_replacing_ops;
6054 * Make sure the new device is big enough.
6056 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
6057 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
6060 * The new device cannot have a higher alignment requirement
6061 * than the top-level vdev.
6063 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
6064 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
6067 * If this is an in-place replacement, update oldvd's path and devid
6068 * to make it distinguishable from newvd, and unopenable from now on.
6070 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
6071 spa_strfree(oldvd->vdev_path);
6072 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
6074 (void) sprintf(oldvd->vdev_path, "%s/%s",
6075 newvd->vdev_path, "old");
6076 if (oldvd->vdev_devid != NULL) {
6077 spa_strfree(oldvd->vdev_devid);
6078 oldvd->vdev_devid = NULL;
6082 /* mark the device being resilvered */
6083 newvd->vdev_resilver_txg = txg;
6086 * If the parent is not a mirror, or if we're replacing, insert the new
6087 * mirror/replacing/spare vdev above oldvd.
6089 if (pvd->vdev_ops != pvops)
6090 pvd = vdev_add_parent(oldvd, pvops);
6092 ASSERT(pvd->vdev_top->vdev_parent == rvd);
6093 ASSERT(pvd->vdev_ops == pvops);
6094 ASSERT(oldvd->vdev_parent == pvd);
6097 * Extract the new device from its root and add it to pvd.
6099 vdev_remove_child(newrootvd, newvd);
6100 newvd->vdev_id = pvd->vdev_children;
6101 newvd->vdev_crtxg = oldvd->vdev_crtxg;
6102 vdev_add_child(pvd, newvd);
6104 tvd = newvd->vdev_top;
6105 ASSERT(pvd->vdev_top == tvd);
6106 ASSERT(tvd->vdev_parent == rvd);
6108 vdev_config_dirty(tvd);
6111 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
6112 * for any dmu_sync-ed blocks. It will propagate upward when
6113 * spa_vdev_exit() calls vdev_dtl_reassess().
6115 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
6117 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
6118 dtl_max_txg - TXG_INITIAL);
6120 if (newvd->vdev_isspare) {
6121 spa_spare_activate(newvd);
6122 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
6125 oldvdpath = spa_strdup(oldvd->vdev_path);
6126 newvdpath = spa_strdup(newvd->vdev_path);
6127 newvd_isspare = newvd->vdev_isspare;
6130 * Mark newvd's DTL dirty in this txg.
6132 vdev_dirty(tvd, VDD_DTL, newvd, txg);
6135 * Schedule the resilver to restart in the future. We do this to
6136 * ensure that dmu_sync-ed blocks have been stitched into the
6137 * respective datasets.
6139 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
6141 if (spa->spa_bootfs)
6142 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
6144 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
6149 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
6151 spa_history_log_internal(spa, "vdev attach", NULL,
6152 "%s vdev=%s %s vdev=%s",
6153 replacing && newvd_isspare ? "spare in" :
6154 replacing ? "replace" : "attach", newvdpath,
6155 replacing ? "for" : "to", oldvdpath);
6157 spa_strfree(oldvdpath);
6158 spa_strfree(newvdpath);
6164 * Detach a device from a mirror or replacing vdev.
6166 * If 'replace_done' is specified, only detach if the parent
6167 * is a replacing vdev.
6170 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
6174 vdev_t *rvd = spa->spa_root_vdev;
6175 vdev_t *vd, *pvd, *cvd, *tvd;
6176 boolean_t unspare = B_FALSE;
6177 uint64_t unspare_guid = 0;
6180 ASSERT(spa_writeable(spa));
6182 txg = spa_vdev_enter(spa);
6184 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6187 * Besides being called directly from the userland through the
6188 * ioctl interface, spa_vdev_detach() can be potentially called
6189 * at the end of spa_vdev_resilver_done().
6191 * In the regular case, when we have a checkpoint this shouldn't
6192 * happen as we never empty the DTLs of a vdev during the scrub
6193 * [see comment in dsl_scan_done()]. Thus spa_vdev_resilvering_done()
6194 * should never get here when we have a checkpoint.
6196 * That said, even in a case when we checkpoint the pool exactly
6197 * as spa_vdev_resilver_done() calls this function everything
6198 * should be fine as the resilver will return right away.
6200 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6201 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6202 error = (spa_has_checkpoint(spa)) ?
6203 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6204 return (spa_vdev_exit(spa, NULL, txg, error));
6208 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
6210 if (!vd->vdev_ops->vdev_op_leaf)
6211 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6213 pvd = vd->vdev_parent;
6216 * If the parent/child relationship is not as expected, don't do it.
6217 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
6218 * vdev that's replacing B with C. The user's intent in replacing
6219 * is to go from M(A,B) to M(A,C). If the user decides to cancel
6220 * the replace by detaching C, the expected behavior is to end up
6221 * M(A,B). But suppose that right after deciding to detach C,
6222 * the replacement of B completes. We would have M(A,C), and then
6223 * ask to detach C, which would leave us with just A -- not what
6224 * the user wanted. To prevent this, we make sure that the
6225 * parent/child relationship hasn't changed -- in this example,
6226 * that C's parent is still the replacing vdev R.
6228 if (pvd->vdev_guid != pguid && pguid != 0)
6229 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6232 * Only 'replacing' or 'spare' vdevs can be replaced.
6234 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
6235 pvd->vdev_ops != &vdev_spare_ops)
6236 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6238 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
6239 spa_version(spa) >= SPA_VERSION_SPARES);
6242 * Only mirror, replacing, and spare vdevs support detach.
6244 if (pvd->vdev_ops != &vdev_replacing_ops &&
6245 pvd->vdev_ops != &vdev_mirror_ops &&
6246 pvd->vdev_ops != &vdev_spare_ops)
6247 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
6250 * If this device has the only valid copy of some data,
6251 * we cannot safely detach it.
6253 if (vdev_dtl_required(vd))
6254 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
6256 ASSERT(pvd->vdev_children >= 2);
6259 * If we are detaching the second disk from a replacing vdev, then
6260 * check to see if we changed the original vdev's path to have "/old"
6261 * at the end in spa_vdev_attach(). If so, undo that change now.
6263 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
6264 vd->vdev_path != NULL) {
6265 size_t len = strlen(vd->vdev_path);
6267 for (int c = 0; c < pvd->vdev_children; c++) {
6268 cvd = pvd->vdev_child[c];
6270 if (cvd == vd || cvd->vdev_path == NULL)
6273 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
6274 strcmp(cvd->vdev_path + len, "/old") == 0) {
6275 spa_strfree(cvd->vdev_path);
6276 cvd->vdev_path = spa_strdup(vd->vdev_path);
6283 * If we are detaching the original disk from a spare, then it implies
6284 * that the spare should become a real disk, and be removed from the
6285 * active spare list for the pool.
6287 if (pvd->vdev_ops == &vdev_spare_ops &&
6289 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
6293 * Erase the disk labels so the disk can be used for other things.
6294 * This must be done after all other error cases are handled,
6295 * but before we disembowel vd (so we can still do I/O to it).
6296 * But if we can't do it, don't treat the error as fatal --
6297 * it may be that the unwritability of the disk is the reason
6298 * it's being detached!
6300 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
6303 * Remove vd from its parent and compact the parent's children.
6305 vdev_remove_child(pvd, vd);
6306 vdev_compact_children(pvd);
6309 * Remember one of the remaining children so we can get tvd below.
6311 cvd = pvd->vdev_child[pvd->vdev_children - 1];
6314 * If we need to remove the remaining child from the list of hot spares,
6315 * do it now, marking the vdev as no longer a spare in the process.
6316 * We must do this before vdev_remove_parent(), because that can
6317 * change the GUID if it creates a new toplevel GUID. For a similar
6318 * reason, we must remove the spare now, in the same txg as the detach;
6319 * otherwise someone could attach a new sibling, change the GUID, and
6320 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
6323 ASSERT(cvd->vdev_isspare);
6324 spa_spare_remove(cvd);
6325 unspare_guid = cvd->vdev_guid;
6326 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
6327 cvd->vdev_unspare = B_TRUE;
6331 * If the parent mirror/replacing vdev only has one child,
6332 * the parent is no longer needed. Remove it from the tree.
6334 if (pvd->vdev_children == 1) {
6335 if (pvd->vdev_ops == &vdev_spare_ops)
6336 cvd->vdev_unspare = B_FALSE;
6337 vdev_remove_parent(cvd);
6342 * We don't set tvd until now because the parent we just removed
6343 * may have been the previous top-level vdev.
6345 tvd = cvd->vdev_top;
6346 ASSERT(tvd->vdev_parent == rvd);
6349 * Reevaluate the parent vdev state.
6351 vdev_propagate_state(cvd);
6354 * If the 'autoexpand' property is set on the pool then automatically
6355 * try to expand the size of the pool. For example if the device we
6356 * just detached was smaller than the others, it may be possible to
6357 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
6358 * first so that we can obtain the updated sizes of the leaf vdevs.
6360 if (spa->spa_autoexpand) {
6362 vdev_expand(tvd, txg);
6365 vdev_config_dirty(tvd);
6368 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
6369 * vd->vdev_detached is set and free vd's DTL object in syncing context.
6370 * But first make sure we're not on any *other* txg's DTL list, to
6371 * prevent vd from being accessed after it's freed.
6373 vdpath = spa_strdup(vd->vdev_path);
6374 for (int t = 0; t < TXG_SIZE; t++)
6375 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
6376 vd->vdev_detached = B_TRUE;
6377 vdev_dirty(tvd, VDD_DTL, vd, txg);
6379 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
6381 /* hang on to the spa before we release the lock */
6382 spa_open_ref(spa, FTAG);
6384 error = spa_vdev_exit(spa, vd, txg, 0);
6386 spa_history_log_internal(spa, "detach", NULL,
6388 spa_strfree(vdpath);
6391 * If this was the removal of the original device in a hot spare vdev,
6392 * then we want to go through and remove the device from the hot spare
6393 * list of every other pool.
6396 spa_t *altspa = NULL;
6398 mutex_enter(&spa_namespace_lock);
6399 while ((altspa = spa_next(altspa)) != NULL) {
6400 if (altspa->spa_state != POOL_STATE_ACTIVE ||
6404 spa_open_ref(altspa, FTAG);
6405 mutex_exit(&spa_namespace_lock);
6406 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
6407 mutex_enter(&spa_namespace_lock);
6408 spa_close(altspa, FTAG);
6410 mutex_exit(&spa_namespace_lock);
6412 /* search the rest of the vdevs for spares to remove */
6413 spa_vdev_resilver_done(spa);
6416 /* all done with the spa; OK to release */
6417 mutex_enter(&spa_namespace_lock);
6418 spa_close(spa, FTAG);
6419 mutex_exit(&spa_namespace_lock);
6425 spa_vdev_initialize(spa_t *spa, uint64_t guid, uint64_t cmd_type)
6428 * We hold the namespace lock through the whole function
6429 * to prevent any changes to the pool while we're starting or
6430 * stopping initialization. The config and state locks are held so that
6431 * we can properly assess the vdev state before we commit to
6432 * the initializing operation.
6434 mutex_enter(&spa_namespace_lock);
6435 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
6437 /* Look up vdev and ensure it's a leaf. */
6438 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
6439 if (vd == NULL || vd->vdev_detached) {
6440 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6441 mutex_exit(&spa_namespace_lock);
6442 return (SET_ERROR(ENODEV));
6443 } else if (!vd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(vd)) {
6444 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6445 mutex_exit(&spa_namespace_lock);
6446 return (SET_ERROR(EINVAL));
6447 } else if (!vdev_writeable(vd)) {
6448 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6449 mutex_exit(&spa_namespace_lock);
6450 return (SET_ERROR(EROFS));
6452 mutex_enter(&vd->vdev_initialize_lock);
6453 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
6456 * When we activate an initialize action we check to see
6457 * if the vdev_initialize_thread is NULL. We do this instead
6458 * of using the vdev_initialize_state since there might be
6459 * a previous initialization process which has completed but
6460 * the thread is not exited.
6462 if (cmd_type == POOL_INITIALIZE_DO &&
6463 (vd->vdev_initialize_thread != NULL ||
6464 vd->vdev_top->vdev_removing)) {
6465 mutex_exit(&vd->vdev_initialize_lock);
6466 mutex_exit(&spa_namespace_lock);
6467 return (SET_ERROR(EBUSY));
6468 } else if (cmd_type == POOL_INITIALIZE_CANCEL &&
6469 (vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE &&
6470 vd->vdev_initialize_state != VDEV_INITIALIZE_SUSPENDED)) {
6471 mutex_exit(&vd->vdev_initialize_lock);
6472 mutex_exit(&spa_namespace_lock);
6473 return (SET_ERROR(ESRCH));
6474 } else if (cmd_type == POOL_INITIALIZE_SUSPEND &&
6475 vd->vdev_initialize_state != VDEV_INITIALIZE_ACTIVE) {
6476 mutex_exit(&vd->vdev_initialize_lock);
6477 mutex_exit(&spa_namespace_lock);
6478 return (SET_ERROR(ESRCH));
6482 case POOL_INITIALIZE_DO:
6483 vdev_initialize(vd);
6485 case POOL_INITIALIZE_CANCEL:
6486 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED);
6488 case POOL_INITIALIZE_SUSPEND:
6489 vdev_initialize_stop(vd, VDEV_INITIALIZE_SUSPENDED);
6492 panic("invalid cmd_type %llu", (unsigned long long)cmd_type);
6494 mutex_exit(&vd->vdev_initialize_lock);
6496 /* Sync out the initializing state */
6497 txg_wait_synced(spa->spa_dsl_pool, 0);
6498 mutex_exit(&spa_namespace_lock);
6505 * Split a set of devices from their mirrors, and create a new pool from them.
6508 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
6509 nvlist_t *props, boolean_t exp)
6512 uint64_t txg, *glist;
6514 uint_t c, children, lastlog;
6515 nvlist_t **child, *nvl, *tmp;
6517 char *altroot = NULL;
6518 vdev_t *rvd, **vml = NULL; /* vdev modify list */
6519 boolean_t activate_slog;
6521 ASSERT(spa_writeable(spa));
6523 txg = spa_vdev_enter(spa);
6525 ASSERT(MUTEX_HELD(&spa_namespace_lock));
6526 if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
6527 error = (spa_has_checkpoint(spa)) ?
6528 ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
6529 return (spa_vdev_exit(spa, NULL, txg, error));
6532 /* clear the log and flush everything up to now */
6533 activate_slog = spa_passivate_log(spa);
6534 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6535 error = spa_reset_logs(spa);
6536 txg = spa_vdev_config_enter(spa);
6539 spa_activate_log(spa);
6542 return (spa_vdev_exit(spa, NULL, txg, error));
6544 /* check new spa name before going any further */
6545 if (spa_lookup(newname) != NULL)
6546 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
6549 * scan through all the children to ensure they're all mirrors
6551 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
6552 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
6554 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6556 /* first, check to ensure we've got the right child count */
6557 rvd = spa->spa_root_vdev;
6559 for (c = 0; c < rvd->vdev_children; c++) {
6560 vdev_t *vd = rvd->vdev_child[c];
6562 /* don't count the holes & logs as children */
6563 if (vd->vdev_islog || !vdev_is_concrete(vd)) {
6571 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
6572 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6574 /* next, ensure no spare or cache devices are part of the split */
6575 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
6576 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
6577 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
6579 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
6580 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
6582 /* then, loop over each vdev and validate it */
6583 for (c = 0; c < children; c++) {
6584 uint64_t is_hole = 0;
6586 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
6590 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
6591 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
6594 error = SET_ERROR(EINVAL);
6599 /* which disk is going to be split? */
6600 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
6602 error = SET_ERROR(EINVAL);
6606 /* look it up in the spa */
6607 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
6608 if (vml[c] == NULL) {
6609 error = SET_ERROR(ENODEV);
6613 /* make sure there's nothing stopping the split */
6614 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
6615 vml[c]->vdev_islog ||
6616 !vdev_is_concrete(vml[c]) ||
6617 vml[c]->vdev_isspare ||
6618 vml[c]->vdev_isl2cache ||
6619 !vdev_writeable(vml[c]) ||
6620 vml[c]->vdev_children != 0 ||
6621 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
6622 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
6623 error = SET_ERROR(EINVAL);
6627 if (vdev_dtl_required(vml[c])) {
6628 error = SET_ERROR(EBUSY);
6632 /* we need certain info from the top level */
6633 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
6634 vml[c]->vdev_top->vdev_ms_array) == 0);
6635 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
6636 vml[c]->vdev_top->vdev_ms_shift) == 0);
6637 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
6638 vml[c]->vdev_top->vdev_asize) == 0);
6639 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
6640 vml[c]->vdev_top->vdev_ashift) == 0);
6642 /* transfer per-vdev ZAPs */
6643 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
6644 VERIFY0(nvlist_add_uint64(child[c],
6645 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
6647 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
6648 VERIFY0(nvlist_add_uint64(child[c],
6649 ZPOOL_CONFIG_VDEV_TOP_ZAP,
6650 vml[c]->vdev_parent->vdev_top_zap));
6654 kmem_free(vml, children * sizeof (vdev_t *));
6655 kmem_free(glist, children * sizeof (uint64_t));
6656 return (spa_vdev_exit(spa, NULL, txg, error));
6659 /* stop writers from using the disks */
6660 for (c = 0; c < children; c++) {
6662 vml[c]->vdev_offline = B_TRUE;
6664 vdev_reopen(spa->spa_root_vdev);
6667 * Temporarily record the splitting vdevs in the spa config. This
6668 * will disappear once the config is regenerated.
6670 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6671 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
6672 glist, children) == 0);
6673 kmem_free(glist, children * sizeof (uint64_t));
6675 mutex_enter(&spa->spa_props_lock);
6676 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
6678 mutex_exit(&spa->spa_props_lock);
6679 spa->spa_config_splitting = nvl;
6680 vdev_config_dirty(spa->spa_root_vdev);
6682 /* configure and create the new pool */
6683 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
6684 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
6685 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
6686 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6687 spa_version(spa)) == 0);
6688 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
6689 spa->spa_config_txg) == 0);
6690 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
6691 spa_generate_guid(NULL)) == 0);
6692 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
6693 (void) nvlist_lookup_string(props,
6694 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
6696 /* add the new pool to the namespace */
6697 newspa = spa_add(newname, config, altroot);
6698 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
6699 newspa->spa_config_txg = spa->spa_config_txg;
6700 spa_set_log_state(newspa, SPA_LOG_CLEAR);
6702 /* release the spa config lock, retaining the namespace lock */
6703 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
6705 if (zio_injection_enabled)
6706 zio_handle_panic_injection(spa, FTAG, 1);
6708 spa_activate(newspa, spa_mode_global);
6709 spa_async_suspend(newspa);
6711 for (c = 0; c < children; c++) {
6712 if (vml[c] != NULL) {
6714 * Temporarily stop the initializing activity. We set
6715 * the state to ACTIVE so that we know to resume
6716 * the initializing once the split has completed.
6718 mutex_enter(&vml[c]->vdev_initialize_lock);
6719 vdev_initialize_stop(vml[c], VDEV_INITIALIZE_ACTIVE);
6720 mutex_exit(&vml[c]->vdev_initialize_lock);
6725 /* mark that we are creating new spa by splitting */
6726 newspa->spa_splitting_newspa = B_TRUE;
6728 newspa->spa_config_source = SPA_CONFIG_SRC_SPLIT;
6730 /* create the new pool from the disks of the original pool */
6731 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE);
6733 newspa->spa_splitting_newspa = B_FALSE;
6738 /* if that worked, generate a real config for the new pool */
6739 if (newspa->spa_root_vdev != NULL) {
6740 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
6741 NV_UNIQUE_NAME, KM_SLEEP) == 0);
6742 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
6743 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
6744 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
6749 if (props != NULL) {
6750 spa_configfile_set(newspa, props, B_FALSE);
6751 error = spa_prop_set(newspa, props);
6756 /* flush everything */
6757 txg = spa_vdev_config_enter(newspa);
6758 vdev_config_dirty(newspa->spa_root_vdev);
6759 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
6761 if (zio_injection_enabled)
6762 zio_handle_panic_injection(spa, FTAG, 2);
6764 spa_async_resume(newspa);
6766 /* finally, update the original pool's config */
6767 txg = spa_vdev_config_enter(spa);
6768 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
6769 error = dmu_tx_assign(tx, TXG_WAIT);
6772 for (c = 0; c < children; c++) {
6773 if (vml[c] != NULL) {
6776 spa_history_log_internal(spa, "detach", tx,
6777 "vdev=%s", vml[c]->vdev_path);
6782 spa->spa_avz_action = AVZ_ACTION_REBUILD;
6783 vdev_config_dirty(spa->spa_root_vdev);
6784 spa->spa_config_splitting = NULL;
6788 (void) spa_vdev_exit(spa, NULL, txg, 0);
6790 if (zio_injection_enabled)
6791 zio_handle_panic_injection(spa, FTAG, 3);
6793 /* split is complete; log a history record */
6794 spa_history_log_internal(newspa, "split", NULL,
6795 "from pool %s", spa_name(spa));
6797 kmem_free(vml, children * sizeof (vdev_t *));
6799 /* if we're not going to mount the filesystems in userland, export */
6801 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
6808 spa_deactivate(newspa);
6811 txg = spa_vdev_config_enter(spa);
6813 /* re-online all offlined disks */
6814 for (c = 0; c < children; c++) {
6816 vml[c]->vdev_offline = B_FALSE;
6819 /* restart initializing disks as necessary */
6820 spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
6822 vdev_reopen(spa->spa_root_vdev);
6824 nvlist_free(spa->spa_config_splitting);
6825 spa->spa_config_splitting = NULL;
6826 (void) spa_vdev_exit(spa, NULL, txg, error);
6828 kmem_free(vml, children * sizeof (vdev_t *));
6833 * Find any device that's done replacing, or a vdev marked 'unspare' that's
6834 * currently spared, so we can detach it.
6837 spa_vdev_resilver_done_hunt(vdev_t *vd)
6839 vdev_t *newvd, *oldvd;
6841 for (int c = 0; c < vd->vdev_children; c++) {
6842 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
6848 * Check for a completed replacement. We always consider the first
6849 * vdev in the list to be the oldest vdev, and the last one to be
6850 * the newest (see spa_vdev_attach() for how that works). In
6851 * the case where the newest vdev is faulted, we will not automatically
6852 * remove it after a resilver completes. This is OK as it will require
6853 * user intervention to determine which disk the admin wishes to keep.
6855 if (vd->vdev_ops == &vdev_replacing_ops) {
6856 ASSERT(vd->vdev_children > 1);
6858 newvd = vd->vdev_child[vd->vdev_children - 1];
6859 oldvd = vd->vdev_child[0];
6861 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
6862 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6863 !vdev_dtl_required(oldvd))
6868 * Check for a completed resilver with the 'unspare' flag set.
6869 * Also potentially update faulted state.
6871 if (vd->vdev_ops == &vdev_spare_ops) {
6872 vdev_t *first = vd->vdev_child[0];
6873 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
6875 if (last->vdev_unspare) {
6878 } else if (first->vdev_unspare) {
6885 if (oldvd != NULL &&
6886 vdev_dtl_empty(newvd, DTL_MISSING) &&
6887 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6888 !vdev_dtl_required(oldvd))
6891 vdev_propagate_state(vd);
6894 * If there are more than two spares attached to a disk,
6895 * and those spares are not required, then we want to
6896 * attempt to free them up now so that they can be used
6897 * by other pools. Once we're back down to a single
6898 * disk+spare, we stop removing them.
6900 if (vd->vdev_children > 2) {
6901 newvd = vd->vdev_child[1];
6903 if (newvd->vdev_isspare && last->vdev_isspare &&
6904 vdev_dtl_empty(last, DTL_MISSING) &&
6905 vdev_dtl_empty(last, DTL_OUTAGE) &&
6906 !vdev_dtl_required(newvd))
6915 spa_vdev_resilver_done(spa_t *spa)
6917 vdev_t *vd, *pvd, *ppvd;
6918 uint64_t guid, sguid, pguid, ppguid;
6920 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6922 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
6923 pvd = vd->vdev_parent;
6924 ppvd = pvd->vdev_parent;
6925 guid = vd->vdev_guid;
6926 pguid = pvd->vdev_guid;
6927 ppguid = ppvd->vdev_guid;
6930 * If we have just finished replacing a hot spared device, then
6931 * we need to detach the parent's first child (the original hot
6934 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
6935 ppvd->vdev_children == 2) {
6936 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
6937 sguid = ppvd->vdev_child[1]->vdev_guid;
6939 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
6941 spa_config_exit(spa, SCL_ALL, FTAG);
6942 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
6944 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
6946 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6949 spa_config_exit(spa, SCL_ALL, FTAG);
6953 * Update the stored path or FRU for this vdev.
6956 spa_vdev_set_common(spa_t *spa, uint64_t guid, const char *value,
6960 boolean_t sync = B_FALSE;
6962 ASSERT(spa_writeable(spa));
6964 spa_vdev_state_enter(spa, SCL_ALL);
6966 if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
6967 return (spa_vdev_state_exit(spa, NULL, ENOENT));
6969 if (!vd->vdev_ops->vdev_op_leaf)
6970 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
6973 if (strcmp(value, vd->vdev_path) != 0) {
6974 spa_strfree(vd->vdev_path);
6975 vd->vdev_path = spa_strdup(value);
6979 if (vd->vdev_fru == NULL) {
6980 vd->vdev_fru = spa_strdup(value);
6982 } else if (strcmp(value, vd->vdev_fru) != 0) {
6983 spa_strfree(vd->vdev_fru);
6984 vd->vdev_fru = spa_strdup(value);
6989 return (spa_vdev_state_exit(spa, sync ? vd : NULL, 0));
6993 spa_vdev_setpath(spa_t *spa, uint64_t guid, const char *newpath)
6995 return (spa_vdev_set_common(spa, guid, newpath, B_TRUE));
6999 spa_vdev_setfru(spa_t *spa, uint64_t guid, const char *newfru)
7001 return (spa_vdev_set_common(spa, guid, newfru, B_FALSE));
7005 * ==========================================================================
7007 * ==========================================================================
7010 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
7012 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7014 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7015 return (SET_ERROR(EBUSY));
7017 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
7021 spa_scan_stop(spa_t *spa)
7023 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7024 if (dsl_scan_resilvering(spa->spa_dsl_pool))
7025 return (SET_ERROR(EBUSY));
7026 return (dsl_scan_cancel(spa->spa_dsl_pool));
7030 spa_scan(spa_t *spa, pool_scan_func_t func)
7032 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
7034 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
7035 return (SET_ERROR(ENOTSUP));
7038 * If a resilver was requested, but there is no DTL on a
7039 * writeable leaf device, we have nothing to do.
7041 if (func == POOL_SCAN_RESILVER &&
7042 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
7043 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
7047 return (dsl_scan(spa->spa_dsl_pool, func));
7051 * ==========================================================================
7052 * SPA async task processing
7053 * ==========================================================================
7057 spa_async_remove(spa_t *spa, vdev_t *vd)
7059 if (vd->vdev_remove_wanted) {
7060 vd->vdev_remove_wanted = B_FALSE;
7061 vd->vdev_delayed_close = B_FALSE;
7062 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
7065 * We want to clear the stats, but we don't want to do a full
7066 * vdev_clear() as that will cause us to throw away
7067 * degraded/faulted state as well as attempt to reopen the
7068 * device, all of which is a waste.
7070 vd->vdev_stat.vs_read_errors = 0;
7071 vd->vdev_stat.vs_write_errors = 0;
7072 vd->vdev_stat.vs_checksum_errors = 0;
7074 vdev_state_dirty(vd->vdev_top);
7075 /* Tell userspace that the vdev is gone. */
7076 zfs_post_remove(spa, vd);
7079 for (int c = 0; c < vd->vdev_children; c++)
7080 spa_async_remove(spa, vd->vdev_child[c]);
7084 spa_async_probe(spa_t *spa, vdev_t *vd)
7086 if (vd->vdev_probe_wanted) {
7087 vd->vdev_probe_wanted = B_FALSE;
7088 vdev_reopen(vd); /* vdev_open() does the actual probe */
7091 for (int c = 0; c < vd->vdev_children; c++)
7092 spa_async_probe(spa, vd->vdev_child[c]);
7096 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
7102 if (!spa->spa_autoexpand)
7105 for (int c = 0; c < vd->vdev_children; c++) {
7106 vdev_t *cvd = vd->vdev_child[c];
7107 spa_async_autoexpand(spa, cvd);
7110 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
7113 physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
7114 (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
7116 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7117 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
7119 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
7120 ESC_ZFS_VDEV_AUTOEXPAND, attr, &eid, DDI_SLEEP);
7123 kmem_free(physpath, MAXPATHLEN);
7127 spa_async_thread(void *arg)
7129 spa_t *spa = (spa_t *)arg;
7132 ASSERT(spa->spa_sync_on);
7134 mutex_enter(&spa->spa_async_lock);
7135 tasks = spa->spa_async_tasks;
7136 spa->spa_async_tasks &= SPA_ASYNC_REMOVE;
7137 mutex_exit(&spa->spa_async_lock);
7140 * See if the config needs to be updated.
7142 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
7143 uint64_t old_space, new_space;
7145 mutex_enter(&spa_namespace_lock);
7146 old_space = metaslab_class_get_space(spa_normal_class(spa));
7147 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
7148 new_space = metaslab_class_get_space(spa_normal_class(spa));
7149 mutex_exit(&spa_namespace_lock);
7152 * If the pool grew as a result of the config update,
7153 * then log an internal history event.
7155 if (new_space != old_space) {
7156 spa_history_log_internal(spa, "vdev online", NULL,
7157 "pool '%s' size: %llu(+%llu)",
7158 spa_name(spa), new_space, new_space - old_space);
7162 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
7163 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7164 spa_async_autoexpand(spa, spa->spa_root_vdev);
7165 spa_config_exit(spa, SCL_CONFIG, FTAG);
7169 * See if any devices need to be probed.
7171 if (tasks & SPA_ASYNC_PROBE) {
7172 spa_vdev_state_enter(spa, SCL_NONE);
7173 spa_async_probe(spa, spa->spa_root_vdev);
7174 (void) spa_vdev_state_exit(spa, NULL, 0);
7178 * If any devices are done replacing, detach them.
7180 if (tasks & SPA_ASYNC_RESILVER_DONE)
7181 spa_vdev_resilver_done(spa);
7184 * Kick off a resilver.
7186 if (tasks & SPA_ASYNC_RESILVER)
7187 dsl_resilver_restart(spa->spa_dsl_pool, 0);
7189 if (tasks & SPA_ASYNC_INITIALIZE_RESTART) {
7190 mutex_enter(&spa_namespace_lock);
7191 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7192 vdev_initialize_restart(spa->spa_root_vdev);
7193 spa_config_exit(spa, SCL_CONFIG, FTAG);
7194 mutex_exit(&spa_namespace_lock);
7198 * Let the world know that we're done.
7200 mutex_enter(&spa->spa_async_lock);
7201 spa->spa_async_thread = NULL;
7202 cv_broadcast(&spa->spa_async_cv);
7203 mutex_exit(&spa->spa_async_lock);
7208 spa_async_thread_vd(void *arg)
7213 mutex_enter(&spa->spa_async_lock);
7214 tasks = spa->spa_async_tasks;
7216 spa->spa_async_tasks &= ~SPA_ASYNC_REMOVE;
7217 mutex_exit(&spa->spa_async_lock);
7220 * See if any devices need to be marked REMOVED.
7222 if (tasks & SPA_ASYNC_REMOVE) {
7223 spa_vdev_state_enter(spa, SCL_NONE);
7224 spa_async_remove(spa, spa->spa_root_vdev);
7225 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
7226 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
7227 for (int i = 0; i < spa->spa_spares.sav_count; i++)
7228 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
7229 (void) spa_vdev_state_exit(spa, NULL, 0);
7233 * Let the world know that we're done.
7235 mutex_enter(&spa->spa_async_lock);
7236 tasks = spa->spa_async_tasks;
7237 if ((tasks & SPA_ASYNC_REMOVE) != 0)
7239 spa->spa_async_thread_vd = NULL;
7240 cv_broadcast(&spa->spa_async_cv);
7241 mutex_exit(&spa->spa_async_lock);
7246 spa_async_suspend(spa_t *spa)
7248 mutex_enter(&spa->spa_async_lock);
7249 spa->spa_async_suspended++;
7250 while (spa->spa_async_thread != NULL ||
7251 spa->spa_async_thread_vd != NULL)
7252 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
7253 mutex_exit(&spa->spa_async_lock);
7255 spa_vdev_remove_suspend(spa);
7257 zthr_t *condense_thread = spa->spa_condense_zthr;
7258 if (condense_thread != NULL && zthr_isrunning(condense_thread))
7259 VERIFY0(zthr_cancel(condense_thread));
7261 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7262 if (discard_thread != NULL && zthr_isrunning(discard_thread))
7263 VERIFY0(zthr_cancel(discard_thread));
7267 spa_async_resume(spa_t *spa)
7269 mutex_enter(&spa->spa_async_lock);
7270 ASSERT(spa->spa_async_suspended != 0);
7271 spa->spa_async_suspended--;
7272 mutex_exit(&spa->spa_async_lock);
7273 spa_restart_removal(spa);
7275 zthr_t *condense_thread = spa->spa_condense_zthr;
7276 if (condense_thread != NULL && !zthr_isrunning(condense_thread))
7277 zthr_resume(condense_thread);
7279 zthr_t *discard_thread = spa->spa_checkpoint_discard_zthr;
7280 if (discard_thread != NULL && !zthr_isrunning(discard_thread))
7281 zthr_resume(discard_thread);
7285 spa_async_tasks_pending(spa_t *spa)
7287 uint_t non_config_tasks;
7289 boolean_t config_task_suspended;
7291 non_config_tasks = spa->spa_async_tasks & ~(SPA_ASYNC_CONFIG_UPDATE |
7293 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
7294 if (spa->spa_ccw_fail_time == 0) {
7295 config_task_suspended = B_FALSE;
7297 config_task_suspended =
7298 (gethrtime() - spa->spa_ccw_fail_time) <
7299 (zfs_ccw_retry_interval * NANOSEC);
7302 return (non_config_tasks || (config_task && !config_task_suspended));
7306 spa_async_dispatch(spa_t *spa)
7308 mutex_enter(&spa->spa_async_lock);
7309 if (spa_async_tasks_pending(spa) &&
7310 !spa->spa_async_suspended &&
7311 spa->spa_async_thread == NULL &&
7313 spa->spa_async_thread = thread_create(NULL, 0,
7314 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
7315 mutex_exit(&spa->spa_async_lock);
7319 spa_async_dispatch_vd(spa_t *spa)
7321 mutex_enter(&spa->spa_async_lock);
7322 if ((spa->spa_async_tasks & SPA_ASYNC_REMOVE) != 0 &&
7323 !spa->spa_async_suspended &&
7324 spa->spa_async_thread_vd == NULL &&
7326 spa->spa_async_thread_vd = thread_create(NULL, 0,
7327 spa_async_thread_vd, spa, 0, &p0, TS_RUN, maxclsyspri);
7328 mutex_exit(&spa->spa_async_lock);
7332 spa_async_request(spa_t *spa, int task)
7334 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
7335 mutex_enter(&spa->spa_async_lock);
7336 spa->spa_async_tasks |= task;
7337 mutex_exit(&spa->spa_async_lock);
7338 spa_async_dispatch_vd(spa);
7342 * ==========================================================================
7343 * SPA syncing routines
7344 * ==========================================================================
7348 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7351 bpobj_enqueue(bpo, bp, tx);
7356 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
7360 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
7361 BP_GET_PSIZE(bp), zio->io_flags));
7366 * Note: this simple function is not inlined to make it easier to dtrace the
7367 * amount of time spent syncing frees.
7370 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
7372 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7373 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
7374 VERIFY(zio_wait(zio) == 0);
7378 * Note: this simple function is not inlined to make it easier to dtrace the
7379 * amount of time spent syncing deferred frees.
7382 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
7384 zio_t *zio = zio_root(spa, NULL, NULL, 0);
7385 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
7386 spa_free_sync_cb, zio, tx), ==, 0);
7387 VERIFY0(zio_wait(zio));
7392 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
7394 char *packed = NULL;
7399 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
7402 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
7403 * information. This avoids the dmu_buf_will_dirty() path and
7404 * saves us a pre-read to get data we don't actually care about.
7406 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
7407 packed = kmem_alloc(bufsize, KM_SLEEP);
7409 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
7411 bzero(packed + nvsize, bufsize - nvsize);
7413 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
7415 kmem_free(packed, bufsize);
7417 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
7418 dmu_buf_will_dirty(db, tx);
7419 *(uint64_t *)db->db_data = nvsize;
7420 dmu_buf_rele(db, FTAG);
7424 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
7425 const char *config, const char *entry)
7435 * Update the MOS nvlist describing the list of available devices.
7436 * spa_validate_aux() will have already made sure this nvlist is
7437 * valid and the vdevs are labeled appropriately.
7439 if (sav->sav_object == 0) {
7440 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
7441 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
7442 sizeof (uint64_t), tx);
7443 VERIFY(zap_update(spa->spa_meta_objset,
7444 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
7445 &sav->sav_object, tx) == 0);
7448 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
7449 if (sav->sav_count == 0) {
7450 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
7452 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
7453 for (i = 0; i < sav->sav_count; i++)
7454 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
7455 B_FALSE, VDEV_CONFIG_L2CACHE);
7456 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
7457 sav->sav_count) == 0);
7458 for (i = 0; i < sav->sav_count; i++)
7459 nvlist_free(list[i]);
7460 kmem_free(list, sav->sav_count * sizeof (void *));
7463 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
7464 nvlist_free(nvroot);
7466 sav->sav_sync = B_FALSE;
7470 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
7471 * The all-vdev ZAP must be empty.
7474 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
7476 spa_t *spa = vd->vdev_spa;
7477 if (vd->vdev_top_zap != 0) {
7478 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7479 vd->vdev_top_zap, tx));
7481 if (vd->vdev_leaf_zap != 0) {
7482 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
7483 vd->vdev_leaf_zap, tx));
7485 for (uint64_t i = 0; i < vd->vdev_children; i++) {
7486 spa_avz_build(vd->vdev_child[i], avz, tx);
7491 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
7496 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
7497 * its config may not be dirty but we still need to build per-vdev ZAPs.
7498 * Similarly, if the pool is being assembled (e.g. after a split), we
7499 * need to rebuild the AVZ although the config may not be dirty.
7501 if (list_is_empty(&spa->spa_config_dirty_list) &&
7502 spa->spa_avz_action == AVZ_ACTION_NONE)
7505 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7507 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
7508 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
7509 spa->spa_all_vdev_zaps != 0);
7511 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
7512 /* Make and build the new AVZ */
7513 uint64_t new_avz = zap_create(spa->spa_meta_objset,
7514 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
7515 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
7517 /* Diff old AVZ with new one */
7521 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7522 spa->spa_all_vdev_zaps);
7523 zap_cursor_retrieve(&zc, &za) == 0;
7524 zap_cursor_advance(&zc)) {
7525 uint64_t vdzap = za.za_first_integer;
7526 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
7529 * ZAP is listed in old AVZ but not in new one;
7532 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
7537 zap_cursor_fini(&zc);
7539 /* Destroy the old AVZ */
7540 VERIFY0(zap_destroy(spa->spa_meta_objset,
7541 spa->spa_all_vdev_zaps, tx));
7543 /* Replace the old AVZ in the dir obj with the new one */
7544 VERIFY0(zap_update(spa->spa_meta_objset,
7545 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
7546 sizeof (new_avz), 1, &new_avz, tx));
7548 spa->spa_all_vdev_zaps = new_avz;
7549 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
7553 /* Walk through the AVZ and destroy all listed ZAPs */
7554 for (zap_cursor_init(&zc, spa->spa_meta_objset,
7555 spa->spa_all_vdev_zaps);
7556 zap_cursor_retrieve(&zc, &za) == 0;
7557 zap_cursor_advance(&zc)) {
7558 uint64_t zap = za.za_first_integer;
7559 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
7562 zap_cursor_fini(&zc);
7564 /* Destroy and unlink the AVZ itself */
7565 VERIFY0(zap_destroy(spa->spa_meta_objset,
7566 spa->spa_all_vdev_zaps, tx));
7567 VERIFY0(zap_remove(spa->spa_meta_objset,
7568 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
7569 spa->spa_all_vdev_zaps = 0;
7572 if (spa->spa_all_vdev_zaps == 0) {
7573 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
7574 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
7575 DMU_POOL_VDEV_ZAP_MAP, tx);
7577 spa->spa_avz_action = AVZ_ACTION_NONE;
7579 /* Create ZAPs for vdevs that don't have them. */
7580 vdev_construct_zaps(spa->spa_root_vdev, tx);
7582 config = spa_config_generate(spa, spa->spa_root_vdev,
7583 dmu_tx_get_txg(tx), B_FALSE);
7586 * If we're upgrading the spa version then make sure that
7587 * the config object gets updated with the correct version.
7589 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
7590 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
7591 spa->spa_uberblock.ub_version);
7593 spa_config_exit(spa, SCL_STATE, FTAG);
7595 nvlist_free(spa->spa_config_syncing);
7596 spa->spa_config_syncing = config;
7598 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
7602 spa_sync_version(void *arg, dmu_tx_t *tx)
7604 uint64_t *versionp = arg;
7605 uint64_t version = *versionp;
7606 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7609 * Setting the version is special cased when first creating the pool.
7611 ASSERT(tx->tx_txg != TXG_INITIAL);
7613 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
7614 ASSERT(version >= spa_version(spa));
7616 spa->spa_uberblock.ub_version = version;
7617 vdev_config_dirty(spa->spa_root_vdev);
7618 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
7622 * Set zpool properties.
7625 spa_sync_props(void *arg, dmu_tx_t *tx)
7627 nvlist_t *nvp = arg;
7628 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
7629 objset_t *mos = spa->spa_meta_objset;
7630 nvpair_t *elem = NULL;
7632 mutex_enter(&spa->spa_props_lock);
7634 while ((elem = nvlist_next_nvpair(nvp, elem))) {
7636 char *strval, *fname;
7638 const char *propname;
7639 zprop_type_t proptype;
7642 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
7643 case ZPOOL_PROP_INVAL:
7645 * We checked this earlier in spa_prop_validate().
7647 ASSERT(zpool_prop_feature(nvpair_name(elem)));
7649 fname = strchr(nvpair_name(elem), '@') + 1;
7650 VERIFY0(zfeature_lookup_name(fname, &fid));
7652 spa_feature_enable(spa, fid, tx);
7653 spa_history_log_internal(spa, "set", tx,
7654 "%s=enabled", nvpair_name(elem));
7657 case ZPOOL_PROP_VERSION:
7658 intval = fnvpair_value_uint64(elem);
7660 * The version is synced seperatly before other
7661 * properties and should be correct by now.
7663 ASSERT3U(spa_version(spa), >=, intval);
7666 case ZPOOL_PROP_ALTROOT:
7668 * 'altroot' is a non-persistent property. It should
7669 * have been set temporarily at creation or import time.
7671 ASSERT(spa->spa_root != NULL);
7674 case ZPOOL_PROP_READONLY:
7675 case ZPOOL_PROP_CACHEFILE:
7677 * 'readonly' and 'cachefile' are also non-persisitent
7681 case ZPOOL_PROP_COMMENT:
7682 strval = fnvpair_value_string(elem);
7683 if (spa->spa_comment != NULL)
7684 spa_strfree(spa->spa_comment);
7685 spa->spa_comment = spa_strdup(strval);
7687 * We need to dirty the configuration on all the vdevs
7688 * so that their labels get updated. It's unnecessary
7689 * to do this for pool creation since the vdev's
7690 * configuratoin has already been dirtied.
7692 if (tx->tx_txg != TXG_INITIAL)
7693 vdev_config_dirty(spa->spa_root_vdev);
7694 spa_history_log_internal(spa, "set", tx,
7695 "%s=%s", nvpair_name(elem), strval);
7699 * Set pool property values in the poolprops mos object.
7701 if (spa->spa_pool_props_object == 0) {
7702 spa->spa_pool_props_object =
7703 zap_create_link(mos, DMU_OT_POOL_PROPS,
7704 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
7708 /* normalize the property name */
7709 propname = zpool_prop_to_name(prop);
7710 proptype = zpool_prop_get_type(prop);
7712 if (nvpair_type(elem) == DATA_TYPE_STRING) {
7713 ASSERT(proptype == PROP_TYPE_STRING);
7714 strval = fnvpair_value_string(elem);
7715 VERIFY0(zap_update(mos,
7716 spa->spa_pool_props_object, propname,
7717 1, strlen(strval) + 1, strval, tx));
7718 spa_history_log_internal(spa, "set", tx,
7719 "%s=%s", nvpair_name(elem), strval);
7720 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
7721 intval = fnvpair_value_uint64(elem);
7723 if (proptype == PROP_TYPE_INDEX) {
7725 VERIFY0(zpool_prop_index_to_string(
7726 prop, intval, &unused));
7728 VERIFY0(zap_update(mos,
7729 spa->spa_pool_props_object, propname,
7730 8, 1, &intval, tx));
7731 spa_history_log_internal(spa, "set", tx,
7732 "%s=%lld", nvpair_name(elem), intval);
7734 ASSERT(0); /* not allowed */
7738 case ZPOOL_PROP_DELEGATION:
7739 spa->spa_delegation = intval;
7741 case ZPOOL_PROP_BOOTFS:
7742 spa->spa_bootfs = intval;
7744 case ZPOOL_PROP_FAILUREMODE:
7745 spa->spa_failmode = intval;
7747 case ZPOOL_PROP_AUTOEXPAND:
7748 spa->spa_autoexpand = intval;
7749 if (tx->tx_txg != TXG_INITIAL)
7750 spa_async_request(spa,
7751 SPA_ASYNC_AUTOEXPAND);
7753 case ZPOOL_PROP_DEDUPDITTO:
7754 spa->spa_dedup_ditto = intval;
7763 mutex_exit(&spa->spa_props_lock);
7767 * Perform one-time upgrade on-disk changes. spa_version() does not
7768 * reflect the new version this txg, so there must be no changes this
7769 * txg to anything that the upgrade code depends on after it executes.
7770 * Therefore this must be called after dsl_pool_sync() does the sync
7774 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
7776 dsl_pool_t *dp = spa->spa_dsl_pool;
7778 ASSERT(spa->spa_sync_pass == 1);
7780 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
7782 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
7783 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
7784 dsl_pool_create_origin(dp, tx);
7786 /* Keeping the origin open increases spa_minref */
7787 spa->spa_minref += 3;
7790 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
7791 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
7792 dsl_pool_upgrade_clones(dp, tx);
7795 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
7796 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
7797 dsl_pool_upgrade_dir_clones(dp, tx);
7799 /* Keeping the freedir open increases spa_minref */
7800 spa->spa_minref += 3;
7803 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
7804 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7805 spa_feature_create_zap_objects(spa, tx);
7809 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
7810 * when possibility to use lz4 compression for metadata was added
7811 * Old pools that have this feature enabled must be upgraded to have
7812 * this feature active
7814 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7815 boolean_t lz4_en = spa_feature_is_enabled(spa,
7816 SPA_FEATURE_LZ4_COMPRESS);
7817 boolean_t lz4_ac = spa_feature_is_active(spa,
7818 SPA_FEATURE_LZ4_COMPRESS);
7820 if (lz4_en && !lz4_ac)
7821 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
7825 * If we haven't written the salt, do so now. Note that the
7826 * feature may not be activated yet, but that's fine since
7827 * the presence of this ZAP entry is backwards compatible.
7829 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7830 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
7831 VERIFY0(zap_add(spa->spa_meta_objset,
7832 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
7833 sizeof (spa->spa_cksum_salt.zcs_bytes),
7834 spa->spa_cksum_salt.zcs_bytes, tx));
7837 rrw_exit(&dp->dp_config_rwlock, FTAG);
7841 vdev_indirect_state_sync_verify(vdev_t *vd)
7843 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
7844 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
7846 if (vd->vdev_ops == &vdev_indirect_ops) {
7847 ASSERT(vim != NULL);
7848 ASSERT(vib != NULL);
7851 if (vdev_obsolete_sm_object(vd) != 0) {
7852 ASSERT(vd->vdev_obsolete_sm != NULL);
7853 ASSERT(vd->vdev_removing ||
7854 vd->vdev_ops == &vdev_indirect_ops);
7855 ASSERT(vdev_indirect_mapping_num_entries(vim) > 0);
7856 ASSERT(vdev_indirect_mapping_bytes_mapped(vim) > 0);
7858 ASSERT3U(vdev_obsolete_sm_object(vd), ==,
7859 space_map_object(vd->vdev_obsolete_sm));
7860 ASSERT3U(vdev_indirect_mapping_bytes_mapped(vim), >=,
7861 space_map_allocated(vd->vdev_obsolete_sm));
7863 ASSERT(vd->vdev_obsolete_segments != NULL);
7866 * Since frees / remaps to an indirect vdev can only
7867 * happen in syncing context, the obsolete segments
7868 * tree must be empty when we start syncing.
7870 ASSERT0(range_tree_space(vd->vdev_obsolete_segments));
7874 * Sync the specified transaction group. New blocks may be dirtied as
7875 * part of the process, so we iterate until it converges.
7878 spa_sync(spa_t *spa, uint64_t txg)
7880 dsl_pool_t *dp = spa->spa_dsl_pool;
7881 objset_t *mos = spa->spa_meta_objset;
7882 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
7883 vdev_t *rvd = spa->spa_root_vdev;
7887 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
7888 zfs_vdev_queue_depth_pct / 100;
7890 VERIFY(spa_writeable(spa));
7893 * Wait for i/os issued in open context that need to complete
7894 * before this txg syncs.
7896 (void) zio_wait(spa->spa_txg_zio[txg & TXG_MASK]);
7897 spa->spa_txg_zio[txg & TXG_MASK] = zio_root(spa, NULL, NULL,
7901 * Lock out configuration changes.
7903 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7905 spa->spa_syncing_txg = txg;
7906 spa->spa_sync_pass = 0;
7908 for (int i = 0; i < spa->spa_alloc_count; i++) {
7909 mutex_enter(&spa->spa_alloc_locks[i]);
7910 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
7911 mutex_exit(&spa->spa_alloc_locks[i]);
7915 * If there are any pending vdev state changes, convert them
7916 * into config changes that go out with this transaction group.
7918 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7919 while (list_head(&spa->spa_state_dirty_list) != NULL) {
7921 * We need the write lock here because, for aux vdevs,
7922 * calling vdev_config_dirty() modifies sav_config.
7923 * This is ugly and will become unnecessary when we
7924 * eliminate the aux vdev wart by integrating all vdevs
7925 * into the root vdev tree.
7927 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7928 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
7929 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
7930 vdev_state_clean(vd);
7931 vdev_config_dirty(vd);
7933 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7934 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
7936 spa_config_exit(spa, SCL_STATE, FTAG);
7938 tx = dmu_tx_create_assigned(dp, txg);
7940 spa->spa_sync_starttime = gethrtime();
7942 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
7943 spa->spa_sync_starttime + spa->spa_deadman_synctime));
7944 #else /* !illumos */
7946 callout_schedule(&spa->spa_deadman_cycid,
7947 hz * spa->spa_deadman_synctime / NANOSEC);
7949 #endif /* illumos */
7952 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
7953 * set spa_deflate if we have no raid-z vdevs.
7955 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
7956 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
7959 for (i = 0; i < rvd->vdev_children; i++) {
7960 vd = rvd->vdev_child[i];
7961 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
7964 if (i == rvd->vdev_children) {
7965 spa->spa_deflate = TRUE;
7966 VERIFY(0 == zap_add(spa->spa_meta_objset,
7967 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
7968 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
7973 * Set the top-level vdev's max queue depth. Evaluate each
7974 * top-level's async write queue depth in case it changed.
7975 * The max queue depth will not change in the middle of syncing
7978 uint64_t slots_per_allocator = 0;
7979 for (int c = 0; c < rvd->vdev_children; c++) {
7980 vdev_t *tvd = rvd->vdev_child[c];
7981 metaslab_group_t *mg = tvd->vdev_mg;
7983 if (mg == NULL || mg->mg_class != spa_normal_class(spa) ||
7984 !metaslab_group_initialized(mg))
7988 * It is safe to do a lock-free check here because only async
7989 * allocations look at mg_max_alloc_queue_depth, and async
7990 * allocations all happen from spa_sync().
7992 for (int i = 0; i < spa->spa_alloc_count; i++)
7993 ASSERT0(refcount_count(&(mg->mg_alloc_queue_depth[i])));
7994 mg->mg_max_alloc_queue_depth = max_queue_depth;
7996 for (int i = 0; i < spa->spa_alloc_count; i++) {
7997 mg->mg_cur_max_alloc_queue_depth[i] =
7998 zfs_vdev_def_queue_depth;
8000 slots_per_allocator += zfs_vdev_def_queue_depth;
8002 metaslab_class_t *mc = spa_normal_class(spa);
8003 for (int i = 0; i < spa->spa_alloc_count; i++) {
8004 ASSERT0(refcount_count(&mc->mc_alloc_slots[i]));
8005 mc->mc_alloc_max_slots[i] = slots_per_allocator;
8007 mc->mc_alloc_throttle_enabled = zio_dva_throttle_enabled;
8009 for (int c = 0; c < rvd->vdev_children; c++) {
8010 vdev_t *vd = rvd->vdev_child[c];
8011 vdev_indirect_state_sync_verify(vd);
8013 if (vdev_indirect_should_condense(vd)) {
8014 spa_condense_indirect_start_sync(vd, tx);
8020 * Iterate to convergence.
8023 int pass = ++spa->spa_sync_pass;
8025 spa_sync_config_object(spa, tx);
8026 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
8027 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
8028 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
8029 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
8030 spa_errlog_sync(spa, txg);
8031 dsl_pool_sync(dp, txg);
8033 if (pass < zfs_sync_pass_deferred_free) {
8034 spa_sync_frees(spa, free_bpl, tx);
8037 * We can not defer frees in pass 1, because
8038 * we sync the deferred frees later in pass 1.
8040 ASSERT3U(pass, >, 1);
8041 bplist_iterate(free_bpl, bpobj_enqueue_cb,
8042 &spa->spa_deferred_bpobj, tx);
8046 dsl_scan_sync(dp, tx);
8048 if (spa->spa_vdev_removal != NULL)
8051 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
8056 spa_sync_upgrades(spa, tx);
8058 spa->spa_uberblock.ub_rootbp.blk_birth);
8060 * Note: We need to check if the MOS is dirty
8061 * because we could have marked the MOS dirty
8062 * without updating the uberblock (e.g. if we
8063 * have sync tasks but no dirty user data). We
8064 * need to check the uberblock's rootbp because
8065 * it is updated if we have synced out dirty
8066 * data (though in this case the MOS will most
8067 * likely also be dirty due to second order
8068 * effects, we don't want to rely on that here).
8070 if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
8071 !dmu_objset_is_dirty(mos, txg)) {
8073 * Nothing changed on the first pass,
8074 * therefore this TXG is a no-op. Avoid
8075 * syncing deferred frees, so that we
8076 * can keep this TXG as a no-op.
8078 ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
8080 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8081 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
8082 ASSERT(txg_list_empty(&dp->dp_early_sync_tasks,
8086 spa_sync_deferred_frees(spa, tx);
8089 } while (dmu_objset_is_dirty(mos, txg));
8091 if (!list_is_empty(&spa->spa_config_dirty_list)) {
8093 * Make sure that the number of ZAPs for all the vdevs matches
8094 * the number of ZAPs in the per-vdev ZAP list. This only gets
8095 * called if the config is dirty; otherwise there may be
8096 * outstanding AVZ operations that weren't completed in
8097 * spa_sync_config_object.
8099 uint64_t all_vdev_zap_entry_count;
8100 ASSERT0(zap_count(spa->spa_meta_objset,
8101 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
8102 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
8103 all_vdev_zap_entry_count);
8106 if (spa->spa_vdev_removal != NULL) {
8107 ASSERT0(spa->spa_vdev_removal->svr_bytes_done[txg & TXG_MASK]);
8111 * Rewrite the vdev configuration (which includes the uberblock)
8112 * to commit the transaction group.
8114 * If there are no dirty vdevs, we sync the uberblock to a few
8115 * random top-level vdevs that are known to be visible in the
8116 * config cache (see spa_vdev_add() for a complete description).
8117 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
8121 * We hold SCL_STATE to prevent vdev open/close/etc.
8122 * while we're attempting to write the vdev labels.
8124 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
8126 if (list_is_empty(&spa->spa_config_dirty_list)) {
8127 vdev_t *svd[SPA_SYNC_MIN_VDEVS] = { NULL };
8129 int children = rvd->vdev_children;
8130 int c0 = spa_get_random(children);
8132 for (int c = 0; c < children; c++) {
8133 vd = rvd->vdev_child[(c0 + c) % children];
8135 /* Stop when revisiting the first vdev */
8136 if (c > 0 && svd[0] == vd)
8139 if (vd->vdev_ms_array == 0 || vd->vdev_islog ||
8140 !vdev_is_concrete(vd))
8143 svd[svdcount++] = vd;
8144 if (svdcount == SPA_SYNC_MIN_VDEVS)
8147 error = vdev_config_sync(svd, svdcount, txg);
8149 error = vdev_config_sync(rvd->vdev_child,
8150 rvd->vdev_children, txg);
8154 spa->spa_last_synced_guid = rvd->vdev_guid;
8156 spa_config_exit(spa, SCL_STATE, FTAG);
8160 zio_suspend(spa, NULL);
8161 zio_resume_wait(spa);
8166 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
8167 #else /* !illumos */
8169 callout_drain(&spa->spa_deadman_cycid);
8171 #endif /* illumos */
8174 * Clear the dirty config list.
8176 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
8177 vdev_config_clean(vd);
8180 * Now that the new config has synced transactionally,
8181 * let it become visible to the config cache.
8183 if (spa->spa_config_syncing != NULL) {
8184 spa_config_set(spa, spa->spa_config_syncing);
8185 spa->spa_config_txg = txg;
8186 spa->spa_config_syncing = NULL;
8189 dsl_pool_sync_done(dp, txg);
8191 for (int i = 0; i < spa->spa_alloc_count; i++) {
8192 mutex_enter(&spa->spa_alloc_locks[i]);
8193 VERIFY0(avl_numnodes(&spa->spa_alloc_trees[i]));
8194 mutex_exit(&spa->spa_alloc_locks[i]);
8198 * Update usable space statistics.
8200 while ((vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
8202 vdev_sync_done(vd, txg);
8204 spa_update_dspace(spa);
8207 * It had better be the case that we didn't dirty anything
8208 * since vdev_config_sync().
8210 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
8211 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
8212 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
8214 while (zfs_pause_spa_sync)
8217 spa->spa_sync_pass = 0;
8220 * Update the last synced uberblock here. We want to do this at
8221 * the end of spa_sync() so that consumers of spa_last_synced_txg()
8222 * will be guaranteed that all the processing associated with
8223 * that txg has been completed.
8225 spa->spa_ubsync = spa->spa_uberblock;
8226 spa_config_exit(spa, SCL_CONFIG, FTAG);
8228 spa_handle_ignored_writes(spa);
8231 * If any async tasks have been requested, kick them off.
8233 spa_async_dispatch(spa);
8234 spa_async_dispatch_vd(spa);
8238 * Sync all pools. We don't want to hold the namespace lock across these
8239 * operations, so we take a reference on the spa_t and drop the lock during the
8243 spa_sync_allpools(void)
8246 mutex_enter(&spa_namespace_lock);
8247 while ((spa = spa_next(spa)) != NULL) {
8248 if (spa_state(spa) != POOL_STATE_ACTIVE ||
8249 !spa_writeable(spa) || spa_suspended(spa))
8251 spa_open_ref(spa, FTAG);
8252 mutex_exit(&spa_namespace_lock);
8253 txg_wait_synced(spa_get_dsl(spa), 0);
8254 mutex_enter(&spa_namespace_lock);
8255 spa_close(spa, FTAG);
8257 mutex_exit(&spa_namespace_lock);
8261 * ==========================================================================
8262 * Miscellaneous routines
8263 * ==========================================================================
8267 * Remove all pools in the system.
8275 * Remove all cached state. All pools should be closed now,
8276 * so every spa in the AVL tree should be unreferenced.
8278 mutex_enter(&spa_namespace_lock);
8279 while ((spa = spa_next(NULL)) != NULL) {
8281 * Stop async tasks. The async thread may need to detach
8282 * a device that's been replaced, which requires grabbing
8283 * spa_namespace_lock, so we must drop it here.
8285 spa_open_ref(spa, FTAG);
8286 mutex_exit(&spa_namespace_lock);
8287 spa_async_suspend(spa);
8288 mutex_enter(&spa_namespace_lock);
8289 spa_close(spa, FTAG);
8291 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
8293 spa_deactivate(spa);
8297 mutex_exit(&spa_namespace_lock);
8301 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
8306 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
8310 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
8311 vd = spa->spa_l2cache.sav_vdevs[i];
8312 if (vd->vdev_guid == guid)
8316 for (i = 0; i < spa->spa_spares.sav_count; i++) {
8317 vd = spa->spa_spares.sav_vdevs[i];
8318 if (vd->vdev_guid == guid)
8327 spa_upgrade(spa_t *spa, uint64_t version)
8329 ASSERT(spa_writeable(spa));
8331 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
8334 * This should only be called for a non-faulted pool, and since a
8335 * future version would result in an unopenable pool, this shouldn't be
8338 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
8339 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
8341 spa->spa_uberblock.ub_version = version;
8342 vdev_config_dirty(spa->spa_root_vdev);
8344 spa_config_exit(spa, SCL_ALL, FTAG);
8346 txg_wait_synced(spa_get_dsl(spa), 0);
8350 spa_has_spare(spa_t *spa, uint64_t guid)
8354 spa_aux_vdev_t *sav = &spa->spa_spares;
8356 for (i = 0; i < sav->sav_count; i++)
8357 if (sav->sav_vdevs[i]->vdev_guid == guid)
8360 for (i = 0; i < sav->sav_npending; i++) {
8361 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
8362 &spareguid) == 0 && spareguid == guid)
8370 * Check if a pool has an active shared spare device.
8371 * Note: reference count of an active spare is 2, as a spare and as a replace
8374 spa_has_active_shared_spare(spa_t *spa)
8378 spa_aux_vdev_t *sav = &spa->spa_spares;
8380 for (i = 0; i < sav->sav_count; i++) {
8381 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
8382 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
8391 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8393 sysevent_t *ev = NULL;
8395 sysevent_attr_list_t *attr = NULL;
8396 sysevent_value_t value;
8398 ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
8402 value.value_type = SE_DATA_TYPE_STRING;
8403 value.value.sv_string = spa_name(spa);
8404 if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
8407 value.value_type = SE_DATA_TYPE_UINT64;
8408 value.value.sv_uint64 = spa_guid(spa);
8409 if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
8413 value.value_type = SE_DATA_TYPE_UINT64;
8414 value.value.sv_uint64 = vd->vdev_guid;
8415 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
8419 if (vd->vdev_path) {
8420 value.value_type = SE_DATA_TYPE_STRING;
8421 value.value.sv_string = vd->vdev_path;
8422 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
8423 &value, SE_SLEEP) != 0)
8428 if (hist_nvl != NULL) {
8429 fnvlist_merge((nvlist_t *)attr, hist_nvl);
8432 if (sysevent_attach_attributes(ev, attr) != 0)
8438 sysevent_free_attr(attr);
8445 spa_event_post(sysevent_t *ev)
8450 (void) log_sysevent(ev, SE_SLEEP, &eid);
8456 spa_event_discard(sysevent_t *ev)
8464 * Post a sysevent corresponding to the given event. The 'name' must be one of
8465 * the event definitions in sys/sysevent/eventdefs.h. The payload will be
8466 * filled in from the spa and (optionally) the vdev and history nvl. This
8467 * doesn't do anything in the userland libzpool, as we don't want consumers to
8468 * misinterpret ztest or zdb as real changes.
8471 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
8473 spa_event_post(spa_event_create(spa, vd, hist_nvl, name));