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