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]
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
24 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
25 * Copyright 2013 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
26 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27 * Copyright 2013 Saso Kiselkov. All rights reserved.
28 * Copyright (c) 2014 Integros [integros.com]
29 * Copyright (c) 2017 Datto Inc.
32 #include <sys/zfs_context.h>
33 #include <sys/spa_impl.h>
34 #include <sys/spa_boot.h>
36 #include <sys/zio_checksum.h>
37 #include <sys/zio_compress.h>
39 #include <sys/dmu_tx.h>
42 #include <sys/vdev_impl.h>
43 #include <sys/vdev_file.h>
44 #include <sys/vdev_initialize.h>
45 #include <sys/metaslab.h>
46 #include <sys/uberblock_impl.h>
49 #include <sys/unique.h>
50 #include <sys/dsl_pool.h>
51 #include <sys/dsl_dir.h>
52 #include <sys/dsl_prop.h>
53 #include <sys/dsl_scan.h>
54 #include <sys/fs/zfs.h>
55 #include <sys/metaslab_impl.h>
59 #include <sys/zfeature.h>
61 #if defined(__FreeBSD__) && defined(_KERNEL)
62 #include <sys/types.h>
63 #include <sys/sysctl.h>
69 * There are four basic locks for managing spa_t structures:
71 * spa_namespace_lock (global mutex)
73 * This lock must be acquired to do any of the following:
75 * - Lookup a spa_t by name
76 * - Add or remove a spa_t from the namespace
77 * - Increase spa_refcount from non-zero
78 * - Check if spa_refcount is zero
80 * - add/remove/attach/detach devices
81 * - Held for the duration of create/destroy/import/export
83 * It does not need to handle recursion. A create or destroy may
84 * reference objects (files or zvols) in other pools, but by
85 * definition they must have an existing reference, and will never need
86 * to lookup a spa_t by name.
88 * spa_refcount (per-spa refcount_t protected by mutex)
90 * This reference count keep track of any active users of the spa_t. The
91 * spa_t cannot be destroyed or freed while this is non-zero. Internally,
92 * the refcount is never really 'zero' - opening a pool implicitly keeps
93 * some references in the DMU. Internally we check against spa_minref, but
94 * present the image of a zero/non-zero value to consumers.
96 * spa_config_lock[] (per-spa array of rwlocks)
98 * This protects the spa_t from config changes, and must be held in
99 * the following circumstances:
101 * - RW_READER to perform I/O to the spa
102 * - RW_WRITER to change the vdev config
104 * The locking order is fairly straightforward:
106 * spa_namespace_lock -> spa_refcount
108 * The namespace lock must be acquired to increase the refcount from 0
109 * or to check if it is zero.
111 * spa_refcount -> spa_config_lock[]
113 * There must be at least one valid reference on the spa_t to acquire
116 * spa_namespace_lock -> spa_config_lock[]
118 * The namespace lock must always be taken before the config lock.
121 * The spa_namespace_lock can be acquired directly and is globally visible.
123 * The namespace is manipulated using the following functions, all of which
124 * require the spa_namespace_lock to be held.
126 * spa_lookup() Lookup a spa_t by name.
128 * spa_add() Create a new spa_t in the namespace.
130 * spa_remove() Remove a spa_t from the namespace. This also
131 * frees up any memory associated with the spa_t.
133 * spa_next() Returns the next spa_t in the system, or the
134 * first if NULL is passed.
136 * spa_evict_all() Shutdown and remove all spa_t structures in
139 * spa_guid_exists() Determine whether a pool/device guid exists.
141 * The spa_refcount is manipulated using the following functions:
143 * spa_open_ref() Adds a reference to the given spa_t. Must be
144 * called with spa_namespace_lock held if the
145 * refcount is currently zero.
147 * spa_close() Remove a reference from the spa_t. This will
148 * not free the spa_t or remove it from the
149 * namespace. No locking is required.
151 * spa_refcount_zero() Returns true if the refcount is currently
152 * zero. Must be called with spa_namespace_lock
155 * The spa_config_lock[] is an array of rwlocks, ordered as follows:
156 * SCL_CONFIG > SCL_STATE > SCL_ALLOC > SCL_ZIO > SCL_FREE > SCL_VDEV.
157 * spa_config_lock[] is manipulated with spa_config_{enter,exit,held}().
159 * To read the configuration, it suffices to hold one of these locks as reader.
160 * To modify the configuration, you must hold all locks as writer. To modify
161 * vdev state without altering the vdev tree's topology (e.g. online/offline),
162 * you must hold SCL_STATE and SCL_ZIO as writer.
164 * We use these distinct config locks to avoid recursive lock entry.
165 * For example, spa_sync() (which holds SCL_CONFIG as reader) induces
166 * block allocations (SCL_ALLOC), which may require reading space maps
167 * from disk (dmu_read() -> zio_read() -> SCL_ZIO).
169 * The spa config locks cannot be normal rwlocks because we need the
170 * ability to hand off ownership. For example, SCL_ZIO is acquired
171 * by the issuing thread and later released by an interrupt thread.
172 * They do, however, obey the usual write-wanted semantics to prevent
173 * writer (i.e. system administrator) starvation.
175 * The lock acquisition rules are as follows:
178 * Protects changes to the vdev tree topology, such as vdev
179 * add/remove/attach/detach. Protects the dirty config list
180 * (spa_config_dirty_list) and the set of spares and l2arc devices.
183 * Protects changes to pool state and vdev state, such as vdev
184 * online/offline/fault/degrade/clear. Protects the dirty state list
185 * (spa_state_dirty_list) and global pool state (spa_state).
188 * Protects changes to metaslab groups and classes.
189 * Held as reader by metaslab_alloc() and metaslab_claim().
192 * Held by bp-level zios (those which have no io_vd upon entry)
193 * to prevent changes to the vdev tree. The bp-level zio implicitly
194 * protects all of its vdev child zios, which do not hold SCL_ZIO.
197 * Protects changes to metaslab groups and classes.
198 * Held as reader by metaslab_free(). SCL_FREE is distinct from
199 * SCL_ALLOC, and lower than SCL_ZIO, so that we can safely free
200 * blocks in zio_done() while another i/o that holds either
201 * SCL_ALLOC or SCL_ZIO is waiting for this i/o to complete.
204 * Held as reader to prevent changes to the vdev tree during trivial
205 * inquiries such as bp_get_dsize(). SCL_VDEV is distinct from the
206 * other locks, and lower than all of them, to ensure that it's safe
207 * to acquire regardless of caller context.
209 * In addition, the following rules apply:
211 * (a) spa_props_lock protects pool properties, spa_config and spa_config_list.
212 * The lock ordering is SCL_CONFIG > spa_props_lock.
214 * (b) I/O operations on leaf vdevs. For any zio operation that takes
215 * an explicit vdev_t argument -- such as zio_ioctl(), zio_read_phys(),
216 * or zio_write_phys() -- the caller must ensure that the config cannot
217 * cannot change in the interim, and that the vdev cannot be reopened.
218 * SCL_STATE as reader suffices for both.
220 * The vdev configuration is protected by spa_vdev_enter() / spa_vdev_exit().
222 * spa_vdev_enter() Acquire the namespace lock and the config lock
225 * spa_vdev_exit() Release the config lock, wait for all I/O
226 * to complete, sync the updated configs to the
227 * cache, and release the namespace lock.
229 * vdev state is protected by spa_vdev_state_enter() / spa_vdev_state_exit().
230 * Like spa_vdev_enter/exit, these are convenience wrappers -- the actual
231 * locking is, always, based on spa_namespace_lock and spa_config_lock[].
233 * spa_rename() is also implemented within this file since it requires
234 * manipulation of the namespace.
237 static avl_tree_t spa_namespace_avl;
238 kmutex_t spa_namespace_lock;
239 static kcondvar_t spa_namespace_cv;
240 static int spa_active_count;
241 int spa_max_replication_override = SPA_DVAS_PER_BP;
243 static kmutex_t spa_spare_lock;
244 static avl_tree_t spa_spare_avl;
245 static kmutex_t spa_l2cache_lock;
246 static avl_tree_t spa_l2cache_avl;
248 kmem_cache_t *spa_buffer_pool;
253 * Everything except dprintf, spa, and indirect_remap is on by default
256 int zfs_flags = ~(ZFS_DEBUG_DPRINTF | ZFS_DEBUG_INDIRECT_REMAP);
262 * zfs_recover can be set to nonzero to attempt to recover from
263 * otherwise-fatal errors, typically caused by on-disk corruption. When
264 * set, calls to zfs_panic_recover() will turn into warning messages.
265 * This should only be used as a last resort, as it typically results
266 * in leaked space, or worse.
268 boolean_t zfs_recover = B_FALSE;
271 * If destroy encounters an EIO while reading metadata (e.g. indirect
272 * blocks), space referenced by the missing metadata can not be freed.
273 * Normally this causes the background destroy to become "stalled", as
274 * it is unable to make forward progress. While in this stalled state,
275 * all remaining space to free from the error-encountering filesystem is
276 * "temporarily leaked". Set this flag to cause it to ignore the EIO,
277 * permanently leak the space from indirect blocks that can not be read,
278 * and continue to free everything else that it can.
280 * The default, "stalling" behavior is useful if the storage partially
281 * fails (i.e. some but not all i/os fail), and then later recovers. In
282 * this case, we will be able to continue pool operations while it is
283 * partially failed, and when it recovers, we can continue to free the
284 * space, with no leaks. However, note that this case is actually
287 * Typically pools either (a) fail completely (but perhaps temporarily,
288 * e.g. a top-level vdev going offline), or (b) have localized,
289 * permanent errors (e.g. disk returns the wrong data due to bit flip or
290 * firmware bug). In case (a), this setting does not matter because the
291 * pool will be suspended and the sync thread will not be able to make
292 * forward progress regardless. In case (b), because the error is
293 * permanent, the best we can do is leak the minimum amount of space,
294 * which is what setting this flag will do. Therefore, it is reasonable
295 * for this flag to normally be set, but we chose the more conservative
296 * approach of not setting it, so that there is no possibility of
297 * leaking space in the "partial temporary" failure case.
299 boolean_t zfs_free_leak_on_eio = B_FALSE;
302 * Expiration time in milliseconds. This value has two meanings. First it is
303 * used to determine when the spa_deadman() logic should fire. By default the
304 * spa_deadman() will fire if spa_sync() has not completed in 1000 seconds.
305 * Secondly, the value determines if an I/O is considered "hung". Any I/O that
306 * has not completed in zfs_deadman_synctime_ms is considered "hung" resulting
309 uint64_t zfs_deadman_synctime_ms = 1000000ULL;
312 * Check time in milliseconds. This defines the frequency at which we check
315 uint64_t zfs_deadman_checktime_ms = 5000ULL;
318 * Default value of -1 for zfs_deadman_enabled is resolved in
321 int zfs_deadman_enabled = -1;
324 * The worst case is single-sector max-parity RAID-Z blocks, in which
325 * case the space requirement is exactly (VDEV_RAIDZ_MAXPARITY + 1)
326 * times the size; so just assume that. Add to this the fact that
327 * we can have up to 3 DVAs per bp, and one more factor of 2 because
328 * the block may be dittoed with up to 3 DVAs by ddt_sync(). All together,
330 * (VDEV_RAIDZ_MAXPARITY + 1) * SPA_DVAS_PER_BP * 2 == 24
332 int spa_asize_inflation = 24;
334 #if defined(__FreeBSD__) && defined(_KERNEL)
335 SYSCTL_DECL(_vfs_zfs);
336 SYSCTL_INT(_vfs_zfs, OID_AUTO, recover, CTLFLAG_RWTUN, &zfs_recover, 0,
337 "Try to recover from otherwise-fatal errors.");
340 sysctl_vfs_zfs_debug_flags(SYSCTL_HANDLER_ARGS)
345 err = sysctl_handle_int(oidp, &val, 0, req);
346 if (err != 0 || req->newptr == NULL)
350 * ZFS_DEBUG_MODIFY must be enabled prior to boot so all
351 * arc buffers in the system have the necessary additional
352 * checksum data. However, it is safe to disable at any
355 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
356 val &= ~ZFS_DEBUG_MODIFY;
362 SYSCTL_PROC(_vfs_zfs, OID_AUTO, debugflags,
363 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RWTUN, 0, sizeof(int),
364 sysctl_vfs_zfs_debug_flags, "IU", "Debug flags for ZFS testing.");
366 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, deadman_synctime_ms, CTLFLAG_RDTUN,
367 &zfs_deadman_synctime_ms, 0,
368 "Stalled ZFS I/O expiration time in milliseconds");
369 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, deadman_checktime_ms, CTLFLAG_RDTUN,
370 &zfs_deadman_checktime_ms, 0,
371 "Period of checks for stalled ZFS I/O in milliseconds");
372 SYSCTL_INT(_vfs_zfs, OID_AUTO, deadman_enabled, CTLFLAG_RDTUN,
373 &zfs_deadman_enabled, 0, "Kernel panic on stalled ZFS I/O");
374 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_asize_inflation, CTLFLAG_RWTUN,
375 &spa_asize_inflation, 0, "Worst case inflation factor for single sector writes");
384 * If we are not i386 or amd64 or in a virtual machine,
385 * disable ZFS deadman thread by default
387 if (zfs_deadman_enabled == -1) {
388 #if defined(__amd64__) || defined(__i386__)
389 zfs_deadman_enabled = (vm_guest == VM_GUEST_NO) ? 1 : 0;
391 zfs_deadman_enabled = 0;
396 #endif /* !illumos */
399 * Normally, we don't allow the last 3.2% (1/(2^spa_slop_shift)) of space in
400 * the pool to be consumed. This ensures that we don't run the pool
401 * completely out of space, due to unaccounted changes (e.g. to the MOS).
402 * It also limits the worst-case time to allocate space. If we have
403 * less than this amount of free space, most ZPL operations (e.g. write,
404 * create) will return ENOSPC.
406 * Certain operations (e.g. file removal, most administrative actions) can
407 * use half the slop space. They will only return ENOSPC if less than half
408 * the slop space is free. Typically, once the pool has less than the slop
409 * space free, the user will use these operations to free up space in the pool.
410 * These are the operations that call dsl_pool_adjustedsize() with the netfree
411 * argument set to TRUE.
413 * Operations that are almost guaranteed to free up space in the absence of
414 * a pool checkpoint can use up to three quarters of the slop space
417 * A very restricted set of operations are always permitted, regardless of
418 * the amount of free space. These are the operations that call
419 * dsl_sync_task(ZFS_SPACE_CHECK_NONE). If these operations result in a net
420 * increase in the amount of space used, it is possible to run the pool
421 * completely out of space, causing it to be permanently read-only.
423 * Note that on very small pools, the slop space will be larger than
424 * 3.2%, in an effort to have it be at least spa_min_slop (128MB),
425 * but we never allow it to be more than half the pool size.
427 * See also the comments in zfs_space_check_t.
429 int spa_slop_shift = 5;
430 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_slop_shift, CTLFLAG_RWTUN,
432 "Shift value of reserved space (1/(2^spa_slop_shift)).");
433 uint64_t spa_min_slop = 128 * 1024 * 1024;
434 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, spa_min_slop, CTLFLAG_RWTUN,
436 "Minimal value of reserved space");
438 int spa_allocators = 4;
440 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_allocators, CTLFLAG_RWTUN,
442 "Number of allocators per metaslab group");
446 spa_load_failed(spa_t *spa, const char *fmt, ...)
452 (void) vsnprintf(buf, sizeof (buf), fmt, adx);
455 zfs_dbgmsg("spa_load(%s, config %s): FAILED: %s", spa->spa_name,
456 spa->spa_trust_config ? "trusted" : "untrusted", buf);
461 spa_load_note(spa_t *spa, const char *fmt, ...)
467 (void) vsnprintf(buf, sizeof (buf), fmt, adx);
470 zfs_dbgmsg("spa_load(%s, config %s): %s", spa->spa_name,
471 spa->spa_trust_config ? "trusted" : "untrusted", buf);
475 * ==========================================================================
477 * ==========================================================================
480 spa_config_lock_init(spa_t *spa)
482 for (int i = 0; i < SCL_LOCKS; i++) {
483 spa_config_lock_t *scl = &spa->spa_config_lock[i];
484 mutex_init(&scl->scl_lock, NULL, MUTEX_DEFAULT, NULL);
485 cv_init(&scl->scl_cv, NULL, CV_DEFAULT, NULL);
486 refcount_create_untracked(&scl->scl_count);
487 scl->scl_writer = NULL;
488 scl->scl_write_wanted = 0;
493 spa_config_lock_destroy(spa_t *spa)
495 for (int i = 0; i < SCL_LOCKS; i++) {
496 spa_config_lock_t *scl = &spa->spa_config_lock[i];
497 mutex_destroy(&scl->scl_lock);
498 cv_destroy(&scl->scl_cv);
499 refcount_destroy(&scl->scl_count);
500 ASSERT(scl->scl_writer == NULL);
501 ASSERT(scl->scl_write_wanted == 0);
506 spa_config_tryenter(spa_t *spa, int locks, void *tag, krw_t rw)
508 for (int i = 0; i < SCL_LOCKS; i++) {
509 spa_config_lock_t *scl = &spa->spa_config_lock[i];
510 if (!(locks & (1 << i)))
512 mutex_enter(&scl->scl_lock);
513 if (rw == RW_READER) {
514 if (scl->scl_writer || scl->scl_write_wanted) {
515 mutex_exit(&scl->scl_lock);
516 spa_config_exit(spa, locks & ((1 << i) - 1),
521 ASSERT(scl->scl_writer != curthread);
522 if (!refcount_is_zero(&scl->scl_count)) {
523 mutex_exit(&scl->scl_lock);
524 spa_config_exit(spa, locks & ((1 << i) - 1),
528 scl->scl_writer = curthread;
530 (void) refcount_add(&scl->scl_count, tag);
531 mutex_exit(&scl->scl_lock);
537 spa_config_enter(spa_t *spa, int locks, void *tag, krw_t rw)
541 ASSERT3U(SCL_LOCKS, <, sizeof (wlocks_held) * NBBY);
543 for (int i = 0; i < SCL_LOCKS; i++) {
544 spa_config_lock_t *scl = &spa->spa_config_lock[i];
545 if (scl->scl_writer == curthread)
546 wlocks_held |= (1 << i);
547 if (!(locks & (1 << i)))
549 mutex_enter(&scl->scl_lock);
550 if (rw == RW_READER) {
551 while (scl->scl_writer || scl->scl_write_wanted) {
552 cv_wait(&scl->scl_cv, &scl->scl_lock);
555 ASSERT(scl->scl_writer != curthread);
556 while (!refcount_is_zero(&scl->scl_count)) {
557 scl->scl_write_wanted++;
558 cv_wait(&scl->scl_cv, &scl->scl_lock);
559 scl->scl_write_wanted--;
561 scl->scl_writer = curthread;
563 (void) refcount_add(&scl->scl_count, tag);
564 mutex_exit(&scl->scl_lock);
566 ASSERT3U(wlocks_held, <=, locks);
570 spa_config_exit(spa_t *spa, int locks, void *tag)
572 for (int i = SCL_LOCKS - 1; i >= 0; i--) {
573 spa_config_lock_t *scl = &spa->spa_config_lock[i];
574 if (!(locks & (1 << i)))
576 mutex_enter(&scl->scl_lock);
577 ASSERT(!refcount_is_zero(&scl->scl_count));
578 if (refcount_remove(&scl->scl_count, tag) == 0) {
579 ASSERT(scl->scl_writer == NULL ||
580 scl->scl_writer == curthread);
581 scl->scl_writer = NULL; /* OK in either case */
582 cv_broadcast(&scl->scl_cv);
584 mutex_exit(&scl->scl_lock);
589 spa_config_held(spa_t *spa, int locks, krw_t rw)
593 for (int i = 0; i < SCL_LOCKS; i++) {
594 spa_config_lock_t *scl = &spa->spa_config_lock[i];
595 if (!(locks & (1 << i)))
597 if ((rw == RW_READER && !refcount_is_zero(&scl->scl_count)) ||
598 (rw == RW_WRITER && scl->scl_writer == curthread))
599 locks_held |= 1 << i;
606 * ==========================================================================
607 * SPA namespace functions
608 * ==========================================================================
612 * Lookup the named spa_t in the AVL tree. The spa_namespace_lock must be held.
613 * Returns NULL if no matching spa_t is found.
616 spa_lookup(const char *name)
618 static spa_t search; /* spa_t is large; don't allocate on stack */
623 ASSERT(MUTEX_HELD(&spa_namespace_lock));
625 (void) strlcpy(search.spa_name, name, sizeof (search.spa_name));
628 * If it's a full dataset name, figure out the pool name and
631 cp = strpbrk(search.spa_name, "/@#");
635 spa = avl_find(&spa_namespace_avl, &search, &where);
641 * Fires when spa_sync has not completed within zfs_deadman_synctime_ms.
642 * If the zfs_deadman_enabled flag is set then it inspects all vdev queues
643 * looking for potentially hung I/Os.
646 spa_deadman(void *arg, int pending)
651 * Disable the deadman timer if the pool is suspended.
653 if (spa_suspended(spa)) {
655 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
657 /* Nothing. just don't schedule any future callouts. */
662 zfs_dbgmsg("slow spa_sync: started %llu seconds ago, calls %llu",
663 (gethrtime() - spa->spa_sync_starttime) / NANOSEC,
664 ++spa->spa_deadman_calls);
665 if (zfs_deadman_enabled)
666 vdev_deadman(spa->spa_root_vdev);
669 callout_schedule(&spa->spa_deadman_cycid,
670 hz * zfs_deadman_checktime_ms / MILLISEC);
675 #if defined(__FreeBSD__) && defined(_KERNEL)
677 spa_deadman_timeout(void *arg)
681 taskqueue_enqueue(taskqueue_thread, &spa->spa_deadman_task);
686 * Create an uninitialized spa_t with the given name. Requires
687 * spa_namespace_lock. The caller must ensure that the spa_t doesn't already
688 * exist by calling spa_lookup() first.
691 spa_add(const char *name, nvlist_t *config, const char *altroot)
694 spa_config_dirent_t *dp;
700 ASSERT(MUTEX_HELD(&spa_namespace_lock));
702 spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
704 mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
705 mutex_init(&spa->spa_errlist_lock, NULL, MUTEX_DEFAULT, NULL);
706 mutex_init(&spa->spa_errlog_lock, NULL, MUTEX_DEFAULT, NULL);
707 mutex_init(&spa->spa_evicting_os_lock, NULL, MUTEX_DEFAULT, NULL);
708 mutex_init(&spa->spa_history_lock, NULL, MUTEX_DEFAULT, NULL);
709 mutex_init(&spa->spa_proc_lock, NULL, MUTEX_DEFAULT, NULL);
710 mutex_init(&spa->spa_props_lock, NULL, MUTEX_DEFAULT, NULL);
711 mutex_init(&spa->spa_cksum_tmpls_lock, NULL, MUTEX_DEFAULT, NULL);
712 mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
713 mutex_init(&spa->spa_suspend_lock, NULL, MUTEX_DEFAULT, NULL);
714 mutex_init(&spa->spa_vdev_top_lock, NULL, MUTEX_DEFAULT, NULL);
715 mutex_init(&spa->spa_feat_stats_lock, NULL, MUTEX_DEFAULT, NULL);
717 cv_init(&spa->spa_async_cv, NULL, CV_DEFAULT, NULL);
718 cv_init(&spa->spa_evicting_os_cv, NULL, CV_DEFAULT, NULL);
719 cv_init(&spa->spa_proc_cv, NULL, CV_DEFAULT, NULL);
720 cv_init(&spa->spa_scrub_io_cv, NULL, CV_DEFAULT, NULL);
721 cv_init(&spa->spa_suspend_cv, NULL, CV_DEFAULT, NULL);
723 for (int t = 0; t < TXG_SIZE; t++)
724 bplist_create(&spa->spa_free_bplist[t]);
726 (void) strlcpy(spa->spa_name, name, sizeof (spa->spa_name));
727 spa->spa_state = POOL_STATE_UNINITIALIZED;
728 spa->spa_freeze_txg = UINT64_MAX;
729 spa->spa_final_txg = UINT64_MAX;
730 spa->spa_load_max_txg = UINT64_MAX;
732 spa->spa_proc_state = SPA_PROC_NONE;
733 spa->spa_trust_config = B_TRUE;
736 hdlr.cyh_func = spa_deadman;
738 hdlr.cyh_level = CY_LOW_LEVEL;
741 spa->spa_deadman_synctime = MSEC2NSEC(zfs_deadman_synctime_ms);
745 * This determines how often we need to check for hung I/Os after
746 * the cyclic has already fired. Since checking for hung I/Os is
747 * an expensive operation we don't want to check too frequently.
748 * Instead wait for 5 seconds before checking again.
750 when.cyt_interval = MSEC2NSEC(zfs_deadman_checktime_ms);
751 when.cyt_when = CY_INFINITY;
752 mutex_enter(&cpu_lock);
753 spa->spa_deadman_cycid = cyclic_add(&hdlr, &when);
754 mutex_exit(&cpu_lock);
758 * callout(9) does not provide a way to initialize a callout with
759 * a function and an argument, so we use callout_reset() to schedule
760 * the callout in the very distant future. Even if that event ever
761 * fires, it should be okayas we won't have any active zio-s.
762 * But normally spa_sync() will reschedule the callout with a proper
764 * callout(9) does not allow the callback function to sleep but
765 * vdev_deadman() needs to acquire vq_lock and illumos mutexes are
766 * emulated using sx(9). For this reason spa_deadman_timeout()
767 * will schedule spa_deadman() as task on a taskqueue that allows
770 TASK_INIT(&spa->spa_deadman_task, 0, spa_deadman, spa);
771 callout_init(&spa->spa_deadman_cycid, 1);
772 callout_reset_sbt(&spa->spa_deadman_cycid, SBT_MAX, 0,
773 spa_deadman_timeout, spa, 0);
776 refcount_create(&spa->spa_refcount);
777 spa_config_lock_init(spa);
779 avl_add(&spa_namespace_avl, spa);
782 * Set the alternate root, if there is one.
785 spa->spa_root = spa_strdup(altroot);
789 spa->spa_alloc_count = spa_allocators;
790 spa->spa_alloc_locks = kmem_zalloc(spa->spa_alloc_count *
791 sizeof (kmutex_t), KM_SLEEP);
792 spa->spa_alloc_trees = kmem_zalloc(spa->spa_alloc_count *
793 sizeof (avl_tree_t), KM_SLEEP);
794 for (int i = 0; i < spa->spa_alloc_count; i++) {
795 mutex_init(&spa->spa_alloc_locks[i], NULL, MUTEX_DEFAULT, NULL);
796 avl_create(&spa->spa_alloc_trees[i], zio_bookmark_compare,
797 sizeof (zio_t), offsetof(zio_t, io_alloc_node));
801 * Every pool starts with the default cachefile
803 list_create(&spa->spa_config_list, sizeof (spa_config_dirent_t),
804 offsetof(spa_config_dirent_t, scd_link));
806 dp = kmem_zalloc(sizeof (spa_config_dirent_t), KM_SLEEP);
807 dp->scd_path = altroot ? NULL : spa_strdup(spa_config_path);
808 list_insert_head(&spa->spa_config_list, dp);
810 VERIFY(nvlist_alloc(&spa->spa_load_info, NV_UNIQUE_NAME,
813 if (config != NULL) {
816 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_FEATURES_FOR_READ,
818 VERIFY(nvlist_dup(features, &spa->spa_label_features,
822 VERIFY(nvlist_dup(config, &spa->spa_config, 0) == 0);
825 if (spa->spa_label_features == NULL) {
826 VERIFY(nvlist_alloc(&spa->spa_label_features, NV_UNIQUE_NAME,
830 spa->spa_min_ashift = INT_MAX;
831 spa->spa_max_ashift = 0;
834 * As a pool is being created, treat all features as disabled by
835 * setting SPA_FEATURE_DISABLED for all entries in the feature
838 for (int i = 0; i < SPA_FEATURES; i++) {
839 spa->spa_feat_refcount_cache[i] = SPA_FEATURE_DISABLED;
846 * Removes a spa_t from the namespace, freeing up any memory used. Requires
847 * spa_namespace_lock. This is called only after the spa_t has been closed and
851 spa_remove(spa_t *spa)
853 spa_config_dirent_t *dp;
855 ASSERT(MUTEX_HELD(&spa_namespace_lock));
856 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
857 ASSERT3U(refcount_count(&spa->spa_refcount), ==, 0);
859 nvlist_free(spa->spa_config_splitting);
861 avl_remove(&spa_namespace_avl, spa);
862 cv_broadcast(&spa_namespace_cv);
865 spa_strfree(spa->spa_root);
869 while ((dp = list_head(&spa->spa_config_list)) != NULL) {
870 list_remove(&spa->spa_config_list, dp);
871 if (dp->scd_path != NULL)
872 spa_strfree(dp->scd_path);
873 kmem_free(dp, sizeof (spa_config_dirent_t));
876 for (int i = 0; i < spa->spa_alloc_count; i++) {
877 avl_destroy(&spa->spa_alloc_trees[i]);
878 mutex_destroy(&spa->spa_alloc_locks[i]);
880 kmem_free(spa->spa_alloc_locks, spa->spa_alloc_count *
882 kmem_free(spa->spa_alloc_trees, spa->spa_alloc_count *
883 sizeof (avl_tree_t));
885 list_destroy(&spa->spa_config_list);
887 nvlist_free(spa->spa_label_features);
888 nvlist_free(spa->spa_load_info);
889 nvlist_free(spa->spa_feat_stats);
890 spa_config_set(spa, NULL);
893 mutex_enter(&cpu_lock);
894 if (spa->spa_deadman_cycid != CYCLIC_NONE)
895 cyclic_remove(spa->spa_deadman_cycid);
896 mutex_exit(&cpu_lock);
897 spa->spa_deadman_cycid = CYCLIC_NONE;
900 callout_drain(&spa->spa_deadman_cycid);
901 taskqueue_drain(taskqueue_thread, &spa->spa_deadman_task);
905 refcount_destroy(&spa->spa_refcount);
907 spa_config_lock_destroy(spa);
909 for (int t = 0; t < TXG_SIZE; t++)
910 bplist_destroy(&spa->spa_free_bplist[t]);
912 zio_checksum_templates_free(spa);
914 cv_destroy(&spa->spa_async_cv);
915 cv_destroy(&spa->spa_evicting_os_cv);
916 cv_destroy(&spa->spa_proc_cv);
917 cv_destroy(&spa->spa_scrub_io_cv);
918 cv_destroy(&spa->spa_suspend_cv);
920 mutex_destroy(&spa->spa_async_lock);
921 mutex_destroy(&spa->spa_errlist_lock);
922 mutex_destroy(&spa->spa_errlog_lock);
923 mutex_destroy(&spa->spa_evicting_os_lock);
924 mutex_destroy(&spa->spa_history_lock);
925 mutex_destroy(&spa->spa_proc_lock);
926 mutex_destroy(&spa->spa_props_lock);
927 mutex_destroy(&spa->spa_cksum_tmpls_lock);
928 mutex_destroy(&spa->spa_scrub_lock);
929 mutex_destroy(&spa->spa_suspend_lock);
930 mutex_destroy(&spa->spa_vdev_top_lock);
931 mutex_destroy(&spa->spa_feat_stats_lock);
933 kmem_free(spa, sizeof (spa_t));
937 * Given a pool, return the next pool in the namespace, or NULL if there is
938 * none. If 'prev' is NULL, return the first pool.
941 spa_next(spa_t *prev)
943 ASSERT(MUTEX_HELD(&spa_namespace_lock));
946 return (AVL_NEXT(&spa_namespace_avl, prev));
948 return (avl_first(&spa_namespace_avl));
952 * ==========================================================================
953 * SPA refcount functions
954 * ==========================================================================
958 * Add a reference to the given spa_t. Must have at least one reference, or
959 * have the namespace lock held.
962 spa_open_ref(spa_t *spa, void *tag)
964 ASSERT(refcount_count(&spa->spa_refcount) >= spa->spa_minref ||
965 MUTEX_HELD(&spa_namespace_lock));
966 (void) refcount_add(&spa->spa_refcount, tag);
970 * Remove a reference to the given spa_t. Must have at least one reference, or
971 * have the namespace lock held.
974 spa_close(spa_t *spa, void *tag)
976 ASSERT(refcount_count(&spa->spa_refcount) > spa->spa_minref ||
977 MUTEX_HELD(&spa_namespace_lock));
978 (void) refcount_remove(&spa->spa_refcount, tag);
982 * Remove a reference to the given spa_t held by a dsl dir that is
983 * being asynchronously released. Async releases occur from a taskq
984 * performing eviction of dsl datasets and dirs. The namespace lock
985 * isn't held and the hold by the object being evicted may contribute to
986 * spa_minref (e.g. dataset or directory released during pool export),
987 * so the asserts in spa_close() do not apply.
990 spa_async_close(spa_t *spa, void *tag)
992 (void) refcount_remove(&spa->spa_refcount, tag);
996 * Check to see if the spa refcount is zero. Must be called with
997 * spa_namespace_lock held. We really compare against spa_minref, which is the
998 * number of references acquired when opening a pool
1001 spa_refcount_zero(spa_t *spa)
1003 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1005 return (refcount_count(&spa->spa_refcount) == spa->spa_minref);
1009 * ==========================================================================
1010 * SPA spare and l2cache tracking
1011 * ==========================================================================
1015 * Hot spares and cache devices are tracked using the same code below,
1016 * for 'auxiliary' devices.
1019 typedef struct spa_aux {
1027 spa_aux_compare(const void *a, const void *b)
1029 const spa_aux_t *sa = (const spa_aux_t *)a;
1030 const spa_aux_t *sb = (const spa_aux_t *)b;
1032 return (AVL_CMP(sa->aux_guid, sb->aux_guid));
1036 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
1042 search.aux_guid = vd->vdev_guid;
1043 if ((aux = avl_find(avl, &search, &where)) != NULL) {
1046 aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
1047 aux->aux_guid = vd->vdev_guid;
1049 avl_insert(avl, aux, where);
1054 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
1060 search.aux_guid = vd->vdev_guid;
1061 aux = avl_find(avl, &search, &where);
1063 ASSERT(aux != NULL);
1065 if (--aux->aux_count == 0) {
1066 avl_remove(avl, aux);
1067 kmem_free(aux, sizeof (spa_aux_t));
1068 } else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
1069 aux->aux_pool = 0ULL;
1074 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
1076 spa_aux_t search, *found;
1078 search.aux_guid = guid;
1079 found = avl_find(avl, &search, NULL);
1083 *pool = found->aux_pool;
1090 *refcnt = found->aux_count;
1095 return (found != NULL);
1099 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
1101 spa_aux_t search, *found;
1104 search.aux_guid = vd->vdev_guid;
1105 found = avl_find(avl, &search, &where);
1106 ASSERT(found != NULL);
1107 ASSERT(found->aux_pool == 0ULL);
1109 found->aux_pool = spa_guid(vd->vdev_spa);
1113 * Spares are tracked globally due to the following constraints:
1115 * - A spare may be part of multiple pools.
1116 * - A spare may be added to a pool even if it's actively in use within
1118 * - A spare in use in any pool can only be the source of a replacement if
1119 * the target is a spare in the same pool.
1121 * We keep track of all spares on the system through the use of a reference
1122 * counted AVL tree. When a vdev is added as a spare, or used as a replacement
1123 * spare, then we bump the reference count in the AVL tree. In addition, we set
1124 * the 'vdev_isspare' member to indicate that the device is a spare (active or
1125 * inactive). When a spare is made active (used to replace a device in the
1126 * pool), we also keep track of which pool its been made a part of.
1128 * The 'spa_spare_lock' protects the AVL tree. These functions are normally
1129 * called under the spa_namespace lock as part of vdev reconfiguration. The
1130 * separate spare lock exists for the status query path, which does not need to
1131 * be completely consistent with respect to other vdev configuration changes.
1135 spa_spare_compare(const void *a, const void *b)
1137 return (spa_aux_compare(a, b));
1141 spa_spare_add(vdev_t *vd)
1143 mutex_enter(&spa_spare_lock);
1144 ASSERT(!vd->vdev_isspare);
1145 spa_aux_add(vd, &spa_spare_avl);
1146 vd->vdev_isspare = B_TRUE;
1147 mutex_exit(&spa_spare_lock);
1151 spa_spare_remove(vdev_t *vd)
1153 mutex_enter(&spa_spare_lock);
1154 ASSERT(vd->vdev_isspare);
1155 spa_aux_remove(vd, &spa_spare_avl);
1156 vd->vdev_isspare = B_FALSE;
1157 mutex_exit(&spa_spare_lock);
1161 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
1165 mutex_enter(&spa_spare_lock);
1166 found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
1167 mutex_exit(&spa_spare_lock);
1173 spa_spare_activate(vdev_t *vd)
1175 mutex_enter(&spa_spare_lock);
1176 ASSERT(vd->vdev_isspare);
1177 spa_aux_activate(vd, &spa_spare_avl);
1178 mutex_exit(&spa_spare_lock);
1182 * Level 2 ARC devices are tracked globally for the same reasons as spares.
1183 * Cache devices currently only support one pool per cache device, and so
1184 * for these devices the aux reference count is currently unused beyond 1.
1188 spa_l2cache_compare(const void *a, const void *b)
1190 return (spa_aux_compare(a, b));
1194 spa_l2cache_add(vdev_t *vd)
1196 mutex_enter(&spa_l2cache_lock);
1197 ASSERT(!vd->vdev_isl2cache);
1198 spa_aux_add(vd, &spa_l2cache_avl);
1199 vd->vdev_isl2cache = B_TRUE;
1200 mutex_exit(&spa_l2cache_lock);
1204 spa_l2cache_remove(vdev_t *vd)
1206 mutex_enter(&spa_l2cache_lock);
1207 ASSERT(vd->vdev_isl2cache);
1208 spa_aux_remove(vd, &spa_l2cache_avl);
1209 vd->vdev_isl2cache = B_FALSE;
1210 mutex_exit(&spa_l2cache_lock);
1214 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
1218 mutex_enter(&spa_l2cache_lock);
1219 found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
1220 mutex_exit(&spa_l2cache_lock);
1226 spa_l2cache_activate(vdev_t *vd)
1228 mutex_enter(&spa_l2cache_lock);
1229 ASSERT(vd->vdev_isl2cache);
1230 spa_aux_activate(vd, &spa_l2cache_avl);
1231 mutex_exit(&spa_l2cache_lock);
1235 * ==========================================================================
1237 * ==========================================================================
1241 * Lock the given spa_t for the purpose of adding or removing a vdev.
1242 * Grabs the global spa_namespace_lock plus the spa config lock for writing.
1243 * It returns the next transaction group for the spa_t.
1246 spa_vdev_enter(spa_t *spa)
1248 mutex_enter(&spa->spa_vdev_top_lock);
1249 mutex_enter(&spa_namespace_lock);
1250 return (spa_vdev_config_enter(spa));
1254 * Internal implementation for spa_vdev_enter(). Used when a vdev
1255 * operation requires multiple syncs (i.e. removing a device) while
1256 * keeping the spa_namespace_lock held.
1259 spa_vdev_config_enter(spa_t *spa)
1261 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1263 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1265 return (spa_last_synced_txg(spa) + 1);
1269 * Used in combination with spa_vdev_config_enter() to allow the syncing
1270 * of multiple transactions without releasing the spa_namespace_lock.
1273 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error, char *tag)
1275 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1277 int config_changed = B_FALSE;
1279 ASSERT(txg > spa_last_synced_txg(spa));
1281 spa->spa_pending_vdev = NULL;
1284 * Reassess the DTLs.
1286 vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE);
1288 if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
1289 config_changed = B_TRUE;
1290 spa->spa_config_generation++;
1294 * Verify the metaslab classes.
1296 ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
1297 ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
1299 spa_config_exit(spa, SCL_ALL, spa);
1302 * Panic the system if the specified tag requires it. This
1303 * is useful for ensuring that configurations are updated
1306 if (zio_injection_enabled)
1307 zio_handle_panic_injection(spa, tag, 0);
1310 * Note: this txg_wait_synced() is important because it ensures
1311 * that there won't be more than one config change per txg.
1312 * This allows us to use the txg as the generation number.
1315 txg_wait_synced(spa->spa_dsl_pool, txg);
1318 ASSERT(!vd->vdev_detached || vd->vdev_dtl_sm == NULL);
1319 if (vd->vdev_ops->vdev_op_leaf) {
1320 mutex_enter(&vd->vdev_initialize_lock);
1321 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED);
1322 mutex_exit(&vd->vdev_initialize_lock);
1325 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1327 spa_config_exit(spa, SCL_ALL, spa);
1331 * If the config changed, update the config cache.
1334 spa_write_cachefile(spa, B_FALSE, B_TRUE);
1338 * Unlock the spa_t after adding or removing a vdev. Besides undoing the
1339 * locking of spa_vdev_enter(), we also want make sure the transactions have
1340 * synced to disk, and then update the global configuration cache with the new
1344 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
1346 spa_vdev_config_exit(spa, vd, txg, error, FTAG);
1347 mutex_exit(&spa_namespace_lock);
1348 mutex_exit(&spa->spa_vdev_top_lock);
1354 * Lock the given spa_t for the purpose of changing vdev state.
1357 spa_vdev_state_enter(spa_t *spa, int oplocks)
1359 int locks = SCL_STATE_ALL | oplocks;
1362 * Root pools may need to read of the underlying devfs filesystem
1363 * when opening up a vdev. Unfortunately if we're holding the
1364 * SCL_ZIO lock it will result in a deadlock when we try to issue
1365 * the read from the root filesystem. Instead we "prefetch"
1366 * the associated vnodes that we need prior to opening the
1367 * underlying devices and cache them so that we can prevent
1368 * any I/O when we are doing the actual open.
1370 if (spa_is_root(spa)) {
1371 int low = locks & ~(SCL_ZIO - 1);
1372 int high = locks & ~low;
1374 spa_config_enter(spa, high, spa, RW_WRITER);
1375 vdev_hold(spa->spa_root_vdev);
1376 spa_config_enter(spa, low, spa, RW_WRITER);
1378 spa_config_enter(spa, locks, spa, RW_WRITER);
1380 spa->spa_vdev_locks = locks;
1384 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
1386 boolean_t config_changed = B_FALSE;
1388 if (vd != NULL || error == 0)
1389 vdev_dtl_reassess(vd ? vd->vdev_top : spa->spa_root_vdev,
1393 vdev_state_dirty(vd->vdev_top);
1394 config_changed = B_TRUE;
1395 spa->spa_config_generation++;
1398 if (spa_is_root(spa))
1399 vdev_rele(spa->spa_root_vdev);
1401 ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1402 spa_config_exit(spa, spa->spa_vdev_locks, spa);
1405 * If anything changed, wait for it to sync. This ensures that,
1406 * from the system administrator's perspective, zpool(1M) commands
1407 * are synchronous. This is important for things like zpool offline:
1408 * when the command completes, you expect no further I/O from ZFS.
1411 txg_wait_synced(spa->spa_dsl_pool, 0);
1414 * If the config changed, update the config cache.
1416 if (config_changed) {
1417 mutex_enter(&spa_namespace_lock);
1418 spa_write_cachefile(spa, B_FALSE, B_TRUE);
1419 mutex_exit(&spa_namespace_lock);
1426 * ==========================================================================
1427 * Miscellaneous functions
1428 * ==========================================================================
1432 spa_activate_mos_feature(spa_t *spa, const char *feature, dmu_tx_t *tx)
1434 if (!nvlist_exists(spa->spa_label_features, feature)) {
1435 fnvlist_add_boolean(spa->spa_label_features, feature);
1437 * When we are creating the pool (tx_txg==TXG_INITIAL), we can't
1438 * dirty the vdev config because lock SCL_CONFIG is not held.
1439 * Thankfully, in this case we don't need to dirty the config
1440 * because it will be written out anyway when we finish
1441 * creating the pool.
1443 if (tx->tx_txg != TXG_INITIAL)
1444 vdev_config_dirty(spa->spa_root_vdev);
1449 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1451 if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1452 vdev_config_dirty(spa->spa_root_vdev);
1459 spa_rename(const char *name, const char *newname)
1465 * Lookup the spa_t and grab the config lock for writing. We need to
1466 * actually open the pool so that we can sync out the necessary labels.
1467 * It's OK to call spa_open() with the namespace lock held because we
1468 * allow recursive calls for other reasons.
1470 mutex_enter(&spa_namespace_lock);
1471 if ((err = spa_open(name, &spa, FTAG)) != 0) {
1472 mutex_exit(&spa_namespace_lock);
1476 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1478 avl_remove(&spa_namespace_avl, spa);
1479 (void) strlcpy(spa->spa_name, newname, sizeof (spa->spa_name));
1480 avl_add(&spa_namespace_avl, spa);
1483 * Sync all labels to disk with the new names by marking the root vdev
1484 * dirty and waiting for it to sync. It will pick up the new pool name
1487 vdev_config_dirty(spa->spa_root_vdev);
1489 spa_config_exit(spa, SCL_ALL, FTAG);
1491 txg_wait_synced(spa->spa_dsl_pool, 0);
1494 * Sync the updated config cache.
1496 spa_write_cachefile(spa, B_FALSE, B_TRUE);
1498 spa_close(spa, FTAG);
1500 mutex_exit(&spa_namespace_lock);
1506 * Return the spa_t associated with given pool_guid, if it exists. If
1507 * device_guid is non-zero, determine whether the pool exists *and* contains
1508 * a device with the specified device_guid.
1511 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1514 avl_tree_t *t = &spa_namespace_avl;
1516 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1518 for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1519 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1521 if (spa->spa_root_vdev == NULL)
1523 if (spa_guid(spa) == pool_guid) {
1524 if (device_guid == 0)
1527 if (vdev_lookup_by_guid(spa->spa_root_vdev,
1528 device_guid) != NULL)
1532 * Check any devices we may be in the process of adding.
1534 if (spa->spa_pending_vdev) {
1535 if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1536 device_guid) != NULL)
1546 * Determine whether a pool with the given pool_guid exists.
1549 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1551 return (spa_by_guid(pool_guid, device_guid) != NULL);
1555 spa_strdup(const char *s)
1561 new = kmem_alloc(len + 1, KM_SLEEP);
1569 spa_strfree(char *s)
1571 kmem_free(s, strlen(s) + 1);
1575 spa_get_random(uint64_t range)
1581 (void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
1587 spa_generate_guid(spa_t *spa)
1589 uint64_t guid = spa_get_random(-1ULL);
1592 while (guid == 0 || spa_guid_exists(spa_guid(spa), guid))
1593 guid = spa_get_random(-1ULL);
1595 while (guid == 0 || spa_guid_exists(guid, 0))
1596 guid = spa_get_random(-1ULL);
1603 snprintf_blkptr(char *buf, size_t buflen, const blkptr_t *bp)
1606 char *checksum = NULL;
1607 char *compress = NULL;
1610 if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1611 dmu_object_byteswap_t bswap =
1612 DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1613 (void) snprintf(type, sizeof (type), "bswap %s %s",
1614 DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1615 "metadata" : "data",
1616 dmu_ot_byteswap[bswap].ob_name);
1618 (void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1621 if (!BP_IS_EMBEDDED(bp)) {
1623 zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1625 compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1628 SNPRINTF_BLKPTR(snprintf, ' ', buf, buflen, bp, type, checksum,
1633 spa_freeze(spa_t *spa)
1635 uint64_t freeze_txg = 0;
1637 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1638 if (spa->spa_freeze_txg == UINT64_MAX) {
1639 freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1640 spa->spa_freeze_txg = freeze_txg;
1642 spa_config_exit(spa, SCL_ALL, FTAG);
1643 if (freeze_txg != 0)
1644 txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1648 zfs_panic_recover(const char *fmt, ...)
1653 vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1658 * This is a stripped-down version of strtoull, suitable only for converting
1659 * lowercase hexadecimal numbers that don't overflow.
1662 zfs_strtonum(const char *str, char **nptr)
1668 while ((c = *str) != '\0') {
1669 if (c >= '0' && c <= '9')
1671 else if (c >= 'a' && c <= 'f')
1672 digit = 10 + c - 'a';
1683 *nptr = (char *)str;
1689 * ==========================================================================
1690 * Accessor functions
1691 * ==========================================================================
1695 spa_shutting_down(spa_t *spa)
1697 return (spa->spa_async_suspended);
1701 spa_get_dsl(spa_t *spa)
1703 return (spa->spa_dsl_pool);
1707 spa_is_initializing(spa_t *spa)
1709 return (spa->spa_is_initializing);
1713 spa_indirect_vdevs_loaded(spa_t *spa)
1715 return (spa->spa_indirect_vdevs_loaded);
1719 spa_get_rootblkptr(spa_t *spa)
1721 return (&spa->spa_ubsync.ub_rootbp);
1725 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1727 spa->spa_uberblock.ub_rootbp = *bp;
1731 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1733 if (spa->spa_root == NULL)
1736 (void) strncpy(buf, spa->spa_root, buflen);
1740 spa_sync_pass(spa_t *spa)
1742 return (spa->spa_sync_pass);
1746 spa_name(spa_t *spa)
1748 return (spa->spa_name);
1752 spa_guid(spa_t *spa)
1754 dsl_pool_t *dp = spa_get_dsl(spa);
1758 * If we fail to parse the config during spa_load(), we can go through
1759 * the error path (which posts an ereport) and end up here with no root
1760 * vdev. We stash the original pool guid in 'spa_config_guid' to handle
1763 if (spa->spa_root_vdev == NULL)
1764 return (spa->spa_config_guid);
1766 guid = spa->spa_last_synced_guid != 0 ?
1767 spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1770 * Return the most recently synced out guid unless we're
1771 * in syncing context.
1773 if (dp && dsl_pool_sync_context(dp))
1774 return (spa->spa_root_vdev->vdev_guid);
1780 spa_load_guid(spa_t *spa)
1783 * This is a GUID that exists solely as a reference for the
1784 * purposes of the arc. It is generated at load time, and
1785 * is never written to persistent storage.
1787 return (spa->spa_load_guid);
1791 spa_last_synced_txg(spa_t *spa)
1793 return (spa->spa_ubsync.ub_txg);
1797 spa_first_txg(spa_t *spa)
1799 return (spa->spa_first_txg);
1803 spa_syncing_txg(spa_t *spa)
1805 return (spa->spa_syncing_txg);
1809 * Return the last txg where data can be dirtied. The final txgs
1810 * will be used to just clear out any deferred frees that remain.
1813 spa_final_dirty_txg(spa_t *spa)
1815 return (spa->spa_final_txg - TXG_DEFER_SIZE);
1819 spa_state(spa_t *spa)
1821 return (spa->spa_state);
1825 spa_load_state(spa_t *spa)
1827 return (spa->spa_load_state);
1831 spa_freeze_txg(spa_t *spa)
1833 return (spa->spa_freeze_txg);
1838 spa_get_worst_case_asize(spa_t *spa, uint64_t lsize)
1840 return (lsize * spa_asize_inflation);
1844 * Return the amount of slop space in bytes. It is 1/32 of the pool (3.2%),
1845 * or at least 128MB, unless that would cause it to be more than half the
1848 * See the comment above spa_slop_shift for details.
1851 spa_get_slop_space(spa_t *spa)
1853 uint64_t space = spa_get_dspace(spa);
1854 return (MAX(space >> spa_slop_shift, MIN(space >> 1, spa_min_slop)));
1858 spa_get_dspace(spa_t *spa)
1860 return (spa->spa_dspace);
1864 spa_get_checkpoint_space(spa_t *spa)
1866 return (spa->spa_checkpoint_info.sci_dspace);
1870 spa_update_dspace(spa_t *spa)
1872 spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1873 ddt_get_dedup_dspace(spa);
1874 if (spa->spa_vdev_removal != NULL) {
1876 * We can't allocate from the removing device, so
1877 * subtract its size. This prevents the DMU/DSL from
1878 * filling up the (now smaller) pool while we are in the
1879 * middle of removing the device.
1881 * Note that the DMU/DSL doesn't actually know or care
1882 * how much space is allocated (it does its own tracking
1883 * of how much space has been logically used). So it
1884 * doesn't matter that the data we are moving may be
1885 * allocated twice (on the old device and the new
1888 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1890 vdev_lookup_top(spa, spa->spa_vdev_removal->svr_vdev_id);
1891 spa->spa_dspace -= spa_deflate(spa) ?
1892 vd->vdev_stat.vs_dspace : vd->vdev_stat.vs_space;
1893 spa_config_exit(spa, SCL_VDEV, FTAG);
1898 * Return the failure mode that has been set to this pool. The default
1899 * behavior will be to block all I/Os when a complete failure occurs.
1902 spa_get_failmode(spa_t *spa)
1904 return (spa->spa_failmode);
1908 spa_suspended(spa_t *spa)
1910 return (spa->spa_suspended);
1914 spa_version(spa_t *spa)
1916 return (spa->spa_ubsync.ub_version);
1920 spa_deflate(spa_t *spa)
1922 return (spa->spa_deflate);
1926 spa_normal_class(spa_t *spa)
1928 return (spa->spa_normal_class);
1932 spa_log_class(spa_t *spa)
1934 return (spa->spa_log_class);
1938 spa_evicting_os_register(spa_t *spa, objset_t *os)
1940 mutex_enter(&spa->spa_evicting_os_lock);
1941 list_insert_head(&spa->spa_evicting_os_list, os);
1942 mutex_exit(&spa->spa_evicting_os_lock);
1946 spa_evicting_os_deregister(spa_t *spa, objset_t *os)
1948 mutex_enter(&spa->spa_evicting_os_lock);
1949 list_remove(&spa->spa_evicting_os_list, os);
1950 cv_broadcast(&spa->spa_evicting_os_cv);
1951 mutex_exit(&spa->spa_evicting_os_lock);
1955 spa_evicting_os_wait(spa_t *spa)
1957 mutex_enter(&spa->spa_evicting_os_lock);
1958 while (!list_is_empty(&spa->spa_evicting_os_list))
1959 cv_wait(&spa->spa_evicting_os_cv, &spa->spa_evicting_os_lock);
1960 mutex_exit(&spa->spa_evicting_os_lock);
1962 dmu_buf_user_evict_wait();
1966 spa_max_replication(spa_t *spa)
1969 * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1970 * handle BPs with more than one DVA allocated. Set our max
1971 * replication level accordingly.
1973 if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1975 return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1979 spa_prev_software_version(spa_t *spa)
1981 return (spa->spa_prev_software_version);
1985 spa_deadman_synctime(spa_t *spa)
1987 return (spa->spa_deadman_synctime);
1991 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
1993 uint64_t asize = DVA_GET_ASIZE(dva);
1994 uint64_t dsize = asize;
1996 ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1998 if (asize != 0 && spa->spa_deflate) {
1999 uint64_t vdev = DVA_GET_VDEV(dva);
2000 vdev_t *vd = vdev_lookup_top(spa, vdev);
2003 "dva_get_dsize_sync(): bad DVA %llu:%llu",
2004 (u_longlong_t)vdev, (u_longlong_t)asize);
2006 dsize = (asize >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio;
2013 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
2017 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
2018 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
2024 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
2028 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2030 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
2031 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
2033 spa_config_exit(spa, SCL_VDEV, FTAG);
2039 spa_dirty_data(spa_t *spa)
2041 return (spa->spa_dsl_pool->dp_dirty_total);
2045 * ==========================================================================
2046 * Initialization and Termination
2047 * ==========================================================================
2051 spa_name_compare(const void *a1, const void *a2)
2053 const spa_t *s1 = a1;
2054 const spa_t *s2 = a2;
2057 s = strcmp(s1->spa_name, s2->spa_name);
2059 return (AVL_ISIGN(s));
2065 return (spa_active_count);
2075 EVENTHANDLER_DEFINE(mountroot, spa_boot_init, NULL, 0);
2081 mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
2082 mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
2083 mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
2084 cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
2086 avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
2087 offsetof(spa_t, spa_avl));
2089 avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
2090 offsetof(spa_aux_t, aux_avl));
2092 avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
2093 offsetof(spa_aux_t, aux_avl));
2095 spa_mode_global = mode;
2101 if (spa_mode_global != FREAD && dprintf_find_string("watch")) {
2102 arc_procfd = open("/proc/self/ctl", O_WRONLY);
2103 if (arc_procfd == -1) {
2104 perror("could not enable watchpoints: "
2105 "opening /proc/self/ctl failed: ");
2111 #endif /* illumos */
2115 metaslab_alloc_trace_init();
2120 vdev_cache_stat_init();
2124 zpool_feature_init();
2128 dsl_scan_global_init();
2133 #endif /* !illumos */
2144 vdev_cache_stat_fini();
2149 metaslab_alloc_trace_fini();
2155 avl_destroy(&spa_namespace_avl);
2156 avl_destroy(&spa_spare_avl);
2157 avl_destroy(&spa_l2cache_avl);
2159 cv_destroy(&spa_namespace_cv);
2160 mutex_destroy(&spa_namespace_lock);
2161 mutex_destroy(&spa_spare_lock);
2162 mutex_destroy(&spa_l2cache_lock);
2166 * Return whether this pool has slogs. No locking needed.
2167 * It's not a problem if the wrong answer is returned as it's only for
2168 * performance and not correctness
2171 spa_has_slogs(spa_t *spa)
2173 return (spa->spa_log_class->mc_rotor != NULL);
2177 spa_get_log_state(spa_t *spa)
2179 return (spa->spa_log_state);
2183 spa_set_log_state(spa_t *spa, spa_log_state_t state)
2185 spa->spa_log_state = state;
2189 spa_is_root(spa_t *spa)
2191 return (spa->spa_is_root);
2195 spa_writeable(spa_t *spa)
2197 return (!!(spa->spa_mode & FWRITE) && spa->spa_trust_config);
2201 * Returns true if there is a pending sync task in any of the current
2202 * syncing txg, the current quiescing txg, or the current open txg.
2205 spa_has_pending_synctask(spa_t *spa)
2207 return (!txg_all_lists_empty(&spa->spa_dsl_pool->dp_sync_tasks) ||
2208 !txg_all_lists_empty(&spa->spa_dsl_pool->dp_early_sync_tasks));
2212 spa_mode(spa_t *spa)
2214 return (spa->spa_mode);
2218 spa_bootfs(spa_t *spa)
2220 return (spa->spa_bootfs);
2224 spa_delegation(spa_t *spa)
2226 return (spa->spa_delegation);
2230 spa_meta_objset(spa_t *spa)
2232 return (spa->spa_meta_objset);
2236 spa_dedup_checksum(spa_t *spa)
2238 return (spa->spa_dedup_checksum);
2242 * Reset pool scan stat per scan pass (or reboot).
2245 spa_scan_stat_init(spa_t *spa)
2247 /* data not stored on disk */
2248 spa->spa_scan_pass_start = gethrestime_sec();
2249 if (dsl_scan_is_paused_scrub(spa->spa_dsl_pool->dp_scan))
2250 spa->spa_scan_pass_scrub_pause = spa->spa_scan_pass_start;
2252 spa->spa_scan_pass_scrub_pause = 0;
2253 spa->spa_scan_pass_scrub_spent_paused = 0;
2254 spa->spa_scan_pass_exam = 0;
2255 spa->spa_scan_pass_issued = 0;
2256 vdev_scan_stat_init(spa->spa_root_vdev);
2260 * Get scan stats for zpool status reports
2263 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
2265 dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
2267 if (scn == NULL || scn->scn_phys.scn_func == POOL_SCAN_NONE)
2268 return (SET_ERROR(ENOENT));
2269 bzero(ps, sizeof (pool_scan_stat_t));
2271 /* data stored on disk */
2272 ps->pss_func = scn->scn_phys.scn_func;
2273 ps->pss_state = scn->scn_phys.scn_state;
2274 ps->pss_start_time = scn->scn_phys.scn_start_time;
2275 ps->pss_end_time = scn->scn_phys.scn_end_time;
2276 ps->pss_to_examine = scn->scn_phys.scn_to_examine;
2277 ps->pss_to_process = scn->scn_phys.scn_to_process;
2278 ps->pss_processed = scn->scn_phys.scn_processed;
2279 ps->pss_errors = scn->scn_phys.scn_errors;
2280 ps->pss_examined = scn->scn_phys.scn_examined;
2282 scn->scn_issued_before_pass + spa->spa_scan_pass_issued;
2283 /* data not stored on disk */
2284 ps->pss_pass_start = spa->spa_scan_pass_start;
2285 ps->pss_pass_exam = spa->spa_scan_pass_exam;
2286 ps->pss_pass_issued = spa->spa_scan_pass_issued;
2287 ps->pss_pass_scrub_pause = spa->spa_scan_pass_scrub_pause;
2288 ps->pss_pass_scrub_spent_paused = spa->spa_scan_pass_scrub_spent_paused;
2294 spa_maxblocksize(spa_t *spa)
2296 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
2297 return (SPA_MAXBLOCKSIZE);
2299 return (SPA_OLD_MAXBLOCKSIZE);
2303 spa_maxdnodesize(spa_t *spa)
2305 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE))
2306 return (DNODE_MAX_SIZE);
2308 return (DNODE_MIN_SIZE);
2313 * Returns the txg that the last device removal completed. No indirect mappings
2314 * have been added since this txg.
2317 spa_get_last_removal_txg(spa_t *spa)
2320 uint64_t ret = -1ULL;
2322 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2324 * sr_prev_indirect_vdev is only modified while holding all the
2325 * config locks, so it is sufficient to hold SCL_VDEV as reader when
2328 vdevid = spa->spa_removing_phys.sr_prev_indirect_vdev;
2330 while (vdevid != -1ULL) {
2331 vdev_t *vd = vdev_lookup_top(spa, vdevid);
2332 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
2334 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
2337 * If the removal did not remap any data, we don't care.
2339 if (vdev_indirect_births_count(vib) != 0) {
2340 ret = vdev_indirect_births_last_entry_txg(vib);
2344 vdevid = vd->vdev_indirect_config.vic_prev_indirect_vdev;
2346 spa_config_exit(spa, SCL_VDEV, FTAG);
2349 spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
2355 spa_trust_config(spa_t *spa)
2357 return (spa->spa_trust_config);
2361 spa_missing_tvds_allowed(spa_t *spa)
2363 return (spa->spa_missing_tvds_allowed);
2367 spa_set_missing_tvds(spa_t *spa, uint64_t missing)
2369 spa->spa_missing_tvds = missing;
2373 spa_top_vdevs_spacemap_addressable(spa_t *spa)
2375 vdev_t *rvd = spa->spa_root_vdev;
2376 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
2377 if (!vdev_is_spacemap_addressable(rvd->vdev_child[c]))
2384 spa_has_checkpoint(spa_t *spa)
2386 return (spa->spa_checkpoint_txg != 0);
2390 spa_importing_readonly_checkpoint(spa_t *spa)
2392 return ((spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT) &&
2393 spa->spa_mode == FREAD);
2397 spa_min_claim_txg(spa_t *spa)
2399 uint64_t checkpoint_txg = spa->spa_uberblock.ub_checkpoint_txg;
2401 if (checkpoint_txg != 0)
2402 return (checkpoint_txg + 1);
2404 return (spa->spa_first_txg);
2408 * If there is a checkpoint, async destroys may consume more space from
2409 * the pool instead of freeing it. In an attempt to save the pool from
2410 * getting suspended when it is about to run out of space, we stop
2411 * processing async destroys.
2414 spa_suspend_async_destroy(spa_t *spa)
2416 dsl_pool_t *dp = spa_get_dsl(spa);
2418 uint64_t unreserved = dsl_pool_unreserved_space(dp,
2419 ZFS_SPACE_CHECK_EXTRA_RESERVED);
2420 uint64_t used = dsl_dir_phys(dp->dp_root_dir)->dd_used_bytes;
2421 uint64_t avail = (unreserved > used) ? (unreserved - used) : 0;
2423 if (spa_has_checkpoint(spa) && avail == 0)