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