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