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