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 https://opensource.org/licenses/CDDL-1.0.
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]
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2024 by Delphix. All rights reserved.
24 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
26 * Copyright 2013 Saso Kiselkov. All rights reserved.
27 * Copyright (c) 2017 Datto Inc.
28 * Copyright (c) 2017, Intel Corporation.
29 * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
30 * Copyright (c) 2023, Klara Inc.
33 #include <sys/zfs_context.h>
34 #include <sys/zfs_chksum.h>
35 #include <sys/spa_impl.h>
37 #include <sys/zio_checksum.h>
38 #include <sys/zio_compress.h>
40 #include <sys/dmu_tx.h>
43 #include <sys/vdev_impl.h>
44 #include <sys/vdev_initialize.h>
45 #include <sys/vdev_trim.h>
46 #include <sys/vdev_file.h>
47 #include <sys/vdev_raidz.h>
48 #include <sys/metaslab.h>
49 #include <sys/uberblock_impl.h>
52 #include <sys/unique.h>
53 #include <sys/dsl_pool.h>
54 #include <sys/dsl_dir.h>
55 #include <sys/dsl_prop.h>
56 #include <sys/fm/util.h>
57 #include <sys/dsl_scan.h>
58 #include <sys/fs/zfs.h>
59 #include <sys/metaslab_impl.h>
63 #include <sys/kstat.h>
65 #include <sys/btree.h>
66 #include <sys/zfeature.h>
68 #include <sys/zstd/zstd.h>
73 * There are three basic locks for managing spa_t structures:
75 * spa_namespace_lock (global mutex)
77 * This lock must be acquired to do any of the following:
79 * - Lookup a spa_t by name
80 * - Add or remove a spa_t from the namespace
81 * - Increase spa_refcount from non-zero
82 * - Check if spa_refcount is zero
84 * - add/remove/attach/detach devices
85 * - Held for the duration of create/destroy/export
86 * - Held at the start and end of import
88 * It does not need to handle recursion. A create or destroy may
89 * reference objects (files or zvols) in other pools, but by
90 * definition they must have an existing reference, and will never need
91 * to lookup a spa_t by name.
93 * spa_refcount (per-spa zfs_refcount_t protected by mutex)
95 * This reference count keep track of any active users of the spa_t. The
96 * spa_t cannot be destroyed or freed while this is non-zero. Internally,
97 * the refcount is never really 'zero' - opening a pool implicitly keeps
98 * some references in the DMU. Internally we check against spa_minref, but
99 * present the image of a zero/non-zero value to consumers.
101 * spa_config_lock[] (per-spa array of rwlocks)
103 * This protects the spa_t from config changes, and must be held in
104 * the following circumstances:
106 * - RW_READER to perform I/O to the spa
107 * - RW_WRITER to change the vdev config
109 * The locking order is fairly straightforward:
111 * spa_namespace_lock -> spa_refcount
113 * The namespace lock must be acquired to increase the refcount from 0
114 * or to check if it is zero.
116 * spa_refcount -> spa_config_lock[]
118 * There must be at least one valid reference on the spa_t to acquire
121 * spa_namespace_lock -> spa_config_lock[]
123 * The namespace lock must always be taken before the config lock.
126 * The spa_namespace_lock can be acquired directly and is globally visible.
128 * The namespace is manipulated using the following functions, all of which
129 * require the spa_namespace_lock to be held.
131 * spa_lookup() Lookup a spa_t by name.
133 * spa_add() Create a new spa_t in the namespace.
135 * spa_remove() Remove a spa_t from the namespace. This also
136 * frees up any memory associated with the spa_t.
138 * spa_next() Returns the next spa_t in the system, or the
139 * first if NULL is passed.
141 * spa_evict_all() Shutdown and remove all spa_t structures in
144 * spa_guid_exists() Determine whether a pool/device guid exists.
146 * The spa_refcount is manipulated using the following functions:
148 * spa_open_ref() Adds a reference to the given spa_t. Must be
149 * called with spa_namespace_lock held if the
150 * refcount is currently zero.
152 * spa_close() Remove a reference from the spa_t. This will
153 * not free the spa_t or remove it from the
154 * namespace. No locking is required.
156 * spa_refcount_zero() Returns true if the refcount is currently
157 * zero. Must be called with spa_namespace_lock
160 * The spa_config_lock[] is an array of rwlocks, ordered as follows:
161 * SCL_CONFIG > SCL_STATE > SCL_ALLOC > SCL_ZIO > SCL_FREE > SCL_VDEV.
162 * spa_config_lock[] is manipulated with spa_config_{enter,exit,held}().
164 * To read the configuration, it suffices to hold one of these locks as reader.
165 * To modify the configuration, you must hold all locks as writer. To modify
166 * vdev state without altering the vdev tree's topology (e.g. online/offline),
167 * you must hold SCL_STATE and SCL_ZIO as writer.
169 * We use these distinct config locks to avoid recursive lock entry.
170 * For example, spa_sync() (which holds SCL_CONFIG as reader) induces
171 * block allocations (SCL_ALLOC), which may require reading space maps
172 * from disk (dmu_read() -> zio_read() -> SCL_ZIO).
174 * The spa config locks cannot be normal rwlocks because we need the
175 * ability to hand off ownership. For example, SCL_ZIO is acquired
176 * by the issuing thread and later released by an interrupt thread.
177 * They do, however, obey the usual write-wanted semantics to prevent
178 * writer (i.e. system administrator) starvation.
180 * The lock acquisition rules are as follows:
183 * Protects changes to the vdev tree topology, such as vdev
184 * add/remove/attach/detach. Protects the dirty config list
185 * (spa_config_dirty_list) and the set of spares and l2arc devices.
188 * Protects changes to pool state and vdev state, such as vdev
189 * online/offline/fault/degrade/clear. Protects the dirty state list
190 * (spa_state_dirty_list) and global pool state (spa_state).
193 * Protects changes to metaslab groups and classes.
194 * Held as reader by metaslab_alloc() and metaslab_claim().
197 * Held by bp-level zios (those which have no io_vd upon entry)
198 * to prevent changes to the vdev tree. The bp-level zio implicitly
199 * protects all of its vdev child zios, which do not hold SCL_ZIO.
202 * Protects changes to metaslab groups and classes.
203 * Held as reader by metaslab_free(). SCL_FREE is distinct from
204 * SCL_ALLOC, and lower than SCL_ZIO, so that we can safely free
205 * blocks in zio_done() while another i/o that holds either
206 * SCL_ALLOC or SCL_ZIO is waiting for this i/o to complete.
209 * Held as reader to prevent changes to the vdev tree during trivial
210 * inquiries such as bp_get_dsize(). SCL_VDEV is distinct from the
211 * other locks, and lower than all of them, to ensure that it's safe
212 * to acquire regardless of caller context.
214 * In addition, the following rules apply:
216 * (a) spa_props_lock protects pool properties, spa_config and spa_config_list.
217 * The lock ordering is SCL_CONFIG > spa_props_lock.
219 * (b) I/O operations on leaf vdevs. For any zio operation that takes
220 * an explicit vdev_t argument -- such as zio_ioctl(), zio_read_phys(),
221 * or zio_write_phys() -- the caller must ensure that the config cannot
222 * cannot change in the interim, and that the vdev cannot be reopened.
223 * SCL_STATE as reader suffices for both.
225 * The vdev configuration is protected by spa_vdev_enter() / spa_vdev_exit().
227 * spa_vdev_enter() Acquire the namespace lock and the config lock
230 * spa_vdev_exit() Release the config lock, wait for all I/O
231 * to complete, sync the updated configs to the
232 * cache, and release the namespace lock.
234 * vdev state is protected by spa_vdev_state_enter() / spa_vdev_state_exit().
235 * Like spa_vdev_enter/exit, these are convenience wrappers -- the actual
236 * locking is, always, based on spa_namespace_lock and spa_config_lock[].
239 avl_tree_t spa_namespace_avl;
240 kmutex_t spa_namespace_lock;
241 kcondvar_t spa_namespace_cv;
242 static const int spa_max_replication_override = SPA_DVAS_PER_BP;
244 static kmutex_t spa_spare_lock;
245 static avl_tree_t spa_spare_avl;
246 static kmutex_t spa_l2cache_lock;
247 static avl_tree_t spa_l2cache_avl;
249 spa_mode_t spa_mode_global = SPA_MODE_UNINIT;
253 * Everything except dprintf, set_error, spa, and indirect_remap is on
254 * by default in debug builds.
256 int zfs_flags = ~(ZFS_DEBUG_DPRINTF | ZFS_DEBUG_SET_ERROR |
257 ZFS_DEBUG_INDIRECT_REMAP);
263 * zfs_recover can be set to nonzero to attempt to recover from
264 * otherwise-fatal errors, typically caused by on-disk corruption. When
265 * set, calls to zfs_panic_recover() will turn into warning messages.
266 * This should only be used as a last resort, as it typically results
267 * in leaked space, or worse.
269 int zfs_recover = B_FALSE;
272 * If destroy encounters an EIO while reading metadata (e.g. indirect
273 * blocks), space referenced by the missing metadata can not be freed.
274 * Normally this causes the background destroy to become "stalled", as
275 * it is unable to make forward progress. While in this stalled state,
276 * all remaining space to free from the error-encountering filesystem is
277 * "temporarily leaked". Set this flag to cause it to ignore the EIO,
278 * permanently leak the space from indirect blocks that can not be read,
279 * and continue to free everything else that it can.
281 * The default, "stalling" behavior is useful if the storage partially
282 * fails (i.e. some but not all i/os fail), and then later recovers. In
283 * this case, we will be able to continue pool operations while it is
284 * partially failed, and when it recovers, we can continue to free the
285 * space, with no leaks. However, note that this case is actually
288 * Typically pools either (a) fail completely (but perhaps temporarily,
289 * e.g. a top-level vdev going offline), or (b) have localized,
290 * permanent errors (e.g. disk returns the wrong data due to bit flip or
291 * firmware bug). In case (a), this setting does not matter because the
292 * pool will be suspended and the sync thread will not be able to make
293 * forward progress regardless. In case (b), because the error is
294 * permanent, the best we can do is leak the minimum amount of space,
295 * which is what setting this flag will do. Therefore, it is reasonable
296 * for this flag to normally be set, but we chose the more conservative
297 * approach of not setting it, so that there is no possibility of
298 * leaking space in the "partial temporary" failure case.
300 int zfs_free_leak_on_eio = B_FALSE;
303 * Expiration time in milliseconds. This value has two meanings. First it is
304 * used to determine when the spa_deadman() logic should fire. By default the
305 * spa_deadman() will fire if spa_sync() has not completed in 600 seconds.
306 * Secondly, the value determines if an I/O is considered "hung". Any I/O that
307 * has not completed in zfs_deadman_synctime_ms is considered "hung" resulting
308 * in one of three behaviors controlled by zfs_deadman_failmode.
310 uint64_t zfs_deadman_synctime_ms = 600000UL; /* 10 min. */
313 * This value controls the maximum amount of time zio_wait() will block for an
314 * outstanding IO. By default this is 300 seconds at which point the "hung"
315 * behavior will be applied as described for zfs_deadman_synctime_ms.
317 uint64_t zfs_deadman_ziotime_ms = 300000UL; /* 5 min. */
320 * Check time in milliseconds. This defines the frequency at which we check
323 uint64_t zfs_deadman_checktime_ms = 60000UL; /* 1 min. */
326 * By default the deadman is enabled.
328 int zfs_deadman_enabled = B_TRUE;
331 * Controls the behavior of the deadman when it detects a "hung" I/O.
332 * Valid values are zfs_deadman_failmode=<wait|continue|panic>.
334 * wait - Wait for the "hung" I/O (default)
335 * continue - Attempt to recover from a "hung" I/O
336 * panic - Panic the system
338 const char *zfs_deadman_failmode = "wait";
341 * The worst case is single-sector max-parity RAID-Z blocks, in which
342 * case the space requirement is exactly (VDEV_RAIDZ_MAXPARITY + 1)
343 * times the size; so just assume that. Add to this the fact that
344 * we can have up to 3 DVAs per bp, and one more factor of 2 because
345 * the block may be dittoed with up to 3 DVAs by ddt_sync(). All together,
347 * (VDEV_RAIDZ_MAXPARITY + 1) * SPA_DVAS_PER_BP * 2 == 24
349 uint_t spa_asize_inflation = 24;
352 * Normally, we don't allow the last 3.2% (1/(2^spa_slop_shift)) of space in
353 * the pool to be consumed (bounded by spa_max_slop). This ensures that we
354 * don't run the pool completely out of space, due to unaccounted changes (e.g.
355 * to the MOS). It also limits the worst-case time to allocate space. If we
356 * have less than this amount of free space, most ZPL operations (e.g. write,
357 * create) will return ENOSPC. The ZIL metaslabs (spa_embedded_log_class) are
358 * also part of this 3.2% of space which can't be consumed by normal writes;
359 * the slop space "proper" (spa_get_slop_space()) is decreased by the embedded
362 * Certain operations (e.g. file removal, most administrative actions) can
363 * use half the slop space. They will only return ENOSPC if less than half
364 * the slop space is free. Typically, once the pool has less than the slop
365 * space free, the user will use these operations to free up space in the pool.
366 * These are the operations that call dsl_pool_adjustedsize() with the netfree
367 * argument set to TRUE.
369 * Operations that are almost guaranteed to free up space in the absence of
370 * a pool checkpoint can use up to three quarters of the slop space
373 * A very restricted set of operations are always permitted, regardless of
374 * the amount of free space. These are the operations that call
375 * dsl_sync_task(ZFS_SPACE_CHECK_NONE). If these operations result in a net
376 * increase in the amount of space used, it is possible to run the pool
377 * completely out of space, causing it to be permanently read-only.
379 * Note that on very small pools, the slop space will be larger than
380 * 3.2%, in an effort to have it be at least spa_min_slop (128MB),
381 * but we never allow it to be more than half the pool size.
383 * Further, on very large pools, the slop space will be smaller than
384 * 3.2%, to avoid reserving much more space than we actually need; bounded
385 * by spa_max_slop (128GB).
387 * See also the comments in zfs_space_check_t.
389 uint_t spa_slop_shift = 5;
390 static const uint64_t spa_min_slop = 128ULL * 1024 * 1024;
391 static const uint64_t spa_max_slop = 128ULL * 1024 * 1024 * 1024;
394 * Number of allocators to use, per spa instance
396 static int spa_num_allocators = 4;
399 * Spa active allocator.
400 * Valid values are zfs_active_allocator=<dynamic|cursor|new-dynamic>.
402 const char *zfs_active_allocator = "dynamic";
405 spa_load_failed(spa_t *spa, const char *fmt, ...)
411 (void) vsnprintf(buf, sizeof (buf), fmt, adx);
414 zfs_dbgmsg("spa_load(%s, config %s): FAILED: %s", spa->spa_name,
415 spa->spa_trust_config ? "trusted" : "untrusted", buf);
419 spa_load_note(spa_t *spa, const char *fmt, ...)
425 (void) vsnprintf(buf, sizeof (buf), fmt, adx);
428 zfs_dbgmsg("spa_load(%s, config %s): %s", spa->spa_name,
429 spa->spa_trust_config ? "trusted" : "untrusted", buf);
431 spa_import_progress_set_notes_nolog(spa, "%s", buf);
435 * By default dedup and user data indirects land in the special class
437 static int zfs_ddt_data_is_special = B_TRUE;
438 static int zfs_user_indirect_is_special = B_TRUE;
441 * The percentage of special class final space reserved for metadata only.
442 * Once we allocate 100 - zfs_special_class_metadata_reserve_pct we only
443 * let metadata into the class.
445 static uint_t zfs_special_class_metadata_reserve_pct = 25;
448 * ==========================================================================
450 * ==========================================================================
453 spa_config_lock_init(spa_t *spa)
455 for (int i = 0; i < SCL_LOCKS; i++) {
456 spa_config_lock_t *scl = &spa->spa_config_lock[i];
457 mutex_init(&scl->scl_lock, NULL, MUTEX_DEFAULT, NULL);
458 cv_init(&scl->scl_cv, NULL, CV_DEFAULT, NULL);
459 scl->scl_writer = NULL;
460 scl->scl_write_wanted = 0;
466 spa_config_lock_destroy(spa_t *spa)
468 for (int i = 0; i < SCL_LOCKS; i++) {
469 spa_config_lock_t *scl = &spa->spa_config_lock[i];
470 mutex_destroy(&scl->scl_lock);
471 cv_destroy(&scl->scl_cv);
472 ASSERT(scl->scl_writer == NULL);
473 ASSERT(scl->scl_write_wanted == 0);
474 ASSERT(scl->scl_count == 0);
479 spa_config_tryenter(spa_t *spa, int locks, const void *tag, krw_t rw)
481 for (int i = 0; i < SCL_LOCKS; i++) {
482 spa_config_lock_t *scl = &spa->spa_config_lock[i];
483 if (!(locks & (1 << i)))
485 mutex_enter(&scl->scl_lock);
486 if (rw == RW_READER) {
487 if (scl->scl_writer || scl->scl_write_wanted) {
488 mutex_exit(&scl->scl_lock);
489 spa_config_exit(spa, locks & ((1 << i) - 1),
494 ASSERT(scl->scl_writer != curthread);
495 if (scl->scl_count != 0) {
496 mutex_exit(&scl->scl_lock);
497 spa_config_exit(spa, locks & ((1 << i) - 1),
501 scl->scl_writer = curthread;
504 mutex_exit(&scl->scl_lock);
510 spa_config_enter_impl(spa_t *spa, int locks, const void *tag, krw_t rw,
516 ASSERT3U(SCL_LOCKS, <, sizeof (wlocks_held) * NBBY);
518 for (int i = 0; i < SCL_LOCKS; i++) {
519 spa_config_lock_t *scl = &spa->spa_config_lock[i];
520 if (scl->scl_writer == curthread)
521 wlocks_held |= (1 << i);
522 if (!(locks & (1 << i)))
524 mutex_enter(&scl->scl_lock);
525 if (rw == RW_READER) {
526 while (scl->scl_writer ||
527 (!mmp_flag && scl->scl_write_wanted)) {
528 cv_wait(&scl->scl_cv, &scl->scl_lock);
531 ASSERT(scl->scl_writer != curthread);
532 while (scl->scl_count != 0) {
533 scl->scl_write_wanted++;
534 cv_wait(&scl->scl_cv, &scl->scl_lock);
535 scl->scl_write_wanted--;
537 scl->scl_writer = curthread;
540 mutex_exit(&scl->scl_lock);
542 ASSERT3U(wlocks_held, <=, locks);
546 spa_config_enter(spa_t *spa, int locks, const void *tag, krw_t rw)
548 spa_config_enter_impl(spa, locks, tag, rw, 0);
552 * The spa_config_enter_mmp() allows the mmp thread to cut in front of
553 * outstanding write lock requests. This is needed since the mmp updates are
554 * time sensitive and failure to service them promptly will result in a
555 * suspended pool. This pool suspension has been seen in practice when there is
556 * a single disk in a pool that is responding slowly and presumably about to
561 spa_config_enter_mmp(spa_t *spa, int locks, const void *tag, krw_t rw)
563 spa_config_enter_impl(spa, locks, tag, rw, 1);
567 spa_config_exit(spa_t *spa, int locks, const void *tag)
570 for (int i = SCL_LOCKS - 1; i >= 0; i--) {
571 spa_config_lock_t *scl = &spa->spa_config_lock[i];
572 if (!(locks & (1 << i)))
574 mutex_enter(&scl->scl_lock);
575 ASSERT(scl->scl_count > 0);
576 if (--scl->scl_count == 0) {
577 ASSERT(scl->scl_writer == NULL ||
578 scl->scl_writer == curthread);
579 scl->scl_writer = NULL; /* OK in either case */
580 cv_broadcast(&scl->scl_cv);
582 mutex_exit(&scl->scl_lock);
587 spa_config_held(spa_t *spa, int locks, krw_t rw)
591 for (int i = 0; i < SCL_LOCKS; i++) {
592 spa_config_lock_t *scl = &spa->spa_config_lock[i];
593 if (!(locks & (1 << i)))
595 if ((rw == RW_READER && scl->scl_count != 0) ||
596 (rw == RW_WRITER && scl->scl_writer == curthread))
597 locks_held |= 1 << i;
604 * ==========================================================================
605 * SPA namespace functions
606 * ==========================================================================
610 * Lookup the named spa_t in the AVL tree. The spa_namespace_lock must be held.
611 * Returns NULL if no matching spa_t is found.
614 spa_lookup(const char *name)
616 static spa_t search; /* spa_t is large; don't allocate on stack */
621 ASSERT(MUTEX_HELD(&spa_namespace_lock));
624 (void) strlcpy(search.spa_name, name, sizeof (search.spa_name));
627 * If it's a full dataset name, figure out the pool name and
630 cp = strpbrk(search.spa_name, "/@#");
634 spa = avl_find(&spa_namespace_avl, &search, &where);
638 if (spa->spa_load_thread != NULL &&
639 spa->spa_load_thread != curthread) {
640 cv_wait(&spa_namespace_cv, &spa_namespace_lock);
648 * Fires when spa_sync has not completed within zfs_deadman_synctime_ms.
649 * If the zfs_deadman_enabled flag is set then it inspects all vdev queues
650 * looking for potentially hung I/Os.
653 spa_deadman(void *arg)
657 /* Disable the deadman if the pool is suspended. */
658 if (spa_suspended(spa))
661 zfs_dbgmsg("slow spa_sync: started %llu seconds ago, calls %llu",
662 (gethrtime() - spa->spa_sync_starttime) / NANOSEC,
663 (u_longlong_t)++spa->spa_deadman_calls);
664 if (zfs_deadman_enabled)
665 vdev_deadman(spa->spa_root_vdev, FTAG);
667 spa->spa_deadman_tqid = taskq_dispatch_delay(system_delay_taskq,
668 spa_deadman, spa, TQ_SLEEP, ddi_get_lbolt() +
669 MSEC_TO_TICK(zfs_deadman_checktime_ms));
673 spa_log_sm_sort_by_txg(const void *va, const void *vb)
675 const spa_log_sm_t *a = va;
676 const spa_log_sm_t *b = vb;
678 return (TREE_CMP(a->sls_txg, b->sls_txg));
682 * Create an uninitialized spa_t with the given name. Requires
683 * spa_namespace_lock. The caller must ensure that the spa_t doesn't already
684 * exist by calling spa_lookup() first.
687 spa_add(const char *name, nvlist_t *config, const char *altroot)
690 spa_config_dirent_t *dp;
692 ASSERT(MUTEX_HELD(&spa_namespace_lock));
694 spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
696 mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
697 mutex_init(&spa->spa_errlist_lock, NULL, MUTEX_DEFAULT, NULL);
698 mutex_init(&spa->spa_errlog_lock, NULL, MUTEX_DEFAULT, NULL);
699 mutex_init(&spa->spa_evicting_os_lock, NULL, MUTEX_DEFAULT, NULL);
700 mutex_init(&spa->spa_history_lock, NULL, MUTEX_DEFAULT, NULL);
701 mutex_init(&spa->spa_proc_lock, NULL, MUTEX_DEFAULT, NULL);
702 mutex_init(&spa->spa_props_lock, NULL, MUTEX_DEFAULT, NULL);
703 mutex_init(&spa->spa_cksum_tmpls_lock, NULL, MUTEX_DEFAULT, NULL);
704 mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
705 mutex_init(&spa->spa_suspend_lock, NULL, MUTEX_DEFAULT, NULL);
706 mutex_init(&spa->spa_vdev_top_lock, NULL, MUTEX_DEFAULT, NULL);
707 mutex_init(&spa->spa_feat_stats_lock, NULL, MUTEX_DEFAULT, NULL);
708 mutex_init(&spa->spa_flushed_ms_lock, NULL, MUTEX_DEFAULT, NULL);
709 mutex_init(&spa->spa_activities_lock, NULL, MUTEX_DEFAULT, NULL);
711 cv_init(&spa->spa_async_cv, NULL, CV_DEFAULT, NULL);
712 cv_init(&spa->spa_evicting_os_cv, NULL, CV_DEFAULT, NULL);
713 cv_init(&spa->spa_proc_cv, NULL, CV_DEFAULT, NULL);
714 cv_init(&spa->spa_scrub_io_cv, NULL, CV_DEFAULT, NULL);
715 cv_init(&spa->spa_suspend_cv, NULL, CV_DEFAULT, NULL);
716 cv_init(&spa->spa_activities_cv, NULL, CV_DEFAULT, NULL);
717 cv_init(&spa->spa_waiters_cv, NULL, CV_DEFAULT, NULL);
719 for (int t = 0; t < TXG_SIZE; t++)
720 bplist_create(&spa->spa_free_bplist[t]);
722 (void) strlcpy(spa->spa_name, name, sizeof (spa->spa_name));
723 spa->spa_state = POOL_STATE_UNINITIALIZED;
724 spa->spa_freeze_txg = UINT64_MAX;
725 spa->spa_final_txg = UINT64_MAX;
726 spa->spa_load_max_txg = UINT64_MAX;
728 spa->spa_proc_state = SPA_PROC_NONE;
729 spa->spa_trust_config = B_TRUE;
730 spa->spa_hostid = zone_get_hostid(NULL);
732 spa->spa_deadman_synctime = MSEC2NSEC(zfs_deadman_synctime_ms);
733 spa->spa_deadman_ziotime = MSEC2NSEC(zfs_deadman_ziotime_ms);
734 spa_set_deadman_failmode(spa, zfs_deadman_failmode);
735 spa_set_allocator(spa, zfs_active_allocator);
737 zfs_refcount_create(&spa->spa_refcount);
738 spa_config_lock_init(spa);
741 ASSERT(MUTEX_HELD(&spa_namespace_lock));
742 avl_add(&spa_namespace_avl, spa);
745 * Set the alternate root, if there is one.
748 spa->spa_root = spa_strdup(altroot);
750 /* Do not allow more allocators than CPUs. */
751 spa->spa_alloc_count = MIN(MAX(spa_num_allocators, 1), boot_ncpus);
753 spa->spa_allocs = kmem_zalloc(spa->spa_alloc_count *
754 sizeof (spa_alloc_t), KM_SLEEP);
755 for (int i = 0; i < spa->spa_alloc_count; i++) {
756 mutex_init(&spa->spa_allocs[i].spaa_lock, NULL, MUTEX_DEFAULT,
758 avl_create(&spa->spa_allocs[i].spaa_tree, zio_bookmark_compare,
759 sizeof (zio_t), offsetof(zio_t, io_queue_node.a));
762 avl_create(&spa->spa_metaslabs_by_flushed, metaslab_sort_by_flushed,
763 sizeof (metaslab_t), offsetof(metaslab_t, ms_spa_txg_node));
764 avl_create(&spa->spa_sm_logs_by_txg, spa_log_sm_sort_by_txg,
765 sizeof (spa_log_sm_t), offsetof(spa_log_sm_t, sls_node));
766 list_create(&spa->spa_log_summary, sizeof (log_summary_entry_t),
767 offsetof(log_summary_entry_t, lse_node));
770 * Every pool starts with the default cachefile
772 list_create(&spa->spa_config_list, sizeof (spa_config_dirent_t),
773 offsetof(spa_config_dirent_t, scd_link));
775 dp = kmem_zalloc(sizeof (spa_config_dirent_t), KM_SLEEP);
776 dp->scd_path = altroot ? NULL : spa_strdup(spa_config_path);
777 list_insert_head(&spa->spa_config_list, dp);
779 VERIFY(nvlist_alloc(&spa->spa_load_info, NV_UNIQUE_NAME,
782 if (config != NULL) {
785 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_FEATURES_FOR_READ,
787 VERIFY(nvlist_dup(features, &spa->spa_label_features,
791 VERIFY(nvlist_dup(config, &spa->spa_config, 0) == 0);
794 if (spa->spa_label_features == NULL) {
795 VERIFY(nvlist_alloc(&spa->spa_label_features, NV_UNIQUE_NAME,
799 spa->spa_min_ashift = INT_MAX;
800 spa->spa_max_ashift = 0;
801 spa->spa_min_alloc = INT_MAX;
802 spa->spa_gcd_alloc = INT_MAX;
804 /* Reset cached value */
805 spa->spa_dedup_dspace = ~0ULL;
808 * As a pool is being created, treat all features as disabled by
809 * setting SPA_FEATURE_DISABLED for all entries in the feature
812 for (int i = 0; i < SPA_FEATURES; i++) {
813 spa->spa_feat_refcount_cache[i] = SPA_FEATURE_DISABLED;
816 list_create(&spa->spa_leaf_list, sizeof (vdev_t),
817 offsetof(vdev_t, vdev_leaf_node));
823 * Removes a spa_t from the namespace, freeing up any memory used. Requires
824 * spa_namespace_lock. This is called only after the spa_t has been closed and
828 spa_remove(spa_t *spa)
830 spa_config_dirent_t *dp;
832 ASSERT(MUTEX_HELD(&spa_namespace_lock));
833 ASSERT(spa_state(spa) == POOL_STATE_UNINITIALIZED);
834 ASSERT3U(zfs_refcount_count(&spa->spa_refcount), ==, 0);
835 ASSERT0(spa->spa_waiters);
837 nvlist_free(spa->spa_config_splitting);
839 avl_remove(&spa_namespace_avl, spa);
842 spa_strfree(spa->spa_root);
844 while ((dp = list_remove_head(&spa->spa_config_list)) != NULL) {
845 if (dp->scd_path != NULL)
846 spa_strfree(dp->scd_path);
847 kmem_free(dp, sizeof (spa_config_dirent_t));
850 for (int i = 0; i < spa->spa_alloc_count; i++) {
851 avl_destroy(&spa->spa_allocs[i].spaa_tree);
852 mutex_destroy(&spa->spa_allocs[i].spaa_lock);
854 kmem_free(spa->spa_allocs, spa->spa_alloc_count *
855 sizeof (spa_alloc_t));
857 avl_destroy(&spa->spa_metaslabs_by_flushed);
858 avl_destroy(&spa->spa_sm_logs_by_txg);
859 list_destroy(&spa->spa_log_summary);
860 list_destroy(&spa->spa_config_list);
861 list_destroy(&spa->spa_leaf_list);
863 nvlist_free(spa->spa_label_features);
864 nvlist_free(spa->spa_load_info);
865 nvlist_free(spa->spa_feat_stats);
866 spa_config_set(spa, NULL);
868 zfs_refcount_destroy(&spa->spa_refcount);
870 spa_stats_destroy(spa);
871 spa_config_lock_destroy(spa);
873 for (int t = 0; t < TXG_SIZE; t++)
874 bplist_destroy(&spa->spa_free_bplist[t]);
876 zio_checksum_templates_free(spa);
878 cv_destroy(&spa->spa_async_cv);
879 cv_destroy(&spa->spa_evicting_os_cv);
880 cv_destroy(&spa->spa_proc_cv);
881 cv_destroy(&spa->spa_scrub_io_cv);
882 cv_destroy(&spa->spa_suspend_cv);
883 cv_destroy(&spa->spa_activities_cv);
884 cv_destroy(&spa->spa_waiters_cv);
886 mutex_destroy(&spa->spa_flushed_ms_lock);
887 mutex_destroy(&spa->spa_async_lock);
888 mutex_destroy(&spa->spa_errlist_lock);
889 mutex_destroy(&spa->spa_errlog_lock);
890 mutex_destroy(&spa->spa_evicting_os_lock);
891 mutex_destroy(&spa->spa_history_lock);
892 mutex_destroy(&spa->spa_proc_lock);
893 mutex_destroy(&spa->spa_props_lock);
894 mutex_destroy(&spa->spa_cksum_tmpls_lock);
895 mutex_destroy(&spa->spa_scrub_lock);
896 mutex_destroy(&spa->spa_suspend_lock);
897 mutex_destroy(&spa->spa_vdev_top_lock);
898 mutex_destroy(&spa->spa_feat_stats_lock);
899 mutex_destroy(&spa->spa_activities_lock);
901 kmem_free(spa, sizeof (spa_t));
905 * Given a pool, return the next pool in the namespace, or NULL if there is
906 * none. If 'prev' is NULL, return the first pool.
909 spa_next(spa_t *prev)
911 ASSERT(MUTEX_HELD(&spa_namespace_lock));
914 return (AVL_NEXT(&spa_namespace_avl, prev));
916 return (avl_first(&spa_namespace_avl));
920 * ==========================================================================
921 * SPA refcount functions
922 * ==========================================================================
926 * Add a reference to the given spa_t. Must have at least one reference, or
927 * have the namespace lock held.
930 spa_open_ref(spa_t *spa, const void *tag)
932 ASSERT(zfs_refcount_count(&spa->spa_refcount) >= spa->spa_minref ||
933 MUTEX_HELD(&spa_namespace_lock) ||
934 spa->spa_load_thread == curthread);
935 (void) zfs_refcount_add(&spa->spa_refcount, tag);
939 * Remove a reference to the given spa_t. Must have at least one reference, or
940 * have the namespace lock held.
943 spa_close(spa_t *spa, const void *tag)
945 ASSERT(zfs_refcount_count(&spa->spa_refcount) > spa->spa_minref ||
946 MUTEX_HELD(&spa_namespace_lock) ||
947 spa->spa_load_thread == curthread);
948 (void) zfs_refcount_remove(&spa->spa_refcount, tag);
952 * Remove a reference to the given spa_t held by a dsl dir that is
953 * being asynchronously released. Async releases occur from a taskq
954 * performing eviction of dsl datasets and dirs. The namespace lock
955 * isn't held and the hold by the object being evicted may contribute to
956 * spa_minref (e.g. dataset or directory released during pool export),
957 * so the asserts in spa_close() do not apply.
960 spa_async_close(spa_t *spa, const void *tag)
962 (void) zfs_refcount_remove(&spa->spa_refcount, tag);
966 * Check to see if the spa refcount is zero. Must be called with
967 * spa_namespace_lock held. We really compare against spa_minref, which is the
968 * number of references acquired when opening a pool
971 spa_refcount_zero(spa_t *spa)
973 ASSERT(MUTEX_HELD(&spa_namespace_lock));
975 return (zfs_refcount_count(&spa->spa_refcount) == spa->spa_minref);
979 * ==========================================================================
980 * SPA spare and l2cache tracking
981 * ==========================================================================
985 * Hot spares and cache devices are tracked using the same code below,
986 * for 'auxiliary' devices.
989 typedef struct spa_aux {
997 spa_aux_compare(const void *a, const void *b)
999 const spa_aux_t *sa = (const spa_aux_t *)a;
1000 const spa_aux_t *sb = (const spa_aux_t *)b;
1002 return (TREE_CMP(sa->aux_guid, sb->aux_guid));
1006 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
1012 search.aux_guid = vd->vdev_guid;
1013 if ((aux = avl_find(avl, &search, &where)) != NULL) {
1016 aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
1017 aux->aux_guid = vd->vdev_guid;
1019 avl_insert(avl, aux, where);
1024 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
1030 search.aux_guid = vd->vdev_guid;
1031 aux = avl_find(avl, &search, &where);
1033 ASSERT(aux != NULL);
1035 if (--aux->aux_count == 0) {
1036 avl_remove(avl, aux);
1037 kmem_free(aux, sizeof (spa_aux_t));
1038 } else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
1039 aux->aux_pool = 0ULL;
1044 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
1046 spa_aux_t search, *found;
1048 search.aux_guid = guid;
1049 found = avl_find(avl, &search, NULL);
1053 *pool = found->aux_pool;
1060 *refcnt = found->aux_count;
1065 return (found != NULL);
1069 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
1071 spa_aux_t search, *found;
1074 search.aux_guid = vd->vdev_guid;
1075 found = avl_find(avl, &search, &where);
1076 ASSERT(found != NULL);
1077 ASSERT(found->aux_pool == 0ULL);
1079 found->aux_pool = spa_guid(vd->vdev_spa);
1083 * Spares are tracked globally due to the following constraints:
1085 * - A spare may be part of multiple pools.
1086 * - A spare may be added to a pool even if it's actively in use within
1088 * - A spare in use in any pool can only be the source of a replacement if
1089 * the target is a spare in the same pool.
1091 * We keep track of all spares on the system through the use of a reference
1092 * counted AVL tree. When a vdev is added as a spare, or used as a replacement
1093 * spare, then we bump the reference count in the AVL tree. In addition, we set
1094 * the 'vdev_isspare' member to indicate that the device is a spare (active or
1095 * inactive). When a spare is made active (used to replace a device in the
1096 * pool), we also keep track of which pool its been made a part of.
1098 * The 'spa_spare_lock' protects the AVL tree. These functions are normally
1099 * called under the spa_namespace lock as part of vdev reconfiguration. The
1100 * separate spare lock exists for the status query path, which does not need to
1101 * be completely consistent with respect to other vdev configuration changes.
1105 spa_spare_compare(const void *a, const void *b)
1107 return (spa_aux_compare(a, b));
1111 spa_spare_add(vdev_t *vd)
1113 mutex_enter(&spa_spare_lock);
1114 ASSERT(!vd->vdev_isspare);
1115 spa_aux_add(vd, &spa_spare_avl);
1116 vd->vdev_isspare = B_TRUE;
1117 mutex_exit(&spa_spare_lock);
1121 spa_spare_remove(vdev_t *vd)
1123 mutex_enter(&spa_spare_lock);
1124 ASSERT(vd->vdev_isspare);
1125 spa_aux_remove(vd, &spa_spare_avl);
1126 vd->vdev_isspare = B_FALSE;
1127 mutex_exit(&spa_spare_lock);
1131 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
1135 mutex_enter(&spa_spare_lock);
1136 found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
1137 mutex_exit(&spa_spare_lock);
1143 spa_spare_activate(vdev_t *vd)
1145 mutex_enter(&spa_spare_lock);
1146 ASSERT(vd->vdev_isspare);
1147 spa_aux_activate(vd, &spa_spare_avl);
1148 mutex_exit(&spa_spare_lock);
1152 * Level 2 ARC devices are tracked globally for the same reasons as spares.
1153 * Cache devices currently only support one pool per cache device, and so
1154 * for these devices the aux reference count is currently unused beyond 1.
1158 spa_l2cache_compare(const void *a, const void *b)
1160 return (spa_aux_compare(a, b));
1164 spa_l2cache_add(vdev_t *vd)
1166 mutex_enter(&spa_l2cache_lock);
1167 ASSERT(!vd->vdev_isl2cache);
1168 spa_aux_add(vd, &spa_l2cache_avl);
1169 vd->vdev_isl2cache = B_TRUE;
1170 mutex_exit(&spa_l2cache_lock);
1174 spa_l2cache_remove(vdev_t *vd)
1176 mutex_enter(&spa_l2cache_lock);
1177 ASSERT(vd->vdev_isl2cache);
1178 spa_aux_remove(vd, &spa_l2cache_avl);
1179 vd->vdev_isl2cache = B_FALSE;
1180 mutex_exit(&spa_l2cache_lock);
1184 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
1188 mutex_enter(&spa_l2cache_lock);
1189 found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
1190 mutex_exit(&spa_l2cache_lock);
1196 spa_l2cache_activate(vdev_t *vd)
1198 mutex_enter(&spa_l2cache_lock);
1199 ASSERT(vd->vdev_isl2cache);
1200 spa_aux_activate(vd, &spa_l2cache_avl);
1201 mutex_exit(&spa_l2cache_lock);
1205 * ==========================================================================
1207 * ==========================================================================
1211 * Lock the given spa_t for the purpose of adding or removing a vdev.
1212 * Grabs the global spa_namespace_lock plus the spa config lock for writing.
1213 * It returns the next transaction group for the spa_t.
1216 spa_vdev_enter(spa_t *spa)
1218 mutex_enter(&spa->spa_vdev_top_lock);
1219 mutex_enter(&spa_namespace_lock);
1221 vdev_autotrim_stop_all(spa);
1223 return (spa_vdev_config_enter(spa));
1227 * The same as spa_vdev_enter() above but additionally takes the guid of
1228 * the vdev being detached. When there is a rebuild in process it will be
1229 * suspended while the vdev tree is modified then resumed by spa_vdev_exit().
1230 * The rebuild is canceled if only a single child remains after the detach.
1233 spa_vdev_detach_enter(spa_t *spa, uint64_t guid)
1235 mutex_enter(&spa->spa_vdev_top_lock);
1236 mutex_enter(&spa_namespace_lock);
1238 vdev_autotrim_stop_all(spa);
1241 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
1243 vdev_rebuild_stop_wait(vd->vdev_top);
1247 return (spa_vdev_config_enter(spa));
1251 * Internal implementation for spa_vdev_enter(). Used when a vdev
1252 * operation requires multiple syncs (i.e. removing a device) while
1253 * keeping the spa_namespace_lock held.
1256 spa_vdev_config_enter(spa_t *spa)
1258 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1260 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1262 return (spa_last_synced_txg(spa) + 1);
1266 * Used in combination with spa_vdev_config_enter() to allow the syncing
1267 * of multiple transactions without releasing the spa_namespace_lock.
1270 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error,
1273 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1275 int config_changed = B_FALSE;
1277 ASSERT(txg > spa_last_synced_txg(spa));
1279 spa->spa_pending_vdev = NULL;
1282 * Reassess the DTLs.
1284 vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE, B_FALSE);
1286 if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
1287 config_changed = B_TRUE;
1288 spa->spa_config_generation++;
1292 * Verify the metaslab classes.
1294 ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
1295 ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
1296 ASSERT(metaslab_class_validate(spa_embedded_log_class(spa)) == 0);
1297 ASSERT(metaslab_class_validate(spa_special_class(spa)) == 0);
1298 ASSERT(metaslab_class_validate(spa_dedup_class(spa)) == 0);
1300 spa_config_exit(spa, SCL_ALL, spa);
1303 * Panic the system if the specified tag requires it. This
1304 * is useful for ensuring that configurations are updated
1307 if (zio_injection_enabled)
1308 zio_handle_panic_injection(spa, tag, 0);
1311 * Note: this txg_wait_synced() is important because it ensures
1312 * that there won't be more than one config change per txg.
1313 * This allows us to use the txg as the generation number.
1316 txg_wait_synced(spa->spa_dsl_pool, txg);
1319 ASSERT(!vd->vdev_detached || vd->vdev_dtl_sm == NULL);
1320 if (vd->vdev_ops->vdev_op_leaf) {
1321 mutex_enter(&vd->vdev_initialize_lock);
1322 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED,
1324 mutex_exit(&vd->vdev_initialize_lock);
1326 mutex_enter(&vd->vdev_trim_lock);
1327 vdev_trim_stop(vd, VDEV_TRIM_CANCELED, NULL);
1328 mutex_exit(&vd->vdev_trim_lock);
1332 * The vdev may be both a leaf and top-level device.
1334 vdev_autotrim_stop_wait(vd);
1336 spa_config_enter(spa, SCL_STATE_ALL, spa, RW_WRITER);
1338 spa_config_exit(spa, SCL_STATE_ALL, spa);
1342 * If the config changed, update the config cache.
1345 spa_write_cachefile(spa, B_FALSE, B_TRUE, B_TRUE);
1349 * Unlock the spa_t after adding or removing a vdev. Besides undoing the
1350 * locking of spa_vdev_enter(), we also want make sure the transactions have
1351 * synced to disk, and then update the global configuration cache with the new
1355 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
1357 vdev_autotrim_restart(spa);
1358 vdev_rebuild_restart(spa);
1360 spa_vdev_config_exit(spa, vd, txg, error, FTAG);
1361 mutex_exit(&spa_namespace_lock);
1362 mutex_exit(&spa->spa_vdev_top_lock);
1368 * Lock the given spa_t for the purpose of changing vdev state.
1371 spa_vdev_state_enter(spa_t *spa, int oplocks)
1373 int locks = SCL_STATE_ALL | oplocks;
1376 * Root pools may need to read of the underlying devfs filesystem
1377 * when opening up a vdev. Unfortunately if we're holding the
1378 * SCL_ZIO lock it will result in a deadlock when we try to issue
1379 * the read from the root filesystem. Instead we "prefetch"
1380 * the associated vnodes that we need prior to opening the
1381 * underlying devices and cache them so that we can prevent
1382 * any I/O when we are doing the actual open.
1384 if (spa_is_root(spa)) {
1385 int low = locks & ~(SCL_ZIO - 1);
1386 int high = locks & ~low;
1388 spa_config_enter(spa, high, spa, RW_WRITER);
1389 vdev_hold(spa->spa_root_vdev);
1390 spa_config_enter(spa, low, spa, RW_WRITER);
1392 spa_config_enter(spa, locks, spa, RW_WRITER);
1394 spa->spa_vdev_locks = locks;
1398 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
1400 boolean_t config_changed = B_FALSE;
1403 if (vd == NULL || vd == spa->spa_root_vdev) {
1404 vdev_top = spa->spa_root_vdev;
1406 vdev_top = vd->vdev_top;
1409 if (vd != NULL || error == 0)
1410 vdev_dtl_reassess(vdev_top, 0, 0, B_FALSE, B_FALSE);
1413 if (vd != spa->spa_root_vdev)
1414 vdev_state_dirty(vdev_top);
1416 config_changed = B_TRUE;
1417 spa->spa_config_generation++;
1420 if (spa_is_root(spa))
1421 vdev_rele(spa->spa_root_vdev);
1423 ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1424 spa_config_exit(spa, spa->spa_vdev_locks, spa);
1427 * If anything changed, wait for it to sync. This ensures that,
1428 * from the system administrator's perspective, zpool(8) commands
1429 * are synchronous. This is important for things like zpool offline:
1430 * when the command completes, you expect no further I/O from ZFS.
1433 txg_wait_synced(spa->spa_dsl_pool, 0);
1436 * If the config changed, update the config cache.
1438 if (config_changed) {
1439 mutex_enter(&spa_namespace_lock);
1440 spa_write_cachefile(spa, B_FALSE, B_TRUE, B_FALSE);
1441 mutex_exit(&spa_namespace_lock);
1448 * ==========================================================================
1449 * Miscellaneous functions
1450 * ==========================================================================
1454 spa_activate_mos_feature(spa_t *spa, const char *feature, dmu_tx_t *tx)
1456 if (!nvlist_exists(spa->spa_label_features, feature)) {
1457 fnvlist_add_boolean(spa->spa_label_features, feature);
1459 * When we are creating the pool (tx_txg==TXG_INITIAL), we can't
1460 * dirty the vdev config because lock SCL_CONFIG is not held.
1461 * Thankfully, in this case we don't need to dirty the config
1462 * because it will be written out anyway when we finish
1463 * creating the pool.
1465 if (tx->tx_txg != TXG_INITIAL)
1466 vdev_config_dirty(spa->spa_root_vdev);
1471 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1473 if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1474 vdev_config_dirty(spa->spa_root_vdev);
1478 * Return the spa_t associated with given pool_guid, if it exists. If
1479 * device_guid is non-zero, determine whether the pool exists *and* contains
1480 * a device with the specified device_guid.
1483 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1486 avl_tree_t *t = &spa_namespace_avl;
1488 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1490 for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1491 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1493 if (spa->spa_root_vdev == NULL)
1495 if (spa_guid(spa) == pool_guid) {
1496 if (device_guid == 0)
1499 if (vdev_lookup_by_guid(spa->spa_root_vdev,
1500 device_guid) != NULL)
1504 * Check any devices we may be in the process of adding.
1506 if (spa->spa_pending_vdev) {
1507 if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1508 device_guid) != NULL)
1518 * Determine whether a pool with the given pool_guid exists.
1521 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1523 return (spa_by_guid(pool_guid, device_guid) != NULL);
1527 spa_strdup(const char *s)
1533 new = kmem_alloc(len + 1, KM_SLEEP);
1534 memcpy(new, s, len + 1);
1540 spa_strfree(char *s)
1542 kmem_free(s, strlen(s) + 1);
1546 spa_generate_guid(spa_t *spa)
1552 (void) random_get_pseudo_bytes((void *)&guid,
1554 } while (guid == 0 || spa_guid_exists(spa_guid(spa), guid));
1557 (void) random_get_pseudo_bytes((void *)&guid,
1559 } while (guid == 0 || spa_guid_exists(guid, 0));
1566 snprintf_blkptr(char *buf, size_t buflen, const blkptr_t *bp)
1569 const char *checksum = NULL;
1570 const char *compress = NULL;
1573 if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1574 dmu_object_byteswap_t bswap =
1575 DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1576 (void) snprintf(type, sizeof (type), "bswap %s %s",
1577 DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1578 "metadata" : "data",
1579 dmu_ot_byteswap[bswap].ob_name);
1581 (void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1584 if (!BP_IS_EMBEDDED(bp)) {
1586 zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1588 compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1591 SNPRINTF_BLKPTR(kmem_scnprintf, ' ', buf, buflen, bp, type, checksum,
1596 spa_freeze(spa_t *spa)
1598 uint64_t freeze_txg = 0;
1600 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1601 if (spa->spa_freeze_txg == UINT64_MAX) {
1602 freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1603 spa->spa_freeze_txg = freeze_txg;
1605 spa_config_exit(spa, SCL_ALL, FTAG);
1606 if (freeze_txg != 0)
1607 txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1611 zfs_panic_recover(const char *fmt, ...)
1616 vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1621 * This is a stripped-down version of strtoull, suitable only for converting
1622 * lowercase hexadecimal numbers that don't overflow.
1625 zfs_strtonum(const char *str, char **nptr)
1631 while ((c = *str) != '\0') {
1632 if (c >= '0' && c <= '9')
1634 else if (c >= 'a' && c <= 'f')
1635 digit = 10 + c - 'a';
1646 *nptr = (char *)str;
1652 spa_activate_allocation_classes(spa_t *spa, dmu_tx_t *tx)
1655 * We bump the feature refcount for each special vdev added to the pool
1657 ASSERT(spa_feature_is_enabled(spa, SPA_FEATURE_ALLOCATION_CLASSES));
1658 spa_feature_incr(spa, SPA_FEATURE_ALLOCATION_CLASSES, tx);
1662 * ==========================================================================
1663 * Accessor functions
1664 * ==========================================================================
1668 spa_shutting_down(spa_t *spa)
1670 return (spa->spa_async_suspended);
1674 spa_get_dsl(spa_t *spa)
1676 return (spa->spa_dsl_pool);
1680 spa_is_initializing(spa_t *spa)
1682 return (spa->spa_is_initializing);
1686 spa_indirect_vdevs_loaded(spa_t *spa)
1688 return (spa->spa_indirect_vdevs_loaded);
1692 spa_get_rootblkptr(spa_t *spa)
1694 return (&spa->spa_ubsync.ub_rootbp);
1698 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1700 spa->spa_uberblock.ub_rootbp = *bp;
1704 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1706 if (spa->spa_root == NULL)
1709 (void) strlcpy(buf, spa->spa_root, buflen);
1713 spa_sync_pass(spa_t *spa)
1715 return (spa->spa_sync_pass);
1719 spa_name(spa_t *spa)
1721 return (spa->spa_name);
1725 spa_guid(spa_t *spa)
1727 dsl_pool_t *dp = spa_get_dsl(spa);
1731 * If we fail to parse the config during spa_load(), we can go through
1732 * the error path (which posts an ereport) and end up here with no root
1733 * vdev. We stash the original pool guid in 'spa_config_guid' to handle
1736 if (spa->spa_root_vdev == NULL)
1737 return (spa->spa_config_guid);
1739 guid = spa->spa_last_synced_guid != 0 ?
1740 spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1743 * Return the most recently synced out guid unless we're
1744 * in syncing context.
1746 if (dp && dsl_pool_sync_context(dp))
1747 return (spa->spa_root_vdev->vdev_guid);
1753 spa_load_guid(spa_t *spa)
1756 * This is a GUID that exists solely as a reference for the
1757 * purposes of the arc. It is generated at load time, and
1758 * is never written to persistent storage.
1760 return (spa->spa_load_guid);
1764 spa_last_synced_txg(spa_t *spa)
1766 return (spa->spa_ubsync.ub_txg);
1770 spa_first_txg(spa_t *spa)
1772 return (spa->spa_first_txg);
1776 spa_syncing_txg(spa_t *spa)
1778 return (spa->spa_syncing_txg);
1782 * Return the last txg where data can be dirtied. The final txgs
1783 * will be used to just clear out any deferred frees that remain.
1786 spa_final_dirty_txg(spa_t *spa)
1788 return (spa->spa_final_txg - TXG_DEFER_SIZE);
1792 spa_state(spa_t *spa)
1794 return (spa->spa_state);
1798 spa_load_state(spa_t *spa)
1800 return (spa->spa_load_state);
1804 spa_freeze_txg(spa_t *spa)
1806 return (spa->spa_freeze_txg);
1810 * Return the inflated asize for a logical write in bytes. This is used by the
1811 * DMU to calculate the space a logical write will require on disk.
1812 * If lsize is smaller than the largest physical block size allocatable on this
1813 * pool we use its value instead, since the write will end up using the whole
1817 spa_get_worst_case_asize(spa_t *spa, uint64_t lsize)
1820 return (0); /* No inflation needed */
1821 return (MAX(lsize, 1 << spa->spa_max_ashift) * spa_asize_inflation);
1825 * Return the amount of slop space in bytes. It is typically 1/32 of the pool
1826 * (3.2%), minus the embedded log space. On very small pools, it may be
1827 * slightly larger than this. On very large pools, it will be capped to
1828 * the value of spa_max_slop. The embedded log space is not included in
1829 * spa_dspace. By subtracting it, the usable space (per "zfs list") is a
1830 * constant 97% of the total space, regardless of metaslab size (assuming the
1831 * default spa_slop_shift=5 and a non-tiny pool).
1833 * See the comment above spa_slop_shift for more details.
1836 spa_get_slop_space(spa_t *spa)
1842 * Make sure spa_dedup_dspace has been set.
1844 if (spa->spa_dedup_dspace == ~0ULL)
1845 spa_update_dspace(spa);
1848 * spa_get_dspace() includes the space only logically "used" by
1849 * deduplicated data, so since it's not useful to reserve more
1850 * space with more deduplicated data, we subtract that out here.
1853 spa_get_dspace(spa) - spa->spa_dedup_dspace - brt_get_dspace(spa);
1854 slop = MIN(space >> spa_slop_shift, spa_max_slop);
1857 * Subtract the embedded log space, but no more than half the (3.2%)
1858 * unusable space. Note, the "no more than half" is only relevant if
1859 * zfs_embedded_slog_min_ms >> spa_slop_shift < 2, which is not true by
1862 uint64_t embedded_log =
1863 metaslab_class_get_dspace(spa_embedded_log_class(spa));
1864 slop -= MIN(embedded_log, slop >> 1);
1867 * Slop space should be at least spa_min_slop, but no more than half
1870 slop = MAX(slop, MIN(space >> 1, spa_min_slop));
1875 spa_get_dspace(spa_t *spa)
1877 return (spa->spa_dspace);
1881 spa_get_checkpoint_space(spa_t *spa)
1883 return (spa->spa_checkpoint_info.sci_dspace);
1887 spa_update_dspace(spa_t *spa)
1889 spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1890 ddt_get_dedup_dspace(spa) + brt_get_dspace(spa);
1891 if (spa->spa_nonallocating_dspace > 0) {
1893 * Subtract the space provided by all non-allocating vdevs that
1894 * contribute to dspace. If a file is overwritten, its old
1895 * blocks are freed and new blocks are allocated. If there are
1896 * no snapshots of the file, the available space should remain
1897 * the same. The old blocks could be freed from the
1898 * non-allocating vdev, but the new blocks must be allocated on
1899 * other (allocating) vdevs. By reserving the entire size of
1900 * the non-allocating vdevs (including allocated space), we
1901 * ensure that there will be enough space on the allocating
1902 * vdevs for this file overwrite to succeed.
1904 * Note that the DMU/DSL doesn't actually know or care
1905 * how much space is allocated (it does its own tracking
1906 * of how much space has been logically used). So it
1907 * doesn't matter that the data we are moving may be
1908 * allocated twice (on the old device and the new device).
1910 ASSERT3U(spa->spa_dspace, >=, spa->spa_nonallocating_dspace);
1911 spa->spa_dspace -= spa->spa_nonallocating_dspace;
1916 * Return the failure mode that has been set to this pool. The default
1917 * behavior will be to block all I/Os when a complete failure occurs.
1920 spa_get_failmode(spa_t *spa)
1922 return (spa->spa_failmode);
1926 spa_suspended(spa_t *spa)
1928 return (spa->spa_suspended != ZIO_SUSPEND_NONE);
1932 spa_version(spa_t *spa)
1934 return (spa->spa_ubsync.ub_version);
1938 spa_deflate(spa_t *spa)
1940 return (spa->spa_deflate);
1944 spa_normal_class(spa_t *spa)
1946 return (spa->spa_normal_class);
1950 spa_log_class(spa_t *spa)
1952 return (spa->spa_log_class);
1956 spa_embedded_log_class(spa_t *spa)
1958 return (spa->spa_embedded_log_class);
1962 spa_special_class(spa_t *spa)
1964 return (spa->spa_special_class);
1968 spa_dedup_class(spa_t *spa)
1970 return (spa->spa_dedup_class);
1974 * Locate an appropriate allocation class
1977 spa_preferred_class(spa_t *spa, uint64_t size, dmu_object_type_t objtype,
1978 uint_t level, uint_t special_smallblk)
1981 * ZIL allocations determine their class in zio_alloc_zil().
1983 ASSERT(objtype != DMU_OT_INTENT_LOG);
1985 boolean_t has_special_class = spa->spa_special_class->mc_groups != 0;
1987 if (DMU_OT_IS_DDT(objtype)) {
1988 if (spa->spa_dedup_class->mc_groups != 0)
1989 return (spa_dedup_class(spa));
1990 else if (has_special_class && zfs_ddt_data_is_special)
1991 return (spa_special_class(spa));
1993 return (spa_normal_class(spa));
1996 /* Indirect blocks for user data can land in special if allowed */
1997 if (level > 0 && (DMU_OT_IS_FILE(objtype) || objtype == DMU_OT_ZVOL)) {
1998 if (has_special_class && zfs_user_indirect_is_special)
1999 return (spa_special_class(spa));
2001 return (spa_normal_class(spa));
2004 if (DMU_OT_IS_METADATA(objtype) || level > 0) {
2005 if (has_special_class)
2006 return (spa_special_class(spa));
2008 return (spa_normal_class(spa));
2012 * Allow small file blocks in special class in some cases (like
2013 * for the dRAID vdev feature). But always leave a reserve of
2014 * zfs_special_class_metadata_reserve_pct exclusively for metadata.
2016 if (DMU_OT_IS_FILE(objtype) &&
2017 has_special_class && size <= special_smallblk) {
2018 metaslab_class_t *special = spa_special_class(spa);
2019 uint64_t alloc = metaslab_class_get_alloc(special);
2020 uint64_t space = metaslab_class_get_space(special);
2022 (space * (100 - zfs_special_class_metadata_reserve_pct))
2029 return (spa_normal_class(spa));
2033 spa_evicting_os_register(spa_t *spa, objset_t *os)
2035 mutex_enter(&spa->spa_evicting_os_lock);
2036 list_insert_head(&spa->spa_evicting_os_list, os);
2037 mutex_exit(&spa->spa_evicting_os_lock);
2041 spa_evicting_os_deregister(spa_t *spa, objset_t *os)
2043 mutex_enter(&spa->spa_evicting_os_lock);
2044 list_remove(&spa->spa_evicting_os_list, os);
2045 cv_broadcast(&spa->spa_evicting_os_cv);
2046 mutex_exit(&spa->spa_evicting_os_lock);
2050 spa_evicting_os_wait(spa_t *spa)
2052 mutex_enter(&spa->spa_evicting_os_lock);
2053 while (!list_is_empty(&spa->spa_evicting_os_list))
2054 cv_wait(&spa->spa_evicting_os_cv, &spa->spa_evicting_os_lock);
2055 mutex_exit(&spa->spa_evicting_os_lock);
2057 dmu_buf_user_evict_wait();
2061 spa_max_replication(spa_t *spa)
2064 * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
2065 * handle BPs with more than one DVA allocated. Set our max
2066 * replication level accordingly.
2068 if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
2070 return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
2074 spa_prev_software_version(spa_t *spa)
2076 return (spa->spa_prev_software_version);
2080 spa_deadman_synctime(spa_t *spa)
2082 return (spa->spa_deadman_synctime);
2086 spa_get_autotrim(spa_t *spa)
2088 return (spa->spa_autotrim);
2092 spa_deadman_ziotime(spa_t *spa)
2094 return (spa->spa_deadman_ziotime);
2098 spa_get_deadman_failmode(spa_t *spa)
2100 return (spa->spa_deadman_failmode);
2104 spa_set_deadman_failmode(spa_t *spa, const char *failmode)
2106 if (strcmp(failmode, "wait") == 0)
2107 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_WAIT;
2108 else if (strcmp(failmode, "continue") == 0)
2109 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_CONTINUE;
2110 else if (strcmp(failmode, "panic") == 0)
2111 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_PANIC;
2113 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_WAIT;
2117 spa_set_deadman_ziotime(hrtime_t ns)
2121 if (spa_mode_global != SPA_MODE_UNINIT) {
2122 mutex_enter(&spa_namespace_lock);
2123 while ((spa = spa_next(spa)) != NULL)
2124 spa->spa_deadman_ziotime = ns;
2125 mutex_exit(&spa_namespace_lock);
2130 spa_set_deadman_synctime(hrtime_t ns)
2134 if (spa_mode_global != SPA_MODE_UNINIT) {
2135 mutex_enter(&spa_namespace_lock);
2136 while ((spa = spa_next(spa)) != NULL)
2137 spa->spa_deadman_synctime = ns;
2138 mutex_exit(&spa_namespace_lock);
2143 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
2145 uint64_t asize = DVA_GET_ASIZE(dva);
2146 uint64_t dsize = asize;
2148 ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
2150 if (asize != 0 && spa->spa_deflate) {
2151 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
2153 dsize = (asize >> SPA_MINBLOCKSHIFT) *
2154 vd->vdev_deflate_ratio;
2161 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
2165 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
2166 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
2172 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
2176 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2178 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
2179 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
2181 spa_config_exit(spa, SCL_VDEV, FTAG);
2187 spa_dirty_data(spa_t *spa)
2189 return (spa->spa_dsl_pool->dp_dirty_total);
2193 * ==========================================================================
2194 * SPA Import Progress Routines
2195 * ==========================================================================
2198 typedef struct spa_import_progress {
2199 uint64_t pool_guid; /* unique id for updates */
2201 spa_load_state_t spa_load_state;
2202 char *spa_load_notes;
2203 uint64_t mmp_sec_remaining; /* MMP activity check */
2204 uint64_t spa_load_max_txg; /* rewind txg */
2205 procfs_list_node_t smh_node;
2206 } spa_import_progress_t;
2208 spa_history_list_t *spa_import_progress_list = NULL;
2211 spa_import_progress_show_header(struct seq_file *f)
2213 seq_printf(f, "%-20s %-14s %-14s %-12s %-16s %s\n", "pool_guid",
2214 "load_state", "multihost_secs", "max_txg",
2215 "pool_name", "notes");
2220 spa_import_progress_show(struct seq_file *f, void *data)
2222 spa_import_progress_t *sip = (spa_import_progress_t *)data;
2224 seq_printf(f, "%-20llu %-14llu %-14llu %-12llu %-16s %s\n",
2225 (u_longlong_t)sip->pool_guid, (u_longlong_t)sip->spa_load_state,
2226 (u_longlong_t)sip->mmp_sec_remaining,
2227 (u_longlong_t)sip->spa_load_max_txg,
2228 (sip->pool_name ? sip->pool_name : "-"),
2229 (sip->spa_load_notes ? sip->spa_load_notes : "-"));
2234 /* Remove oldest elements from list until there are no more than 'size' left */
2236 spa_import_progress_truncate(spa_history_list_t *shl, unsigned int size)
2238 spa_import_progress_t *sip;
2239 while (shl->size > size) {
2240 sip = list_remove_head(&shl->procfs_list.pl_list);
2242 spa_strfree(sip->pool_name);
2243 if (sip->spa_load_notes)
2244 kmem_strfree(sip->spa_load_notes);
2245 kmem_free(sip, sizeof (spa_import_progress_t));
2249 IMPLY(size == 0, list_is_empty(&shl->procfs_list.pl_list));
2253 spa_import_progress_init(void)
2255 spa_import_progress_list = kmem_zalloc(sizeof (spa_history_list_t),
2258 spa_import_progress_list->size = 0;
2260 spa_import_progress_list->procfs_list.pl_private =
2261 spa_import_progress_list;
2263 procfs_list_install("zfs",
2267 &spa_import_progress_list->procfs_list,
2268 spa_import_progress_show,
2269 spa_import_progress_show_header,
2271 offsetof(spa_import_progress_t, smh_node));
2275 spa_import_progress_destroy(void)
2277 spa_history_list_t *shl = spa_import_progress_list;
2278 procfs_list_uninstall(&shl->procfs_list);
2279 spa_import_progress_truncate(shl, 0);
2280 procfs_list_destroy(&shl->procfs_list);
2281 kmem_free(shl, sizeof (spa_history_list_t));
2285 spa_import_progress_set_state(uint64_t pool_guid,
2286 spa_load_state_t load_state)
2288 spa_history_list_t *shl = spa_import_progress_list;
2289 spa_import_progress_t *sip;
2295 mutex_enter(&shl->procfs_list.pl_lock);
2296 for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2297 sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2298 if (sip->pool_guid == pool_guid) {
2299 sip->spa_load_state = load_state;
2300 if (sip->spa_load_notes != NULL) {
2301 kmem_strfree(sip->spa_load_notes);
2302 sip->spa_load_notes = NULL;
2308 mutex_exit(&shl->procfs_list.pl_lock);
2314 spa_import_progress_set_notes_impl(spa_t *spa, boolean_t log_dbgmsg,
2315 const char *fmt, va_list adx)
2317 spa_history_list_t *shl = spa_import_progress_list;
2318 spa_import_progress_t *sip;
2319 uint64_t pool_guid = spa_guid(spa);
2324 char *notes = kmem_vasprintf(fmt, adx);
2326 mutex_enter(&shl->procfs_list.pl_lock);
2327 for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2328 sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2329 if (sip->pool_guid == pool_guid) {
2330 if (sip->spa_load_notes != NULL) {
2331 kmem_strfree(sip->spa_load_notes);
2332 sip->spa_load_notes = NULL;
2334 sip->spa_load_notes = notes;
2336 zfs_dbgmsg("'%s' %s", sip->pool_name, notes);
2341 mutex_exit(&shl->procfs_list.pl_lock);
2343 kmem_strfree(notes);
2347 spa_import_progress_set_notes(spa_t *spa, const char *fmt, ...)
2352 spa_import_progress_set_notes_impl(spa, B_TRUE, fmt, adx);
2357 spa_import_progress_set_notes_nolog(spa_t *spa, const char *fmt, ...)
2362 spa_import_progress_set_notes_impl(spa, B_FALSE, fmt, adx);
2367 spa_import_progress_set_max_txg(uint64_t pool_guid, uint64_t load_max_txg)
2369 spa_history_list_t *shl = spa_import_progress_list;
2370 spa_import_progress_t *sip;
2376 mutex_enter(&shl->procfs_list.pl_lock);
2377 for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2378 sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2379 if (sip->pool_guid == pool_guid) {
2380 sip->spa_load_max_txg = load_max_txg;
2385 mutex_exit(&shl->procfs_list.pl_lock);
2391 spa_import_progress_set_mmp_check(uint64_t pool_guid,
2392 uint64_t mmp_sec_remaining)
2394 spa_history_list_t *shl = spa_import_progress_list;
2395 spa_import_progress_t *sip;
2401 mutex_enter(&shl->procfs_list.pl_lock);
2402 for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2403 sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2404 if (sip->pool_guid == pool_guid) {
2405 sip->mmp_sec_remaining = mmp_sec_remaining;
2410 mutex_exit(&shl->procfs_list.pl_lock);
2416 * A new import is in progress, add an entry.
2419 spa_import_progress_add(spa_t *spa)
2421 spa_history_list_t *shl = spa_import_progress_list;
2422 spa_import_progress_t *sip;
2423 const char *poolname = NULL;
2425 sip = kmem_zalloc(sizeof (spa_import_progress_t), KM_SLEEP);
2426 sip->pool_guid = spa_guid(spa);
2428 (void) nvlist_lookup_string(spa->spa_config, ZPOOL_CONFIG_POOL_NAME,
2430 if (poolname == NULL)
2431 poolname = spa_name(spa);
2432 sip->pool_name = spa_strdup(poolname);
2433 sip->spa_load_state = spa_load_state(spa);
2434 sip->spa_load_notes = NULL;
2436 mutex_enter(&shl->procfs_list.pl_lock);
2437 procfs_list_add(&shl->procfs_list, sip);
2439 mutex_exit(&shl->procfs_list.pl_lock);
2443 spa_import_progress_remove(uint64_t pool_guid)
2445 spa_history_list_t *shl = spa_import_progress_list;
2446 spa_import_progress_t *sip;
2448 mutex_enter(&shl->procfs_list.pl_lock);
2449 for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2450 sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2451 if (sip->pool_guid == pool_guid) {
2453 spa_strfree(sip->pool_name);
2454 if (sip->spa_load_notes)
2455 spa_strfree(sip->spa_load_notes);
2456 list_remove(&shl->procfs_list.pl_list, sip);
2458 kmem_free(sip, sizeof (spa_import_progress_t));
2462 mutex_exit(&shl->procfs_list.pl_lock);
2466 * ==========================================================================
2467 * Initialization and Termination
2468 * ==========================================================================
2472 spa_name_compare(const void *a1, const void *a2)
2474 const spa_t *s1 = a1;
2475 const spa_t *s2 = a2;
2478 s = strcmp(s1->spa_name, s2->spa_name);
2480 return (TREE_ISIGN(s));
2490 spa_init(spa_mode_t mode)
2492 mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
2493 mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
2494 mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
2495 cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
2497 avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
2498 offsetof(spa_t, spa_avl));
2500 avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
2501 offsetof(spa_aux_t, aux_avl));
2503 avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
2504 offsetof(spa_aux_t, aux_avl));
2506 spa_mode_global = mode;
2509 if (spa_mode_global != SPA_MODE_READ && dprintf_find_string("watch")) {
2510 struct sigaction sa;
2512 sa.sa_flags = SA_SIGINFO;
2513 sigemptyset(&sa.sa_mask);
2514 sa.sa_sigaction = arc_buf_sigsegv;
2516 if (sigaction(SIGSEGV, &sa, NULL) == -1) {
2517 perror("could not enable watchpoints: "
2518 "sigaction(SIGSEGV, ...) = ");
2526 zfs_refcount_init();
2529 metaslab_stat_init();
2535 vdev_mirror_stat_init();
2536 vdev_raidz_math_init();
2541 zpool_feature_init();
2547 spa_import_progress_init();
2558 vdev_mirror_stat_fini();
2559 vdev_raidz_math_fini();
2566 metaslab_stat_fini();
2569 zfs_refcount_fini();
2573 spa_import_progress_destroy();
2575 avl_destroy(&spa_namespace_avl);
2576 avl_destroy(&spa_spare_avl);
2577 avl_destroy(&spa_l2cache_avl);
2579 cv_destroy(&spa_namespace_cv);
2580 mutex_destroy(&spa_namespace_lock);
2581 mutex_destroy(&spa_spare_lock);
2582 mutex_destroy(&spa_l2cache_lock);
2586 * Return whether this pool has a dedicated slog device. No locking needed.
2587 * It's not a problem if the wrong answer is returned as it's only for
2588 * performance and not correctness.
2591 spa_has_slogs(spa_t *spa)
2593 return (spa->spa_log_class->mc_groups != 0);
2597 spa_get_log_state(spa_t *spa)
2599 return (spa->spa_log_state);
2603 spa_set_log_state(spa_t *spa, spa_log_state_t state)
2605 spa->spa_log_state = state;
2609 spa_is_root(spa_t *spa)
2611 return (spa->spa_is_root);
2615 spa_writeable(spa_t *spa)
2617 return (!!(spa->spa_mode & SPA_MODE_WRITE) && spa->spa_trust_config);
2621 * Returns true if there is a pending sync task in any of the current
2622 * syncing txg, the current quiescing txg, or the current open txg.
2625 spa_has_pending_synctask(spa_t *spa)
2627 return (!txg_all_lists_empty(&spa->spa_dsl_pool->dp_sync_tasks) ||
2628 !txg_all_lists_empty(&spa->spa_dsl_pool->dp_early_sync_tasks));
2632 spa_mode(spa_t *spa)
2634 return (spa->spa_mode);
2638 spa_bootfs(spa_t *spa)
2640 return (spa->spa_bootfs);
2644 spa_delegation(spa_t *spa)
2646 return (spa->spa_delegation);
2650 spa_meta_objset(spa_t *spa)
2652 return (spa->spa_meta_objset);
2656 spa_dedup_checksum(spa_t *spa)
2658 return (spa->spa_dedup_checksum);
2662 * Reset pool scan stat per scan pass (or reboot).
2665 spa_scan_stat_init(spa_t *spa)
2667 /* data not stored on disk */
2668 spa->spa_scan_pass_start = gethrestime_sec();
2669 if (dsl_scan_is_paused_scrub(spa->spa_dsl_pool->dp_scan))
2670 spa->spa_scan_pass_scrub_pause = spa->spa_scan_pass_start;
2672 spa->spa_scan_pass_scrub_pause = 0;
2674 if (dsl_errorscrub_is_paused(spa->spa_dsl_pool->dp_scan))
2675 spa->spa_scan_pass_errorscrub_pause = spa->spa_scan_pass_start;
2677 spa->spa_scan_pass_errorscrub_pause = 0;
2679 spa->spa_scan_pass_scrub_spent_paused = 0;
2680 spa->spa_scan_pass_exam = 0;
2681 spa->spa_scan_pass_issued = 0;
2683 // error scrub stats
2684 spa->spa_scan_pass_errorscrub_spent_paused = 0;
2688 * Get scan stats for zpool status reports
2691 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
2693 dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
2695 if (scn == NULL || (scn->scn_phys.scn_func == POOL_SCAN_NONE &&
2696 scn->errorscrub_phys.dep_func == POOL_SCAN_NONE))
2697 return (SET_ERROR(ENOENT));
2699 memset(ps, 0, sizeof (pool_scan_stat_t));
2701 /* data stored on disk */
2702 ps->pss_func = scn->scn_phys.scn_func;
2703 ps->pss_state = scn->scn_phys.scn_state;
2704 ps->pss_start_time = scn->scn_phys.scn_start_time;
2705 ps->pss_end_time = scn->scn_phys.scn_end_time;
2706 ps->pss_to_examine = scn->scn_phys.scn_to_examine;
2707 ps->pss_examined = scn->scn_phys.scn_examined;
2708 ps->pss_skipped = scn->scn_phys.scn_skipped;
2709 ps->pss_processed = scn->scn_phys.scn_processed;
2710 ps->pss_errors = scn->scn_phys.scn_errors;
2712 /* data not stored on disk */
2713 ps->pss_pass_exam = spa->spa_scan_pass_exam;
2714 ps->pss_pass_start = spa->spa_scan_pass_start;
2715 ps->pss_pass_scrub_pause = spa->spa_scan_pass_scrub_pause;
2716 ps->pss_pass_scrub_spent_paused = spa->spa_scan_pass_scrub_spent_paused;
2717 ps->pss_pass_issued = spa->spa_scan_pass_issued;
2719 scn->scn_issued_before_pass + spa->spa_scan_pass_issued;
2721 /* error scrub data stored on disk */
2722 ps->pss_error_scrub_func = scn->errorscrub_phys.dep_func;
2723 ps->pss_error_scrub_state = scn->errorscrub_phys.dep_state;
2724 ps->pss_error_scrub_start = scn->errorscrub_phys.dep_start_time;
2725 ps->pss_error_scrub_end = scn->errorscrub_phys.dep_end_time;
2726 ps->pss_error_scrub_examined = scn->errorscrub_phys.dep_examined;
2727 ps->pss_error_scrub_to_be_examined =
2728 scn->errorscrub_phys.dep_to_examine;
2730 /* error scrub data not stored on disk */
2731 ps->pss_pass_error_scrub_pause = spa->spa_scan_pass_errorscrub_pause;
2737 spa_maxblocksize(spa_t *spa)
2739 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
2740 return (SPA_MAXBLOCKSIZE);
2742 return (SPA_OLD_MAXBLOCKSIZE);
2747 * Returns the txg that the last device removal completed. No indirect mappings
2748 * have been added since this txg.
2751 spa_get_last_removal_txg(spa_t *spa)
2754 uint64_t ret = -1ULL;
2756 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2758 * sr_prev_indirect_vdev is only modified while holding all the
2759 * config locks, so it is sufficient to hold SCL_VDEV as reader when
2762 vdevid = spa->spa_removing_phys.sr_prev_indirect_vdev;
2764 while (vdevid != -1ULL) {
2765 vdev_t *vd = vdev_lookup_top(spa, vdevid);
2766 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
2768 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
2771 * If the removal did not remap any data, we don't care.
2773 if (vdev_indirect_births_count(vib) != 0) {
2774 ret = vdev_indirect_births_last_entry_txg(vib);
2778 vdevid = vd->vdev_indirect_config.vic_prev_indirect_vdev;
2780 spa_config_exit(spa, SCL_VDEV, FTAG);
2783 spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
2789 spa_maxdnodesize(spa_t *spa)
2791 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE))
2792 return (DNODE_MAX_SIZE);
2794 return (DNODE_MIN_SIZE);
2798 spa_multihost(spa_t *spa)
2800 return (spa->spa_multihost ? B_TRUE : B_FALSE);
2804 spa_get_hostid(spa_t *spa)
2806 return (spa->spa_hostid);
2810 spa_trust_config(spa_t *spa)
2812 return (spa->spa_trust_config);
2816 spa_missing_tvds_allowed(spa_t *spa)
2818 return (spa->spa_missing_tvds_allowed);
2822 spa_syncing_log_sm(spa_t *spa)
2824 return (spa->spa_syncing_log_sm);
2828 spa_set_missing_tvds(spa_t *spa, uint64_t missing)
2830 spa->spa_missing_tvds = missing;
2834 * Return the pool state string ("ONLINE", "DEGRADED", "SUSPENDED", etc).
2837 spa_state_to_name(spa_t *spa)
2839 ASSERT3P(spa, !=, NULL);
2842 * it is possible for the spa to exist, without root vdev
2843 * as the spa transitions during import/export
2845 vdev_t *rvd = spa->spa_root_vdev;
2847 return ("TRANSITIONING");
2849 vdev_state_t state = rvd->vdev_state;
2850 vdev_aux_t aux = rvd->vdev_stat.vs_aux;
2852 if (spa_suspended(spa))
2853 return ("SUSPENDED");
2856 case VDEV_STATE_CLOSED:
2857 case VDEV_STATE_OFFLINE:
2859 case VDEV_STATE_REMOVED:
2861 case VDEV_STATE_CANT_OPEN:
2862 if (aux == VDEV_AUX_CORRUPT_DATA || aux == VDEV_AUX_BAD_LOG)
2864 else if (aux == VDEV_AUX_SPLIT_POOL)
2868 case VDEV_STATE_FAULTED:
2870 case VDEV_STATE_DEGRADED:
2871 return ("DEGRADED");
2872 case VDEV_STATE_HEALTHY:
2882 spa_top_vdevs_spacemap_addressable(spa_t *spa)
2884 vdev_t *rvd = spa->spa_root_vdev;
2885 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
2886 if (!vdev_is_spacemap_addressable(rvd->vdev_child[c]))
2893 spa_has_checkpoint(spa_t *spa)
2895 return (spa->spa_checkpoint_txg != 0);
2899 spa_importing_readonly_checkpoint(spa_t *spa)
2901 return ((spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT) &&
2902 spa->spa_mode == SPA_MODE_READ);
2906 spa_min_claim_txg(spa_t *spa)
2908 uint64_t checkpoint_txg = spa->spa_uberblock.ub_checkpoint_txg;
2910 if (checkpoint_txg != 0)
2911 return (checkpoint_txg + 1);
2913 return (spa->spa_first_txg);
2917 * If there is a checkpoint, async destroys may consume more space from
2918 * the pool instead of freeing it. In an attempt to save the pool from
2919 * getting suspended when it is about to run out of space, we stop
2920 * processing async destroys.
2923 spa_suspend_async_destroy(spa_t *spa)
2925 dsl_pool_t *dp = spa_get_dsl(spa);
2927 uint64_t unreserved = dsl_pool_unreserved_space(dp,
2928 ZFS_SPACE_CHECK_EXTRA_RESERVED);
2929 uint64_t used = dsl_dir_phys(dp->dp_root_dir)->dd_used_bytes;
2930 uint64_t avail = (unreserved > used) ? (unreserved - used) : 0;
2932 if (spa_has_checkpoint(spa) && avail == 0)
2938 #if defined(_KERNEL)
2941 param_set_deadman_failmode_common(const char *val)
2947 return (SET_ERROR(EINVAL));
2949 if ((p = strchr(val, '\n')) != NULL)
2952 if (strcmp(val, "wait") != 0 && strcmp(val, "continue") != 0 &&
2953 strcmp(val, "panic"))
2954 return (SET_ERROR(EINVAL));
2956 if (spa_mode_global != SPA_MODE_UNINIT) {
2957 mutex_enter(&spa_namespace_lock);
2958 while ((spa = spa_next(spa)) != NULL)
2959 spa_set_deadman_failmode(spa, val);
2960 mutex_exit(&spa_namespace_lock);
2967 /* Namespace manipulation */
2968 EXPORT_SYMBOL(spa_lookup);
2969 EXPORT_SYMBOL(spa_add);
2970 EXPORT_SYMBOL(spa_remove);
2971 EXPORT_SYMBOL(spa_next);
2973 /* Refcount functions */
2974 EXPORT_SYMBOL(spa_open_ref);
2975 EXPORT_SYMBOL(spa_close);
2976 EXPORT_SYMBOL(spa_refcount_zero);
2978 /* Pool configuration lock */
2979 EXPORT_SYMBOL(spa_config_tryenter);
2980 EXPORT_SYMBOL(spa_config_enter);
2981 EXPORT_SYMBOL(spa_config_exit);
2982 EXPORT_SYMBOL(spa_config_held);
2984 /* Pool vdev add/remove lock */
2985 EXPORT_SYMBOL(spa_vdev_enter);
2986 EXPORT_SYMBOL(spa_vdev_exit);
2988 /* Pool vdev state change lock */
2989 EXPORT_SYMBOL(spa_vdev_state_enter);
2990 EXPORT_SYMBOL(spa_vdev_state_exit);
2992 /* Accessor functions */
2993 EXPORT_SYMBOL(spa_shutting_down);
2994 EXPORT_SYMBOL(spa_get_dsl);
2995 EXPORT_SYMBOL(spa_get_rootblkptr);
2996 EXPORT_SYMBOL(spa_set_rootblkptr);
2997 EXPORT_SYMBOL(spa_altroot);
2998 EXPORT_SYMBOL(spa_sync_pass);
2999 EXPORT_SYMBOL(spa_name);
3000 EXPORT_SYMBOL(spa_guid);
3001 EXPORT_SYMBOL(spa_last_synced_txg);
3002 EXPORT_SYMBOL(spa_first_txg);
3003 EXPORT_SYMBOL(spa_syncing_txg);
3004 EXPORT_SYMBOL(spa_version);
3005 EXPORT_SYMBOL(spa_state);
3006 EXPORT_SYMBOL(spa_load_state);
3007 EXPORT_SYMBOL(spa_freeze_txg);
3008 EXPORT_SYMBOL(spa_get_dspace);
3009 EXPORT_SYMBOL(spa_update_dspace);
3010 EXPORT_SYMBOL(spa_deflate);
3011 EXPORT_SYMBOL(spa_normal_class);
3012 EXPORT_SYMBOL(spa_log_class);
3013 EXPORT_SYMBOL(spa_special_class);
3014 EXPORT_SYMBOL(spa_preferred_class);
3015 EXPORT_SYMBOL(spa_max_replication);
3016 EXPORT_SYMBOL(spa_prev_software_version);
3017 EXPORT_SYMBOL(spa_get_failmode);
3018 EXPORT_SYMBOL(spa_suspended);
3019 EXPORT_SYMBOL(spa_bootfs);
3020 EXPORT_SYMBOL(spa_delegation);
3021 EXPORT_SYMBOL(spa_meta_objset);
3022 EXPORT_SYMBOL(spa_maxblocksize);
3023 EXPORT_SYMBOL(spa_maxdnodesize);
3025 /* Miscellaneous support routines */
3026 EXPORT_SYMBOL(spa_guid_exists);
3027 EXPORT_SYMBOL(spa_strdup);
3028 EXPORT_SYMBOL(spa_strfree);
3029 EXPORT_SYMBOL(spa_generate_guid);
3030 EXPORT_SYMBOL(snprintf_blkptr);
3031 EXPORT_SYMBOL(spa_freeze);
3032 EXPORT_SYMBOL(spa_upgrade);
3033 EXPORT_SYMBOL(spa_evict_all);
3034 EXPORT_SYMBOL(spa_lookup_by_guid);
3035 EXPORT_SYMBOL(spa_has_spare);
3036 EXPORT_SYMBOL(dva_get_dsize_sync);
3037 EXPORT_SYMBOL(bp_get_dsize_sync);
3038 EXPORT_SYMBOL(bp_get_dsize);
3039 EXPORT_SYMBOL(spa_has_slogs);
3040 EXPORT_SYMBOL(spa_is_root);
3041 EXPORT_SYMBOL(spa_writeable);
3042 EXPORT_SYMBOL(spa_mode);
3043 EXPORT_SYMBOL(spa_namespace_lock);
3044 EXPORT_SYMBOL(spa_trust_config);
3045 EXPORT_SYMBOL(spa_missing_tvds_allowed);
3046 EXPORT_SYMBOL(spa_set_missing_tvds);
3047 EXPORT_SYMBOL(spa_state_to_name);
3048 EXPORT_SYMBOL(spa_importing_readonly_checkpoint);
3049 EXPORT_SYMBOL(spa_min_claim_txg);
3050 EXPORT_SYMBOL(spa_suspend_async_destroy);
3051 EXPORT_SYMBOL(spa_has_checkpoint);
3052 EXPORT_SYMBOL(spa_top_vdevs_spacemap_addressable);
3054 ZFS_MODULE_PARAM(zfs, zfs_, flags, UINT, ZMOD_RW,
3055 "Set additional debugging flags");
3057 ZFS_MODULE_PARAM(zfs, zfs_, recover, INT, ZMOD_RW,
3058 "Set to attempt to recover from fatal errors");
3060 ZFS_MODULE_PARAM(zfs, zfs_, free_leak_on_eio, INT, ZMOD_RW,
3061 "Set to ignore IO errors during free and permanently leak the space");
3063 ZFS_MODULE_PARAM(zfs_deadman, zfs_deadman_, checktime_ms, U64, ZMOD_RW,
3064 "Dead I/O check interval in milliseconds");
3066 ZFS_MODULE_PARAM(zfs_deadman, zfs_deadman_, enabled, INT, ZMOD_RW,
3067 "Enable deadman timer");
3069 ZFS_MODULE_PARAM(zfs_spa, spa_, asize_inflation, UINT, ZMOD_RW,
3070 "SPA size estimate multiplication factor");
3072 ZFS_MODULE_PARAM(zfs, zfs_, ddt_data_is_special, INT, ZMOD_RW,
3073 "Place DDT data into the special class");
3075 ZFS_MODULE_PARAM(zfs, zfs_, user_indirect_is_special, INT, ZMOD_RW,
3076 "Place user data indirect blocks into the special class");
3079 ZFS_MODULE_PARAM_CALL(zfs_deadman, zfs_deadman_, failmode,
3080 param_set_deadman_failmode, param_get_charp, ZMOD_RW,
3081 "Failmode for deadman timer");
3083 ZFS_MODULE_PARAM_CALL(zfs_deadman, zfs_deadman_, synctime_ms,
3084 param_set_deadman_synctime, spl_param_get_u64, ZMOD_RW,
3085 "Pool sync expiration time in milliseconds");
3087 ZFS_MODULE_PARAM_CALL(zfs_deadman, zfs_deadman_, ziotime_ms,
3088 param_set_deadman_ziotime, spl_param_get_u64, ZMOD_RW,
3089 "IO expiration time in milliseconds");
3091 ZFS_MODULE_PARAM(zfs, zfs_, special_class_metadata_reserve_pct, UINT, ZMOD_RW,
3092 "Small file blocks in special vdevs depends on this much "
3093 "free space available");
3096 ZFS_MODULE_PARAM_CALL(zfs_spa, spa_, slop_shift, param_set_slop_shift,
3097 param_get_uint, ZMOD_RW, "Reserved free space in pool");
3099 ZFS_MODULE_PARAM(zfs, spa_, num_allocators, INT, ZMOD_RW,
3100 "Number of allocators per spa, capped by ncpus");