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