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