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