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