xref: /illumos-gate/usr/src/uts/common/fs/zfs/spa_misc.c (revision 663207adb1669640c01c5ec6949ce78fd806efae)
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 int
919 spa_aux_compare(const void *a, const void *b)
920 {
921 	const spa_aux_t *sa = a;
922 	const spa_aux_t *sb = b;
923 
924 	if (sa->aux_guid < sb->aux_guid)
925 		return (-1);
926 	else if (sa->aux_guid > sb->aux_guid)
927 		return (1);
928 	else
929 		return (0);
930 }
931 
932 void
933 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
934 {
935 	avl_index_t where;
936 	spa_aux_t search;
937 	spa_aux_t *aux;
938 
939 	search.aux_guid = vd->vdev_guid;
940 	if ((aux = avl_find(avl, &search, &where)) != NULL) {
941 		aux->aux_count++;
942 	} else {
943 		aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
944 		aux->aux_guid = vd->vdev_guid;
945 		aux->aux_count = 1;
946 		avl_insert(avl, aux, where);
947 	}
948 }
949 
950 void
951 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
952 {
953 	spa_aux_t search;
954 	spa_aux_t *aux;
955 	avl_index_t where;
956 
957 	search.aux_guid = vd->vdev_guid;
958 	aux = avl_find(avl, &search, &where);
959 
960 	ASSERT(aux != NULL);
961 
962 	if (--aux->aux_count == 0) {
963 		avl_remove(avl, aux);
964 		kmem_free(aux, sizeof (spa_aux_t));
965 	} else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
966 		aux->aux_pool = 0ULL;
967 	}
968 }
969 
970 boolean_t
971 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
972 {
973 	spa_aux_t search, *found;
974 
975 	search.aux_guid = guid;
976 	found = avl_find(avl, &search, NULL);
977 
978 	if (pool) {
979 		if (found)
980 			*pool = found->aux_pool;
981 		else
982 			*pool = 0ULL;
983 	}
984 
985 	if (refcnt) {
986 		if (found)
987 			*refcnt = found->aux_count;
988 		else
989 			*refcnt = 0;
990 	}
991 
992 	return (found != NULL);
993 }
994 
995 void
996 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
997 {
998 	spa_aux_t search, *found;
999 	avl_index_t where;
1000 
1001 	search.aux_guid = vd->vdev_guid;
1002 	found = avl_find(avl, &search, &where);
1003 	ASSERT(found != NULL);
1004 	ASSERT(found->aux_pool == 0ULL);
1005 
1006 	found->aux_pool = spa_guid(vd->vdev_spa);
1007 }
1008 
1009 /*
1010  * Spares are tracked globally due to the following constraints:
1011  *
1012  *	- A spare may be part of multiple pools.
1013  *	- A spare may be added to a pool even if it's actively in use within
1014  *	  another pool.
1015  *	- A spare in use in any pool can only be the source of a replacement if
1016  *	  the target is a spare in the same pool.
1017  *
1018  * We keep track of all spares on the system through the use of a reference
1019  * counted AVL tree.  When a vdev is added as a spare, or used as a replacement
1020  * spare, then we bump the reference count in the AVL tree.  In addition, we set
1021  * the 'vdev_isspare' member to indicate that the device is a spare (active or
1022  * inactive).  When a spare is made active (used to replace a device in the
1023  * pool), we also keep track of which pool its been made a part of.
1024  *
1025  * The 'spa_spare_lock' protects the AVL tree.  These functions are normally
1026  * called under the spa_namespace lock as part of vdev reconfiguration.  The
1027  * separate spare lock exists for the status query path, which does not need to
1028  * be completely consistent with respect to other vdev configuration changes.
1029  */
1030 
1031 static int
1032 spa_spare_compare(const void *a, const void *b)
1033 {
1034 	return (spa_aux_compare(a, b));
1035 }
1036 
1037 void
1038 spa_spare_add(vdev_t *vd)
1039 {
1040 	mutex_enter(&spa_spare_lock);
1041 	ASSERT(!vd->vdev_isspare);
1042 	spa_aux_add(vd, &spa_spare_avl);
1043 	vd->vdev_isspare = B_TRUE;
1044 	mutex_exit(&spa_spare_lock);
1045 }
1046 
1047 void
1048 spa_spare_remove(vdev_t *vd)
1049 {
1050 	mutex_enter(&spa_spare_lock);
1051 	ASSERT(vd->vdev_isspare);
1052 	spa_aux_remove(vd, &spa_spare_avl);
1053 	vd->vdev_isspare = B_FALSE;
1054 	mutex_exit(&spa_spare_lock);
1055 }
1056 
1057 boolean_t
1058 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
1059 {
1060 	boolean_t found;
1061 
1062 	mutex_enter(&spa_spare_lock);
1063 	found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
1064 	mutex_exit(&spa_spare_lock);
1065 
1066 	return (found);
1067 }
1068 
1069 void
1070 spa_spare_activate(vdev_t *vd)
1071 {
1072 	mutex_enter(&spa_spare_lock);
1073 	ASSERT(vd->vdev_isspare);
1074 	spa_aux_activate(vd, &spa_spare_avl);
1075 	mutex_exit(&spa_spare_lock);
1076 }
1077 
1078 /*
1079  * Level 2 ARC devices are tracked globally for the same reasons as spares.
1080  * Cache devices currently only support one pool per cache device, and so
1081  * for these devices the aux reference count is currently unused beyond 1.
1082  */
1083 
1084 static int
1085 spa_l2cache_compare(const void *a, const void *b)
1086 {
1087 	return (spa_aux_compare(a, b));
1088 }
1089 
1090 void
1091 spa_l2cache_add(vdev_t *vd)
1092 {
1093 	mutex_enter(&spa_l2cache_lock);
1094 	ASSERT(!vd->vdev_isl2cache);
1095 	spa_aux_add(vd, &spa_l2cache_avl);
1096 	vd->vdev_isl2cache = B_TRUE;
1097 	mutex_exit(&spa_l2cache_lock);
1098 }
1099 
1100 void
1101 spa_l2cache_remove(vdev_t *vd)
1102 {
1103 	mutex_enter(&spa_l2cache_lock);
1104 	ASSERT(vd->vdev_isl2cache);
1105 	spa_aux_remove(vd, &spa_l2cache_avl);
1106 	vd->vdev_isl2cache = B_FALSE;
1107 	mutex_exit(&spa_l2cache_lock);
1108 }
1109 
1110 boolean_t
1111 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
1112 {
1113 	boolean_t found;
1114 
1115 	mutex_enter(&spa_l2cache_lock);
1116 	found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
1117 	mutex_exit(&spa_l2cache_lock);
1118 
1119 	return (found);
1120 }
1121 
1122 void
1123 spa_l2cache_activate(vdev_t *vd)
1124 {
1125 	mutex_enter(&spa_l2cache_lock);
1126 	ASSERT(vd->vdev_isl2cache);
1127 	spa_aux_activate(vd, &spa_l2cache_avl);
1128 	mutex_exit(&spa_l2cache_lock);
1129 }
1130 
1131 /*
1132  * ==========================================================================
1133  * SPA vdev locking
1134  * ==========================================================================
1135  */
1136 
1137 /*
1138  * Lock the given spa_t for the purpose of adding or removing a vdev.
1139  * Grabs the global spa_namespace_lock plus the spa config lock for writing.
1140  * It returns the next transaction group for the spa_t.
1141  */
1142 uint64_t
1143 spa_vdev_enter(spa_t *spa)
1144 {
1145 	mutex_enter(&spa->spa_vdev_top_lock);
1146 	mutex_enter(&spa_namespace_lock);
1147 	return (spa_vdev_config_enter(spa));
1148 }
1149 
1150 /*
1151  * Internal implementation for spa_vdev_enter().  Used when a vdev
1152  * operation requires multiple syncs (i.e. removing a device) while
1153  * keeping the spa_namespace_lock held.
1154  */
1155 uint64_t
1156 spa_vdev_config_enter(spa_t *spa)
1157 {
1158 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1159 
1160 	spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1161 
1162 	return (spa_last_synced_txg(spa) + 1);
1163 }
1164 
1165 /*
1166  * Used in combination with spa_vdev_config_enter() to allow the syncing
1167  * of multiple transactions without releasing the spa_namespace_lock.
1168  */
1169 void
1170 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error, char *tag)
1171 {
1172 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1173 
1174 	int config_changed = B_FALSE;
1175 
1176 	ASSERT(txg > spa_last_synced_txg(spa));
1177 
1178 	spa->spa_pending_vdev = NULL;
1179 
1180 	/*
1181 	 * Reassess the DTLs.
1182 	 */
1183 	vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE);
1184 
1185 	if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
1186 		config_changed = B_TRUE;
1187 		spa->spa_config_generation++;
1188 	}
1189 
1190 	/*
1191 	 * Verify the metaslab classes.
1192 	 */
1193 	ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
1194 	ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
1195 	ASSERT(metaslab_class_validate(spa_special_class(spa)) == 0);
1196 	ASSERT(metaslab_class_validate(spa_dedup_class(spa)) == 0);
1197 
1198 	spa_config_exit(spa, SCL_ALL, spa);
1199 
1200 	/*
1201 	 * Panic the system if the specified tag requires it.  This
1202 	 * is useful for ensuring that configurations are updated
1203 	 * transactionally.
1204 	 */
1205 	if (zio_injection_enabled)
1206 		zio_handle_panic_injection(spa, tag, 0);
1207 
1208 	/*
1209 	 * Note: this txg_wait_synced() is important because it ensures
1210 	 * that there won't be more than one config change per txg.
1211 	 * This allows us to use the txg as the generation number.
1212 	 */
1213 	if (error == 0)
1214 		txg_wait_synced(spa->spa_dsl_pool, txg);
1215 
1216 	if (vd != NULL) {
1217 		ASSERT(!vd->vdev_detached || vd->vdev_dtl_sm == NULL);
1218 		if (vd->vdev_ops->vdev_op_leaf) {
1219 			mutex_enter(&vd->vdev_initialize_lock);
1220 			vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED);
1221 			mutex_exit(&vd->vdev_initialize_lock);
1222 		}
1223 
1224 		spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1225 		vdev_free(vd);
1226 		spa_config_exit(spa, SCL_ALL, spa);
1227 	}
1228 
1229 	/*
1230 	 * If the config changed, update the config cache.
1231 	 */
1232 	if (config_changed)
1233 		spa_write_cachefile(spa, B_FALSE, B_TRUE);
1234 }
1235 
1236 /*
1237  * Unlock the spa_t after adding or removing a vdev.  Besides undoing the
1238  * locking of spa_vdev_enter(), we also want make sure the transactions have
1239  * synced to disk, and then update the global configuration cache with the new
1240  * information.
1241  */
1242 int
1243 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
1244 {
1245 	spa_vdev_config_exit(spa, vd, txg, error, FTAG);
1246 	mutex_exit(&spa_namespace_lock);
1247 	mutex_exit(&spa->spa_vdev_top_lock);
1248 
1249 	return (error);
1250 }
1251 
1252 /*
1253  * Lock the given spa_t for the purpose of changing vdev state.
1254  */
1255 void
1256 spa_vdev_state_enter(spa_t *spa, int oplocks)
1257 {
1258 	int locks = SCL_STATE_ALL | oplocks;
1259 
1260 	/*
1261 	 * Root pools may need to read of the underlying devfs filesystem
1262 	 * when opening up a vdev.  Unfortunately if we're holding the
1263 	 * SCL_ZIO lock it will result in a deadlock when we try to issue
1264 	 * the read from the root filesystem.  Instead we "prefetch"
1265 	 * the associated vnodes that we need prior to opening the
1266 	 * underlying devices and cache them so that we can prevent
1267 	 * any I/O when we are doing the actual open.
1268 	 */
1269 	if (spa_is_root(spa)) {
1270 		int low = locks & ~(SCL_ZIO - 1);
1271 		int high = locks & ~low;
1272 
1273 		spa_config_enter(spa, high, spa, RW_WRITER);
1274 		vdev_hold(spa->spa_root_vdev);
1275 		spa_config_enter(spa, low, spa, RW_WRITER);
1276 	} else {
1277 		spa_config_enter(spa, locks, spa, RW_WRITER);
1278 	}
1279 	spa->spa_vdev_locks = locks;
1280 }
1281 
1282 int
1283 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
1284 {
1285 	boolean_t config_changed = B_FALSE;
1286 
1287 	if (vd != NULL || error == 0)
1288 		vdev_dtl_reassess(vd ? vd->vdev_top : spa->spa_root_vdev,
1289 		    0, 0, B_FALSE);
1290 
1291 	if (vd != NULL) {
1292 		vdev_state_dirty(vd->vdev_top);
1293 		config_changed = B_TRUE;
1294 		spa->spa_config_generation++;
1295 	}
1296 
1297 	if (spa_is_root(spa))
1298 		vdev_rele(spa->spa_root_vdev);
1299 
1300 	ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1301 	spa_config_exit(spa, spa->spa_vdev_locks, spa);
1302 
1303 	/*
1304 	 * If anything changed, wait for it to sync.  This ensures that,
1305 	 * from the system administrator's perspective, zpool(1M) commands
1306 	 * are synchronous.  This is important for things like zpool offline:
1307 	 * when the command completes, you expect no further I/O from ZFS.
1308 	 */
1309 	if (vd != NULL)
1310 		txg_wait_synced(spa->spa_dsl_pool, 0);
1311 
1312 	/*
1313 	 * If the config changed, update the config cache.
1314 	 */
1315 	if (config_changed) {
1316 		mutex_enter(&spa_namespace_lock);
1317 		spa_write_cachefile(spa, B_FALSE, B_TRUE);
1318 		mutex_exit(&spa_namespace_lock);
1319 	}
1320 
1321 	return (error);
1322 }
1323 
1324 /*
1325  * ==========================================================================
1326  * Miscellaneous functions
1327  * ==========================================================================
1328  */
1329 
1330 void
1331 spa_activate_mos_feature(spa_t *spa, const char *feature, dmu_tx_t *tx)
1332 {
1333 	if (!nvlist_exists(spa->spa_label_features, feature)) {
1334 		fnvlist_add_boolean(spa->spa_label_features, feature);
1335 		/*
1336 		 * When we are creating the pool (tx_txg==TXG_INITIAL), we can't
1337 		 * dirty the vdev config because lock SCL_CONFIG is not held.
1338 		 * Thankfully, in this case we don't need to dirty the config
1339 		 * because it will be written out anyway when we finish
1340 		 * creating the pool.
1341 		 */
1342 		if (tx->tx_txg != TXG_INITIAL)
1343 			vdev_config_dirty(spa->spa_root_vdev);
1344 	}
1345 }
1346 
1347 void
1348 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1349 {
1350 	if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1351 		vdev_config_dirty(spa->spa_root_vdev);
1352 }
1353 
1354 /*
1355  * Return the spa_t associated with given pool_guid, if it exists.  If
1356  * device_guid is non-zero, determine whether the pool exists *and* contains
1357  * a device with the specified device_guid.
1358  */
1359 spa_t *
1360 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1361 {
1362 	spa_t *spa;
1363 	avl_tree_t *t = &spa_namespace_avl;
1364 
1365 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1366 
1367 	for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1368 		if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1369 			continue;
1370 		if (spa->spa_root_vdev == NULL)
1371 			continue;
1372 		if (spa_guid(spa) == pool_guid) {
1373 			if (device_guid == 0)
1374 				break;
1375 
1376 			if (vdev_lookup_by_guid(spa->spa_root_vdev,
1377 			    device_guid) != NULL)
1378 				break;
1379 
1380 			/*
1381 			 * Check any devices we may be in the process of adding.
1382 			 */
1383 			if (spa->spa_pending_vdev) {
1384 				if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1385 				    device_guid) != NULL)
1386 					break;
1387 			}
1388 		}
1389 	}
1390 
1391 	return (spa);
1392 }
1393 
1394 /*
1395  * Determine whether a pool with the given pool_guid exists.
1396  */
1397 boolean_t
1398 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1399 {
1400 	return (spa_by_guid(pool_guid, device_guid) != NULL);
1401 }
1402 
1403 char *
1404 spa_strdup(const char *s)
1405 {
1406 	size_t len;
1407 	char *new;
1408 
1409 	len = strlen(s);
1410 	new = kmem_alloc(len + 1, KM_SLEEP);
1411 	bcopy(s, new, len);
1412 	new[len] = '\0';
1413 
1414 	return (new);
1415 }
1416 
1417 void
1418 spa_strfree(char *s)
1419 {
1420 	kmem_free(s, strlen(s) + 1);
1421 }
1422 
1423 uint64_t
1424 spa_get_random(uint64_t range)
1425 {
1426 	uint64_t r;
1427 
1428 	ASSERT(range != 0);
1429 
1430 	if (range == 1)
1431 		return (0);
1432 
1433 	(void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
1434 
1435 	return (r % range);
1436 }
1437 
1438 uint64_t
1439 spa_generate_guid(spa_t *spa)
1440 {
1441 	uint64_t guid = spa_get_random(-1ULL);
1442 
1443 	if (spa != NULL) {
1444 		while (guid == 0 || spa_guid_exists(spa_guid(spa), guid))
1445 			guid = spa_get_random(-1ULL);
1446 	} else {
1447 		while (guid == 0 || spa_guid_exists(guid, 0))
1448 			guid = spa_get_random(-1ULL);
1449 	}
1450 
1451 	return (guid);
1452 }
1453 
1454 void
1455 snprintf_blkptr(char *buf, size_t buflen, const blkptr_t *bp)
1456 {
1457 	char type[256];
1458 	char *checksum = NULL;
1459 	char *compress = NULL;
1460 
1461 	if (bp != NULL) {
1462 		if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1463 			dmu_object_byteswap_t bswap =
1464 			    DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1465 			(void) snprintf(type, sizeof (type), "bswap %s %s",
1466 			    DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1467 			    "metadata" : "data",
1468 			    dmu_ot_byteswap[bswap].ob_name);
1469 		} else {
1470 			(void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1471 			    sizeof (type));
1472 		}
1473 		if (!BP_IS_EMBEDDED(bp)) {
1474 			checksum =
1475 			    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1476 		}
1477 		compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1478 	}
1479 
1480 	SNPRINTF_BLKPTR(snprintf, ' ', buf, buflen, bp, type, checksum,
1481 	    compress);
1482 }
1483 
1484 void
1485 spa_freeze(spa_t *spa)
1486 {
1487 	uint64_t freeze_txg = 0;
1488 
1489 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1490 	if (spa->spa_freeze_txg == UINT64_MAX) {
1491 		freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1492 		spa->spa_freeze_txg = freeze_txg;
1493 	}
1494 	spa_config_exit(spa, SCL_ALL, FTAG);
1495 	if (freeze_txg != 0)
1496 		txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1497 }
1498 
1499 void
1500 zfs_panic_recover(const char *fmt, ...)
1501 {
1502 	va_list adx;
1503 
1504 	va_start(adx, fmt);
1505 	vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1506 	va_end(adx);
1507 }
1508 
1509 /*
1510  * This is a stripped-down version of strtoull, suitable only for converting
1511  * lowercase hexadecimal numbers that don't overflow.
1512  */
1513 uint64_t
1514 zfs_strtonum(const char *str, char **nptr)
1515 {
1516 	uint64_t val = 0;
1517 	char c;
1518 	int digit;
1519 
1520 	while ((c = *str) != '\0') {
1521 		if (c >= '0' && c <= '9')
1522 			digit = c - '0';
1523 		else if (c >= 'a' && c <= 'f')
1524 			digit = 10 + c - 'a';
1525 		else
1526 			break;
1527 
1528 		val *= 16;
1529 		val += digit;
1530 
1531 		str++;
1532 	}
1533 
1534 	if (nptr)
1535 		*nptr = (char *)str;
1536 
1537 	return (val);
1538 }
1539 
1540 void
1541 spa_activate_allocation_classes(spa_t *spa, dmu_tx_t *tx)
1542 {
1543 	/*
1544 	 * We bump the feature refcount for each special vdev added to the pool
1545 	 */
1546 	ASSERT(spa_feature_is_enabled(spa, SPA_FEATURE_ALLOCATION_CLASSES));
1547 	spa_feature_incr(spa, SPA_FEATURE_ALLOCATION_CLASSES, tx);
1548 }
1549 
1550 /*
1551  * ==========================================================================
1552  * Accessor functions
1553  * ==========================================================================
1554  */
1555 
1556 boolean_t
1557 spa_shutting_down(spa_t *spa)
1558 {
1559 	return (spa->spa_async_suspended);
1560 }
1561 
1562 dsl_pool_t *
1563 spa_get_dsl(spa_t *spa)
1564 {
1565 	return (spa->spa_dsl_pool);
1566 }
1567 
1568 boolean_t
1569 spa_is_initializing(spa_t *spa)
1570 {
1571 	return (spa->spa_is_initializing);
1572 }
1573 
1574 boolean_t
1575 spa_indirect_vdevs_loaded(spa_t *spa)
1576 {
1577 	return (spa->spa_indirect_vdevs_loaded);
1578 }
1579 
1580 blkptr_t *
1581 spa_get_rootblkptr(spa_t *spa)
1582 {
1583 	return (&spa->spa_ubsync.ub_rootbp);
1584 }
1585 
1586 void
1587 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1588 {
1589 	spa->spa_uberblock.ub_rootbp = *bp;
1590 }
1591 
1592 void
1593 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1594 {
1595 	if (spa->spa_root == NULL)
1596 		buf[0] = '\0';
1597 	else
1598 		(void) strncpy(buf, spa->spa_root, buflen);
1599 }
1600 
1601 int
1602 spa_sync_pass(spa_t *spa)
1603 {
1604 	return (spa->spa_sync_pass);
1605 }
1606 
1607 char *
1608 spa_name(spa_t *spa)
1609 {
1610 	return (spa->spa_name);
1611 }
1612 
1613 uint64_t
1614 spa_guid(spa_t *spa)
1615 {
1616 	dsl_pool_t *dp = spa_get_dsl(spa);
1617 	uint64_t guid;
1618 
1619 	/*
1620 	 * If we fail to parse the config during spa_load(), we can go through
1621 	 * the error path (which posts an ereport) and end up here with no root
1622 	 * vdev.  We stash the original pool guid in 'spa_config_guid' to handle
1623 	 * this case.
1624 	 */
1625 	if (spa->spa_root_vdev == NULL)
1626 		return (spa->spa_config_guid);
1627 
1628 	guid = spa->spa_last_synced_guid != 0 ?
1629 	    spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1630 
1631 	/*
1632 	 * Return the most recently synced out guid unless we're
1633 	 * in syncing context.
1634 	 */
1635 	if (dp && dsl_pool_sync_context(dp))
1636 		return (spa->spa_root_vdev->vdev_guid);
1637 	else
1638 		return (guid);
1639 }
1640 
1641 uint64_t
1642 spa_load_guid(spa_t *spa)
1643 {
1644 	/*
1645 	 * This is a GUID that exists solely as a reference for the
1646 	 * purposes of the arc.  It is generated at load time, and
1647 	 * is never written to persistent storage.
1648 	 */
1649 	return (spa->spa_load_guid);
1650 }
1651 
1652 uint64_t
1653 spa_last_synced_txg(spa_t *spa)
1654 {
1655 	return (spa->spa_ubsync.ub_txg);
1656 }
1657 
1658 uint64_t
1659 spa_first_txg(spa_t *spa)
1660 {
1661 	return (spa->spa_first_txg);
1662 }
1663 
1664 uint64_t
1665 spa_syncing_txg(spa_t *spa)
1666 {
1667 	return (spa->spa_syncing_txg);
1668 }
1669 
1670 /*
1671  * Return the last txg where data can be dirtied. The final txgs
1672  * will be used to just clear out any deferred frees that remain.
1673  */
1674 uint64_t
1675 spa_final_dirty_txg(spa_t *spa)
1676 {
1677 	return (spa->spa_final_txg - TXG_DEFER_SIZE);
1678 }
1679 
1680 pool_state_t
1681 spa_state(spa_t *spa)
1682 {
1683 	return (spa->spa_state);
1684 }
1685 
1686 spa_load_state_t
1687 spa_load_state(spa_t *spa)
1688 {
1689 	return (spa->spa_load_state);
1690 }
1691 
1692 uint64_t
1693 spa_freeze_txg(spa_t *spa)
1694 {
1695 	return (spa->spa_freeze_txg);
1696 }
1697 
1698 /* ARGSUSED */
1699 uint64_t
1700 spa_get_worst_case_asize(spa_t *spa, uint64_t lsize)
1701 {
1702 	return (lsize * spa_asize_inflation);
1703 }
1704 
1705 /*
1706  * Return the amount of slop space in bytes.  It is 1/32 of the pool (3.2%),
1707  * or at least 128MB, unless that would cause it to be more than half the
1708  * pool size.
1709  *
1710  * See the comment above spa_slop_shift for details.
1711  */
1712 uint64_t
1713 spa_get_slop_space(spa_t *spa)
1714 {
1715 	uint64_t space = spa_get_dspace(spa);
1716 	return (MAX(space >> spa_slop_shift, MIN(space >> 1, spa_min_slop)));
1717 }
1718 
1719 uint64_t
1720 spa_get_dspace(spa_t *spa)
1721 {
1722 	return (spa->spa_dspace);
1723 }
1724 
1725 uint64_t
1726 spa_get_checkpoint_space(spa_t *spa)
1727 {
1728 	return (spa->spa_checkpoint_info.sci_dspace);
1729 }
1730 
1731 void
1732 spa_update_dspace(spa_t *spa)
1733 {
1734 	spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1735 	    ddt_get_dedup_dspace(spa);
1736 	if (spa->spa_vdev_removal != NULL) {
1737 		/*
1738 		 * We can't allocate from the removing device, so
1739 		 * subtract its size.  This prevents the DMU/DSL from
1740 		 * filling up the (now smaller) pool while we are in the
1741 		 * middle of removing the device.
1742 		 *
1743 		 * Note that the DMU/DSL doesn't actually know or care
1744 		 * how much space is allocated (it does its own tracking
1745 		 * of how much space has been logically used).  So it
1746 		 * doesn't matter that the data we are moving may be
1747 		 * allocated twice (on the old device and the new
1748 		 * device).
1749 		 */
1750 		spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1751 		vdev_t *vd =
1752 		    vdev_lookup_top(spa, spa->spa_vdev_removal->svr_vdev_id);
1753 		spa->spa_dspace -= spa_deflate(spa) ?
1754 		    vd->vdev_stat.vs_dspace : vd->vdev_stat.vs_space;
1755 		spa_config_exit(spa, SCL_VDEV, FTAG);
1756 	}
1757 }
1758 
1759 /*
1760  * Return the failure mode that has been set to this pool. The default
1761  * behavior will be to block all I/Os when a complete failure occurs.
1762  */
1763 uint8_t
1764 spa_get_failmode(spa_t *spa)
1765 {
1766 	return (spa->spa_failmode);
1767 }
1768 
1769 boolean_t
1770 spa_suspended(spa_t *spa)
1771 {
1772 	return (spa->spa_suspended != ZIO_SUSPEND_NONE);
1773 }
1774 
1775 uint64_t
1776 spa_version(spa_t *spa)
1777 {
1778 	return (spa->spa_ubsync.ub_version);
1779 }
1780 
1781 boolean_t
1782 spa_deflate(spa_t *spa)
1783 {
1784 	return (spa->spa_deflate);
1785 }
1786 
1787 metaslab_class_t *
1788 spa_normal_class(spa_t *spa)
1789 {
1790 	return (spa->spa_normal_class);
1791 }
1792 
1793 metaslab_class_t *
1794 spa_log_class(spa_t *spa)
1795 {
1796 	return (spa->spa_log_class);
1797 }
1798 
1799 metaslab_class_t *
1800 spa_special_class(spa_t *spa)
1801 {
1802 	return (spa->spa_special_class);
1803 }
1804 
1805 metaslab_class_t *
1806 spa_dedup_class(spa_t *spa)
1807 {
1808 	return (spa->spa_dedup_class);
1809 }
1810 
1811 /*
1812  * Locate an appropriate allocation class
1813  */
1814 metaslab_class_t *
1815 spa_preferred_class(spa_t *spa, uint64_t size, dmu_object_type_t objtype,
1816     uint_t level, uint_t special_smallblk)
1817 {
1818 	if (DMU_OT_IS_ZIL(objtype)) {
1819 		if (spa->spa_log_class->mc_groups != 0)
1820 			return (spa_log_class(spa));
1821 		else
1822 			return (spa_normal_class(spa));
1823 	}
1824 
1825 	boolean_t has_special_class = spa->spa_special_class->mc_groups != 0;
1826 
1827 	if (DMU_OT_IS_DDT(objtype)) {
1828 		if (spa->spa_dedup_class->mc_groups != 0)
1829 			return (spa_dedup_class(spa));
1830 		else if (has_special_class && zfs_ddt_data_is_special)
1831 			return (spa_special_class(spa));
1832 		else
1833 			return (spa_normal_class(spa));
1834 	}
1835 
1836 	/* Indirect blocks for user data can land in special if allowed */
1837 	if (level > 0 && (DMU_OT_IS_FILE(objtype) || objtype == DMU_OT_ZVOL)) {
1838 		if (has_special_class && zfs_user_indirect_is_special)
1839 			return (spa_special_class(spa));
1840 		else
1841 			return (spa_normal_class(spa));
1842 	}
1843 
1844 	if (DMU_OT_IS_METADATA(objtype) || level > 0) {
1845 		if (has_special_class)
1846 			return (spa_special_class(spa));
1847 		else
1848 			return (spa_normal_class(spa));
1849 	}
1850 
1851 	/*
1852 	 * Allow small file blocks in special class in some cases (like
1853 	 * for the dRAID vdev feature). But always leave a reserve of
1854 	 * zfs_special_class_metadata_reserve_pct exclusively for metadata.
1855 	 */
1856 	if (DMU_OT_IS_FILE(objtype) &&
1857 	    has_special_class && size <= special_smallblk) {
1858 		metaslab_class_t *special = spa_special_class(spa);
1859 		uint64_t alloc = metaslab_class_get_alloc(special);
1860 		uint64_t space = metaslab_class_get_space(special);
1861 		uint64_t limit =
1862 		    (space * (100 - zfs_special_class_metadata_reserve_pct))
1863 		    / 100;
1864 
1865 		if (alloc < limit)
1866 			return (special);
1867 	}
1868 
1869 	return (spa_normal_class(spa));
1870 }
1871 
1872 void
1873 spa_evicting_os_register(spa_t *spa, objset_t *os)
1874 {
1875 	mutex_enter(&spa->spa_evicting_os_lock);
1876 	list_insert_head(&spa->spa_evicting_os_list, os);
1877 	mutex_exit(&spa->spa_evicting_os_lock);
1878 }
1879 
1880 void
1881 spa_evicting_os_deregister(spa_t *spa, objset_t *os)
1882 {
1883 	mutex_enter(&spa->spa_evicting_os_lock);
1884 	list_remove(&spa->spa_evicting_os_list, os);
1885 	cv_broadcast(&spa->spa_evicting_os_cv);
1886 	mutex_exit(&spa->spa_evicting_os_lock);
1887 }
1888 
1889 void
1890 spa_evicting_os_wait(spa_t *spa)
1891 {
1892 	mutex_enter(&spa->spa_evicting_os_lock);
1893 	while (!list_is_empty(&spa->spa_evicting_os_list))
1894 		cv_wait(&spa->spa_evicting_os_cv, &spa->spa_evicting_os_lock);
1895 	mutex_exit(&spa->spa_evicting_os_lock);
1896 
1897 	dmu_buf_user_evict_wait();
1898 }
1899 
1900 int
1901 spa_max_replication(spa_t *spa)
1902 {
1903 	/*
1904 	 * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1905 	 * handle BPs with more than one DVA allocated.  Set our max
1906 	 * replication level accordingly.
1907 	 */
1908 	if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1909 		return (1);
1910 	return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1911 }
1912 
1913 int
1914 spa_prev_software_version(spa_t *spa)
1915 {
1916 	return (spa->spa_prev_software_version);
1917 }
1918 
1919 uint64_t
1920 spa_deadman_synctime(spa_t *spa)
1921 {
1922 	return (spa->spa_deadman_synctime);
1923 }
1924 
1925 uint64_t
1926 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
1927 {
1928 	uint64_t asize = DVA_GET_ASIZE(dva);
1929 	uint64_t dsize = asize;
1930 
1931 	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1932 
1933 	if (asize != 0 && spa->spa_deflate) {
1934 		vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
1935 		dsize = (asize >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio;
1936 	}
1937 
1938 	return (dsize);
1939 }
1940 
1941 uint64_t
1942 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
1943 {
1944 	uint64_t dsize = 0;
1945 
1946 	for (int d = 0; d < BP_GET_NDVAS(bp); d++)
1947 		dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1948 
1949 	return (dsize);
1950 }
1951 
1952 uint64_t
1953 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
1954 {
1955 	uint64_t dsize = 0;
1956 
1957 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1958 
1959 	for (int d = 0; d < BP_GET_NDVAS(bp); d++)
1960 		dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1961 
1962 	spa_config_exit(spa, SCL_VDEV, FTAG);
1963 
1964 	return (dsize);
1965 }
1966 
1967 uint64_t
1968 spa_dirty_data(spa_t *spa)
1969 {
1970 	return (spa->spa_dsl_pool->dp_dirty_total);
1971 }
1972 
1973 /*
1974  * ==========================================================================
1975  * Initialization and Termination
1976  * ==========================================================================
1977  */
1978 
1979 static int
1980 spa_name_compare(const void *a1, const void *a2)
1981 {
1982 	const spa_t *s1 = a1;
1983 	const spa_t *s2 = a2;
1984 	int s;
1985 
1986 	s = strcmp(s1->spa_name, s2->spa_name);
1987 	if (s > 0)
1988 		return (1);
1989 	if (s < 0)
1990 		return (-1);
1991 	return (0);
1992 }
1993 
1994 int
1995 spa_busy(void)
1996 {
1997 	return (spa_active_count);
1998 }
1999 
2000 void
2001 spa_boot_init()
2002 {
2003 	spa_config_load();
2004 }
2005 
2006 void
2007 spa_init(int mode)
2008 {
2009 	mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
2010 	mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
2011 	mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
2012 	cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
2013 
2014 	avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
2015 	    offsetof(spa_t, spa_avl));
2016 
2017 	avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
2018 	    offsetof(spa_aux_t, aux_avl));
2019 
2020 	avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
2021 	    offsetof(spa_aux_t, aux_avl));
2022 
2023 	spa_mode_global = mode;
2024 
2025 #ifdef _KERNEL
2026 	spa_arch_init();
2027 #else
2028 	if (spa_mode_global != FREAD && dprintf_find_string("watch")) {
2029 		arc_procfd = open("/proc/self/ctl", O_WRONLY);
2030 		if (arc_procfd == -1) {
2031 			perror("could not enable watchpoints: "
2032 			    "opening /proc/self/ctl failed: ");
2033 		} else {
2034 			arc_watch = B_TRUE;
2035 		}
2036 	}
2037 #endif
2038 
2039 	zfs_refcount_init();
2040 	unique_init();
2041 	range_tree_init();
2042 	metaslab_alloc_trace_init();
2043 	zio_init();
2044 	dmu_init();
2045 	zil_init();
2046 	vdev_cache_stat_init();
2047 	zfs_prop_init();
2048 	zpool_prop_init();
2049 	zpool_feature_init();
2050 	spa_config_load();
2051 	l2arc_start();
2052 }
2053 
2054 void
2055 spa_fini(void)
2056 {
2057 	l2arc_stop();
2058 
2059 	spa_evict_all();
2060 
2061 	vdev_cache_stat_fini();
2062 	zil_fini();
2063 	dmu_fini();
2064 	zio_fini();
2065 	metaslab_alloc_trace_fini();
2066 	range_tree_fini();
2067 	unique_fini();
2068 	zfs_refcount_fini();
2069 
2070 	avl_destroy(&spa_namespace_avl);
2071 	avl_destroy(&spa_spare_avl);
2072 	avl_destroy(&spa_l2cache_avl);
2073 
2074 	cv_destroy(&spa_namespace_cv);
2075 	mutex_destroy(&spa_namespace_lock);
2076 	mutex_destroy(&spa_spare_lock);
2077 	mutex_destroy(&spa_l2cache_lock);
2078 }
2079 
2080 /*
2081  * Return whether this pool has slogs. No locking needed.
2082  * It's not a problem if the wrong answer is returned as it's only for
2083  * performance and not correctness
2084  */
2085 boolean_t
2086 spa_has_slogs(spa_t *spa)
2087 {
2088 	return (spa->spa_log_class->mc_rotor != NULL);
2089 }
2090 
2091 spa_log_state_t
2092 spa_get_log_state(spa_t *spa)
2093 {
2094 	return (spa->spa_log_state);
2095 }
2096 
2097 void
2098 spa_set_log_state(spa_t *spa, spa_log_state_t state)
2099 {
2100 	spa->spa_log_state = state;
2101 }
2102 
2103 boolean_t
2104 spa_is_root(spa_t *spa)
2105 {
2106 	return (spa->spa_is_root);
2107 }
2108 
2109 boolean_t
2110 spa_writeable(spa_t *spa)
2111 {
2112 	return (!!(spa->spa_mode & FWRITE) && spa->spa_trust_config);
2113 }
2114 
2115 /*
2116  * Returns true if there is a pending sync task in any of the current
2117  * syncing txg, the current quiescing txg, or the current open txg.
2118  */
2119 boolean_t
2120 spa_has_pending_synctask(spa_t *spa)
2121 {
2122 	return (!txg_all_lists_empty(&spa->spa_dsl_pool->dp_sync_tasks) ||
2123 	    !txg_all_lists_empty(&spa->spa_dsl_pool->dp_early_sync_tasks));
2124 }
2125 
2126 int
2127 spa_mode(spa_t *spa)
2128 {
2129 	return (spa->spa_mode);
2130 }
2131 
2132 uint64_t
2133 spa_bootfs(spa_t *spa)
2134 {
2135 	return (spa->spa_bootfs);
2136 }
2137 
2138 uint64_t
2139 spa_delegation(spa_t *spa)
2140 {
2141 	return (spa->spa_delegation);
2142 }
2143 
2144 objset_t *
2145 spa_meta_objset(spa_t *spa)
2146 {
2147 	return (spa->spa_meta_objset);
2148 }
2149 
2150 enum zio_checksum
2151 spa_dedup_checksum(spa_t *spa)
2152 {
2153 	return (spa->spa_dedup_checksum);
2154 }
2155 
2156 /*
2157  * Reset pool scan stat per scan pass (or reboot).
2158  */
2159 void
2160 spa_scan_stat_init(spa_t *spa)
2161 {
2162 	/* data not stored on disk */
2163 	spa->spa_scan_pass_start = gethrestime_sec();
2164 	if (dsl_scan_is_paused_scrub(spa->spa_dsl_pool->dp_scan))
2165 		spa->spa_scan_pass_scrub_pause = spa->spa_scan_pass_start;
2166 	else
2167 		spa->spa_scan_pass_scrub_pause = 0;
2168 	spa->spa_scan_pass_scrub_spent_paused = 0;
2169 	spa->spa_scan_pass_exam = 0;
2170 	vdev_scan_stat_init(spa->spa_root_vdev);
2171 }
2172 
2173 /*
2174  * Get scan stats for zpool status reports
2175  */
2176 int
2177 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
2178 {
2179 	dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
2180 
2181 	if (scn == NULL || scn->scn_phys.scn_func == POOL_SCAN_NONE)
2182 		return (SET_ERROR(ENOENT));
2183 	bzero(ps, sizeof (pool_scan_stat_t));
2184 
2185 	/* data stored on disk */
2186 	ps->pss_func = scn->scn_phys.scn_func;
2187 	ps->pss_start_time = scn->scn_phys.scn_start_time;
2188 	ps->pss_end_time = scn->scn_phys.scn_end_time;
2189 	ps->pss_to_examine = scn->scn_phys.scn_to_examine;
2190 	ps->pss_examined = scn->scn_phys.scn_examined;
2191 	ps->pss_to_process = scn->scn_phys.scn_to_process;
2192 	ps->pss_processed = scn->scn_phys.scn_processed;
2193 	ps->pss_errors = scn->scn_phys.scn_errors;
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_scrub_pause = spa->spa_scan_pass_scrub_pause;
2200 	ps->pss_pass_scrub_spent_paused = spa->spa_scan_pass_scrub_spent_paused;
2201 
2202 	return (0);
2203 }
2204 
2205 int
2206 spa_maxblocksize(spa_t *spa)
2207 {
2208 	if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
2209 		return (SPA_MAXBLOCKSIZE);
2210 	else
2211 		return (SPA_OLD_MAXBLOCKSIZE);
2212 }
2213 
2214 int
2215 spa_maxdnodesize(spa_t *spa)
2216 {
2217 	if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE))
2218 		return (DNODE_MAX_SIZE);
2219 	else
2220 		return (DNODE_MIN_SIZE);
2221 }
2222 
2223 boolean_t
2224 spa_multihost(spa_t *spa)
2225 {
2226 	return (spa->spa_multihost ? B_TRUE : B_FALSE);
2227 }
2228 
2229 unsigned long
2230 spa_get_hostid(void)
2231 {
2232 	unsigned long myhostid;
2233 
2234 #ifdef	_KERNEL
2235 	myhostid = zone_get_hostid(NULL);
2236 #else	/* _KERNEL */
2237 	/*
2238 	 * We're emulating the system's hostid in userland, so
2239 	 * we can't use zone_get_hostid().
2240 	 */
2241 	(void) ddi_strtoul(hw_serial, NULL, 10, &myhostid);
2242 #endif	/* _KERNEL */
2243 
2244 	return (myhostid);
2245 }
2246 
2247 /*
2248  * Returns the txg that the last device removal completed. No indirect mappings
2249  * have been added since this txg.
2250  */
2251 uint64_t
2252 spa_get_last_removal_txg(spa_t *spa)
2253 {
2254 	uint64_t vdevid;
2255 	uint64_t ret = -1ULL;
2256 
2257 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2258 	/*
2259 	 * sr_prev_indirect_vdev is only modified while holding all the
2260 	 * config locks, so it is sufficient to hold SCL_VDEV as reader when
2261 	 * examining it.
2262 	 */
2263 	vdevid = spa->spa_removing_phys.sr_prev_indirect_vdev;
2264 
2265 	while (vdevid != -1ULL) {
2266 		vdev_t *vd = vdev_lookup_top(spa, vdevid);
2267 		vdev_indirect_births_t *vib = vd->vdev_indirect_births;
2268 
2269 		ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
2270 
2271 		/*
2272 		 * If the removal did not remap any data, we don't care.
2273 		 */
2274 		if (vdev_indirect_births_count(vib) != 0) {
2275 			ret = vdev_indirect_births_last_entry_txg(vib);
2276 			break;
2277 		}
2278 
2279 		vdevid = vd->vdev_indirect_config.vic_prev_indirect_vdev;
2280 	}
2281 	spa_config_exit(spa, SCL_VDEV, FTAG);
2282 
2283 	IMPLY(ret != -1ULL,
2284 	    spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
2285 
2286 	return (ret);
2287 }
2288 
2289 boolean_t
2290 spa_trust_config(spa_t *spa)
2291 {
2292 	return (spa->spa_trust_config);
2293 }
2294 
2295 uint64_t
2296 spa_missing_tvds_allowed(spa_t *spa)
2297 {
2298 	return (spa->spa_missing_tvds_allowed);
2299 }
2300 
2301 void
2302 spa_set_missing_tvds(spa_t *spa, uint64_t missing)
2303 {
2304 	spa->spa_missing_tvds = missing;
2305 }
2306 
2307 boolean_t
2308 spa_top_vdevs_spacemap_addressable(spa_t *spa)
2309 {
2310 	vdev_t *rvd = spa->spa_root_vdev;
2311 	for (uint64_t c = 0; c < rvd->vdev_children; c++) {
2312 		if (!vdev_is_spacemap_addressable(rvd->vdev_child[c]))
2313 			return (B_FALSE);
2314 	}
2315 	return (B_TRUE);
2316 }
2317 
2318 boolean_t
2319 spa_has_checkpoint(spa_t *spa)
2320 {
2321 	return (spa->spa_checkpoint_txg != 0);
2322 }
2323 
2324 boolean_t
2325 spa_importing_readonly_checkpoint(spa_t *spa)
2326 {
2327 	return ((spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT) &&
2328 	    spa->spa_mode == FREAD);
2329 }
2330 
2331 uint64_t
2332 spa_min_claim_txg(spa_t *spa)
2333 {
2334 	uint64_t checkpoint_txg = spa->spa_uberblock.ub_checkpoint_txg;
2335 
2336 	if (checkpoint_txg != 0)
2337 		return (checkpoint_txg + 1);
2338 
2339 	return (spa->spa_first_txg);
2340 }
2341 
2342 /*
2343  * If there is a checkpoint, async destroys may consume more space from
2344  * the pool instead of freeing it. In an attempt to save the pool from
2345  * getting suspended when it is about to run out of space, we stop
2346  * processing async destroys.
2347  */
2348 boolean_t
2349 spa_suspend_async_destroy(spa_t *spa)
2350 {
2351 	dsl_pool_t *dp = spa_get_dsl(spa);
2352 
2353 	uint64_t unreserved = dsl_pool_unreserved_space(dp,
2354 	    ZFS_SPACE_CHECK_EXTRA_RESERVED);
2355 	uint64_t used = dsl_dir_phys(dp->dp_root_dir)->dd_used_bytes;
2356 	uint64_t avail = (unreserved > used) ? (unreserved - used) : 0;
2357 
2358 	if (spa_has_checkpoint(spa) && avail == 0)
2359 		return (B_TRUE);
2360 
2361 	return (B_FALSE);
2362 }
2363