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