xref: /illumos-gate/usr/src/uts/common/fs/zfs/spa_misc.c (revision d1aea6f139360e9e7f1504facb24f8521047b15c)
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, 2017 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  */
29 
30 #include <sys/zfs_context.h>
31 #include <sys/spa_impl.h>
32 #include <sys/spa_boot.h>
33 #include <sys/zio.h>
34 #include <sys/zio_checksum.h>
35 #include <sys/zio_compress.h>
36 #include <sys/dmu.h>
37 #include <sys/dmu_tx.h>
38 #include <sys/zap.h>
39 #include <sys/zil.h>
40 #include <sys/vdev_impl.h>
41 #include <sys/metaslab.h>
42 #include <sys/uberblock_impl.h>
43 #include <sys/txg.h>
44 #include <sys/avl.h>
45 #include <sys/unique.h>
46 #include <sys/dsl_pool.h>
47 #include <sys/dsl_dir.h>
48 #include <sys/dsl_prop.h>
49 #include <sys/dsl_scan.h>
50 #include <sys/fs/zfs.h>
51 #include <sys/metaslab_impl.h>
52 #include <sys/arc.h>
53 #include <sys/ddt.h>
54 #include "zfs_prop.h"
55 #include <sys/zfeature.h>
56 
57 /*
58  * SPA locking
59  *
60  * There are four basic locks for managing spa_t structures:
61  *
62  * spa_namespace_lock (global mutex)
63  *
64  *	This lock must be acquired to do any of the following:
65  *
66  *		- Lookup a spa_t by name
67  *		- Add or remove a spa_t from the namespace
68  *		- Increase spa_refcount from non-zero
69  *		- Check if spa_refcount is zero
70  *		- Rename a spa_t
71  *		- add/remove/attach/detach devices
72  *		- Held for the duration of create/destroy/import/export
73  *
74  *	It does not need to handle recursion.  A create or destroy may
75  *	reference objects (files or zvols) in other pools, but by
76  *	definition they must have an existing reference, and will never need
77  *	to lookup a spa_t by name.
78  *
79  * spa_refcount (per-spa refcount_t protected by mutex)
80  *
81  *	This reference count keep track of any active users of the spa_t.  The
82  *	spa_t cannot be destroyed or freed while this is non-zero.  Internally,
83  *	the refcount is never really 'zero' - opening a pool implicitly keeps
84  *	some references in the DMU.  Internally we check against spa_minref, but
85  *	present the image of a zero/non-zero value to consumers.
86  *
87  * spa_config_lock[] (per-spa array of rwlocks)
88  *
89  *	This protects the spa_t from config changes, and must be held in
90  *	the following circumstances:
91  *
92  *		- RW_READER to perform I/O to the spa
93  *		- RW_WRITER to change the vdev config
94  *
95  * The locking order is fairly straightforward:
96  *
97  *		spa_namespace_lock	->	spa_refcount
98  *
99  *	The namespace lock must be acquired to increase the refcount from 0
100  *	or to check if it is zero.
101  *
102  *		spa_refcount		->	spa_config_lock[]
103  *
104  *	There must be at least one valid reference on the spa_t to acquire
105  *	the config lock.
106  *
107  *		spa_namespace_lock	->	spa_config_lock[]
108  *
109  *	The namespace lock must always be taken before the config lock.
110  *
111  *
112  * The spa_namespace_lock can be acquired directly and is globally visible.
113  *
114  * The namespace is manipulated using the following functions, all of which
115  * require the spa_namespace_lock to be held.
116  *
117  *	spa_lookup()		Lookup a spa_t by name.
118  *
119  *	spa_add()		Create a new spa_t in the namespace.
120  *
121  *	spa_remove()		Remove a spa_t from the namespace.  This also
122  *				frees up any memory associated with the spa_t.
123  *
124  *	spa_next()		Returns the next spa_t in the system, or the
125  *				first if NULL is passed.
126  *
127  *	spa_evict_all()		Shutdown and remove all spa_t structures in
128  *				the system.
129  *
130  *	spa_guid_exists()	Determine whether a pool/device guid exists.
131  *
132  * The spa_refcount is manipulated using the following functions:
133  *
134  *	spa_open_ref()		Adds a reference to the given spa_t.  Must be
135  *				called with spa_namespace_lock held if the
136  *				refcount is currently zero.
137  *
138  *	spa_close()		Remove a reference from the spa_t.  This will
139  *				not free the spa_t or remove it from the
140  *				namespace.  No locking is required.
141  *
142  *	spa_refcount_zero()	Returns true if the refcount is currently
143  *				zero.  Must be called with spa_namespace_lock
144  *				held.
145  *
146  * The spa_config_lock[] is an array of rwlocks, ordered as follows:
147  * SCL_CONFIG > SCL_STATE > SCL_ALLOC > SCL_ZIO > SCL_FREE > SCL_VDEV.
148  * spa_config_lock[] is manipulated with spa_config_{enter,exit,held}().
149  *
150  * To read the configuration, it suffices to hold one of these locks as reader.
151  * To modify the configuration, you must hold all locks as writer.  To modify
152  * vdev state without altering the vdev tree's topology (e.g. online/offline),
153  * you must hold SCL_STATE and SCL_ZIO as writer.
154  *
155  * We use these distinct config locks to avoid recursive lock entry.
156  * For example, spa_sync() (which holds SCL_CONFIG as reader) induces
157  * block allocations (SCL_ALLOC), which may require reading space maps
158  * from disk (dmu_read() -> zio_read() -> SCL_ZIO).
159  *
160  * The spa config locks cannot be normal rwlocks because we need the
161  * ability to hand off ownership.  For example, SCL_ZIO is acquired
162  * by the issuing thread and later released by an interrupt thread.
163  * They do, however, obey the usual write-wanted semantics to prevent
164  * writer (i.e. system administrator) starvation.
165  *
166  * The lock acquisition rules are as follows:
167  *
168  * SCL_CONFIG
169  *	Protects changes to the vdev tree topology, such as vdev
170  *	add/remove/attach/detach.  Protects the dirty config list
171  *	(spa_config_dirty_list) and the set of spares and l2arc devices.
172  *
173  * SCL_STATE
174  *	Protects changes to pool state and vdev state, such as vdev
175  *	online/offline/fault/degrade/clear.  Protects the dirty state list
176  *	(spa_state_dirty_list) and global pool state (spa_state).
177  *
178  * SCL_ALLOC
179  *	Protects changes to metaslab groups and classes.
180  *	Held as reader by metaslab_alloc() and metaslab_claim().
181  *
182  * SCL_ZIO
183  *	Held by bp-level zios (those which have no io_vd upon entry)
184  *	to prevent changes to the vdev tree.  The bp-level zio implicitly
185  *	protects all of its vdev child zios, which do not hold SCL_ZIO.
186  *
187  * SCL_FREE
188  *	Protects changes to metaslab groups and classes.
189  *	Held as reader by metaslab_free().  SCL_FREE is distinct from
190  *	SCL_ALLOC, and lower than SCL_ZIO, so that we can safely free
191  *	blocks in zio_done() while another i/o that holds either
192  *	SCL_ALLOC or SCL_ZIO is waiting for this i/o to complete.
193  *
194  * SCL_VDEV
195  *	Held as reader to prevent changes to the vdev tree during trivial
196  *	inquiries such as bp_get_dsize().  SCL_VDEV is distinct from the
197  *	other locks, and lower than all of them, to ensure that it's safe
198  *	to acquire regardless of caller context.
199  *
200  * In addition, the following rules apply:
201  *
202  * (a)	spa_props_lock protects pool properties, spa_config and spa_config_list.
203  *	The lock ordering is SCL_CONFIG > spa_props_lock.
204  *
205  * (b)	I/O operations on leaf vdevs.  For any zio operation that takes
206  *	an explicit vdev_t argument -- such as zio_ioctl(), zio_read_phys(),
207  *	or zio_write_phys() -- the caller must ensure that the config cannot
208  *	cannot change in the interim, and that the vdev cannot be reopened.
209  *	SCL_STATE as reader suffices for both.
210  *
211  * The vdev configuration is protected by spa_vdev_enter() / spa_vdev_exit().
212  *
213  *	spa_vdev_enter()	Acquire the namespace lock and the config lock
214  *				for writing.
215  *
216  *	spa_vdev_exit()		Release the config lock, wait for all I/O
217  *				to complete, sync the updated configs to the
218  *				cache, and release the namespace lock.
219  *
220  * vdev state is protected by spa_vdev_state_enter() / spa_vdev_state_exit().
221  * Like spa_vdev_enter/exit, these are convenience wrappers -- the actual
222  * locking is, always, based on spa_namespace_lock and spa_config_lock[].
223  *
224  * spa_rename() is also implemented within this file since it requires
225  * manipulation of the namespace.
226  */
227 
228 static avl_tree_t spa_namespace_avl;
229 kmutex_t spa_namespace_lock;
230 static kcondvar_t spa_namespace_cv;
231 static int spa_active_count;
232 int spa_max_replication_override = SPA_DVAS_PER_BP;
233 
234 static kmutex_t spa_spare_lock;
235 static avl_tree_t spa_spare_avl;
236 static kmutex_t spa_l2cache_lock;
237 static avl_tree_t spa_l2cache_avl;
238 
239 kmem_cache_t *spa_buffer_pool;
240 int spa_mode_global;
241 
242 #ifdef ZFS_DEBUG
243 /* Everything except dprintf and spa is on by default in debug builds */
244 int zfs_flags = ~(ZFS_DEBUG_DPRINTF | ZFS_DEBUG_SPA);
245 #else
246 int zfs_flags = 0;
247 #endif
248 
249 /*
250  * zfs_recover can be set to nonzero to attempt to recover from
251  * otherwise-fatal errors, typically caused by on-disk corruption.  When
252  * set, calls to zfs_panic_recover() will turn into warning messages.
253  * This should only be used as a last resort, as it typically results
254  * in leaked space, or worse.
255  */
256 boolean_t zfs_recover = B_FALSE;
257 
258 /*
259  * If destroy encounters an EIO while reading metadata (e.g. indirect
260  * blocks), space referenced by the missing metadata can not be freed.
261  * Normally this causes the background destroy to become "stalled", as
262  * it is unable to make forward progress.  While in this stalled state,
263  * all remaining space to free from the error-encountering filesystem is
264  * "temporarily leaked".  Set this flag to cause it to ignore the EIO,
265  * permanently leak the space from indirect blocks that can not be read,
266  * and continue to free everything else that it can.
267  *
268  * The default, "stalling" behavior is useful if the storage partially
269  * fails (i.e. some but not all i/os fail), and then later recovers.  In
270  * this case, we will be able to continue pool operations while it is
271  * partially failed, and when it recovers, we can continue to free the
272  * space, with no leaks.  However, note that this case is actually
273  * fairly rare.
274  *
275  * Typically pools either (a) fail completely (but perhaps temporarily,
276  * e.g. a top-level vdev going offline), or (b) have localized,
277  * permanent errors (e.g. disk returns the wrong data due to bit flip or
278  * firmware bug).  In case (a), this setting does not matter because the
279  * pool will be suspended and the sync thread will not be able to make
280  * forward progress regardless.  In case (b), because the error is
281  * permanent, the best we can do is leak the minimum amount of space,
282  * which is what setting this flag will do.  Therefore, it is reasonable
283  * for this flag to normally be set, but we chose the more conservative
284  * approach of not setting it, so that there is no possibility of
285  * leaking space in the "partial temporary" failure case.
286  */
287 boolean_t zfs_free_leak_on_eio = B_FALSE;
288 
289 /*
290  * Expiration time in milliseconds. This value has two meanings. First it is
291  * used to determine when the spa_deadman() logic should fire. By default the
292  * spa_deadman() will fire if spa_sync() has not completed in 1000 seconds.
293  * Secondly, the value determines if an I/O is considered "hung". Any I/O that
294  * has not completed in zfs_deadman_synctime_ms is considered "hung" resulting
295  * in a system panic.
296  */
297 uint64_t zfs_deadman_synctime_ms = 1000000ULL;
298 
299 /*
300  * Check time in milliseconds. This defines the frequency at which we check
301  * for hung I/O.
302  */
303 uint64_t zfs_deadman_checktime_ms = 5000ULL;
304 
305 /*
306  * Override the zfs deadman behavior via /etc/system. By default the
307  * deadman is enabled except on VMware and sparc deployments.
308  */
309 int zfs_deadman_enabled = -1;
310 
311 /*
312  * The worst case is single-sector max-parity RAID-Z blocks, in which
313  * case the space requirement is exactly (VDEV_RAIDZ_MAXPARITY + 1)
314  * times the size; so just assume that.  Add to this the fact that
315  * we can have up to 3 DVAs per bp, and one more factor of 2 because
316  * the block may be dittoed with up to 3 DVAs by ddt_sync().  All together,
317  * the worst case is:
318  *     (VDEV_RAIDZ_MAXPARITY + 1) * SPA_DVAS_PER_BP * 2 == 24
319  */
320 int spa_asize_inflation = 24;
321 
322 /*
323  * Normally, we don't allow the last 3.2% (1/(2^spa_slop_shift)) of space in
324  * the pool to be consumed.  This ensures that we don't run the pool
325  * completely out of space, due to unaccounted changes (e.g. to the MOS).
326  * It also limits the worst-case time to allocate space.  If we have
327  * less than this amount of free space, most ZPL operations (e.g. write,
328  * create) will return ENOSPC.
329  *
330  * Certain operations (e.g. file removal, most administrative actions) can
331  * use half the slop space.  They will only return ENOSPC if less than half
332  * the slop space is free.  Typically, once the pool has less than the slop
333  * space free, the user will use these operations to free up space in the pool.
334  * These are the operations that call dsl_pool_adjustedsize() with the netfree
335  * argument set to TRUE.
336  *
337  * A very restricted set of operations are always permitted, regardless of
338  * the amount of free space.  These are the operations that call
339  * dsl_sync_task(ZFS_SPACE_CHECK_NONE), e.g. "zfs destroy".  If these
340  * operations result in a net increase in the amount of space used,
341  * it is possible to run the pool completely out of space, causing it to
342  * be permanently read-only.
343  *
344  * Note that on very small pools, the slop space will be larger than
345  * 3.2%, in an effort to have it be at least spa_min_slop (128MB),
346  * but we never allow it to be more than half the pool size.
347  *
348  * See also the comments in zfs_space_check_t.
349  */
350 int spa_slop_shift = 5;
351 uint64_t spa_min_slop = 128 * 1024 * 1024;
352 
353 /*
354  * ==========================================================================
355  * SPA config locking
356  * ==========================================================================
357  */
358 static void
359 spa_config_lock_init(spa_t *spa)
360 {
361 	for (int i = 0; i < SCL_LOCKS; i++) {
362 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
363 		mutex_init(&scl->scl_lock, NULL, MUTEX_DEFAULT, NULL);
364 		cv_init(&scl->scl_cv, NULL, CV_DEFAULT, NULL);
365 		refcount_create_untracked(&scl->scl_count);
366 		scl->scl_writer = NULL;
367 		scl->scl_write_wanted = 0;
368 	}
369 }
370 
371 static void
372 spa_config_lock_destroy(spa_t *spa)
373 {
374 	for (int i = 0; i < SCL_LOCKS; i++) {
375 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
376 		mutex_destroy(&scl->scl_lock);
377 		cv_destroy(&scl->scl_cv);
378 		refcount_destroy(&scl->scl_count);
379 		ASSERT(scl->scl_writer == NULL);
380 		ASSERT(scl->scl_write_wanted == 0);
381 	}
382 }
383 
384 int
385 spa_config_tryenter(spa_t *spa, int locks, void *tag, krw_t rw)
386 {
387 	for (int i = 0; i < SCL_LOCKS; i++) {
388 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
389 		if (!(locks & (1 << i)))
390 			continue;
391 		mutex_enter(&scl->scl_lock);
392 		if (rw == RW_READER) {
393 			if (scl->scl_writer || scl->scl_write_wanted) {
394 				mutex_exit(&scl->scl_lock);
395 				spa_config_exit(spa, locks & ((1 << i) - 1),
396 				    tag);
397 				return (0);
398 			}
399 		} else {
400 			ASSERT(scl->scl_writer != curthread);
401 			if (!refcount_is_zero(&scl->scl_count)) {
402 				mutex_exit(&scl->scl_lock);
403 				spa_config_exit(spa, locks & ((1 << i) - 1),
404 				    tag);
405 				return (0);
406 			}
407 			scl->scl_writer = curthread;
408 		}
409 		(void) refcount_add(&scl->scl_count, tag);
410 		mutex_exit(&scl->scl_lock);
411 	}
412 	return (1);
413 }
414 
415 void
416 spa_config_enter(spa_t *spa, int locks, void *tag, krw_t rw)
417 {
418 	int wlocks_held = 0;
419 
420 	ASSERT3U(SCL_LOCKS, <, sizeof (wlocks_held) * NBBY);
421 
422 	for (int i = 0; i < SCL_LOCKS; i++) {
423 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
424 		if (scl->scl_writer == curthread)
425 			wlocks_held |= (1 << i);
426 		if (!(locks & (1 << i)))
427 			continue;
428 		mutex_enter(&scl->scl_lock);
429 		if (rw == RW_READER) {
430 			while (scl->scl_writer || scl->scl_write_wanted) {
431 				cv_wait(&scl->scl_cv, &scl->scl_lock);
432 			}
433 		} else {
434 			ASSERT(scl->scl_writer != curthread);
435 			while (!refcount_is_zero(&scl->scl_count)) {
436 				scl->scl_write_wanted++;
437 				cv_wait(&scl->scl_cv, &scl->scl_lock);
438 				scl->scl_write_wanted--;
439 			}
440 			scl->scl_writer = curthread;
441 		}
442 		(void) refcount_add(&scl->scl_count, tag);
443 		mutex_exit(&scl->scl_lock);
444 	}
445 	ASSERT(wlocks_held <= locks);
446 }
447 
448 void
449 spa_config_exit(spa_t *spa, int locks, void *tag)
450 {
451 	for (int i = SCL_LOCKS - 1; i >= 0; i--) {
452 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
453 		if (!(locks & (1 << i)))
454 			continue;
455 		mutex_enter(&scl->scl_lock);
456 		ASSERT(!refcount_is_zero(&scl->scl_count));
457 		if (refcount_remove(&scl->scl_count, tag) == 0) {
458 			ASSERT(scl->scl_writer == NULL ||
459 			    scl->scl_writer == curthread);
460 			scl->scl_writer = NULL;	/* OK in either case */
461 			cv_broadcast(&scl->scl_cv);
462 		}
463 		mutex_exit(&scl->scl_lock);
464 	}
465 }
466 
467 int
468 spa_config_held(spa_t *spa, int locks, krw_t rw)
469 {
470 	int locks_held = 0;
471 
472 	for (int i = 0; i < SCL_LOCKS; i++) {
473 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
474 		if (!(locks & (1 << i)))
475 			continue;
476 		if ((rw == RW_READER && !refcount_is_zero(&scl->scl_count)) ||
477 		    (rw == RW_WRITER && scl->scl_writer == curthread))
478 			locks_held |= 1 << i;
479 	}
480 
481 	return (locks_held);
482 }
483 
484 /*
485  * ==========================================================================
486  * SPA namespace functions
487  * ==========================================================================
488  */
489 
490 /*
491  * Lookup the named spa_t in the AVL tree.  The spa_namespace_lock must be held.
492  * Returns NULL if no matching spa_t is found.
493  */
494 spa_t *
495 spa_lookup(const char *name)
496 {
497 	static spa_t search;	/* spa_t is large; don't allocate on stack */
498 	spa_t *spa;
499 	avl_index_t where;
500 	char *cp;
501 
502 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
503 
504 	(void) strlcpy(search.spa_name, name, sizeof (search.spa_name));
505 
506 	/*
507 	 * If it's a full dataset name, figure out the pool name and
508 	 * just use that.
509 	 */
510 	cp = strpbrk(search.spa_name, "/@#");
511 	if (cp != NULL)
512 		*cp = '\0';
513 
514 	spa = avl_find(&spa_namespace_avl, &search, &where);
515 
516 	return (spa);
517 }
518 
519 /*
520  * Fires when spa_sync has not completed within zfs_deadman_synctime_ms.
521  * If the zfs_deadman_enabled flag is set then it inspects all vdev queues
522  * looking for potentially hung I/Os.
523  */
524 void
525 spa_deadman(void *arg)
526 {
527 	spa_t *spa = arg;
528 
529 	/*
530 	 * Disable the deadman timer if the pool is suspended.
531 	 */
532 	if (spa_suspended(spa)) {
533 		VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
534 		return;
535 	}
536 
537 	zfs_dbgmsg("slow spa_sync: started %llu seconds ago, calls %llu",
538 	    (gethrtime() - spa->spa_sync_starttime) / NANOSEC,
539 	    ++spa->spa_deadman_calls);
540 	if (zfs_deadman_enabled)
541 		vdev_deadman(spa->spa_root_vdev);
542 }
543 
544 /*
545  * Create an uninitialized spa_t with the given name.  Requires
546  * spa_namespace_lock.  The caller must ensure that the spa_t doesn't already
547  * exist by calling spa_lookup() first.
548  */
549 spa_t *
550 spa_add(const char *name, nvlist_t *config, const char *altroot)
551 {
552 	spa_t *spa;
553 	spa_config_dirent_t *dp;
554 	cyc_handler_t hdlr;
555 	cyc_time_t when;
556 
557 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
558 
559 	spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
560 
561 	mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
562 	mutex_init(&spa->spa_errlist_lock, NULL, MUTEX_DEFAULT, NULL);
563 	mutex_init(&spa->spa_errlog_lock, NULL, MUTEX_DEFAULT, NULL);
564 	mutex_init(&spa->spa_evicting_os_lock, NULL, MUTEX_DEFAULT, NULL);
565 	mutex_init(&spa->spa_history_lock, NULL, MUTEX_DEFAULT, NULL);
566 	mutex_init(&spa->spa_proc_lock, NULL, MUTEX_DEFAULT, NULL);
567 	mutex_init(&spa->spa_props_lock, NULL, MUTEX_DEFAULT, NULL);
568 	mutex_init(&spa->spa_cksum_tmpls_lock, NULL, MUTEX_DEFAULT, NULL);
569 	mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
570 	mutex_init(&spa->spa_suspend_lock, NULL, MUTEX_DEFAULT, NULL);
571 	mutex_init(&spa->spa_vdev_top_lock, NULL, MUTEX_DEFAULT, NULL);
572 	mutex_init(&spa->spa_iokstat_lock, NULL, MUTEX_DEFAULT, NULL);
573 	mutex_init(&spa->spa_alloc_lock, NULL, MUTEX_DEFAULT, NULL);
574 
575 	cv_init(&spa->spa_async_cv, NULL, CV_DEFAULT, NULL);
576 	cv_init(&spa->spa_evicting_os_cv, NULL, CV_DEFAULT, NULL);
577 	cv_init(&spa->spa_proc_cv, NULL, CV_DEFAULT, NULL);
578 	cv_init(&spa->spa_scrub_io_cv, NULL, CV_DEFAULT, NULL);
579 	cv_init(&spa->spa_suspend_cv, NULL, CV_DEFAULT, NULL);
580 
581 	for (int t = 0; t < TXG_SIZE; t++)
582 		bplist_create(&spa->spa_free_bplist[t]);
583 
584 	(void) strlcpy(spa->spa_name, name, sizeof (spa->spa_name));
585 	spa->spa_state = POOL_STATE_UNINITIALIZED;
586 	spa->spa_freeze_txg = UINT64_MAX;
587 	spa->spa_final_txg = UINT64_MAX;
588 	spa->spa_load_max_txg = UINT64_MAX;
589 	spa->spa_proc = &p0;
590 	spa->spa_proc_state = SPA_PROC_NONE;
591 
592 	hdlr.cyh_func = spa_deadman;
593 	hdlr.cyh_arg = spa;
594 	hdlr.cyh_level = CY_LOW_LEVEL;
595 
596 	spa->spa_deadman_synctime = MSEC2NSEC(zfs_deadman_synctime_ms);
597 
598 	/*
599 	 * This determines how often we need to check for hung I/Os after
600 	 * the cyclic has already fired. Since checking for hung I/Os is
601 	 * an expensive operation we don't want to check too frequently.
602 	 * Instead wait for 5 seconds before checking again.
603 	 */
604 	when.cyt_interval = MSEC2NSEC(zfs_deadman_checktime_ms);
605 	when.cyt_when = CY_INFINITY;
606 	mutex_enter(&cpu_lock);
607 	spa->spa_deadman_cycid = cyclic_add(&hdlr, &when);
608 	mutex_exit(&cpu_lock);
609 
610 	refcount_create(&spa->spa_refcount);
611 	spa_config_lock_init(spa);
612 
613 	avl_add(&spa_namespace_avl, spa);
614 
615 	/*
616 	 * Set the alternate root, if there is one.
617 	 */
618 	if (altroot) {
619 		spa->spa_root = spa_strdup(altroot);
620 		spa_active_count++;
621 	}
622 
623 	avl_create(&spa->spa_alloc_tree, zio_bookmark_compare,
624 	    sizeof (zio_t), offsetof(zio_t, io_alloc_node));
625 
626 	/*
627 	 * Every pool starts with the default cachefile
628 	 */
629 	list_create(&spa->spa_config_list, sizeof (spa_config_dirent_t),
630 	    offsetof(spa_config_dirent_t, scd_link));
631 
632 	dp = kmem_zalloc(sizeof (spa_config_dirent_t), KM_SLEEP);
633 	dp->scd_path = altroot ? NULL : spa_strdup(spa_config_path);
634 	list_insert_head(&spa->spa_config_list, dp);
635 
636 	VERIFY(nvlist_alloc(&spa->spa_load_info, NV_UNIQUE_NAME,
637 	    KM_SLEEP) == 0);
638 
639 	if (config != NULL) {
640 		nvlist_t *features;
641 
642 		if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_FEATURES_FOR_READ,
643 		    &features) == 0) {
644 			VERIFY(nvlist_dup(features, &spa->spa_label_features,
645 			    0) == 0);
646 		}
647 
648 		VERIFY(nvlist_dup(config, &spa->spa_config, 0) == 0);
649 	}
650 
651 	if (spa->spa_label_features == NULL) {
652 		VERIFY(nvlist_alloc(&spa->spa_label_features, NV_UNIQUE_NAME,
653 		    KM_SLEEP) == 0);
654 	}
655 
656 	spa->spa_iokstat = kstat_create("zfs", 0, name,
657 	    "disk", KSTAT_TYPE_IO, 1, 0);
658 	if (spa->spa_iokstat) {
659 		spa->spa_iokstat->ks_lock = &spa->spa_iokstat_lock;
660 		kstat_install(spa->spa_iokstat);
661 	}
662 
663 	spa->spa_debug = ((zfs_flags & ZFS_DEBUG_SPA) != 0);
664 
665 	spa->spa_min_ashift = INT_MAX;
666 	spa->spa_max_ashift = 0;
667 
668 	/*
669 	 * As a pool is being created, treat all features as disabled by
670 	 * setting SPA_FEATURE_DISABLED for all entries in the feature
671 	 * refcount cache.
672 	 */
673 	for (int i = 0; i < SPA_FEATURES; i++) {
674 		spa->spa_feat_refcount_cache[i] = SPA_FEATURE_DISABLED;
675 	}
676 
677 	return (spa);
678 }
679 
680 /*
681  * Removes a spa_t from the namespace, freeing up any memory used.  Requires
682  * spa_namespace_lock.  This is called only after the spa_t has been closed and
683  * deactivated.
684  */
685 void
686 spa_remove(spa_t *spa)
687 {
688 	spa_config_dirent_t *dp;
689 
690 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
691 	ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
692 	ASSERT3U(refcount_count(&spa->spa_refcount), ==, 0);
693 
694 	nvlist_free(spa->spa_config_splitting);
695 
696 	avl_remove(&spa_namespace_avl, spa);
697 	cv_broadcast(&spa_namespace_cv);
698 
699 	if (spa->spa_root) {
700 		spa_strfree(spa->spa_root);
701 		spa_active_count--;
702 	}
703 
704 	while ((dp = list_head(&spa->spa_config_list)) != NULL) {
705 		list_remove(&spa->spa_config_list, dp);
706 		if (dp->scd_path != NULL)
707 			spa_strfree(dp->scd_path);
708 		kmem_free(dp, sizeof (spa_config_dirent_t));
709 	}
710 
711 	avl_destroy(&spa->spa_alloc_tree);
712 	list_destroy(&spa->spa_config_list);
713 
714 	nvlist_free(spa->spa_label_features);
715 	nvlist_free(spa->spa_load_info);
716 	spa_config_set(spa, NULL);
717 
718 	mutex_enter(&cpu_lock);
719 	if (spa->spa_deadman_cycid != CYCLIC_NONE)
720 		cyclic_remove(spa->spa_deadman_cycid);
721 	mutex_exit(&cpu_lock);
722 	spa->spa_deadman_cycid = CYCLIC_NONE;
723 
724 	refcount_destroy(&spa->spa_refcount);
725 
726 	spa_config_lock_destroy(spa);
727 
728 	kstat_delete(spa->spa_iokstat);
729 	spa->spa_iokstat = NULL;
730 
731 	for (int t = 0; t < TXG_SIZE; t++)
732 		bplist_destroy(&spa->spa_free_bplist[t]);
733 
734 	zio_checksum_templates_free(spa);
735 
736 	cv_destroy(&spa->spa_async_cv);
737 	cv_destroy(&spa->spa_evicting_os_cv);
738 	cv_destroy(&spa->spa_proc_cv);
739 	cv_destroy(&spa->spa_scrub_io_cv);
740 	cv_destroy(&spa->spa_suspend_cv);
741 
742 	mutex_destroy(&spa->spa_alloc_lock);
743 	mutex_destroy(&spa->spa_async_lock);
744 	mutex_destroy(&spa->spa_errlist_lock);
745 	mutex_destroy(&spa->spa_errlog_lock);
746 	mutex_destroy(&spa->spa_evicting_os_lock);
747 	mutex_destroy(&spa->spa_history_lock);
748 	mutex_destroy(&spa->spa_proc_lock);
749 	mutex_destroy(&spa->spa_props_lock);
750 	mutex_destroy(&spa->spa_cksum_tmpls_lock);
751 	mutex_destroy(&spa->spa_scrub_lock);
752 	mutex_destroy(&spa->spa_suspend_lock);
753 	mutex_destroy(&spa->spa_vdev_top_lock);
754 	mutex_destroy(&spa->spa_iokstat_lock);
755 
756 	kmem_free(spa, sizeof (spa_t));
757 }
758 
759 /*
760  * Given a pool, return the next pool in the namespace, or NULL if there is
761  * none.  If 'prev' is NULL, return the first pool.
762  */
763 spa_t *
764 spa_next(spa_t *prev)
765 {
766 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
767 
768 	if (prev)
769 		return (AVL_NEXT(&spa_namespace_avl, prev));
770 	else
771 		return (avl_first(&spa_namespace_avl));
772 }
773 
774 /*
775  * ==========================================================================
776  * SPA refcount functions
777  * ==========================================================================
778  */
779 
780 /*
781  * Add a reference to the given spa_t.  Must have at least one reference, or
782  * have the namespace lock held.
783  */
784 void
785 spa_open_ref(spa_t *spa, void *tag)
786 {
787 	ASSERT(refcount_count(&spa->spa_refcount) >= spa->spa_minref ||
788 	    MUTEX_HELD(&spa_namespace_lock));
789 	(void) refcount_add(&spa->spa_refcount, tag);
790 }
791 
792 /*
793  * Remove a reference to the given spa_t.  Must have at least one reference, or
794  * have the namespace lock held.
795  */
796 void
797 spa_close(spa_t *spa, void *tag)
798 {
799 	ASSERT(refcount_count(&spa->spa_refcount) > spa->spa_minref ||
800 	    MUTEX_HELD(&spa_namespace_lock));
801 	(void) refcount_remove(&spa->spa_refcount, tag);
802 }
803 
804 /*
805  * Remove a reference to the given spa_t held by a dsl dir that is
806  * being asynchronously released.  Async releases occur from a taskq
807  * performing eviction of dsl datasets and dirs.  The namespace lock
808  * isn't held and the hold by the object being evicted may contribute to
809  * spa_minref (e.g. dataset or directory released during pool export),
810  * so the asserts in spa_close() do not apply.
811  */
812 void
813 spa_async_close(spa_t *spa, void *tag)
814 {
815 	(void) refcount_remove(&spa->spa_refcount, tag);
816 }
817 
818 /*
819  * Check to see if the spa refcount is zero.  Must be called with
820  * spa_namespace_lock held.  We really compare against spa_minref, which is the
821  * number of references acquired when opening a pool
822  */
823 boolean_t
824 spa_refcount_zero(spa_t *spa)
825 {
826 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
827 
828 	return (refcount_count(&spa->spa_refcount) == spa->spa_minref);
829 }
830 
831 /*
832  * ==========================================================================
833  * SPA spare and l2cache tracking
834  * ==========================================================================
835  */
836 
837 /*
838  * Hot spares and cache devices are tracked using the same code below,
839  * for 'auxiliary' devices.
840  */
841 
842 typedef struct spa_aux {
843 	uint64_t	aux_guid;
844 	uint64_t	aux_pool;
845 	avl_node_t	aux_avl;
846 	int		aux_count;
847 } spa_aux_t;
848 
849 static int
850 spa_aux_compare(const void *a, const void *b)
851 {
852 	const spa_aux_t *sa = a;
853 	const spa_aux_t *sb = b;
854 
855 	if (sa->aux_guid < sb->aux_guid)
856 		return (-1);
857 	else if (sa->aux_guid > sb->aux_guid)
858 		return (1);
859 	else
860 		return (0);
861 }
862 
863 void
864 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
865 {
866 	avl_index_t where;
867 	spa_aux_t search;
868 	spa_aux_t *aux;
869 
870 	search.aux_guid = vd->vdev_guid;
871 	if ((aux = avl_find(avl, &search, &where)) != NULL) {
872 		aux->aux_count++;
873 	} else {
874 		aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
875 		aux->aux_guid = vd->vdev_guid;
876 		aux->aux_count = 1;
877 		avl_insert(avl, aux, where);
878 	}
879 }
880 
881 void
882 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
883 {
884 	spa_aux_t search;
885 	spa_aux_t *aux;
886 	avl_index_t where;
887 
888 	search.aux_guid = vd->vdev_guid;
889 	aux = avl_find(avl, &search, &where);
890 
891 	ASSERT(aux != NULL);
892 
893 	if (--aux->aux_count == 0) {
894 		avl_remove(avl, aux);
895 		kmem_free(aux, sizeof (spa_aux_t));
896 	} else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
897 		aux->aux_pool = 0ULL;
898 	}
899 }
900 
901 boolean_t
902 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
903 {
904 	spa_aux_t search, *found;
905 
906 	search.aux_guid = guid;
907 	found = avl_find(avl, &search, NULL);
908 
909 	if (pool) {
910 		if (found)
911 			*pool = found->aux_pool;
912 		else
913 			*pool = 0ULL;
914 	}
915 
916 	if (refcnt) {
917 		if (found)
918 			*refcnt = found->aux_count;
919 		else
920 			*refcnt = 0;
921 	}
922 
923 	return (found != NULL);
924 }
925 
926 void
927 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
928 {
929 	spa_aux_t search, *found;
930 	avl_index_t where;
931 
932 	search.aux_guid = vd->vdev_guid;
933 	found = avl_find(avl, &search, &where);
934 	ASSERT(found != NULL);
935 	ASSERT(found->aux_pool == 0ULL);
936 
937 	found->aux_pool = spa_guid(vd->vdev_spa);
938 }
939 
940 /*
941  * Spares are tracked globally due to the following constraints:
942  *
943  * 	- A spare may be part of multiple pools.
944  * 	- A spare may be added to a pool even if it's actively in use within
945  *	  another pool.
946  * 	- A spare in use in any pool can only be the source of a replacement if
947  *	  the target is a spare in the same pool.
948  *
949  * We keep track of all spares on the system through the use of a reference
950  * counted AVL tree.  When a vdev is added as a spare, or used as a replacement
951  * spare, then we bump the reference count in the AVL tree.  In addition, we set
952  * the 'vdev_isspare' member to indicate that the device is a spare (active or
953  * inactive).  When a spare is made active (used to replace a device in the
954  * pool), we also keep track of which pool its been made a part of.
955  *
956  * The 'spa_spare_lock' protects the AVL tree.  These functions are normally
957  * called under the spa_namespace lock as part of vdev reconfiguration.  The
958  * separate spare lock exists for the status query path, which does not need to
959  * be completely consistent with respect to other vdev configuration changes.
960  */
961 
962 static int
963 spa_spare_compare(const void *a, const void *b)
964 {
965 	return (spa_aux_compare(a, b));
966 }
967 
968 void
969 spa_spare_add(vdev_t *vd)
970 {
971 	mutex_enter(&spa_spare_lock);
972 	ASSERT(!vd->vdev_isspare);
973 	spa_aux_add(vd, &spa_spare_avl);
974 	vd->vdev_isspare = B_TRUE;
975 	mutex_exit(&spa_spare_lock);
976 }
977 
978 void
979 spa_spare_remove(vdev_t *vd)
980 {
981 	mutex_enter(&spa_spare_lock);
982 	ASSERT(vd->vdev_isspare);
983 	spa_aux_remove(vd, &spa_spare_avl);
984 	vd->vdev_isspare = B_FALSE;
985 	mutex_exit(&spa_spare_lock);
986 }
987 
988 boolean_t
989 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
990 {
991 	boolean_t found;
992 
993 	mutex_enter(&spa_spare_lock);
994 	found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
995 	mutex_exit(&spa_spare_lock);
996 
997 	return (found);
998 }
999 
1000 void
1001 spa_spare_activate(vdev_t *vd)
1002 {
1003 	mutex_enter(&spa_spare_lock);
1004 	ASSERT(vd->vdev_isspare);
1005 	spa_aux_activate(vd, &spa_spare_avl);
1006 	mutex_exit(&spa_spare_lock);
1007 }
1008 
1009 /*
1010  * Level 2 ARC devices are tracked globally for the same reasons as spares.
1011  * Cache devices currently only support one pool per cache device, and so
1012  * for these devices the aux reference count is currently unused beyond 1.
1013  */
1014 
1015 static int
1016 spa_l2cache_compare(const void *a, const void *b)
1017 {
1018 	return (spa_aux_compare(a, b));
1019 }
1020 
1021 void
1022 spa_l2cache_add(vdev_t *vd)
1023 {
1024 	mutex_enter(&spa_l2cache_lock);
1025 	ASSERT(!vd->vdev_isl2cache);
1026 	spa_aux_add(vd, &spa_l2cache_avl);
1027 	vd->vdev_isl2cache = B_TRUE;
1028 	mutex_exit(&spa_l2cache_lock);
1029 }
1030 
1031 void
1032 spa_l2cache_remove(vdev_t *vd)
1033 {
1034 	mutex_enter(&spa_l2cache_lock);
1035 	ASSERT(vd->vdev_isl2cache);
1036 	spa_aux_remove(vd, &spa_l2cache_avl);
1037 	vd->vdev_isl2cache = B_FALSE;
1038 	mutex_exit(&spa_l2cache_lock);
1039 }
1040 
1041 boolean_t
1042 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
1043 {
1044 	boolean_t found;
1045 
1046 	mutex_enter(&spa_l2cache_lock);
1047 	found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
1048 	mutex_exit(&spa_l2cache_lock);
1049 
1050 	return (found);
1051 }
1052 
1053 void
1054 spa_l2cache_activate(vdev_t *vd)
1055 {
1056 	mutex_enter(&spa_l2cache_lock);
1057 	ASSERT(vd->vdev_isl2cache);
1058 	spa_aux_activate(vd, &spa_l2cache_avl);
1059 	mutex_exit(&spa_l2cache_lock);
1060 }
1061 
1062 /*
1063  * ==========================================================================
1064  * SPA vdev locking
1065  * ==========================================================================
1066  */
1067 
1068 /*
1069  * Lock the given spa_t for the purpose of adding or removing a vdev.
1070  * Grabs the global spa_namespace_lock plus the spa config lock for writing.
1071  * It returns the next transaction group for the spa_t.
1072  */
1073 uint64_t
1074 spa_vdev_enter(spa_t *spa)
1075 {
1076 	mutex_enter(&spa->spa_vdev_top_lock);
1077 	mutex_enter(&spa_namespace_lock);
1078 	return (spa_vdev_config_enter(spa));
1079 }
1080 
1081 /*
1082  * Internal implementation for spa_vdev_enter().  Used when a vdev
1083  * operation requires multiple syncs (i.e. removing a device) while
1084  * keeping the spa_namespace_lock held.
1085  */
1086 uint64_t
1087 spa_vdev_config_enter(spa_t *spa)
1088 {
1089 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1090 
1091 	spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1092 
1093 	return (spa_last_synced_txg(spa) + 1);
1094 }
1095 
1096 /*
1097  * Used in combination with spa_vdev_config_enter() to allow the syncing
1098  * of multiple transactions without releasing the spa_namespace_lock.
1099  */
1100 void
1101 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error, char *tag)
1102 {
1103 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1104 
1105 	int config_changed = B_FALSE;
1106 
1107 	ASSERT(txg > spa_last_synced_txg(spa));
1108 
1109 	spa->spa_pending_vdev = NULL;
1110 
1111 	/*
1112 	 * Reassess the DTLs.
1113 	 */
1114 	vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE);
1115 
1116 	if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
1117 		config_changed = B_TRUE;
1118 		spa->spa_config_generation++;
1119 	}
1120 
1121 	/*
1122 	 * Verify the metaslab classes.
1123 	 */
1124 	ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
1125 	ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
1126 
1127 	spa_config_exit(spa, SCL_ALL, spa);
1128 
1129 	/*
1130 	 * Panic the system if the specified tag requires it.  This
1131 	 * is useful for ensuring that configurations are updated
1132 	 * transactionally.
1133 	 */
1134 	if (zio_injection_enabled)
1135 		zio_handle_panic_injection(spa, tag, 0);
1136 
1137 	/*
1138 	 * Note: this txg_wait_synced() is important because it ensures
1139 	 * that there won't be more than one config change per txg.
1140 	 * This allows us to use the txg as the generation number.
1141 	 */
1142 	if (error == 0)
1143 		txg_wait_synced(spa->spa_dsl_pool, txg);
1144 
1145 	if (vd != NULL) {
1146 		ASSERT(!vd->vdev_detached || vd->vdev_dtl_sm == NULL);
1147 		spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1148 		vdev_free(vd);
1149 		spa_config_exit(spa, SCL_ALL, spa);
1150 	}
1151 
1152 	/*
1153 	 * If the config changed, update the config cache.
1154 	 */
1155 	if (config_changed)
1156 		spa_config_sync(spa, B_FALSE, B_TRUE);
1157 }
1158 
1159 /*
1160  * Unlock the spa_t after adding or removing a vdev.  Besides undoing the
1161  * locking of spa_vdev_enter(), we also want make sure the transactions have
1162  * synced to disk, and then update the global configuration cache with the new
1163  * information.
1164  */
1165 int
1166 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
1167 {
1168 	spa_vdev_config_exit(spa, vd, txg, error, FTAG);
1169 	mutex_exit(&spa_namespace_lock);
1170 	mutex_exit(&spa->spa_vdev_top_lock);
1171 
1172 	return (error);
1173 }
1174 
1175 /*
1176  * Lock the given spa_t for the purpose of changing vdev state.
1177  */
1178 void
1179 spa_vdev_state_enter(spa_t *spa, int oplocks)
1180 {
1181 	int locks = SCL_STATE_ALL | oplocks;
1182 
1183 	/*
1184 	 * Root pools may need to read of the underlying devfs filesystem
1185 	 * when opening up a vdev.  Unfortunately if we're holding the
1186 	 * SCL_ZIO lock it will result in a deadlock when we try to issue
1187 	 * the read from the root filesystem.  Instead we "prefetch"
1188 	 * the associated vnodes that we need prior to opening the
1189 	 * underlying devices and cache them so that we can prevent
1190 	 * any I/O when we are doing the actual open.
1191 	 */
1192 	if (spa_is_root(spa)) {
1193 		int low = locks & ~(SCL_ZIO - 1);
1194 		int high = locks & ~low;
1195 
1196 		spa_config_enter(spa, high, spa, RW_WRITER);
1197 		vdev_hold(spa->spa_root_vdev);
1198 		spa_config_enter(spa, low, spa, RW_WRITER);
1199 	} else {
1200 		spa_config_enter(spa, locks, spa, RW_WRITER);
1201 	}
1202 	spa->spa_vdev_locks = locks;
1203 }
1204 
1205 int
1206 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
1207 {
1208 	boolean_t config_changed = B_FALSE;
1209 
1210 	if (vd != NULL || error == 0)
1211 		vdev_dtl_reassess(vd ? vd->vdev_top : spa->spa_root_vdev,
1212 		    0, 0, B_FALSE);
1213 
1214 	if (vd != NULL) {
1215 		vdev_state_dirty(vd->vdev_top);
1216 		config_changed = B_TRUE;
1217 		spa->spa_config_generation++;
1218 	}
1219 
1220 	if (spa_is_root(spa))
1221 		vdev_rele(spa->spa_root_vdev);
1222 
1223 	ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1224 	spa_config_exit(spa, spa->spa_vdev_locks, spa);
1225 
1226 	/*
1227 	 * If anything changed, wait for it to sync.  This ensures that,
1228 	 * from the system administrator's perspective, zpool(1M) commands
1229 	 * are synchronous.  This is important for things like zpool offline:
1230 	 * when the command completes, you expect no further I/O from ZFS.
1231 	 */
1232 	if (vd != NULL)
1233 		txg_wait_synced(spa->spa_dsl_pool, 0);
1234 
1235 	/*
1236 	 * If the config changed, update the config cache.
1237 	 */
1238 	if (config_changed) {
1239 		mutex_enter(&spa_namespace_lock);
1240 		spa_config_sync(spa, B_FALSE, B_TRUE);
1241 		mutex_exit(&spa_namespace_lock);
1242 	}
1243 
1244 	return (error);
1245 }
1246 
1247 /*
1248  * ==========================================================================
1249  * Miscellaneous functions
1250  * ==========================================================================
1251  */
1252 
1253 void
1254 spa_activate_mos_feature(spa_t *spa, const char *feature, dmu_tx_t *tx)
1255 {
1256 	if (!nvlist_exists(spa->spa_label_features, feature)) {
1257 		fnvlist_add_boolean(spa->spa_label_features, feature);
1258 		/*
1259 		 * When we are creating the pool (tx_txg==TXG_INITIAL), we can't
1260 		 * dirty the vdev config because lock SCL_CONFIG is not held.
1261 		 * Thankfully, in this case we don't need to dirty the config
1262 		 * because it will be written out anyway when we finish
1263 		 * creating the pool.
1264 		 */
1265 		if (tx->tx_txg != TXG_INITIAL)
1266 			vdev_config_dirty(spa->spa_root_vdev);
1267 	}
1268 }
1269 
1270 void
1271 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1272 {
1273 	if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1274 		vdev_config_dirty(spa->spa_root_vdev);
1275 }
1276 
1277 /*
1278  * Rename a spa_t.
1279  */
1280 int
1281 spa_rename(const char *name, const char *newname)
1282 {
1283 	spa_t *spa;
1284 	int err;
1285 
1286 	/*
1287 	 * Lookup the spa_t and grab the config lock for writing.  We need to
1288 	 * actually open the pool so that we can sync out the necessary labels.
1289 	 * It's OK to call spa_open() with the namespace lock held because we
1290 	 * allow recursive calls for other reasons.
1291 	 */
1292 	mutex_enter(&spa_namespace_lock);
1293 	if ((err = spa_open(name, &spa, FTAG)) != 0) {
1294 		mutex_exit(&spa_namespace_lock);
1295 		return (err);
1296 	}
1297 
1298 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1299 
1300 	avl_remove(&spa_namespace_avl, spa);
1301 	(void) strlcpy(spa->spa_name, newname, sizeof (spa->spa_name));
1302 	avl_add(&spa_namespace_avl, spa);
1303 
1304 	/*
1305 	 * Sync all labels to disk with the new names by marking the root vdev
1306 	 * dirty and waiting for it to sync.  It will pick up the new pool name
1307 	 * during the sync.
1308 	 */
1309 	vdev_config_dirty(spa->spa_root_vdev);
1310 
1311 	spa_config_exit(spa, SCL_ALL, FTAG);
1312 
1313 	txg_wait_synced(spa->spa_dsl_pool, 0);
1314 
1315 	/*
1316 	 * Sync the updated config cache.
1317 	 */
1318 	spa_config_sync(spa, B_FALSE, B_TRUE);
1319 
1320 	spa_close(spa, FTAG);
1321 
1322 	mutex_exit(&spa_namespace_lock);
1323 
1324 	return (0);
1325 }
1326 
1327 /*
1328  * Return the spa_t associated with given pool_guid, if it exists.  If
1329  * device_guid is non-zero, determine whether the pool exists *and* contains
1330  * a device with the specified device_guid.
1331  */
1332 spa_t *
1333 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1334 {
1335 	spa_t *spa;
1336 	avl_tree_t *t = &spa_namespace_avl;
1337 
1338 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1339 
1340 	for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1341 		if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1342 			continue;
1343 		if (spa->spa_root_vdev == NULL)
1344 			continue;
1345 		if (spa_guid(spa) == pool_guid) {
1346 			if (device_guid == 0)
1347 				break;
1348 
1349 			if (vdev_lookup_by_guid(spa->spa_root_vdev,
1350 			    device_guid) != NULL)
1351 				break;
1352 
1353 			/*
1354 			 * Check any devices we may be in the process of adding.
1355 			 */
1356 			if (spa->spa_pending_vdev) {
1357 				if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1358 				    device_guid) != NULL)
1359 					break;
1360 			}
1361 		}
1362 	}
1363 
1364 	return (spa);
1365 }
1366 
1367 /*
1368  * Determine whether a pool with the given pool_guid exists.
1369  */
1370 boolean_t
1371 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1372 {
1373 	return (spa_by_guid(pool_guid, device_guid) != NULL);
1374 }
1375 
1376 char *
1377 spa_strdup(const char *s)
1378 {
1379 	size_t len;
1380 	char *new;
1381 
1382 	len = strlen(s);
1383 	new = kmem_alloc(len + 1, KM_SLEEP);
1384 	bcopy(s, new, len);
1385 	new[len] = '\0';
1386 
1387 	return (new);
1388 }
1389 
1390 void
1391 spa_strfree(char *s)
1392 {
1393 	kmem_free(s, strlen(s) + 1);
1394 }
1395 
1396 uint64_t
1397 spa_get_random(uint64_t range)
1398 {
1399 	uint64_t r;
1400 
1401 	ASSERT(range != 0);
1402 
1403 	(void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
1404 
1405 	return (r % range);
1406 }
1407 
1408 uint64_t
1409 spa_generate_guid(spa_t *spa)
1410 {
1411 	uint64_t guid = spa_get_random(-1ULL);
1412 
1413 	if (spa != NULL) {
1414 		while (guid == 0 || spa_guid_exists(spa_guid(spa), guid))
1415 			guid = spa_get_random(-1ULL);
1416 	} else {
1417 		while (guid == 0 || spa_guid_exists(guid, 0))
1418 			guid = spa_get_random(-1ULL);
1419 	}
1420 
1421 	return (guid);
1422 }
1423 
1424 void
1425 snprintf_blkptr(char *buf, size_t buflen, const blkptr_t *bp)
1426 {
1427 	char type[256];
1428 	char *checksum = NULL;
1429 	char *compress = NULL;
1430 
1431 	if (bp != NULL) {
1432 		if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1433 			dmu_object_byteswap_t bswap =
1434 			    DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1435 			(void) snprintf(type, sizeof (type), "bswap %s %s",
1436 			    DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1437 			    "metadata" : "data",
1438 			    dmu_ot_byteswap[bswap].ob_name);
1439 		} else {
1440 			(void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1441 			    sizeof (type));
1442 		}
1443 		if (!BP_IS_EMBEDDED(bp)) {
1444 			checksum =
1445 			    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1446 		}
1447 		compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1448 	}
1449 
1450 	SNPRINTF_BLKPTR(snprintf, ' ', buf, buflen, bp, type, checksum,
1451 	    compress);
1452 }
1453 
1454 void
1455 spa_freeze(spa_t *spa)
1456 {
1457 	uint64_t freeze_txg = 0;
1458 
1459 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1460 	if (spa->spa_freeze_txg == UINT64_MAX) {
1461 		freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1462 		spa->spa_freeze_txg = freeze_txg;
1463 	}
1464 	spa_config_exit(spa, SCL_ALL, FTAG);
1465 	if (freeze_txg != 0)
1466 		txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1467 }
1468 
1469 void
1470 zfs_panic_recover(const char *fmt, ...)
1471 {
1472 	va_list adx;
1473 
1474 	va_start(adx, fmt);
1475 	vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1476 	va_end(adx);
1477 }
1478 
1479 /*
1480  * This is a stripped-down version of strtoull, suitable only for converting
1481  * lowercase hexadecimal numbers that don't overflow.
1482  */
1483 uint64_t
1484 strtonum(const char *str, char **nptr)
1485 {
1486 	uint64_t val = 0;
1487 	char c;
1488 	int digit;
1489 
1490 	while ((c = *str) != '\0') {
1491 		if (c >= '0' && c <= '9')
1492 			digit = c - '0';
1493 		else if (c >= 'a' && c <= 'f')
1494 			digit = 10 + c - 'a';
1495 		else
1496 			break;
1497 
1498 		val *= 16;
1499 		val += digit;
1500 
1501 		str++;
1502 	}
1503 
1504 	if (nptr)
1505 		*nptr = (char *)str;
1506 
1507 	return (val);
1508 }
1509 
1510 /*
1511  * ==========================================================================
1512  * Accessor functions
1513  * ==========================================================================
1514  */
1515 
1516 boolean_t
1517 spa_shutting_down(spa_t *spa)
1518 {
1519 	return (spa->spa_async_suspended);
1520 }
1521 
1522 dsl_pool_t *
1523 spa_get_dsl(spa_t *spa)
1524 {
1525 	return (spa->spa_dsl_pool);
1526 }
1527 
1528 boolean_t
1529 spa_is_initializing(spa_t *spa)
1530 {
1531 	return (spa->spa_is_initializing);
1532 }
1533 
1534 blkptr_t *
1535 spa_get_rootblkptr(spa_t *spa)
1536 {
1537 	return (&spa->spa_ubsync.ub_rootbp);
1538 }
1539 
1540 void
1541 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1542 {
1543 	spa->spa_uberblock.ub_rootbp = *bp;
1544 }
1545 
1546 void
1547 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1548 {
1549 	if (spa->spa_root == NULL)
1550 		buf[0] = '\0';
1551 	else
1552 		(void) strncpy(buf, spa->spa_root, buflen);
1553 }
1554 
1555 int
1556 spa_sync_pass(spa_t *spa)
1557 {
1558 	return (spa->spa_sync_pass);
1559 }
1560 
1561 char *
1562 spa_name(spa_t *spa)
1563 {
1564 	return (spa->spa_name);
1565 }
1566 
1567 uint64_t
1568 spa_guid(spa_t *spa)
1569 {
1570 	dsl_pool_t *dp = spa_get_dsl(spa);
1571 	uint64_t guid;
1572 
1573 	/*
1574 	 * If we fail to parse the config during spa_load(), we can go through
1575 	 * the error path (which posts an ereport) and end up here with no root
1576 	 * vdev.  We stash the original pool guid in 'spa_config_guid' to handle
1577 	 * this case.
1578 	 */
1579 	if (spa->spa_root_vdev == NULL)
1580 		return (spa->spa_config_guid);
1581 
1582 	guid = spa->spa_last_synced_guid != 0 ?
1583 	    spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1584 
1585 	/*
1586 	 * Return the most recently synced out guid unless we're
1587 	 * in syncing context.
1588 	 */
1589 	if (dp && dsl_pool_sync_context(dp))
1590 		return (spa->spa_root_vdev->vdev_guid);
1591 	else
1592 		return (guid);
1593 }
1594 
1595 uint64_t
1596 spa_load_guid(spa_t *spa)
1597 {
1598 	/*
1599 	 * This is a GUID that exists solely as a reference for the
1600 	 * purposes of the arc.  It is generated at load time, and
1601 	 * is never written to persistent storage.
1602 	 */
1603 	return (spa->spa_load_guid);
1604 }
1605 
1606 uint64_t
1607 spa_last_synced_txg(spa_t *spa)
1608 {
1609 	return (spa->spa_ubsync.ub_txg);
1610 }
1611 
1612 uint64_t
1613 spa_first_txg(spa_t *spa)
1614 {
1615 	return (spa->spa_first_txg);
1616 }
1617 
1618 uint64_t
1619 spa_syncing_txg(spa_t *spa)
1620 {
1621 	return (spa->spa_syncing_txg);
1622 }
1623 
1624 /*
1625  * Return the last txg where data can be dirtied. The final txgs
1626  * will be used to just clear out any deferred frees that remain.
1627  */
1628 uint64_t
1629 spa_final_dirty_txg(spa_t *spa)
1630 {
1631 	return (spa->spa_final_txg - TXG_DEFER_SIZE);
1632 }
1633 
1634 pool_state_t
1635 spa_state(spa_t *spa)
1636 {
1637 	return (spa->spa_state);
1638 }
1639 
1640 spa_load_state_t
1641 spa_load_state(spa_t *spa)
1642 {
1643 	return (spa->spa_load_state);
1644 }
1645 
1646 uint64_t
1647 spa_freeze_txg(spa_t *spa)
1648 {
1649 	return (spa->spa_freeze_txg);
1650 }
1651 
1652 /* ARGSUSED */
1653 uint64_t
1654 spa_get_worst_case_asize(spa_t *spa, uint64_t lsize)
1655 {
1656 	return (lsize * spa_asize_inflation);
1657 }
1658 
1659 /*
1660  * Return the amount of slop space in bytes.  It is 1/32 of the pool (3.2%),
1661  * or at least 128MB, unless that would cause it to be more than half the
1662  * pool size.
1663  *
1664  * See the comment above spa_slop_shift for details.
1665  */
1666 uint64_t
1667 spa_get_slop_space(spa_t *spa)
1668 {
1669 	uint64_t space = spa_get_dspace(spa);
1670 	return (MAX(space >> spa_slop_shift, MIN(space >> 1, spa_min_slop)));
1671 }
1672 
1673 uint64_t
1674 spa_get_dspace(spa_t *spa)
1675 {
1676 	return (spa->spa_dspace);
1677 }
1678 
1679 void
1680 spa_update_dspace(spa_t *spa)
1681 {
1682 	spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1683 	    ddt_get_dedup_dspace(spa);
1684 }
1685 
1686 /*
1687  * Return the failure mode that has been set to this pool. The default
1688  * behavior will be to block all I/Os when a complete failure occurs.
1689  */
1690 uint8_t
1691 spa_get_failmode(spa_t *spa)
1692 {
1693 	return (spa->spa_failmode);
1694 }
1695 
1696 boolean_t
1697 spa_suspended(spa_t *spa)
1698 {
1699 	return (spa->spa_suspended);
1700 }
1701 
1702 uint64_t
1703 spa_version(spa_t *spa)
1704 {
1705 	return (spa->spa_ubsync.ub_version);
1706 }
1707 
1708 boolean_t
1709 spa_deflate(spa_t *spa)
1710 {
1711 	return (spa->spa_deflate);
1712 }
1713 
1714 metaslab_class_t *
1715 spa_normal_class(spa_t *spa)
1716 {
1717 	return (spa->spa_normal_class);
1718 }
1719 
1720 metaslab_class_t *
1721 spa_log_class(spa_t *spa)
1722 {
1723 	return (spa->spa_log_class);
1724 }
1725 
1726 void
1727 spa_evicting_os_register(spa_t *spa, objset_t *os)
1728 {
1729 	mutex_enter(&spa->spa_evicting_os_lock);
1730 	list_insert_head(&spa->spa_evicting_os_list, os);
1731 	mutex_exit(&spa->spa_evicting_os_lock);
1732 }
1733 
1734 void
1735 spa_evicting_os_deregister(spa_t *spa, objset_t *os)
1736 {
1737 	mutex_enter(&spa->spa_evicting_os_lock);
1738 	list_remove(&spa->spa_evicting_os_list, os);
1739 	cv_broadcast(&spa->spa_evicting_os_cv);
1740 	mutex_exit(&spa->spa_evicting_os_lock);
1741 }
1742 
1743 void
1744 spa_evicting_os_wait(spa_t *spa)
1745 {
1746 	mutex_enter(&spa->spa_evicting_os_lock);
1747 	while (!list_is_empty(&spa->spa_evicting_os_list))
1748 		cv_wait(&spa->spa_evicting_os_cv, &spa->spa_evicting_os_lock);
1749 	mutex_exit(&spa->spa_evicting_os_lock);
1750 
1751 	dmu_buf_user_evict_wait();
1752 }
1753 
1754 int
1755 spa_max_replication(spa_t *spa)
1756 {
1757 	/*
1758 	 * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1759 	 * handle BPs with more than one DVA allocated.  Set our max
1760 	 * replication level accordingly.
1761 	 */
1762 	if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1763 		return (1);
1764 	return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1765 }
1766 
1767 int
1768 spa_prev_software_version(spa_t *spa)
1769 {
1770 	return (spa->spa_prev_software_version);
1771 }
1772 
1773 uint64_t
1774 spa_deadman_synctime(spa_t *spa)
1775 {
1776 	return (spa->spa_deadman_synctime);
1777 }
1778 
1779 uint64_t
1780 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
1781 {
1782 	uint64_t asize = DVA_GET_ASIZE(dva);
1783 	uint64_t dsize = asize;
1784 
1785 	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1786 
1787 	if (asize != 0 && spa->spa_deflate) {
1788 		vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
1789 		dsize = (asize >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio;
1790 	}
1791 
1792 	return (dsize);
1793 }
1794 
1795 uint64_t
1796 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
1797 {
1798 	uint64_t dsize = 0;
1799 
1800 	for (int d = 0; d < BP_GET_NDVAS(bp); d++)
1801 		dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1802 
1803 	return (dsize);
1804 }
1805 
1806 uint64_t
1807 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
1808 {
1809 	uint64_t dsize = 0;
1810 
1811 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1812 
1813 	for (int d = 0; d < BP_GET_NDVAS(bp); d++)
1814 		dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1815 
1816 	spa_config_exit(spa, SCL_VDEV, FTAG);
1817 
1818 	return (dsize);
1819 }
1820 
1821 /*
1822  * ==========================================================================
1823  * Initialization and Termination
1824  * ==========================================================================
1825  */
1826 
1827 static int
1828 spa_name_compare(const void *a1, const void *a2)
1829 {
1830 	const spa_t *s1 = a1;
1831 	const spa_t *s2 = a2;
1832 	int s;
1833 
1834 	s = strcmp(s1->spa_name, s2->spa_name);
1835 	if (s > 0)
1836 		return (1);
1837 	if (s < 0)
1838 		return (-1);
1839 	return (0);
1840 }
1841 
1842 int
1843 spa_busy(void)
1844 {
1845 	return (spa_active_count);
1846 }
1847 
1848 void
1849 spa_boot_init()
1850 {
1851 	spa_config_load();
1852 }
1853 
1854 void
1855 spa_init(int mode)
1856 {
1857 	mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
1858 	mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
1859 	mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
1860 	cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
1861 
1862 	avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
1863 	    offsetof(spa_t, spa_avl));
1864 
1865 	avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
1866 	    offsetof(spa_aux_t, aux_avl));
1867 
1868 	avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
1869 	    offsetof(spa_aux_t, aux_avl));
1870 
1871 	spa_mode_global = mode;
1872 
1873 #ifdef _KERNEL
1874 	spa_arch_init();
1875 #else
1876 	if (spa_mode_global != FREAD && dprintf_find_string("watch")) {
1877 		arc_procfd = open("/proc/self/ctl", O_WRONLY);
1878 		if (arc_procfd == -1) {
1879 			perror("could not enable watchpoints: "
1880 			    "opening /proc/self/ctl failed: ");
1881 		} else {
1882 			arc_watch = B_TRUE;
1883 		}
1884 	}
1885 #endif
1886 
1887 	refcount_init();
1888 	unique_init();
1889 	range_tree_init();
1890 	metaslab_alloc_trace_init();
1891 	zio_init();
1892 	dmu_init();
1893 	zil_init();
1894 	vdev_cache_stat_init();
1895 	zfs_prop_init();
1896 	zpool_prop_init();
1897 	zpool_feature_init();
1898 	spa_config_load();
1899 	l2arc_start();
1900 }
1901 
1902 void
1903 spa_fini(void)
1904 {
1905 	l2arc_stop();
1906 
1907 	spa_evict_all();
1908 
1909 	vdev_cache_stat_fini();
1910 	zil_fini();
1911 	dmu_fini();
1912 	zio_fini();
1913 	metaslab_alloc_trace_fini();
1914 	range_tree_fini();
1915 	unique_fini();
1916 	refcount_fini();
1917 
1918 	avl_destroy(&spa_namespace_avl);
1919 	avl_destroy(&spa_spare_avl);
1920 	avl_destroy(&spa_l2cache_avl);
1921 
1922 	cv_destroy(&spa_namespace_cv);
1923 	mutex_destroy(&spa_namespace_lock);
1924 	mutex_destroy(&spa_spare_lock);
1925 	mutex_destroy(&spa_l2cache_lock);
1926 }
1927 
1928 /*
1929  * Return whether this pool has slogs. No locking needed.
1930  * It's not a problem if the wrong answer is returned as it's only for
1931  * performance and not correctness
1932  */
1933 boolean_t
1934 spa_has_slogs(spa_t *spa)
1935 {
1936 	return (spa->spa_log_class->mc_rotor != NULL);
1937 }
1938 
1939 spa_log_state_t
1940 spa_get_log_state(spa_t *spa)
1941 {
1942 	return (spa->spa_log_state);
1943 }
1944 
1945 void
1946 spa_set_log_state(spa_t *spa, spa_log_state_t state)
1947 {
1948 	spa->spa_log_state = state;
1949 }
1950 
1951 boolean_t
1952 spa_is_root(spa_t *spa)
1953 {
1954 	return (spa->spa_is_root);
1955 }
1956 
1957 boolean_t
1958 spa_writeable(spa_t *spa)
1959 {
1960 	return (!!(spa->spa_mode & FWRITE));
1961 }
1962 
1963 /*
1964  * Returns true if there is a pending sync task in any of the current
1965  * syncing txg, the current quiescing txg, or the current open txg.
1966  */
1967 boolean_t
1968 spa_has_pending_synctask(spa_t *spa)
1969 {
1970 	return (!txg_all_lists_empty(&spa->spa_dsl_pool->dp_sync_tasks));
1971 }
1972 
1973 int
1974 spa_mode(spa_t *spa)
1975 {
1976 	return (spa->spa_mode);
1977 }
1978 
1979 uint64_t
1980 spa_bootfs(spa_t *spa)
1981 {
1982 	return (spa->spa_bootfs);
1983 }
1984 
1985 uint64_t
1986 spa_delegation(spa_t *spa)
1987 {
1988 	return (spa->spa_delegation);
1989 }
1990 
1991 objset_t *
1992 spa_meta_objset(spa_t *spa)
1993 {
1994 	return (spa->spa_meta_objset);
1995 }
1996 
1997 enum zio_checksum
1998 spa_dedup_checksum(spa_t *spa)
1999 {
2000 	return (spa->spa_dedup_checksum);
2001 }
2002 
2003 /*
2004  * Reset pool scan stat per scan pass (or reboot).
2005  */
2006 void
2007 spa_scan_stat_init(spa_t *spa)
2008 {
2009 	/* data not stored on disk */
2010 	spa->spa_scan_pass_start = gethrestime_sec();
2011 	spa->spa_scan_pass_exam = 0;
2012 	vdev_scan_stat_init(spa->spa_root_vdev);
2013 }
2014 
2015 /*
2016  * Get scan stats for zpool status reports
2017  */
2018 int
2019 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
2020 {
2021 	dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
2022 
2023 	if (scn == NULL || scn->scn_phys.scn_func == POOL_SCAN_NONE)
2024 		return (SET_ERROR(ENOENT));
2025 	bzero(ps, sizeof (pool_scan_stat_t));
2026 
2027 	/* data stored on disk */
2028 	ps->pss_func = scn->scn_phys.scn_func;
2029 	ps->pss_start_time = scn->scn_phys.scn_start_time;
2030 	ps->pss_end_time = scn->scn_phys.scn_end_time;
2031 	ps->pss_to_examine = scn->scn_phys.scn_to_examine;
2032 	ps->pss_examined = scn->scn_phys.scn_examined;
2033 	ps->pss_to_process = scn->scn_phys.scn_to_process;
2034 	ps->pss_processed = scn->scn_phys.scn_processed;
2035 	ps->pss_errors = scn->scn_phys.scn_errors;
2036 	ps->pss_state = scn->scn_phys.scn_state;
2037 
2038 	/* data not stored on disk */
2039 	ps->pss_pass_start = spa->spa_scan_pass_start;
2040 	ps->pss_pass_exam = spa->spa_scan_pass_exam;
2041 
2042 	return (0);
2043 }
2044 
2045 boolean_t
2046 spa_debug_enabled(spa_t *spa)
2047 {
2048 	return (spa->spa_debug);
2049 }
2050 
2051 int
2052 spa_maxblocksize(spa_t *spa)
2053 {
2054 	if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
2055 		return (SPA_MAXBLOCKSIZE);
2056 	else
2057 		return (SPA_OLD_MAXBLOCKSIZE);
2058 }
2059