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