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