xref: /trueos/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_misc.c (revision fd9c7ff5320b460878bd4f9a4264a2efbf79bc6c)
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, 2014 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 
226 static avl_tree_t spa_namespace_avl;
227 kmutex_t spa_namespace_lock;
228 static kcondvar_t spa_namespace_cv;
229 static int spa_active_count;
230 int spa_max_replication_override = SPA_DVAS_PER_BP;
231 
232 static kmutex_t spa_spare_lock;
233 static avl_tree_t spa_spare_avl;
234 static kmutex_t spa_l2cache_lock;
235 static avl_tree_t spa_l2cache_avl;
236 
237 kmem_cache_t *spa_buffer_pool;
238 int spa_mode_global;
239 
240 #ifdef ZFS_DEBUG
241 /* Everything except dprintf and spa is on by default in debug builds */
242 int zfs_flags = ~(ZFS_DEBUG_DPRINTF | ZFS_DEBUG_SPA);
243 #else
244 int zfs_flags = 0;
245 #endif
246 SYSCTL_DECL(_debug);
247 TUNABLE_INT("debug.zfs_flags", &zfs_flags);
248 SYSCTL_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  */
258 boolean_t zfs_recover = B_FALSE;
259 SYSCTL_DECL(_vfs_zfs);
260 TUNABLE_INT("vfs.zfs.recover", &zfs_recover);
261 SYSCTL_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  */
293 boolean_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  */
303 uint64_t zfs_deadman_synctime_ms = 1000000ULL;
304 TUNABLE_QUAD("vfs.zfs.deadman_synctime_ms", &zfs_deadman_synctime_ms);
305 SYSCTL_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  */
313 uint64_t zfs_deadman_checktime_ms = 5000ULL;
314 TUNABLE_QUAD("vfs.zfs.deadman_checktime_ms", &zfs_deadman_checktime_ms);
315 SYSCTL_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  */
323 int zfs_deadman_enabled = -1;
324 TUNABLE_INT("vfs.zfs.deadman_enabled", &zfs_deadman_enabled);
325 SYSCTL_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  */
337 int spa_asize_inflation = 24;
338 TUNABLE_INT("vfs.zfs.spa_asize_inflation", &spa_asize_inflation);
339 SYSCTL_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
344 static void
zfs_deadman_init()345 zfs_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  */
386 int spa_slop_shift = 5;
387 SYSCTL_INT(_vfs_zfs, OID_AUTO, spa_slop_shift, CTLFLAG_RWTUN,
388     &spa_slop_shift, 0,
389     "Shift value of reserved space (1/(2^spa_slop_shift)).");
390 
391 /*
392  * ==========================================================================
393  * SPA config locking
394  * ==========================================================================
395  */
396 static void
spa_config_lock_init(spa_t * spa)397 spa_config_lock_init(spa_t *spa)
398 {
399 	for (int i = 0; i < SCL_LOCKS; i++) {
400 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
401 		mutex_init(&scl->scl_lock, NULL, MUTEX_DEFAULT, NULL);
402 		cv_init(&scl->scl_cv, NULL, CV_DEFAULT, NULL);
403 		refcount_create_untracked(&scl->scl_count);
404 		scl->scl_writer = NULL;
405 		scl->scl_write_wanted = 0;
406 	}
407 }
408 
409 static void
spa_config_lock_destroy(spa_t * spa)410 spa_config_lock_destroy(spa_t *spa)
411 {
412 	for (int i = 0; i < SCL_LOCKS; i++) {
413 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
414 		mutex_destroy(&scl->scl_lock);
415 		cv_destroy(&scl->scl_cv);
416 		refcount_destroy(&scl->scl_count);
417 		ASSERT(scl->scl_writer == NULL);
418 		ASSERT(scl->scl_write_wanted == 0);
419 	}
420 }
421 
422 int
spa_config_tryenter(spa_t * spa,int locks,void * tag,krw_t rw)423 spa_config_tryenter(spa_t *spa, int locks, void *tag, krw_t rw)
424 {
425 	for (int i = 0; i < SCL_LOCKS; i++) {
426 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
427 		if (!(locks & (1 << i)))
428 			continue;
429 		mutex_enter(&scl->scl_lock);
430 		if (rw == RW_READER) {
431 			if (scl->scl_writer || scl->scl_write_wanted) {
432 				mutex_exit(&scl->scl_lock);
433 				spa_config_exit(spa, locks ^ (1 << i), tag);
434 				return (0);
435 			}
436 		} else {
437 			ASSERT(scl->scl_writer != curthread);
438 			if (!refcount_is_zero(&scl->scl_count)) {
439 				mutex_exit(&scl->scl_lock);
440 				spa_config_exit(spa, locks ^ (1 << i), tag);
441 				return (0);
442 			}
443 			scl->scl_writer = curthread;
444 		}
445 		(void) refcount_add(&scl->scl_count, tag);
446 		mutex_exit(&scl->scl_lock);
447 	}
448 	return (1);
449 }
450 
451 void
spa_config_enter(spa_t * spa,int locks,void * tag,krw_t rw)452 spa_config_enter(spa_t *spa, int locks, void *tag, krw_t rw)
453 {
454 	int wlocks_held = 0;
455 
456 	ASSERT3U(SCL_LOCKS, <, sizeof (wlocks_held) * NBBY);
457 
458 	for (int i = 0; i < SCL_LOCKS; i++) {
459 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
460 		if (scl->scl_writer == curthread)
461 			wlocks_held |= (1 << i);
462 		if (!(locks & (1 << i)))
463 			continue;
464 		mutex_enter(&scl->scl_lock);
465 		if (rw == RW_READER) {
466 			while (scl->scl_writer || scl->scl_write_wanted) {
467 				cv_wait(&scl->scl_cv, &scl->scl_lock);
468 			}
469 		} else {
470 			ASSERT(scl->scl_writer != curthread);
471 			while (!refcount_is_zero(&scl->scl_count)) {
472 				scl->scl_write_wanted++;
473 				cv_wait(&scl->scl_cv, &scl->scl_lock);
474 				scl->scl_write_wanted--;
475 			}
476 			scl->scl_writer = curthread;
477 		}
478 		(void) refcount_add(&scl->scl_count, tag);
479 		mutex_exit(&scl->scl_lock);
480 	}
481 	ASSERT(wlocks_held <= locks);
482 }
483 
484 void
spa_config_exit(spa_t * spa,int locks,void * tag)485 spa_config_exit(spa_t *spa, int locks, void *tag)
486 {
487 	for (int i = SCL_LOCKS - 1; i >= 0; i--) {
488 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
489 		if (!(locks & (1 << i)))
490 			continue;
491 		mutex_enter(&scl->scl_lock);
492 		ASSERT(!refcount_is_zero(&scl->scl_count));
493 		if (refcount_remove(&scl->scl_count, tag) == 0) {
494 			ASSERT(scl->scl_writer == NULL ||
495 			    scl->scl_writer == curthread);
496 			scl->scl_writer = NULL;	/* OK in either case */
497 			cv_broadcast(&scl->scl_cv);
498 		}
499 		mutex_exit(&scl->scl_lock);
500 	}
501 }
502 
503 int
spa_config_held(spa_t * spa,int locks,krw_t rw)504 spa_config_held(spa_t *spa, int locks, krw_t rw)
505 {
506 	int locks_held = 0;
507 
508 	for (int i = 0; i < SCL_LOCKS; i++) {
509 		spa_config_lock_t *scl = &spa->spa_config_lock[i];
510 		if (!(locks & (1 << i)))
511 			continue;
512 		if ((rw == RW_READER && !refcount_is_zero(&scl->scl_count)) ||
513 		    (rw == RW_WRITER && scl->scl_writer == curthread))
514 			locks_held |= 1 << i;
515 	}
516 
517 	return (locks_held);
518 }
519 
520 /*
521  * ==========================================================================
522  * SPA namespace functions
523  * ==========================================================================
524  */
525 
526 /*
527  * Lookup the named spa_t in the AVL tree.  The spa_namespace_lock must be held.
528  * Returns NULL if no matching spa_t is found.
529  */
530 spa_t *
spa_lookup(const char * name)531 spa_lookup(const char *name)
532 {
533 	static spa_t search;	/* spa_t is large; don't allocate on stack */
534 	spa_t *spa;
535 	avl_index_t where;
536 	char *cp;
537 
538 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
539 
540 	(void) strlcpy(search.spa_name, name, sizeof (search.spa_name));
541 
542 	/*
543 	 * If it's a full dataset name, figure out the pool name and
544 	 * just use that.
545 	 */
546 	cp = strpbrk(search.spa_name, "/@#");
547 	if (cp != NULL)
548 		*cp = '\0';
549 
550 	spa = avl_find(&spa_namespace_avl, &search, &where);
551 
552 	return (spa);
553 }
554 
555 /*
556  * Fires when spa_sync has not completed within zfs_deadman_synctime_ms.
557  * If the zfs_deadman_enabled flag is set then it inspects all vdev queues
558  * looking for potentially hung I/Os.
559  */
560 void
spa_deadman(void * arg)561 spa_deadman(void *arg)
562 {
563 	spa_t *spa = arg;
564 
565 	/*
566 	 * Disable the deadman timer if the pool is suspended.
567 	 */
568 	if (spa_suspended(spa)) {
569 #ifdef illumos
570 		VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
571 #else
572 		/* Nothing.  just don't schedule any future callouts. */
573 #endif
574 		return;
575 	}
576 
577 	zfs_dbgmsg("slow spa_sync: started %llu seconds ago, calls %llu",
578 	    (gethrtime() - spa->spa_sync_starttime) / NANOSEC,
579 	    ++spa->spa_deadman_calls);
580 	if (zfs_deadman_enabled)
581 		vdev_deadman(spa->spa_root_vdev);
582 }
583 
584 /*
585  * Create an uninitialized spa_t with the given name.  Requires
586  * spa_namespace_lock.  The caller must ensure that the spa_t doesn't already
587  * exist by calling spa_lookup() first.
588  */
589 spa_t *
spa_add(const char * name,nvlist_t * config,const char * altroot)590 spa_add(const char *name, nvlist_t *config, const char *altroot)
591 {
592 	spa_t *spa;
593 	spa_config_dirent_t *dp;
594 #ifdef illumos
595 	cyc_handler_t hdlr;
596 	cyc_time_t when;
597 #endif
598 
599 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
600 
601 	spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
602 
603 	mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
604 	mutex_init(&spa->spa_errlist_lock, NULL, MUTEX_DEFAULT, NULL);
605 	mutex_init(&spa->spa_errlog_lock, NULL, MUTEX_DEFAULT, NULL);
606 	mutex_init(&spa->spa_history_lock, NULL, MUTEX_DEFAULT, NULL);
607 	mutex_init(&spa->spa_proc_lock, NULL, MUTEX_DEFAULT, NULL);
608 	mutex_init(&spa->spa_props_lock, NULL, MUTEX_DEFAULT, NULL);
609 	mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
610 	mutex_init(&spa->spa_suspend_lock, NULL, MUTEX_DEFAULT, NULL);
611 	mutex_init(&spa->spa_vdev_top_lock, NULL, MUTEX_DEFAULT, NULL);
612 
613 	cv_init(&spa->spa_async_cv, NULL, CV_DEFAULT, NULL);
614 	cv_init(&spa->spa_proc_cv, NULL, CV_DEFAULT, NULL);
615 	cv_init(&spa->spa_scrub_io_cv, NULL, CV_DEFAULT, NULL);
616 	cv_init(&spa->spa_suspend_cv, NULL, CV_DEFAULT, NULL);
617 
618 	for (int t = 0; t < TXG_SIZE; t++)
619 		bplist_create(&spa->spa_free_bplist[t]);
620 
621 	(void) strlcpy(spa->spa_name, name, sizeof (spa->spa_name));
622 	spa->spa_state = POOL_STATE_UNINITIALIZED;
623 	spa->spa_freeze_txg = UINT64_MAX;
624 	spa->spa_final_txg = UINT64_MAX;
625 	spa->spa_load_max_txg = UINT64_MAX;
626 	spa->spa_proc = &p0;
627 	spa->spa_proc_state = SPA_PROC_NONE;
628 
629 #ifdef illumos
630 	hdlr.cyh_func = spa_deadman;
631 	hdlr.cyh_arg = spa;
632 	hdlr.cyh_level = CY_LOW_LEVEL;
633 #endif
634 
635 	spa->spa_deadman_synctime = MSEC2NSEC(zfs_deadman_synctime_ms);
636 
637 #ifdef illumos
638 	/*
639 	 * This determines how often we need to check for hung I/Os after
640 	 * the cyclic has already fired. Since checking for hung I/Os is
641 	 * an expensive operation we don't want to check too frequently.
642 	 * Instead wait for 5 seconds before checking again.
643 	 */
644 	when.cyt_interval = MSEC2NSEC(zfs_deadman_checktime_ms);
645 	when.cyt_when = CY_INFINITY;
646 	mutex_enter(&cpu_lock);
647 	spa->spa_deadman_cycid = cyclic_add(&hdlr, &when);
648 	mutex_exit(&cpu_lock);
649 #else	/* !illumos */
650 #ifdef _KERNEL
651 	callout_init(&spa->spa_deadman_cycid, CALLOUT_MPSAFE);
652 #endif
653 #endif
654 	refcount_create(&spa->spa_refcount);
655 	spa_config_lock_init(spa);
656 
657 	avl_add(&spa_namespace_avl, spa);
658 
659 	/*
660 	 * Set the alternate root, if there is one.
661 	 */
662 	if (altroot) {
663 		spa->spa_root = spa_strdup(altroot);
664 		spa_active_count++;
665 	}
666 
667 	/*
668 	 * Every pool starts with the default cachefile
669 	 */
670 	list_create(&spa->spa_config_list, sizeof (spa_config_dirent_t),
671 	    offsetof(spa_config_dirent_t, scd_link));
672 
673 	dp = kmem_zalloc(sizeof (spa_config_dirent_t), KM_SLEEP);
674 	dp->scd_path = altroot ? NULL : spa_strdup(spa_config_path);
675 	list_insert_head(&spa->spa_config_list, dp);
676 
677 	VERIFY(nvlist_alloc(&spa->spa_load_info, NV_UNIQUE_NAME,
678 	    KM_SLEEP) == 0);
679 
680 	if (config != NULL) {
681 		nvlist_t *features;
682 
683 		if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_FEATURES_FOR_READ,
684 		    &features) == 0) {
685 			VERIFY(nvlist_dup(features, &spa->spa_label_features,
686 			    0) == 0);
687 		}
688 
689 		VERIFY(nvlist_dup(config, &spa->spa_config, 0) == 0);
690 	}
691 
692 	if (spa->spa_label_features == NULL) {
693 		VERIFY(nvlist_alloc(&spa->spa_label_features, NV_UNIQUE_NAME,
694 		    KM_SLEEP) == 0);
695 	}
696 
697 	spa->spa_debug = ((zfs_flags & ZFS_DEBUG_SPA) != 0);
698 
699 	/*
700 	 * As a pool is being created, treat all features as disabled by
701 	 * setting SPA_FEATURE_DISABLED for all entries in the feature
702 	 * refcount cache.
703 	 */
704 	for (int i = 0; i < SPA_FEATURES; i++) {
705 		spa->spa_feat_refcount_cache[i] = SPA_FEATURE_DISABLED;
706 	}
707 
708 	return (spa);
709 }
710 
711 /*
712  * Removes a spa_t from the namespace, freeing up any memory used.  Requires
713  * spa_namespace_lock.  This is called only after the spa_t has been closed and
714  * deactivated.
715  */
716 void
spa_remove(spa_t * spa)717 spa_remove(spa_t *spa)
718 {
719 	spa_config_dirent_t *dp;
720 
721 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
722 	ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
723 
724 	nvlist_free(spa->spa_config_splitting);
725 
726 	avl_remove(&spa_namespace_avl, spa);
727 	cv_broadcast(&spa_namespace_cv);
728 
729 	if (spa->spa_root) {
730 		spa_strfree(spa->spa_root);
731 		spa_active_count--;
732 	}
733 
734 	while ((dp = list_head(&spa->spa_config_list)) != NULL) {
735 		list_remove(&spa->spa_config_list, dp);
736 		if (dp->scd_path != NULL)
737 			spa_strfree(dp->scd_path);
738 		kmem_free(dp, sizeof (spa_config_dirent_t));
739 	}
740 
741 	list_destroy(&spa->spa_config_list);
742 
743 	nvlist_free(spa->spa_label_features);
744 	nvlist_free(spa->spa_load_info);
745 	spa_config_set(spa, NULL);
746 
747 #ifdef illumos
748 	mutex_enter(&cpu_lock);
749 	if (spa->spa_deadman_cycid != CYCLIC_NONE)
750 		cyclic_remove(spa->spa_deadman_cycid);
751 	mutex_exit(&cpu_lock);
752 	spa->spa_deadman_cycid = CYCLIC_NONE;
753 #else	/* !illumos */
754 #ifdef _KERNEL
755 	callout_drain(&spa->spa_deadman_cycid);
756 #endif
757 #endif
758 
759 	refcount_destroy(&spa->spa_refcount);
760 
761 	spa_config_lock_destroy(spa);
762 
763 	for (int t = 0; t < TXG_SIZE; t++)
764 		bplist_destroy(&spa->spa_free_bplist[t]);
765 
766 	cv_destroy(&spa->spa_async_cv);
767 	cv_destroy(&spa->spa_proc_cv);
768 	cv_destroy(&spa->spa_scrub_io_cv);
769 	cv_destroy(&spa->spa_suspend_cv);
770 
771 	mutex_destroy(&spa->spa_async_lock);
772 	mutex_destroy(&spa->spa_errlist_lock);
773 	mutex_destroy(&spa->spa_errlog_lock);
774 	mutex_destroy(&spa->spa_history_lock);
775 	mutex_destroy(&spa->spa_proc_lock);
776 	mutex_destroy(&spa->spa_props_lock);
777 	mutex_destroy(&spa->spa_scrub_lock);
778 	mutex_destroy(&spa->spa_suspend_lock);
779 	mutex_destroy(&spa->spa_vdev_top_lock);
780 
781 	kmem_free(spa, sizeof (spa_t));
782 }
783 
784 /*
785  * Given a pool, return the next pool in the namespace, or NULL if there is
786  * none.  If 'prev' is NULL, return the first pool.
787  */
788 spa_t *
spa_next(spa_t * prev)789 spa_next(spa_t *prev)
790 {
791 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
792 
793 	if (prev)
794 		return (AVL_NEXT(&spa_namespace_avl, prev));
795 	else
796 		return (avl_first(&spa_namespace_avl));
797 }
798 
799 /*
800  * ==========================================================================
801  * SPA refcount functions
802  * ==========================================================================
803  */
804 
805 /*
806  * Add a reference to the given spa_t.  Must have at least one reference, or
807  * have the namespace lock held.
808  */
809 void
spa_open_ref(spa_t * spa,void * tag)810 spa_open_ref(spa_t *spa, void *tag)
811 {
812 	ASSERT(refcount_count(&spa->spa_refcount) >= spa->spa_minref ||
813 	    MUTEX_HELD(&spa_namespace_lock));
814 	(void) refcount_add(&spa->spa_refcount, tag);
815 }
816 
817 /*
818  * Remove a reference to the given spa_t.  Must have at least one reference, or
819  * have the namespace lock held.
820  */
821 void
spa_close(spa_t * spa,void * tag)822 spa_close(spa_t *spa, void *tag)
823 {
824 	ASSERT(refcount_count(&spa->spa_refcount) > spa->spa_minref ||
825 	    MUTEX_HELD(&spa_namespace_lock));
826 	(void) refcount_remove(&spa->spa_refcount, tag);
827 }
828 
829 /*
830  * Check to see if the spa refcount is zero.  Must be called with
831  * spa_namespace_lock held.  We really compare against spa_minref, which is the
832  * number of references acquired when opening a pool
833  */
834 boolean_t
spa_refcount_zero(spa_t * spa)835 spa_refcount_zero(spa_t *spa)
836 {
837 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
838 
839 	return (refcount_count(&spa->spa_refcount) == spa->spa_minref);
840 }
841 
842 /*
843  * ==========================================================================
844  * SPA spare and l2cache tracking
845  * ==========================================================================
846  */
847 
848 /*
849  * Hot spares and cache devices are tracked using the same code below,
850  * for 'auxiliary' devices.
851  */
852 
853 typedef struct spa_aux {
854 	uint64_t	aux_guid;
855 	uint64_t	aux_pool;
856 	avl_node_t	aux_avl;
857 	int		aux_count;
858 } spa_aux_t;
859 
860 static int
spa_aux_compare(const void * a,const void * b)861 spa_aux_compare(const void *a, const void *b)
862 {
863 	const spa_aux_t *sa = a;
864 	const spa_aux_t *sb = b;
865 
866 	if (sa->aux_guid < sb->aux_guid)
867 		return (-1);
868 	else if (sa->aux_guid > sb->aux_guid)
869 		return (1);
870 	else
871 		return (0);
872 }
873 
874 void
spa_aux_add(vdev_t * vd,avl_tree_t * avl)875 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
876 {
877 	avl_index_t where;
878 	spa_aux_t search;
879 	spa_aux_t *aux;
880 
881 	search.aux_guid = vd->vdev_guid;
882 	if ((aux = avl_find(avl, &search, &where)) != NULL) {
883 		aux->aux_count++;
884 	} else {
885 		aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
886 		aux->aux_guid = vd->vdev_guid;
887 		aux->aux_count = 1;
888 		avl_insert(avl, aux, where);
889 	}
890 }
891 
892 void
spa_aux_remove(vdev_t * vd,avl_tree_t * avl)893 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
894 {
895 	spa_aux_t search;
896 	spa_aux_t *aux;
897 	avl_index_t where;
898 
899 	search.aux_guid = vd->vdev_guid;
900 	aux = avl_find(avl, &search, &where);
901 
902 	ASSERT(aux != NULL);
903 
904 	if (--aux->aux_count == 0) {
905 		avl_remove(avl, aux);
906 		kmem_free(aux, sizeof (spa_aux_t));
907 	} else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
908 		aux->aux_pool = 0ULL;
909 	}
910 }
911 
912 boolean_t
spa_aux_exists(uint64_t guid,uint64_t * pool,int * refcnt,avl_tree_t * avl)913 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
914 {
915 	spa_aux_t search, *found;
916 
917 	search.aux_guid = guid;
918 	found = avl_find(avl, &search, NULL);
919 
920 	if (pool) {
921 		if (found)
922 			*pool = found->aux_pool;
923 		else
924 			*pool = 0ULL;
925 	}
926 
927 	if (refcnt) {
928 		if (found)
929 			*refcnt = found->aux_count;
930 		else
931 			*refcnt = 0;
932 	}
933 
934 	return (found != NULL);
935 }
936 
937 void
spa_aux_activate(vdev_t * vd,avl_tree_t * avl)938 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
939 {
940 	spa_aux_t search, *found;
941 	avl_index_t where;
942 
943 	search.aux_guid = vd->vdev_guid;
944 	found = avl_find(avl, &search, &where);
945 	ASSERT(found != NULL);
946 	ASSERT(found->aux_pool == 0ULL);
947 
948 	found->aux_pool = spa_guid(vd->vdev_spa);
949 }
950 
951 /*
952  * Spares are tracked globally due to the following constraints:
953  *
954  * 	- A spare may be part of multiple pools.
955  * 	- A spare may be added to a pool even if it's actively in use within
956  *	  another pool.
957  * 	- A spare in use in any pool can only be the source of a replacement if
958  *	  the target is a spare in the same pool.
959  *
960  * We keep track of all spares on the system through the use of a reference
961  * counted AVL tree.  When a vdev is added as a spare, or used as a replacement
962  * spare, then we bump the reference count in the AVL tree.  In addition, we set
963  * the 'vdev_isspare' member to indicate that the device is a spare (active or
964  * inactive).  When a spare is made active (used to replace a device in the
965  * pool), we also keep track of which pool its been made a part of.
966  *
967  * The 'spa_spare_lock' protects the AVL tree.  These functions are normally
968  * called under the spa_namespace lock as part of vdev reconfiguration.  The
969  * separate spare lock exists for the status query path, which does not need to
970  * be completely consistent with respect to other vdev configuration changes.
971  */
972 
973 static int
spa_spare_compare(const void * a,const void * b)974 spa_spare_compare(const void *a, const void *b)
975 {
976 	return (spa_aux_compare(a, b));
977 }
978 
979 void
spa_spare_add(vdev_t * vd)980 spa_spare_add(vdev_t *vd)
981 {
982 	mutex_enter(&spa_spare_lock);
983 	ASSERT(!vd->vdev_isspare);
984 	spa_aux_add(vd, &spa_spare_avl);
985 	vd->vdev_isspare = B_TRUE;
986 	mutex_exit(&spa_spare_lock);
987 }
988 
989 void
spa_spare_remove(vdev_t * vd)990 spa_spare_remove(vdev_t *vd)
991 {
992 	mutex_enter(&spa_spare_lock);
993 	ASSERT(vd->vdev_isspare);
994 	spa_aux_remove(vd, &spa_spare_avl);
995 	vd->vdev_isspare = B_FALSE;
996 	mutex_exit(&spa_spare_lock);
997 }
998 
999 boolean_t
spa_spare_exists(uint64_t guid,uint64_t * pool,int * refcnt)1000 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
1001 {
1002 	boolean_t found;
1003 
1004 	mutex_enter(&spa_spare_lock);
1005 	found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
1006 	mutex_exit(&spa_spare_lock);
1007 
1008 	return (found);
1009 }
1010 
1011 void
spa_spare_activate(vdev_t * vd)1012 spa_spare_activate(vdev_t *vd)
1013 {
1014 	mutex_enter(&spa_spare_lock);
1015 	ASSERT(vd->vdev_isspare);
1016 	spa_aux_activate(vd, &spa_spare_avl);
1017 	mutex_exit(&spa_spare_lock);
1018 }
1019 
1020 /*
1021  * Level 2 ARC devices are tracked globally for the same reasons as spares.
1022  * Cache devices currently only support one pool per cache device, and so
1023  * for these devices the aux reference count is currently unused beyond 1.
1024  */
1025 
1026 static int
spa_l2cache_compare(const void * a,const void * b)1027 spa_l2cache_compare(const void *a, const void *b)
1028 {
1029 	return (spa_aux_compare(a, b));
1030 }
1031 
1032 void
spa_l2cache_add(vdev_t * vd)1033 spa_l2cache_add(vdev_t *vd)
1034 {
1035 	mutex_enter(&spa_l2cache_lock);
1036 	ASSERT(!vd->vdev_isl2cache);
1037 	spa_aux_add(vd, &spa_l2cache_avl);
1038 	vd->vdev_isl2cache = B_TRUE;
1039 	mutex_exit(&spa_l2cache_lock);
1040 }
1041 
1042 void
spa_l2cache_remove(vdev_t * vd)1043 spa_l2cache_remove(vdev_t *vd)
1044 {
1045 	mutex_enter(&spa_l2cache_lock);
1046 	ASSERT(vd->vdev_isl2cache);
1047 	spa_aux_remove(vd, &spa_l2cache_avl);
1048 	vd->vdev_isl2cache = B_FALSE;
1049 	mutex_exit(&spa_l2cache_lock);
1050 }
1051 
1052 boolean_t
spa_l2cache_exists(uint64_t guid,uint64_t * pool)1053 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
1054 {
1055 	boolean_t found;
1056 
1057 	mutex_enter(&spa_l2cache_lock);
1058 	found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
1059 	mutex_exit(&spa_l2cache_lock);
1060 
1061 	return (found);
1062 }
1063 
1064 void
spa_l2cache_activate(vdev_t * vd)1065 spa_l2cache_activate(vdev_t *vd)
1066 {
1067 	mutex_enter(&spa_l2cache_lock);
1068 	ASSERT(vd->vdev_isl2cache);
1069 	spa_aux_activate(vd, &spa_l2cache_avl);
1070 	mutex_exit(&spa_l2cache_lock);
1071 }
1072 
1073 /*
1074  * ==========================================================================
1075  * SPA vdev locking
1076  * ==========================================================================
1077  */
1078 
1079 /*
1080  * Lock the given spa_t for the purpose of adding or removing a vdev.
1081  * Grabs the global spa_namespace_lock plus the spa config lock for writing.
1082  * It returns the next transaction group for the spa_t.
1083  */
1084 uint64_t
spa_vdev_enter(spa_t * spa)1085 spa_vdev_enter(spa_t *spa)
1086 {
1087 	mutex_enter(&spa->spa_vdev_top_lock);
1088 	mutex_enter(&spa_namespace_lock);
1089 	return (spa_vdev_config_enter(spa));
1090 }
1091 
1092 /*
1093  * Internal implementation for spa_vdev_enter().  Used when a vdev
1094  * operation requires multiple syncs (i.e. removing a device) while
1095  * keeping the spa_namespace_lock held.
1096  */
1097 uint64_t
spa_vdev_config_enter(spa_t * spa)1098 spa_vdev_config_enter(spa_t *spa)
1099 {
1100 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1101 
1102 	spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1103 
1104 	return (spa_last_synced_txg(spa) + 1);
1105 }
1106 
1107 /*
1108  * Used in combination with spa_vdev_config_enter() to allow the syncing
1109  * of multiple transactions without releasing the spa_namespace_lock.
1110  */
1111 void
spa_vdev_config_exit(spa_t * spa,vdev_t * vd,uint64_t txg,int error,char * tag)1112 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error, char *tag)
1113 {
1114 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1115 
1116 	int config_changed = B_FALSE;
1117 
1118 	ASSERT(txg > spa_last_synced_txg(spa));
1119 
1120 	spa->spa_pending_vdev = NULL;
1121 
1122 	/*
1123 	 * Reassess the DTLs.
1124 	 */
1125 	vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE);
1126 
1127 	if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
1128 		config_changed = B_TRUE;
1129 		spa->spa_config_generation++;
1130 	}
1131 
1132 	/*
1133 	 * Verify the metaslab classes.
1134 	 */
1135 	ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
1136 	ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
1137 
1138 	spa_config_exit(spa, SCL_ALL, spa);
1139 
1140 	/*
1141 	 * Panic the system if the specified tag requires it.  This
1142 	 * is useful for ensuring that configurations are updated
1143 	 * transactionally.
1144 	 */
1145 	if (zio_injection_enabled)
1146 		zio_handle_panic_injection(spa, tag, 0);
1147 
1148 	/*
1149 	 * Note: this txg_wait_synced() is important because it ensures
1150 	 * that there won't be more than one config change per txg.
1151 	 * This allows us to use the txg as the generation number.
1152 	 */
1153 	if (error == 0)
1154 		txg_wait_synced(spa->spa_dsl_pool, txg);
1155 
1156 	if (vd != NULL) {
1157 		ASSERT(!vd->vdev_detached || vd->vdev_dtl_sm == NULL);
1158 		spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1159 		vdev_free(vd);
1160 		spa_config_exit(spa, SCL_ALL, spa);
1161 	}
1162 
1163 	/*
1164 	 * If the config changed, update the config cache.
1165 	 */
1166 	if (config_changed)
1167 		spa_config_sync(spa, B_FALSE, B_TRUE);
1168 }
1169 
1170 /*
1171  * Unlock the spa_t after adding or removing a vdev.  Besides undoing the
1172  * locking of spa_vdev_enter(), we also want make sure the transactions have
1173  * synced to disk, and then update the global configuration cache with the new
1174  * information.
1175  */
1176 int
spa_vdev_exit(spa_t * spa,vdev_t * vd,uint64_t txg,int error)1177 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
1178 {
1179 	spa_vdev_config_exit(spa, vd, txg, error, FTAG);
1180 	mutex_exit(&spa_namespace_lock);
1181 	mutex_exit(&spa->spa_vdev_top_lock);
1182 
1183 	return (error);
1184 }
1185 
1186 /*
1187  * Lock the given spa_t for the purpose of changing vdev state.
1188  */
1189 void
spa_vdev_state_enter(spa_t * spa,int oplocks)1190 spa_vdev_state_enter(spa_t *spa, int oplocks)
1191 {
1192 	int locks = SCL_STATE_ALL | oplocks;
1193 
1194 	/*
1195 	 * Root pools may need to read of the underlying devfs filesystem
1196 	 * when opening up a vdev.  Unfortunately if we're holding the
1197 	 * SCL_ZIO lock it will result in a deadlock when we try to issue
1198 	 * the read from the root filesystem.  Instead we "prefetch"
1199 	 * the associated vnodes that we need prior to opening the
1200 	 * underlying devices and cache them so that we can prevent
1201 	 * any I/O when we are doing the actual open.
1202 	 */
1203 	if (spa_is_root(spa)) {
1204 		int low = locks & ~(SCL_ZIO - 1);
1205 		int high = locks & ~low;
1206 
1207 		spa_config_enter(spa, high, spa, RW_WRITER);
1208 		vdev_hold(spa->spa_root_vdev);
1209 		spa_config_enter(spa, low, spa, RW_WRITER);
1210 	} else {
1211 		spa_config_enter(spa, locks, spa, RW_WRITER);
1212 	}
1213 	spa->spa_vdev_locks = locks;
1214 }
1215 
1216 int
spa_vdev_state_exit(spa_t * spa,vdev_t * vd,int error)1217 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
1218 {
1219 	boolean_t config_changed = B_FALSE;
1220 
1221 	if (vd != NULL || error == 0)
1222 		vdev_dtl_reassess(vd ? vd->vdev_top : spa->spa_root_vdev,
1223 		    0, 0, B_FALSE);
1224 
1225 	if (vd != NULL) {
1226 		vdev_state_dirty(vd->vdev_top);
1227 		config_changed = B_TRUE;
1228 		spa->spa_config_generation++;
1229 	}
1230 
1231 	if (spa_is_root(spa))
1232 		vdev_rele(spa->spa_root_vdev);
1233 
1234 	ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1235 	spa_config_exit(spa, spa->spa_vdev_locks, spa);
1236 
1237 	/*
1238 	 * If anything changed, wait for it to sync.  This ensures that,
1239 	 * from the system administrator's perspective, zpool(1M) commands
1240 	 * are synchronous.  This is important for things like zpool offline:
1241 	 * when the command completes, you expect no further I/O from ZFS.
1242 	 */
1243 	if (vd != NULL)
1244 		txg_wait_synced(spa->spa_dsl_pool, 0);
1245 
1246 	/*
1247 	 * If the config changed, update the config cache.
1248 	 */
1249 	if (config_changed) {
1250 		mutex_enter(&spa_namespace_lock);
1251 		spa_config_sync(spa, B_FALSE, B_TRUE);
1252 		mutex_exit(&spa_namespace_lock);
1253 	}
1254 
1255 	return (error);
1256 }
1257 
1258 /*
1259  * ==========================================================================
1260  * Miscellaneous functions
1261  * ==========================================================================
1262  */
1263 
1264 void
spa_activate_mos_feature(spa_t * spa,const char * feature,dmu_tx_t * tx)1265 spa_activate_mos_feature(spa_t *spa, const char *feature, dmu_tx_t *tx)
1266 {
1267 	if (!nvlist_exists(spa->spa_label_features, feature)) {
1268 		fnvlist_add_boolean(spa->spa_label_features, feature);
1269 		/*
1270 		 * When we are creating the pool (tx_txg==TXG_INITIAL), we can't
1271 		 * dirty the vdev config because lock SCL_CONFIG is not held.
1272 		 * Thankfully, in this case we don't need to dirty the config
1273 		 * because it will be written out anyway when we finish
1274 		 * creating the pool.
1275 		 */
1276 		if (tx->tx_txg != TXG_INITIAL)
1277 			vdev_config_dirty(spa->spa_root_vdev);
1278 	}
1279 }
1280 
1281 void
spa_deactivate_mos_feature(spa_t * spa,const char * feature)1282 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1283 {
1284 	if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1285 		vdev_config_dirty(spa->spa_root_vdev);
1286 }
1287 
1288 /*
1289  * Rename a spa_t.
1290  */
1291 int
spa_rename(const char * name,const char * newname)1292 spa_rename(const char *name, const char *newname)
1293 {
1294 	spa_t *spa;
1295 	int err;
1296 
1297 	/*
1298 	 * Lookup the spa_t and grab the config lock for writing.  We need to
1299 	 * actually open the pool so that we can sync out the necessary labels.
1300 	 * It's OK to call spa_open() with the namespace lock held because we
1301 	 * allow recursive calls for other reasons.
1302 	 */
1303 	mutex_enter(&spa_namespace_lock);
1304 	if ((err = spa_open(name, &spa, FTAG)) != 0) {
1305 		mutex_exit(&spa_namespace_lock);
1306 		return (err);
1307 	}
1308 
1309 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1310 
1311 	avl_remove(&spa_namespace_avl, spa);
1312 	(void) strlcpy(spa->spa_name, newname, sizeof (spa->spa_name));
1313 	avl_add(&spa_namespace_avl, spa);
1314 
1315 	/*
1316 	 * Sync all labels to disk with the new names by marking the root vdev
1317 	 * dirty and waiting for it to sync.  It will pick up the new pool name
1318 	 * during the sync.
1319 	 */
1320 	vdev_config_dirty(spa->spa_root_vdev);
1321 
1322 	spa_config_exit(spa, SCL_ALL, FTAG);
1323 
1324 	txg_wait_synced(spa->spa_dsl_pool, 0);
1325 
1326 	/*
1327 	 * Sync the updated config cache.
1328 	 */
1329 	spa_config_sync(spa, B_FALSE, B_TRUE);
1330 
1331 	spa_close(spa, FTAG);
1332 
1333 	mutex_exit(&spa_namespace_lock);
1334 
1335 	return (0);
1336 }
1337 
1338 /*
1339  * Return the spa_t associated with given pool_guid, if it exists.  If
1340  * device_guid is non-zero, determine whether the pool exists *and* contains
1341  * a device with the specified device_guid.
1342  */
1343 spa_t *
spa_by_guid(uint64_t pool_guid,uint64_t device_guid)1344 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1345 {
1346 	spa_t *spa;
1347 	avl_tree_t *t = &spa_namespace_avl;
1348 
1349 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1350 
1351 	for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1352 		if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1353 			continue;
1354 		if (spa->spa_root_vdev == NULL)
1355 			continue;
1356 		if (spa_guid(spa) == pool_guid) {
1357 			if (device_guid == 0)
1358 				break;
1359 
1360 			if (vdev_lookup_by_guid(spa->spa_root_vdev,
1361 			    device_guid) != NULL)
1362 				break;
1363 
1364 			/*
1365 			 * Check any devices we may be in the process of adding.
1366 			 */
1367 			if (spa->spa_pending_vdev) {
1368 				if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1369 				    device_guid) != NULL)
1370 					break;
1371 			}
1372 		}
1373 	}
1374 
1375 	return (spa);
1376 }
1377 
1378 /*
1379  * Determine whether a pool with the given pool_guid exists.
1380  */
1381 boolean_t
spa_guid_exists(uint64_t pool_guid,uint64_t device_guid)1382 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1383 {
1384 	return (spa_by_guid(pool_guid, device_guid) != NULL);
1385 }
1386 
1387 char *
spa_strdup(const char * s)1388 spa_strdup(const char *s)
1389 {
1390 	size_t len;
1391 	char *new;
1392 
1393 	len = strlen(s);
1394 	new = kmem_alloc(len + 1, KM_SLEEP);
1395 	bcopy(s, new, len);
1396 	new[len] = '\0';
1397 
1398 	return (new);
1399 }
1400 
1401 void
spa_strfree(char * s)1402 spa_strfree(char *s)
1403 {
1404 	kmem_free(s, strlen(s) + 1);
1405 }
1406 
1407 uint64_t
spa_get_random(uint64_t range)1408 spa_get_random(uint64_t range)
1409 {
1410 	uint64_t r;
1411 
1412 	ASSERT(range != 0);
1413 
1414 	(void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
1415 
1416 	return (r % range);
1417 }
1418 
1419 uint64_t
spa_generate_guid(spa_t * spa)1420 spa_generate_guid(spa_t *spa)
1421 {
1422 	uint64_t guid = spa_get_random(-1ULL);
1423 
1424 	if (spa != NULL) {
1425 		while (guid == 0 || spa_guid_exists(spa_guid(spa), guid))
1426 			guid = spa_get_random(-1ULL);
1427 	} else {
1428 		while (guid == 0 || spa_guid_exists(guid, 0))
1429 			guid = spa_get_random(-1ULL);
1430 	}
1431 
1432 	return (guid);
1433 }
1434 
1435 void
snprintf_blkptr(char * buf,size_t buflen,const blkptr_t * bp)1436 snprintf_blkptr(char *buf, size_t buflen, const blkptr_t *bp)
1437 {
1438 	char type[256];
1439 	char *checksum = NULL;
1440 	char *compress = NULL;
1441 
1442 	if (bp != NULL) {
1443 		if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1444 			dmu_object_byteswap_t bswap =
1445 			    DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1446 			(void) snprintf(type, sizeof (type), "bswap %s %s",
1447 			    DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1448 			    "metadata" : "data",
1449 			    dmu_ot_byteswap[bswap].ob_name);
1450 		} else {
1451 			(void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1452 			    sizeof (type));
1453 		}
1454 		if (!BP_IS_EMBEDDED(bp)) {
1455 			checksum =
1456 			    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1457 		}
1458 		compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1459 	}
1460 
1461 	SNPRINTF_BLKPTR(snprintf, ' ', buf, buflen, bp, type, checksum,
1462 	    compress);
1463 }
1464 
1465 void
spa_freeze(spa_t * spa)1466 spa_freeze(spa_t *spa)
1467 {
1468 	uint64_t freeze_txg = 0;
1469 
1470 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1471 	if (spa->spa_freeze_txg == UINT64_MAX) {
1472 		freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1473 		spa->spa_freeze_txg = freeze_txg;
1474 	}
1475 	spa_config_exit(spa, SCL_ALL, FTAG);
1476 	if (freeze_txg != 0)
1477 		txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1478 }
1479 
1480 void
zfs_panic_recover(const char * fmt,...)1481 zfs_panic_recover(const char *fmt, ...)
1482 {
1483 	va_list adx;
1484 
1485 	va_start(adx, fmt);
1486 	vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1487 	va_end(adx);
1488 }
1489 
1490 /*
1491  * This is a stripped-down version of strtoull, suitable only for converting
1492  * lowercase hexadecimal numbers that don't overflow.
1493  */
1494 uint64_t
zfs_strtonum(const char * str,char ** nptr)1495 zfs_strtonum(const char *str, char **nptr)
1496 {
1497 	uint64_t val = 0;
1498 	char c;
1499 	int digit;
1500 
1501 	while ((c = *str) != '\0') {
1502 		if (c >= '0' && c <= '9')
1503 			digit = c - '0';
1504 		else if (c >= 'a' && c <= 'f')
1505 			digit = 10 + c - 'a';
1506 		else
1507 			break;
1508 
1509 		val *= 16;
1510 		val += digit;
1511 
1512 		str++;
1513 	}
1514 
1515 	if (nptr)
1516 		*nptr = (char *)str;
1517 
1518 	return (val);
1519 }
1520 
1521 /*
1522  * ==========================================================================
1523  * Accessor functions
1524  * ==========================================================================
1525  */
1526 
1527 boolean_t
spa_shutting_down(spa_t * spa)1528 spa_shutting_down(spa_t *spa)
1529 {
1530 	return (spa->spa_async_suspended);
1531 }
1532 
1533 dsl_pool_t *
spa_get_dsl(spa_t * spa)1534 spa_get_dsl(spa_t *spa)
1535 {
1536 	return (spa->spa_dsl_pool);
1537 }
1538 
1539 boolean_t
spa_is_initializing(spa_t * spa)1540 spa_is_initializing(spa_t *spa)
1541 {
1542 	return (spa->spa_is_initializing);
1543 }
1544 
1545 blkptr_t *
spa_get_rootblkptr(spa_t * spa)1546 spa_get_rootblkptr(spa_t *spa)
1547 {
1548 	return (&spa->spa_ubsync.ub_rootbp);
1549 }
1550 
1551 void
spa_set_rootblkptr(spa_t * spa,const blkptr_t * bp)1552 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1553 {
1554 	spa->spa_uberblock.ub_rootbp = *bp;
1555 }
1556 
1557 void
spa_altroot(spa_t * spa,char * buf,size_t buflen)1558 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1559 {
1560 	if (spa->spa_root == NULL)
1561 		buf[0] = '\0';
1562 	else
1563 		(void) strncpy(buf, spa->spa_root, buflen);
1564 }
1565 
1566 int
spa_sync_pass(spa_t * spa)1567 spa_sync_pass(spa_t *spa)
1568 {
1569 	return (spa->spa_sync_pass);
1570 }
1571 
1572 char *
spa_name(spa_t * spa)1573 spa_name(spa_t *spa)
1574 {
1575 	return (spa->spa_name);
1576 }
1577 
1578 uint64_t
spa_guid(spa_t * spa)1579 spa_guid(spa_t *spa)
1580 {
1581 	dsl_pool_t *dp = spa_get_dsl(spa);
1582 	uint64_t guid;
1583 
1584 	/*
1585 	 * If we fail to parse the config during spa_load(), we can go through
1586 	 * the error path (which posts an ereport) and end up here with no root
1587 	 * vdev.  We stash the original pool guid in 'spa_config_guid' to handle
1588 	 * this case.
1589 	 */
1590 	if (spa->spa_root_vdev == NULL)
1591 		return (spa->spa_config_guid);
1592 
1593 	guid = spa->spa_last_synced_guid != 0 ?
1594 	    spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1595 
1596 	/*
1597 	 * Return the most recently synced out guid unless we're
1598 	 * in syncing context.
1599 	 */
1600 	if (dp && dsl_pool_sync_context(dp))
1601 		return (spa->spa_root_vdev->vdev_guid);
1602 	else
1603 		return (guid);
1604 }
1605 
1606 uint64_t
spa_load_guid(spa_t * spa)1607 spa_load_guid(spa_t *spa)
1608 {
1609 	/*
1610 	 * This is a GUID that exists solely as a reference for the
1611 	 * purposes of the arc.  It is generated at load time, and
1612 	 * is never written to persistent storage.
1613 	 */
1614 	return (spa->spa_load_guid);
1615 }
1616 
1617 uint64_t
spa_last_synced_txg(spa_t * spa)1618 spa_last_synced_txg(spa_t *spa)
1619 {
1620 	return (spa->spa_ubsync.ub_txg);
1621 }
1622 
1623 uint64_t
spa_first_txg(spa_t * spa)1624 spa_first_txg(spa_t *spa)
1625 {
1626 	return (spa->spa_first_txg);
1627 }
1628 
1629 uint64_t
spa_syncing_txg(spa_t * spa)1630 spa_syncing_txg(spa_t *spa)
1631 {
1632 	return (spa->spa_syncing_txg);
1633 }
1634 
1635 pool_state_t
spa_state(spa_t * spa)1636 spa_state(spa_t *spa)
1637 {
1638 	return (spa->spa_state);
1639 }
1640 
1641 spa_load_state_t
spa_load_state(spa_t * spa)1642 spa_load_state(spa_t *spa)
1643 {
1644 	return (spa->spa_load_state);
1645 }
1646 
1647 uint64_t
spa_freeze_txg(spa_t * spa)1648 spa_freeze_txg(spa_t *spa)
1649 {
1650 	return (spa->spa_freeze_txg);
1651 }
1652 
1653 /* ARGSUSED */
1654 uint64_t
spa_get_asize(spa_t * spa,uint64_t lsize)1655 spa_get_asize(spa_t *spa, uint64_t lsize)
1656 {
1657 	return (lsize * spa_asize_inflation);
1658 }
1659 
1660 /*
1661  * Return the amount of slop space in bytes.  It is 1/32 of the pool (3.2%),
1662  * or at least 32MB.
1663  *
1664  * See the comment above spa_slop_shift for details.
1665  */
1666 uint64_t
spa_get_slop_space(spa_t * spa)1667 spa_get_slop_space(spa_t *spa) {
1668 	uint64_t space = spa_get_dspace(spa);
1669 	return (MAX(space >> spa_slop_shift, SPA_MINDEVSIZE >> 1));
1670 }
1671 
1672 uint64_t
spa_get_dspace(spa_t * spa)1673 spa_get_dspace(spa_t *spa)
1674 {
1675 	return (spa->spa_dspace);
1676 }
1677 
1678 void
spa_update_dspace(spa_t * spa)1679 spa_update_dspace(spa_t *spa)
1680 {
1681 	spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1682 	    ddt_get_dedup_dspace(spa);
1683 }
1684 
1685 /*
1686  * Return the failure mode that has been set to this pool. The default
1687  * behavior will be to block all I/Os when a complete failure occurs.
1688  */
1689 uint8_t
spa_get_failmode(spa_t * spa)1690 spa_get_failmode(spa_t *spa)
1691 {
1692 	return (spa->spa_failmode);
1693 }
1694 
1695 boolean_t
spa_suspended(spa_t * spa)1696 spa_suspended(spa_t *spa)
1697 {
1698 	return (spa->spa_suspended);
1699 }
1700 
1701 uint64_t
spa_version(spa_t * spa)1702 spa_version(spa_t *spa)
1703 {
1704 	return (spa->spa_ubsync.ub_version);
1705 }
1706 
1707 boolean_t
spa_deflate(spa_t * spa)1708 spa_deflate(spa_t *spa)
1709 {
1710 	return (spa->spa_deflate);
1711 }
1712 
1713 metaslab_class_t *
spa_normal_class(spa_t * spa)1714 spa_normal_class(spa_t *spa)
1715 {
1716 	return (spa->spa_normal_class);
1717 }
1718 
1719 metaslab_class_t *
spa_log_class(spa_t * spa)1720 spa_log_class(spa_t *spa)
1721 {
1722 	return (spa->spa_log_class);
1723 }
1724 
1725 int
spa_max_replication(spa_t * spa)1726 spa_max_replication(spa_t *spa)
1727 {
1728 	/*
1729 	 * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1730 	 * handle BPs with more than one DVA allocated.  Set our max
1731 	 * replication level accordingly.
1732 	 */
1733 	if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1734 		return (1);
1735 	return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1736 }
1737 
1738 int
spa_prev_software_version(spa_t * spa)1739 spa_prev_software_version(spa_t *spa)
1740 {
1741 	return (spa->spa_prev_software_version);
1742 }
1743 
1744 uint64_t
spa_deadman_synctime(spa_t * spa)1745 spa_deadman_synctime(spa_t *spa)
1746 {
1747 	return (spa->spa_deadman_synctime);
1748 }
1749 
1750 uint64_t
dva_get_dsize_sync(spa_t * spa,const dva_t * dva)1751 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
1752 {
1753 	uint64_t asize = DVA_GET_ASIZE(dva);
1754 	uint64_t dsize = asize;
1755 
1756 	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1757 
1758 	if (asize != 0 && spa->spa_deflate) {
1759 		vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
1760 		if (vd != NULL)
1761 			dsize = (asize >> SPA_MINBLOCKSHIFT) *
1762 				vd->vdev_deflate_ratio;
1763 	}
1764 
1765 	return (dsize);
1766 }
1767 
1768 uint64_t
bp_get_dsize_sync(spa_t * spa,const blkptr_t * bp)1769 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
1770 {
1771 	uint64_t dsize = 0;
1772 
1773 	for (int d = 0; d < BP_GET_NDVAS(bp); d++)
1774 		dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1775 
1776 	return (dsize);
1777 }
1778 
1779 uint64_t
bp_get_dsize(spa_t * spa,const blkptr_t * bp)1780 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
1781 {
1782 	uint64_t dsize = 0;
1783 
1784 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1785 
1786 	for (int d = 0; d < BP_GET_NDVAS(bp); d++)
1787 		dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1788 
1789 	spa_config_exit(spa, SCL_VDEV, FTAG);
1790 
1791 	return (dsize);
1792 }
1793 
1794 /*
1795  * ==========================================================================
1796  * Initialization and Termination
1797  * ==========================================================================
1798  */
1799 
1800 static int
spa_name_compare(const void * a1,const void * a2)1801 spa_name_compare(const void *a1, const void *a2)
1802 {
1803 	const spa_t *s1 = a1;
1804 	const spa_t *s2 = a2;
1805 	int s;
1806 
1807 	s = strcmp(s1->spa_name, s2->spa_name);
1808 	if (s > 0)
1809 		return (1);
1810 	if (s < 0)
1811 		return (-1);
1812 	return (0);
1813 }
1814 
1815 int
spa_busy(void)1816 spa_busy(void)
1817 {
1818 	return (spa_active_count);
1819 }
1820 
1821 void
spa_boot_init()1822 spa_boot_init()
1823 {
1824 	spa_config_load();
1825 }
1826 
1827 #ifdef _KERNEL
1828 EVENTHANDLER_DEFINE(mountroot, spa_boot_init, NULL, 0);
1829 #endif
1830 
1831 void
spa_init(int mode)1832 spa_init(int mode)
1833 {
1834 	mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
1835 	mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
1836 	mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
1837 	cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
1838 
1839 	avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
1840 	    offsetof(spa_t, spa_avl));
1841 
1842 	avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
1843 	    offsetof(spa_aux_t, aux_avl));
1844 
1845 	avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
1846 	    offsetof(spa_aux_t, aux_avl));
1847 
1848 	spa_mode_global = mode;
1849 
1850 #ifdef illumos
1851 #ifdef _KERNEL
1852 	spa_arch_init();
1853 #else
1854 	if (spa_mode_global != FREAD && dprintf_find_string("watch")) {
1855 		arc_procfd = open("/proc/self/ctl", O_WRONLY);
1856 		if (arc_procfd == -1) {
1857 			perror("could not enable watchpoints: "
1858 			    "opening /proc/self/ctl failed: ");
1859 		} else {
1860 			arc_watch = B_TRUE;
1861 		}
1862 	}
1863 #endif
1864 #endif /* illumos */
1865 	refcount_sysinit();
1866 	unique_init();
1867 	range_tree_init();
1868 	zio_init();
1869 	lz4_init();
1870 	dmu_init();
1871 	zil_init();
1872 	vdev_cache_stat_init();
1873 	zfs_prop_init();
1874 	zpool_prop_init();
1875 	zpool_feature_init();
1876 	spa_config_load();
1877 	l2arc_start();
1878 #ifndef illumos
1879 #ifdef _KERNEL
1880 	zfs_deadman_init();
1881 #endif
1882 #endif	/* !illumos */
1883 }
1884 
1885 void
spa_fini(void)1886 spa_fini(void)
1887 {
1888 	l2arc_stop();
1889 
1890 	spa_evict_all();
1891 
1892 	vdev_cache_stat_fini();
1893 	zil_fini();
1894 	dmu_fini();
1895 	lz4_fini();
1896 	zio_fini();
1897 	range_tree_fini();
1898 	unique_fini();
1899 	refcount_fini();
1900 
1901 	avl_destroy(&spa_namespace_avl);
1902 	avl_destroy(&spa_spare_avl);
1903 	avl_destroy(&spa_l2cache_avl);
1904 
1905 	cv_destroy(&spa_namespace_cv);
1906 	mutex_destroy(&spa_namespace_lock);
1907 	mutex_destroy(&spa_spare_lock);
1908 	mutex_destroy(&spa_l2cache_lock);
1909 }
1910 
1911 /*
1912  * Return whether this pool has slogs. No locking needed.
1913  * It's not a problem if the wrong answer is returned as it's only for
1914  * performance and not correctness
1915  */
1916 boolean_t
spa_has_slogs(spa_t * spa)1917 spa_has_slogs(spa_t *spa)
1918 {
1919 	return (spa->spa_log_class->mc_rotor != NULL);
1920 }
1921 
1922 spa_log_state_t
spa_get_log_state(spa_t * spa)1923 spa_get_log_state(spa_t *spa)
1924 {
1925 	return (spa->spa_log_state);
1926 }
1927 
1928 void
spa_set_log_state(spa_t * spa,spa_log_state_t state)1929 spa_set_log_state(spa_t *spa, spa_log_state_t state)
1930 {
1931 	spa->spa_log_state = state;
1932 }
1933 
1934 boolean_t
spa_is_root(spa_t * spa)1935 spa_is_root(spa_t *spa)
1936 {
1937 	return (spa->spa_is_root);
1938 }
1939 
1940 boolean_t
spa_writeable(spa_t * spa)1941 spa_writeable(spa_t *spa)
1942 {
1943 	return (!!(spa->spa_mode & FWRITE));
1944 }
1945 
1946 /*
1947  * Returns true if there is a pending sync task in any of the current
1948  * syncing txg, the current quiescing txg, or the current open txg.
1949  */
1950 boolean_t
spa_has_pending_synctask(spa_t * spa)1951 spa_has_pending_synctask(spa_t *spa)
1952 {
1953 	return (!txg_all_lists_empty(&spa->spa_dsl_pool->dp_sync_tasks));
1954 }
1955 
1956 int
spa_mode(spa_t * spa)1957 spa_mode(spa_t *spa)
1958 {
1959 	return (spa->spa_mode);
1960 }
1961 
1962 uint64_t
spa_bootfs(spa_t * spa)1963 spa_bootfs(spa_t *spa)
1964 {
1965 	return (spa->spa_bootfs);
1966 }
1967 
1968 uint64_t
spa_delegation(spa_t * spa)1969 spa_delegation(spa_t *spa)
1970 {
1971 	return (spa->spa_delegation);
1972 }
1973 
1974 objset_t *
spa_meta_objset(spa_t * spa)1975 spa_meta_objset(spa_t *spa)
1976 {
1977 	return (spa->spa_meta_objset);
1978 }
1979 
1980 enum zio_checksum
spa_dedup_checksum(spa_t * spa)1981 spa_dedup_checksum(spa_t *spa)
1982 {
1983 	return (spa->spa_dedup_checksum);
1984 }
1985 
1986 /*
1987  * Reset pool scan stat per scan pass (or reboot).
1988  */
1989 void
spa_scan_stat_init(spa_t * spa)1990 spa_scan_stat_init(spa_t *spa)
1991 {
1992 	/* data not stored on disk */
1993 	spa->spa_scan_pass_start = gethrestime_sec();
1994 	spa->spa_scan_pass_exam = 0;
1995 	vdev_scan_stat_init(spa->spa_root_vdev);
1996 }
1997 
1998 /*
1999  * Get scan stats for zpool status reports
2000  */
2001 int
spa_scan_get_stats(spa_t * spa,pool_scan_stat_t * ps)2002 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
2003 {
2004 	dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
2005 
2006 	if (scn == NULL || scn->scn_phys.scn_func == POOL_SCAN_NONE)
2007 		return (SET_ERROR(ENOENT));
2008 	bzero(ps, sizeof (pool_scan_stat_t));
2009 
2010 	/* data stored on disk */
2011 	ps->pss_func = scn->scn_phys.scn_func;
2012 	ps->pss_start_time = scn->scn_phys.scn_start_time;
2013 	ps->pss_end_time = scn->scn_phys.scn_end_time;
2014 	ps->pss_to_examine = scn->scn_phys.scn_to_examine;
2015 	ps->pss_examined = scn->scn_phys.scn_examined;
2016 	ps->pss_to_process = scn->scn_phys.scn_to_process;
2017 	ps->pss_processed = scn->scn_phys.scn_processed;
2018 	ps->pss_errors = scn->scn_phys.scn_errors;
2019 	ps->pss_state = scn->scn_phys.scn_state;
2020 
2021 	/* data not stored on disk */
2022 	ps->pss_pass_start = spa->spa_scan_pass_start;
2023 	ps->pss_pass_exam = spa->spa_scan_pass_exam;
2024 
2025 	return (0);
2026 }
2027 
2028 boolean_t
spa_debug_enabled(spa_t * spa)2029 spa_debug_enabled(spa_t *spa)
2030 {
2031 	return (spa->spa_debug);
2032 }
2033 
2034 int
spa_maxblocksize(spa_t * spa)2035 spa_maxblocksize(spa_t *spa)
2036 {
2037 	if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
2038 		return (SPA_MAXBLOCKSIZE);
2039 	else
2040 		return (SPA_OLD_MAXBLOCKSIZE);
2041 }
2042