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