5818 zfs {ref}compressratio is incorrect with 4k sector size
[unleashed.git] / usr / src / uts / common / fs / zfs / spa_misc.c
blobc5af055a8608745ec5099a4f4ebf4a159767d0b4
1 /*
2 * CDDL HEADER START
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]
19 * CDDL HEADER END
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
24 * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28 #include <sys/zfs_context.h>
29 #include <sys/spa_impl.h>
30 #include <sys/spa_boot.h>
31 #include <sys/zio.h>
32 #include <sys/zio_checksum.h>
33 #include <sys/zio_compress.h>
34 #include <sys/dmu.h>
35 #include <sys/dmu_tx.h>
36 #include <sys/zap.h>
37 #include <sys/zil.h>
38 #include <sys/vdev_impl.h>
39 #include <sys/metaslab.h>
40 #include <sys/uberblock_impl.h>
41 #include <sys/txg.h>
42 #include <sys/avl.h>
43 #include <sys/unique.h>
44 #include <sys/dsl_pool.h>
45 #include <sys/dsl_dir.h>
46 #include <sys/dsl_prop.h>
47 #include <sys/dsl_scan.h>
48 #include <sys/fs/zfs.h>
49 #include <sys/metaslab_impl.h>
50 #include <sys/arc.h>
51 #include <sys/ddt.h>
52 #include "zfs_prop.h"
53 #include "zfeature_common.h"
56 * SPA locking
58 * There are four basic locks for managing spa_t structures:
60 * spa_namespace_lock (global mutex)
62 * This lock must be acquired to do any of the following:
64 * - Lookup a spa_t by name
65 * - Add or remove a spa_t from the namespace
66 * - Increase spa_refcount from non-zero
67 * - Check if spa_refcount is zero
68 * - Rename a spa_t
69 * - add/remove/attach/detach devices
70 * - Held for the duration of create/destroy/import/export
72 * It does not need to handle recursion. A create or destroy may
73 * reference objects (files or zvols) in other pools, but by
74 * definition they must have an existing reference, and will never need
75 * to lookup a spa_t by name.
77 * spa_refcount (per-spa refcount_t protected by mutex)
79 * This reference count keep track of any active users of the spa_t. The
80 * spa_t cannot be destroyed or freed while this is non-zero. Internally,
81 * the refcount is never really 'zero' - opening a pool implicitly keeps
82 * some references in the DMU. Internally we check against spa_minref, but
83 * present the image of a zero/non-zero value to consumers.
85 * spa_config_lock[] (per-spa array of rwlocks)
87 * This protects the spa_t from config changes, and must be held in
88 * the following circumstances:
90 * - RW_READER to perform I/O to the spa
91 * - RW_WRITER to change the vdev config
93 * The locking order is fairly straightforward:
95 * spa_namespace_lock -> spa_refcount
97 * The namespace lock must be acquired to increase the refcount from 0
98 * or to check if it is zero.
100 * spa_refcount -> spa_config_lock[]
102 * There must be at least one valid reference on the spa_t to acquire
103 * the config lock.
105 * spa_namespace_lock -> spa_config_lock[]
107 * The namespace lock must always be taken before the config lock.
110 * The spa_namespace_lock can be acquired directly and is globally visible.
112 * The namespace is manipulated using the following functions, all of which
113 * require the spa_namespace_lock to be held.
115 * spa_lookup() Lookup a spa_t by name.
117 * spa_add() Create a new spa_t in the namespace.
119 * spa_remove() Remove a spa_t from the namespace. This also
120 * frees up any memory associated with the spa_t.
122 * spa_next() Returns the next spa_t in the system, or the
123 * first if NULL is passed.
125 * spa_evict_all() Shutdown and remove all spa_t structures in
126 * the system.
128 * spa_guid_exists() Determine whether a pool/device guid exists.
130 * The spa_refcount is manipulated using the following functions:
132 * spa_open_ref() Adds a reference to the given spa_t. Must be
133 * called with spa_namespace_lock held if the
134 * refcount is currently zero.
136 * spa_close() Remove a reference from the spa_t. This will
137 * not free the spa_t or remove it from the
138 * namespace. No locking is required.
140 * spa_refcount_zero() Returns true if the refcount is currently
141 * zero. Must be called with spa_namespace_lock
142 * held.
144 * The spa_config_lock[] is an array of rwlocks, ordered as follows:
145 * SCL_CONFIG > SCL_STATE > SCL_ALLOC > SCL_ZIO > SCL_FREE > SCL_VDEV.
146 * spa_config_lock[] is manipulated with spa_config_{enter,exit,held}().
148 * To read the configuration, it suffices to hold one of these locks as reader.
149 * To modify the configuration, you must hold all locks as writer. To modify
150 * vdev state without altering the vdev tree's topology (e.g. online/offline),
151 * you must hold SCL_STATE and SCL_ZIO as writer.
153 * We use these distinct config locks to avoid recursive lock entry.
154 * For example, spa_sync() (which holds SCL_CONFIG as reader) induces
155 * block allocations (SCL_ALLOC), which may require reading space maps
156 * from disk (dmu_read() -> zio_read() -> SCL_ZIO).
158 * The spa config locks cannot be normal rwlocks because we need the
159 * ability to hand off ownership. For example, SCL_ZIO is acquired
160 * by the issuing thread and later released by an interrupt thread.
161 * They do, however, obey the usual write-wanted semantics to prevent
162 * writer (i.e. system administrator) starvation.
164 * The lock acquisition rules are as follows:
166 * SCL_CONFIG
167 * Protects changes to the vdev tree topology, such as vdev
168 * add/remove/attach/detach. Protects the dirty config list
169 * (spa_config_dirty_list) and the set of spares and l2arc devices.
171 * SCL_STATE
172 * Protects changes to pool state and vdev state, such as vdev
173 * online/offline/fault/degrade/clear. Protects the dirty state list
174 * (spa_state_dirty_list) and global pool state (spa_state).
176 * SCL_ALLOC
177 * Protects changes to metaslab groups and classes.
178 * Held as reader by metaslab_alloc() and metaslab_claim().
180 * SCL_ZIO
181 * Held by bp-level zios (those which have no io_vd upon entry)
182 * to prevent changes to the vdev tree. The bp-level zio implicitly
183 * protects all of its vdev child zios, which do not hold SCL_ZIO.
185 * SCL_FREE
186 * Protects changes to metaslab groups and classes.
187 * Held as reader by metaslab_free(). SCL_FREE is distinct from
188 * SCL_ALLOC, and lower than SCL_ZIO, so that we can safely free
189 * blocks in zio_done() while another i/o that holds either
190 * SCL_ALLOC or SCL_ZIO is waiting for this i/o to complete.
192 * SCL_VDEV
193 * Held as reader to prevent changes to the vdev tree during trivial
194 * inquiries such as bp_get_dsize(). SCL_VDEV is distinct from the
195 * other locks, and lower than all of them, to ensure that it's safe
196 * to acquire regardless of caller context.
198 * In addition, the following rules apply:
200 * (a) spa_props_lock protects pool properties, spa_config and spa_config_list.
201 * The lock ordering is SCL_CONFIG > spa_props_lock.
203 * (b) I/O operations on leaf vdevs. For any zio operation that takes
204 * an explicit vdev_t argument -- such as zio_ioctl(), zio_read_phys(),
205 * or zio_write_phys() -- the caller must ensure that the config cannot
206 * cannot change in the interim, and that the vdev cannot be reopened.
207 * SCL_STATE as reader suffices for both.
209 * The vdev configuration is protected by spa_vdev_enter() / spa_vdev_exit().
211 * spa_vdev_enter() Acquire the namespace lock and the config lock
212 * for writing.
214 * spa_vdev_exit() Release the config lock, wait for all I/O
215 * to complete, sync the updated configs to the
216 * cache, and release the namespace lock.
218 * vdev state is protected by spa_vdev_state_enter() / spa_vdev_state_exit().
219 * Like spa_vdev_enter/exit, these are convenience wrappers -- the actual
220 * locking is, always, based on spa_namespace_lock and spa_config_lock[].
222 * spa_rename() is also implemented within this file since it requires
223 * manipulation of the namespace.
226 static avl_tree_t spa_namespace_avl;
227 kmutex_t spa_namespace_lock;
228 static kcondvar_t spa_namespace_cv;
229 static int spa_active_count;
230 int spa_max_replication_override = SPA_DVAS_PER_BP;
232 static kmutex_t spa_spare_lock;
233 static avl_tree_t spa_spare_avl;
234 static kmutex_t spa_l2cache_lock;
235 static avl_tree_t spa_l2cache_avl;
237 kmem_cache_t *spa_buffer_pool;
238 int spa_mode_global;
240 #ifdef ZFS_DEBUG
241 /* Everything except dprintf and spa is on by default in debug builds */
242 int zfs_flags = ~(ZFS_DEBUG_DPRINTF | ZFS_DEBUG_SPA);
243 #else
244 int zfs_flags = 0;
245 #endif
248 * zfs_recover can be set to nonzero to attempt to recover from
249 * otherwise-fatal errors, typically caused by on-disk corruption. When
250 * set, calls to zfs_panic_recover() will turn into warning messages.
251 * This should only be used as a last resort, as it typically results
252 * in leaked space, or worse.
254 boolean_t zfs_recover = B_FALSE;
257 * If destroy encounters an EIO while reading metadata (e.g. indirect
258 * blocks), space referenced by the missing metadata can not be freed.
259 * Normally this causes the background destroy to become "stalled", as
260 * it is unable to make forward progress. While in this stalled state,
261 * all remaining space to free from the error-encountering filesystem is
262 * "temporarily leaked". Set this flag to cause it to ignore the EIO,
263 * permanently leak the space from indirect blocks that can not be read,
264 * and continue to free everything else that it can.
266 * The default, "stalling" behavior is useful if the storage partially
267 * fails (i.e. some but not all i/os fail), and then later recovers. In
268 * this case, we will be able to continue pool operations while it is
269 * partially failed, and when it recovers, we can continue to free the
270 * space, with no leaks. However, note that this case is actually
271 * fairly rare.
273 * Typically pools either (a) fail completely (but perhaps temporarily,
274 * e.g. a top-level vdev going offline), or (b) have localized,
275 * permanent errors (e.g. disk returns the wrong data due to bit flip or
276 * firmware bug). In case (a), this setting does not matter because the
277 * pool will be suspended and the sync thread will not be able to make
278 * forward progress regardless. In case (b), because the error is
279 * permanent, the best we can do is leak the minimum amount of space,
280 * which is what setting this flag will do. Therefore, it is reasonable
281 * for this flag to normally be set, but we chose the more conservative
282 * approach of not setting it, so that there is no possibility of
283 * leaking space in the "partial temporary" failure case.
285 boolean_t zfs_free_leak_on_eio = B_FALSE;
288 * Expiration time in milliseconds. This value has two meanings. First it is
289 * used to determine when the spa_deadman() logic should fire. By default the
290 * spa_deadman() will fire if spa_sync() has not completed in 1000 seconds.
291 * Secondly, the value determines if an I/O is considered "hung". Any I/O that
292 * has not completed in zfs_deadman_synctime_ms is considered "hung" resulting
293 * in a system panic.
295 uint64_t zfs_deadman_synctime_ms = 1000000ULL;
298 * Check time in milliseconds. This defines the frequency at which we check
299 * for hung I/O.
301 uint64_t zfs_deadman_checktime_ms = 5000ULL;
304 * Override the zfs deadman behavior via /etc/system. By default the
305 * deadman is enabled except on VMware and sparc deployments.
307 int zfs_deadman_enabled = -1;
310 * The worst case is single-sector max-parity RAID-Z blocks, in which
311 * case the space requirement is exactly (VDEV_RAIDZ_MAXPARITY + 1)
312 * times the size; so just assume that. Add to this the fact that
313 * we can have up to 3 DVAs per bp, and one more factor of 2 because
314 * the block may be dittoed with up to 3 DVAs by ddt_sync(). All together,
315 * the worst case is:
316 * (VDEV_RAIDZ_MAXPARITY + 1) * SPA_DVAS_PER_BP * 2 == 24
318 int spa_asize_inflation = 24;
321 * Normally, we don't allow the last 3.2% (1/(2^spa_slop_shift)) of space in
322 * the pool to be consumed. This ensures that we don't run the pool
323 * completely out of space, due to unaccounted changes (e.g. to the MOS).
324 * It also limits the worst-case time to allocate space. If we have
325 * less than this amount of free space, most ZPL operations (e.g. write,
326 * create) will return ENOSPC.
328 * Certain operations (e.g. file removal, most administrative actions) can
329 * use half the slop space. They will only return ENOSPC if less than half
330 * the slop space is free. Typically, once the pool has less than the slop
331 * space free, the user will use these operations to free up space in the pool.
332 * These are the operations that call dsl_pool_adjustedsize() with the netfree
333 * argument set to TRUE.
335 * A very restricted set of operations are always permitted, regardless of
336 * the amount of free space. These are the operations that call
337 * dsl_sync_task(ZFS_SPACE_CHECK_NONE), e.g. "zfs destroy". If these
338 * operations result in a net increase in the amount of space used,
339 * it is possible to run the pool completely out of space, causing it to
340 * be permanently read-only.
342 * See also the comments in zfs_space_check_t.
344 int spa_slop_shift = 5;
347 * ==========================================================================
348 * SPA config locking
349 * ==========================================================================
351 static void
352 spa_config_lock_init(spa_t *spa)
354 for (int i = 0; i < SCL_LOCKS; i++) {
355 spa_config_lock_t *scl = &spa->spa_config_lock[i];
356 mutex_init(&scl->scl_lock, NULL, MUTEX_DEFAULT, NULL);
357 cv_init(&scl->scl_cv, NULL, CV_DEFAULT, NULL);
358 refcount_create_untracked(&scl->scl_count);
359 scl->scl_writer = NULL;
360 scl->scl_write_wanted = 0;
364 static void
365 spa_config_lock_destroy(spa_t *spa)
367 for (int i = 0; i < SCL_LOCKS; i++) {
368 spa_config_lock_t *scl = &spa->spa_config_lock[i];
369 mutex_destroy(&scl->scl_lock);
370 cv_destroy(&scl->scl_cv);
371 refcount_destroy(&scl->scl_count);
372 ASSERT(scl->scl_writer == NULL);
373 ASSERT(scl->scl_write_wanted == 0);
378 spa_config_tryenter(spa_t *spa, int locks, void *tag, krw_t rw)
380 for (int i = 0; i < SCL_LOCKS; i++) {
381 spa_config_lock_t *scl = &spa->spa_config_lock[i];
382 if (!(locks & (1 << i)))
383 continue;
384 mutex_enter(&scl->scl_lock);
385 if (rw == RW_READER) {
386 if (scl->scl_writer || scl->scl_write_wanted) {
387 mutex_exit(&scl->scl_lock);
388 spa_config_exit(spa, locks ^ (1 << i), tag);
389 return (0);
391 } else {
392 ASSERT(scl->scl_writer != curthread);
393 if (!refcount_is_zero(&scl->scl_count)) {
394 mutex_exit(&scl->scl_lock);
395 spa_config_exit(spa, locks ^ (1 << i), tag);
396 return (0);
398 scl->scl_writer = curthread;
400 (void) refcount_add(&scl->scl_count, tag);
401 mutex_exit(&scl->scl_lock);
403 return (1);
406 void
407 spa_config_enter(spa_t *spa, int locks, void *tag, krw_t rw)
409 int wlocks_held = 0;
411 ASSERT3U(SCL_LOCKS, <, sizeof (wlocks_held) * NBBY);
413 for (int i = 0; i < SCL_LOCKS; i++) {
414 spa_config_lock_t *scl = &spa->spa_config_lock[i];
415 if (scl->scl_writer == curthread)
416 wlocks_held |= (1 << i);
417 if (!(locks & (1 << i)))
418 continue;
419 mutex_enter(&scl->scl_lock);
420 if (rw == RW_READER) {
421 while (scl->scl_writer || scl->scl_write_wanted) {
422 cv_wait(&scl->scl_cv, &scl->scl_lock);
424 } else {
425 ASSERT(scl->scl_writer != curthread);
426 while (!refcount_is_zero(&scl->scl_count)) {
427 scl->scl_write_wanted++;
428 cv_wait(&scl->scl_cv, &scl->scl_lock);
429 scl->scl_write_wanted--;
431 scl->scl_writer = curthread;
433 (void) refcount_add(&scl->scl_count, tag);
434 mutex_exit(&scl->scl_lock);
436 ASSERT(wlocks_held <= locks);
439 void
440 spa_config_exit(spa_t *spa, int locks, void *tag)
442 for (int i = SCL_LOCKS - 1; i >= 0; i--) {
443 spa_config_lock_t *scl = &spa->spa_config_lock[i];
444 if (!(locks & (1 << i)))
445 continue;
446 mutex_enter(&scl->scl_lock);
447 ASSERT(!refcount_is_zero(&scl->scl_count));
448 if (refcount_remove(&scl->scl_count, tag) == 0) {
449 ASSERT(scl->scl_writer == NULL ||
450 scl->scl_writer == curthread);
451 scl->scl_writer = NULL; /* OK in either case */
452 cv_broadcast(&scl->scl_cv);
454 mutex_exit(&scl->scl_lock);
459 spa_config_held(spa_t *spa, int locks, krw_t rw)
461 int locks_held = 0;
463 for (int i = 0; i < SCL_LOCKS; i++) {
464 spa_config_lock_t *scl = &spa->spa_config_lock[i];
465 if (!(locks & (1 << i)))
466 continue;
467 if ((rw == RW_READER && !refcount_is_zero(&scl->scl_count)) ||
468 (rw == RW_WRITER && scl->scl_writer == curthread))
469 locks_held |= 1 << i;
472 return (locks_held);
476 * ==========================================================================
477 * SPA namespace functions
478 * ==========================================================================
482 * Lookup the named spa_t in the AVL tree. The spa_namespace_lock must be held.
483 * Returns NULL if no matching spa_t is found.
485 spa_t *
486 spa_lookup(const char *name)
488 static spa_t search; /* spa_t is large; don't allocate on stack */
489 spa_t *spa;
490 avl_index_t where;
491 char *cp;
493 ASSERT(MUTEX_HELD(&spa_namespace_lock));
495 (void) strlcpy(search.spa_name, name, sizeof (search.spa_name));
498 * If it's a full dataset name, figure out the pool name and
499 * just use that.
501 cp = strpbrk(search.spa_name, "/@#");
502 if (cp != NULL)
503 *cp = '\0';
505 spa = avl_find(&spa_namespace_avl, &search, &where);
507 return (spa);
511 * Fires when spa_sync has not completed within zfs_deadman_synctime_ms.
512 * If the zfs_deadman_enabled flag is set then it inspects all vdev queues
513 * looking for potentially hung I/Os.
515 void
516 spa_deadman(void *arg)
518 spa_t *spa = arg;
521 * Disable the deadman timer if the pool is suspended.
523 if (spa_suspended(spa)) {
524 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
525 return;
528 zfs_dbgmsg("slow spa_sync: started %llu seconds ago, calls %llu",
529 (gethrtime() - spa->spa_sync_starttime) / NANOSEC,
530 ++spa->spa_deadman_calls);
531 if (zfs_deadman_enabled)
532 vdev_deadman(spa->spa_root_vdev);
536 * Create an uninitialized spa_t with the given name. Requires
537 * spa_namespace_lock. The caller must ensure that the spa_t doesn't already
538 * exist by calling spa_lookup() first.
540 spa_t *
541 spa_add(const char *name, nvlist_t *config, const char *altroot)
543 spa_t *spa;
544 spa_config_dirent_t *dp;
545 cyc_handler_t hdlr;
546 cyc_time_t when;
548 ASSERT(MUTEX_HELD(&spa_namespace_lock));
550 spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
552 mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
553 mutex_init(&spa->spa_errlist_lock, NULL, MUTEX_DEFAULT, NULL);
554 mutex_init(&spa->spa_errlog_lock, NULL, MUTEX_DEFAULT, NULL);
555 mutex_init(&spa->spa_evicting_os_lock, NULL, MUTEX_DEFAULT, NULL);
556 mutex_init(&spa->spa_history_lock, NULL, MUTEX_DEFAULT, NULL);
557 mutex_init(&spa->spa_proc_lock, NULL, MUTEX_DEFAULT, NULL);
558 mutex_init(&spa->spa_props_lock, NULL, MUTEX_DEFAULT, NULL);
559 mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
560 mutex_init(&spa->spa_suspend_lock, NULL, MUTEX_DEFAULT, NULL);
561 mutex_init(&spa->spa_vdev_top_lock, NULL, MUTEX_DEFAULT, NULL);
562 mutex_init(&spa->spa_iokstat_lock, NULL, MUTEX_DEFAULT, NULL);
564 cv_init(&spa->spa_async_cv, NULL, CV_DEFAULT, NULL);
565 cv_init(&spa->spa_evicting_os_cv, NULL, CV_DEFAULT, NULL);
566 cv_init(&spa->spa_proc_cv, NULL, CV_DEFAULT, NULL);
567 cv_init(&spa->spa_scrub_io_cv, NULL, CV_DEFAULT, NULL);
568 cv_init(&spa->spa_suspend_cv, NULL, CV_DEFAULT, NULL);
570 for (int t = 0; t < TXG_SIZE; t++)
571 bplist_create(&spa->spa_free_bplist[t]);
573 (void) strlcpy(spa->spa_name, name, sizeof (spa->spa_name));
574 spa->spa_state = POOL_STATE_UNINITIALIZED;
575 spa->spa_freeze_txg = UINT64_MAX;
576 spa->spa_final_txg = UINT64_MAX;
577 spa->spa_load_max_txg = UINT64_MAX;
578 spa->spa_proc = &p0;
579 spa->spa_proc_state = SPA_PROC_NONE;
581 hdlr.cyh_func = spa_deadman;
582 hdlr.cyh_arg = spa;
583 hdlr.cyh_level = CY_LOW_LEVEL;
585 spa->spa_deadman_synctime = MSEC2NSEC(zfs_deadman_synctime_ms);
588 * This determines how often we need to check for hung I/Os after
589 * the cyclic has already fired. Since checking for hung I/Os is
590 * an expensive operation we don't want to check too frequently.
591 * Instead wait for 5 seconds before checking again.
593 when.cyt_interval = MSEC2NSEC(zfs_deadman_checktime_ms);
594 when.cyt_when = CY_INFINITY;
595 mutex_enter(&cpu_lock);
596 spa->spa_deadman_cycid = cyclic_add(&hdlr, &when);
597 mutex_exit(&cpu_lock);
599 refcount_create(&spa->spa_refcount);
600 spa_config_lock_init(spa);
602 avl_add(&spa_namespace_avl, spa);
605 * Set the alternate root, if there is one.
607 if (altroot) {
608 spa->spa_root = spa_strdup(altroot);
609 spa_active_count++;
613 * Every pool starts with the default cachefile
615 list_create(&spa->spa_config_list, sizeof (spa_config_dirent_t),
616 offsetof(spa_config_dirent_t, scd_link));
618 dp = kmem_zalloc(sizeof (spa_config_dirent_t), KM_SLEEP);
619 dp->scd_path = altroot ? NULL : spa_strdup(spa_config_path);
620 list_insert_head(&spa->spa_config_list, dp);
622 VERIFY(nvlist_alloc(&spa->spa_load_info, NV_UNIQUE_NAME,
623 KM_SLEEP) == 0);
625 if (config != NULL) {
626 nvlist_t *features;
628 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_FEATURES_FOR_READ,
629 &features) == 0) {
630 VERIFY(nvlist_dup(features, &spa->spa_label_features,
631 0) == 0);
634 VERIFY(nvlist_dup(config, &spa->spa_config, 0) == 0);
637 if (spa->spa_label_features == NULL) {
638 VERIFY(nvlist_alloc(&spa->spa_label_features, NV_UNIQUE_NAME,
639 KM_SLEEP) == 0);
642 spa->spa_iokstat = kstat_create("zfs", 0, name,
643 "disk", KSTAT_TYPE_IO, 1, 0);
644 if (spa->spa_iokstat) {
645 spa->spa_iokstat->ks_lock = &spa->spa_iokstat_lock;
646 kstat_install(spa->spa_iokstat);
649 spa->spa_debug = ((zfs_flags & ZFS_DEBUG_SPA) != 0);
651 spa->spa_min_ashift = INT_MAX;
652 spa->spa_max_ashift = 0;
655 * As a pool is being created, treat all features as disabled by
656 * setting SPA_FEATURE_DISABLED for all entries in the feature
657 * refcount cache.
659 for (int i = 0; i < SPA_FEATURES; i++) {
660 spa->spa_feat_refcount_cache[i] = SPA_FEATURE_DISABLED;
663 return (spa);
667 * Removes a spa_t from the namespace, freeing up any memory used. Requires
668 * spa_namespace_lock. This is called only after the spa_t has been closed and
669 * deactivated.
671 void
672 spa_remove(spa_t *spa)
674 spa_config_dirent_t *dp;
676 ASSERT(MUTEX_HELD(&spa_namespace_lock));
677 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
678 ASSERT3U(refcount_count(&spa->spa_refcount), ==, 0);
680 nvlist_free(spa->spa_config_splitting);
682 avl_remove(&spa_namespace_avl, spa);
683 cv_broadcast(&spa_namespace_cv);
685 if (spa->spa_root) {
686 spa_strfree(spa->spa_root);
687 spa_active_count--;
690 while ((dp = list_head(&spa->spa_config_list)) != NULL) {
691 list_remove(&spa->spa_config_list, dp);
692 if (dp->scd_path != NULL)
693 spa_strfree(dp->scd_path);
694 kmem_free(dp, sizeof (spa_config_dirent_t));
697 list_destroy(&spa->spa_config_list);
699 nvlist_free(spa->spa_label_features);
700 nvlist_free(spa->spa_load_info);
701 spa_config_set(spa, NULL);
703 mutex_enter(&cpu_lock);
704 if (spa->spa_deadman_cycid != CYCLIC_NONE)
705 cyclic_remove(spa->spa_deadman_cycid);
706 mutex_exit(&cpu_lock);
707 spa->spa_deadman_cycid = CYCLIC_NONE;
709 refcount_destroy(&spa->spa_refcount);
711 spa_config_lock_destroy(spa);
713 kstat_delete(spa->spa_iokstat);
714 spa->spa_iokstat = NULL;
716 for (int t = 0; t < TXG_SIZE; t++)
717 bplist_destroy(&spa->spa_free_bplist[t]);
719 cv_destroy(&spa->spa_async_cv);
720 cv_destroy(&spa->spa_evicting_os_cv);
721 cv_destroy(&spa->spa_proc_cv);
722 cv_destroy(&spa->spa_scrub_io_cv);
723 cv_destroy(&spa->spa_suspend_cv);
725 mutex_destroy(&spa->spa_async_lock);
726 mutex_destroy(&spa->spa_errlist_lock);
727 mutex_destroy(&spa->spa_errlog_lock);
728 mutex_destroy(&spa->spa_evicting_os_lock);
729 mutex_destroy(&spa->spa_history_lock);
730 mutex_destroy(&spa->spa_proc_lock);
731 mutex_destroy(&spa->spa_props_lock);
732 mutex_destroy(&spa->spa_scrub_lock);
733 mutex_destroy(&spa->spa_suspend_lock);
734 mutex_destroy(&spa->spa_vdev_top_lock);
735 mutex_destroy(&spa->spa_iokstat_lock);
737 kmem_free(spa, sizeof (spa_t));
741 * Given a pool, return the next pool in the namespace, or NULL if there is
742 * none. If 'prev' is NULL, return the first pool.
744 spa_t *
745 spa_next(spa_t *prev)
747 ASSERT(MUTEX_HELD(&spa_namespace_lock));
749 if (prev)
750 return (AVL_NEXT(&spa_namespace_avl, prev));
751 else
752 return (avl_first(&spa_namespace_avl));
756 * ==========================================================================
757 * SPA refcount functions
758 * ==========================================================================
762 * Add a reference to the given spa_t. Must have at least one reference, or
763 * have the namespace lock held.
765 void
766 spa_open_ref(spa_t *spa, void *tag)
768 ASSERT(refcount_count(&spa->spa_refcount) >= spa->spa_minref ||
769 MUTEX_HELD(&spa_namespace_lock));
770 (void) refcount_add(&spa->spa_refcount, tag);
774 * Remove a reference to the given spa_t. Must have at least one reference, or
775 * have the namespace lock held.
777 void
778 spa_close(spa_t *spa, void *tag)
780 ASSERT(refcount_count(&spa->spa_refcount) > spa->spa_minref ||
781 MUTEX_HELD(&spa_namespace_lock));
782 (void) refcount_remove(&spa->spa_refcount, tag);
786 * Remove a reference to the given spa_t held by a dsl dir that is
787 * being asynchronously released. Async releases occur from a taskq
788 * performing eviction of dsl datasets and dirs. The namespace lock
789 * isn't held and the hold by the object being evicted may contribute to
790 * spa_minref (e.g. dataset or directory released during pool export),
791 * so the asserts in spa_close() do not apply.
793 void
794 spa_async_close(spa_t *spa, void *tag)
796 (void) refcount_remove(&spa->spa_refcount, tag);
800 * Check to see if the spa refcount is zero. Must be called with
801 * spa_namespace_lock held. We really compare against spa_minref, which is the
802 * number of references acquired when opening a pool
804 boolean_t
805 spa_refcount_zero(spa_t *spa)
807 ASSERT(MUTEX_HELD(&spa_namespace_lock));
809 return (refcount_count(&spa->spa_refcount) == spa->spa_minref);
813 * ==========================================================================
814 * SPA spare and l2cache tracking
815 * ==========================================================================
819 * Hot spares and cache devices are tracked using the same code below,
820 * for 'auxiliary' devices.
823 typedef struct spa_aux {
824 uint64_t aux_guid;
825 uint64_t aux_pool;
826 avl_node_t aux_avl;
827 int aux_count;
828 } spa_aux_t;
830 static int
831 spa_aux_compare(const void *a, const void *b)
833 const spa_aux_t *sa = a;
834 const spa_aux_t *sb = b;
836 if (sa->aux_guid < sb->aux_guid)
837 return (-1);
838 else if (sa->aux_guid > sb->aux_guid)
839 return (1);
840 else
841 return (0);
844 void
845 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
847 avl_index_t where;
848 spa_aux_t search;
849 spa_aux_t *aux;
851 search.aux_guid = vd->vdev_guid;
852 if ((aux = avl_find(avl, &search, &where)) != NULL) {
853 aux->aux_count++;
854 } else {
855 aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
856 aux->aux_guid = vd->vdev_guid;
857 aux->aux_count = 1;
858 avl_insert(avl, aux, where);
862 void
863 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
865 spa_aux_t search;
866 spa_aux_t *aux;
867 avl_index_t where;
869 search.aux_guid = vd->vdev_guid;
870 aux = avl_find(avl, &search, &where);
872 ASSERT(aux != NULL);
874 if (--aux->aux_count == 0) {
875 avl_remove(avl, aux);
876 kmem_free(aux, sizeof (spa_aux_t));
877 } else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
878 aux->aux_pool = 0ULL;
882 boolean_t
883 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
885 spa_aux_t search, *found;
887 search.aux_guid = guid;
888 found = avl_find(avl, &search, NULL);
890 if (pool) {
891 if (found)
892 *pool = found->aux_pool;
893 else
894 *pool = 0ULL;
897 if (refcnt) {
898 if (found)
899 *refcnt = found->aux_count;
900 else
901 *refcnt = 0;
904 return (found != NULL);
907 void
908 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
910 spa_aux_t search, *found;
911 avl_index_t where;
913 search.aux_guid = vd->vdev_guid;
914 found = avl_find(avl, &search, &where);
915 ASSERT(found != NULL);
916 ASSERT(found->aux_pool == 0ULL);
918 found->aux_pool = spa_guid(vd->vdev_spa);
922 * Spares are tracked globally due to the following constraints:
924 * - A spare may be part of multiple pools.
925 * - A spare may be added to a pool even if it's actively in use within
926 * another pool.
927 * - A spare in use in any pool can only be the source of a replacement if
928 * the target is a spare in the same pool.
930 * We keep track of all spares on the system through the use of a reference
931 * counted AVL tree. When a vdev is added as a spare, or used as a replacement
932 * spare, then we bump the reference count in the AVL tree. In addition, we set
933 * the 'vdev_isspare' member to indicate that the device is a spare (active or
934 * inactive). When a spare is made active (used to replace a device in the
935 * pool), we also keep track of which pool its been made a part of.
937 * The 'spa_spare_lock' protects the AVL tree. These functions are normally
938 * called under the spa_namespace lock as part of vdev reconfiguration. The
939 * separate spare lock exists for the status query path, which does not need to
940 * be completely consistent with respect to other vdev configuration changes.
943 static int
944 spa_spare_compare(const void *a, const void *b)
946 return (spa_aux_compare(a, b));
949 void
950 spa_spare_add(vdev_t *vd)
952 mutex_enter(&spa_spare_lock);
953 ASSERT(!vd->vdev_isspare);
954 spa_aux_add(vd, &spa_spare_avl);
955 vd->vdev_isspare = B_TRUE;
956 mutex_exit(&spa_spare_lock);
959 void
960 spa_spare_remove(vdev_t *vd)
962 mutex_enter(&spa_spare_lock);
963 ASSERT(vd->vdev_isspare);
964 spa_aux_remove(vd, &spa_spare_avl);
965 vd->vdev_isspare = B_FALSE;
966 mutex_exit(&spa_spare_lock);
969 boolean_t
970 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
972 boolean_t found;
974 mutex_enter(&spa_spare_lock);
975 found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
976 mutex_exit(&spa_spare_lock);
978 return (found);
981 void
982 spa_spare_activate(vdev_t *vd)
984 mutex_enter(&spa_spare_lock);
985 ASSERT(vd->vdev_isspare);
986 spa_aux_activate(vd, &spa_spare_avl);
987 mutex_exit(&spa_spare_lock);
991 * Level 2 ARC devices are tracked globally for the same reasons as spares.
992 * Cache devices currently only support one pool per cache device, and so
993 * for these devices the aux reference count is currently unused beyond 1.
996 static int
997 spa_l2cache_compare(const void *a, const void *b)
999 return (spa_aux_compare(a, b));
1002 void
1003 spa_l2cache_add(vdev_t *vd)
1005 mutex_enter(&spa_l2cache_lock);
1006 ASSERT(!vd->vdev_isl2cache);
1007 spa_aux_add(vd, &spa_l2cache_avl);
1008 vd->vdev_isl2cache = B_TRUE;
1009 mutex_exit(&spa_l2cache_lock);
1012 void
1013 spa_l2cache_remove(vdev_t *vd)
1015 mutex_enter(&spa_l2cache_lock);
1016 ASSERT(vd->vdev_isl2cache);
1017 spa_aux_remove(vd, &spa_l2cache_avl);
1018 vd->vdev_isl2cache = B_FALSE;
1019 mutex_exit(&spa_l2cache_lock);
1022 boolean_t
1023 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
1025 boolean_t found;
1027 mutex_enter(&spa_l2cache_lock);
1028 found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
1029 mutex_exit(&spa_l2cache_lock);
1031 return (found);
1034 void
1035 spa_l2cache_activate(vdev_t *vd)
1037 mutex_enter(&spa_l2cache_lock);
1038 ASSERT(vd->vdev_isl2cache);
1039 spa_aux_activate(vd, &spa_l2cache_avl);
1040 mutex_exit(&spa_l2cache_lock);
1044 * ==========================================================================
1045 * SPA vdev locking
1046 * ==========================================================================
1050 * Lock the given spa_t for the purpose of adding or removing a vdev.
1051 * Grabs the global spa_namespace_lock plus the spa config lock for writing.
1052 * It returns the next transaction group for the spa_t.
1054 uint64_t
1055 spa_vdev_enter(spa_t *spa)
1057 mutex_enter(&spa->spa_vdev_top_lock);
1058 mutex_enter(&spa_namespace_lock);
1059 return (spa_vdev_config_enter(spa));
1063 * Internal implementation for spa_vdev_enter(). Used when a vdev
1064 * operation requires multiple syncs (i.e. removing a device) while
1065 * keeping the spa_namespace_lock held.
1067 uint64_t
1068 spa_vdev_config_enter(spa_t *spa)
1070 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1072 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1074 return (spa_last_synced_txg(spa) + 1);
1078 * Used in combination with spa_vdev_config_enter() to allow the syncing
1079 * of multiple transactions without releasing the spa_namespace_lock.
1081 void
1082 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error, char *tag)
1084 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1086 int config_changed = B_FALSE;
1088 ASSERT(txg > spa_last_synced_txg(spa));
1090 spa->spa_pending_vdev = NULL;
1093 * Reassess the DTLs.
1095 vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE);
1097 if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
1098 config_changed = B_TRUE;
1099 spa->spa_config_generation++;
1103 * Verify the metaslab classes.
1105 ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
1106 ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
1108 spa_config_exit(spa, SCL_ALL, spa);
1111 * Panic the system if the specified tag requires it. This
1112 * is useful for ensuring that configurations are updated
1113 * transactionally.
1115 if (zio_injection_enabled)
1116 zio_handle_panic_injection(spa, tag, 0);
1119 * Note: this txg_wait_synced() is important because it ensures
1120 * that there won't be more than one config change per txg.
1121 * This allows us to use the txg as the generation number.
1123 if (error == 0)
1124 txg_wait_synced(spa->spa_dsl_pool, txg);
1126 if (vd != NULL) {
1127 ASSERT(!vd->vdev_detached || vd->vdev_dtl_sm == NULL);
1128 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1129 vdev_free(vd);
1130 spa_config_exit(spa, SCL_ALL, spa);
1134 * If the config changed, update the config cache.
1136 if (config_changed)
1137 spa_config_sync(spa, B_FALSE, B_TRUE);
1141 * Unlock the spa_t after adding or removing a vdev. Besides undoing the
1142 * locking of spa_vdev_enter(), we also want make sure the transactions have
1143 * synced to disk, and then update the global configuration cache with the new
1144 * information.
1147 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
1149 spa_vdev_config_exit(spa, vd, txg, error, FTAG);
1150 mutex_exit(&spa_namespace_lock);
1151 mutex_exit(&spa->spa_vdev_top_lock);
1153 return (error);
1157 * Lock the given spa_t for the purpose of changing vdev state.
1159 void
1160 spa_vdev_state_enter(spa_t *spa, int oplocks)
1162 int locks = SCL_STATE_ALL | oplocks;
1165 * Root pools may need to read of the underlying devfs filesystem
1166 * when opening up a vdev. Unfortunately if we're holding the
1167 * SCL_ZIO lock it will result in a deadlock when we try to issue
1168 * the read from the root filesystem. Instead we "prefetch"
1169 * the associated vnodes that we need prior to opening the
1170 * underlying devices and cache them so that we can prevent
1171 * any I/O when we are doing the actual open.
1173 if (spa_is_root(spa)) {
1174 int low = locks & ~(SCL_ZIO - 1);
1175 int high = locks & ~low;
1177 spa_config_enter(spa, high, spa, RW_WRITER);
1178 vdev_hold(spa->spa_root_vdev);
1179 spa_config_enter(spa, low, spa, RW_WRITER);
1180 } else {
1181 spa_config_enter(spa, locks, spa, RW_WRITER);
1183 spa->spa_vdev_locks = locks;
1187 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
1189 boolean_t config_changed = B_FALSE;
1191 if (vd != NULL || error == 0)
1192 vdev_dtl_reassess(vd ? vd->vdev_top : spa->spa_root_vdev,
1193 0, 0, B_FALSE);
1195 if (vd != NULL) {
1196 vdev_state_dirty(vd->vdev_top);
1197 config_changed = B_TRUE;
1198 spa->spa_config_generation++;
1201 if (spa_is_root(spa))
1202 vdev_rele(spa->spa_root_vdev);
1204 ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1205 spa_config_exit(spa, spa->spa_vdev_locks, spa);
1208 * If anything changed, wait for it to sync. This ensures that,
1209 * from the system administrator's perspective, zpool(1M) commands
1210 * are synchronous. This is important for things like zpool offline:
1211 * when the command completes, you expect no further I/O from ZFS.
1213 if (vd != NULL)
1214 txg_wait_synced(spa->spa_dsl_pool, 0);
1217 * If the config changed, update the config cache.
1219 if (config_changed) {
1220 mutex_enter(&spa_namespace_lock);
1221 spa_config_sync(spa, B_FALSE, B_TRUE);
1222 mutex_exit(&spa_namespace_lock);
1225 return (error);
1229 * ==========================================================================
1230 * Miscellaneous functions
1231 * ==========================================================================
1234 void
1235 spa_activate_mos_feature(spa_t *spa, const char *feature, dmu_tx_t *tx)
1237 if (!nvlist_exists(spa->spa_label_features, feature)) {
1238 fnvlist_add_boolean(spa->spa_label_features, feature);
1240 * When we are creating the pool (tx_txg==TXG_INITIAL), we can't
1241 * dirty the vdev config because lock SCL_CONFIG is not held.
1242 * Thankfully, in this case we don't need to dirty the config
1243 * because it will be written out anyway when we finish
1244 * creating the pool.
1246 if (tx->tx_txg != TXG_INITIAL)
1247 vdev_config_dirty(spa->spa_root_vdev);
1251 void
1252 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1254 if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1255 vdev_config_dirty(spa->spa_root_vdev);
1259 * Rename a spa_t.
1262 spa_rename(const char *name, const char *newname)
1264 spa_t *spa;
1265 int err;
1268 * Lookup the spa_t and grab the config lock for writing. We need to
1269 * actually open the pool so that we can sync out the necessary labels.
1270 * It's OK to call spa_open() with the namespace lock held because we
1271 * allow recursive calls for other reasons.
1273 mutex_enter(&spa_namespace_lock);
1274 if ((err = spa_open(name, &spa, FTAG)) != 0) {
1275 mutex_exit(&spa_namespace_lock);
1276 return (err);
1279 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1281 avl_remove(&spa_namespace_avl, spa);
1282 (void) strlcpy(spa->spa_name, newname, sizeof (spa->spa_name));
1283 avl_add(&spa_namespace_avl, spa);
1286 * Sync all labels to disk with the new names by marking the root vdev
1287 * dirty and waiting for it to sync. It will pick up the new pool name
1288 * during the sync.
1290 vdev_config_dirty(spa->spa_root_vdev);
1292 spa_config_exit(spa, SCL_ALL, FTAG);
1294 txg_wait_synced(spa->spa_dsl_pool, 0);
1297 * Sync the updated config cache.
1299 spa_config_sync(spa, B_FALSE, B_TRUE);
1301 spa_close(spa, FTAG);
1303 mutex_exit(&spa_namespace_lock);
1305 return (0);
1309 * Return the spa_t associated with given pool_guid, if it exists. If
1310 * device_guid is non-zero, determine whether the pool exists *and* contains
1311 * a device with the specified device_guid.
1313 spa_t *
1314 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1316 spa_t *spa;
1317 avl_tree_t *t = &spa_namespace_avl;
1319 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1321 for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1322 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1323 continue;
1324 if (spa->spa_root_vdev == NULL)
1325 continue;
1326 if (spa_guid(spa) == pool_guid) {
1327 if (device_guid == 0)
1328 break;
1330 if (vdev_lookup_by_guid(spa->spa_root_vdev,
1331 device_guid) != NULL)
1332 break;
1335 * Check any devices we may be in the process of adding.
1337 if (spa->spa_pending_vdev) {
1338 if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1339 device_guid) != NULL)
1340 break;
1345 return (spa);
1349 * Determine whether a pool with the given pool_guid exists.
1351 boolean_t
1352 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1354 return (spa_by_guid(pool_guid, device_guid) != NULL);
1357 char *
1358 spa_strdup(const char *s)
1360 size_t len;
1361 char *new;
1363 len = strlen(s);
1364 new = kmem_alloc(len + 1, KM_SLEEP);
1365 bcopy(s, new, len);
1366 new[len] = '\0';
1368 return (new);
1371 void
1372 spa_strfree(char *s)
1374 kmem_free(s, strlen(s) + 1);
1377 uint64_t
1378 spa_get_random(uint64_t range)
1380 uint64_t r;
1382 ASSERT(range != 0);
1384 (void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
1386 return (r % range);
1389 uint64_t
1390 spa_generate_guid(spa_t *spa)
1392 uint64_t guid = spa_get_random(-1ULL);
1394 if (spa != NULL) {
1395 while (guid == 0 || spa_guid_exists(spa_guid(spa), guid))
1396 guid = spa_get_random(-1ULL);
1397 } else {
1398 while (guid == 0 || spa_guid_exists(guid, 0))
1399 guid = spa_get_random(-1ULL);
1402 return (guid);
1405 void
1406 snprintf_blkptr(char *buf, size_t buflen, const blkptr_t *bp)
1408 char type[256];
1409 char *checksum = NULL;
1410 char *compress = NULL;
1412 if (bp != NULL) {
1413 if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1414 dmu_object_byteswap_t bswap =
1415 DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1416 (void) snprintf(type, sizeof (type), "bswap %s %s",
1417 DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1418 "metadata" : "data",
1419 dmu_ot_byteswap[bswap].ob_name);
1420 } else {
1421 (void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1422 sizeof (type));
1424 if (!BP_IS_EMBEDDED(bp)) {
1425 checksum =
1426 zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1428 compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1431 SNPRINTF_BLKPTR(snprintf, ' ', buf, buflen, bp, type, checksum,
1432 compress);
1435 void
1436 spa_freeze(spa_t *spa)
1438 uint64_t freeze_txg = 0;
1440 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1441 if (spa->spa_freeze_txg == UINT64_MAX) {
1442 freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1443 spa->spa_freeze_txg = freeze_txg;
1445 spa_config_exit(spa, SCL_ALL, FTAG);
1446 if (freeze_txg != 0)
1447 txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1450 void
1451 zfs_panic_recover(const char *fmt, ...)
1453 va_list adx;
1455 va_start(adx, fmt);
1456 vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1457 va_end(adx);
1461 * This is a stripped-down version of strtoull, suitable only for converting
1462 * lowercase hexadecimal numbers that don't overflow.
1464 uint64_t
1465 strtonum(const char *str, char **nptr)
1467 uint64_t val = 0;
1468 char c;
1469 int digit;
1471 while ((c = *str) != '\0') {
1472 if (c >= '0' && c <= '9')
1473 digit = c - '0';
1474 else if (c >= 'a' && c <= 'f')
1475 digit = 10 + c - 'a';
1476 else
1477 break;
1479 val *= 16;
1480 val += digit;
1482 str++;
1485 if (nptr)
1486 *nptr = (char *)str;
1488 return (val);
1492 * ==========================================================================
1493 * Accessor functions
1494 * ==========================================================================
1497 boolean_t
1498 spa_shutting_down(spa_t *spa)
1500 return (spa->spa_async_suspended);
1503 dsl_pool_t *
1504 spa_get_dsl(spa_t *spa)
1506 return (spa->spa_dsl_pool);
1509 boolean_t
1510 spa_is_initializing(spa_t *spa)
1512 return (spa->spa_is_initializing);
1515 blkptr_t *
1516 spa_get_rootblkptr(spa_t *spa)
1518 return (&spa->spa_ubsync.ub_rootbp);
1521 void
1522 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1524 spa->spa_uberblock.ub_rootbp = *bp;
1527 void
1528 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1530 if (spa->spa_root == NULL)
1531 buf[0] = '\0';
1532 else
1533 (void) strncpy(buf, spa->spa_root, buflen);
1537 spa_sync_pass(spa_t *spa)
1539 return (spa->spa_sync_pass);
1542 char *
1543 spa_name(spa_t *spa)
1545 return (spa->spa_name);
1548 uint64_t
1549 spa_guid(spa_t *spa)
1551 dsl_pool_t *dp = spa_get_dsl(spa);
1552 uint64_t guid;
1555 * If we fail to parse the config during spa_load(), we can go through
1556 * the error path (which posts an ereport) and end up here with no root
1557 * vdev. We stash the original pool guid in 'spa_config_guid' to handle
1558 * this case.
1560 if (spa->spa_root_vdev == NULL)
1561 return (spa->spa_config_guid);
1563 guid = spa->spa_last_synced_guid != 0 ?
1564 spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1567 * Return the most recently synced out guid unless we're
1568 * in syncing context.
1570 if (dp && dsl_pool_sync_context(dp))
1571 return (spa->spa_root_vdev->vdev_guid);
1572 else
1573 return (guid);
1576 uint64_t
1577 spa_load_guid(spa_t *spa)
1580 * This is a GUID that exists solely as a reference for the
1581 * purposes of the arc. It is generated at load time, and
1582 * is never written to persistent storage.
1584 return (spa->spa_load_guid);
1587 uint64_t
1588 spa_last_synced_txg(spa_t *spa)
1590 return (spa->spa_ubsync.ub_txg);
1593 uint64_t
1594 spa_first_txg(spa_t *spa)
1596 return (spa->spa_first_txg);
1599 uint64_t
1600 spa_syncing_txg(spa_t *spa)
1602 return (spa->spa_syncing_txg);
1605 pool_state_t
1606 spa_state(spa_t *spa)
1608 return (spa->spa_state);
1611 spa_load_state_t
1612 spa_load_state(spa_t *spa)
1614 return (spa->spa_load_state);
1617 uint64_t
1618 spa_freeze_txg(spa_t *spa)
1620 return (spa->spa_freeze_txg);
1623 /* ARGSUSED */
1624 uint64_t
1625 spa_get_asize(spa_t *spa, uint64_t lsize)
1627 return (lsize * spa_asize_inflation);
1631 * Return the amount of slop space in bytes. It is 1/32 of the pool (3.2%),
1632 * or at least 32MB.
1634 * See the comment above spa_slop_shift for details.
1636 uint64_t
1637 spa_get_slop_space(spa_t *spa) {
1638 uint64_t space = spa_get_dspace(spa);
1639 return (MAX(space >> spa_slop_shift, SPA_MINDEVSIZE >> 1));
1642 uint64_t
1643 spa_get_dspace(spa_t *spa)
1645 return (spa->spa_dspace);
1648 void
1649 spa_update_dspace(spa_t *spa)
1651 spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1652 ddt_get_dedup_dspace(spa);
1656 * Return the failure mode that has been set to this pool. The default
1657 * behavior will be to block all I/Os when a complete failure occurs.
1659 uint8_t
1660 spa_get_failmode(spa_t *spa)
1662 return (spa->spa_failmode);
1665 boolean_t
1666 spa_suspended(spa_t *spa)
1668 return (spa->spa_suspended);
1671 uint64_t
1672 spa_version(spa_t *spa)
1674 return (spa->spa_ubsync.ub_version);
1677 boolean_t
1678 spa_deflate(spa_t *spa)
1680 return (spa->spa_deflate);
1683 metaslab_class_t *
1684 spa_normal_class(spa_t *spa)
1686 return (spa->spa_normal_class);
1689 metaslab_class_t *
1690 spa_log_class(spa_t *spa)
1692 return (spa->spa_log_class);
1695 void
1696 spa_evicting_os_register(spa_t *spa, objset_t *os)
1698 mutex_enter(&spa->spa_evicting_os_lock);
1699 list_insert_head(&spa->spa_evicting_os_list, os);
1700 mutex_exit(&spa->spa_evicting_os_lock);
1703 void
1704 spa_evicting_os_deregister(spa_t *spa, objset_t *os)
1706 mutex_enter(&spa->spa_evicting_os_lock);
1707 list_remove(&spa->spa_evicting_os_list, os);
1708 cv_broadcast(&spa->spa_evicting_os_cv);
1709 mutex_exit(&spa->spa_evicting_os_lock);
1712 void
1713 spa_evicting_os_wait(spa_t *spa)
1715 mutex_enter(&spa->spa_evicting_os_lock);
1716 while (!list_is_empty(&spa->spa_evicting_os_list))
1717 cv_wait(&spa->spa_evicting_os_cv, &spa->spa_evicting_os_lock);
1718 mutex_exit(&spa->spa_evicting_os_lock);
1720 dmu_buf_user_evict_wait();
1724 spa_max_replication(spa_t *spa)
1727 * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1728 * handle BPs with more than one DVA allocated. Set our max
1729 * replication level accordingly.
1731 if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1732 return (1);
1733 return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1737 spa_prev_software_version(spa_t *spa)
1739 return (spa->spa_prev_software_version);
1742 uint64_t
1743 spa_deadman_synctime(spa_t *spa)
1745 return (spa->spa_deadman_synctime);
1748 uint64_t
1749 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
1751 uint64_t asize = DVA_GET_ASIZE(dva);
1752 uint64_t dsize = asize;
1754 ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1756 if (asize != 0 && spa->spa_deflate) {
1757 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
1758 dsize = (asize >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio;
1761 return (dsize);
1764 uint64_t
1765 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
1767 uint64_t dsize = 0;
1769 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
1770 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1772 return (dsize);
1775 uint64_t
1776 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
1778 uint64_t dsize = 0;
1780 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1782 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
1783 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1785 spa_config_exit(spa, SCL_VDEV, FTAG);
1787 return (dsize);
1791 * ==========================================================================
1792 * Initialization and Termination
1793 * ==========================================================================
1796 static int
1797 spa_name_compare(const void *a1, const void *a2)
1799 const spa_t *s1 = a1;
1800 const spa_t *s2 = a2;
1801 int s;
1803 s = strcmp(s1->spa_name, s2->spa_name);
1804 if (s > 0)
1805 return (1);
1806 if (s < 0)
1807 return (-1);
1808 return (0);
1812 spa_busy(void)
1814 return (spa_active_count);
1817 void
1818 spa_boot_init()
1820 spa_config_load();
1823 void
1824 spa_init(int mode)
1826 mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
1827 mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
1828 mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
1829 cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
1831 avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
1832 offsetof(spa_t, spa_avl));
1834 avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
1835 offsetof(spa_aux_t, aux_avl));
1837 avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
1838 offsetof(spa_aux_t, aux_avl));
1840 spa_mode_global = mode;
1842 #ifdef _KERNEL
1843 spa_arch_init();
1844 #else
1845 if (spa_mode_global != FREAD && dprintf_find_string("watch")) {
1846 arc_procfd = open("/proc/self/ctl", O_WRONLY);
1847 if (arc_procfd == -1) {
1848 perror("could not enable watchpoints: "
1849 "opening /proc/self/ctl failed: ");
1850 } else {
1851 arc_watch = B_TRUE;
1854 #endif
1856 refcount_init();
1857 unique_init();
1858 range_tree_init();
1859 zio_init();
1860 dmu_init();
1861 zil_init();
1862 vdev_cache_stat_init();
1863 zfs_prop_init();
1864 zpool_prop_init();
1865 zpool_feature_init();
1866 spa_config_load();
1867 l2arc_start();
1870 void
1871 spa_fini(void)
1873 l2arc_stop();
1875 spa_evict_all();
1877 vdev_cache_stat_fini();
1878 zil_fini();
1879 dmu_fini();
1880 zio_fini();
1881 range_tree_fini();
1882 unique_fini();
1883 refcount_fini();
1885 avl_destroy(&spa_namespace_avl);
1886 avl_destroy(&spa_spare_avl);
1887 avl_destroy(&spa_l2cache_avl);
1889 cv_destroy(&spa_namespace_cv);
1890 mutex_destroy(&spa_namespace_lock);
1891 mutex_destroy(&spa_spare_lock);
1892 mutex_destroy(&spa_l2cache_lock);
1896 * Return whether this pool has slogs. No locking needed.
1897 * It's not a problem if the wrong answer is returned as it's only for
1898 * performance and not correctness
1900 boolean_t
1901 spa_has_slogs(spa_t *spa)
1903 return (spa->spa_log_class->mc_rotor != NULL);
1906 spa_log_state_t
1907 spa_get_log_state(spa_t *spa)
1909 return (spa->spa_log_state);
1912 void
1913 spa_set_log_state(spa_t *spa, spa_log_state_t state)
1915 spa->spa_log_state = state;
1918 boolean_t
1919 spa_is_root(spa_t *spa)
1921 return (spa->spa_is_root);
1924 boolean_t
1925 spa_writeable(spa_t *spa)
1927 return (!!(spa->spa_mode & FWRITE));
1931 * Returns true if there is a pending sync task in any of the current
1932 * syncing txg, the current quiescing txg, or the current open txg.
1934 boolean_t
1935 spa_has_pending_synctask(spa_t *spa)
1937 return (!txg_all_lists_empty(&spa->spa_dsl_pool->dp_sync_tasks));
1941 spa_mode(spa_t *spa)
1943 return (spa->spa_mode);
1946 uint64_t
1947 spa_bootfs(spa_t *spa)
1949 return (spa->spa_bootfs);
1952 uint64_t
1953 spa_delegation(spa_t *spa)
1955 return (spa->spa_delegation);
1958 objset_t *
1959 spa_meta_objset(spa_t *spa)
1961 return (spa->spa_meta_objset);
1964 enum zio_checksum
1965 spa_dedup_checksum(spa_t *spa)
1967 return (spa->spa_dedup_checksum);
1971 * Reset pool scan stat per scan pass (or reboot).
1973 void
1974 spa_scan_stat_init(spa_t *spa)
1976 /* data not stored on disk */
1977 spa->spa_scan_pass_start = gethrestime_sec();
1978 spa->spa_scan_pass_exam = 0;
1979 vdev_scan_stat_init(spa->spa_root_vdev);
1983 * Get scan stats for zpool status reports
1986 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
1988 dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
1990 if (scn == NULL || scn->scn_phys.scn_func == POOL_SCAN_NONE)
1991 return (SET_ERROR(ENOENT));
1992 bzero(ps, sizeof (pool_scan_stat_t));
1994 /* data stored on disk */
1995 ps->pss_func = scn->scn_phys.scn_func;
1996 ps->pss_start_time = scn->scn_phys.scn_start_time;
1997 ps->pss_end_time = scn->scn_phys.scn_end_time;
1998 ps->pss_to_examine = scn->scn_phys.scn_to_examine;
1999 ps->pss_examined = scn->scn_phys.scn_examined;
2000 ps->pss_to_process = scn->scn_phys.scn_to_process;
2001 ps->pss_processed = scn->scn_phys.scn_processed;
2002 ps->pss_errors = scn->scn_phys.scn_errors;
2003 ps->pss_state = scn->scn_phys.scn_state;
2005 /* data not stored on disk */
2006 ps->pss_pass_start = spa->spa_scan_pass_start;
2007 ps->pss_pass_exam = spa->spa_scan_pass_exam;
2009 return (0);
2012 boolean_t
2013 spa_debug_enabled(spa_t *spa)
2015 return (spa->spa_debug);
2019 spa_maxblocksize(spa_t *spa)
2021 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
2022 return (SPA_MAXBLOCKSIZE);
2023 else
2024 return (SPA_OLD_MAXBLOCKSIZE);