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