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