]> git.proxmox.com Git - mirror_zfs.git/blob - module/zfs/spa_misc.c
Improve ZFS objset sync parallelism
[mirror_zfs.git] / module / zfs / spa_misc.c
1 /*
2 * CDDL HEADER START
3 *
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.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or https://opensource.org/licenses/CDDL-1.0.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
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]
18 *
19 * CDDL HEADER END
20 */
21 /*
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2019 by Delphix. All rights reserved.
24 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
26 * Copyright 2013 Saso Kiselkov. All rights reserved.
27 * Copyright (c) 2017 Datto Inc.
28 * Copyright (c) 2017, Intel Corporation.
29 * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
30 * Copyright (c) 2023, Klara Inc.
31 */
32
33 #include <sys/zfs_context.h>
34 #include <sys/zfs_chksum.h>
35 #include <sys/spa_impl.h>
36 #include <sys/zio.h>
37 #include <sys/zio_checksum.h>
38 #include <sys/zio_compress.h>
39 #include <sys/dmu.h>
40 #include <sys/dmu_tx.h>
41 #include <sys/zap.h>
42 #include <sys/zil.h>
43 #include <sys/vdev_impl.h>
44 #include <sys/vdev_initialize.h>
45 #include <sys/vdev_trim.h>
46 #include <sys/vdev_file.h>
47 #include <sys/vdev_raidz.h>
48 #include <sys/metaslab.h>
49 #include <sys/uberblock_impl.h>
50 #include <sys/txg.h>
51 #include <sys/avl.h>
52 #include <sys/unique.h>
53 #include <sys/dsl_pool.h>
54 #include <sys/dsl_dir.h>
55 #include <sys/dsl_prop.h>
56 #include <sys/fm/util.h>
57 #include <sys/dsl_scan.h>
58 #include <sys/fs/zfs.h>
59 #include <sys/metaslab_impl.h>
60 #include <sys/arc.h>
61 #include <sys/brt.h>
62 #include <sys/ddt.h>
63 #include <sys/kstat.h>
64 #include "zfs_prop.h"
65 #include <sys/btree.h>
66 #include <sys/zfeature.h>
67 #include <sys/qat.h>
68 #include <sys/zstd/zstd.h>
69
70 /*
71 * SPA locking
72 *
73 * There are three basic locks for managing spa_t structures:
74 *
75 * spa_namespace_lock (global mutex)
76 *
77 * This lock must be acquired to do any of the following:
78 *
79 * - Lookup a spa_t by name
80 * - Add or remove a spa_t from the namespace
81 * - Increase spa_refcount from non-zero
82 * - Check if spa_refcount is zero
83 * - Rename a spa_t
84 * - add/remove/attach/detach devices
85 * - Held for the duration of create/destroy/import/export
86 *
87 * It does not need to handle recursion. A create or destroy may
88 * reference objects (files or zvols) in other pools, but by
89 * definition they must have an existing reference, and will never need
90 * to lookup a spa_t by name.
91 *
92 * spa_refcount (per-spa zfs_refcount_t protected by mutex)
93 *
94 * This reference count keep track of any active users of the spa_t. The
95 * spa_t cannot be destroyed or freed while this is non-zero. Internally,
96 * the refcount is never really 'zero' - opening a pool implicitly keeps
97 * some references in the DMU. Internally we check against spa_minref, but
98 * present the image of a zero/non-zero value to consumers.
99 *
100 * spa_config_lock[] (per-spa array of rwlocks)
101 *
102 * This protects the spa_t from config changes, and must be held in
103 * the following circumstances:
104 *
105 * - RW_READER to perform I/O to the spa
106 * - RW_WRITER to change the vdev config
107 *
108 * The locking order is fairly straightforward:
109 *
110 * spa_namespace_lock -> spa_refcount
111 *
112 * The namespace lock must be acquired to increase the refcount from 0
113 * or to check if it is zero.
114 *
115 * spa_refcount -> spa_config_lock[]
116 *
117 * There must be at least one valid reference on the spa_t to acquire
118 * the config lock.
119 *
120 * spa_namespace_lock -> spa_config_lock[]
121 *
122 * The namespace lock must always be taken before the config lock.
123 *
124 *
125 * The spa_namespace_lock can be acquired directly and is globally visible.
126 *
127 * The namespace is manipulated using the following functions, all of which
128 * require the spa_namespace_lock to be held.
129 *
130 * spa_lookup() Lookup a spa_t by name.
131 *
132 * spa_add() Create a new spa_t in the namespace.
133 *
134 * spa_remove() Remove a spa_t from the namespace. This also
135 * frees up any memory associated with the spa_t.
136 *
137 * spa_next() Returns the next spa_t in the system, or the
138 * first if NULL is passed.
139 *
140 * spa_evict_all() Shutdown and remove all spa_t structures in
141 * the system.
142 *
143 * spa_guid_exists() Determine whether a pool/device guid exists.
144 *
145 * The spa_refcount is manipulated using the following functions:
146 *
147 * spa_open_ref() Adds a reference to the given spa_t. Must be
148 * called with spa_namespace_lock held if the
149 * refcount is currently zero.
150 *
151 * spa_close() Remove a reference from the spa_t. This will
152 * not free the spa_t or remove it from the
153 * namespace. No locking is required.
154 *
155 * spa_refcount_zero() Returns true if the refcount is currently
156 * zero. Must be called with spa_namespace_lock
157 * held.
158 *
159 * The spa_config_lock[] is an array of rwlocks, ordered as follows:
160 * SCL_CONFIG > SCL_STATE > SCL_ALLOC > SCL_ZIO > SCL_FREE > SCL_VDEV.
161 * spa_config_lock[] is manipulated with spa_config_{enter,exit,held}().
162 *
163 * To read the configuration, it suffices to hold one of these locks as reader.
164 * To modify the configuration, you must hold all locks as writer. To modify
165 * vdev state without altering the vdev tree's topology (e.g. online/offline),
166 * you must hold SCL_STATE and SCL_ZIO as writer.
167 *
168 * We use these distinct config locks to avoid recursive lock entry.
169 * For example, spa_sync() (which holds SCL_CONFIG as reader) induces
170 * block allocations (SCL_ALLOC), which may require reading space maps
171 * from disk (dmu_read() -> zio_read() -> SCL_ZIO).
172 *
173 * The spa config locks cannot be normal rwlocks because we need the
174 * ability to hand off ownership. For example, SCL_ZIO is acquired
175 * by the issuing thread and later released by an interrupt thread.
176 * They do, however, obey the usual write-wanted semantics to prevent
177 * writer (i.e. system administrator) starvation.
178 *
179 * The lock acquisition rules are as follows:
180 *
181 * SCL_CONFIG
182 * Protects changes to the vdev tree topology, such as vdev
183 * add/remove/attach/detach. Protects the dirty config list
184 * (spa_config_dirty_list) and the set of spares and l2arc devices.
185 *
186 * SCL_STATE
187 * Protects changes to pool state and vdev state, such as vdev
188 * online/offline/fault/degrade/clear. Protects the dirty state list
189 * (spa_state_dirty_list) and global pool state (spa_state).
190 *
191 * SCL_ALLOC
192 * Protects changes to metaslab groups and classes.
193 * Held as reader by metaslab_alloc() and metaslab_claim().
194 *
195 * SCL_ZIO
196 * Held by bp-level zios (those which have no io_vd upon entry)
197 * to prevent changes to the vdev tree. The bp-level zio implicitly
198 * protects all of its vdev child zios, which do not hold SCL_ZIO.
199 *
200 * SCL_FREE
201 * Protects changes to metaslab groups and classes.
202 * Held as reader by metaslab_free(). SCL_FREE is distinct from
203 * SCL_ALLOC, and lower than SCL_ZIO, so that we can safely free
204 * blocks in zio_done() while another i/o that holds either
205 * SCL_ALLOC or SCL_ZIO is waiting for this i/o to complete.
206 *
207 * SCL_VDEV
208 * Held as reader to prevent changes to the vdev tree during trivial
209 * inquiries such as bp_get_dsize(). SCL_VDEV is distinct from the
210 * other locks, and lower than all of them, to ensure that it's safe
211 * to acquire regardless of caller context.
212 *
213 * In addition, the following rules apply:
214 *
215 * (a) spa_props_lock protects pool properties, spa_config and spa_config_list.
216 * The lock ordering is SCL_CONFIG > spa_props_lock.
217 *
218 * (b) I/O operations on leaf vdevs. For any zio operation that takes
219 * an explicit vdev_t argument -- such as zio_ioctl(), zio_read_phys(),
220 * or zio_write_phys() -- the caller must ensure that the config cannot
221 * cannot change in the interim, and that the vdev cannot be reopened.
222 * SCL_STATE as reader suffices for both.
223 *
224 * The vdev configuration is protected by spa_vdev_enter() / spa_vdev_exit().
225 *
226 * spa_vdev_enter() Acquire the namespace lock and the config lock
227 * for writing.
228 *
229 * spa_vdev_exit() Release the config lock, wait for all I/O
230 * to complete, sync the updated configs to the
231 * cache, and release the namespace lock.
232 *
233 * vdev state is protected by spa_vdev_state_enter() / spa_vdev_state_exit().
234 * Like spa_vdev_enter/exit, these are convenience wrappers -- the actual
235 * locking is, always, based on spa_namespace_lock and spa_config_lock[].
236 */
237
238 static avl_tree_t spa_namespace_avl;
239 kmutex_t spa_namespace_lock;
240 static kcondvar_t spa_namespace_cv;
241 static const int spa_max_replication_override = SPA_DVAS_PER_BP;
242
243 static kmutex_t spa_spare_lock;
244 static avl_tree_t spa_spare_avl;
245 static kmutex_t spa_l2cache_lock;
246 static avl_tree_t spa_l2cache_avl;
247
248 spa_mode_t spa_mode_global = SPA_MODE_UNINIT;
249
250 #ifdef ZFS_DEBUG
251 /*
252 * Everything except dprintf, set_error, spa, and indirect_remap is on
253 * by default in debug builds.
254 */
255 int zfs_flags = ~(ZFS_DEBUG_DPRINTF | ZFS_DEBUG_SET_ERROR |
256 ZFS_DEBUG_INDIRECT_REMAP);
257 #else
258 int zfs_flags = 0;
259 #endif
260
261 /*
262 * zfs_recover can be set to nonzero to attempt to recover from
263 * otherwise-fatal errors, typically caused by on-disk corruption. When
264 * set, calls to zfs_panic_recover() will turn into warning messages.
265 * This should only be used as a last resort, as it typically results
266 * in leaked space, or worse.
267 */
268 int zfs_recover = B_FALSE;
269
270 /*
271 * If destroy encounters an EIO while reading metadata (e.g. indirect
272 * blocks), space referenced by the missing metadata can not be freed.
273 * Normally this causes the background destroy to become "stalled", as
274 * it is unable to make forward progress. While in this stalled state,
275 * all remaining space to free from the error-encountering filesystem is
276 * "temporarily leaked". Set this flag to cause it to ignore the EIO,
277 * permanently leak the space from indirect blocks that can not be read,
278 * and continue to free everything else that it can.
279 *
280 * The default, "stalling" behavior is useful if the storage partially
281 * fails (i.e. some but not all i/os fail), and then later recovers. In
282 * this case, we will be able to continue pool operations while it is
283 * partially failed, and when it recovers, we can continue to free the
284 * space, with no leaks. However, note that this case is actually
285 * fairly rare.
286 *
287 * Typically pools either (a) fail completely (but perhaps temporarily,
288 * e.g. a top-level vdev going offline), or (b) have localized,
289 * permanent errors (e.g. disk returns the wrong data due to bit flip or
290 * firmware bug). In case (a), this setting does not matter because the
291 * pool will be suspended and the sync thread will not be able to make
292 * forward progress regardless. In case (b), because the error is
293 * permanent, the best we can do is leak the minimum amount of space,
294 * which is what setting this flag will do. Therefore, it is reasonable
295 * for this flag to normally be set, but we chose the more conservative
296 * approach of not setting it, so that there is no possibility of
297 * leaking space in the "partial temporary" failure case.
298 */
299 int zfs_free_leak_on_eio = B_FALSE;
300
301 /*
302 * Expiration time in milliseconds. This value has two meanings. First it is
303 * used to determine when the spa_deadman() logic should fire. By default the
304 * spa_deadman() will fire if spa_sync() has not completed in 600 seconds.
305 * Secondly, the value determines if an I/O is considered "hung". Any I/O that
306 * has not completed in zfs_deadman_synctime_ms is considered "hung" resulting
307 * in one of three behaviors controlled by zfs_deadman_failmode.
308 */
309 uint64_t zfs_deadman_synctime_ms = 600000UL; /* 10 min. */
310
311 /*
312 * This value controls the maximum amount of time zio_wait() will block for an
313 * outstanding IO. By default this is 300 seconds at which point the "hung"
314 * behavior will be applied as described for zfs_deadman_synctime_ms.
315 */
316 uint64_t zfs_deadman_ziotime_ms = 300000UL; /* 5 min. */
317
318 /*
319 * Check time in milliseconds. This defines the frequency at which we check
320 * for hung I/O.
321 */
322 uint64_t zfs_deadman_checktime_ms = 60000UL; /* 1 min. */
323
324 /*
325 * By default the deadman is enabled.
326 */
327 int zfs_deadman_enabled = B_TRUE;
328
329 /*
330 * Controls the behavior of the deadman when it detects a "hung" I/O.
331 * Valid values are zfs_deadman_failmode=<wait|continue|panic>.
332 *
333 * wait - Wait for the "hung" I/O (default)
334 * continue - Attempt to recover from a "hung" I/O
335 * panic - Panic the system
336 */
337 const char *zfs_deadman_failmode = "wait";
338
339 /*
340 * The worst case is single-sector max-parity RAID-Z blocks, in which
341 * case the space requirement is exactly (VDEV_RAIDZ_MAXPARITY + 1)
342 * times the size; so just assume that. Add to this the fact that
343 * we can have up to 3 DVAs per bp, and one more factor of 2 because
344 * the block may be dittoed with up to 3 DVAs by ddt_sync(). All together,
345 * the worst case is:
346 * (VDEV_RAIDZ_MAXPARITY + 1) * SPA_DVAS_PER_BP * 2 == 24
347 */
348 uint_t spa_asize_inflation = 24;
349
350 /*
351 * Normally, we don't allow the last 3.2% (1/(2^spa_slop_shift)) of space in
352 * the pool to be consumed (bounded by spa_max_slop). This ensures that we
353 * don't run the pool completely out of space, due to unaccounted changes (e.g.
354 * to the MOS). It also limits the worst-case time to allocate space. If we
355 * have less than this amount of free space, most ZPL operations (e.g. write,
356 * create) will return ENOSPC. The ZIL metaslabs (spa_embedded_log_class) are
357 * also part of this 3.2% of space which can't be consumed by normal writes;
358 * the slop space "proper" (spa_get_slop_space()) is decreased by the embedded
359 * log space.
360 *
361 * Certain operations (e.g. file removal, most administrative actions) can
362 * use half the slop space. They will only return ENOSPC if less than half
363 * the slop space is free. Typically, once the pool has less than the slop
364 * space free, the user will use these operations to free up space in the pool.
365 * These are the operations that call dsl_pool_adjustedsize() with the netfree
366 * argument set to TRUE.
367 *
368 * Operations that are almost guaranteed to free up space in the absence of
369 * a pool checkpoint can use up to three quarters of the slop space
370 * (e.g zfs destroy).
371 *
372 * A very restricted set of operations are always permitted, regardless of
373 * the amount of free space. These are the operations that call
374 * dsl_sync_task(ZFS_SPACE_CHECK_NONE). If these operations result in a net
375 * increase in the amount of space used, it is possible to run the pool
376 * completely out of space, causing it to be permanently read-only.
377 *
378 * Note that on very small pools, the slop space will be larger than
379 * 3.2%, in an effort to have it be at least spa_min_slop (128MB),
380 * but we never allow it to be more than half the pool size.
381 *
382 * Further, on very large pools, the slop space will be smaller than
383 * 3.2%, to avoid reserving much more space than we actually need; bounded
384 * by spa_max_slop (128GB).
385 *
386 * See also the comments in zfs_space_check_t.
387 */
388 uint_t spa_slop_shift = 5;
389 static const uint64_t spa_min_slop = 128ULL * 1024 * 1024;
390 static const uint64_t spa_max_slop = 128ULL * 1024 * 1024 * 1024;
391
392 /*
393 * Number of allocators to use, per spa instance
394 */
395 static int spa_num_allocators = 4;
396
397 /*
398 * Spa active allocator.
399 * Valid values are zfs_active_allocator=<dynamic|cursor|new-dynamic>.
400 */
401 const char *zfs_active_allocator = "dynamic";
402
403 void
404 spa_load_failed(spa_t *spa, const char *fmt, ...)
405 {
406 va_list adx;
407 char buf[256];
408
409 va_start(adx, fmt);
410 (void) vsnprintf(buf, sizeof (buf), fmt, adx);
411 va_end(adx);
412
413 zfs_dbgmsg("spa_load(%s, config %s): FAILED: %s", spa->spa_name,
414 spa->spa_trust_config ? "trusted" : "untrusted", buf);
415 }
416
417 void
418 spa_load_note(spa_t *spa, const char *fmt, ...)
419 {
420 va_list adx;
421 char buf[256];
422
423 va_start(adx, fmt);
424 (void) vsnprintf(buf, sizeof (buf), fmt, adx);
425 va_end(adx);
426
427 zfs_dbgmsg("spa_load(%s, config %s): %s", spa->spa_name,
428 spa->spa_trust_config ? "trusted" : "untrusted", buf);
429 }
430
431 /*
432 * By default dedup and user data indirects land in the special class
433 */
434 static int zfs_ddt_data_is_special = B_TRUE;
435 static int zfs_user_indirect_is_special = B_TRUE;
436
437 /*
438 * The percentage of special class final space reserved for metadata only.
439 * Once we allocate 100 - zfs_special_class_metadata_reserve_pct we only
440 * let metadata into the class.
441 */
442 static uint_t zfs_special_class_metadata_reserve_pct = 25;
443
444 /*
445 * ==========================================================================
446 * SPA config locking
447 * ==========================================================================
448 */
449 static void
450 spa_config_lock_init(spa_t *spa)
451 {
452 for (int i = 0; i < SCL_LOCKS; i++) {
453 spa_config_lock_t *scl = &spa->spa_config_lock[i];
454 mutex_init(&scl->scl_lock, NULL, MUTEX_DEFAULT, NULL);
455 cv_init(&scl->scl_cv, NULL, CV_DEFAULT, NULL);
456 scl->scl_writer = NULL;
457 scl->scl_write_wanted = 0;
458 scl->scl_count = 0;
459 }
460 }
461
462 static void
463 spa_config_lock_destroy(spa_t *spa)
464 {
465 for (int i = 0; i < SCL_LOCKS; i++) {
466 spa_config_lock_t *scl = &spa->spa_config_lock[i];
467 mutex_destroy(&scl->scl_lock);
468 cv_destroy(&scl->scl_cv);
469 ASSERT(scl->scl_writer == NULL);
470 ASSERT(scl->scl_write_wanted == 0);
471 ASSERT(scl->scl_count == 0);
472 }
473 }
474
475 int
476 spa_config_tryenter(spa_t *spa, int locks, const void *tag, krw_t rw)
477 {
478 for (int i = 0; i < SCL_LOCKS; i++) {
479 spa_config_lock_t *scl = &spa->spa_config_lock[i];
480 if (!(locks & (1 << i)))
481 continue;
482 mutex_enter(&scl->scl_lock);
483 if (rw == RW_READER) {
484 if (scl->scl_writer || scl->scl_write_wanted) {
485 mutex_exit(&scl->scl_lock);
486 spa_config_exit(spa, locks & ((1 << i) - 1),
487 tag);
488 return (0);
489 }
490 } else {
491 ASSERT(scl->scl_writer != curthread);
492 if (scl->scl_count != 0) {
493 mutex_exit(&scl->scl_lock);
494 spa_config_exit(spa, locks & ((1 << i) - 1),
495 tag);
496 return (0);
497 }
498 scl->scl_writer = curthread;
499 }
500 scl->scl_count++;
501 mutex_exit(&scl->scl_lock);
502 }
503 return (1);
504 }
505
506 static void
507 spa_config_enter_impl(spa_t *spa, int locks, const void *tag, krw_t rw,
508 int mmp_flag)
509 {
510 (void) tag;
511 int wlocks_held = 0;
512
513 ASSERT3U(SCL_LOCKS, <, sizeof (wlocks_held) * NBBY);
514
515 for (int i = 0; i < SCL_LOCKS; i++) {
516 spa_config_lock_t *scl = &spa->spa_config_lock[i];
517 if (scl->scl_writer == curthread)
518 wlocks_held |= (1 << i);
519 if (!(locks & (1 << i)))
520 continue;
521 mutex_enter(&scl->scl_lock);
522 if (rw == RW_READER) {
523 while (scl->scl_writer ||
524 (!mmp_flag && scl->scl_write_wanted)) {
525 cv_wait(&scl->scl_cv, &scl->scl_lock);
526 }
527 } else {
528 ASSERT(scl->scl_writer != curthread);
529 while (scl->scl_count != 0) {
530 scl->scl_write_wanted++;
531 cv_wait(&scl->scl_cv, &scl->scl_lock);
532 scl->scl_write_wanted--;
533 }
534 scl->scl_writer = curthread;
535 }
536 scl->scl_count++;
537 mutex_exit(&scl->scl_lock);
538 }
539 ASSERT3U(wlocks_held, <=, locks);
540 }
541
542 void
543 spa_config_enter(spa_t *spa, int locks, const void *tag, krw_t rw)
544 {
545 spa_config_enter_impl(spa, locks, tag, rw, 0);
546 }
547
548 /*
549 * The spa_config_enter_mmp() allows the mmp thread to cut in front of
550 * outstanding write lock requests. This is needed since the mmp updates are
551 * time sensitive and failure to service them promptly will result in a
552 * suspended pool. This pool suspension has been seen in practice when there is
553 * a single disk in a pool that is responding slowly and presumably about to
554 * fail.
555 */
556
557 void
558 spa_config_enter_mmp(spa_t *spa, int locks, const void *tag, krw_t rw)
559 {
560 spa_config_enter_impl(spa, locks, tag, rw, 1);
561 }
562
563 void
564 spa_config_exit(spa_t *spa, int locks, const void *tag)
565 {
566 (void) tag;
567 for (int i = SCL_LOCKS - 1; i >= 0; i--) {
568 spa_config_lock_t *scl = &spa->spa_config_lock[i];
569 if (!(locks & (1 << i)))
570 continue;
571 mutex_enter(&scl->scl_lock);
572 ASSERT(scl->scl_count > 0);
573 if (--scl->scl_count == 0) {
574 ASSERT(scl->scl_writer == NULL ||
575 scl->scl_writer == curthread);
576 scl->scl_writer = NULL; /* OK in either case */
577 cv_broadcast(&scl->scl_cv);
578 }
579 mutex_exit(&scl->scl_lock);
580 }
581 }
582
583 int
584 spa_config_held(spa_t *spa, int locks, krw_t rw)
585 {
586 int locks_held = 0;
587
588 for (int i = 0; i < SCL_LOCKS; i++) {
589 spa_config_lock_t *scl = &spa->spa_config_lock[i];
590 if (!(locks & (1 << i)))
591 continue;
592 if ((rw == RW_READER && scl->scl_count != 0) ||
593 (rw == RW_WRITER && scl->scl_writer == curthread))
594 locks_held |= 1 << i;
595 }
596
597 return (locks_held);
598 }
599
600 /*
601 * ==========================================================================
602 * SPA namespace functions
603 * ==========================================================================
604 */
605
606 /*
607 * Lookup the named spa_t in the AVL tree. The spa_namespace_lock must be held.
608 * Returns NULL if no matching spa_t is found.
609 */
610 spa_t *
611 spa_lookup(const char *name)
612 {
613 static spa_t search; /* spa_t is large; don't allocate on stack */
614 spa_t *spa;
615 avl_index_t where;
616 char *cp;
617
618 ASSERT(MUTEX_HELD(&spa_namespace_lock));
619
620 (void) strlcpy(search.spa_name, name, sizeof (search.spa_name));
621
622 /*
623 * If it's a full dataset name, figure out the pool name and
624 * just use that.
625 */
626 cp = strpbrk(search.spa_name, "/@#");
627 if (cp != NULL)
628 *cp = '\0';
629
630 spa = avl_find(&spa_namespace_avl, &search, &where);
631
632 return (spa);
633 }
634
635 /*
636 * Fires when spa_sync has not completed within zfs_deadman_synctime_ms.
637 * If the zfs_deadman_enabled flag is set then it inspects all vdev queues
638 * looking for potentially hung I/Os.
639 */
640 void
641 spa_deadman(void *arg)
642 {
643 spa_t *spa = arg;
644
645 /* Disable the deadman if the pool is suspended. */
646 if (spa_suspended(spa))
647 return;
648
649 zfs_dbgmsg("slow spa_sync: started %llu seconds ago, calls %llu",
650 (gethrtime() - spa->spa_sync_starttime) / NANOSEC,
651 (u_longlong_t)++spa->spa_deadman_calls);
652 if (zfs_deadman_enabled)
653 vdev_deadman(spa->spa_root_vdev, FTAG);
654
655 spa->spa_deadman_tqid = taskq_dispatch_delay(system_delay_taskq,
656 spa_deadman, spa, TQ_SLEEP, ddi_get_lbolt() +
657 MSEC_TO_TICK(zfs_deadman_checktime_ms));
658 }
659
660 static int
661 spa_log_sm_sort_by_txg(const void *va, const void *vb)
662 {
663 const spa_log_sm_t *a = va;
664 const spa_log_sm_t *b = vb;
665
666 return (TREE_CMP(a->sls_txg, b->sls_txg));
667 }
668
669 /*
670 * Create an uninitialized spa_t with the given name. Requires
671 * spa_namespace_lock. The caller must ensure that the spa_t doesn't already
672 * exist by calling spa_lookup() first.
673 */
674 spa_t *
675 spa_add(const char *name, nvlist_t *config, const char *altroot)
676 {
677 spa_t *spa;
678 spa_config_dirent_t *dp;
679
680 ASSERT(MUTEX_HELD(&spa_namespace_lock));
681
682 spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
683
684 mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
685 mutex_init(&spa->spa_errlist_lock, NULL, MUTEX_DEFAULT, NULL);
686 mutex_init(&spa->spa_errlog_lock, NULL, MUTEX_DEFAULT, NULL);
687 mutex_init(&spa->spa_evicting_os_lock, NULL, MUTEX_DEFAULT, NULL);
688 mutex_init(&spa->spa_history_lock, NULL, MUTEX_DEFAULT, NULL);
689 mutex_init(&spa->spa_proc_lock, NULL, MUTEX_DEFAULT, NULL);
690 mutex_init(&spa->spa_props_lock, NULL, MUTEX_DEFAULT, NULL);
691 mutex_init(&spa->spa_cksum_tmpls_lock, NULL, MUTEX_DEFAULT, NULL);
692 mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
693 mutex_init(&spa->spa_suspend_lock, NULL, MUTEX_DEFAULT, NULL);
694 mutex_init(&spa->spa_vdev_top_lock, NULL, MUTEX_DEFAULT, NULL);
695 mutex_init(&spa->spa_feat_stats_lock, NULL, MUTEX_DEFAULT, NULL);
696 mutex_init(&spa->spa_flushed_ms_lock, NULL, MUTEX_DEFAULT, NULL);
697 mutex_init(&spa->spa_activities_lock, NULL, MUTEX_DEFAULT, NULL);
698
699 cv_init(&spa->spa_async_cv, NULL, CV_DEFAULT, NULL);
700 cv_init(&spa->spa_evicting_os_cv, NULL, CV_DEFAULT, NULL);
701 cv_init(&spa->spa_proc_cv, NULL, CV_DEFAULT, NULL);
702 cv_init(&spa->spa_scrub_io_cv, NULL, CV_DEFAULT, NULL);
703 cv_init(&spa->spa_suspend_cv, NULL, CV_DEFAULT, NULL);
704 cv_init(&spa->spa_activities_cv, NULL, CV_DEFAULT, NULL);
705 cv_init(&spa->spa_waiters_cv, NULL, CV_DEFAULT, NULL);
706
707 for (int t = 0; t < TXG_SIZE; t++)
708 bplist_create(&spa->spa_free_bplist[t]);
709
710 (void) strlcpy(spa->spa_name, name, sizeof (spa->spa_name));
711 spa->spa_state = POOL_STATE_UNINITIALIZED;
712 spa->spa_freeze_txg = UINT64_MAX;
713 spa->spa_final_txg = UINT64_MAX;
714 spa->spa_load_max_txg = UINT64_MAX;
715 spa->spa_proc = &p0;
716 spa->spa_proc_state = SPA_PROC_NONE;
717 spa->spa_trust_config = B_TRUE;
718 spa->spa_hostid = zone_get_hostid(NULL);
719
720 spa->spa_deadman_synctime = MSEC2NSEC(zfs_deadman_synctime_ms);
721 spa->spa_deadman_ziotime = MSEC2NSEC(zfs_deadman_ziotime_ms);
722 spa_set_deadman_failmode(spa, zfs_deadman_failmode);
723 spa_set_allocator(spa, zfs_active_allocator);
724
725 zfs_refcount_create(&spa->spa_refcount);
726 spa_config_lock_init(spa);
727 spa_stats_init(spa);
728
729 avl_add(&spa_namespace_avl, spa);
730
731 /*
732 * Set the alternate root, if there is one.
733 */
734 if (altroot)
735 spa->spa_root = spa_strdup(altroot);
736
737 /* Do not allow more allocators than CPUs. */
738 spa->spa_alloc_count = MIN(MAX(spa_num_allocators, 1), boot_ncpus);
739
740 spa->spa_allocs = kmem_zalloc(spa->spa_alloc_count *
741 sizeof (spa_alloc_t), KM_SLEEP);
742 for (int i = 0; i < spa->spa_alloc_count; i++) {
743 mutex_init(&spa->spa_allocs[i].spaa_lock, NULL, MUTEX_DEFAULT,
744 NULL);
745 avl_create(&spa->spa_allocs[i].spaa_tree, zio_bookmark_compare,
746 sizeof (zio_t), offsetof(zio_t, io_queue_node.a));
747 }
748
749 avl_create(&spa->spa_metaslabs_by_flushed, metaslab_sort_by_flushed,
750 sizeof (metaslab_t), offsetof(metaslab_t, ms_spa_txg_node));
751 avl_create(&spa->spa_sm_logs_by_txg, spa_log_sm_sort_by_txg,
752 sizeof (spa_log_sm_t), offsetof(spa_log_sm_t, sls_node));
753 list_create(&spa->spa_log_summary, sizeof (log_summary_entry_t),
754 offsetof(log_summary_entry_t, lse_node));
755
756 /*
757 * Every pool starts with the default cachefile
758 */
759 list_create(&spa->spa_config_list, sizeof (spa_config_dirent_t),
760 offsetof(spa_config_dirent_t, scd_link));
761
762 dp = kmem_zalloc(sizeof (spa_config_dirent_t), KM_SLEEP);
763 dp->scd_path = altroot ? NULL : spa_strdup(spa_config_path);
764 list_insert_head(&spa->spa_config_list, dp);
765
766 VERIFY(nvlist_alloc(&spa->spa_load_info, NV_UNIQUE_NAME,
767 KM_SLEEP) == 0);
768
769 if (config != NULL) {
770 nvlist_t *features;
771
772 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_FEATURES_FOR_READ,
773 &features) == 0) {
774 VERIFY(nvlist_dup(features, &spa->spa_label_features,
775 0) == 0);
776 }
777
778 VERIFY(nvlist_dup(config, &spa->spa_config, 0) == 0);
779 }
780
781 if (spa->spa_label_features == NULL) {
782 VERIFY(nvlist_alloc(&spa->spa_label_features, NV_UNIQUE_NAME,
783 KM_SLEEP) == 0);
784 }
785
786 spa->spa_min_ashift = INT_MAX;
787 spa->spa_max_ashift = 0;
788 spa->spa_min_alloc = INT_MAX;
789 spa->spa_gcd_alloc = INT_MAX;
790
791 /* Reset cached value */
792 spa->spa_dedup_dspace = ~0ULL;
793
794 /*
795 * As a pool is being created, treat all features as disabled by
796 * setting SPA_FEATURE_DISABLED for all entries in the feature
797 * refcount cache.
798 */
799 for (int i = 0; i < SPA_FEATURES; i++) {
800 spa->spa_feat_refcount_cache[i] = SPA_FEATURE_DISABLED;
801 }
802
803 list_create(&spa->spa_leaf_list, sizeof (vdev_t),
804 offsetof(vdev_t, vdev_leaf_node));
805
806 return (spa);
807 }
808
809 /*
810 * Removes a spa_t from the namespace, freeing up any memory used. Requires
811 * spa_namespace_lock. This is called only after the spa_t has been closed and
812 * deactivated.
813 */
814 void
815 spa_remove(spa_t *spa)
816 {
817 spa_config_dirent_t *dp;
818
819 ASSERT(MUTEX_HELD(&spa_namespace_lock));
820 ASSERT(spa_state(spa) == POOL_STATE_UNINITIALIZED);
821 ASSERT3U(zfs_refcount_count(&spa->spa_refcount), ==, 0);
822 ASSERT0(spa->spa_waiters);
823
824 nvlist_free(spa->spa_config_splitting);
825
826 avl_remove(&spa_namespace_avl, spa);
827 cv_broadcast(&spa_namespace_cv);
828
829 if (spa->spa_root)
830 spa_strfree(spa->spa_root);
831
832 while ((dp = list_remove_head(&spa->spa_config_list)) != NULL) {
833 if (dp->scd_path != NULL)
834 spa_strfree(dp->scd_path);
835 kmem_free(dp, sizeof (spa_config_dirent_t));
836 }
837
838 for (int i = 0; i < spa->spa_alloc_count; i++) {
839 avl_destroy(&spa->spa_allocs[i].spaa_tree);
840 mutex_destroy(&spa->spa_allocs[i].spaa_lock);
841 }
842 kmem_free(spa->spa_allocs, spa->spa_alloc_count *
843 sizeof (spa_alloc_t));
844
845 avl_destroy(&spa->spa_metaslabs_by_flushed);
846 avl_destroy(&spa->spa_sm_logs_by_txg);
847 list_destroy(&spa->spa_log_summary);
848 list_destroy(&spa->spa_config_list);
849 list_destroy(&spa->spa_leaf_list);
850
851 nvlist_free(spa->spa_label_features);
852 nvlist_free(spa->spa_load_info);
853 nvlist_free(spa->spa_feat_stats);
854 spa_config_set(spa, NULL);
855
856 zfs_refcount_destroy(&spa->spa_refcount);
857
858 spa_stats_destroy(spa);
859 spa_config_lock_destroy(spa);
860
861 for (int t = 0; t < TXG_SIZE; t++)
862 bplist_destroy(&spa->spa_free_bplist[t]);
863
864 zio_checksum_templates_free(spa);
865
866 cv_destroy(&spa->spa_async_cv);
867 cv_destroy(&spa->spa_evicting_os_cv);
868 cv_destroy(&spa->spa_proc_cv);
869 cv_destroy(&spa->spa_scrub_io_cv);
870 cv_destroy(&spa->spa_suspend_cv);
871 cv_destroy(&spa->spa_activities_cv);
872 cv_destroy(&spa->spa_waiters_cv);
873
874 mutex_destroy(&spa->spa_flushed_ms_lock);
875 mutex_destroy(&spa->spa_async_lock);
876 mutex_destroy(&spa->spa_errlist_lock);
877 mutex_destroy(&spa->spa_errlog_lock);
878 mutex_destroy(&spa->spa_evicting_os_lock);
879 mutex_destroy(&spa->spa_history_lock);
880 mutex_destroy(&spa->spa_proc_lock);
881 mutex_destroy(&spa->spa_props_lock);
882 mutex_destroy(&spa->spa_cksum_tmpls_lock);
883 mutex_destroy(&spa->spa_scrub_lock);
884 mutex_destroy(&spa->spa_suspend_lock);
885 mutex_destroy(&spa->spa_vdev_top_lock);
886 mutex_destroy(&spa->spa_feat_stats_lock);
887 mutex_destroy(&spa->spa_activities_lock);
888
889 kmem_free(spa, sizeof (spa_t));
890 }
891
892 /*
893 * Given a pool, return the next pool in the namespace, or NULL if there is
894 * none. If 'prev' is NULL, return the first pool.
895 */
896 spa_t *
897 spa_next(spa_t *prev)
898 {
899 ASSERT(MUTEX_HELD(&spa_namespace_lock));
900
901 if (prev)
902 return (AVL_NEXT(&spa_namespace_avl, prev));
903 else
904 return (avl_first(&spa_namespace_avl));
905 }
906
907 /*
908 * ==========================================================================
909 * SPA refcount functions
910 * ==========================================================================
911 */
912
913 /*
914 * Add a reference to the given spa_t. Must have at least one reference, or
915 * have the namespace lock held.
916 */
917 void
918 spa_open_ref(spa_t *spa, const void *tag)
919 {
920 ASSERT(zfs_refcount_count(&spa->spa_refcount) >= spa->spa_minref ||
921 MUTEX_HELD(&spa_namespace_lock));
922 (void) zfs_refcount_add(&spa->spa_refcount, tag);
923 }
924
925 /*
926 * Remove a reference to the given spa_t. Must have at least one reference, or
927 * have the namespace lock held.
928 */
929 void
930 spa_close(spa_t *spa, const void *tag)
931 {
932 ASSERT(zfs_refcount_count(&spa->spa_refcount) > spa->spa_minref ||
933 MUTEX_HELD(&spa_namespace_lock));
934 (void) zfs_refcount_remove(&spa->spa_refcount, tag);
935 }
936
937 /*
938 * Remove a reference to the given spa_t held by a dsl dir that is
939 * being asynchronously released. Async releases occur from a taskq
940 * performing eviction of dsl datasets and dirs. The namespace lock
941 * isn't held and the hold by the object being evicted may contribute to
942 * spa_minref (e.g. dataset or directory released during pool export),
943 * so the asserts in spa_close() do not apply.
944 */
945 void
946 spa_async_close(spa_t *spa, const void *tag)
947 {
948 (void) zfs_refcount_remove(&spa->spa_refcount, tag);
949 }
950
951 /*
952 * Check to see if the spa refcount is zero. Must be called with
953 * spa_namespace_lock held. We really compare against spa_minref, which is the
954 * number of references acquired when opening a pool
955 */
956 boolean_t
957 spa_refcount_zero(spa_t *spa)
958 {
959 ASSERT(MUTEX_HELD(&spa_namespace_lock));
960
961 return (zfs_refcount_count(&spa->spa_refcount) == spa->spa_minref);
962 }
963
964 /*
965 * ==========================================================================
966 * SPA spare and l2cache tracking
967 * ==========================================================================
968 */
969
970 /*
971 * Hot spares and cache devices are tracked using the same code below,
972 * for 'auxiliary' devices.
973 */
974
975 typedef struct spa_aux {
976 uint64_t aux_guid;
977 uint64_t aux_pool;
978 avl_node_t aux_avl;
979 int aux_count;
980 } spa_aux_t;
981
982 static inline int
983 spa_aux_compare(const void *a, const void *b)
984 {
985 const spa_aux_t *sa = (const spa_aux_t *)a;
986 const spa_aux_t *sb = (const spa_aux_t *)b;
987
988 return (TREE_CMP(sa->aux_guid, sb->aux_guid));
989 }
990
991 static void
992 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
993 {
994 avl_index_t where;
995 spa_aux_t search;
996 spa_aux_t *aux;
997
998 search.aux_guid = vd->vdev_guid;
999 if ((aux = avl_find(avl, &search, &where)) != NULL) {
1000 aux->aux_count++;
1001 } else {
1002 aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
1003 aux->aux_guid = vd->vdev_guid;
1004 aux->aux_count = 1;
1005 avl_insert(avl, aux, where);
1006 }
1007 }
1008
1009 static void
1010 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
1011 {
1012 spa_aux_t search;
1013 spa_aux_t *aux;
1014 avl_index_t where;
1015
1016 search.aux_guid = vd->vdev_guid;
1017 aux = avl_find(avl, &search, &where);
1018
1019 ASSERT(aux != NULL);
1020
1021 if (--aux->aux_count == 0) {
1022 avl_remove(avl, aux);
1023 kmem_free(aux, sizeof (spa_aux_t));
1024 } else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
1025 aux->aux_pool = 0ULL;
1026 }
1027 }
1028
1029 static boolean_t
1030 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
1031 {
1032 spa_aux_t search, *found;
1033
1034 search.aux_guid = guid;
1035 found = avl_find(avl, &search, NULL);
1036
1037 if (pool) {
1038 if (found)
1039 *pool = found->aux_pool;
1040 else
1041 *pool = 0ULL;
1042 }
1043
1044 if (refcnt) {
1045 if (found)
1046 *refcnt = found->aux_count;
1047 else
1048 *refcnt = 0;
1049 }
1050
1051 return (found != NULL);
1052 }
1053
1054 static void
1055 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
1056 {
1057 spa_aux_t search, *found;
1058 avl_index_t where;
1059
1060 search.aux_guid = vd->vdev_guid;
1061 found = avl_find(avl, &search, &where);
1062 ASSERT(found != NULL);
1063 ASSERT(found->aux_pool == 0ULL);
1064
1065 found->aux_pool = spa_guid(vd->vdev_spa);
1066 }
1067
1068 /*
1069 * Spares are tracked globally due to the following constraints:
1070 *
1071 * - A spare may be part of multiple pools.
1072 * - A spare may be added to a pool even if it's actively in use within
1073 * another pool.
1074 * - A spare in use in any pool can only be the source of a replacement if
1075 * the target is a spare in the same pool.
1076 *
1077 * We keep track of all spares on the system through the use of a reference
1078 * counted AVL tree. When a vdev is added as a spare, or used as a replacement
1079 * spare, then we bump the reference count in the AVL tree. In addition, we set
1080 * the 'vdev_isspare' member to indicate that the device is a spare (active or
1081 * inactive). When a spare is made active (used to replace a device in the
1082 * pool), we also keep track of which pool its been made a part of.
1083 *
1084 * The 'spa_spare_lock' protects the AVL tree. These functions are normally
1085 * called under the spa_namespace lock as part of vdev reconfiguration. The
1086 * separate spare lock exists for the status query path, which does not need to
1087 * be completely consistent with respect to other vdev configuration changes.
1088 */
1089
1090 static int
1091 spa_spare_compare(const void *a, const void *b)
1092 {
1093 return (spa_aux_compare(a, b));
1094 }
1095
1096 void
1097 spa_spare_add(vdev_t *vd)
1098 {
1099 mutex_enter(&spa_spare_lock);
1100 ASSERT(!vd->vdev_isspare);
1101 spa_aux_add(vd, &spa_spare_avl);
1102 vd->vdev_isspare = B_TRUE;
1103 mutex_exit(&spa_spare_lock);
1104 }
1105
1106 void
1107 spa_spare_remove(vdev_t *vd)
1108 {
1109 mutex_enter(&spa_spare_lock);
1110 ASSERT(vd->vdev_isspare);
1111 spa_aux_remove(vd, &spa_spare_avl);
1112 vd->vdev_isspare = B_FALSE;
1113 mutex_exit(&spa_spare_lock);
1114 }
1115
1116 boolean_t
1117 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
1118 {
1119 boolean_t found;
1120
1121 mutex_enter(&spa_spare_lock);
1122 found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
1123 mutex_exit(&spa_spare_lock);
1124
1125 return (found);
1126 }
1127
1128 void
1129 spa_spare_activate(vdev_t *vd)
1130 {
1131 mutex_enter(&spa_spare_lock);
1132 ASSERT(vd->vdev_isspare);
1133 spa_aux_activate(vd, &spa_spare_avl);
1134 mutex_exit(&spa_spare_lock);
1135 }
1136
1137 /*
1138 * Level 2 ARC devices are tracked globally for the same reasons as spares.
1139 * Cache devices currently only support one pool per cache device, and so
1140 * for these devices the aux reference count is currently unused beyond 1.
1141 */
1142
1143 static int
1144 spa_l2cache_compare(const void *a, const void *b)
1145 {
1146 return (spa_aux_compare(a, b));
1147 }
1148
1149 void
1150 spa_l2cache_add(vdev_t *vd)
1151 {
1152 mutex_enter(&spa_l2cache_lock);
1153 ASSERT(!vd->vdev_isl2cache);
1154 spa_aux_add(vd, &spa_l2cache_avl);
1155 vd->vdev_isl2cache = B_TRUE;
1156 mutex_exit(&spa_l2cache_lock);
1157 }
1158
1159 void
1160 spa_l2cache_remove(vdev_t *vd)
1161 {
1162 mutex_enter(&spa_l2cache_lock);
1163 ASSERT(vd->vdev_isl2cache);
1164 spa_aux_remove(vd, &spa_l2cache_avl);
1165 vd->vdev_isl2cache = B_FALSE;
1166 mutex_exit(&spa_l2cache_lock);
1167 }
1168
1169 boolean_t
1170 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
1171 {
1172 boolean_t found;
1173
1174 mutex_enter(&spa_l2cache_lock);
1175 found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
1176 mutex_exit(&spa_l2cache_lock);
1177
1178 return (found);
1179 }
1180
1181 void
1182 spa_l2cache_activate(vdev_t *vd)
1183 {
1184 mutex_enter(&spa_l2cache_lock);
1185 ASSERT(vd->vdev_isl2cache);
1186 spa_aux_activate(vd, &spa_l2cache_avl);
1187 mutex_exit(&spa_l2cache_lock);
1188 }
1189
1190 /*
1191 * ==========================================================================
1192 * SPA vdev locking
1193 * ==========================================================================
1194 */
1195
1196 /*
1197 * Lock the given spa_t for the purpose of adding or removing a vdev.
1198 * Grabs the global spa_namespace_lock plus the spa config lock for writing.
1199 * It returns the next transaction group for the spa_t.
1200 */
1201 uint64_t
1202 spa_vdev_enter(spa_t *spa)
1203 {
1204 mutex_enter(&spa->spa_vdev_top_lock);
1205 mutex_enter(&spa_namespace_lock);
1206
1207 vdev_autotrim_stop_all(spa);
1208
1209 return (spa_vdev_config_enter(spa));
1210 }
1211
1212 /*
1213 * The same as spa_vdev_enter() above but additionally takes the guid of
1214 * the vdev being detached. When there is a rebuild in process it will be
1215 * suspended while the vdev tree is modified then resumed by spa_vdev_exit().
1216 * The rebuild is canceled if only a single child remains after the detach.
1217 */
1218 uint64_t
1219 spa_vdev_detach_enter(spa_t *spa, uint64_t guid)
1220 {
1221 mutex_enter(&spa->spa_vdev_top_lock);
1222 mutex_enter(&spa_namespace_lock);
1223
1224 vdev_autotrim_stop_all(spa);
1225
1226 if (guid != 0) {
1227 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
1228 if (vd) {
1229 vdev_rebuild_stop_wait(vd->vdev_top);
1230 }
1231 }
1232
1233 return (spa_vdev_config_enter(spa));
1234 }
1235
1236 /*
1237 * Internal implementation for spa_vdev_enter(). Used when a vdev
1238 * operation requires multiple syncs (i.e. removing a device) while
1239 * keeping the spa_namespace_lock held.
1240 */
1241 uint64_t
1242 spa_vdev_config_enter(spa_t *spa)
1243 {
1244 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1245
1246 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1247
1248 return (spa_last_synced_txg(spa) + 1);
1249 }
1250
1251 /*
1252 * Used in combination with spa_vdev_config_enter() to allow the syncing
1253 * of multiple transactions without releasing the spa_namespace_lock.
1254 */
1255 void
1256 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error,
1257 const char *tag)
1258 {
1259 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1260
1261 int config_changed = B_FALSE;
1262
1263 ASSERT(txg > spa_last_synced_txg(spa));
1264
1265 spa->spa_pending_vdev = NULL;
1266
1267 /*
1268 * Reassess the DTLs.
1269 */
1270 vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE, B_FALSE);
1271
1272 if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
1273 config_changed = B_TRUE;
1274 spa->spa_config_generation++;
1275 }
1276
1277 /*
1278 * Verify the metaslab classes.
1279 */
1280 ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
1281 ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
1282 ASSERT(metaslab_class_validate(spa_embedded_log_class(spa)) == 0);
1283 ASSERT(metaslab_class_validate(spa_special_class(spa)) == 0);
1284 ASSERT(metaslab_class_validate(spa_dedup_class(spa)) == 0);
1285
1286 spa_config_exit(spa, SCL_ALL, spa);
1287
1288 /*
1289 * Panic the system if the specified tag requires it. This
1290 * is useful for ensuring that configurations are updated
1291 * transactionally.
1292 */
1293 if (zio_injection_enabled)
1294 zio_handle_panic_injection(spa, tag, 0);
1295
1296 /*
1297 * Note: this txg_wait_synced() is important because it ensures
1298 * that there won't be more than one config change per txg.
1299 * This allows us to use the txg as the generation number.
1300 */
1301 if (error == 0)
1302 txg_wait_synced(spa->spa_dsl_pool, txg);
1303
1304 if (vd != NULL) {
1305 ASSERT(!vd->vdev_detached || vd->vdev_dtl_sm == NULL);
1306 if (vd->vdev_ops->vdev_op_leaf) {
1307 mutex_enter(&vd->vdev_initialize_lock);
1308 vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED,
1309 NULL);
1310 mutex_exit(&vd->vdev_initialize_lock);
1311
1312 mutex_enter(&vd->vdev_trim_lock);
1313 vdev_trim_stop(vd, VDEV_TRIM_CANCELED, NULL);
1314 mutex_exit(&vd->vdev_trim_lock);
1315 }
1316
1317 /*
1318 * The vdev may be both a leaf and top-level device.
1319 */
1320 vdev_autotrim_stop_wait(vd);
1321
1322 spa_config_enter(spa, SCL_STATE_ALL, spa, RW_WRITER);
1323 vdev_free(vd);
1324 spa_config_exit(spa, SCL_STATE_ALL, spa);
1325 }
1326
1327 /*
1328 * If the config changed, update the config cache.
1329 */
1330 if (config_changed)
1331 spa_write_cachefile(spa, B_FALSE, B_TRUE, B_TRUE);
1332 }
1333
1334 /*
1335 * Unlock the spa_t after adding or removing a vdev. Besides undoing the
1336 * locking of spa_vdev_enter(), we also want make sure the transactions have
1337 * synced to disk, and then update the global configuration cache with the new
1338 * information.
1339 */
1340 int
1341 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
1342 {
1343 vdev_autotrim_restart(spa);
1344 vdev_rebuild_restart(spa);
1345
1346 spa_vdev_config_exit(spa, vd, txg, error, FTAG);
1347 mutex_exit(&spa_namespace_lock);
1348 mutex_exit(&spa->spa_vdev_top_lock);
1349
1350 return (error);
1351 }
1352
1353 /*
1354 * Lock the given spa_t for the purpose of changing vdev state.
1355 */
1356 void
1357 spa_vdev_state_enter(spa_t *spa, int oplocks)
1358 {
1359 int locks = SCL_STATE_ALL | oplocks;
1360
1361 /*
1362 * Root pools may need to read of the underlying devfs filesystem
1363 * when opening up a vdev. Unfortunately if we're holding the
1364 * SCL_ZIO lock it will result in a deadlock when we try to issue
1365 * the read from the root filesystem. Instead we "prefetch"
1366 * the associated vnodes that we need prior to opening the
1367 * underlying devices and cache them so that we can prevent
1368 * any I/O when we are doing the actual open.
1369 */
1370 if (spa_is_root(spa)) {
1371 int low = locks & ~(SCL_ZIO - 1);
1372 int high = locks & ~low;
1373
1374 spa_config_enter(spa, high, spa, RW_WRITER);
1375 vdev_hold(spa->spa_root_vdev);
1376 spa_config_enter(spa, low, spa, RW_WRITER);
1377 } else {
1378 spa_config_enter(spa, locks, spa, RW_WRITER);
1379 }
1380 spa->spa_vdev_locks = locks;
1381 }
1382
1383 int
1384 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
1385 {
1386 boolean_t config_changed = B_FALSE;
1387 vdev_t *vdev_top;
1388
1389 if (vd == NULL || vd == spa->spa_root_vdev) {
1390 vdev_top = spa->spa_root_vdev;
1391 } else {
1392 vdev_top = vd->vdev_top;
1393 }
1394
1395 if (vd != NULL || error == 0)
1396 vdev_dtl_reassess(vdev_top, 0, 0, B_FALSE, B_FALSE);
1397
1398 if (vd != NULL) {
1399 if (vd != spa->spa_root_vdev)
1400 vdev_state_dirty(vdev_top);
1401
1402 config_changed = B_TRUE;
1403 spa->spa_config_generation++;
1404 }
1405
1406 if (spa_is_root(spa))
1407 vdev_rele(spa->spa_root_vdev);
1408
1409 ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1410 spa_config_exit(spa, spa->spa_vdev_locks, spa);
1411
1412 /*
1413 * If anything changed, wait for it to sync. This ensures that,
1414 * from the system administrator's perspective, zpool(8) commands
1415 * are synchronous. This is important for things like zpool offline:
1416 * when the command completes, you expect no further I/O from ZFS.
1417 */
1418 if (vd != NULL)
1419 txg_wait_synced(spa->spa_dsl_pool, 0);
1420
1421 /*
1422 * If the config changed, update the config cache.
1423 */
1424 if (config_changed) {
1425 mutex_enter(&spa_namespace_lock);
1426 spa_write_cachefile(spa, B_FALSE, B_TRUE, B_FALSE);
1427 mutex_exit(&spa_namespace_lock);
1428 }
1429
1430 return (error);
1431 }
1432
1433 /*
1434 * ==========================================================================
1435 * Miscellaneous functions
1436 * ==========================================================================
1437 */
1438
1439 void
1440 spa_activate_mos_feature(spa_t *spa, const char *feature, dmu_tx_t *tx)
1441 {
1442 if (!nvlist_exists(spa->spa_label_features, feature)) {
1443 fnvlist_add_boolean(spa->spa_label_features, feature);
1444 /*
1445 * When we are creating the pool (tx_txg==TXG_INITIAL), we can't
1446 * dirty the vdev config because lock SCL_CONFIG is not held.
1447 * Thankfully, in this case we don't need to dirty the config
1448 * because it will be written out anyway when we finish
1449 * creating the pool.
1450 */
1451 if (tx->tx_txg != TXG_INITIAL)
1452 vdev_config_dirty(spa->spa_root_vdev);
1453 }
1454 }
1455
1456 void
1457 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1458 {
1459 if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1460 vdev_config_dirty(spa->spa_root_vdev);
1461 }
1462
1463 /*
1464 * Return the spa_t associated with given pool_guid, if it exists. If
1465 * device_guid is non-zero, determine whether the pool exists *and* contains
1466 * a device with the specified device_guid.
1467 */
1468 spa_t *
1469 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1470 {
1471 spa_t *spa;
1472 avl_tree_t *t = &spa_namespace_avl;
1473
1474 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1475
1476 for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1477 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1478 continue;
1479 if (spa->spa_root_vdev == NULL)
1480 continue;
1481 if (spa_guid(spa) == pool_guid) {
1482 if (device_guid == 0)
1483 break;
1484
1485 if (vdev_lookup_by_guid(spa->spa_root_vdev,
1486 device_guid) != NULL)
1487 break;
1488
1489 /*
1490 * Check any devices we may be in the process of adding.
1491 */
1492 if (spa->spa_pending_vdev) {
1493 if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1494 device_guid) != NULL)
1495 break;
1496 }
1497 }
1498 }
1499
1500 return (spa);
1501 }
1502
1503 /*
1504 * Determine whether a pool with the given pool_guid exists.
1505 */
1506 boolean_t
1507 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1508 {
1509 return (spa_by_guid(pool_guid, device_guid) != NULL);
1510 }
1511
1512 char *
1513 spa_strdup(const char *s)
1514 {
1515 size_t len;
1516 char *new;
1517
1518 len = strlen(s);
1519 new = kmem_alloc(len + 1, KM_SLEEP);
1520 memcpy(new, s, len + 1);
1521
1522 return (new);
1523 }
1524
1525 void
1526 spa_strfree(char *s)
1527 {
1528 kmem_free(s, strlen(s) + 1);
1529 }
1530
1531 uint64_t
1532 spa_generate_guid(spa_t *spa)
1533 {
1534 uint64_t guid;
1535
1536 if (spa != NULL) {
1537 do {
1538 (void) random_get_pseudo_bytes((void *)&guid,
1539 sizeof (guid));
1540 } while (guid == 0 || spa_guid_exists(spa_guid(spa), guid));
1541 } else {
1542 do {
1543 (void) random_get_pseudo_bytes((void *)&guid,
1544 sizeof (guid));
1545 } while (guid == 0 || spa_guid_exists(guid, 0));
1546 }
1547
1548 return (guid);
1549 }
1550
1551 void
1552 snprintf_blkptr(char *buf, size_t buflen, const blkptr_t *bp)
1553 {
1554 char type[256];
1555 const char *checksum = NULL;
1556 const char *compress = NULL;
1557
1558 if (bp != NULL) {
1559 if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1560 dmu_object_byteswap_t bswap =
1561 DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1562 (void) snprintf(type, sizeof (type), "bswap %s %s",
1563 DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1564 "metadata" : "data",
1565 dmu_ot_byteswap[bswap].ob_name);
1566 } else {
1567 (void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1568 sizeof (type));
1569 }
1570 if (!BP_IS_EMBEDDED(bp)) {
1571 checksum =
1572 zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1573 }
1574 compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1575 }
1576
1577 SNPRINTF_BLKPTR(kmem_scnprintf, ' ', buf, buflen, bp, type, checksum,
1578 compress);
1579 }
1580
1581 void
1582 spa_freeze(spa_t *spa)
1583 {
1584 uint64_t freeze_txg = 0;
1585
1586 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1587 if (spa->spa_freeze_txg == UINT64_MAX) {
1588 freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1589 spa->spa_freeze_txg = freeze_txg;
1590 }
1591 spa_config_exit(spa, SCL_ALL, FTAG);
1592 if (freeze_txg != 0)
1593 txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1594 }
1595
1596 void
1597 zfs_panic_recover(const char *fmt, ...)
1598 {
1599 va_list adx;
1600
1601 va_start(adx, fmt);
1602 vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1603 va_end(adx);
1604 }
1605
1606 /*
1607 * This is a stripped-down version of strtoull, suitable only for converting
1608 * lowercase hexadecimal numbers that don't overflow.
1609 */
1610 uint64_t
1611 zfs_strtonum(const char *str, char **nptr)
1612 {
1613 uint64_t val = 0;
1614 char c;
1615 int digit;
1616
1617 while ((c = *str) != '\0') {
1618 if (c >= '0' && c <= '9')
1619 digit = c - '0';
1620 else if (c >= 'a' && c <= 'f')
1621 digit = 10 + c - 'a';
1622 else
1623 break;
1624
1625 val *= 16;
1626 val += digit;
1627
1628 str++;
1629 }
1630
1631 if (nptr)
1632 *nptr = (char *)str;
1633
1634 return (val);
1635 }
1636
1637 void
1638 spa_activate_allocation_classes(spa_t *spa, dmu_tx_t *tx)
1639 {
1640 /*
1641 * We bump the feature refcount for each special vdev added to the pool
1642 */
1643 ASSERT(spa_feature_is_enabled(spa, SPA_FEATURE_ALLOCATION_CLASSES));
1644 spa_feature_incr(spa, SPA_FEATURE_ALLOCATION_CLASSES, tx);
1645 }
1646
1647 /*
1648 * ==========================================================================
1649 * Accessor functions
1650 * ==========================================================================
1651 */
1652
1653 boolean_t
1654 spa_shutting_down(spa_t *spa)
1655 {
1656 return (spa->spa_async_suspended);
1657 }
1658
1659 dsl_pool_t *
1660 spa_get_dsl(spa_t *spa)
1661 {
1662 return (spa->spa_dsl_pool);
1663 }
1664
1665 boolean_t
1666 spa_is_initializing(spa_t *spa)
1667 {
1668 return (spa->spa_is_initializing);
1669 }
1670
1671 boolean_t
1672 spa_indirect_vdevs_loaded(spa_t *spa)
1673 {
1674 return (spa->spa_indirect_vdevs_loaded);
1675 }
1676
1677 blkptr_t *
1678 spa_get_rootblkptr(spa_t *spa)
1679 {
1680 return (&spa->spa_ubsync.ub_rootbp);
1681 }
1682
1683 void
1684 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1685 {
1686 spa->spa_uberblock.ub_rootbp = *bp;
1687 }
1688
1689 void
1690 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1691 {
1692 if (spa->spa_root == NULL)
1693 buf[0] = '\0';
1694 else
1695 (void) strlcpy(buf, spa->spa_root, buflen);
1696 }
1697
1698 uint32_t
1699 spa_sync_pass(spa_t *spa)
1700 {
1701 return (spa->spa_sync_pass);
1702 }
1703
1704 char *
1705 spa_name(spa_t *spa)
1706 {
1707 return (spa->spa_name);
1708 }
1709
1710 uint64_t
1711 spa_guid(spa_t *spa)
1712 {
1713 dsl_pool_t *dp = spa_get_dsl(spa);
1714 uint64_t guid;
1715
1716 /*
1717 * If we fail to parse the config during spa_load(), we can go through
1718 * the error path (which posts an ereport) and end up here with no root
1719 * vdev. We stash the original pool guid in 'spa_config_guid' to handle
1720 * this case.
1721 */
1722 if (spa->spa_root_vdev == NULL)
1723 return (spa->spa_config_guid);
1724
1725 guid = spa->spa_last_synced_guid != 0 ?
1726 spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1727
1728 /*
1729 * Return the most recently synced out guid unless we're
1730 * in syncing context.
1731 */
1732 if (dp && dsl_pool_sync_context(dp))
1733 return (spa->spa_root_vdev->vdev_guid);
1734 else
1735 return (guid);
1736 }
1737
1738 uint64_t
1739 spa_load_guid(spa_t *spa)
1740 {
1741 /*
1742 * This is a GUID that exists solely as a reference for the
1743 * purposes of the arc. It is generated at load time, and
1744 * is never written to persistent storage.
1745 */
1746 return (spa->spa_load_guid);
1747 }
1748
1749 uint64_t
1750 spa_last_synced_txg(spa_t *spa)
1751 {
1752 return (spa->spa_ubsync.ub_txg);
1753 }
1754
1755 uint64_t
1756 spa_first_txg(spa_t *spa)
1757 {
1758 return (spa->spa_first_txg);
1759 }
1760
1761 uint64_t
1762 spa_syncing_txg(spa_t *spa)
1763 {
1764 return (spa->spa_syncing_txg);
1765 }
1766
1767 /*
1768 * Return the last txg where data can be dirtied. The final txgs
1769 * will be used to just clear out any deferred frees that remain.
1770 */
1771 uint64_t
1772 spa_final_dirty_txg(spa_t *spa)
1773 {
1774 return (spa->spa_final_txg - TXG_DEFER_SIZE);
1775 }
1776
1777 pool_state_t
1778 spa_state(spa_t *spa)
1779 {
1780 return (spa->spa_state);
1781 }
1782
1783 spa_load_state_t
1784 spa_load_state(spa_t *spa)
1785 {
1786 return (spa->spa_load_state);
1787 }
1788
1789 uint64_t
1790 spa_freeze_txg(spa_t *spa)
1791 {
1792 return (spa->spa_freeze_txg);
1793 }
1794
1795 /*
1796 * Return the inflated asize for a logical write in bytes. This is used by the
1797 * DMU to calculate the space a logical write will require on disk.
1798 * If lsize is smaller than the largest physical block size allocatable on this
1799 * pool we use its value instead, since the write will end up using the whole
1800 * block anyway.
1801 */
1802 uint64_t
1803 spa_get_worst_case_asize(spa_t *spa, uint64_t lsize)
1804 {
1805 if (lsize == 0)
1806 return (0); /* No inflation needed */
1807 return (MAX(lsize, 1 << spa->spa_max_ashift) * spa_asize_inflation);
1808 }
1809
1810 /*
1811 * Return the amount of slop space in bytes. It is typically 1/32 of the pool
1812 * (3.2%), minus the embedded log space. On very small pools, it may be
1813 * slightly larger than this. On very large pools, it will be capped to
1814 * the value of spa_max_slop. The embedded log space is not included in
1815 * spa_dspace. By subtracting it, the usable space (per "zfs list") is a
1816 * constant 97% of the total space, regardless of metaslab size (assuming the
1817 * default spa_slop_shift=5 and a non-tiny pool).
1818 *
1819 * See the comment above spa_slop_shift for more details.
1820 */
1821 uint64_t
1822 spa_get_slop_space(spa_t *spa)
1823 {
1824 uint64_t space = 0;
1825 uint64_t slop = 0;
1826
1827 /*
1828 * Make sure spa_dedup_dspace has been set.
1829 */
1830 if (spa->spa_dedup_dspace == ~0ULL)
1831 spa_update_dspace(spa);
1832
1833 /*
1834 * spa_get_dspace() includes the space only logically "used" by
1835 * deduplicated data, so since it's not useful to reserve more
1836 * space with more deduplicated data, we subtract that out here.
1837 */
1838 space = spa_get_dspace(spa) - spa->spa_dedup_dspace;
1839 slop = MIN(space >> spa_slop_shift, spa_max_slop);
1840
1841 /*
1842 * Subtract the embedded log space, but no more than half the (3.2%)
1843 * unusable space. Note, the "no more than half" is only relevant if
1844 * zfs_embedded_slog_min_ms >> spa_slop_shift < 2, which is not true by
1845 * default.
1846 */
1847 uint64_t embedded_log =
1848 metaslab_class_get_dspace(spa_embedded_log_class(spa));
1849 slop -= MIN(embedded_log, slop >> 1);
1850
1851 /*
1852 * Slop space should be at least spa_min_slop, but no more than half
1853 * the entire pool.
1854 */
1855 slop = MAX(slop, MIN(space >> 1, spa_min_slop));
1856 return (slop);
1857 }
1858
1859 uint64_t
1860 spa_get_dspace(spa_t *spa)
1861 {
1862 return (spa->spa_dspace);
1863 }
1864
1865 uint64_t
1866 spa_get_checkpoint_space(spa_t *spa)
1867 {
1868 return (spa->spa_checkpoint_info.sci_dspace);
1869 }
1870
1871 void
1872 spa_update_dspace(spa_t *spa)
1873 {
1874 spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1875 ddt_get_dedup_dspace(spa) + brt_get_dspace(spa);
1876 if (spa->spa_nonallocating_dspace > 0) {
1877 /*
1878 * Subtract the space provided by all non-allocating vdevs that
1879 * contribute to dspace. If a file is overwritten, its old
1880 * blocks are freed and new blocks are allocated. If there are
1881 * no snapshots of the file, the available space should remain
1882 * the same. The old blocks could be freed from the
1883 * non-allocating vdev, but the new blocks must be allocated on
1884 * other (allocating) vdevs. By reserving the entire size of
1885 * the non-allocating vdevs (including allocated space), we
1886 * ensure that there will be enough space on the allocating
1887 * vdevs for this file overwrite to succeed.
1888 *
1889 * Note that the DMU/DSL doesn't actually know or care
1890 * how much space is allocated (it does its own tracking
1891 * of how much space has been logically used). So it
1892 * doesn't matter that the data we are moving may be
1893 * allocated twice (on the old device and the new device).
1894 */
1895 ASSERT3U(spa->spa_dspace, >=, spa->spa_nonallocating_dspace);
1896 spa->spa_dspace -= spa->spa_nonallocating_dspace;
1897 }
1898 }
1899
1900 /*
1901 * Return the failure mode that has been set to this pool. The default
1902 * behavior will be to block all I/Os when a complete failure occurs.
1903 */
1904 uint64_t
1905 spa_get_failmode(spa_t *spa)
1906 {
1907 return (spa->spa_failmode);
1908 }
1909
1910 boolean_t
1911 spa_suspended(spa_t *spa)
1912 {
1913 return (spa->spa_suspended != ZIO_SUSPEND_NONE);
1914 }
1915
1916 uint64_t
1917 spa_version(spa_t *spa)
1918 {
1919 return (spa->spa_ubsync.ub_version);
1920 }
1921
1922 boolean_t
1923 spa_deflate(spa_t *spa)
1924 {
1925 return (spa->spa_deflate);
1926 }
1927
1928 metaslab_class_t *
1929 spa_normal_class(spa_t *spa)
1930 {
1931 return (spa->spa_normal_class);
1932 }
1933
1934 metaslab_class_t *
1935 spa_log_class(spa_t *spa)
1936 {
1937 return (spa->spa_log_class);
1938 }
1939
1940 metaslab_class_t *
1941 spa_embedded_log_class(spa_t *spa)
1942 {
1943 return (spa->spa_embedded_log_class);
1944 }
1945
1946 metaslab_class_t *
1947 spa_special_class(spa_t *spa)
1948 {
1949 return (spa->spa_special_class);
1950 }
1951
1952 metaslab_class_t *
1953 spa_dedup_class(spa_t *spa)
1954 {
1955 return (spa->spa_dedup_class);
1956 }
1957
1958 /*
1959 * Locate an appropriate allocation class
1960 */
1961 metaslab_class_t *
1962 spa_preferred_class(spa_t *spa, uint64_t size, dmu_object_type_t objtype,
1963 uint_t level, uint_t special_smallblk)
1964 {
1965 /*
1966 * ZIL allocations determine their class in zio_alloc_zil().
1967 */
1968 ASSERT(objtype != DMU_OT_INTENT_LOG);
1969
1970 boolean_t has_special_class = spa->spa_special_class->mc_groups != 0;
1971
1972 if (DMU_OT_IS_DDT(objtype)) {
1973 if (spa->spa_dedup_class->mc_groups != 0)
1974 return (spa_dedup_class(spa));
1975 else if (has_special_class && zfs_ddt_data_is_special)
1976 return (spa_special_class(spa));
1977 else
1978 return (spa_normal_class(spa));
1979 }
1980
1981 /* Indirect blocks for user data can land in special if allowed */
1982 if (level > 0 && (DMU_OT_IS_FILE(objtype) || objtype == DMU_OT_ZVOL)) {
1983 if (has_special_class && zfs_user_indirect_is_special)
1984 return (spa_special_class(spa));
1985 else
1986 return (spa_normal_class(spa));
1987 }
1988
1989 if (DMU_OT_IS_METADATA(objtype) || level > 0) {
1990 if (has_special_class)
1991 return (spa_special_class(spa));
1992 else
1993 return (spa_normal_class(spa));
1994 }
1995
1996 /*
1997 * Allow small file blocks in special class in some cases (like
1998 * for the dRAID vdev feature). But always leave a reserve of
1999 * zfs_special_class_metadata_reserve_pct exclusively for metadata.
2000 */
2001 if (DMU_OT_IS_FILE(objtype) &&
2002 has_special_class && size <= special_smallblk) {
2003 metaslab_class_t *special = spa_special_class(spa);
2004 uint64_t alloc = metaslab_class_get_alloc(special);
2005 uint64_t space = metaslab_class_get_space(special);
2006 uint64_t limit =
2007 (space * (100 - zfs_special_class_metadata_reserve_pct))
2008 / 100;
2009
2010 if (alloc < limit)
2011 return (special);
2012 }
2013
2014 return (spa_normal_class(spa));
2015 }
2016
2017 void
2018 spa_evicting_os_register(spa_t *spa, objset_t *os)
2019 {
2020 mutex_enter(&spa->spa_evicting_os_lock);
2021 list_insert_head(&spa->spa_evicting_os_list, os);
2022 mutex_exit(&spa->spa_evicting_os_lock);
2023 }
2024
2025 void
2026 spa_evicting_os_deregister(spa_t *spa, objset_t *os)
2027 {
2028 mutex_enter(&spa->spa_evicting_os_lock);
2029 list_remove(&spa->spa_evicting_os_list, os);
2030 cv_broadcast(&spa->spa_evicting_os_cv);
2031 mutex_exit(&spa->spa_evicting_os_lock);
2032 }
2033
2034 void
2035 spa_evicting_os_wait(spa_t *spa)
2036 {
2037 mutex_enter(&spa->spa_evicting_os_lock);
2038 while (!list_is_empty(&spa->spa_evicting_os_list))
2039 cv_wait(&spa->spa_evicting_os_cv, &spa->spa_evicting_os_lock);
2040 mutex_exit(&spa->spa_evicting_os_lock);
2041
2042 dmu_buf_user_evict_wait();
2043 }
2044
2045 int
2046 spa_max_replication(spa_t *spa)
2047 {
2048 /*
2049 * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
2050 * handle BPs with more than one DVA allocated. Set our max
2051 * replication level accordingly.
2052 */
2053 if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
2054 return (1);
2055 return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
2056 }
2057
2058 int
2059 spa_prev_software_version(spa_t *spa)
2060 {
2061 return (spa->spa_prev_software_version);
2062 }
2063
2064 uint64_t
2065 spa_deadman_synctime(spa_t *spa)
2066 {
2067 return (spa->spa_deadman_synctime);
2068 }
2069
2070 spa_autotrim_t
2071 spa_get_autotrim(spa_t *spa)
2072 {
2073 return (spa->spa_autotrim);
2074 }
2075
2076 uint64_t
2077 spa_deadman_ziotime(spa_t *spa)
2078 {
2079 return (spa->spa_deadman_ziotime);
2080 }
2081
2082 uint64_t
2083 spa_get_deadman_failmode(spa_t *spa)
2084 {
2085 return (spa->spa_deadman_failmode);
2086 }
2087
2088 void
2089 spa_set_deadman_failmode(spa_t *spa, const char *failmode)
2090 {
2091 if (strcmp(failmode, "wait") == 0)
2092 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_WAIT;
2093 else if (strcmp(failmode, "continue") == 0)
2094 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_CONTINUE;
2095 else if (strcmp(failmode, "panic") == 0)
2096 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_PANIC;
2097 else
2098 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_WAIT;
2099 }
2100
2101 void
2102 spa_set_deadman_ziotime(hrtime_t ns)
2103 {
2104 spa_t *spa = NULL;
2105
2106 if (spa_mode_global != SPA_MODE_UNINIT) {
2107 mutex_enter(&spa_namespace_lock);
2108 while ((spa = spa_next(spa)) != NULL)
2109 spa->spa_deadman_ziotime = ns;
2110 mutex_exit(&spa_namespace_lock);
2111 }
2112 }
2113
2114 void
2115 spa_set_deadman_synctime(hrtime_t ns)
2116 {
2117 spa_t *spa = NULL;
2118
2119 if (spa_mode_global != SPA_MODE_UNINIT) {
2120 mutex_enter(&spa_namespace_lock);
2121 while ((spa = spa_next(spa)) != NULL)
2122 spa->spa_deadman_synctime = ns;
2123 mutex_exit(&spa_namespace_lock);
2124 }
2125 }
2126
2127 uint64_t
2128 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
2129 {
2130 uint64_t asize = DVA_GET_ASIZE(dva);
2131 uint64_t dsize = asize;
2132
2133 ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
2134
2135 if (asize != 0 && spa->spa_deflate) {
2136 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
2137 if (vd != NULL)
2138 dsize = (asize >> SPA_MINBLOCKSHIFT) *
2139 vd->vdev_deflate_ratio;
2140 }
2141
2142 return (dsize);
2143 }
2144
2145 uint64_t
2146 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
2147 {
2148 uint64_t dsize = 0;
2149
2150 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
2151 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
2152
2153 return (dsize);
2154 }
2155
2156 uint64_t
2157 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
2158 {
2159 uint64_t dsize = 0;
2160
2161 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2162
2163 for (int d = 0; d < BP_GET_NDVAS(bp); d++)
2164 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
2165
2166 spa_config_exit(spa, SCL_VDEV, FTAG);
2167
2168 return (dsize);
2169 }
2170
2171 uint64_t
2172 spa_dirty_data(spa_t *spa)
2173 {
2174 return (spa->spa_dsl_pool->dp_dirty_total);
2175 }
2176
2177 /*
2178 * ==========================================================================
2179 * SPA Import Progress Routines
2180 * ==========================================================================
2181 */
2182
2183 typedef struct spa_import_progress {
2184 uint64_t pool_guid; /* unique id for updates */
2185 char *pool_name;
2186 spa_load_state_t spa_load_state;
2187 uint64_t mmp_sec_remaining; /* MMP activity check */
2188 uint64_t spa_load_max_txg; /* rewind txg */
2189 procfs_list_node_t smh_node;
2190 } spa_import_progress_t;
2191
2192 spa_history_list_t *spa_import_progress_list = NULL;
2193
2194 static int
2195 spa_import_progress_show_header(struct seq_file *f)
2196 {
2197 seq_printf(f, "%-20s %-14s %-14s %-12s %s\n", "pool_guid",
2198 "load_state", "multihost_secs", "max_txg",
2199 "pool_name");
2200 return (0);
2201 }
2202
2203 static int
2204 spa_import_progress_show(struct seq_file *f, void *data)
2205 {
2206 spa_import_progress_t *sip = (spa_import_progress_t *)data;
2207
2208 seq_printf(f, "%-20llu %-14llu %-14llu %-12llu %s\n",
2209 (u_longlong_t)sip->pool_guid, (u_longlong_t)sip->spa_load_state,
2210 (u_longlong_t)sip->mmp_sec_remaining,
2211 (u_longlong_t)sip->spa_load_max_txg,
2212 (sip->pool_name ? sip->pool_name : "-"));
2213
2214 return (0);
2215 }
2216
2217 /* Remove oldest elements from list until there are no more than 'size' left */
2218 static void
2219 spa_import_progress_truncate(spa_history_list_t *shl, unsigned int size)
2220 {
2221 spa_import_progress_t *sip;
2222 while (shl->size > size) {
2223 sip = list_remove_head(&shl->procfs_list.pl_list);
2224 if (sip->pool_name)
2225 spa_strfree(sip->pool_name);
2226 kmem_free(sip, sizeof (spa_import_progress_t));
2227 shl->size--;
2228 }
2229
2230 IMPLY(size == 0, list_is_empty(&shl->procfs_list.pl_list));
2231 }
2232
2233 static void
2234 spa_import_progress_init(void)
2235 {
2236 spa_import_progress_list = kmem_zalloc(sizeof (spa_history_list_t),
2237 KM_SLEEP);
2238
2239 spa_import_progress_list->size = 0;
2240
2241 spa_import_progress_list->procfs_list.pl_private =
2242 spa_import_progress_list;
2243
2244 procfs_list_install("zfs",
2245 NULL,
2246 "import_progress",
2247 0644,
2248 &spa_import_progress_list->procfs_list,
2249 spa_import_progress_show,
2250 spa_import_progress_show_header,
2251 NULL,
2252 offsetof(spa_import_progress_t, smh_node));
2253 }
2254
2255 static void
2256 spa_import_progress_destroy(void)
2257 {
2258 spa_history_list_t *shl = spa_import_progress_list;
2259 procfs_list_uninstall(&shl->procfs_list);
2260 spa_import_progress_truncate(shl, 0);
2261 procfs_list_destroy(&shl->procfs_list);
2262 kmem_free(shl, sizeof (spa_history_list_t));
2263 }
2264
2265 int
2266 spa_import_progress_set_state(uint64_t pool_guid,
2267 spa_load_state_t load_state)
2268 {
2269 spa_history_list_t *shl = spa_import_progress_list;
2270 spa_import_progress_t *sip;
2271 int error = ENOENT;
2272
2273 if (shl->size == 0)
2274 return (0);
2275
2276 mutex_enter(&shl->procfs_list.pl_lock);
2277 for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2278 sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2279 if (sip->pool_guid == pool_guid) {
2280 sip->spa_load_state = load_state;
2281 error = 0;
2282 break;
2283 }
2284 }
2285 mutex_exit(&shl->procfs_list.pl_lock);
2286
2287 return (error);
2288 }
2289
2290 int
2291 spa_import_progress_set_max_txg(uint64_t pool_guid, uint64_t load_max_txg)
2292 {
2293 spa_history_list_t *shl = spa_import_progress_list;
2294 spa_import_progress_t *sip;
2295 int error = ENOENT;
2296
2297 if (shl->size == 0)
2298 return (0);
2299
2300 mutex_enter(&shl->procfs_list.pl_lock);
2301 for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2302 sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2303 if (sip->pool_guid == pool_guid) {
2304 sip->spa_load_max_txg = load_max_txg;
2305 error = 0;
2306 break;
2307 }
2308 }
2309 mutex_exit(&shl->procfs_list.pl_lock);
2310
2311 return (error);
2312 }
2313
2314 int
2315 spa_import_progress_set_mmp_check(uint64_t pool_guid,
2316 uint64_t mmp_sec_remaining)
2317 {
2318 spa_history_list_t *shl = spa_import_progress_list;
2319 spa_import_progress_t *sip;
2320 int error = ENOENT;
2321
2322 if (shl->size == 0)
2323 return (0);
2324
2325 mutex_enter(&shl->procfs_list.pl_lock);
2326 for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2327 sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2328 if (sip->pool_guid == pool_guid) {
2329 sip->mmp_sec_remaining = mmp_sec_remaining;
2330 error = 0;
2331 break;
2332 }
2333 }
2334 mutex_exit(&shl->procfs_list.pl_lock);
2335
2336 return (error);
2337 }
2338
2339 /*
2340 * A new import is in progress, add an entry.
2341 */
2342 void
2343 spa_import_progress_add(spa_t *spa)
2344 {
2345 spa_history_list_t *shl = spa_import_progress_list;
2346 spa_import_progress_t *sip;
2347 const char *poolname = NULL;
2348
2349 sip = kmem_zalloc(sizeof (spa_import_progress_t), KM_SLEEP);
2350 sip->pool_guid = spa_guid(spa);
2351
2352 (void) nvlist_lookup_string(spa->spa_config, ZPOOL_CONFIG_POOL_NAME,
2353 &poolname);
2354 if (poolname == NULL)
2355 poolname = spa_name(spa);
2356 sip->pool_name = spa_strdup(poolname);
2357 sip->spa_load_state = spa_load_state(spa);
2358
2359 mutex_enter(&shl->procfs_list.pl_lock);
2360 procfs_list_add(&shl->procfs_list, sip);
2361 shl->size++;
2362 mutex_exit(&shl->procfs_list.pl_lock);
2363 }
2364
2365 void
2366 spa_import_progress_remove(uint64_t pool_guid)
2367 {
2368 spa_history_list_t *shl = spa_import_progress_list;
2369 spa_import_progress_t *sip;
2370
2371 mutex_enter(&shl->procfs_list.pl_lock);
2372 for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2373 sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2374 if (sip->pool_guid == pool_guid) {
2375 if (sip->pool_name)
2376 spa_strfree(sip->pool_name);
2377 list_remove(&shl->procfs_list.pl_list, sip);
2378 shl->size--;
2379 kmem_free(sip, sizeof (spa_import_progress_t));
2380 break;
2381 }
2382 }
2383 mutex_exit(&shl->procfs_list.pl_lock);
2384 }
2385
2386 /*
2387 * ==========================================================================
2388 * Initialization and Termination
2389 * ==========================================================================
2390 */
2391
2392 static int
2393 spa_name_compare(const void *a1, const void *a2)
2394 {
2395 const spa_t *s1 = a1;
2396 const spa_t *s2 = a2;
2397 int s;
2398
2399 s = strcmp(s1->spa_name, s2->spa_name);
2400
2401 return (TREE_ISIGN(s));
2402 }
2403
2404 void
2405 spa_boot_init(void)
2406 {
2407 spa_config_load();
2408 }
2409
2410 void
2411 spa_init(spa_mode_t mode)
2412 {
2413 mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
2414 mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
2415 mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
2416 cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
2417
2418 avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
2419 offsetof(spa_t, spa_avl));
2420
2421 avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
2422 offsetof(spa_aux_t, aux_avl));
2423
2424 avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
2425 offsetof(spa_aux_t, aux_avl));
2426
2427 spa_mode_global = mode;
2428
2429 #ifndef _KERNEL
2430 if (spa_mode_global != SPA_MODE_READ && dprintf_find_string("watch")) {
2431 struct sigaction sa;
2432
2433 sa.sa_flags = SA_SIGINFO;
2434 sigemptyset(&sa.sa_mask);
2435 sa.sa_sigaction = arc_buf_sigsegv;
2436
2437 if (sigaction(SIGSEGV, &sa, NULL) == -1) {
2438 perror("could not enable watchpoints: "
2439 "sigaction(SIGSEGV, ...) = ");
2440 } else {
2441 arc_watch = B_TRUE;
2442 }
2443 }
2444 #endif
2445
2446 fm_init();
2447 zfs_refcount_init();
2448 unique_init();
2449 zfs_btree_init();
2450 metaslab_stat_init();
2451 brt_init();
2452 ddt_init();
2453 zio_init();
2454 dmu_init();
2455 zil_init();
2456 vdev_mirror_stat_init();
2457 vdev_raidz_math_init();
2458 vdev_file_init();
2459 zfs_prop_init();
2460 chksum_init();
2461 zpool_prop_init();
2462 zpool_feature_init();
2463 spa_config_load();
2464 vdev_prop_init();
2465 l2arc_start();
2466 scan_init();
2467 qat_init();
2468 spa_import_progress_init();
2469 }
2470
2471 void
2472 spa_fini(void)
2473 {
2474 l2arc_stop();
2475
2476 spa_evict_all();
2477
2478 vdev_file_fini();
2479 vdev_mirror_stat_fini();
2480 vdev_raidz_math_fini();
2481 chksum_fini();
2482 zil_fini();
2483 dmu_fini();
2484 zio_fini();
2485 ddt_fini();
2486 brt_fini();
2487 metaslab_stat_fini();
2488 zfs_btree_fini();
2489 unique_fini();
2490 zfs_refcount_fini();
2491 fm_fini();
2492 scan_fini();
2493 qat_fini();
2494 spa_import_progress_destroy();
2495
2496 avl_destroy(&spa_namespace_avl);
2497 avl_destroy(&spa_spare_avl);
2498 avl_destroy(&spa_l2cache_avl);
2499
2500 cv_destroy(&spa_namespace_cv);
2501 mutex_destroy(&spa_namespace_lock);
2502 mutex_destroy(&spa_spare_lock);
2503 mutex_destroy(&spa_l2cache_lock);
2504 }
2505
2506 /*
2507 * Return whether this pool has a dedicated slog device. No locking needed.
2508 * It's not a problem if the wrong answer is returned as it's only for
2509 * performance and not correctness.
2510 */
2511 boolean_t
2512 spa_has_slogs(spa_t *spa)
2513 {
2514 return (spa->spa_log_class->mc_groups != 0);
2515 }
2516
2517 spa_log_state_t
2518 spa_get_log_state(spa_t *spa)
2519 {
2520 return (spa->spa_log_state);
2521 }
2522
2523 void
2524 spa_set_log_state(spa_t *spa, spa_log_state_t state)
2525 {
2526 spa->spa_log_state = state;
2527 }
2528
2529 boolean_t
2530 spa_is_root(spa_t *spa)
2531 {
2532 return (spa->spa_is_root);
2533 }
2534
2535 boolean_t
2536 spa_writeable(spa_t *spa)
2537 {
2538 return (!!(spa->spa_mode & SPA_MODE_WRITE) && spa->spa_trust_config);
2539 }
2540
2541 /*
2542 * Returns true if there is a pending sync task in any of the current
2543 * syncing txg, the current quiescing txg, or the current open txg.
2544 */
2545 boolean_t
2546 spa_has_pending_synctask(spa_t *spa)
2547 {
2548 return (!txg_all_lists_empty(&spa->spa_dsl_pool->dp_sync_tasks) ||
2549 !txg_all_lists_empty(&spa->spa_dsl_pool->dp_early_sync_tasks));
2550 }
2551
2552 spa_mode_t
2553 spa_mode(spa_t *spa)
2554 {
2555 return (spa->spa_mode);
2556 }
2557
2558 uint64_t
2559 spa_bootfs(spa_t *spa)
2560 {
2561 return (spa->spa_bootfs);
2562 }
2563
2564 uint64_t
2565 spa_delegation(spa_t *spa)
2566 {
2567 return (spa->spa_delegation);
2568 }
2569
2570 objset_t *
2571 spa_meta_objset(spa_t *spa)
2572 {
2573 return (spa->spa_meta_objset);
2574 }
2575
2576 enum zio_checksum
2577 spa_dedup_checksum(spa_t *spa)
2578 {
2579 return (spa->spa_dedup_checksum);
2580 }
2581
2582 /*
2583 * Reset pool scan stat per scan pass (or reboot).
2584 */
2585 void
2586 spa_scan_stat_init(spa_t *spa)
2587 {
2588 /* data not stored on disk */
2589 spa->spa_scan_pass_start = gethrestime_sec();
2590 if (dsl_scan_is_paused_scrub(spa->spa_dsl_pool->dp_scan))
2591 spa->spa_scan_pass_scrub_pause = spa->spa_scan_pass_start;
2592 else
2593 spa->spa_scan_pass_scrub_pause = 0;
2594
2595 if (dsl_errorscrub_is_paused(spa->spa_dsl_pool->dp_scan))
2596 spa->spa_scan_pass_errorscrub_pause = spa->spa_scan_pass_start;
2597 else
2598 spa->spa_scan_pass_errorscrub_pause = 0;
2599
2600 spa->spa_scan_pass_scrub_spent_paused = 0;
2601 spa->spa_scan_pass_exam = 0;
2602 spa->spa_scan_pass_issued = 0;
2603
2604 // error scrub stats
2605 spa->spa_scan_pass_errorscrub_spent_paused = 0;
2606 }
2607
2608 /*
2609 * Get scan stats for zpool status reports
2610 */
2611 int
2612 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
2613 {
2614 dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
2615
2616 if (scn == NULL || (scn->scn_phys.scn_func == POOL_SCAN_NONE &&
2617 scn->errorscrub_phys.dep_func == POOL_SCAN_NONE))
2618 return (SET_ERROR(ENOENT));
2619
2620 memset(ps, 0, sizeof (pool_scan_stat_t));
2621
2622 /* data stored on disk */
2623 ps->pss_func = scn->scn_phys.scn_func;
2624 ps->pss_state = scn->scn_phys.scn_state;
2625 ps->pss_start_time = scn->scn_phys.scn_start_time;
2626 ps->pss_end_time = scn->scn_phys.scn_end_time;
2627 ps->pss_to_examine = scn->scn_phys.scn_to_examine;
2628 ps->pss_examined = scn->scn_phys.scn_examined;
2629 ps->pss_skipped = scn->scn_phys.scn_skipped;
2630 ps->pss_processed = scn->scn_phys.scn_processed;
2631 ps->pss_errors = scn->scn_phys.scn_errors;
2632
2633 /* data not stored on disk */
2634 ps->pss_pass_exam = spa->spa_scan_pass_exam;
2635 ps->pss_pass_start = spa->spa_scan_pass_start;
2636 ps->pss_pass_scrub_pause = spa->spa_scan_pass_scrub_pause;
2637 ps->pss_pass_scrub_spent_paused = spa->spa_scan_pass_scrub_spent_paused;
2638 ps->pss_pass_issued = spa->spa_scan_pass_issued;
2639 ps->pss_issued =
2640 scn->scn_issued_before_pass + spa->spa_scan_pass_issued;
2641
2642 /* error scrub data stored on disk */
2643 ps->pss_error_scrub_func = scn->errorscrub_phys.dep_func;
2644 ps->pss_error_scrub_state = scn->errorscrub_phys.dep_state;
2645 ps->pss_error_scrub_start = scn->errorscrub_phys.dep_start_time;
2646 ps->pss_error_scrub_end = scn->errorscrub_phys.dep_end_time;
2647 ps->pss_error_scrub_examined = scn->errorscrub_phys.dep_examined;
2648 ps->pss_error_scrub_to_be_examined =
2649 scn->errorscrub_phys.dep_to_examine;
2650
2651 /* error scrub data not stored on disk */
2652 ps->pss_pass_error_scrub_pause = spa->spa_scan_pass_errorscrub_pause;
2653
2654 return (0);
2655 }
2656
2657 int
2658 spa_maxblocksize(spa_t *spa)
2659 {
2660 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
2661 return (SPA_MAXBLOCKSIZE);
2662 else
2663 return (SPA_OLD_MAXBLOCKSIZE);
2664 }
2665
2666
2667 /*
2668 * Returns the txg that the last device removal completed. No indirect mappings
2669 * have been added since this txg.
2670 */
2671 uint64_t
2672 spa_get_last_removal_txg(spa_t *spa)
2673 {
2674 uint64_t vdevid;
2675 uint64_t ret = -1ULL;
2676
2677 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2678 /*
2679 * sr_prev_indirect_vdev is only modified while holding all the
2680 * config locks, so it is sufficient to hold SCL_VDEV as reader when
2681 * examining it.
2682 */
2683 vdevid = spa->spa_removing_phys.sr_prev_indirect_vdev;
2684
2685 while (vdevid != -1ULL) {
2686 vdev_t *vd = vdev_lookup_top(spa, vdevid);
2687 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
2688
2689 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
2690
2691 /*
2692 * If the removal did not remap any data, we don't care.
2693 */
2694 if (vdev_indirect_births_count(vib) != 0) {
2695 ret = vdev_indirect_births_last_entry_txg(vib);
2696 break;
2697 }
2698
2699 vdevid = vd->vdev_indirect_config.vic_prev_indirect_vdev;
2700 }
2701 spa_config_exit(spa, SCL_VDEV, FTAG);
2702
2703 IMPLY(ret != -1ULL,
2704 spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
2705
2706 return (ret);
2707 }
2708
2709 int
2710 spa_maxdnodesize(spa_t *spa)
2711 {
2712 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE))
2713 return (DNODE_MAX_SIZE);
2714 else
2715 return (DNODE_MIN_SIZE);
2716 }
2717
2718 boolean_t
2719 spa_multihost(spa_t *spa)
2720 {
2721 return (spa->spa_multihost ? B_TRUE : B_FALSE);
2722 }
2723
2724 uint32_t
2725 spa_get_hostid(spa_t *spa)
2726 {
2727 return (spa->spa_hostid);
2728 }
2729
2730 boolean_t
2731 spa_trust_config(spa_t *spa)
2732 {
2733 return (spa->spa_trust_config);
2734 }
2735
2736 uint64_t
2737 spa_missing_tvds_allowed(spa_t *spa)
2738 {
2739 return (spa->spa_missing_tvds_allowed);
2740 }
2741
2742 space_map_t *
2743 spa_syncing_log_sm(spa_t *spa)
2744 {
2745 return (spa->spa_syncing_log_sm);
2746 }
2747
2748 void
2749 spa_set_missing_tvds(spa_t *spa, uint64_t missing)
2750 {
2751 spa->spa_missing_tvds = missing;
2752 }
2753
2754 /*
2755 * Return the pool state string ("ONLINE", "DEGRADED", "SUSPENDED", etc).
2756 */
2757 const char *
2758 spa_state_to_name(spa_t *spa)
2759 {
2760 ASSERT3P(spa, !=, NULL);
2761
2762 /*
2763 * it is possible for the spa to exist, without root vdev
2764 * as the spa transitions during import/export
2765 */
2766 vdev_t *rvd = spa->spa_root_vdev;
2767 if (rvd == NULL) {
2768 return ("TRANSITIONING");
2769 }
2770 vdev_state_t state = rvd->vdev_state;
2771 vdev_aux_t aux = rvd->vdev_stat.vs_aux;
2772
2773 if (spa_suspended(spa))
2774 return ("SUSPENDED");
2775
2776 switch (state) {
2777 case VDEV_STATE_CLOSED:
2778 case VDEV_STATE_OFFLINE:
2779 return ("OFFLINE");
2780 case VDEV_STATE_REMOVED:
2781 return ("REMOVED");
2782 case VDEV_STATE_CANT_OPEN:
2783 if (aux == VDEV_AUX_CORRUPT_DATA || aux == VDEV_AUX_BAD_LOG)
2784 return ("FAULTED");
2785 else if (aux == VDEV_AUX_SPLIT_POOL)
2786 return ("SPLIT");
2787 else
2788 return ("UNAVAIL");
2789 case VDEV_STATE_FAULTED:
2790 return ("FAULTED");
2791 case VDEV_STATE_DEGRADED:
2792 return ("DEGRADED");
2793 case VDEV_STATE_HEALTHY:
2794 return ("ONLINE");
2795 default:
2796 break;
2797 }
2798
2799 return ("UNKNOWN");
2800 }
2801
2802 boolean_t
2803 spa_top_vdevs_spacemap_addressable(spa_t *spa)
2804 {
2805 vdev_t *rvd = spa->spa_root_vdev;
2806 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
2807 if (!vdev_is_spacemap_addressable(rvd->vdev_child[c]))
2808 return (B_FALSE);
2809 }
2810 return (B_TRUE);
2811 }
2812
2813 boolean_t
2814 spa_has_checkpoint(spa_t *spa)
2815 {
2816 return (spa->spa_checkpoint_txg != 0);
2817 }
2818
2819 boolean_t
2820 spa_importing_readonly_checkpoint(spa_t *spa)
2821 {
2822 return ((spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT) &&
2823 spa->spa_mode == SPA_MODE_READ);
2824 }
2825
2826 uint64_t
2827 spa_min_claim_txg(spa_t *spa)
2828 {
2829 uint64_t checkpoint_txg = spa->spa_uberblock.ub_checkpoint_txg;
2830
2831 if (checkpoint_txg != 0)
2832 return (checkpoint_txg + 1);
2833
2834 return (spa->spa_first_txg);
2835 }
2836
2837 /*
2838 * If there is a checkpoint, async destroys may consume more space from
2839 * the pool instead of freeing it. In an attempt to save the pool from
2840 * getting suspended when it is about to run out of space, we stop
2841 * processing async destroys.
2842 */
2843 boolean_t
2844 spa_suspend_async_destroy(spa_t *spa)
2845 {
2846 dsl_pool_t *dp = spa_get_dsl(spa);
2847
2848 uint64_t unreserved = dsl_pool_unreserved_space(dp,
2849 ZFS_SPACE_CHECK_EXTRA_RESERVED);
2850 uint64_t used = dsl_dir_phys(dp->dp_root_dir)->dd_used_bytes;
2851 uint64_t avail = (unreserved > used) ? (unreserved - used) : 0;
2852
2853 if (spa_has_checkpoint(spa) && avail == 0)
2854 return (B_TRUE);
2855
2856 return (B_FALSE);
2857 }
2858
2859 #if defined(_KERNEL)
2860
2861 int
2862 param_set_deadman_failmode_common(const char *val)
2863 {
2864 spa_t *spa = NULL;
2865 char *p;
2866
2867 if (val == NULL)
2868 return (SET_ERROR(EINVAL));
2869
2870 if ((p = strchr(val, '\n')) != NULL)
2871 *p = '\0';
2872
2873 if (strcmp(val, "wait") != 0 && strcmp(val, "continue") != 0 &&
2874 strcmp(val, "panic"))
2875 return (SET_ERROR(EINVAL));
2876
2877 if (spa_mode_global != SPA_MODE_UNINIT) {
2878 mutex_enter(&spa_namespace_lock);
2879 while ((spa = spa_next(spa)) != NULL)
2880 spa_set_deadman_failmode(spa, val);
2881 mutex_exit(&spa_namespace_lock);
2882 }
2883
2884 return (0);
2885 }
2886 #endif
2887
2888 /* Namespace manipulation */
2889 EXPORT_SYMBOL(spa_lookup);
2890 EXPORT_SYMBOL(spa_add);
2891 EXPORT_SYMBOL(spa_remove);
2892 EXPORT_SYMBOL(spa_next);
2893
2894 /* Refcount functions */
2895 EXPORT_SYMBOL(spa_open_ref);
2896 EXPORT_SYMBOL(spa_close);
2897 EXPORT_SYMBOL(spa_refcount_zero);
2898
2899 /* Pool configuration lock */
2900 EXPORT_SYMBOL(spa_config_tryenter);
2901 EXPORT_SYMBOL(spa_config_enter);
2902 EXPORT_SYMBOL(spa_config_exit);
2903 EXPORT_SYMBOL(spa_config_held);
2904
2905 /* Pool vdev add/remove lock */
2906 EXPORT_SYMBOL(spa_vdev_enter);
2907 EXPORT_SYMBOL(spa_vdev_exit);
2908
2909 /* Pool vdev state change lock */
2910 EXPORT_SYMBOL(spa_vdev_state_enter);
2911 EXPORT_SYMBOL(spa_vdev_state_exit);
2912
2913 /* Accessor functions */
2914 EXPORT_SYMBOL(spa_shutting_down);
2915 EXPORT_SYMBOL(spa_get_dsl);
2916 EXPORT_SYMBOL(spa_get_rootblkptr);
2917 EXPORT_SYMBOL(spa_set_rootblkptr);
2918 EXPORT_SYMBOL(spa_altroot);
2919 EXPORT_SYMBOL(spa_sync_pass);
2920 EXPORT_SYMBOL(spa_name);
2921 EXPORT_SYMBOL(spa_guid);
2922 EXPORT_SYMBOL(spa_last_synced_txg);
2923 EXPORT_SYMBOL(spa_first_txg);
2924 EXPORT_SYMBOL(spa_syncing_txg);
2925 EXPORT_SYMBOL(spa_version);
2926 EXPORT_SYMBOL(spa_state);
2927 EXPORT_SYMBOL(spa_load_state);
2928 EXPORT_SYMBOL(spa_freeze_txg);
2929 EXPORT_SYMBOL(spa_get_dspace);
2930 EXPORT_SYMBOL(spa_update_dspace);
2931 EXPORT_SYMBOL(spa_deflate);
2932 EXPORT_SYMBOL(spa_normal_class);
2933 EXPORT_SYMBOL(spa_log_class);
2934 EXPORT_SYMBOL(spa_special_class);
2935 EXPORT_SYMBOL(spa_preferred_class);
2936 EXPORT_SYMBOL(spa_max_replication);
2937 EXPORT_SYMBOL(spa_prev_software_version);
2938 EXPORT_SYMBOL(spa_get_failmode);
2939 EXPORT_SYMBOL(spa_suspended);
2940 EXPORT_SYMBOL(spa_bootfs);
2941 EXPORT_SYMBOL(spa_delegation);
2942 EXPORT_SYMBOL(spa_meta_objset);
2943 EXPORT_SYMBOL(spa_maxblocksize);
2944 EXPORT_SYMBOL(spa_maxdnodesize);
2945
2946 /* Miscellaneous support routines */
2947 EXPORT_SYMBOL(spa_guid_exists);
2948 EXPORT_SYMBOL(spa_strdup);
2949 EXPORT_SYMBOL(spa_strfree);
2950 EXPORT_SYMBOL(spa_generate_guid);
2951 EXPORT_SYMBOL(snprintf_blkptr);
2952 EXPORT_SYMBOL(spa_freeze);
2953 EXPORT_SYMBOL(spa_upgrade);
2954 EXPORT_SYMBOL(spa_evict_all);
2955 EXPORT_SYMBOL(spa_lookup_by_guid);
2956 EXPORT_SYMBOL(spa_has_spare);
2957 EXPORT_SYMBOL(dva_get_dsize_sync);
2958 EXPORT_SYMBOL(bp_get_dsize_sync);
2959 EXPORT_SYMBOL(bp_get_dsize);
2960 EXPORT_SYMBOL(spa_has_slogs);
2961 EXPORT_SYMBOL(spa_is_root);
2962 EXPORT_SYMBOL(spa_writeable);
2963 EXPORT_SYMBOL(spa_mode);
2964 EXPORT_SYMBOL(spa_namespace_lock);
2965 EXPORT_SYMBOL(spa_trust_config);
2966 EXPORT_SYMBOL(spa_missing_tvds_allowed);
2967 EXPORT_SYMBOL(spa_set_missing_tvds);
2968 EXPORT_SYMBOL(spa_state_to_name);
2969 EXPORT_SYMBOL(spa_importing_readonly_checkpoint);
2970 EXPORT_SYMBOL(spa_min_claim_txg);
2971 EXPORT_SYMBOL(spa_suspend_async_destroy);
2972 EXPORT_SYMBOL(spa_has_checkpoint);
2973 EXPORT_SYMBOL(spa_top_vdevs_spacemap_addressable);
2974
2975 ZFS_MODULE_PARAM(zfs, zfs_, flags, UINT, ZMOD_RW,
2976 "Set additional debugging flags");
2977
2978 ZFS_MODULE_PARAM(zfs, zfs_, recover, INT, ZMOD_RW,
2979 "Set to attempt to recover from fatal errors");
2980
2981 ZFS_MODULE_PARAM(zfs, zfs_, free_leak_on_eio, INT, ZMOD_RW,
2982 "Set to ignore IO errors during free and permanently leak the space");
2983
2984 ZFS_MODULE_PARAM(zfs_deadman, zfs_deadman_, checktime_ms, U64, ZMOD_RW,
2985 "Dead I/O check interval in milliseconds");
2986
2987 ZFS_MODULE_PARAM(zfs_deadman, zfs_deadman_, enabled, INT, ZMOD_RW,
2988 "Enable deadman timer");
2989
2990 ZFS_MODULE_PARAM(zfs_spa, spa_, asize_inflation, UINT, ZMOD_RW,
2991 "SPA size estimate multiplication factor");
2992
2993 ZFS_MODULE_PARAM(zfs, zfs_, ddt_data_is_special, INT, ZMOD_RW,
2994 "Place DDT data into the special class");
2995
2996 ZFS_MODULE_PARAM(zfs, zfs_, user_indirect_is_special, INT, ZMOD_RW,
2997 "Place user data indirect blocks into the special class");
2998
2999 /* BEGIN CSTYLED */
3000 ZFS_MODULE_PARAM_CALL(zfs_deadman, zfs_deadman_, failmode,
3001 param_set_deadman_failmode, param_get_charp, ZMOD_RW,
3002 "Failmode for deadman timer");
3003
3004 ZFS_MODULE_PARAM_CALL(zfs_deadman, zfs_deadman_, synctime_ms,
3005 param_set_deadman_synctime, spl_param_get_u64, ZMOD_RW,
3006 "Pool sync expiration time in milliseconds");
3007
3008 ZFS_MODULE_PARAM_CALL(zfs_deadman, zfs_deadman_, ziotime_ms,
3009 param_set_deadman_ziotime, spl_param_get_u64, ZMOD_RW,
3010 "IO expiration time in milliseconds");
3011
3012 ZFS_MODULE_PARAM(zfs, zfs_, special_class_metadata_reserve_pct, UINT, ZMOD_RW,
3013 "Small file blocks in special vdevs depends on this much "
3014 "free space available");
3015 /* END CSTYLED */
3016
3017 ZFS_MODULE_PARAM_CALL(zfs_spa, spa_, slop_shift, param_set_slop_shift,
3018 param_get_uint, ZMOD_RW, "Reserved free space in pool");
3019
3020 ZFS_MODULE_PARAM(zfs, spa_, num_allocators, INT, ZMOD_RW,
3021 "Number of allocators per spa, capped by ncpus");