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