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