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