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