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