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