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