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