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