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