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