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/metaslab.h>
45 #include <sys/uberblock_impl.h>
48 #include <sys/unique.h>
49 #include <sys/dsl_pool.h>
50 #include <sys/dsl_dir.h>
51 #include <sys/dsl_prop.h>
52 #include <sys/dsl_scan.h>
53 #include <sys/fs/zfs.h>
54 #include <sys/metaslab_impl.h>
58 #include <sys/zfeature.h>
60 #if defined(__FreeBSD__) && defined(_KERNEL)
61 #include <sys/types.h>
62 #include <sys/sysctl.h>
68 * There are four basic locks for managing spa_t structures:
70 * spa_namespace_lock (global mutex)
72 * This lock must be acquired to do any of the following:
74 * - Lookup a spa_t by name
75 * - Add or remove a spa_t from the namespace
76 * - Increase spa_refcount from non-zero
77 * - Check if spa_refcount is zero
79 * - add/remove/attach/detach devices
80 * - Held for the duration of create/destroy/import/export
82 * It does not need to handle recursion. A create or destroy may
83 * reference objects (files or zvols) in other pools, but by
84 * definition they must have an existing reference, and will never need
85 * to lookup a spa_t by name.
87 * spa_refcount (per-spa refcount_t protected by mutex)
89 * This reference count keep track of any active users of the spa_t. The
90 * spa_t cannot be destroyed or freed while this is non-zero. Internally,
91 * the refcount is never really 'zero' - opening a pool implicitly keeps
92 * some references in the DMU. Internally we check against spa_minref, but
93 * present the image of a zero/non-zero value to consumers.
95 * spa_config_lock[] (per-spa array of rwlocks)
97 * This protects the spa_t from config changes, and must be held in
98 * the following circumstances:
100 * - RW_READER to perform I/O to the spa
101 * - RW_WRITER to change the vdev config
103 * The locking order is fairly straightforward:
105 * spa_namespace_lock -> spa_refcount
107 * The namespace lock must be acquired to increase the refcount from 0
108 * or to check if it is zero.
110 * spa_refcount -> spa_config_lock[]
112 * There must be at least one valid reference on the spa_t to acquire
115 * spa_namespace_lock -> spa_config_lock[]
117 * The namespace lock must always be taken before the config lock.
120 * The spa_namespace_lock can be acquired directly and is globally visible.
122 * The namespace is manipulated using the following functions, all of which
123 * require the spa_namespace_lock to be held.
125 * spa_lookup() Lookup a spa_t by name.
127 * spa_add() Create a new spa_t in the namespace.
129 * spa_remove() Remove a spa_t from the namespace. This also
130 * frees up any memory associated with the spa_t.
132 * spa_next() Returns the next spa_t in the system, or the
133 * first if NULL is passed.
135 * spa_evict_all() Shutdown and remove all spa_t structures in
138 * spa_guid_exists() Determine whether a pool/device guid exists.
140 * The spa_refcount is manipulated using the following functions:
142 * spa_open_ref() Adds a reference to the given spa_t. Must be
143 * called with spa_namespace_lock held if the
144 * refcount is currently zero.
146 * spa_close() Remove a reference from the spa_t. This will
147 * not free the spa_t or remove it from the
148 * namespace. No locking is required.
150 * spa_refcount_zero() Returns true if the refcount is currently
151 * zero. Must be called with spa_namespace_lock
154 * The spa_config_lock[] is an array of rwlocks, ordered as follows:
155 * SCL_CONFIG > SCL_STATE > SCL_ALLOC > SCL_ZIO > SCL_FREE > SCL_VDEV.
156 * spa_config_lock[] is manipulated with spa_config_{enter,exit,held}().
158 * To read the configuration, it suffices to hold one of these locks as reader.
159 * To modify the configuration, you must hold all locks as writer. To modify
160 * vdev state without altering the vdev tree's topology (e.g. online/offline),
161 * you must hold SCL_STATE and SCL_ZIO as writer.
163 * We use these distinct config locks to avoid recursive lock entry.
164 * For example, spa_sync() (which holds SCL_CONFIG as reader) induces
165 * block allocations (SCL_ALLOC), which may require reading space maps
166 * from disk (dmu_read() -> zio_read() -> SCL_ZIO).
168 * The spa config locks cannot be normal rwlocks because we need the
169 * ability to hand off ownership. For example, SCL_ZIO is acquired
170 * by the issuing thread and later released by an interrupt thread.
171 * They do, however, obey the usual write-wanted semantics to prevent
172 * writer (i.e. system administrator) starvation.
174 * The lock acquisition rules are as follows:
177 * Protects changes to the vdev tree topology, such as vdev
178 * add/remove/attach/detach. Protects the dirty config list
179 * (spa_config_dirty_list) and the set of spares and l2arc devices.
182 * Protects changes to pool state and vdev state, such as vdev
183 * online/offline/fault/degrade/clear. Protects the dirty state list
184 * (spa_state_dirty_list) and global pool state (spa_state).
187 * Protects changes to metaslab groups and classes.
188 * Held as reader by metaslab_alloc() and metaslab_claim().
191 * Held by bp-level zios (those which have no io_vd upon entry)
192 * to prevent changes to the vdev tree. The bp-level zio implicitly
193 * protects all of its vdev child zios, which do not hold SCL_ZIO.
196 * Protects changes to metaslab groups and classes.
197 * Held as reader by metaslab_free(). SCL_FREE is distinct from
198 * SCL_ALLOC, and lower than SCL_ZIO, so that we can safely free
199 * blocks in zio_done() while another i/o that holds either
200 * SCL_ALLOC or SCL_ZIO is waiting for this i/o to complete.
203 * Held as reader to prevent changes to the vdev tree during trivial
204 * inquiries such as bp_get_dsize(). SCL_VDEV is distinct from the
205 * other locks, and lower than all of them, to ensure that it's safe
206 * to acquire regardless of caller context.
208 * In addition, the following rules apply:
210 * (a) spa_props_lock protects pool properties, spa_config and spa_config_list.
211 * The lock ordering is SCL_CONFIG > spa_props_lock.
213 * (b) I/O operations on leaf vdevs. For any zio operation that takes
214 * an explicit vdev_t argument -- such as zio_ioctl(), zio_read_phys(),
215 * or zio_write_phys() -- the caller must ensure that the config cannot
216 * cannot change in the interim, and that the vdev cannot be reopened.
217 * SCL_STATE as reader suffices for both.
219 * The vdev configuration is protected by spa_vdev_enter() / spa_vdev_exit().
221 * spa_vdev_enter() Acquire the namespace lock and the config lock
224 * spa_vdev_exit() Release the config lock, wait for all I/O
225 * to complete, sync the updated configs to the
226 * cache, and release the namespace lock.
228 * vdev state is protected by spa_vdev_state_enter() / spa_vdev_state_exit().
229 * Like spa_vdev_enter/exit, these are convenience wrappers -- the actual
230 * locking is, always, based on spa_namespace_lock and spa_config_lock[].
232 * spa_rename() is also implemented within this file since it requires
233 * manipulation of the namespace.
236 static avl_tree_t spa_namespace_avl;
237 kmutex_t spa_namespace_lock;
238 static kcondvar_t spa_namespace_cv;
239 static int spa_active_count;
240 int spa_max_replication_override = SPA_DVAS_PER_BP;
242 static kmutex_t spa_spare_lock;
243 static avl_tree_t spa_spare_avl;
244 static kmutex_t spa_l2cache_lock;
245 static avl_tree_t spa_l2cache_avl;
247 kmem_cache_t *spa_buffer_pool;
252 * Everything except dprintf, spa, and indirect_remap is on by default
255 int zfs_flags = ~(ZFS_DEBUG_DPRINTF | ZFS_DEBUG_SPA | ZFS_DEBUG_INDIRECT_REMAP);
261 * zfs_recover can be set to nonzero to attempt to recover from
262 * otherwise-fatal errors, typically caused by on-disk corruption. When
263 * set, calls to zfs_panic_recover() will turn into warning messages.
264 * This should only be used as a last resort, as it typically results
265 * in leaked space, or worse.
267 boolean_t zfs_recover = B_FALSE;
270 * If destroy encounters an EIO while reading metadata (e.g. indirect
271 * blocks), space referenced by the missing metadata can not be freed.
272 * Normally this causes the background destroy to become "stalled", as
273 * it is unable to make forward progress. While in this stalled state,
274 * all remaining space to free from the error-encountering filesystem is
275 * "temporarily leaked". Set this flag to cause it to ignore the EIO,
276 * permanently leak the space from indirect blocks that can not be read,
277 * and continue to free everything else that it can.
279 * The default, "stalling" behavior is useful if the storage partially
280 * fails (i.e. some but not all i/os fail), and then later recovers. In
281 * this case, we will be able to continue pool operations while it is
282 * partially failed, and when it recovers, we can continue to free the
283 * space, with no leaks. However, note that this case is actually
286 * Typically pools either (a) fail completely (but perhaps temporarily,
287 * e.g. a top-level vdev going offline), or (b) have localized,
288 * permanent errors (e.g. disk returns the wrong data due to bit flip or
289 * firmware bug). In case (a), this setting does not matter because the
290 * pool will be suspended and the sync thread will not be able to make
291 * forward progress regardless. In case (b), because the error is
292 * permanent, the best we can do is leak the minimum amount of space,
293 * which is what setting this flag will do. Therefore, it is reasonable
294 * for this flag to normally be set, but we chose the more conservative
295 * approach of not setting it, so that there is no possibility of
296 * leaking space in the "partial temporary" failure case.
298 boolean_t zfs_free_leak_on_eio = B_FALSE;
301 * Expiration time in milliseconds. This value has two meanings. First it is
302 * used to determine when the spa_deadman() logic should fire. By default the
303 * spa_deadman() will fire if spa_sync() has not completed in 1000 seconds.
304 * Secondly, the value determines if an I/O is considered "hung". Any I/O that
305 * has not completed in zfs_deadman_synctime_ms is considered "hung" resulting
308 uint64_t zfs_deadman_synctime_ms = 1000000ULL;
311 * Check time in milliseconds. This defines the frequency at which we check
314 uint64_t zfs_deadman_checktime_ms = 5000ULL;
317 * Default value of -1 for zfs_deadman_enabled is resolved in
320 int zfs_deadman_enabled = -1;
323 * The worst case is single-sector max-parity RAID-Z blocks, in which
324 * case the space requirement is exactly (VDEV_RAIDZ_MAXPARITY + 1)
325 * times the size; so just assume that. Add to this the fact that
326 * we can have up to 3 DVAs per bp, and one more factor of 2 because
327 * the block may be dittoed with up to 3 DVAs by ddt_sync(). All together,
329 * (VDEV_RAIDZ_MAXPARITY + 1) * SPA_DVAS_PER_BP * 2 == 24
331 int spa_asize_inflation = 24;
333 #if defined(__FreeBSD__) && defined(_KERNEL)
334 SYSCTL_DECL(_vfs_zfs);
335 SYSCTL_INT(_vfs_zfs, OID_AUTO, recover, CTLFLAG_RWTUN, &zfs_recover, 0,
336 "Try to recover from otherwise-fatal errors.");
339 sysctl_vfs_zfs_debug_flags(SYSCTL_HANDLER_ARGS)
344 err = sysctl_handle_int(oidp, &val, 0, req);
345 if (err != 0 || req->newptr == NULL)
349 * ZFS_DEBUG_MODIFY must be enabled prior to boot so all
350 * arc buffers in the system have the necessary additional
351 * checksum data. However, it is safe to disable at any
354 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
355 val &= ~ZFS_DEBUG_MODIFY;
361 SYSCTL_PROC(_vfs_zfs, OID_AUTO, debugflags,
362 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RWTUN, 0, sizeof(int),
363 sysctl_vfs_zfs_debug_flags, "IU", "Debug flags for ZFS testing.");
365 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, deadman_synctime_ms, CTLFLAG_RDTUN,
366 &zfs_deadman_synctime_ms, 0,
367 "Stalled ZFS I/O expiration time in milliseconds");
368 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, deadman_checktime_ms, CTLFLAG_RDTUN,
369 &zfs_deadman_checktime_ms, 0,
370 "Period of checks for stalled ZFS I/O in milliseconds");
371 SYSCTL_INT(_vfs_zfs, OID_AUTO, deadman_enabled, CTLFLAG_RDTUN,
372 &zfs_deadman_enabled, 0, "Kernel panic on stalled ZFS I/O");
373 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_asize_inflation, CTLFLAG_RWTUN,
374 &spa_asize_inflation, 0, "Worst case inflation factor for single sector writes");
383 * If we are not i386 or amd64 or in a virtual machine,
384 * disable ZFS deadman thread by default
386 if (zfs_deadman_enabled == -1) {
387 #if defined(__amd64__) || defined(__i386__)
388 zfs_deadman_enabled = (vm_guest == VM_GUEST_NO) ? 1 : 0;
390 zfs_deadman_enabled = 0;
395 #endif /* !illumos */
398 * Normally, we don't allow the last 3.2% (1/(2^spa_slop_shift)) of space in
399 * the pool to be consumed. This ensures that we don't run the pool
400 * completely out of space, due to unaccounted changes (e.g. to the MOS).
401 * It also limits the worst-case time to allocate space. If we have
402 * less than this amount of free space, most ZPL operations (e.g. write,
403 * create) will return ENOSPC.
405 * Certain operations (e.g. file removal, most administrative actions) can
406 * use half the slop space. They will only return ENOSPC if less than half
407 * the slop space is free. Typically, once the pool has less than the slop
408 * space free, the user will use these operations to free up space in the pool.
409 * These are the operations that call dsl_pool_adjustedsize() with the netfree
410 * argument set to TRUE.
412 * Operations that are almost guaranteed to free up space in the absence of
413 * a pool checkpoint can use up to three quarters of the slop space
416 * A very restricted set of operations are always permitted, regardless of
417 * the amount of free space. These are the operations that call
418 * dsl_sync_task(ZFS_SPACE_CHECK_NONE). If these operations result in a net
419 * increase in the amount of space used, it is possible to run the pool
420 * completely out of space, causing it to be permanently read-only.
422 * Note that on very small pools, the slop space will be larger than
423 * 3.2%, in an effort to have it be at least spa_min_slop (128MB),
424 * but we never allow it to be more than half the pool size.
426 * See also the comments in zfs_space_check_t.
428 int spa_slop_shift = 5;
429 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_slop_shift, CTLFLAG_RWTUN,
431 "Shift value of reserved space (1/(2^spa_slop_shift)).");
432 uint64_t spa_min_slop = 128 * 1024 * 1024;
433 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, spa_min_slop, CTLFLAG_RWTUN,
435 "Minimal value of reserved space");
437 int spa_allocators = 4;
441 spa_load_failed(spa_t *spa, const char *fmt, ...)
447 (void) vsnprintf(buf, sizeof (buf), fmt, adx);
450 zfs_dbgmsg("spa_load(%s, config %s): FAILED: %s", spa->spa_name,
451 spa->spa_trust_config ? "trusted" : "untrusted", buf);
456 spa_load_note(spa_t *spa, const char *fmt, ...)
462 (void) vsnprintf(buf, sizeof (buf), fmt, adx);
465 zfs_dbgmsg("spa_load(%s, config %s): %s", spa->spa_name,
466 spa->spa_trust_config ? "trusted" : "untrusted", buf);
470 * ==========================================================================
472 * ==========================================================================
475 spa_config_lock_init(spa_t *spa)
477 for (int i = 0; i < SCL_LOCKS; i++) {
478 spa_config_lock_t *scl = &spa->spa_config_lock[i];
479 mutex_init(&scl->scl_lock, NULL, MUTEX_DEFAULT, NULL);
480 cv_init(&scl->scl_cv, NULL, CV_DEFAULT, NULL);
481 refcount_create_untracked(&scl->scl_count);
482 scl->scl_writer = NULL;
483 scl->scl_write_wanted = 0;
488 spa_config_lock_destroy(spa_t *spa)
490 for (int i = 0; i < SCL_LOCKS; i++) {
491 spa_config_lock_t *scl = &spa->spa_config_lock[i];
492 mutex_destroy(&scl->scl_lock);
493 cv_destroy(&scl->scl_cv);
494 refcount_destroy(&scl->scl_count);
495 ASSERT(scl->scl_writer == NULL);
496 ASSERT(scl->scl_write_wanted == 0);
501 spa_config_tryenter(spa_t *spa, int locks, void *tag, krw_t rw)
503 for (int i = 0; i < SCL_LOCKS; i++) {
504 spa_config_lock_t *scl = &spa->spa_config_lock[i];
505 if (!(locks & (1 << i)))
507 mutex_enter(&scl->scl_lock);
508 if (rw == RW_READER) {
509 if (scl->scl_writer || scl->scl_write_wanted) {
510 mutex_exit(&scl->scl_lock);
511 spa_config_exit(spa, locks & ((1 << i) - 1),
516 ASSERT(scl->scl_writer != curthread);
517 if (!refcount_is_zero(&scl->scl_count)) {
518 mutex_exit(&scl->scl_lock);
519 spa_config_exit(spa, locks & ((1 << i) - 1),
523 scl->scl_writer = curthread;
525 (void) refcount_add(&scl->scl_count, tag);
526 mutex_exit(&scl->scl_lock);
532 spa_config_enter(spa_t *spa, int locks, void *tag, krw_t rw)
536 ASSERT3U(SCL_LOCKS, <, sizeof (wlocks_held) * NBBY);
538 for (int i = 0; i < SCL_LOCKS; i++) {
539 spa_config_lock_t *scl = &spa->spa_config_lock[i];
540 if (scl->scl_writer == curthread)
541 wlocks_held |= (1 << i);
542 if (!(locks & (1 << i)))
544 mutex_enter(&scl->scl_lock);
545 if (rw == RW_READER) {
546 while (scl->scl_writer || scl->scl_write_wanted) {
547 cv_wait(&scl->scl_cv, &scl->scl_lock);
550 ASSERT(scl->scl_writer != curthread);
551 while (!refcount_is_zero(&scl->scl_count)) {
552 scl->scl_write_wanted++;
553 cv_wait(&scl->scl_cv, &scl->scl_lock);
554 scl->scl_write_wanted--;
556 scl->scl_writer = curthread;
558 (void) refcount_add(&scl->scl_count, tag);
559 mutex_exit(&scl->scl_lock);
561 ASSERT3U(wlocks_held, <=, locks);
565 spa_config_exit(spa_t *spa, int locks, void *tag)
567 for (int i = SCL_LOCKS - 1; i >= 0; i--) {
568 spa_config_lock_t *scl = &spa->spa_config_lock[i];
569 if (!(locks & (1 << i)))
571 mutex_enter(&scl->scl_lock);
572 ASSERT(!refcount_is_zero(&scl->scl_count));
573 if (refcount_remove(&scl->scl_count, tag) == 0) {
574 ASSERT(scl->scl_writer == NULL ||
575 scl->scl_writer == curthread);
576 scl->scl_writer = NULL; /* OK in either case */
577 cv_broadcast(&scl->scl_cv);
579 mutex_exit(&scl->scl_lock);
584 spa_config_held(spa_t *spa, int locks, krw_t rw)
588 for (int i = 0; i < SCL_LOCKS; i++) {
589 spa_config_lock_t *scl = &spa->spa_config_lock[i];
590 if (!(locks & (1 << i)))
592 if ((rw == RW_READER && !refcount_is_zero(&scl->scl_count)) ||
593 (rw == RW_WRITER && scl->scl_writer == curthread))
594 locks_held |= 1 << i;
601 * ==========================================================================
602 * SPA namespace functions
603 * ==========================================================================
607 * Lookup the named spa_t in the AVL tree. The spa_namespace_lock must be held.
608 * Returns NULL if no matching spa_t is found.
611 spa_lookup(const char *name)
613 static spa_t search; /* spa_t is large; don't allocate on stack */
618 ASSERT(MUTEX_HELD(&spa_namespace_lock));
620 (void) strlcpy(search.spa_name, name, sizeof (search.spa_name));
623 * If it's a full dataset name, figure out the pool name and
626 cp = strpbrk(search.spa_name, "/@#");
630 spa = avl_find(&spa_namespace_avl, &search, &where);
636 * Fires when spa_sync has not completed within zfs_deadman_synctime_ms.
637 * If the zfs_deadman_enabled flag is set then it inspects all vdev queues
638 * looking for potentially hung I/Os.
641 spa_deadman(void *arg, int pending)
646 * Disable the deadman timer if the pool is suspended.
648 if (spa_suspended(spa)) {
650 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
652 /* Nothing. just don't schedule any future callouts. */
657 zfs_dbgmsg("slow spa_sync: started %llu seconds ago, calls %llu",
658 (gethrtime() - spa->spa_sync_starttime) / NANOSEC,
659 ++spa->spa_deadman_calls);
660 if (zfs_deadman_enabled)
661 vdev_deadman(spa->spa_root_vdev);
664 callout_schedule(&spa->spa_deadman_cycid,
665 hz * zfs_deadman_checktime_ms / MILLISEC);
670 #if defined(__FreeBSD__) && defined(_KERNEL)
672 spa_deadman_timeout(void *arg)
676 taskqueue_enqueue(taskqueue_thread, &spa->spa_deadman_task);
681 * Create an uninitialized spa_t with the given name. Requires
682 * spa_namespace_lock. The caller must ensure that the spa_t doesn't already
683 * exist by calling spa_lookup() first.
686 spa_add(const char *name, nvlist_t *config, const char *altroot)
689 spa_config_dirent_t *dp;
695 ASSERT(MUTEX_HELD(&spa_namespace_lock));
697 spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
699 mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
700 mutex_init(&spa->spa_errlist_lock, NULL, MUTEX_DEFAULT, NULL);
701 mutex_init(&spa->spa_errlog_lock, NULL, MUTEX_DEFAULT, NULL);
702 mutex_init(&spa->spa_evicting_os_lock, NULL, MUTEX_DEFAULT, NULL);
703 mutex_init(&spa->spa_history_lock, NULL, MUTEX_DEFAULT, NULL);
704 mutex_init(&spa->spa_proc_lock, NULL, MUTEX_DEFAULT, NULL);
705 mutex_init(&spa->spa_props_lock, NULL, MUTEX_DEFAULT, NULL);
706 mutex_init(&spa->spa_cksum_tmpls_lock, NULL, MUTEX_DEFAULT, NULL);
707 mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
708 mutex_init(&spa->spa_suspend_lock, NULL, MUTEX_DEFAULT, NULL);
709 mutex_init(&spa->spa_vdev_top_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);
717 for (int t = 0; t < TXG_SIZE; t++)
718 bplist_create(&spa->spa_free_bplist[t]);
720 (void) strlcpy(spa->spa_name, name, sizeof (spa->spa_name));
721 spa->spa_state = POOL_STATE_UNINITIALIZED;
722 spa->spa_freeze_txg = UINT64_MAX;
723 spa->spa_final_txg = UINT64_MAX;
724 spa->spa_load_max_txg = UINT64_MAX;
726 spa->spa_proc_state = SPA_PROC_NONE;
727 spa->spa_trust_config = B_TRUE;
730 hdlr.cyh_func = spa_deadman;
732 hdlr.cyh_level = CY_LOW_LEVEL;
735 spa->spa_deadman_synctime = MSEC2NSEC(zfs_deadman_synctime_ms);
739 * This determines how often we need to check for hung I/Os after
740 * the cyclic has already fired. Since checking for hung I/Os is
741 * an expensive operation we don't want to check too frequently.
742 * Instead wait for 5 seconds before checking again.
744 when.cyt_interval = MSEC2NSEC(zfs_deadman_checktime_ms);
745 when.cyt_when = CY_INFINITY;
746 mutex_enter(&cpu_lock);
747 spa->spa_deadman_cycid = cyclic_add(&hdlr, &when);
748 mutex_exit(&cpu_lock);
752 * callout(9) does not provide a way to initialize a callout with
753 * a function and an argument, so we use callout_reset() to schedule
754 * the callout in the very distant future. Even if that event ever
755 * fires, it should be okayas we won't have any active zio-s.
756 * But normally spa_sync() will reschedule the callout with a proper
758 * callout(9) does not allow the callback function to sleep but
759 * vdev_deadman() needs to acquire vq_lock and illumos mutexes are
760 * emulated using sx(9). For this reason spa_deadman_timeout()
761 * will schedule spa_deadman() as task on a taskqueue that allows
764 TASK_INIT(&spa->spa_deadman_task, 0, spa_deadman, spa);
765 callout_init(&spa->spa_deadman_cycid, 1);
766 callout_reset_sbt(&spa->spa_deadman_cycid, SBT_MAX, 0,
767 spa_deadman_timeout, spa, 0);
770 refcount_create(&spa->spa_refcount);
771 spa_config_lock_init(spa);
773 avl_add(&spa_namespace_avl, spa);
776 * Set the alternate root, if there is one.
779 spa->spa_root = spa_strdup(altroot);
783 spa->spa_alloc_count = spa_allocators;
784 spa->spa_alloc_locks = kmem_zalloc(spa->spa_alloc_count *
785 sizeof (kmutex_t), KM_SLEEP);
786 spa->spa_alloc_trees = kmem_zalloc(spa->spa_alloc_count *
787 sizeof (avl_tree_t), KM_SLEEP);
788 for (int i = 0; i < spa->spa_alloc_count; i++) {
789 mutex_init(&spa->spa_alloc_locks[i], NULL, MUTEX_DEFAULT, NULL);
790 avl_create(&spa->spa_alloc_trees[i], zio_bookmark_compare,
791 sizeof (zio_t), offsetof(zio_t, io_alloc_node));
795 * Every pool starts with the default cachefile
797 list_create(&spa->spa_config_list, sizeof (spa_config_dirent_t),
798 offsetof(spa_config_dirent_t, scd_link));
800 dp = kmem_zalloc(sizeof (spa_config_dirent_t), KM_SLEEP);
801 dp->scd_path = altroot ? NULL : spa_strdup(spa_config_path);
802 list_insert_head(&spa->spa_config_list, dp);
804 VERIFY(nvlist_alloc(&spa->spa_load_info, NV_UNIQUE_NAME,
807 if (config != NULL) {
810 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_FEATURES_FOR_READ,
812 VERIFY(nvlist_dup(features, &spa->spa_label_features,
816 VERIFY(nvlist_dup(config, &spa->spa_config, 0) == 0);
819 if (spa->spa_label_features == NULL) {
820 VERIFY(nvlist_alloc(&spa->spa_label_features, NV_UNIQUE_NAME,
824 spa->spa_debug = ((zfs_flags & ZFS_DEBUG_SPA) != 0);
826 spa->spa_min_ashift = INT_MAX;
827 spa->spa_max_ashift = 0;
830 * As a pool is being created, treat all features as disabled by
831 * setting SPA_FEATURE_DISABLED for all entries in the feature
834 for (int i = 0; i < SPA_FEATURES; i++) {
835 spa->spa_feat_refcount_cache[i] = SPA_FEATURE_DISABLED;
842 * Removes a spa_t from the namespace, freeing up any memory used. Requires
843 * spa_namespace_lock. This is called only after the spa_t has been closed and
847 spa_remove(spa_t *spa)
849 spa_config_dirent_t *dp;
851 ASSERT(MUTEX_HELD(&spa_namespace_lock));
852 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
853 ASSERT3U(refcount_count(&spa->spa_refcount), ==, 0);
855 nvlist_free(spa->spa_config_splitting);
857 avl_remove(&spa_namespace_avl, spa);
858 cv_broadcast(&spa_namespace_cv);
861 spa_strfree(spa->spa_root);
865 while ((dp = list_head(&spa->spa_config_list)) != NULL) {
866 list_remove(&spa->spa_config_list, dp);
867 if (dp->scd_path != NULL)
868 spa_strfree(dp->scd_path);
869 kmem_free(dp, sizeof (spa_config_dirent_t));
872 for (int i = 0; i < spa->spa_alloc_count; i++) {
873 avl_destroy(&spa->spa_alloc_trees[i]);
874 mutex_destroy(&spa->spa_alloc_locks[i]);
876 kmem_free(spa->spa_alloc_locks, spa->spa_alloc_count *
878 kmem_free(spa->spa_alloc_trees, spa->spa_alloc_count *
879 sizeof (avl_tree_t));
881 list_destroy(&spa->spa_config_list);
883 nvlist_free(spa->spa_label_features);
884 nvlist_free(spa->spa_load_info);
885 spa_config_set(spa, NULL);
888 mutex_enter(&cpu_lock);
889 if (spa->spa_deadman_cycid != CYCLIC_NONE)
890 cyclic_remove(spa->spa_deadman_cycid);
891 mutex_exit(&cpu_lock);
892 spa->spa_deadman_cycid = CYCLIC_NONE;
895 callout_drain(&spa->spa_deadman_cycid);
896 taskqueue_drain(taskqueue_thread, &spa->spa_deadman_task);
900 refcount_destroy(&spa->spa_refcount);
902 spa_config_lock_destroy(spa);
904 for (int t = 0; t < TXG_SIZE; t++)
905 bplist_destroy(&spa->spa_free_bplist[t]);
907 zio_checksum_templates_free(spa);
909 cv_destroy(&spa->spa_async_cv);
910 cv_destroy(&spa->spa_evicting_os_cv);
911 cv_destroy(&spa->spa_proc_cv);
912 cv_destroy(&spa->spa_scrub_io_cv);
913 cv_destroy(&spa->spa_suspend_cv);
915 mutex_destroy(&spa->spa_async_lock);
916 mutex_destroy(&spa->spa_errlist_lock);
917 mutex_destroy(&spa->spa_errlog_lock);
918 mutex_destroy(&spa->spa_evicting_os_lock);
919 mutex_destroy(&spa->spa_history_lock);
920 mutex_destroy(&spa->spa_proc_lock);
921 mutex_destroy(&spa->spa_props_lock);
922 mutex_destroy(&spa->spa_cksum_tmpls_lock);
923 mutex_destroy(&spa->spa_scrub_lock);
924 mutex_destroy(&spa->spa_suspend_lock);
925 mutex_destroy(&spa->spa_vdev_top_lock);
927 kmem_free(spa, sizeof (spa_t));
931 * Given a pool, return the next pool in the namespace, or NULL if there is
932 * none. If 'prev' is NULL, return the first pool.
935 spa_next(spa_t *prev)
937 ASSERT(MUTEX_HELD(&spa_namespace_lock));
940 return (AVL_NEXT(&spa_namespace_avl, prev));
942 return (avl_first(&spa_namespace_avl));
946 * ==========================================================================
947 * SPA refcount functions
948 * ==========================================================================
952 * Add a reference to the given spa_t. Must have at least one reference, or
953 * have the namespace lock held.
956 spa_open_ref(spa_t *spa, void *tag)
958 ASSERT(refcount_count(&spa->spa_refcount) >= spa->spa_minref ||
959 MUTEX_HELD(&spa_namespace_lock));
960 (void) refcount_add(&spa->spa_refcount, tag);
964 * Remove a reference to the given spa_t. Must have at least one reference, or
965 * have the namespace lock held.
968 spa_close(spa_t *spa, void *tag)
970 ASSERT(refcount_count(&spa->spa_refcount) > spa->spa_minref ||
971 MUTEX_HELD(&spa_namespace_lock));
972 (void) refcount_remove(&spa->spa_refcount, tag);
976 * Remove a reference to the given spa_t held by a dsl dir that is
977 * being asynchronously released. Async releases occur from a taskq
978 * performing eviction of dsl datasets and dirs. The namespace lock
979 * isn't held and the hold by the object being evicted may contribute to
980 * spa_minref (e.g. dataset or directory released during pool export),
981 * so the asserts in spa_close() do not apply.
984 spa_async_close(spa_t *spa, void *tag)
986 (void) refcount_remove(&spa->spa_refcount, tag);
990 * Check to see if the spa refcount is zero. Must be called with
991 * spa_namespace_lock held. We really compare against spa_minref, which is the
992 * number of references acquired when opening a pool
995 spa_refcount_zero(spa_t *spa)
997 ASSERT(MUTEX_HELD(&spa_namespace_lock));
999 return (refcount_count(&spa->spa_refcount) == spa->spa_minref);
1003 * ==========================================================================
1004 * SPA spare and l2cache tracking
1005 * ==========================================================================
1009 * Hot spares and cache devices are tracked using the same code below,
1010 * for 'auxiliary' devices.
1013 typedef struct spa_aux {
1021 spa_aux_compare(const void *a, const void *b)
1023 const spa_aux_t *sa = a;
1024 const spa_aux_t *sb = b;
1026 if (sa->aux_guid < sb->aux_guid)
1028 else if (sa->aux_guid > sb->aux_guid)
1035 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
1041 search.aux_guid = vd->vdev_guid;
1042 if ((aux = avl_find(avl, &search, &where)) != NULL) {
1045 aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
1046 aux->aux_guid = vd->vdev_guid;
1048 avl_insert(avl, aux, where);
1053 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
1059 search.aux_guid = vd->vdev_guid;
1060 aux = avl_find(avl, &search, &where);
1062 ASSERT(aux != NULL);
1064 if (--aux->aux_count == 0) {
1065 avl_remove(avl, aux);
1066 kmem_free(aux, sizeof (spa_aux_t));
1067 } else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
1068 aux->aux_pool = 0ULL;
1073 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
1075 spa_aux_t search, *found;
1077 search.aux_guid = guid;
1078 found = avl_find(avl, &search, NULL);
1082 *pool = found->aux_pool;
1089 *refcnt = found->aux_count;
1094 return (found != NULL);
1098 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
1100 spa_aux_t search, *found;
1103 search.aux_guid = vd->vdev_guid;
1104 found = avl_find(avl, &search, &where);
1105 ASSERT(found != NULL);
1106 ASSERT(found->aux_pool == 0ULL);
1108 found->aux_pool = spa_guid(vd->vdev_spa);
1112 * Spares are tracked globally due to the following constraints:
1114 * - A spare may be part of multiple pools.
1115 * - A spare may be added to a pool even if it's actively in use within
1117 * - A spare in use in any pool can only be the source of a replacement if
1118 * the target is a spare in the same pool.
1120 * We keep track of all spares on the system through the use of a reference
1121 * counted AVL tree. When a vdev is added as a spare, or used as a replacement
1122 * spare, then we bump the reference count in the AVL tree. In addition, we set
1123 * the 'vdev_isspare' member to indicate that the device is a spare (active or
1124 * inactive). When a spare is made active (used to replace a device in the
1125 * pool), we also keep track of which pool its been made a part of.
1127 * The 'spa_spare_lock' protects the AVL tree. These functions are normally
1128 * called under the spa_namespace lock as part of vdev reconfiguration. The
1129 * separate spare lock exists for the status query path, which does not need to
1130 * be completely consistent with respect to other vdev configuration changes.
1134 spa_spare_compare(const void *a, const void *b)
1136 return (spa_aux_compare(a, b));
1140 spa_spare_add(vdev_t *vd)
1142 mutex_enter(&spa_spare_lock);
1143 ASSERT(!vd->vdev_isspare);
1144 spa_aux_add(vd, &spa_spare_avl);
1145 vd->vdev_isspare = B_TRUE;
1146 mutex_exit(&spa_spare_lock);
1150 spa_spare_remove(vdev_t *vd)
1152 mutex_enter(&spa_spare_lock);
1153 ASSERT(vd->vdev_isspare);
1154 spa_aux_remove(vd, &spa_spare_avl);
1155 vd->vdev_isspare = B_FALSE;
1156 mutex_exit(&spa_spare_lock);
1160 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
1164 mutex_enter(&spa_spare_lock);
1165 found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
1166 mutex_exit(&spa_spare_lock);
1172 spa_spare_activate(vdev_t *vd)
1174 mutex_enter(&spa_spare_lock);
1175 ASSERT(vd->vdev_isspare);
1176 spa_aux_activate(vd, &spa_spare_avl);
1177 mutex_exit(&spa_spare_lock);
1181 * Level 2 ARC devices are tracked globally for the same reasons as spares.
1182 * Cache devices currently only support one pool per cache device, and so
1183 * for these devices the aux reference count is currently unused beyond 1.
1187 spa_l2cache_compare(const void *a, const void *b)
1189 return (spa_aux_compare(a, b));
1193 spa_l2cache_add(vdev_t *vd)
1195 mutex_enter(&spa_l2cache_lock);
1196 ASSERT(!vd->vdev_isl2cache);
1197 spa_aux_add(vd, &spa_l2cache_avl);
1198 vd->vdev_isl2cache = B_TRUE;
1199 mutex_exit(&spa_l2cache_lock);
1203 spa_l2cache_remove(vdev_t *vd)
1205 mutex_enter(&spa_l2cache_lock);
1206 ASSERT(vd->vdev_isl2cache);
1207 spa_aux_remove(vd, &spa_l2cache_avl);
1208 vd->vdev_isl2cache = B_FALSE;
1209 mutex_exit(&spa_l2cache_lock);
1213 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
1217 mutex_enter(&spa_l2cache_lock);
1218 found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
1219 mutex_exit(&spa_l2cache_lock);
1225 spa_l2cache_activate(vdev_t *vd)
1227 mutex_enter(&spa_l2cache_lock);
1228 ASSERT(vd->vdev_isl2cache);
1229 spa_aux_activate(vd, &spa_l2cache_avl);
1230 mutex_exit(&spa_l2cache_lock);
1234 * ==========================================================================
1236 * ==========================================================================
1240 * Lock the given spa_t for the purpose of adding or removing a vdev.
1241 * Grabs the global spa_namespace_lock plus the spa config lock for writing.
1242 * It returns the next transaction group for the spa_t.
1245 spa_vdev_enter(spa_t *spa)
1247 mutex_enter(&spa->spa_vdev_top_lock);
1248 mutex_enter(&spa_namespace_lock);
1249 return (spa_vdev_config_enter(spa));
1253 * Internal implementation for spa_vdev_enter(). Used when a vdev
1254 * operation requires multiple syncs (i.e. removing a device) while
1255 * keeping the spa_namespace_lock held.
1258 spa_vdev_config_enter(spa_t *spa)
1260 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1262 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1264 return (spa_last_synced_txg(spa) + 1);
1268 * Used in combination with spa_vdev_config_enter() to allow the syncing
1269 * of multiple transactions without releasing the spa_namespace_lock.
1272 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error, char *tag)
1274 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1276 int config_changed = B_FALSE;
1278 ASSERT(txg > spa_last_synced_txg(spa));
1280 spa->spa_pending_vdev = NULL;
1283 * Reassess the DTLs.
1285 vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE);
1287 if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
1288 config_changed = B_TRUE;
1289 spa->spa_config_generation++;
1293 * Verify the metaslab classes.
1295 ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
1296 ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
1298 spa_config_exit(spa, SCL_ALL, spa);
1301 * Panic the system if the specified tag requires it. This
1302 * is useful for ensuring that configurations are updated
1305 if (zio_injection_enabled)
1306 zio_handle_panic_injection(spa, tag, 0);
1309 * Note: this txg_wait_synced() is important because it ensures
1310 * that there won't be more than one config change per txg.
1311 * This allows us to use the txg as the generation number.
1314 txg_wait_synced(spa->spa_dsl_pool, txg);
1317 ASSERT(!vd->vdev_detached || vd->vdev_dtl_sm == NULL);
1318 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1320 spa_config_exit(spa, SCL_ALL, spa);
1324 * If the config changed, update the config cache.
1327 spa_write_cachefile(spa, B_FALSE, B_TRUE);
1331 * Unlock the spa_t after adding or removing a vdev. Besides undoing the
1332 * locking of spa_vdev_enter(), we also want make sure the transactions have
1333 * synced to disk, and then update the global configuration cache with the new
1337 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
1339 spa_vdev_config_exit(spa, vd, txg, error, FTAG);
1340 mutex_exit(&spa_namespace_lock);
1341 mutex_exit(&spa->spa_vdev_top_lock);
1347 * Lock the given spa_t for the purpose of changing vdev state.
1350 spa_vdev_state_enter(spa_t *spa, int oplocks)
1352 int locks = SCL_STATE_ALL | oplocks;
1355 * Root pools may need to read of the underlying devfs filesystem
1356 * when opening up a vdev. Unfortunately if we're holding the
1357 * SCL_ZIO lock it will result in a deadlock when we try to issue
1358 * the read from the root filesystem. Instead we "prefetch"
1359 * the associated vnodes that we need prior to opening the
1360 * underlying devices and cache them so that we can prevent
1361 * any I/O when we are doing the actual open.
1363 if (spa_is_root(spa)) {
1364 int low = locks & ~(SCL_ZIO - 1);
1365 int high = locks & ~low;
1367 spa_config_enter(spa, high, spa, RW_WRITER);
1368 vdev_hold(spa->spa_root_vdev);
1369 spa_config_enter(spa, low, spa, RW_WRITER);
1371 spa_config_enter(spa, locks, spa, RW_WRITER);
1373 spa->spa_vdev_locks = locks;
1377 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
1379 boolean_t config_changed = B_FALSE;
1381 if (vd != NULL || error == 0)
1382 vdev_dtl_reassess(vd ? vd->vdev_top : spa->spa_root_vdev,
1386 vdev_state_dirty(vd->vdev_top);
1387 config_changed = B_TRUE;
1388 spa->spa_config_generation++;
1391 if (spa_is_root(spa))
1392 vdev_rele(spa->spa_root_vdev);
1394 ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1395 spa_config_exit(spa, spa->spa_vdev_locks, spa);
1398 * If anything changed, wait for it to sync. This ensures that,
1399 * from the system administrator's perspective, zpool(1M) commands
1400 * are synchronous. This is important for things like zpool offline:
1401 * when the command completes, you expect no further I/O from ZFS.
1404 txg_wait_synced(spa->spa_dsl_pool, 0);
1407 * If the config changed, update the config cache.
1409 if (config_changed) {
1410 mutex_enter(&spa_namespace_lock);
1411 spa_write_cachefile(spa, B_FALSE, B_TRUE);
1412 mutex_exit(&spa_namespace_lock);
1419 * ==========================================================================
1420 * Miscellaneous functions
1421 * ==========================================================================
1425 spa_activate_mos_feature(spa_t *spa, const char *feature, dmu_tx_t *tx)
1427 if (!nvlist_exists(spa->spa_label_features, feature)) {
1428 fnvlist_add_boolean(spa->spa_label_features, feature);
1430 * When we are creating the pool (tx_txg==TXG_INITIAL), we can't
1431 * dirty the vdev config because lock SCL_CONFIG is not held.
1432 * Thankfully, in this case we don't need to dirty the config
1433 * because it will be written out anyway when we finish
1434 * creating the pool.
1436 if (tx->tx_txg != TXG_INITIAL)
1437 vdev_config_dirty(spa->spa_root_vdev);
1442 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1444 if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1445 vdev_config_dirty(spa->spa_root_vdev);
1452 spa_rename(const char *name, const char *newname)
1458 * Lookup the spa_t and grab the config lock for writing. We need to
1459 * actually open the pool so that we can sync out the necessary labels.
1460 * It's OK to call spa_open() with the namespace lock held because we
1461 * allow recursive calls for other reasons.
1463 mutex_enter(&spa_namespace_lock);
1464 if ((err = spa_open(name, &spa, FTAG)) != 0) {
1465 mutex_exit(&spa_namespace_lock);
1469 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1471 avl_remove(&spa_namespace_avl, spa);
1472 (void) strlcpy(spa->spa_name, newname, sizeof (spa->spa_name));
1473 avl_add(&spa_namespace_avl, spa);
1476 * Sync all labels to disk with the new names by marking the root vdev
1477 * dirty and waiting for it to sync. It will pick up the new pool name
1480 vdev_config_dirty(spa->spa_root_vdev);
1482 spa_config_exit(spa, SCL_ALL, FTAG);
1484 txg_wait_synced(spa->spa_dsl_pool, 0);
1487 * Sync the updated config cache.
1489 spa_write_cachefile(spa, B_FALSE, B_TRUE);
1491 spa_close(spa, FTAG);
1493 mutex_exit(&spa_namespace_lock);
1499 * Return the spa_t associated with given pool_guid, if it exists. If
1500 * device_guid is non-zero, determine whether the pool exists *and* contains
1501 * a device with the specified device_guid.
1504 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1507 avl_tree_t *t = &spa_namespace_avl;
1509 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1511 for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1512 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1514 if (spa->spa_root_vdev == NULL)
1516 if (spa_guid(spa) == pool_guid) {
1517 if (device_guid == 0)
1520 if (vdev_lookup_by_guid(spa->spa_root_vdev,
1521 device_guid) != NULL)
1525 * Check any devices we may be in the process of adding.
1527 if (spa->spa_pending_vdev) {
1528 if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1529 device_guid) != NULL)
1539 * Determine whether a pool with the given pool_guid exists.
1542 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1544 return (spa_by_guid(pool_guid, device_guid) != NULL);
1548 spa_strdup(const char *s)
1554 new = kmem_alloc(len + 1, KM_SLEEP);
1562 spa_strfree(char *s)
1564 kmem_free(s, strlen(s) + 1);
1568 spa_get_random(uint64_t range)
1574 (void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
1580 spa_generate_guid(spa_t *spa)
1582 uint64_t guid = spa_get_random(-1ULL);
1585 while (guid == 0 || spa_guid_exists(spa_guid(spa), guid))
1586 guid = spa_get_random(-1ULL);
1588 while (guid == 0 || spa_guid_exists(guid, 0))
1589 guid = spa_get_random(-1ULL);
1596 snprintf_blkptr(char *buf, size_t buflen, const blkptr_t *bp)
1599 char *checksum = NULL;
1600 char *compress = NULL;
1603 if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1604 dmu_object_byteswap_t bswap =
1605 DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1606 (void) snprintf(type, sizeof (type), "bswap %s %s",
1607 DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1608 "metadata" : "data",
1609 dmu_ot_byteswap[bswap].ob_name);
1611 (void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1614 if (!BP_IS_EMBEDDED(bp)) {
1616 zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1618 compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1621 SNPRINTF_BLKPTR(snprintf, ' ', buf, buflen, bp, type, checksum,
1626 spa_freeze(spa_t *spa)
1628 uint64_t freeze_txg = 0;
1630 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1631 if (spa->spa_freeze_txg == UINT64_MAX) {
1632 freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1633 spa->spa_freeze_txg = freeze_txg;
1635 spa_config_exit(spa, SCL_ALL, FTAG);
1636 if (freeze_txg != 0)
1637 txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1641 zfs_panic_recover(const char *fmt, ...)
1646 vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1651 * This is a stripped-down version of strtoull, suitable only for converting
1652 * lowercase hexadecimal numbers that don't overflow.
1655 zfs_strtonum(const char *str, char **nptr)
1661 while ((c = *str) != '\0') {
1662 if (c >= '0' && c <= '9')
1664 else if (c >= 'a' && c <= 'f')
1665 digit = 10 + c - 'a';
1676 *nptr = (char *)str;
1682 * ==========================================================================
1683 * Accessor functions
1684 * ==========================================================================
1688 spa_shutting_down(spa_t *spa)
1690 return (spa->spa_async_suspended);
1694 spa_get_dsl(spa_t *spa)
1696 return (spa->spa_dsl_pool);
1700 spa_is_initializing(spa_t *spa)
1702 return (spa->spa_is_initializing);
1706 spa_indirect_vdevs_loaded(spa_t *spa)
1708 return (spa->spa_indirect_vdevs_loaded);
1712 spa_get_rootblkptr(spa_t *spa)
1714 return (&spa->spa_ubsync.ub_rootbp);
1718 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1720 spa->spa_uberblock.ub_rootbp = *bp;
1724 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1726 if (spa->spa_root == NULL)
1729 (void) strncpy(buf, spa->spa_root, buflen);
1733 spa_sync_pass(spa_t *spa)
1735 return (spa->spa_sync_pass);
1739 spa_name(spa_t *spa)
1741 return (spa->spa_name);
1745 spa_guid(spa_t *spa)
1747 dsl_pool_t *dp = spa_get_dsl(spa);
1751 * If we fail to parse the config during spa_load(), we can go through
1752 * the error path (which posts an ereport) and end up here with no root
1753 * vdev. We stash the original pool guid in 'spa_config_guid' to handle
1756 if (spa->spa_root_vdev == NULL)
1757 return (spa->spa_config_guid);
1759 guid = spa->spa_last_synced_guid != 0 ?
1760 spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1763 * Return the most recently synced out guid unless we're
1764 * in syncing context.
1766 if (dp && dsl_pool_sync_context(dp))
1767 return (spa->spa_root_vdev->vdev_guid);
1773 spa_load_guid(spa_t *spa)
1776 * This is a GUID that exists solely as a reference for the
1777 * purposes of the arc. It is generated at load time, and
1778 * is never written to persistent storage.
1780 return (spa->spa_load_guid);
1784 spa_last_synced_txg(spa_t *spa)
1786 return (spa->spa_ubsync.ub_txg);
1790 spa_first_txg(spa_t *spa)
1792 return (spa->spa_first_txg);
1796 spa_syncing_txg(spa_t *spa)
1798 return (spa->spa_syncing_txg);
1802 * Return the last txg where data can be dirtied. The final txgs
1803 * will be used to just clear out any deferred frees that remain.
1806 spa_final_dirty_txg(spa_t *spa)
1808 return (spa->spa_final_txg - TXG_DEFER_SIZE);
1812 spa_state(spa_t *spa)
1814 return (spa->spa_state);
1818 spa_load_state(spa_t *spa)
1820 return (spa->spa_load_state);
1824 spa_freeze_txg(spa_t *spa)
1826 return (spa->spa_freeze_txg);
1831 spa_get_worst_case_asize(spa_t *spa, uint64_t lsize)
1833 return (lsize * spa_asize_inflation);
1837 * Return the amount of slop space in bytes. It is 1/32 of the pool (3.2%),
1838 * or at least 128MB, unless that would cause it to be more than half the
1841 * See the comment above spa_slop_shift for details.
1844 spa_get_slop_space(spa_t *spa)
1846 uint64_t space = spa_get_dspace(spa);
1847 return (MAX(space >> spa_slop_shift, MIN(space >> 1, spa_min_slop)));
1851 spa_get_dspace(spa_t *spa)
1853 return (spa->spa_dspace);
1857 spa_get_checkpoint_space(spa_t *spa)
1859 return (spa->spa_checkpoint_info.sci_dspace);
1863 spa_update_dspace(spa_t *spa)
1865 spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1866 ddt_get_dedup_dspace(spa);
1867 if (spa->spa_vdev_removal != NULL) {
1869 * We can't allocate from the removing device, so
1870 * subtract its size. This prevents the DMU/DSL from
1871 * filling up the (now smaller) pool while we are in the
1872 * middle of removing the device.
1874 * Note that the DMU/DSL doesn't actually know or care
1875 * how much space is allocated (it does its own tracking
1876 * of how much space has been logically used). So it
1877 * doesn't matter that the data we are moving may be
1878 * allocated twice (on the old device and the new
1881 vdev_t *vd = spa->spa_vdev_removal->svr_vdev;
1882 spa->spa_dspace -= spa_deflate(spa) ?
1883 vd->vdev_stat.vs_dspace : vd->vdev_stat.vs_space;
1888 * Return the failure mode that has been set to this pool. The default
1889 * behavior will be to block all I/Os when a complete failure occurs.
1892 spa_get_failmode(spa_t *spa)
1894 return (spa->spa_failmode);
1898 spa_suspended(spa_t *spa)
1900 return (spa->spa_suspended);
1904 spa_version(spa_t *spa)
1906 return (spa->spa_ubsync.ub_version);
1910 spa_deflate(spa_t *spa)
1912 return (spa->spa_deflate);
1916 spa_normal_class(spa_t *spa)
1918 return (spa->spa_normal_class);
1922 spa_log_class(spa_t *spa)
1924 return (spa->spa_log_class);
1928 spa_evicting_os_register(spa_t *spa, objset_t *os)
1930 mutex_enter(&spa->spa_evicting_os_lock);
1931 list_insert_head(&spa->spa_evicting_os_list, os);
1932 mutex_exit(&spa->spa_evicting_os_lock);
1936 spa_evicting_os_deregister(spa_t *spa, objset_t *os)
1938 mutex_enter(&spa->spa_evicting_os_lock);
1939 list_remove(&spa->spa_evicting_os_list, os);
1940 cv_broadcast(&spa->spa_evicting_os_cv);
1941 mutex_exit(&spa->spa_evicting_os_lock);
1945 spa_evicting_os_wait(spa_t *spa)
1947 mutex_enter(&spa->spa_evicting_os_lock);
1948 while (!list_is_empty(&spa->spa_evicting_os_list))
1949 cv_wait(&spa->spa_evicting_os_cv, &spa->spa_evicting_os_lock);
1950 mutex_exit(&spa->spa_evicting_os_lock);
1952 dmu_buf_user_evict_wait();
1956 spa_max_replication(spa_t *spa)
1959 * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1960 * handle BPs with more than one DVA allocated. Set our max
1961 * replication level accordingly.
1963 if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1965 return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1969 spa_prev_software_version(spa_t *spa)
1971 return (spa->spa_prev_software_version);
1975 spa_deadman_synctime(spa_t *spa)
1977 return (spa->spa_deadman_synctime);
1981 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
1983 uint64_t asize = DVA_GET_ASIZE(dva);
1984 uint64_t dsize = asize;
1986 ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1988 if (asize != 0 && spa->spa_deflate) {
1989 uint64_t vdev = DVA_GET_VDEV(dva);
1990 vdev_t *vd = vdev_lookup_top(spa, vdev);
1993 "dva_get_dsize_sync(): bad DVA %llu:%llu",
1994 (u_longlong_t)vdev, (u_longlong_t)asize);
1996 dsize = (asize >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio;
2003 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
2007 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
2008 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
2014 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
2018 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2020 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
2021 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
2023 spa_config_exit(spa, SCL_VDEV, FTAG);
2029 * ==========================================================================
2030 * Initialization and Termination
2031 * ==========================================================================
2035 spa_name_compare(const void *a1, const void *a2)
2037 const spa_t *s1 = a1;
2038 const spa_t *s2 = a2;
2041 s = strcmp(s1->spa_name, s2->spa_name);
2052 return (spa_active_count);
2062 EVENTHANDLER_DEFINE(mountroot, spa_boot_init, NULL, 0);
2068 mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
2069 mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
2070 mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
2071 cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
2073 avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
2074 offsetof(spa_t, spa_avl));
2076 avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
2077 offsetof(spa_aux_t, aux_avl));
2079 avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
2080 offsetof(spa_aux_t, aux_avl));
2082 spa_mode_global = mode;
2088 if (spa_mode_global != FREAD && dprintf_find_string("watch")) {
2089 arc_procfd = open("/proc/self/ctl", O_WRONLY);
2090 if (arc_procfd == -1) {
2091 perror("could not enable watchpoints: "
2092 "opening /proc/self/ctl failed: ");
2098 #endif /* illumos */
2102 metaslab_alloc_trace_init();
2107 vdev_cache_stat_init();
2111 zpool_feature_init();
2115 dsl_scan_global_init();
2120 #endif /* !illumos */
2131 vdev_cache_stat_fini();
2136 metaslab_alloc_trace_fini();
2142 avl_destroy(&spa_namespace_avl);
2143 avl_destroy(&spa_spare_avl);
2144 avl_destroy(&spa_l2cache_avl);
2146 cv_destroy(&spa_namespace_cv);
2147 mutex_destroy(&spa_namespace_lock);
2148 mutex_destroy(&spa_spare_lock);
2149 mutex_destroy(&spa_l2cache_lock);
2153 * Return whether this pool has slogs. No locking needed.
2154 * It's not a problem if the wrong answer is returned as it's only for
2155 * performance and not correctness
2158 spa_has_slogs(spa_t *spa)
2160 return (spa->spa_log_class->mc_rotor != NULL);
2164 spa_get_log_state(spa_t *spa)
2166 return (spa->spa_log_state);
2170 spa_set_log_state(spa_t *spa, spa_log_state_t state)
2172 spa->spa_log_state = state;
2176 spa_is_root(spa_t *spa)
2178 return (spa->spa_is_root);
2182 spa_writeable(spa_t *spa)
2184 return (!!(spa->spa_mode & FWRITE) && spa->spa_trust_config);
2188 * Returns true if there is a pending sync task in any of the current
2189 * syncing txg, the current quiescing txg, or the current open txg.
2192 spa_has_pending_synctask(spa_t *spa)
2194 return (!txg_all_lists_empty(&spa->spa_dsl_pool->dp_sync_tasks) ||
2195 !txg_all_lists_empty(&spa->spa_dsl_pool->dp_early_sync_tasks));
2199 spa_mode(spa_t *spa)
2201 return (spa->spa_mode);
2205 spa_bootfs(spa_t *spa)
2207 return (spa->spa_bootfs);
2211 spa_delegation(spa_t *spa)
2213 return (spa->spa_delegation);
2217 spa_meta_objset(spa_t *spa)
2219 return (spa->spa_meta_objset);
2223 spa_dedup_checksum(spa_t *spa)
2225 return (spa->spa_dedup_checksum);
2229 * Reset pool scan stat per scan pass (or reboot).
2232 spa_scan_stat_init(spa_t *spa)
2234 /* data not stored on disk */
2235 spa->spa_scan_pass_start = gethrestime_sec();
2236 if (dsl_scan_is_paused_scrub(spa->spa_dsl_pool->dp_scan))
2237 spa->spa_scan_pass_scrub_pause = spa->spa_scan_pass_start;
2239 spa->spa_scan_pass_scrub_pause = 0;
2240 spa->spa_scan_pass_scrub_spent_paused = 0;
2241 spa->spa_scan_pass_exam = 0;
2242 spa->spa_scan_pass_issued = 0;
2243 vdev_scan_stat_init(spa->spa_root_vdev);
2247 * Get scan stats for zpool status reports
2250 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
2252 dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
2254 if (scn == NULL || scn->scn_phys.scn_func == POOL_SCAN_NONE)
2255 return (SET_ERROR(ENOENT));
2256 bzero(ps, sizeof (pool_scan_stat_t));
2258 /* data stored on disk */
2259 ps->pss_func = scn->scn_phys.scn_func;
2260 ps->pss_state = scn->scn_phys.scn_state;
2261 ps->pss_start_time = scn->scn_phys.scn_start_time;
2262 ps->pss_end_time = scn->scn_phys.scn_end_time;
2263 ps->pss_to_examine = scn->scn_phys.scn_to_examine;
2264 ps->pss_to_process = scn->scn_phys.scn_to_process;
2265 ps->pss_processed = scn->scn_phys.scn_processed;
2266 ps->pss_errors = scn->scn_phys.scn_errors;
2267 ps->pss_examined = scn->scn_phys.scn_examined;
2269 scn->scn_issued_before_pass + spa->spa_scan_pass_issued;
2270 /* data not stored on disk */
2271 ps->pss_pass_start = spa->spa_scan_pass_start;
2272 ps->pss_pass_exam = spa->spa_scan_pass_exam;
2273 ps->pss_pass_issued = spa->spa_scan_pass_issued;
2274 ps->pss_pass_scrub_pause = spa->spa_scan_pass_scrub_pause;
2275 ps->pss_pass_scrub_spent_paused = spa->spa_scan_pass_scrub_spent_paused;
2281 spa_debug_enabled(spa_t *spa)
2283 return (spa->spa_debug);
2287 spa_maxblocksize(spa_t *spa)
2289 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
2290 return (SPA_MAXBLOCKSIZE);
2292 return (SPA_OLD_MAXBLOCKSIZE);
2296 * Returns the txg that the last device removal completed. No indirect mappings
2297 * have been added since this txg.
2300 spa_get_last_removal_txg(spa_t *spa)
2303 uint64_t ret = -1ULL;
2305 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2307 * sr_prev_indirect_vdev is only modified while holding all the
2308 * config locks, so it is sufficient to hold SCL_VDEV as reader when
2311 vdevid = spa->spa_removing_phys.sr_prev_indirect_vdev;
2313 while (vdevid != -1ULL) {
2314 vdev_t *vd = vdev_lookup_top(spa, vdevid);
2315 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
2317 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
2320 * If the removal did not remap any data, we don't care.
2322 if (vdev_indirect_births_count(vib) != 0) {
2323 ret = vdev_indirect_births_last_entry_txg(vib);
2327 vdevid = vd->vdev_indirect_config.vic_prev_indirect_vdev;
2329 spa_config_exit(spa, SCL_VDEV, FTAG);
2332 spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
2338 spa_trust_config(spa_t *spa)
2340 return (spa->spa_trust_config);
2344 spa_missing_tvds_allowed(spa_t *spa)
2346 return (spa->spa_missing_tvds_allowed);
2350 spa_set_missing_tvds(spa_t *spa, uint64_t missing)
2352 spa->spa_missing_tvds = missing;
2356 spa_top_vdevs_spacemap_addressable(spa_t *spa)
2358 vdev_t *rvd = spa->spa_root_vdev;
2359 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
2360 if (!vdev_is_spacemap_addressable(rvd->vdev_child[c]))
2367 spa_has_checkpoint(spa_t *spa)
2369 return (spa->spa_checkpoint_txg != 0);
2373 spa_importing_readonly_checkpoint(spa_t *spa)
2375 return ((spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT) &&
2376 spa->spa_mode == FREAD);
2380 spa_min_claim_txg(spa_t *spa)
2382 uint64_t checkpoint_txg = spa->spa_uberblock.ub_checkpoint_txg;
2384 if (checkpoint_txg != 0)
2385 return (checkpoint_txg + 1);
2387 return (spa->spa_first_txg);
2391 * If there is a checkpoint, async destroys may consume more space from
2392 * the pool instead of freeing it. In an attempt to save the pool from
2393 * getting suspended when it is about to run out of space, we stop
2394 * processing async destroys.
2397 spa_suspend_async_destroy(spa_t *spa)
2399 dsl_pool_t *dp = spa_get_dsl(spa);
2401 uint64_t unreserved = dsl_pool_unreserved_space(dp,
2402 ZFS_SPACE_CHECK_EXTRA_RESERVED);
2403 uint64_t used = dsl_dir_phys(dp->dp_root_dir)->dd_used_bytes;
2404 uint64_t avail = (unreserved > used) ? (unreserved - used) : 0;
2406 if (spa_has_checkpoint(spa) && avail == 0)