5027 zfs large block support (add copyright)
[unleashed.git] / usr / src / uts / common / fs / zfs / spa_misc.c
blob699b15cc58da38297e9d191dca924dc6acc59835
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 2015 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
26 * Copyright 2013 Saso Kiselkov. All rights reserved.
27 * Copyright (c) 2014 Integros [integros.com]
30 #include <sys/zfs_context.h>
31 #include <sys/spa_impl.h>
32 #include <sys/spa_boot.h>
33 #include <sys/zio.h>
34 #include <sys/zio_checksum.h>
35 #include <sys/zio_compress.h>
36 #include <sys/dmu.h>
37 #include <sys/dmu_tx.h>
38 #include <sys/zap.h>
39 #include <sys/zil.h>
40 #include <sys/vdev_impl.h>
41 #include <sys/metaslab.h>
42 #include <sys/uberblock_impl.h>
43 #include <sys/txg.h>
44 #include <sys/avl.h>
45 #include <sys/unique.h>
46 #include <sys/dsl_pool.h>
47 #include <sys/dsl_dir.h>
48 #include <sys/dsl_prop.h>
49 #include <sys/dsl_scan.h>
50 #include <sys/fs/zfs.h>
51 #include <sys/metaslab_impl.h>
52 #include <sys/arc.h>
53 #include <sys/ddt.h>
54 #include "zfs_prop.h"
55 #include <sys/zfeature.h>
58 * SPA locking
60 * There are four basic locks for managing spa_t structures:
62 * spa_namespace_lock (global mutex)
64 * This lock must be acquired to do any of the following:
66 * - Lookup a spa_t by name
67 * - Add or remove a spa_t from the namespace
68 * - Increase spa_refcount from non-zero
69 * - Check if spa_refcount is zero
70 * - Rename a spa_t
71 * - add/remove/attach/detach devices
72 * - Held for the duration of create/destroy/import/export
74 * It does not need to handle recursion. A create or destroy may
75 * reference objects (files or zvols) in other pools, but by
76 * definition they must have an existing reference, and will never need
77 * to lookup a spa_t by name.
79 * spa_refcount (per-spa refcount_t protected by mutex)
81 * This reference count keep track of any active users of the spa_t. The
82 * spa_t cannot be destroyed or freed while this is non-zero. Internally,
83 * the refcount is never really 'zero' - opening a pool implicitly keeps
84 * some references in the DMU. Internally we check against spa_minref, but
85 * present the image of a zero/non-zero value to consumers.
87 * spa_config_lock[] (per-spa array of rwlocks)
89 * This protects the spa_t from config changes, and must be held in
90 * the following circumstances:
92 * - RW_READER to perform I/O to the spa
93 * - RW_WRITER to change the vdev config
95 * The locking order is fairly straightforward:
97 * spa_namespace_lock -> spa_refcount
99 * The namespace lock must be acquired to increase the refcount from 0
100 * or to check if it is zero.
102 * spa_refcount -> spa_config_lock[]
104 * There must be at least one valid reference on the spa_t to acquire
105 * the config lock.
107 * spa_namespace_lock -> spa_config_lock[]
109 * The namespace lock must always be taken before the config lock.
112 * The spa_namespace_lock can be acquired directly and is globally visible.
114 * The namespace is manipulated using the following functions, all of which
115 * require the spa_namespace_lock to be held.
117 * spa_lookup() Lookup a spa_t by name.
119 * spa_add() Create a new spa_t in the namespace.
121 * spa_remove() Remove a spa_t from the namespace. This also
122 * frees up any memory associated with the spa_t.
124 * spa_next() Returns the next spa_t in the system, or the
125 * first if NULL is passed.
127 * spa_evict_all() Shutdown and remove all spa_t structures in
128 * the system.
130 * spa_guid_exists() Determine whether a pool/device guid exists.
132 * The spa_refcount is manipulated using the following functions:
134 * spa_open_ref() Adds a reference to the given spa_t. Must be
135 * called with spa_namespace_lock held if the
136 * refcount is currently zero.
138 * spa_close() Remove a reference from the spa_t. This will
139 * not free the spa_t or remove it from the
140 * namespace. No locking is required.
142 * spa_refcount_zero() Returns true if the refcount is currently
143 * zero. Must be called with spa_namespace_lock
144 * held.
146 * The spa_config_lock[] is an array of rwlocks, ordered as follows:
147 * SCL_CONFIG > SCL_STATE > SCL_ALLOC > SCL_ZIO > SCL_FREE > SCL_VDEV.
148 * spa_config_lock[] is manipulated with spa_config_{enter,exit,held}().
150 * To read the configuration, it suffices to hold one of these locks as reader.
151 * To modify the configuration, you must hold all locks as writer. To modify
152 * vdev state without altering the vdev tree's topology (e.g. online/offline),
153 * you must hold SCL_STATE and SCL_ZIO as writer.
155 * We use these distinct config locks to avoid recursive lock entry.
156 * For example, spa_sync() (which holds SCL_CONFIG as reader) induces
157 * block allocations (SCL_ALLOC), which may require reading space maps
158 * from disk (dmu_read() -> zio_read() -> SCL_ZIO).
160 * The spa config locks cannot be normal rwlocks because we need the
161 * ability to hand off ownership. For example, SCL_ZIO is acquired
162 * by the issuing thread and later released by an interrupt thread.
163 * They do, however, obey the usual write-wanted semantics to prevent
164 * writer (i.e. system administrator) starvation.
166 * The lock acquisition rules are as follows:
168 * SCL_CONFIG
169 * Protects changes to the vdev tree topology, such as vdev
170 * add/remove/attach/detach. Protects the dirty config list
171 * (spa_config_dirty_list) and the set of spares and l2arc devices.
173 * SCL_STATE
174 * Protects changes to pool state and vdev state, such as vdev
175 * online/offline/fault/degrade/clear. Protects the dirty state list
176 * (spa_state_dirty_list) and global pool state (spa_state).
178 * SCL_ALLOC
179 * Protects changes to metaslab groups and classes.
180 * Held as reader by metaslab_alloc() and metaslab_claim().
182 * SCL_ZIO
183 * Held by bp-level zios (those which have no io_vd upon entry)
184 * to prevent changes to the vdev tree. The bp-level zio implicitly
185 * protects all of its vdev child zios, which do not hold SCL_ZIO.
187 * SCL_FREE
188 * Protects changes to metaslab groups and classes.
189 * Held as reader by metaslab_free(). SCL_FREE is distinct from
190 * SCL_ALLOC, and lower than SCL_ZIO, so that we can safely free
191 * blocks in zio_done() while another i/o that holds either
192 * SCL_ALLOC or SCL_ZIO is waiting for this i/o to complete.
194 * SCL_VDEV
195 * Held as reader to prevent changes to the vdev tree during trivial
196 * inquiries such as bp_get_dsize(). SCL_VDEV is distinct from the
197 * other locks, and lower than all of them, to ensure that it's safe
198 * to acquire regardless of caller context.
200 * In addition, the following rules apply:
202 * (a) spa_props_lock protects pool properties, spa_config and spa_config_list.
203 * The lock ordering is SCL_CONFIG > spa_props_lock.
205 * (b) I/O operations on leaf vdevs. For any zio operation that takes
206 * an explicit vdev_t argument -- such as zio_ioctl(), zio_read_phys(),
207 * or zio_write_phys() -- the caller must ensure that the config cannot
208 * cannot change in the interim, and that the vdev cannot be reopened.
209 * SCL_STATE as reader suffices for both.
211 * The vdev configuration is protected by spa_vdev_enter() / spa_vdev_exit().
213 * spa_vdev_enter() Acquire the namespace lock and the config lock
214 * for writing.
216 * spa_vdev_exit() Release the config lock, wait for all I/O
217 * to complete, sync the updated configs to the
218 * cache, and release the namespace lock.
220 * vdev state is protected by spa_vdev_state_enter() / spa_vdev_state_exit().
221 * Like spa_vdev_enter/exit, these are convenience wrappers -- the actual
222 * locking is, always, based on spa_namespace_lock and spa_config_lock[].
224 * spa_rename() is also implemented within this file since it requires
225 * manipulation of the namespace.
228 static avl_tree_t spa_namespace_avl;
229 kmutex_t spa_namespace_lock;
230 static kcondvar_t spa_namespace_cv;
231 static int spa_active_count;
232 int spa_max_replication_override = SPA_DVAS_PER_BP;
234 static kmutex_t spa_spare_lock;
235 static avl_tree_t spa_spare_avl;
236 static kmutex_t spa_l2cache_lock;
237 static avl_tree_t spa_l2cache_avl;
239 kmem_cache_t *spa_buffer_pool;
240 int spa_mode_global;
242 #ifdef ZFS_DEBUG
243 /* Everything except dprintf and spa is on by default in debug builds */
244 int zfs_flags = ~(ZFS_DEBUG_DPRINTF | ZFS_DEBUG_SPA);
245 #else
246 int zfs_flags = 0;
247 #endif
250 * zfs_recover can be set to nonzero to attempt to recover from
251 * otherwise-fatal errors, typically caused by on-disk corruption. When
252 * set, calls to zfs_panic_recover() will turn into warning messages.
253 * This should only be used as a last resort, as it typically results
254 * in leaked space, or worse.
256 boolean_t zfs_recover = B_FALSE;
259 * If destroy encounters an EIO while reading metadata (e.g. indirect
260 * blocks), space referenced by the missing metadata can not be freed.
261 * Normally this causes the background destroy to become "stalled", as
262 * it is unable to make forward progress. While in this stalled state,
263 * all remaining space to free from the error-encountering filesystem is
264 * "temporarily leaked". Set this flag to cause it to ignore the EIO,
265 * permanently leak the space from indirect blocks that can not be read,
266 * and continue to free everything else that it can.
268 * The default, "stalling" behavior is useful if the storage partially
269 * fails (i.e. some but not all i/os fail), and then later recovers. In
270 * this case, we will be able to continue pool operations while it is
271 * partially failed, and when it recovers, we can continue to free the
272 * space, with no leaks. However, note that this case is actually
273 * fairly rare.
275 * Typically pools either (a) fail completely (but perhaps temporarily,
276 * e.g. a top-level vdev going offline), or (b) have localized,
277 * permanent errors (e.g. disk returns the wrong data due to bit flip or
278 * firmware bug). In case (a), this setting does not matter because the
279 * pool will be suspended and the sync thread will not be able to make
280 * forward progress regardless. In case (b), because the error is
281 * permanent, the best we can do is leak the minimum amount of space,
282 * which is what setting this flag will do. Therefore, it is reasonable
283 * for this flag to normally be set, but we chose the more conservative
284 * approach of not setting it, so that there is no possibility of
285 * leaking space in the "partial temporary" failure case.
287 boolean_t zfs_free_leak_on_eio = B_FALSE;
290 * Expiration time in milliseconds. This value has two meanings. First it is
291 * used to determine when the spa_deadman() logic should fire. By default the
292 * spa_deadman() will fire if spa_sync() has not completed in 1000 seconds.
293 * Secondly, the value determines if an I/O is considered "hung". Any I/O that
294 * has not completed in zfs_deadman_synctime_ms is considered "hung" resulting
295 * in a system panic.
297 uint64_t zfs_deadman_synctime_ms = 1000000ULL;
300 * Check time in milliseconds. This defines the frequency at which we check
301 * for hung I/O.
303 uint64_t zfs_deadman_checktime_ms = 5000ULL;
306 * Override the zfs deadman behavior via /etc/system. By default the
307 * deadman is enabled except on VMware and sparc deployments.
309 int zfs_deadman_enabled = -1;
312 * The worst case is single-sector max-parity RAID-Z blocks, in which
313 * case the space requirement is exactly (VDEV_RAIDZ_MAXPARITY + 1)
314 * times the size; so just assume that. Add to this the fact that
315 * we can have up to 3 DVAs per bp, and one more factor of 2 because
316 * the block may be dittoed with up to 3 DVAs by ddt_sync(). All together,
317 * the worst case is:
318 * (VDEV_RAIDZ_MAXPARITY + 1) * SPA_DVAS_PER_BP * 2 == 24
320 int spa_asize_inflation = 24;
323 * Normally, we don't allow the last 3.2% (1/(2^spa_slop_shift)) of space in
324 * the pool to be consumed. This ensures that we don't run the pool
325 * completely out of space, due to unaccounted changes (e.g. to the MOS).
326 * It also limits the worst-case time to allocate space. If we have
327 * less than this amount of free space, most ZPL operations (e.g. write,
328 * create) will return ENOSPC.
330 * Certain operations (e.g. file removal, most administrative actions) can
331 * use half the slop space. They will only return ENOSPC if less than half
332 * the slop space is free. Typically, once the pool has less than the slop
333 * space free, the user will use these operations to free up space in the pool.
334 * These are the operations that call dsl_pool_adjustedsize() with the netfree
335 * argument set to TRUE.
337 * A very restricted set of operations are always permitted, regardless of
338 * the amount of free space. These are the operations that call
339 * dsl_sync_task(ZFS_SPACE_CHECK_NONE), e.g. "zfs destroy". If these
340 * operations result in a net increase in the amount of space used,
341 * it is possible to run the pool completely out of space, causing it to
342 * be permanently read-only.
344 * See also the comments in zfs_space_check_t.
346 int spa_slop_shift = 5;
349 * ==========================================================================
350 * SPA config locking
351 * ==========================================================================
353 static void
354 spa_config_lock_init(spa_t *spa)
356 for (int i = 0; i < SCL_LOCKS; i++) {
357 spa_config_lock_t *scl = &spa->spa_config_lock[i];
358 mutex_init(&scl->scl_lock, NULL, MUTEX_DEFAULT, NULL);
359 cv_init(&scl->scl_cv, NULL, CV_DEFAULT, NULL);
360 refcount_create_untracked(&scl->scl_count);
361 scl->scl_writer = NULL;
362 scl->scl_write_wanted = 0;
366 static void
367 spa_config_lock_destroy(spa_t *spa)
369 for (int i = 0; i < SCL_LOCKS; i++) {
370 spa_config_lock_t *scl = &spa->spa_config_lock[i];
371 mutex_destroy(&scl->scl_lock);
372 cv_destroy(&scl->scl_cv);
373 refcount_destroy(&scl->scl_count);
374 ASSERT(scl->scl_writer == NULL);
375 ASSERT(scl->scl_write_wanted == 0);
380 spa_config_tryenter(spa_t *spa, int locks, void *tag, krw_t rw)
382 for (int i = 0; i < SCL_LOCKS; i++) {
383 spa_config_lock_t *scl = &spa->spa_config_lock[i];
384 if (!(locks & (1 << i)))
385 continue;
386 mutex_enter(&scl->scl_lock);
387 if (rw == RW_READER) {
388 if (scl->scl_writer || scl->scl_write_wanted) {
389 mutex_exit(&scl->scl_lock);
390 spa_config_exit(spa, locks & ((1 << i) - 1),
391 tag);
392 return (0);
394 } else {
395 ASSERT(scl->scl_writer != curthread);
396 if (!refcount_is_zero(&scl->scl_count)) {
397 mutex_exit(&scl->scl_lock);
398 spa_config_exit(spa, locks & ((1 << i) - 1),
399 tag);
400 return (0);
402 scl->scl_writer = curthread;
404 (void) refcount_add(&scl->scl_count, tag);
405 mutex_exit(&scl->scl_lock);
407 return (1);
410 void
411 spa_config_enter(spa_t *spa, int locks, void *tag, krw_t rw)
413 int wlocks_held = 0;
415 ASSERT3U(SCL_LOCKS, <, sizeof (wlocks_held) * NBBY);
417 for (int i = 0; i < SCL_LOCKS; i++) {
418 spa_config_lock_t *scl = &spa->spa_config_lock[i];
419 if (scl->scl_writer == curthread)
420 wlocks_held |= (1 << i);
421 if (!(locks & (1 << i)))
422 continue;
423 mutex_enter(&scl->scl_lock);
424 if (rw == RW_READER) {
425 while (scl->scl_writer || scl->scl_write_wanted) {
426 cv_wait(&scl->scl_cv, &scl->scl_lock);
428 } else {
429 ASSERT(scl->scl_writer != curthread);
430 while (!refcount_is_zero(&scl->scl_count)) {
431 scl->scl_write_wanted++;
432 cv_wait(&scl->scl_cv, &scl->scl_lock);
433 scl->scl_write_wanted--;
435 scl->scl_writer = curthread;
437 (void) refcount_add(&scl->scl_count, tag);
438 mutex_exit(&scl->scl_lock);
440 ASSERT(wlocks_held <= locks);
443 void
444 spa_config_exit(spa_t *spa, int locks, void *tag)
446 for (int i = SCL_LOCKS - 1; i >= 0; i--) {
447 spa_config_lock_t *scl = &spa->spa_config_lock[i];
448 if (!(locks & (1 << i)))
449 continue;
450 mutex_enter(&scl->scl_lock);
451 ASSERT(!refcount_is_zero(&scl->scl_count));
452 if (refcount_remove(&scl->scl_count, tag) == 0) {
453 ASSERT(scl->scl_writer == NULL ||
454 scl->scl_writer == curthread);
455 scl->scl_writer = NULL; /* OK in either case */
456 cv_broadcast(&scl->scl_cv);
458 mutex_exit(&scl->scl_lock);
463 spa_config_held(spa_t *spa, int locks, krw_t rw)
465 int locks_held = 0;
467 for (int i = 0; i < SCL_LOCKS; i++) {
468 spa_config_lock_t *scl = &spa->spa_config_lock[i];
469 if (!(locks & (1 << i)))
470 continue;
471 if ((rw == RW_READER && !refcount_is_zero(&scl->scl_count)) ||
472 (rw == RW_WRITER && scl->scl_writer == curthread))
473 locks_held |= 1 << i;
476 return (locks_held);
480 * ==========================================================================
481 * SPA namespace functions
482 * ==========================================================================
486 * Lookup the named spa_t in the AVL tree. The spa_namespace_lock must be held.
487 * Returns NULL if no matching spa_t is found.
489 spa_t *
490 spa_lookup(const char *name)
492 static spa_t search; /* spa_t is large; don't allocate on stack */
493 spa_t *spa;
494 avl_index_t where;
495 char *cp;
497 ASSERT(MUTEX_HELD(&spa_namespace_lock));
499 (void) strlcpy(search.spa_name, name, sizeof (search.spa_name));
502 * If it's a full dataset name, figure out the pool name and
503 * just use that.
505 cp = strpbrk(search.spa_name, "/@#");
506 if (cp != NULL)
507 *cp = '\0';
509 spa = avl_find(&spa_namespace_avl, &search, &where);
511 return (spa);
515 * Fires when spa_sync has not completed within zfs_deadman_synctime_ms.
516 * If the zfs_deadman_enabled flag is set then it inspects all vdev queues
517 * looking for potentially hung I/Os.
519 void
520 spa_deadman(void *arg)
522 spa_t *spa = arg;
525 * Disable the deadman timer if the pool is suspended.
527 if (spa_suspended(spa)) {
528 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
529 return;
532 zfs_dbgmsg("slow spa_sync: started %llu seconds ago, calls %llu",
533 (gethrtime() - spa->spa_sync_starttime) / NANOSEC,
534 ++spa->spa_deadman_calls);
535 if (zfs_deadman_enabled)
536 vdev_deadman(spa->spa_root_vdev);
540 * Create an uninitialized spa_t with the given name. Requires
541 * spa_namespace_lock. The caller must ensure that the spa_t doesn't already
542 * exist by calling spa_lookup() first.
544 spa_t *
545 spa_add(const char *name, nvlist_t *config, const char *altroot)
547 spa_t *spa;
548 spa_config_dirent_t *dp;
549 cyc_handler_t hdlr;
550 cyc_time_t when;
552 ASSERT(MUTEX_HELD(&spa_namespace_lock));
554 spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
556 mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
557 mutex_init(&spa->spa_errlist_lock, NULL, MUTEX_DEFAULT, NULL);
558 mutex_init(&spa->spa_errlog_lock, NULL, MUTEX_DEFAULT, NULL);
559 mutex_init(&spa->spa_evicting_os_lock, NULL, MUTEX_DEFAULT, NULL);
560 mutex_init(&spa->spa_history_lock, NULL, MUTEX_DEFAULT, NULL);
561 mutex_init(&spa->spa_proc_lock, NULL, MUTEX_DEFAULT, NULL);
562 mutex_init(&spa->spa_props_lock, NULL, MUTEX_DEFAULT, NULL);
563 mutex_init(&spa->spa_cksum_tmpls_lock, NULL, MUTEX_DEFAULT, NULL);
564 mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
565 mutex_init(&spa->spa_suspend_lock, NULL, MUTEX_DEFAULT, NULL);
566 mutex_init(&spa->spa_vdev_top_lock, NULL, MUTEX_DEFAULT, NULL);
567 mutex_init(&spa->spa_iokstat_lock, NULL, MUTEX_DEFAULT, NULL);
569 cv_init(&spa->spa_async_cv, NULL, CV_DEFAULT, NULL);
570 cv_init(&spa->spa_evicting_os_cv, NULL, CV_DEFAULT, NULL);
571 cv_init(&spa->spa_proc_cv, NULL, CV_DEFAULT, NULL);
572 cv_init(&spa->spa_scrub_io_cv, NULL, CV_DEFAULT, NULL);
573 cv_init(&spa->spa_suspend_cv, NULL, CV_DEFAULT, NULL);
575 for (int t = 0; t < TXG_SIZE; t++)
576 bplist_create(&spa->spa_free_bplist[t]);
578 (void) strlcpy(spa->spa_name, name, sizeof (spa->spa_name));
579 spa->spa_state = POOL_STATE_UNINITIALIZED;
580 spa->spa_freeze_txg = UINT64_MAX;
581 spa->spa_final_txg = UINT64_MAX;
582 spa->spa_load_max_txg = UINT64_MAX;
583 spa->spa_proc = &p0;
584 spa->spa_proc_state = SPA_PROC_NONE;
586 hdlr.cyh_func = spa_deadman;
587 hdlr.cyh_arg = spa;
588 hdlr.cyh_level = CY_LOW_LEVEL;
590 spa->spa_deadman_synctime = MSEC2NSEC(zfs_deadman_synctime_ms);
593 * This determines how often we need to check for hung I/Os after
594 * the cyclic has already fired. Since checking for hung I/Os is
595 * an expensive operation we don't want to check too frequently.
596 * Instead wait for 5 seconds before checking again.
598 when.cyt_interval = MSEC2NSEC(zfs_deadman_checktime_ms);
599 when.cyt_when = CY_INFINITY;
600 mutex_enter(&cpu_lock);
601 spa->spa_deadman_cycid = cyclic_add(&hdlr, &when);
602 mutex_exit(&cpu_lock);
604 refcount_create(&spa->spa_refcount);
605 spa_config_lock_init(spa);
607 avl_add(&spa_namespace_avl, spa);
610 * Set the alternate root, if there is one.
612 if (altroot) {
613 spa->spa_root = spa_strdup(altroot);
614 spa_active_count++;
618 * Every pool starts with the default cachefile
620 list_create(&spa->spa_config_list, sizeof (spa_config_dirent_t),
621 offsetof(spa_config_dirent_t, scd_link));
623 dp = kmem_zalloc(sizeof (spa_config_dirent_t), KM_SLEEP);
624 dp->scd_path = altroot ? NULL : spa_strdup(spa_config_path);
625 list_insert_head(&spa->spa_config_list, dp);
627 VERIFY(nvlist_alloc(&spa->spa_load_info, NV_UNIQUE_NAME,
628 KM_SLEEP) == 0);
630 if (config != NULL) {
631 nvlist_t *features;
633 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_FEATURES_FOR_READ,
634 &features) == 0) {
635 VERIFY(nvlist_dup(features, &spa->spa_label_features,
636 0) == 0);
639 VERIFY(nvlist_dup(config, &spa->spa_config, 0) == 0);
642 if (spa->spa_label_features == NULL) {
643 VERIFY(nvlist_alloc(&spa->spa_label_features, NV_UNIQUE_NAME,
644 KM_SLEEP) == 0);
647 spa->spa_iokstat = kstat_create("zfs", 0, name,
648 "disk", KSTAT_TYPE_IO, 1, 0);
649 if (spa->spa_iokstat) {
650 spa->spa_iokstat->ks_lock = &spa->spa_iokstat_lock;
651 kstat_install(spa->spa_iokstat);
654 spa->spa_debug = ((zfs_flags & ZFS_DEBUG_SPA) != 0);
656 spa->spa_min_ashift = INT_MAX;
657 spa->spa_max_ashift = 0;
660 * As a pool is being created, treat all features as disabled by
661 * setting SPA_FEATURE_DISABLED for all entries in the feature
662 * refcount cache.
664 for (int i = 0; i < SPA_FEATURES; i++) {
665 spa->spa_feat_refcount_cache[i] = SPA_FEATURE_DISABLED;
668 return (spa);
672 * Removes a spa_t from the namespace, freeing up any memory used. Requires
673 * spa_namespace_lock. This is called only after the spa_t has been closed and
674 * deactivated.
676 void
677 spa_remove(spa_t *spa)
679 spa_config_dirent_t *dp;
681 ASSERT(MUTEX_HELD(&spa_namespace_lock));
682 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
683 ASSERT3U(refcount_count(&spa->spa_refcount), ==, 0);
685 nvlist_free(spa->spa_config_splitting);
687 avl_remove(&spa_namespace_avl, spa);
688 cv_broadcast(&spa_namespace_cv);
690 if (spa->spa_root) {
691 spa_strfree(spa->spa_root);
692 spa_active_count--;
695 while ((dp = list_head(&spa->spa_config_list)) != NULL) {
696 list_remove(&spa->spa_config_list, dp);
697 if (dp->scd_path != NULL)
698 spa_strfree(dp->scd_path);
699 kmem_free(dp, sizeof (spa_config_dirent_t));
702 list_destroy(&spa->spa_config_list);
704 nvlist_free(spa->spa_label_features);
705 nvlist_free(spa->spa_load_info);
706 spa_config_set(spa, NULL);
708 mutex_enter(&cpu_lock);
709 if (spa->spa_deadman_cycid != CYCLIC_NONE)
710 cyclic_remove(spa->spa_deadman_cycid);
711 mutex_exit(&cpu_lock);
712 spa->spa_deadman_cycid = CYCLIC_NONE;
714 refcount_destroy(&spa->spa_refcount);
716 spa_config_lock_destroy(spa);
718 kstat_delete(spa->spa_iokstat);
719 spa->spa_iokstat = NULL;
721 for (int t = 0; t < TXG_SIZE; t++)
722 bplist_destroy(&spa->spa_free_bplist[t]);
724 zio_checksum_templates_free(spa);
726 cv_destroy(&spa->spa_async_cv);
727 cv_destroy(&spa->spa_evicting_os_cv);
728 cv_destroy(&spa->spa_proc_cv);
729 cv_destroy(&spa->spa_scrub_io_cv);
730 cv_destroy(&spa->spa_suspend_cv);
732 mutex_destroy(&spa->spa_async_lock);
733 mutex_destroy(&spa->spa_errlist_lock);
734 mutex_destroy(&spa->spa_errlog_lock);
735 mutex_destroy(&spa->spa_evicting_os_lock);
736 mutex_destroy(&spa->spa_history_lock);
737 mutex_destroy(&spa->spa_proc_lock);
738 mutex_destroy(&spa->spa_props_lock);
739 mutex_destroy(&spa->spa_cksum_tmpls_lock);
740 mutex_destroy(&spa->spa_scrub_lock);
741 mutex_destroy(&spa->spa_suspend_lock);
742 mutex_destroy(&spa->spa_vdev_top_lock);
743 mutex_destroy(&spa->spa_iokstat_lock);
745 kmem_free(spa, sizeof (spa_t));
749 * Given a pool, return the next pool in the namespace, or NULL if there is
750 * none. If 'prev' is NULL, return the first pool.
752 spa_t *
753 spa_next(spa_t *prev)
755 ASSERT(MUTEX_HELD(&spa_namespace_lock));
757 if (prev)
758 return (AVL_NEXT(&spa_namespace_avl, prev));
759 else
760 return (avl_first(&spa_namespace_avl));
764 * ==========================================================================
765 * SPA refcount functions
766 * ==========================================================================
770 * Add a reference to the given spa_t. Must have at least one reference, or
771 * have the namespace lock held.
773 void
774 spa_open_ref(spa_t *spa, void *tag)
776 ASSERT(refcount_count(&spa->spa_refcount) >= spa->spa_minref ||
777 MUTEX_HELD(&spa_namespace_lock));
778 (void) refcount_add(&spa->spa_refcount, tag);
782 * Remove a reference to the given spa_t. Must have at least one reference, or
783 * have the namespace lock held.
785 void
786 spa_close(spa_t *spa, void *tag)
788 ASSERT(refcount_count(&spa->spa_refcount) > spa->spa_minref ||
789 MUTEX_HELD(&spa_namespace_lock));
790 (void) refcount_remove(&spa->spa_refcount, tag);
794 * Remove a reference to the given spa_t held by a dsl dir that is
795 * being asynchronously released. Async releases occur from a taskq
796 * performing eviction of dsl datasets and dirs. The namespace lock
797 * isn't held and the hold by the object being evicted may contribute to
798 * spa_minref (e.g. dataset or directory released during pool export),
799 * so the asserts in spa_close() do not apply.
801 void
802 spa_async_close(spa_t *spa, void *tag)
804 (void) refcount_remove(&spa->spa_refcount, tag);
808 * Check to see if the spa refcount is zero. Must be called with
809 * spa_namespace_lock held. We really compare against spa_minref, which is the
810 * number of references acquired when opening a pool
812 boolean_t
813 spa_refcount_zero(spa_t *spa)
815 ASSERT(MUTEX_HELD(&spa_namespace_lock));
817 return (refcount_count(&spa->spa_refcount) == spa->spa_minref);
821 * ==========================================================================
822 * SPA spare and l2cache tracking
823 * ==========================================================================
827 * Hot spares and cache devices are tracked using the same code below,
828 * for 'auxiliary' devices.
831 typedef struct spa_aux {
832 uint64_t aux_guid;
833 uint64_t aux_pool;
834 avl_node_t aux_avl;
835 int aux_count;
836 } spa_aux_t;
838 static int
839 spa_aux_compare(const void *a, const void *b)
841 const spa_aux_t *sa = a;
842 const spa_aux_t *sb = b;
844 if (sa->aux_guid < sb->aux_guid)
845 return (-1);
846 else if (sa->aux_guid > sb->aux_guid)
847 return (1);
848 else
849 return (0);
852 void
853 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
855 avl_index_t where;
856 spa_aux_t search;
857 spa_aux_t *aux;
859 search.aux_guid = vd->vdev_guid;
860 if ((aux = avl_find(avl, &search, &where)) != NULL) {
861 aux->aux_count++;
862 } else {
863 aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
864 aux->aux_guid = vd->vdev_guid;
865 aux->aux_count = 1;
866 avl_insert(avl, aux, where);
870 void
871 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
873 spa_aux_t search;
874 spa_aux_t *aux;
875 avl_index_t where;
877 search.aux_guid = vd->vdev_guid;
878 aux = avl_find(avl, &search, &where);
880 ASSERT(aux != NULL);
882 if (--aux->aux_count == 0) {
883 avl_remove(avl, aux);
884 kmem_free(aux, sizeof (spa_aux_t));
885 } else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
886 aux->aux_pool = 0ULL;
890 boolean_t
891 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
893 spa_aux_t search, *found;
895 search.aux_guid = guid;
896 found = avl_find(avl, &search, NULL);
898 if (pool) {
899 if (found)
900 *pool = found->aux_pool;
901 else
902 *pool = 0ULL;
905 if (refcnt) {
906 if (found)
907 *refcnt = found->aux_count;
908 else
909 *refcnt = 0;
912 return (found != NULL);
915 void
916 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
918 spa_aux_t search, *found;
919 avl_index_t where;
921 search.aux_guid = vd->vdev_guid;
922 found = avl_find(avl, &search, &where);
923 ASSERT(found != NULL);
924 ASSERT(found->aux_pool == 0ULL);
926 found->aux_pool = spa_guid(vd->vdev_spa);
930 * Spares are tracked globally due to the following constraints:
932 * - A spare may be part of multiple pools.
933 * - A spare may be added to a pool even if it's actively in use within
934 * another pool.
935 * - A spare in use in any pool can only be the source of a replacement if
936 * the target is a spare in the same pool.
938 * We keep track of all spares on the system through the use of a reference
939 * counted AVL tree. When a vdev is added as a spare, or used as a replacement
940 * spare, then we bump the reference count in the AVL tree. In addition, we set
941 * the 'vdev_isspare' member to indicate that the device is a spare (active or
942 * inactive). When a spare is made active (used to replace a device in the
943 * pool), we also keep track of which pool its been made a part of.
945 * The 'spa_spare_lock' protects the AVL tree. These functions are normally
946 * called under the spa_namespace lock as part of vdev reconfiguration. The
947 * separate spare lock exists for the status query path, which does not need to
948 * be completely consistent with respect to other vdev configuration changes.
951 static int
952 spa_spare_compare(const void *a, const void *b)
954 return (spa_aux_compare(a, b));
957 void
958 spa_spare_add(vdev_t *vd)
960 mutex_enter(&spa_spare_lock);
961 ASSERT(!vd->vdev_isspare);
962 spa_aux_add(vd, &spa_spare_avl);
963 vd->vdev_isspare = B_TRUE;
964 mutex_exit(&spa_spare_lock);
967 void
968 spa_spare_remove(vdev_t *vd)
970 mutex_enter(&spa_spare_lock);
971 ASSERT(vd->vdev_isspare);
972 spa_aux_remove(vd, &spa_spare_avl);
973 vd->vdev_isspare = B_FALSE;
974 mutex_exit(&spa_spare_lock);
977 boolean_t
978 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
980 boolean_t found;
982 mutex_enter(&spa_spare_lock);
983 found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
984 mutex_exit(&spa_spare_lock);
986 return (found);
989 void
990 spa_spare_activate(vdev_t *vd)
992 mutex_enter(&spa_spare_lock);
993 ASSERT(vd->vdev_isspare);
994 spa_aux_activate(vd, &spa_spare_avl);
995 mutex_exit(&spa_spare_lock);
999 * Level 2 ARC devices are tracked globally for the same reasons as spares.
1000 * Cache devices currently only support one pool per cache device, and so
1001 * for these devices the aux reference count is currently unused beyond 1.
1004 static int
1005 spa_l2cache_compare(const void *a, const void *b)
1007 return (spa_aux_compare(a, b));
1010 void
1011 spa_l2cache_add(vdev_t *vd)
1013 mutex_enter(&spa_l2cache_lock);
1014 ASSERT(!vd->vdev_isl2cache);
1015 spa_aux_add(vd, &spa_l2cache_avl);
1016 vd->vdev_isl2cache = B_TRUE;
1017 mutex_exit(&spa_l2cache_lock);
1020 void
1021 spa_l2cache_remove(vdev_t *vd)
1023 mutex_enter(&spa_l2cache_lock);
1024 ASSERT(vd->vdev_isl2cache);
1025 spa_aux_remove(vd, &spa_l2cache_avl);
1026 vd->vdev_isl2cache = B_FALSE;
1027 mutex_exit(&spa_l2cache_lock);
1030 boolean_t
1031 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
1033 boolean_t found;
1035 mutex_enter(&spa_l2cache_lock);
1036 found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
1037 mutex_exit(&spa_l2cache_lock);
1039 return (found);
1042 void
1043 spa_l2cache_activate(vdev_t *vd)
1045 mutex_enter(&spa_l2cache_lock);
1046 ASSERT(vd->vdev_isl2cache);
1047 spa_aux_activate(vd, &spa_l2cache_avl);
1048 mutex_exit(&spa_l2cache_lock);
1052 * ==========================================================================
1053 * SPA vdev locking
1054 * ==========================================================================
1058 * Lock the given spa_t for the purpose of adding or removing a vdev.
1059 * Grabs the global spa_namespace_lock plus the spa config lock for writing.
1060 * It returns the next transaction group for the spa_t.
1062 uint64_t
1063 spa_vdev_enter(spa_t *spa)
1065 mutex_enter(&spa->spa_vdev_top_lock);
1066 mutex_enter(&spa_namespace_lock);
1067 return (spa_vdev_config_enter(spa));
1071 * Internal implementation for spa_vdev_enter(). Used when a vdev
1072 * operation requires multiple syncs (i.e. removing a device) while
1073 * keeping the spa_namespace_lock held.
1075 uint64_t
1076 spa_vdev_config_enter(spa_t *spa)
1078 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1080 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1082 return (spa_last_synced_txg(spa) + 1);
1086 * Used in combination with spa_vdev_config_enter() to allow the syncing
1087 * of multiple transactions without releasing the spa_namespace_lock.
1089 void
1090 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error, char *tag)
1092 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1094 int config_changed = B_FALSE;
1096 ASSERT(txg > spa_last_synced_txg(spa));
1098 spa->spa_pending_vdev = NULL;
1101 * Reassess the DTLs.
1103 vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE);
1105 if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
1106 config_changed = B_TRUE;
1107 spa->spa_config_generation++;
1111 * Verify the metaslab classes.
1113 ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
1114 ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
1116 spa_config_exit(spa, SCL_ALL, spa);
1119 * Panic the system if the specified tag requires it. This
1120 * is useful for ensuring that configurations are updated
1121 * transactionally.
1123 if (zio_injection_enabled)
1124 zio_handle_panic_injection(spa, tag, 0);
1127 * Note: this txg_wait_synced() is important because it ensures
1128 * that there won't be more than one config change per txg.
1129 * This allows us to use the txg as the generation number.
1131 if (error == 0)
1132 txg_wait_synced(spa->spa_dsl_pool, txg);
1134 if (vd != NULL) {
1135 ASSERT(!vd->vdev_detached || vd->vdev_dtl_sm == NULL);
1136 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1137 vdev_free(vd);
1138 spa_config_exit(spa, SCL_ALL, spa);
1142 * If the config changed, update the config cache.
1144 if (config_changed)
1145 spa_config_sync(spa, B_FALSE, B_TRUE);
1149 * Unlock the spa_t after adding or removing a vdev. Besides undoing the
1150 * locking of spa_vdev_enter(), we also want make sure the transactions have
1151 * synced to disk, and then update the global configuration cache with the new
1152 * information.
1155 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
1157 spa_vdev_config_exit(spa, vd, txg, error, FTAG);
1158 mutex_exit(&spa_namespace_lock);
1159 mutex_exit(&spa->spa_vdev_top_lock);
1161 return (error);
1165 * Lock the given spa_t for the purpose of changing vdev state.
1167 void
1168 spa_vdev_state_enter(spa_t *spa, int oplocks)
1170 int locks = SCL_STATE_ALL | oplocks;
1173 * Root pools may need to read of the underlying devfs filesystem
1174 * when opening up a vdev. Unfortunately if we're holding the
1175 * SCL_ZIO lock it will result in a deadlock when we try to issue
1176 * the read from the root filesystem. Instead we "prefetch"
1177 * the associated vnodes that we need prior to opening the
1178 * underlying devices and cache them so that we can prevent
1179 * any I/O when we are doing the actual open.
1181 if (spa_is_root(spa)) {
1182 int low = locks & ~(SCL_ZIO - 1);
1183 int high = locks & ~low;
1185 spa_config_enter(spa, high, spa, RW_WRITER);
1186 vdev_hold(spa->spa_root_vdev);
1187 spa_config_enter(spa, low, spa, RW_WRITER);
1188 } else {
1189 spa_config_enter(spa, locks, spa, RW_WRITER);
1191 spa->spa_vdev_locks = locks;
1195 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
1197 boolean_t config_changed = B_FALSE;
1199 if (vd != NULL || error == 0)
1200 vdev_dtl_reassess(vd ? vd->vdev_top : spa->spa_root_vdev,
1201 0, 0, B_FALSE);
1203 if (vd != NULL) {
1204 vdev_state_dirty(vd->vdev_top);
1205 config_changed = B_TRUE;
1206 spa->spa_config_generation++;
1209 if (spa_is_root(spa))
1210 vdev_rele(spa->spa_root_vdev);
1212 ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1213 spa_config_exit(spa, spa->spa_vdev_locks, spa);
1216 * If anything changed, wait for it to sync. This ensures that,
1217 * from the system administrator's perspective, zpool(1M) commands
1218 * are synchronous. This is important for things like zpool offline:
1219 * when the command completes, you expect no further I/O from ZFS.
1221 if (vd != NULL)
1222 txg_wait_synced(spa->spa_dsl_pool, 0);
1225 * If the config changed, update the config cache.
1227 if (config_changed) {
1228 mutex_enter(&spa_namespace_lock);
1229 spa_config_sync(spa, B_FALSE, B_TRUE);
1230 mutex_exit(&spa_namespace_lock);
1233 return (error);
1237 * ==========================================================================
1238 * Miscellaneous functions
1239 * ==========================================================================
1242 void
1243 spa_activate_mos_feature(spa_t *spa, const char *feature, dmu_tx_t *tx)
1245 if (!nvlist_exists(spa->spa_label_features, feature)) {
1246 fnvlist_add_boolean(spa->spa_label_features, feature);
1248 * When we are creating the pool (tx_txg==TXG_INITIAL), we can't
1249 * dirty the vdev config because lock SCL_CONFIG is not held.
1250 * Thankfully, in this case we don't need to dirty the config
1251 * because it will be written out anyway when we finish
1252 * creating the pool.
1254 if (tx->tx_txg != TXG_INITIAL)
1255 vdev_config_dirty(spa->spa_root_vdev);
1259 void
1260 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1262 if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1263 vdev_config_dirty(spa->spa_root_vdev);
1267 * Rename a spa_t.
1270 spa_rename(const char *name, const char *newname)
1272 spa_t *spa;
1273 int err;
1276 * Lookup the spa_t and grab the config lock for writing. We need to
1277 * actually open the pool so that we can sync out the necessary labels.
1278 * It's OK to call spa_open() with the namespace lock held because we
1279 * allow recursive calls for other reasons.
1281 mutex_enter(&spa_namespace_lock);
1282 if ((err = spa_open(name, &spa, FTAG)) != 0) {
1283 mutex_exit(&spa_namespace_lock);
1284 return (err);
1287 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1289 avl_remove(&spa_namespace_avl, spa);
1290 (void) strlcpy(spa->spa_name, newname, sizeof (spa->spa_name));
1291 avl_add(&spa_namespace_avl, spa);
1294 * Sync all labels to disk with the new names by marking the root vdev
1295 * dirty and waiting for it to sync. It will pick up the new pool name
1296 * during the sync.
1298 vdev_config_dirty(spa->spa_root_vdev);
1300 spa_config_exit(spa, SCL_ALL, FTAG);
1302 txg_wait_synced(spa->spa_dsl_pool, 0);
1305 * Sync the updated config cache.
1307 spa_config_sync(spa, B_FALSE, B_TRUE);
1309 spa_close(spa, FTAG);
1311 mutex_exit(&spa_namespace_lock);
1313 return (0);
1317 * Return the spa_t associated with given pool_guid, if it exists. If
1318 * device_guid is non-zero, determine whether the pool exists *and* contains
1319 * a device with the specified device_guid.
1321 spa_t *
1322 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1324 spa_t *spa;
1325 avl_tree_t *t = &spa_namespace_avl;
1327 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1329 for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1330 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1331 continue;
1332 if (spa->spa_root_vdev == NULL)
1333 continue;
1334 if (spa_guid(spa) == pool_guid) {
1335 if (device_guid == 0)
1336 break;
1338 if (vdev_lookup_by_guid(spa->spa_root_vdev,
1339 device_guid) != NULL)
1340 break;
1343 * Check any devices we may be in the process of adding.
1345 if (spa->spa_pending_vdev) {
1346 if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1347 device_guid) != NULL)
1348 break;
1353 return (spa);
1357 * Determine whether a pool with the given pool_guid exists.
1359 boolean_t
1360 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1362 return (spa_by_guid(pool_guid, device_guid) != NULL);
1365 char *
1366 spa_strdup(const char *s)
1368 size_t len;
1369 char *new;
1371 len = strlen(s);
1372 new = kmem_alloc(len + 1, KM_SLEEP);
1373 bcopy(s, new, len);
1374 new[len] = '\0';
1376 return (new);
1379 void
1380 spa_strfree(char *s)
1382 kmem_free(s, strlen(s) + 1);
1385 uint64_t
1386 spa_get_random(uint64_t range)
1388 uint64_t r;
1390 ASSERT(range != 0);
1392 (void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
1394 return (r % range);
1397 uint64_t
1398 spa_generate_guid(spa_t *spa)
1400 uint64_t guid = spa_get_random(-1ULL);
1402 if (spa != NULL) {
1403 while (guid == 0 || spa_guid_exists(spa_guid(spa), guid))
1404 guid = spa_get_random(-1ULL);
1405 } else {
1406 while (guid == 0 || spa_guid_exists(guid, 0))
1407 guid = spa_get_random(-1ULL);
1410 return (guid);
1413 void
1414 snprintf_blkptr(char *buf, size_t buflen, const blkptr_t *bp)
1416 char type[256];
1417 char *checksum = NULL;
1418 char *compress = NULL;
1420 if (bp != NULL) {
1421 if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1422 dmu_object_byteswap_t bswap =
1423 DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1424 (void) snprintf(type, sizeof (type), "bswap %s %s",
1425 DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1426 "metadata" : "data",
1427 dmu_ot_byteswap[bswap].ob_name);
1428 } else {
1429 (void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1430 sizeof (type));
1432 if (!BP_IS_EMBEDDED(bp)) {
1433 checksum =
1434 zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1436 compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1439 SNPRINTF_BLKPTR(snprintf, ' ', buf, buflen, bp, type, checksum,
1440 compress);
1443 void
1444 spa_freeze(spa_t *spa)
1446 uint64_t freeze_txg = 0;
1448 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1449 if (spa->spa_freeze_txg == UINT64_MAX) {
1450 freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1451 spa->spa_freeze_txg = freeze_txg;
1453 spa_config_exit(spa, SCL_ALL, FTAG);
1454 if (freeze_txg != 0)
1455 txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1458 void
1459 zfs_panic_recover(const char *fmt, ...)
1461 va_list adx;
1463 va_start(adx, fmt);
1464 vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1465 va_end(adx);
1469 * This is a stripped-down version of strtoull, suitable only for converting
1470 * lowercase hexadecimal numbers that don't overflow.
1472 uint64_t
1473 strtonum(const char *str, char **nptr)
1475 uint64_t val = 0;
1476 char c;
1477 int digit;
1479 while ((c = *str) != '\0') {
1480 if (c >= '0' && c <= '9')
1481 digit = c - '0';
1482 else if (c >= 'a' && c <= 'f')
1483 digit = 10 + c - 'a';
1484 else
1485 break;
1487 val *= 16;
1488 val += digit;
1490 str++;
1493 if (nptr)
1494 *nptr = (char *)str;
1496 return (val);
1500 * ==========================================================================
1501 * Accessor functions
1502 * ==========================================================================
1505 boolean_t
1506 spa_shutting_down(spa_t *spa)
1508 return (spa->spa_async_suspended);
1511 dsl_pool_t *
1512 spa_get_dsl(spa_t *spa)
1514 return (spa->spa_dsl_pool);
1517 boolean_t
1518 spa_is_initializing(spa_t *spa)
1520 return (spa->spa_is_initializing);
1523 blkptr_t *
1524 spa_get_rootblkptr(spa_t *spa)
1526 return (&spa->spa_ubsync.ub_rootbp);
1529 void
1530 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1532 spa->spa_uberblock.ub_rootbp = *bp;
1535 void
1536 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1538 if (spa->spa_root == NULL)
1539 buf[0] = '\0';
1540 else
1541 (void) strncpy(buf, spa->spa_root, buflen);
1545 spa_sync_pass(spa_t *spa)
1547 return (spa->spa_sync_pass);
1550 char *
1551 spa_name(spa_t *spa)
1553 return (spa->spa_name);
1556 uint64_t
1557 spa_guid(spa_t *spa)
1559 dsl_pool_t *dp = spa_get_dsl(spa);
1560 uint64_t guid;
1563 * If we fail to parse the config during spa_load(), we can go through
1564 * the error path (which posts an ereport) and end up here with no root
1565 * vdev. We stash the original pool guid in 'spa_config_guid' to handle
1566 * this case.
1568 if (spa->spa_root_vdev == NULL)
1569 return (spa->spa_config_guid);
1571 guid = spa->spa_last_synced_guid != 0 ?
1572 spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1575 * Return the most recently synced out guid unless we're
1576 * in syncing context.
1578 if (dp && dsl_pool_sync_context(dp))
1579 return (spa->spa_root_vdev->vdev_guid);
1580 else
1581 return (guid);
1584 uint64_t
1585 spa_load_guid(spa_t *spa)
1588 * This is a GUID that exists solely as a reference for the
1589 * purposes of the arc. It is generated at load time, and
1590 * is never written to persistent storage.
1592 return (spa->spa_load_guid);
1595 uint64_t
1596 spa_last_synced_txg(spa_t *spa)
1598 return (spa->spa_ubsync.ub_txg);
1601 uint64_t
1602 spa_first_txg(spa_t *spa)
1604 return (spa->spa_first_txg);
1607 uint64_t
1608 spa_syncing_txg(spa_t *spa)
1610 return (spa->spa_syncing_txg);
1613 pool_state_t
1614 spa_state(spa_t *spa)
1616 return (spa->spa_state);
1619 spa_load_state_t
1620 spa_load_state(spa_t *spa)
1622 return (spa->spa_load_state);
1625 uint64_t
1626 spa_freeze_txg(spa_t *spa)
1628 return (spa->spa_freeze_txg);
1631 /* ARGSUSED */
1632 uint64_t
1633 spa_get_asize(spa_t *spa, uint64_t lsize)
1635 return (lsize * spa_asize_inflation);
1639 * Return the amount of slop space in bytes. It is 1/32 of the pool (3.2%),
1640 * or at least 32MB.
1642 * See the comment above spa_slop_shift for details.
1644 uint64_t
1645 spa_get_slop_space(spa_t *spa) {
1646 uint64_t space = spa_get_dspace(spa);
1647 return (MAX(space >> spa_slop_shift, SPA_MINDEVSIZE >> 1));
1650 uint64_t
1651 spa_get_dspace(spa_t *spa)
1653 return (spa->spa_dspace);
1656 void
1657 spa_update_dspace(spa_t *spa)
1659 spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1660 ddt_get_dedup_dspace(spa);
1664 * Return the failure mode that has been set to this pool. The default
1665 * behavior will be to block all I/Os when a complete failure occurs.
1667 uint8_t
1668 spa_get_failmode(spa_t *spa)
1670 return (spa->spa_failmode);
1673 boolean_t
1674 spa_suspended(spa_t *spa)
1676 return (spa->spa_suspended);
1679 uint64_t
1680 spa_version(spa_t *spa)
1682 return (spa->spa_ubsync.ub_version);
1685 boolean_t
1686 spa_deflate(spa_t *spa)
1688 return (spa->spa_deflate);
1691 metaslab_class_t *
1692 spa_normal_class(spa_t *spa)
1694 return (spa->spa_normal_class);
1697 metaslab_class_t *
1698 spa_log_class(spa_t *spa)
1700 return (spa->spa_log_class);
1703 void
1704 spa_evicting_os_register(spa_t *spa, objset_t *os)
1706 mutex_enter(&spa->spa_evicting_os_lock);
1707 list_insert_head(&spa->spa_evicting_os_list, os);
1708 mutex_exit(&spa->spa_evicting_os_lock);
1711 void
1712 spa_evicting_os_deregister(spa_t *spa, objset_t *os)
1714 mutex_enter(&spa->spa_evicting_os_lock);
1715 list_remove(&spa->spa_evicting_os_list, os);
1716 cv_broadcast(&spa->spa_evicting_os_cv);
1717 mutex_exit(&spa->spa_evicting_os_lock);
1720 void
1721 spa_evicting_os_wait(spa_t *spa)
1723 mutex_enter(&spa->spa_evicting_os_lock);
1724 while (!list_is_empty(&spa->spa_evicting_os_list))
1725 cv_wait(&spa->spa_evicting_os_cv, &spa->spa_evicting_os_lock);
1726 mutex_exit(&spa->spa_evicting_os_lock);
1728 dmu_buf_user_evict_wait();
1732 spa_max_replication(spa_t *spa)
1735 * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1736 * handle BPs with more than one DVA allocated. Set our max
1737 * replication level accordingly.
1739 if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1740 return (1);
1741 return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1745 spa_prev_software_version(spa_t *spa)
1747 return (spa->spa_prev_software_version);
1750 uint64_t
1751 spa_deadman_synctime(spa_t *spa)
1753 return (spa->spa_deadman_synctime);
1756 uint64_t
1757 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
1759 uint64_t asize = DVA_GET_ASIZE(dva);
1760 uint64_t dsize = asize;
1762 ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1764 if (asize != 0 && spa->spa_deflate) {
1765 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
1766 dsize = (asize >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio;
1769 return (dsize);
1772 uint64_t
1773 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
1775 uint64_t dsize = 0;
1777 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
1778 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1780 return (dsize);
1783 uint64_t
1784 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
1786 uint64_t dsize = 0;
1788 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1790 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
1791 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1793 spa_config_exit(spa, SCL_VDEV, FTAG);
1795 return (dsize);
1799 * ==========================================================================
1800 * Initialization and Termination
1801 * ==========================================================================
1804 static int
1805 spa_name_compare(const void *a1, const void *a2)
1807 const spa_t *s1 = a1;
1808 const spa_t *s2 = a2;
1809 int s;
1811 s = strcmp(s1->spa_name, s2->spa_name);
1812 if (s > 0)
1813 return (1);
1814 if (s < 0)
1815 return (-1);
1816 return (0);
1820 spa_busy(void)
1822 return (spa_active_count);
1825 void
1826 spa_boot_init()
1828 spa_config_load();
1831 void
1832 spa_init(int mode)
1834 mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
1835 mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
1836 mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
1837 cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
1839 avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
1840 offsetof(spa_t, spa_avl));
1842 avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
1843 offsetof(spa_aux_t, aux_avl));
1845 avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
1846 offsetof(spa_aux_t, aux_avl));
1848 spa_mode_global = mode;
1850 #ifdef _KERNEL
1851 spa_arch_init();
1852 #else
1853 if (spa_mode_global != FREAD && dprintf_find_string("watch")) {
1854 arc_procfd = open("/proc/self/ctl", O_WRONLY);
1855 if (arc_procfd == -1) {
1856 perror("could not enable watchpoints: "
1857 "opening /proc/self/ctl failed: ");
1858 } else {
1859 arc_watch = B_TRUE;
1862 #endif
1864 refcount_init();
1865 unique_init();
1866 range_tree_init();
1867 zio_init();
1868 dmu_init();
1869 zil_init();
1870 vdev_cache_stat_init();
1871 zfs_prop_init();
1872 zpool_prop_init();
1873 zpool_feature_init();
1874 spa_config_load();
1875 l2arc_start();
1878 void
1879 spa_fini(void)
1881 l2arc_stop();
1883 spa_evict_all();
1885 vdev_cache_stat_fini();
1886 zil_fini();
1887 dmu_fini();
1888 zio_fini();
1889 range_tree_fini();
1890 unique_fini();
1891 refcount_fini();
1893 avl_destroy(&spa_namespace_avl);
1894 avl_destroy(&spa_spare_avl);
1895 avl_destroy(&spa_l2cache_avl);
1897 cv_destroy(&spa_namespace_cv);
1898 mutex_destroy(&spa_namespace_lock);
1899 mutex_destroy(&spa_spare_lock);
1900 mutex_destroy(&spa_l2cache_lock);
1904 * Return whether this pool has slogs. No locking needed.
1905 * It's not a problem if the wrong answer is returned as it's only for
1906 * performance and not correctness
1908 boolean_t
1909 spa_has_slogs(spa_t *spa)
1911 return (spa->spa_log_class->mc_rotor != NULL);
1914 spa_log_state_t
1915 spa_get_log_state(spa_t *spa)
1917 return (spa->spa_log_state);
1920 void
1921 spa_set_log_state(spa_t *spa, spa_log_state_t state)
1923 spa->spa_log_state = state;
1926 boolean_t
1927 spa_is_root(spa_t *spa)
1929 return (spa->spa_is_root);
1932 boolean_t
1933 spa_writeable(spa_t *spa)
1935 return (!!(spa->spa_mode & FWRITE));
1939 * Returns true if there is a pending sync task in any of the current
1940 * syncing txg, the current quiescing txg, or the current open txg.
1942 boolean_t
1943 spa_has_pending_synctask(spa_t *spa)
1945 return (!txg_all_lists_empty(&spa->spa_dsl_pool->dp_sync_tasks));
1949 spa_mode(spa_t *spa)
1951 return (spa->spa_mode);
1954 uint64_t
1955 spa_bootfs(spa_t *spa)
1957 return (spa->spa_bootfs);
1960 uint64_t
1961 spa_delegation(spa_t *spa)
1963 return (spa->spa_delegation);
1966 objset_t *
1967 spa_meta_objset(spa_t *spa)
1969 return (spa->spa_meta_objset);
1972 enum zio_checksum
1973 spa_dedup_checksum(spa_t *spa)
1975 return (spa->spa_dedup_checksum);
1979 * Reset pool scan stat per scan pass (or reboot).
1981 void
1982 spa_scan_stat_init(spa_t *spa)
1984 /* data not stored on disk */
1985 spa->spa_scan_pass_start = gethrestime_sec();
1986 spa->spa_scan_pass_exam = 0;
1987 vdev_scan_stat_init(spa->spa_root_vdev);
1991 * Get scan stats for zpool status reports
1994 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
1996 dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
1998 if (scn == NULL || scn->scn_phys.scn_func == POOL_SCAN_NONE)
1999 return (SET_ERROR(ENOENT));
2000 bzero(ps, sizeof (pool_scan_stat_t));
2002 /* data stored on disk */
2003 ps->pss_func = scn->scn_phys.scn_func;
2004 ps->pss_start_time = scn->scn_phys.scn_start_time;
2005 ps->pss_end_time = scn->scn_phys.scn_end_time;
2006 ps->pss_to_examine = scn->scn_phys.scn_to_examine;
2007 ps->pss_examined = scn->scn_phys.scn_examined;
2008 ps->pss_to_process = scn->scn_phys.scn_to_process;
2009 ps->pss_processed = scn->scn_phys.scn_processed;
2010 ps->pss_errors = scn->scn_phys.scn_errors;
2011 ps->pss_state = scn->scn_phys.scn_state;
2013 /* data not stored on disk */
2014 ps->pss_pass_start = spa->spa_scan_pass_start;
2015 ps->pss_pass_exam = spa->spa_scan_pass_exam;
2017 return (0);
2020 boolean_t
2021 spa_debug_enabled(spa_t *spa)
2023 return (spa->spa_debug);
2027 spa_maxblocksize(spa_t *spa)
2029 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
2030 return (SPA_MAXBLOCKSIZE);
2031 else
2032 return (SPA_OLD_MAXBLOCKSIZE);