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