]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/contrib/openzfs/module/zfs/spa_misc.c
OpenZFS: MFV 2.0-rc3-gfc5966
[FreeBSD/FreeBSD.git] / sys / contrib / openzfs / 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, 2019 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  * Copyright (c) 2017, Intel Corporation.
29  * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
30  */
31
32 #include <sys/zfs_context.h>
33 #include <sys/spa_impl.h>
34 #include <sys/zio.h>
35 #include <sys/zio_checksum.h>
36 #include <sys/zio_compress.h>
37 #include <sys/dmu.h>
38 #include <sys/dmu_tx.h>
39 #include <sys/zap.h>
40 #include <sys/zil.h>
41 #include <sys/vdev_impl.h>
42 #include <sys/vdev_initialize.h>
43 #include <sys/vdev_trim.h>
44 #include <sys/vdev_file.h>
45 #include <sys/vdev_raidz.h>
46 #include <sys/metaslab.h>
47 #include <sys/uberblock_impl.h>
48 #include <sys/txg.h>
49 #include <sys/avl.h>
50 #include <sys/unique.h>
51 #include <sys/dsl_pool.h>
52 #include <sys/dsl_dir.h>
53 #include <sys/dsl_prop.h>
54 #include <sys/fm/util.h>
55 #include <sys/dsl_scan.h>
56 #include <sys/fs/zfs.h>
57 #include <sys/metaslab_impl.h>
58 #include <sys/arc.h>
59 #include <sys/ddt.h>
60 #include <sys/kstat.h>
61 #include "zfs_prop.h"
62 #include <sys/btree.h>
63 #include <sys/zfeature.h>
64 #include <sys/qat.h>
65 #include <sys/zstd/zstd.h>
66
67 /*
68  * SPA locking
69  *
70  * There are three basic locks for managing spa_t structures:
71  *
72  * spa_namespace_lock (global mutex)
73  *
74  *      This lock must be acquired to do any of the following:
75  *
76  *              - Lookup a spa_t by name
77  *              - Add or remove a spa_t from the namespace
78  *              - Increase spa_refcount from non-zero
79  *              - Check if spa_refcount is zero
80  *              - Rename a spa_t
81  *              - add/remove/attach/detach devices
82  *              - Held for the duration of create/destroy/import/export
83  *
84  *      It does not need to handle recursion.  A create or destroy may
85  *      reference objects (files or zvols) in other pools, but by
86  *      definition they must have an existing reference, and will never need
87  *      to lookup a spa_t by name.
88  *
89  * spa_refcount (per-spa zfs_refcount_t protected by mutex)
90  *
91  *      This reference count keep track of any active users of the spa_t.  The
92  *      spa_t cannot be destroyed or freed while this is non-zero.  Internally,
93  *      the refcount is never really 'zero' - opening a pool implicitly keeps
94  *      some references in the DMU.  Internally we check against spa_minref, but
95  *      present the image of a zero/non-zero value to consumers.
96  *
97  * spa_config_lock[] (per-spa array of rwlocks)
98  *
99  *      This protects the spa_t from config changes, and must be held in
100  *      the following circumstances:
101  *
102  *              - RW_READER to perform I/O to the spa
103  *              - RW_WRITER to change the vdev config
104  *
105  * The locking order is fairly straightforward:
106  *
107  *              spa_namespace_lock      ->      spa_refcount
108  *
109  *      The namespace lock must be acquired to increase the refcount from 0
110  *      or to check if it is zero.
111  *
112  *              spa_refcount            ->      spa_config_lock[]
113  *
114  *      There must be at least one valid reference on the spa_t to acquire
115  *      the config lock.
116  *
117  *              spa_namespace_lock      ->      spa_config_lock[]
118  *
119  *      The namespace lock must always be taken before the config lock.
120  *
121  *
122  * The spa_namespace_lock can be acquired directly and is globally visible.
123  *
124  * The namespace is manipulated using the following functions, all of which
125  * require the spa_namespace_lock to be held.
126  *
127  *      spa_lookup()            Lookup a spa_t by name.
128  *
129  *      spa_add()               Create a new spa_t in the namespace.
130  *
131  *      spa_remove()            Remove a spa_t from the namespace.  This also
132  *                              frees up any memory associated with the spa_t.
133  *
134  *      spa_next()              Returns the next spa_t in the system, or the
135  *                              first if NULL is passed.
136  *
137  *      spa_evict_all()         Shutdown and remove all spa_t structures in
138  *                              the system.
139  *
140  *      spa_guid_exists()       Determine whether a pool/device guid exists.
141  *
142  * The spa_refcount is manipulated using the following functions:
143  *
144  *      spa_open_ref()          Adds a reference to the given spa_t.  Must be
145  *                              called with spa_namespace_lock held if the
146  *                              refcount is currently zero.
147  *
148  *      spa_close()             Remove a reference from the spa_t.  This will
149  *                              not free the spa_t or remove it from the
150  *                              namespace.  No locking is required.
151  *
152  *      spa_refcount_zero()     Returns true if the refcount is currently
153  *                              zero.  Must be called with spa_namespace_lock
154  *                              held.
155  *
156  * The spa_config_lock[] is an array of rwlocks, ordered as follows:
157  * SCL_CONFIG > SCL_STATE > SCL_ALLOC > SCL_ZIO > SCL_FREE > SCL_VDEV.
158  * spa_config_lock[] is manipulated with spa_config_{enter,exit,held}().
159  *
160  * To read the configuration, it suffices to hold one of these locks as reader.
161  * To modify the configuration, you must hold all locks as writer.  To modify
162  * vdev state without altering the vdev tree's topology (e.g. online/offline),
163  * you must hold SCL_STATE and SCL_ZIO as writer.
164  *
165  * We use these distinct config locks to avoid recursive lock entry.
166  * For example, spa_sync() (which holds SCL_CONFIG as reader) induces
167  * block allocations (SCL_ALLOC), which may require reading space maps
168  * from disk (dmu_read() -> zio_read() -> SCL_ZIO).
169  *
170  * The spa config locks cannot be normal rwlocks because we need the
171  * ability to hand off ownership.  For example, SCL_ZIO is acquired
172  * by the issuing thread and later released by an interrupt thread.
173  * They do, however, obey the usual write-wanted semantics to prevent
174  * writer (i.e. system administrator) starvation.
175  *
176  * The lock acquisition rules are as follows:
177  *
178  * SCL_CONFIG
179  *      Protects changes to the vdev tree topology, such as vdev
180  *      add/remove/attach/detach.  Protects the dirty config list
181  *      (spa_config_dirty_list) and the set of spares and l2arc devices.
182  *
183  * SCL_STATE
184  *      Protects changes to pool state and vdev state, such as vdev
185  *      online/offline/fault/degrade/clear.  Protects the dirty state list
186  *      (spa_state_dirty_list) and global pool state (spa_state).
187  *
188  * SCL_ALLOC
189  *      Protects changes to metaslab groups and classes.
190  *      Held as reader by metaslab_alloc() and metaslab_claim().
191  *
192  * SCL_ZIO
193  *      Held by bp-level zios (those which have no io_vd upon entry)
194  *      to prevent changes to the vdev tree.  The bp-level zio implicitly
195  *      protects all of its vdev child zios, which do not hold SCL_ZIO.
196  *
197  * SCL_FREE
198  *      Protects changes to metaslab groups and classes.
199  *      Held as reader by metaslab_free().  SCL_FREE is distinct from
200  *      SCL_ALLOC, and lower than SCL_ZIO, so that we can safely free
201  *      blocks in zio_done() while another i/o that holds either
202  *      SCL_ALLOC or SCL_ZIO is waiting for this i/o to complete.
203  *
204  * SCL_VDEV
205  *      Held as reader to prevent changes to the vdev tree during trivial
206  *      inquiries such as bp_get_dsize().  SCL_VDEV is distinct from the
207  *      other locks, and lower than all of them, to ensure that it's safe
208  *      to acquire regardless of caller context.
209  *
210  * In addition, the following rules apply:
211  *
212  * (a)  spa_props_lock protects pool properties, spa_config and spa_config_list.
213  *      The lock ordering is SCL_CONFIG > spa_props_lock.
214  *
215  * (b)  I/O operations on leaf vdevs.  For any zio operation that takes
216  *      an explicit vdev_t argument -- such as zio_ioctl(), zio_read_phys(),
217  *      or zio_write_phys() -- the caller must ensure that the config cannot
218  *      cannot change in the interim, and that the vdev cannot be reopened.
219  *      SCL_STATE as reader suffices for both.
220  *
221  * The vdev configuration is protected by spa_vdev_enter() / spa_vdev_exit().
222  *
223  *      spa_vdev_enter()        Acquire the namespace lock and the config lock
224  *                              for writing.
225  *
226  *      spa_vdev_exit()         Release the config lock, wait for all I/O
227  *                              to complete, sync the updated configs to the
228  *                              cache, and release the namespace lock.
229  *
230  * vdev state is protected by spa_vdev_state_enter() / spa_vdev_state_exit().
231  * Like spa_vdev_enter/exit, these are convenience wrappers -- the actual
232  * locking is, always, based on spa_namespace_lock and spa_config_lock[].
233  */
234
235 static avl_tree_t spa_namespace_avl;
236 kmutex_t spa_namespace_lock;
237 static kcondvar_t spa_namespace_cv;
238 int spa_max_replication_override = SPA_DVAS_PER_BP;
239
240 static kmutex_t spa_spare_lock;
241 static avl_tree_t spa_spare_avl;
242 static kmutex_t spa_l2cache_lock;
243 static avl_tree_t spa_l2cache_avl;
244
245 kmem_cache_t *spa_buffer_pool;
246 spa_mode_t spa_mode_global = SPA_MODE_UNINIT;
247
248 #ifdef ZFS_DEBUG
249 /*
250  * Everything except dprintf, set_error, spa, and indirect_remap is on
251  * by default in debug builds.
252  */
253 int zfs_flags = ~(ZFS_DEBUG_DPRINTF | ZFS_DEBUG_SET_ERROR |
254     ZFS_DEBUG_INDIRECT_REMAP);
255 #else
256 int zfs_flags = 0;
257 #endif
258
259 /*
260  * zfs_recover can be set to nonzero to attempt to recover from
261  * otherwise-fatal errors, typically caused by on-disk corruption.  When
262  * set, calls to zfs_panic_recover() will turn into warning messages.
263  * This should only be used as a last resort, as it typically results
264  * in leaked space, or worse.
265  */
266 int zfs_recover = B_FALSE;
267
268 /*
269  * If destroy encounters an EIO while reading metadata (e.g. indirect
270  * blocks), space referenced by the missing metadata can not be freed.
271  * Normally this causes the background destroy to become "stalled", as
272  * it is unable to make forward progress.  While in this stalled state,
273  * all remaining space to free from the error-encountering filesystem is
274  * "temporarily leaked".  Set this flag to cause it to ignore the EIO,
275  * permanently leak the space from indirect blocks that can not be read,
276  * and continue to free everything else that it can.
277  *
278  * The default, "stalling" behavior is useful if the storage partially
279  * fails (i.e. some but not all i/os fail), and then later recovers.  In
280  * this case, we will be able to continue pool operations while it is
281  * partially failed, and when it recovers, we can continue to free the
282  * space, with no leaks.  However, note that this case is actually
283  * fairly rare.
284  *
285  * Typically pools either (a) fail completely (but perhaps temporarily,
286  * e.g. a top-level vdev going offline), or (b) have localized,
287  * permanent errors (e.g. disk returns the wrong data due to bit flip or
288  * firmware bug).  In case (a), this setting does not matter because the
289  * pool will be suspended and the sync thread will not be able to make
290  * forward progress regardless.  In case (b), because the error is
291  * permanent, the best we can do is leak the minimum amount of space,
292  * which is what setting this flag will do.  Therefore, it is reasonable
293  * for this flag to normally be set, but we chose the more conservative
294  * approach of not setting it, so that there is no possibility of
295  * leaking space in the "partial temporary" failure case.
296  */
297 int zfs_free_leak_on_eio = B_FALSE;
298
299 /*
300  * Expiration time in milliseconds. This value has two meanings. First it is
301  * used to determine when the spa_deadman() logic should fire. By default the
302  * spa_deadman() will fire if spa_sync() has not completed in 600 seconds.
303  * Secondly, the value determines if an I/O is considered "hung". Any I/O that
304  * has not completed in zfs_deadman_synctime_ms is considered "hung" resulting
305  * in one of three behaviors controlled by zfs_deadman_failmode.
306  */
307 unsigned long zfs_deadman_synctime_ms = 600000UL;
308
309 /*
310  * This value controls the maximum amount of time zio_wait() will block for an
311  * outstanding IO.  By default this is 300 seconds at which point the "hung"
312  * behavior will be applied as described for zfs_deadman_synctime_ms.
313  */
314 unsigned long zfs_deadman_ziotime_ms = 300000UL;
315
316 /*
317  * Check time in milliseconds. This defines the frequency at which we check
318  * for hung I/O.
319  */
320 unsigned long zfs_deadman_checktime_ms = 60000UL;
321
322 /*
323  * By default the deadman is enabled.
324  */
325 int zfs_deadman_enabled = 1;
326
327 /*
328  * Controls the behavior of the deadman when it detects a "hung" I/O.
329  * Valid values are zfs_deadman_failmode=<wait|continue|panic>.
330  *
331  * wait     - Wait for the "hung" I/O (default)
332  * continue - Attempt to recover from a "hung" I/O
333  * panic    - Panic the system
334  */
335 char *zfs_deadman_failmode = "wait";
336
337 /*
338  * The worst case is single-sector max-parity RAID-Z blocks, in which
339  * case the space requirement is exactly (VDEV_RAIDZ_MAXPARITY + 1)
340  * times the size; so just assume that.  Add to this the fact that
341  * we can have up to 3 DVAs per bp, and one more factor of 2 because
342  * the block may be dittoed with up to 3 DVAs by ddt_sync().  All together,
343  * the worst case is:
344  *     (VDEV_RAIDZ_MAXPARITY + 1) * SPA_DVAS_PER_BP * 2 == 24
345  */
346 int spa_asize_inflation = 24;
347
348 /*
349  * Normally, we don't allow the last 3.2% (1/(2^spa_slop_shift)) of space in
350  * the pool to be consumed.  This ensures that we don't run the pool
351  * completely out of space, due to unaccounted changes (e.g. to the MOS).
352  * It also limits the worst-case time to allocate space.  If we have
353  * less than this amount of free space, most ZPL operations (e.g. write,
354  * create) will return ENOSPC.
355  *
356  * Certain operations (e.g. file removal, most administrative actions) can
357  * use half the slop space.  They will only return ENOSPC if less than half
358  * the slop space is free.  Typically, once the pool has less than the slop
359  * space free, the user will use these operations to free up space in the pool.
360  * These are the operations that call dsl_pool_adjustedsize() with the netfree
361  * argument set to TRUE.
362  *
363  * Operations that are almost guaranteed to free up space in the absence of
364  * a pool checkpoint can use up to three quarters of the slop space
365  * (e.g zfs destroy).
366  *
367  * A very restricted set of operations are always permitted, regardless of
368  * the amount of free space.  These are the operations that call
369  * dsl_sync_task(ZFS_SPACE_CHECK_NONE). If these operations result in a net
370  * increase in the amount of space used, it is possible to run the pool
371  * completely out of space, causing it to be permanently read-only.
372  *
373  * Note that on very small pools, the slop space will be larger than
374  * 3.2%, in an effort to have it be at least spa_min_slop (128MB),
375  * but we never allow it to be more than half the pool size.
376  *
377  * See also the comments in zfs_space_check_t.
378  */
379 int spa_slop_shift = 5;
380 uint64_t spa_min_slop = 128 * 1024 * 1024;
381 int spa_allocators = 4;
382
383
384 /*PRINTFLIKE2*/
385 void
386 spa_load_failed(spa_t *spa, const char *fmt, ...)
387 {
388         va_list adx;
389         char buf[256];
390
391         va_start(adx, fmt);
392         (void) vsnprintf(buf, sizeof (buf), fmt, adx);
393         va_end(adx);
394
395         zfs_dbgmsg("spa_load(%s, config %s): FAILED: %s", spa->spa_name,
396             spa->spa_trust_config ? "trusted" : "untrusted", buf);
397 }
398
399 /*PRINTFLIKE2*/
400 void
401 spa_load_note(spa_t *spa, const char *fmt, ...)
402 {
403         va_list adx;
404         char buf[256];
405
406         va_start(adx, fmt);
407         (void) vsnprintf(buf, sizeof (buf), fmt, adx);
408         va_end(adx);
409
410         zfs_dbgmsg("spa_load(%s, config %s): %s", spa->spa_name,
411             spa->spa_trust_config ? "trusted" : "untrusted", buf);
412 }
413
414 /*
415  * By default dedup and user data indirects land in the special class
416  */
417 int zfs_ddt_data_is_special = B_TRUE;
418 int zfs_user_indirect_is_special = B_TRUE;
419
420 /*
421  * The percentage of special class final space reserved for metadata only.
422  * Once we allocate 100 - zfs_special_class_metadata_reserve_pct we only
423  * let metadata into the class.
424  */
425 int zfs_special_class_metadata_reserve_pct = 25;
426
427 /*
428  * ==========================================================================
429  * SPA config locking
430  * ==========================================================================
431  */
432 static void
433 spa_config_lock_init(spa_t *spa)
434 {
435         for (int i = 0; i < SCL_LOCKS; i++) {
436                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
437                 mutex_init(&scl->scl_lock, NULL, MUTEX_DEFAULT, NULL);
438                 cv_init(&scl->scl_cv, NULL, CV_DEFAULT, NULL);
439                 zfs_refcount_create_untracked(&scl->scl_count);
440                 scl->scl_writer = NULL;
441                 scl->scl_write_wanted = 0;
442         }
443 }
444
445 static void
446 spa_config_lock_destroy(spa_t *spa)
447 {
448         for (int i = 0; i < SCL_LOCKS; i++) {
449                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
450                 mutex_destroy(&scl->scl_lock);
451                 cv_destroy(&scl->scl_cv);
452                 zfs_refcount_destroy(&scl->scl_count);
453                 ASSERT(scl->scl_writer == NULL);
454                 ASSERT(scl->scl_write_wanted == 0);
455         }
456 }
457
458 int
459 spa_config_tryenter(spa_t *spa, int locks, void *tag, krw_t rw)
460 {
461         for (int i = 0; i < SCL_LOCKS; i++) {
462                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
463                 if (!(locks & (1 << i)))
464                         continue;
465                 mutex_enter(&scl->scl_lock);
466                 if (rw == RW_READER) {
467                         if (scl->scl_writer || scl->scl_write_wanted) {
468                                 mutex_exit(&scl->scl_lock);
469                                 spa_config_exit(spa, locks & ((1 << i) - 1),
470                                     tag);
471                                 return (0);
472                         }
473                 } else {
474                         ASSERT(scl->scl_writer != curthread);
475                         if (!zfs_refcount_is_zero(&scl->scl_count)) {
476                                 mutex_exit(&scl->scl_lock);
477                                 spa_config_exit(spa, locks & ((1 << i) - 1),
478                                     tag);
479                                 return (0);
480                         }
481                         scl->scl_writer = curthread;
482                 }
483                 (void) zfs_refcount_add(&scl->scl_count, tag);
484                 mutex_exit(&scl->scl_lock);
485         }
486         return (1);
487 }
488
489 void
490 spa_config_enter(spa_t *spa, int locks, const void *tag, krw_t rw)
491 {
492         int wlocks_held = 0;
493
494         ASSERT3U(SCL_LOCKS, <, sizeof (wlocks_held) * NBBY);
495
496         for (int i = 0; i < SCL_LOCKS; i++) {
497                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
498                 if (scl->scl_writer == curthread)
499                         wlocks_held |= (1 << i);
500                 if (!(locks & (1 << i)))
501                         continue;
502                 mutex_enter(&scl->scl_lock);
503                 if (rw == RW_READER) {
504                         while (scl->scl_writer || scl->scl_write_wanted) {
505                                 cv_wait(&scl->scl_cv, &scl->scl_lock);
506                         }
507                 } else {
508                         ASSERT(scl->scl_writer != curthread);
509                         while (!zfs_refcount_is_zero(&scl->scl_count)) {
510                                 scl->scl_write_wanted++;
511                                 cv_wait(&scl->scl_cv, &scl->scl_lock);
512                                 scl->scl_write_wanted--;
513                         }
514                         scl->scl_writer = curthread;
515                 }
516                 (void) zfs_refcount_add(&scl->scl_count, tag);
517                 mutex_exit(&scl->scl_lock);
518         }
519         ASSERT3U(wlocks_held, <=, locks);
520 }
521
522 void
523 spa_config_exit(spa_t *spa, int locks, const void *tag)
524 {
525         for (int i = SCL_LOCKS - 1; i >= 0; i--) {
526                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
527                 if (!(locks & (1 << i)))
528                         continue;
529                 mutex_enter(&scl->scl_lock);
530                 ASSERT(!zfs_refcount_is_zero(&scl->scl_count));
531                 if (zfs_refcount_remove(&scl->scl_count, tag) == 0) {
532                         ASSERT(scl->scl_writer == NULL ||
533                             scl->scl_writer == curthread);
534                         scl->scl_writer = NULL; /* OK in either case */
535                         cv_broadcast(&scl->scl_cv);
536                 }
537                 mutex_exit(&scl->scl_lock);
538         }
539 }
540
541 int
542 spa_config_held(spa_t *spa, int locks, krw_t rw)
543 {
544         int locks_held = 0;
545
546         for (int i = 0; i < SCL_LOCKS; i++) {
547                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
548                 if (!(locks & (1 << i)))
549                         continue;
550                 if ((rw == RW_READER &&
551                     !zfs_refcount_is_zero(&scl->scl_count)) ||
552                     (rw == RW_WRITER && scl->scl_writer == curthread))
553                         locks_held |= 1 << i;
554         }
555
556         return (locks_held);
557 }
558
559 /*
560  * ==========================================================================
561  * SPA namespace functions
562  * ==========================================================================
563  */
564
565 /*
566  * Lookup the named spa_t in the AVL tree.  The spa_namespace_lock must be held.
567  * Returns NULL if no matching spa_t is found.
568  */
569 spa_t *
570 spa_lookup(const char *name)
571 {
572         static spa_t search;    /* spa_t is large; don't allocate on stack */
573         spa_t *spa;
574         avl_index_t where;
575         char *cp;
576
577         ASSERT(MUTEX_HELD(&spa_namespace_lock));
578
579         (void) strlcpy(search.spa_name, name, sizeof (search.spa_name));
580
581         /*
582          * If it's a full dataset name, figure out the pool name and
583          * just use that.
584          */
585         cp = strpbrk(search.spa_name, "/@#");
586         if (cp != NULL)
587                 *cp = '\0';
588
589         spa = avl_find(&spa_namespace_avl, &search, &where);
590
591         return (spa);
592 }
593
594 /*
595  * Fires when spa_sync has not completed within zfs_deadman_synctime_ms.
596  * If the zfs_deadman_enabled flag is set then it inspects all vdev queues
597  * looking for potentially hung I/Os.
598  */
599 void
600 spa_deadman(void *arg)
601 {
602         spa_t *spa = arg;
603
604         /* Disable the deadman if the pool is suspended. */
605         if (spa_suspended(spa))
606                 return;
607
608         zfs_dbgmsg("slow spa_sync: started %llu seconds ago, calls %llu",
609             (gethrtime() - spa->spa_sync_starttime) / NANOSEC,
610             ++spa->spa_deadman_calls);
611         if (zfs_deadman_enabled)
612                 vdev_deadman(spa->spa_root_vdev, FTAG);
613
614         spa->spa_deadman_tqid = taskq_dispatch_delay(system_delay_taskq,
615             spa_deadman, spa, TQ_SLEEP, ddi_get_lbolt() +
616             MSEC_TO_TICK(zfs_deadman_checktime_ms));
617 }
618
619 static int
620 spa_log_sm_sort_by_txg(const void *va, const void *vb)
621 {
622         const spa_log_sm_t *a = va;
623         const spa_log_sm_t *b = vb;
624
625         return (TREE_CMP(a->sls_txg, b->sls_txg));
626 }
627
628 /*
629  * Create an uninitialized spa_t with the given name.  Requires
630  * spa_namespace_lock.  The caller must ensure that the spa_t doesn't already
631  * exist by calling spa_lookup() first.
632  */
633 spa_t *
634 spa_add(const char *name, nvlist_t *config, const char *altroot)
635 {
636         spa_t *spa;
637         spa_config_dirent_t *dp;
638
639         ASSERT(MUTEX_HELD(&spa_namespace_lock));
640
641         spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
642
643         mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
644         mutex_init(&spa->spa_errlist_lock, NULL, MUTEX_DEFAULT, NULL);
645         mutex_init(&spa->spa_errlog_lock, NULL, MUTEX_DEFAULT, NULL);
646         mutex_init(&spa->spa_evicting_os_lock, NULL, MUTEX_DEFAULT, NULL);
647         mutex_init(&spa->spa_history_lock, NULL, MUTEX_DEFAULT, NULL);
648         mutex_init(&spa->spa_proc_lock, NULL, MUTEX_DEFAULT, NULL);
649         mutex_init(&spa->spa_props_lock, NULL, MUTEX_DEFAULT, NULL);
650         mutex_init(&spa->spa_cksum_tmpls_lock, NULL, MUTEX_DEFAULT, NULL);
651         mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
652         mutex_init(&spa->spa_suspend_lock, NULL, MUTEX_DEFAULT, NULL);
653         mutex_init(&spa->spa_vdev_top_lock, NULL, MUTEX_DEFAULT, NULL);
654         mutex_init(&spa->spa_feat_stats_lock, NULL, MUTEX_DEFAULT, NULL);
655         mutex_init(&spa->spa_flushed_ms_lock, NULL, MUTEX_DEFAULT, NULL);
656         mutex_init(&spa->spa_activities_lock, NULL, MUTEX_DEFAULT, NULL);
657
658         cv_init(&spa->spa_async_cv, NULL, CV_DEFAULT, NULL);
659         cv_init(&spa->spa_evicting_os_cv, NULL, CV_DEFAULT, NULL);
660         cv_init(&spa->spa_proc_cv, NULL, CV_DEFAULT, NULL);
661         cv_init(&spa->spa_scrub_io_cv, NULL, CV_DEFAULT, NULL);
662         cv_init(&spa->spa_suspend_cv, NULL, CV_DEFAULT, NULL);
663         cv_init(&spa->spa_activities_cv, NULL, CV_DEFAULT, NULL);
664         cv_init(&spa->spa_waiters_cv, NULL, CV_DEFAULT, NULL);
665
666         for (int t = 0; t < TXG_SIZE; t++)
667                 bplist_create(&spa->spa_free_bplist[t]);
668
669         (void) strlcpy(spa->spa_name, name, sizeof (spa->spa_name));
670         spa->spa_state = POOL_STATE_UNINITIALIZED;
671         spa->spa_freeze_txg = UINT64_MAX;
672         spa->spa_final_txg = UINT64_MAX;
673         spa->spa_load_max_txg = UINT64_MAX;
674         spa->spa_proc = &p0;
675         spa->spa_proc_state = SPA_PROC_NONE;
676         spa->spa_trust_config = B_TRUE;
677         spa->spa_hostid = zone_get_hostid(NULL);
678
679         spa->spa_deadman_synctime = MSEC2NSEC(zfs_deadman_synctime_ms);
680         spa->spa_deadman_ziotime = MSEC2NSEC(zfs_deadman_ziotime_ms);
681         spa_set_deadman_failmode(spa, zfs_deadman_failmode);
682
683         zfs_refcount_create(&spa->spa_refcount);
684         spa_config_lock_init(spa);
685         spa_stats_init(spa);
686
687         avl_add(&spa_namespace_avl, spa);
688
689         /*
690          * Set the alternate root, if there is one.
691          */
692         if (altroot)
693                 spa->spa_root = spa_strdup(altroot);
694
695         spa->spa_alloc_count = spa_allocators;
696         spa->spa_alloc_locks = kmem_zalloc(spa->spa_alloc_count *
697             sizeof (kmutex_t), KM_SLEEP);
698         spa->spa_alloc_trees = kmem_zalloc(spa->spa_alloc_count *
699             sizeof (avl_tree_t), KM_SLEEP);
700         for (int i = 0; i < spa->spa_alloc_count; i++) {
701                 mutex_init(&spa->spa_alloc_locks[i], NULL, MUTEX_DEFAULT, NULL);
702                 avl_create(&spa->spa_alloc_trees[i], zio_bookmark_compare,
703                     sizeof (zio_t), offsetof(zio_t, io_alloc_node));
704         }
705         avl_create(&spa->spa_metaslabs_by_flushed, metaslab_sort_by_flushed,
706             sizeof (metaslab_t), offsetof(metaslab_t, ms_spa_txg_node));
707         avl_create(&spa->spa_sm_logs_by_txg, spa_log_sm_sort_by_txg,
708             sizeof (spa_log_sm_t), offsetof(spa_log_sm_t, sls_node));
709         list_create(&spa->spa_log_summary, sizeof (log_summary_entry_t),
710             offsetof(log_summary_entry_t, lse_node));
711
712         /*
713          * Every pool starts with the default cachefile
714          */
715         list_create(&spa->spa_config_list, sizeof (spa_config_dirent_t),
716             offsetof(spa_config_dirent_t, scd_link));
717
718         dp = kmem_zalloc(sizeof (spa_config_dirent_t), KM_SLEEP);
719         dp->scd_path = altroot ? NULL : spa_strdup(spa_config_path);
720         list_insert_head(&spa->spa_config_list, dp);
721
722         VERIFY(nvlist_alloc(&spa->spa_load_info, NV_UNIQUE_NAME,
723             KM_SLEEP) == 0);
724
725         if (config != NULL) {
726                 nvlist_t *features;
727
728                 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_FEATURES_FOR_READ,
729                     &features) == 0) {
730                         VERIFY(nvlist_dup(features, &spa->spa_label_features,
731                             0) == 0);
732                 }
733
734                 VERIFY(nvlist_dup(config, &spa->spa_config, 0) == 0);
735         }
736
737         if (spa->spa_label_features == NULL) {
738                 VERIFY(nvlist_alloc(&spa->spa_label_features, NV_UNIQUE_NAME,
739                     KM_SLEEP) == 0);
740         }
741
742         spa->spa_min_ashift = INT_MAX;
743         spa->spa_max_ashift = 0;
744
745         /* Reset cached value */
746         spa->spa_dedup_dspace = ~0ULL;
747
748         /*
749          * As a pool is being created, treat all features as disabled by
750          * setting SPA_FEATURE_DISABLED for all entries in the feature
751          * refcount cache.
752          */
753         for (int i = 0; i < SPA_FEATURES; i++) {
754                 spa->spa_feat_refcount_cache[i] = SPA_FEATURE_DISABLED;
755         }
756
757         list_create(&spa->spa_leaf_list, sizeof (vdev_t),
758             offsetof(vdev_t, vdev_leaf_node));
759
760         return (spa);
761 }
762
763 /*
764  * Removes a spa_t from the namespace, freeing up any memory used.  Requires
765  * spa_namespace_lock.  This is called only after the spa_t has been closed and
766  * deactivated.
767  */
768 void
769 spa_remove(spa_t *spa)
770 {
771         spa_config_dirent_t *dp;
772
773         ASSERT(MUTEX_HELD(&spa_namespace_lock));
774         ASSERT(spa_state(spa) == POOL_STATE_UNINITIALIZED);
775         ASSERT3U(zfs_refcount_count(&spa->spa_refcount), ==, 0);
776         ASSERT0(spa->spa_waiters);
777
778         nvlist_free(spa->spa_config_splitting);
779
780         avl_remove(&spa_namespace_avl, spa);
781         cv_broadcast(&spa_namespace_cv);
782
783         if (spa->spa_root)
784                 spa_strfree(spa->spa_root);
785
786         while ((dp = list_head(&spa->spa_config_list)) != NULL) {
787                 list_remove(&spa->spa_config_list, dp);
788                 if (dp->scd_path != NULL)
789                         spa_strfree(dp->scd_path);
790                 kmem_free(dp, sizeof (spa_config_dirent_t));
791         }
792
793         for (int i = 0; i < spa->spa_alloc_count; i++) {
794                 avl_destroy(&spa->spa_alloc_trees[i]);
795                 mutex_destroy(&spa->spa_alloc_locks[i]);
796         }
797         kmem_free(spa->spa_alloc_locks, spa->spa_alloc_count *
798             sizeof (kmutex_t));
799         kmem_free(spa->spa_alloc_trees, spa->spa_alloc_count *
800             sizeof (avl_tree_t));
801
802         avl_destroy(&spa->spa_metaslabs_by_flushed);
803         avl_destroy(&spa->spa_sm_logs_by_txg);
804         list_destroy(&spa->spa_log_summary);
805         list_destroy(&spa->spa_config_list);
806         list_destroy(&spa->spa_leaf_list);
807
808         nvlist_free(spa->spa_label_features);
809         nvlist_free(spa->spa_load_info);
810         nvlist_free(spa->spa_feat_stats);
811         spa_config_set(spa, NULL);
812
813         zfs_refcount_destroy(&spa->spa_refcount);
814
815         spa_stats_destroy(spa);
816         spa_config_lock_destroy(spa);
817
818         for (int t = 0; t < TXG_SIZE; t++)
819                 bplist_destroy(&spa->spa_free_bplist[t]);
820
821         zio_checksum_templates_free(spa);
822
823         cv_destroy(&spa->spa_async_cv);
824         cv_destroy(&spa->spa_evicting_os_cv);
825         cv_destroy(&spa->spa_proc_cv);
826         cv_destroy(&spa->spa_scrub_io_cv);
827         cv_destroy(&spa->spa_suspend_cv);
828         cv_destroy(&spa->spa_activities_cv);
829         cv_destroy(&spa->spa_waiters_cv);
830
831         mutex_destroy(&spa->spa_flushed_ms_lock);
832         mutex_destroy(&spa->spa_async_lock);
833         mutex_destroy(&spa->spa_errlist_lock);
834         mutex_destroy(&spa->spa_errlog_lock);
835         mutex_destroy(&spa->spa_evicting_os_lock);
836         mutex_destroy(&spa->spa_history_lock);
837         mutex_destroy(&spa->spa_proc_lock);
838         mutex_destroy(&spa->spa_props_lock);
839         mutex_destroy(&spa->spa_cksum_tmpls_lock);
840         mutex_destroy(&spa->spa_scrub_lock);
841         mutex_destroy(&spa->spa_suspend_lock);
842         mutex_destroy(&spa->spa_vdev_top_lock);
843         mutex_destroy(&spa->spa_feat_stats_lock);
844         mutex_destroy(&spa->spa_activities_lock);
845
846         kmem_free(spa, sizeof (spa_t));
847 }
848
849 /*
850  * Given a pool, return the next pool in the namespace, or NULL if there is
851  * none.  If 'prev' is NULL, return the first pool.
852  */
853 spa_t *
854 spa_next(spa_t *prev)
855 {
856         ASSERT(MUTEX_HELD(&spa_namespace_lock));
857
858         if (prev)
859                 return (AVL_NEXT(&spa_namespace_avl, prev));
860         else
861                 return (avl_first(&spa_namespace_avl));
862 }
863
864 /*
865  * ==========================================================================
866  * SPA refcount functions
867  * ==========================================================================
868  */
869
870 /*
871  * Add a reference to the given spa_t.  Must have at least one reference, or
872  * have the namespace lock held.
873  */
874 void
875 spa_open_ref(spa_t *spa, void *tag)
876 {
877         ASSERT(zfs_refcount_count(&spa->spa_refcount) >= spa->spa_minref ||
878             MUTEX_HELD(&spa_namespace_lock));
879         (void) zfs_refcount_add(&spa->spa_refcount, tag);
880 }
881
882 /*
883  * Remove a reference to the given spa_t.  Must have at least one reference, or
884  * have the namespace lock held.
885  */
886 void
887 spa_close(spa_t *spa, void *tag)
888 {
889         ASSERT(zfs_refcount_count(&spa->spa_refcount) > spa->spa_minref ||
890             MUTEX_HELD(&spa_namespace_lock));
891         (void) zfs_refcount_remove(&spa->spa_refcount, tag);
892 }
893
894 /*
895  * Remove a reference to the given spa_t held by a dsl dir that is
896  * being asynchronously released.  Async releases occur from a taskq
897  * performing eviction of dsl datasets and dirs.  The namespace lock
898  * isn't held and the hold by the object being evicted may contribute to
899  * spa_minref (e.g. dataset or directory released during pool export),
900  * so the asserts in spa_close() do not apply.
901  */
902 void
903 spa_async_close(spa_t *spa, void *tag)
904 {
905         (void) zfs_refcount_remove(&spa->spa_refcount, tag);
906 }
907
908 /*
909  * Check to see if the spa refcount is zero.  Must be called with
910  * spa_namespace_lock held.  We really compare against spa_minref, which is the
911  * number of references acquired when opening a pool
912  */
913 boolean_t
914 spa_refcount_zero(spa_t *spa)
915 {
916         ASSERT(MUTEX_HELD(&spa_namespace_lock));
917
918         return (zfs_refcount_count(&spa->spa_refcount) == spa->spa_minref);
919 }
920
921 /*
922  * ==========================================================================
923  * SPA spare and l2cache tracking
924  * ==========================================================================
925  */
926
927 /*
928  * Hot spares and cache devices are tracked using the same code below,
929  * for 'auxiliary' devices.
930  */
931
932 typedef struct spa_aux {
933         uint64_t        aux_guid;
934         uint64_t        aux_pool;
935         avl_node_t      aux_avl;
936         int             aux_count;
937 } spa_aux_t;
938
939 static inline int
940 spa_aux_compare(const void *a, const void *b)
941 {
942         const spa_aux_t *sa = (const spa_aux_t *)a;
943         const spa_aux_t *sb = (const spa_aux_t *)b;
944
945         return (TREE_CMP(sa->aux_guid, sb->aux_guid));
946 }
947
948 static void
949 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
950 {
951         avl_index_t where;
952         spa_aux_t search;
953         spa_aux_t *aux;
954
955         search.aux_guid = vd->vdev_guid;
956         if ((aux = avl_find(avl, &search, &where)) != NULL) {
957                 aux->aux_count++;
958         } else {
959                 aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
960                 aux->aux_guid = vd->vdev_guid;
961                 aux->aux_count = 1;
962                 avl_insert(avl, aux, where);
963         }
964 }
965
966 static void
967 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
968 {
969         spa_aux_t search;
970         spa_aux_t *aux;
971         avl_index_t where;
972
973         search.aux_guid = vd->vdev_guid;
974         aux = avl_find(avl, &search, &where);
975
976         ASSERT(aux != NULL);
977
978         if (--aux->aux_count == 0) {
979                 avl_remove(avl, aux);
980                 kmem_free(aux, sizeof (spa_aux_t));
981         } else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
982                 aux->aux_pool = 0ULL;
983         }
984 }
985
986 static boolean_t
987 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
988 {
989         spa_aux_t search, *found;
990
991         search.aux_guid = guid;
992         found = avl_find(avl, &search, NULL);
993
994         if (pool) {
995                 if (found)
996                         *pool = found->aux_pool;
997                 else
998                         *pool = 0ULL;
999         }
1000
1001         if (refcnt) {
1002                 if (found)
1003                         *refcnt = found->aux_count;
1004                 else
1005                         *refcnt = 0;
1006         }
1007
1008         return (found != NULL);
1009 }
1010
1011 static void
1012 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
1013 {
1014         spa_aux_t search, *found;
1015         avl_index_t where;
1016
1017         search.aux_guid = vd->vdev_guid;
1018         found = avl_find(avl, &search, &where);
1019         ASSERT(found != NULL);
1020         ASSERT(found->aux_pool == 0ULL);
1021
1022         found->aux_pool = spa_guid(vd->vdev_spa);
1023 }
1024
1025 /*
1026  * Spares are tracked globally due to the following constraints:
1027  *
1028  *      - A spare may be part of multiple pools.
1029  *      - A spare may be added to a pool even if it's actively in use within
1030  *        another pool.
1031  *      - A spare in use in any pool can only be the source of a replacement if
1032  *        the target is a spare in the same pool.
1033  *
1034  * We keep track of all spares on the system through the use of a reference
1035  * counted AVL tree.  When a vdev is added as a spare, or used as a replacement
1036  * spare, then we bump the reference count in the AVL tree.  In addition, we set
1037  * the 'vdev_isspare' member to indicate that the device is a spare (active or
1038  * inactive).  When a spare is made active (used to replace a device in the
1039  * pool), we also keep track of which pool its been made a part of.
1040  *
1041  * The 'spa_spare_lock' protects the AVL tree.  These functions are normally
1042  * called under the spa_namespace lock as part of vdev reconfiguration.  The
1043  * separate spare lock exists for the status query path, which does not need to
1044  * be completely consistent with respect to other vdev configuration changes.
1045  */
1046
1047 static int
1048 spa_spare_compare(const void *a, const void *b)
1049 {
1050         return (spa_aux_compare(a, b));
1051 }
1052
1053 void
1054 spa_spare_add(vdev_t *vd)
1055 {
1056         mutex_enter(&spa_spare_lock);
1057         ASSERT(!vd->vdev_isspare);
1058         spa_aux_add(vd, &spa_spare_avl);
1059         vd->vdev_isspare = B_TRUE;
1060         mutex_exit(&spa_spare_lock);
1061 }
1062
1063 void
1064 spa_spare_remove(vdev_t *vd)
1065 {
1066         mutex_enter(&spa_spare_lock);
1067         ASSERT(vd->vdev_isspare);
1068         spa_aux_remove(vd, &spa_spare_avl);
1069         vd->vdev_isspare = B_FALSE;
1070         mutex_exit(&spa_spare_lock);
1071 }
1072
1073 boolean_t
1074 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
1075 {
1076         boolean_t found;
1077
1078         mutex_enter(&spa_spare_lock);
1079         found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
1080         mutex_exit(&spa_spare_lock);
1081
1082         return (found);
1083 }
1084
1085 void
1086 spa_spare_activate(vdev_t *vd)
1087 {
1088         mutex_enter(&spa_spare_lock);
1089         ASSERT(vd->vdev_isspare);
1090         spa_aux_activate(vd, &spa_spare_avl);
1091         mutex_exit(&spa_spare_lock);
1092 }
1093
1094 /*
1095  * Level 2 ARC devices are tracked globally for the same reasons as spares.
1096  * Cache devices currently only support one pool per cache device, and so
1097  * for these devices the aux reference count is currently unused beyond 1.
1098  */
1099
1100 static int
1101 spa_l2cache_compare(const void *a, const void *b)
1102 {
1103         return (spa_aux_compare(a, b));
1104 }
1105
1106 void
1107 spa_l2cache_add(vdev_t *vd)
1108 {
1109         mutex_enter(&spa_l2cache_lock);
1110         ASSERT(!vd->vdev_isl2cache);
1111         spa_aux_add(vd, &spa_l2cache_avl);
1112         vd->vdev_isl2cache = B_TRUE;
1113         mutex_exit(&spa_l2cache_lock);
1114 }
1115
1116 void
1117 spa_l2cache_remove(vdev_t *vd)
1118 {
1119         mutex_enter(&spa_l2cache_lock);
1120         ASSERT(vd->vdev_isl2cache);
1121         spa_aux_remove(vd, &spa_l2cache_avl);
1122         vd->vdev_isl2cache = B_FALSE;
1123         mutex_exit(&spa_l2cache_lock);
1124 }
1125
1126 boolean_t
1127 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
1128 {
1129         boolean_t found;
1130
1131         mutex_enter(&spa_l2cache_lock);
1132         found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
1133         mutex_exit(&spa_l2cache_lock);
1134
1135         return (found);
1136 }
1137
1138 void
1139 spa_l2cache_activate(vdev_t *vd)
1140 {
1141         mutex_enter(&spa_l2cache_lock);
1142         ASSERT(vd->vdev_isl2cache);
1143         spa_aux_activate(vd, &spa_l2cache_avl);
1144         mutex_exit(&spa_l2cache_lock);
1145 }
1146
1147 /*
1148  * ==========================================================================
1149  * SPA vdev locking
1150  * ==========================================================================
1151  */
1152
1153 /*
1154  * Lock the given spa_t for the purpose of adding or removing a vdev.
1155  * Grabs the global spa_namespace_lock plus the spa config lock for writing.
1156  * It returns the next transaction group for the spa_t.
1157  */
1158 uint64_t
1159 spa_vdev_enter(spa_t *spa)
1160 {
1161         mutex_enter(&spa->spa_vdev_top_lock);
1162         mutex_enter(&spa_namespace_lock);
1163
1164         vdev_autotrim_stop_all(spa);
1165
1166         return (spa_vdev_config_enter(spa));
1167 }
1168
1169 /*
1170  * The same as spa_vdev_enter() above but additionally takes the guid of
1171  * the vdev being detached.  When there is a rebuild in process it will be
1172  * suspended while the vdev tree is modified then resumed by spa_vdev_exit().
1173  * The rebuild is canceled if only a single child remains after the detach.
1174  */
1175 uint64_t
1176 spa_vdev_detach_enter(spa_t *spa, uint64_t guid)
1177 {
1178         mutex_enter(&spa->spa_vdev_top_lock);
1179         mutex_enter(&spa_namespace_lock);
1180
1181         vdev_autotrim_stop_all(spa);
1182
1183         if (guid != 0) {
1184                 vdev_t *vd = spa_lookup_by_guid(spa, guid, B_FALSE);
1185                 if (vd) {
1186                         vdev_rebuild_stop_wait(vd->vdev_top);
1187                 }
1188         }
1189
1190         return (spa_vdev_config_enter(spa));
1191 }
1192
1193 /*
1194  * Internal implementation for spa_vdev_enter().  Used when a vdev
1195  * operation requires multiple syncs (i.e. removing a device) while
1196  * keeping the spa_namespace_lock held.
1197  */
1198 uint64_t
1199 spa_vdev_config_enter(spa_t *spa)
1200 {
1201         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1202
1203         spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1204
1205         return (spa_last_synced_txg(spa) + 1);
1206 }
1207
1208 /*
1209  * Used in combination with spa_vdev_config_enter() to allow the syncing
1210  * of multiple transactions without releasing the spa_namespace_lock.
1211  */
1212 void
1213 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error, char *tag)
1214 {
1215         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1216
1217         int config_changed = B_FALSE;
1218
1219         ASSERT(txg > spa_last_synced_txg(spa));
1220
1221         spa->spa_pending_vdev = NULL;
1222
1223         /*
1224          * Reassess the DTLs.
1225          */
1226         vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE, B_FALSE);
1227
1228         if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
1229                 config_changed = B_TRUE;
1230                 spa->spa_config_generation++;
1231         }
1232
1233         /*
1234          * Verify the metaslab classes.
1235          */
1236         ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
1237         ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
1238         ASSERT(metaslab_class_validate(spa_special_class(spa)) == 0);
1239         ASSERT(metaslab_class_validate(spa_dedup_class(spa)) == 0);
1240
1241         spa_config_exit(spa, SCL_ALL, spa);
1242
1243         /*
1244          * Panic the system if the specified tag requires it.  This
1245          * is useful for ensuring that configurations are updated
1246          * transactionally.
1247          */
1248         if (zio_injection_enabled)
1249                 zio_handle_panic_injection(spa, tag, 0);
1250
1251         /*
1252          * Note: this txg_wait_synced() is important because it ensures
1253          * that there won't be more than one config change per txg.
1254          * This allows us to use the txg as the generation number.
1255          */
1256         if (error == 0)
1257                 txg_wait_synced(spa->spa_dsl_pool, txg);
1258
1259         if (vd != NULL) {
1260                 ASSERT(!vd->vdev_detached || vd->vdev_dtl_sm == NULL);
1261                 if (vd->vdev_ops->vdev_op_leaf) {
1262                         mutex_enter(&vd->vdev_initialize_lock);
1263                         vdev_initialize_stop(vd, VDEV_INITIALIZE_CANCELED,
1264                             NULL);
1265                         mutex_exit(&vd->vdev_initialize_lock);
1266
1267                         mutex_enter(&vd->vdev_trim_lock);
1268                         vdev_trim_stop(vd, VDEV_TRIM_CANCELED, NULL);
1269                         mutex_exit(&vd->vdev_trim_lock);
1270                 }
1271
1272                 /*
1273                  * The vdev may be both a leaf and top-level device.
1274                  */
1275                 vdev_autotrim_stop_wait(vd);
1276
1277                 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1278                 vdev_free(vd);
1279                 spa_config_exit(spa, SCL_ALL, spa);
1280         }
1281
1282         /*
1283          * If the config changed, update the config cache.
1284          */
1285         if (config_changed)
1286                 spa_write_cachefile(spa, B_FALSE, B_TRUE);
1287 }
1288
1289 /*
1290  * Unlock the spa_t after adding or removing a vdev.  Besides undoing the
1291  * locking of spa_vdev_enter(), we also want make sure the transactions have
1292  * synced to disk, and then update the global configuration cache with the new
1293  * information.
1294  */
1295 int
1296 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
1297 {
1298         vdev_autotrim_restart(spa);
1299         vdev_rebuild_restart(spa);
1300
1301         spa_vdev_config_exit(spa, vd, txg, error, FTAG);
1302         mutex_exit(&spa_namespace_lock);
1303         mutex_exit(&spa->spa_vdev_top_lock);
1304
1305         return (error);
1306 }
1307
1308 /*
1309  * Lock the given spa_t for the purpose of changing vdev state.
1310  */
1311 void
1312 spa_vdev_state_enter(spa_t *spa, int oplocks)
1313 {
1314         int locks = SCL_STATE_ALL | oplocks;
1315
1316         /*
1317          * Root pools may need to read of the underlying devfs filesystem
1318          * when opening up a vdev.  Unfortunately if we're holding the
1319          * SCL_ZIO lock it will result in a deadlock when we try to issue
1320          * the read from the root filesystem.  Instead we "prefetch"
1321          * the associated vnodes that we need prior to opening the
1322          * underlying devices and cache them so that we can prevent
1323          * any I/O when we are doing the actual open.
1324          */
1325         if (spa_is_root(spa)) {
1326                 int low = locks & ~(SCL_ZIO - 1);
1327                 int high = locks & ~low;
1328
1329                 spa_config_enter(spa, high, spa, RW_WRITER);
1330                 vdev_hold(spa->spa_root_vdev);
1331                 spa_config_enter(spa, low, spa, RW_WRITER);
1332         } else {
1333                 spa_config_enter(spa, locks, spa, RW_WRITER);
1334         }
1335         spa->spa_vdev_locks = locks;
1336 }
1337
1338 int
1339 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
1340 {
1341         boolean_t config_changed = B_FALSE;
1342         vdev_t *vdev_top;
1343
1344         if (vd == NULL || vd == spa->spa_root_vdev) {
1345                 vdev_top = spa->spa_root_vdev;
1346         } else {
1347                 vdev_top = vd->vdev_top;
1348         }
1349
1350         if (vd != NULL || error == 0)
1351                 vdev_dtl_reassess(vdev_top, 0, 0, B_FALSE, B_FALSE);
1352
1353         if (vd != NULL) {
1354                 if (vd != spa->spa_root_vdev)
1355                         vdev_state_dirty(vdev_top);
1356
1357                 config_changed = B_TRUE;
1358                 spa->spa_config_generation++;
1359         }
1360
1361         if (spa_is_root(spa))
1362                 vdev_rele(spa->spa_root_vdev);
1363
1364         ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1365         spa_config_exit(spa, spa->spa_vdev_locks, spa);
1366
1367         /*
1368          * If anything changed, wait for it to sync.  This ensures that,
1369          * from the system administrator's perspective, zpool(1M) commands
1370          * are synchronous.  This is important for things like zpool offline:
1371          * when the command completes, you expect no further I/O from ZFS.
1372          */
1373         if (vd != NULL)
1374                 txg_wait_synced(spa->spa_dsl_pool, 0);
1375
1376         /*
1377          * If the config changed, update the config cache.
1378          */
1379         if (config_changed) {
1380                 mutex_enter(&spa_namespace_lock);
1381                 spa_write_cachefile(spa, B_FALSE, B_TRUE);
1382                 mutex_exit(&spa_namespace_lock);
1383         }
1384
1385         return (error);
1386 }
1387
1388 /*
1389  * ==========================================================================
1390  * Miscellaneous functions
1391  * ==========================================================================
1392  */
1393
1394 void
1395 spa_activate_mos_feature(spa_t *spa, const char *feature, dmu_tx_t *tx)
1396 {
1397         if (!nvlist_exists(spa->spa_label_features, feature)) {
1398                 fnvlist_add_boolean(spa->spa_label_features, feature);
1399                 /*
1400                  * When we are creating the pool (tx_txg==TXG_INITIAL), we can't
1401                  * dirty the vdev config because lock SCL_CONFIG is not held.
1402                  * Thankfully, in this case we don't need to dirty the config
1403                  * because it will be written out anyway when we finish
1404                  * creating the pool.
1405                  */
1406                 if (tx->tx_txg != TXG_INITIAL)
1407                         vdev_config_dirty(spa->spa_root_vdev);
1408         }
1409 }
1410
1411 void
1412 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1413 {
1414         if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1415                 vdev_config_dirty(spa->spa_root_vdev);
1416 }
1417
1418 /*
1419  * Return the spa_t associated with given pool_guid, if it exists.  If
1420  * device_guid is non-zero, determine whether the pool exists *and* contains
1421  * a device with the specified device_guid.
1422  */
1423 spa_t *
1424 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1425 {
1426         spa_t *spa;
1427         avl_tree_t *t = &spa_namespace_avl;
1428
1429         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1430
1431         for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1432                 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1433                         continue;
1434                 if (spa->spa_root_vdev == NULL)
1435                         continue;
1436                 if (spa_guid(spa) == pool_guid) {
1437                         if (device_guid == 0)
1438                                 break;
1439
1440                         if (vdev_lookup_by_guid(spa->spa_root_vdev,
1441                             device_guid) != NULL)
1442                                 break;
1443
1444                         /*
1445                          * Check any devices we may be in the process of adding.
1446                          */
1447                         if (spa->spa_pending_vdev) {
1448                                 if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1449                                     device_guid) != NULL)
1450                                         break;
1451                         }
1452                 }
1453         }
1454
1455         return (spa);
1456 }
1457
1458 /*
1459  * Determine whether a pool with the given pool_guid exists.
1460  */
1461 boolean_t
1462 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1463 {
1464         return (spa_by_guid(pool_guid, device_guid) != NULL);
1465 }
1466
1467 char *
1468 spa_strdup(const char *s)
1469 {
1470         size_t len;
1471         char *new;
1472
1473         len = strlen(s);
1474         new = kmem_alloc(len + 1, KM_SLEEP);
1475         bcopy(s, new, len);
1476         new[len] = '\0';
1477
1478         return (new);
1479 }
1480
1481 void
1482 spa_strfree(char *s)
1483 {
1484         kmem_free(s, strlen(s) + 1);
1485 }
1486
1487 uint64_t
1488 spa_get_random(uint64_t range)
1489 {
1490         uint64_t r;
1491
1492         ASSERT(range != 0);
1493
1494         if (range == 1)
1495                 return (0);
1496
1497         (void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
1498
1499         return (r % range);
1500 }
1501
1502 uint64_t
1503 spa_generate_guid(spa_t *spa)
1504 {
1505         uint64_t guid = spa_get_random(-1ULL);
1506
1507         if (spa != NULL) {
1508                 while (guid == 0 || spa_guid_exists(spa_guid(spa), guid))
1509                         guid = spa_get_random(-1ULL);
1510         } else {
1511                 while (guid == 0 || spa_guid_exists(guid, 0))
1512                         guid = spa_get_random(-1ULL);
1513         }
1514
1515         return (guid);
1516 }
1517
1518 void
1519 snprintf_blkptr(char *buf, size_t buflen, const blkptr_t *bp)
1520 {
1521         char type[256];
1522         char *checksum = NULL;
1523         char *compress = NULL;
1524
1525         if (bp != NULL) {
1526                 if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1527                         dmu_object_byteswap_t bswap =
1528                             DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1529                         (void) snprintf(type, sizeof (type), "bswap %s %s",
1530                             DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1531                             "metadata" : "data",
1532                             dmu_ot_byteswap[bswap].ob_name);
1533                 } else {
1534                         (void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1535                             sizeof (type));
1536                 }
1537                 if (!BP_IS_EMBEDDED(bp)) {
1538                         checksum =
1539                             zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1540                 }
1541                 compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1542         }
1543
1544         SNPRINTF_BLKPTR(snprintf, ' ', buf, buflen, bp, type, checksum,
1545             compress);
1546 }
1547
1548 void
1549 spa_freeze(spa_t *spa)
1550 {
1551         uint64_t freeze_txg = 0;
1552
1553         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1554         if (spa->spa_freeze_txg == UINT64_MAX) {
1555                 freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1556                 spa->spa_freeze_txg = freeze_txg;
1557         }
1558         spa_config_exit(spa, SCL_ALL, FTAG);
1559         if (freeze_txg != 0)
1560                 txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1561 }
1562
1563 void
1564 zfs_panic_recover(const char *fmt, ...)
1565 {
1566         va_list adx;
1567
1568         va_start(adx, fmt);
1569         vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1570         va_end(adx);
1571 }
1572
1573 /*
1574  * This is a stripped-down version of strtoull, suitable only for converting
1575  * lowercase hexadecimal numbers that don't overflow.
1576  */
1577 uint64_t
1578 zfs_strtonum(const char *str, char **nptr)
1579 {
1580         uint64_t val = 0;
1581         char c;
1582         int digit;
1583
1584         while ((c = *str) != '\0') {
1585                 if (c >= '0' && c <= '9')
1586                         digit = c - '0';
1587                 else if (c >= 'a' && c <= 'f')
1588                         digit = 10 + c - 'a';
1589                 else
1590                         break;
1591
1592                 val *= 16;
1593                 val += digit;
1594
1595                 str++;
1596         }
1597
1598         if (nptr)
1599                 *nptr = (char *)str;
1600
1601         return (val);
1602 }
1603
1604 void
1605 spa_activate_allocation_classes(spa_t *spa, dmu_tx_t *tx)
1606 {
1607         /*
1608          * We bump the feature refcount for each special vdev added to the pool
1609          */
1610         ASSERT(spa_feature_is_enabled(spa, SPA_FEATURE_ALLOCATION_CLASSES));
1611         spa_feature_incr(spa, SPA_FEATURE_ALLOCATION_CLASSES, tx);
1612 }
1613
1614 /*
1615  * ==========================================================================
1616  * Accessor functions
1617  * ==========================================================================
1618  */
1619
1620 boolean_t
1621 spa_shutting_down(spa_t *spa)
1622 {
1623         return (spa->spa_async_suspended);
1624 }
1625
1626 dsl_pool_t *
1627 spa_get_dsl(spa_t *spa)
1628 {
1629         return (spa->spa_dsl_pool);
1630 }
1631
1632 boolean_t
1633 spa_is_initializing(spa_t *spa)
1634 {
1635         return (spa->spa_is_initializing);
1636 }
1637
1638 boolean_t
1639 spa_indirect_vdevs_loaded(spa_t *spa)
1640 {
1641         return (spa->spa_indirect_vdevs_loaded);
1642 }
1643
1644 blkptr_t *
1645 spa_get_rootblkptr(spa_t *spa)
1646 {
1647         return (&spa->spa_ubsync.ub_rootbp);
1648 }
1649
1650 void
1651 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1652 {
1653         spa->spa_uberblock.ub_rootbp = *bp;
1654 }
1655
1656 void
1657 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1658 {
1659         if (spa->spa_root == NULL)
1660                 buf[0] = '\0';
1661         else
1662                 (void) strncpy(buf, spa->spa_root, buflen);
1663 }
1664
1665 int
1666 spa_sync_pass(spa_t *spa)
1667 {
1668         return (spa->spa_sync_pass);
1669 }
1670
1671 char *
1672 spa_name(spa_t *spa)
1673 {
1674         return (spa->spa_name);
1675 }
1676
1677 uint64_t
1678 spa_guid(spa_t *spa)
1679 {
1680         dsl_pool_t *dp = spa_get_dsl(spa);
1681         uint64_t guid;
1682
1683         /*
1684          * If we fail to parse the config during spa_load(), we can go through
1685          * the error path (which posts an ereport) and end up here with no root
1686          * vdev.  We stash the original pool guid in 'spa_config_guid' to handle
1687          * this case.
1688          */
1689         if (spa->spa_root_vdev == NULL)
1690                 return (spa->spa_config_guid);
1691
1692         guid = spa->spa_last_synced_guid != 0 ?
1693             spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1694
1695         /*
1696          * Return the most recently synced out guid unless we're
1697          * in syncing context.
1698          */
1699         if (dp && dsl_pool_sync_context(dp))
1700                 return (spa->spa_root_vdev->vdev_guid);
1701         else
1702                 return (guid);
1703 }
1704
1705 uint64_t
1706 spa_load_guid(spa_t *spa)
1707 {
1708         /*
1709          * This is a GUID that exists solely as a reference for the
1710          * purposes of the arc.  It is generated at load time, and
1711          * is never written to persistent storage.
1712          */
1713         return (spa->spa_load_guid);
1714 }
1715
1716 uint64_t
1717 spa_last_synced_txg(spa_t *spa)
1718 {
1719         return (spa->spa_ubsync.ub_txg);
1720 }
1721
1722 uint64_t
1723 spa_first_txg(spa_t *spa)
1724 {
1725         return (spa->spa_first_txg);
1726 }
1727
1728 uint64_t
1729 spa_syncing_txg(spa_t *spa)
1730 {
1731         return (spa->spa_syncing_txg);
1732 }
1733
1734 /*
1735  * Return the last txg where data can be dirtied. The final txgs
1736  * will be used to just clear out any deferred frees that remain.
1737  */
1738 uint64_t
1739 spa_final_dirty_txg(spa_t *spa)
1740 {
1741         return (spa->spa_final_txg - TXG_DEFER_SIZE);
1742 }
1743
1744 pool_state_t
1745 spa_state(spa_t *spa)
1746 {
1747         return (spa->spa_state);
1748 }
1749
1750 spa_load_state_t
1751 spa_load_state(spa_t *spa)
1752 {
1753         return (spa->spa_load_state);
1754 }
1755
1756 uint64_t
1757 spa_freeze_txg(spa_t *spa)
1758 {
1759         return (spa->spa_freeze_txg);
1760 }
1761
1762 /*
1763  * Return the inflated asize for a logical write in bytes. This is used by the
1764  * DMU to calculate the space a logical write will require on disk.
1765  * If lsize is smaller than the largest physical block size allocatable on this
1766  * pool we use its value instead, since the write will end up using the whole
1767  * block anyway.
1768  */
1769 uint64_t
1770 spa_get_worst_case_asize(spa_t *spa, uint64_t lsize)
1771 {
1772         if (lsize == 0)
1773                 return (0);     /* No inflation needed */
1774         return (MAX(lsize, 1 << spa->spa_max_ashift) * spa_asize_inflation);
1775 }
1776
1777 /*
1778  * Return the amount of slop space in bytes.  It is 1/32 of the pool (3.2%),
1779  * or at least 128MB, unless that would cause it to be more than half the
1780  * pool size.
1781  *
1782  * See the comment above spa_slop_shift for details.
1783  */
1784 uint64_t
1785 spa_get_slop_space(spa_t *spa)
1786 {
1787         uint64_t space = spa_get_dspace(spa);
1788         return (MAX(space >> spa_slop_shift, MIN(space >> 1, spa_min_slop)));
1789 }
1790
1791 uint64_t
1792 spa_get_dspace(spa_t *spa)
1793 {
1794         return (spa->spa_dspace);
1795 }
1796
1797 uint64_t
1798 spa_get_checkpoint_space(spa_t *spa)
1799 {
1800         return (spa->spa_checkpoint_info.sci_dspace);
1801 }
1802
1803 void
1804 spa_update_dspace(spa_t *spa)
1805 {
1806         spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1807             ddt_get_dedup_dspace(spa);
1808         if (spa->spa_vdev_removal != NULL) {
1809                 /*
1810                  * We can't allocate from the removing device, so
1811                  * subtract its size.  This prevents the DMU/DSL from
1812                  * filling up the (now smaller) pool while we are in the
1813                  * middle of removing the device.
1814                  *
1815                  * Note that the DMU/DSL doesn't actually know or care
1816                  * how much space is allocated (it does its own tracking
1817                  * of how much space has been logically used).  So it
1818                  * doesn't matter that the data we are moving may be
1819                  * allocated twice (on the old device and the new
1820                  * device).
1821                  */
1822                 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1823                 vdev_t *vd =
1824                     vdev_lookup_top(spa, spa->spa_vdev_removal->svr_vdev_id);
1825                 spa->spa_dspace -= spa_deflate(spa) ?
1826                     vd->vdev_stat.vs_dspace : vd->vdev_stat.vs_space;
1827                 spa_config_exit(spa, SCL_VDEV, FTAG);
1828         }
1829 }
1830
1831 /*
1832  * Return the failure mode that has been set to this pool. The default
1833  * behavior will be to block all I/Os when a complete failure occurs.
1834  */
1835 uint64_t
1836 spa_get_failmode(spa_t *spa)
1837 {
1838         return (spa->spa_failmode);
1839 }
1840
1841 boolean_t
1842 spa_suspended(spa_t *spa)
1843 {
1844         return (spa->spa_suspended != ZIO_SUSPEND_NONE);
1845 }
1846
1847 uint64_t
1848 spa_version(spa_t *spa)
1849 {
1850         return (spa->spa_ubsync.ub_version);
1851 }
1852
1853 boolean_t
1854 spa_deflate(spa_t *spa)
1855 {
1856         return (spa->spa_deflate);
1857 }
1858
1859 metaslab_class_t *
1860 spa_normal_class(spa_t *spa)
1861 {
1862         return (spa->spa_normal_class);
1863 }
1864
1865 metaslab_class_t *
1866 spa_log_class(spa_t *spa)
1867 {
1868         return (spa->spa_log_class);
1869 }
1870
1871 metaslab_class_t *
1872 spa_special_class(spa_t *spa)
1873 {
1874         return (spa->spa_special_class);
1875 }
1876
1877 metaslab_class_t *
1878 spa_dedup_class(spa_t *spa)
1879 {
1880         return (spa->spa_dedup_class);
1881 }
1882
1883 /*
1884  * Locate an appropriate allocation class
1885  */
1886 metaslab_class_t *
1887 spa_preferred_class(spa_t *spa, uint64_t size, dmu_object_type_t objtype,
1888     uint_t level, uint_t special_smallblk)
1889 {
1890         if (DMU_OT_IS_ZIL(objtype)) {
1891                 if (spa->spa_log_class->mc_groups != 0)
1892                         return (spa_log_class(spa));
1893                 else
1894                         return (spa_normal_class(spa));
1895         }
1896
1897         boolean_t has_special_class = spa->spa_special_class->mc_groups != 0;
1898
1899         if (DMU_OT_IS_DDT(objtype)) {
1900                 if (spa->spa_dedup_class->mc_groups != 0)
1901                         return (spa_dedup_class(spa));
1902                 else if (has_special_class && zfs_ddt_data_is_special)
1903                         return (spa_special_class(spa));
1904                 else
1905                         return (spa_normal_class(spa));
1906         }
1907
1908         /* Indirect blocks for user data can land in special if allowed */
1909         if (level > 0 && (DMU_OT_IS_FILE(objtype) || objtype == DMU_OT_ZVOL)) {
1910                 if (has_special_class && zfs_user_indirect_is_special)
1911                         return (spa_special_class(spa));
1912                 else
1913                         return (spa_normal_class(spa));
1914         }
1915
1916         if (DMU_OT_IS_METADATA(objtype) || level > 0) {
1917                 if (has_special_class)
1918                         return (spa_special_class(spa));
1919                 else
1920                         return (spa_normal_class(spa));
1921         }
1922
1923         /*
1924          * Allow small file blocks in special class in some cases (like
1925          * for the dRAID vdev feature). But always leave a reserve of
1926          * zfs_special_class_metadata_reserve_pct exclusively for metadata.
1927          */
1928         if (DMU_OT_IS_FILE(objtype) &&
1929             has_special_class && size <= special_smallblk) {
1930                 metaslab_class_t *special = spa_special_class(spa);
1931                 uint64_t alloc = metaslab_class_get_alloc(special);
1932                 uint64_t space = metaslab_class_get_space(special);
1933                 uint64_t limit =
1934                     (space * (100 - zfs_special_class_metadata_reserve_pct))
1935                     / 100;
1936
1937                 if (alloc < limit)
1938                         return (special);
1939         }
1940
1941         return (spa_normal_class(spa));
1942 }
1943
1944 void
1945 spa_evicting_os_register(spa_t *spa, objset_t *os)
1946 {
1947         mutex_enter(&spa->spa_evicting_os_lock);
1948         list_insert_head(&spa->spa_evicting_os_list, os);
1949         mutex_exit(&spa->spa_evicting_os_lock);
1950 }
1951
1952 void
1953 spa_evicting_os_deregister(spa_t *spa, objset_t *os)
1954 {
1955         mutex_enter(&spa->spa_evicting_os_lock);
1956         list_remove(&spa->spa_evicting_os_list, os);
1957         cv_broadcast(&spa->spa_evicting_os_cv);
1958         mutex_exit(&spa->spa_evicting_os_lock);
1959 }
1960
1961 void
1962 spa_evicting_os_wait(spa_t *spa)
1963 {
1964         mutex_enter(&spa->spa_evicting_os_lock);
1965         while (!list_is_empty(&spa->spa_evicting_os_list))
1966                 cv_wait(&spa->spa_evicting_os_cv, &spa->spa_evicting_os_lock);
1967         mutex_exit(&spa->spa_evicting_os_lock);
1968
1969         dmu_buf_user_evict_wait();
1970 }
1971
1972 int
1973 spa_max_replication(spa_t *spa)
1974 {
1975         /*
1976          * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1977          * handle BPs with more than one DVA allocated.  Set our max
1978          * replication level accordingly.
1979          */
1980         if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1981                 return (1);
1982         return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1983 }
1984
1985 int
1986 spa_prev_software_version(spa_t *spa)
1987 {
1988         return (spa->spa_prev_software_version);
1989 }
1990
1991 uint64_t
1992 spa_deadman_synctime(spa_t *spa)
1993 {
1994         return (spa->spa_deadman_synctime);
1995 }
1996
1997 spa_autotrim_t
1998 spa_get_autotrim(spa_t *spa)
1999 {
2000         return (spa->spa_autotrim);
2001 }
2002
2003 uint64_t
2004 spa_deadman_ziotime(spa_t *spa)
2005 {
2006         return (spa->spa_deadman_ziotime);
2007 }
2008
2009 uint64_t
2010 spa_get_deadman_failmode(spa_t *spa)
2011 {
2012         return (spa->spa_deadman_failmode);
2013 }
2014
2015 void
2016 spa_set_deadman_failmode(spa_t *spa, const char *failmode)
2017 {
2018         if (strcmp(failmode, "wait") == 0)
2019                 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_WAIT;
2020         else if (strcmp(failmode, "continue") == 0)
2021                 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_CONTINUE;
2022         else if (strcmp(failmode, "panic") == 0)
2023                 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_PANIC;
2024         else
2025                 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_WAIT;
2026 }
2027
2028 void
2029 spa_set_deadman_ziotime(hrtime_t ns)
2030 {
2031         spa_t *spa = NULL;
2032
2033         if (spa_mode_global != SPA_MODE_UNINIT) {
2034                 mutex_enter(&spa_namespace_lock);
2035                 while ((spa = spa_next(spa)) != NULL)
2036                         spa->spa_deadman_ziotime = ns;
2037                 mutex_exit(&spa_namespace_lock);
2038         }
2039 }
2040
2041 void
2042 spa_set_deadman_synctime(hrtime_t ns)
2043 {
2044         spa_t *spa = NULL;
2045
2046         if (spa_mode_global != SPA_MODE_UNINIT) {
2047                 mutex_enter(&spa_namespace_lock);
2048                 while ((spa = spa_next(spa)) != NULL)
2049                         spa->spa_deadman_synctime = ns;
2050                 mutex_exit(&spa_namespace_lock);
2051         }
2052 }
2053
2054 uint64_t
2055 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
2056 {
2057         uint64_t asize = DVA_GET_ASIZE(dva);
2058         uint64_t dsize = asize;
2059
2060         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
2061
2062         if (asize != 0 && spa->spa_deflate) {
2063                 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
2064                 if (vd != NULL)
2065                         dsize = (asize >> SPA_MINBLOCKSHIFT) *
2066                             vd->vdev_deflate_ratio;
2067         }
2068
2069         return (dsize);
2070 }
2071
2072 uint64_t
2073 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
2074 {
2075         uint64_t dsize = 0;
2076
2077         for (int d = 0; d < BP_GET_NDVAS(bp); d++)
2078                 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
2079
2080         return (dsize);
2081 }
2082
2083 uint64_t
2084 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
2085 {
2086         uint64_t dsize = 0;
2087
2088         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2089
2090         for (int d = 0; d < BP_GET_NDVAS(bp); d++)
2091                 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
2092
2093         spa_config_exit(spa, SCL_VDEV, FTAG);
2094
2095         return (dsize);
2096 }
2097
2098 uint64_t
2099 spa_dirty_data(spa_t *spa)
2100 {
2101         return (spa->spa_dsl_pool->dp_dirty_total);
2102 }
2103
2104 /*
2105  * ==========================================================================
2106  * SPA Import Progress Routines
2107  * ==========================================================================
2108  */
2109
2110 typedef struct spa_import_progress {
2111         uint64_t                pool_guid;      /* unique id for updates */
2112         char                    *pool_name;
2113         spa_load_state_t        spa_load_state;
2114         uint64_t                mmp_sec_remaining;      /* MMP activity check */
2115         uint64_t                spa_load_max_txg;       /* rewind txg */
2116         procfs_list_node_t      smh_node;
2117 } spa_import_progress_t;
2118
2119 spa_history_list_t *spa_import_progress_list = NULL;
2120
2121 static int
2122 spa_import_progress_show_header(struct seq_file *f)
2123 {
2124         seq_printf(f, "%-20s %-14s %-14s %-12s %s\n", "pool_guid",
2125             "load_state", "multihost_secs", "max_txg",
2126             "pool_name");
2127         return (0);
2128 }
2129
2130 static int
2131 spa_import_progress_show(struct seq_file *f, void *data)
2132 {
2133         spa_import_progress_t *sip = (spa_import_progress_t *)data;
2134
2135         seq_printf(f, "%-20llu %-14llu %-14llu %-12llu %s\n",
2136             (u_longlong_t)sip->pool_guid, (u_longlong_t)sip->spa_load_state,
2137             (u_longlong_t)sip->mmp_sec_remaining,
2138             (u_longlong_t)sip->spa_load_max_txg,
2139             (sip->pool_name ? sip->pool_name : "-"));
2140
2141         return (0);
2142 }
2143
2144 /* Remove oldest elements from list until there are no more than 'size' left */
2145 static void
2146 spa_import_progress_truncate(spa_history_list_t *shl, unsigned int size)
2147 {
2148         spa_import_progress_t *sip;
2149         while (shl->size > size) {
2150                 sip = list_remove_head(&shl->procfs_list.pl_list);
2151                 if (sip->pool_name)
2152                         spa_strfree(sip->pool_name);
2153                 kmem_free(sip, sizeof (spa_import_progress_t));
2154                 shl->size--;
2155         }
2156
2157         IMPLY(size == 0, list_is_empty(&shl->procfs_list.pl_list));
2158 }
2159
2160 static void
2161 spa_import_progress_init(void)
2162 {
2163         spa_import_progress_list = kmem_zalloc(sizeof (spa_history_list_t),
2164             KM_SLEEP);
2165
2166         spa_import_progress_list->size = 0;
2167
2168         spa_import_progress_list->procfs_list.pl_private =
2169             spa_import_progress_list;
2170
2171         procfs_list_install("zfs",
2172             NULL,
2173             "import_progress",
2174             0644,
2175             &spa_import_progress_list->procfs_list,
2176             spa_import_progress_show,
2177             spa_import_progress_show_header,
2178             NULL,
2179             offsetof(spa_import_progress_t, smh_node));
2180 }
2181
2182 static void
2183 spa_import_progress_destroy(void)
2184 {
2185         spa_history_list_t *shl = spa_import_progress_list;
2186         procfs_list_uninstall(&shl->procfs_list);
2187         spa_import_progress_truncate(shl, 0);
2188         procfs_list_destroy(&shl->procfs_list);
2189         kmem_free(shl, sizeof (spa_history_list_t));
2190 }
2191
2192 int
2193 spa_import_progress_set_state(uint64_t pool_guid,
2194     spa_load_state_t load_state)
2195 {
2196         spa_history_list_t *shl = spa_import_progress_list;
2197         spa_import_progress_t *sip;
2198         int error = ENOENT;
2199
2200         if (shl->size == 0)
2201                 return (0);
2202
2203         mutex_enter(&shl->procfs_list.pl_lock);
2204         for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2205             sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2206                 if (sip->pool_guid == pool_guid) {
2207                         sip->spa_load_state = load_state;
2208                         error = 0;
2209                         break;
2210                 }
2211         }
2212         mutex_exit(&shl->procfs_list.pl_lock);
2213
2214         return (error);
2215 }
2216
2217 int
2218 spa_import_progress_set_max_txg(uint64_t pool_guid, uint64_t load_max_txg)
2219 {
2220         spa_history_list_t *shl = spa_import_progress_list;
2221         spa_import_progress_t *sip;
2222         int error = ENOENT;
2223
2224         if (shl->size == 0)
2225                 return (0);
2226
2227         mutex_enter(&shl->procfs_list.pl_lock);
2228         for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2229             sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2230                 if (sip->pool_guid == pool_guid) {
2231                         sip->spa_load_max_txg = load_max_txg;
2232                         error = 0;
2233                         break;
2234                 }
2235         }
2236         mutex_exit(&shl->procfs_list.pl_lock);
2237
2238         return (error);
2239 }
2240
2241 int
2242 spa_import_progress_set_mmp_check(uint64_t pool_guid,
2243     uint64_t mmp_sec_remaining)
2244 {
2245         spa_history_list_t *shl = spa_import_progress_list;
2246         spa_import_progress_t *sip;
2247         int error = ENOENT;
2248
2249         if (shl->size == 0)
2250                 return (0);
2251
2252         mutex_enter(&shl->procfs_list.pl_lock);
2253         for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2254             sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2255                 if (sip->pool_guid == pool_guid) {
2256                         sip->mmp_sec_remaining = mmp_sec_remaining;
2257                         error = 0;
2258                         break;
2259                 }
2260         }
2261         mutex_exit(&shl->procfs_list.pl_lock);
2262
2263         return (error);
2264 }
2265
2266 /*
2267  * A new import is in progress, add an entry.
2268  */
2269 void
2270 spa_import_progress_add(spa_t *spa)
2271 {
2272         spa_history_list_t *shl = spa_import_progress_list;
2273         spa_import_progress_t *sip;
2274         char *poolname = NULL;
2275
2276         sip = kmem_zalloc(sizeof (spa_import_progress_t), KM_SLEEP);
2277         sip->pool_guid = spa_guid(spa);
2278
2279         (void) nvlist_lookup_string(spa->spa_config, ZPOOL_CONFIG_POOL_NAME,
2280             &poolname);
2281         if (poolname == NULL)
2282                 poolname = spa_name(spa);
2283         sip->pool_name = spa_strdup(poolname);
2284         sip->spa_load_state = spa_load_state(spa);
2285
2286         mutex_enter(&shl->procfs_list.pl_lock);
2287         procfs_list_add(&shl->procfs_list, sip);
2288         shl->size++;
2289         mutex_exit(&shl->procfs_list.pl_lock);
2290 }
2291
2292 void
2293 spa_import_progress_remove(uint64_t pool_guid)
2294 {
2295         spa_history_list_t *shl = spa_import_progress_list;
2296         spa_import_progress_t *sip;
2297
2298         mutex_enter(&shl->procfs_list.pl_lock);
2299         for (sip = list_tail(&shl->procfs_list.pl_list); sip != NULL;
2300             sip = list_prev(&shl->procfs_list.pl_list, sip)) {
2301                 if (sip->pool_guid == pool_guid) {
2302                         if (sip->pool_name)
2303                                 spa_strfree(sip->pool_name);
2304                         list_remove(&shl->procfs_list.pl_list, sip);
2305                         shl->size--;
2306                         kmem_free(sip, sizeof (spa_import_progress_t));
2307                         break;
2308                 }
2309         }
2310         mutex_exit(&shl->procfs_list.pl_lock);
2311 }
2312
2313 /*
2314  * ==========================================================================
2315  * Initialization and Termination
2316  * ==========================================================================
2317  */
2318
2319 static int
2320 spa_name_compare(const void *a1, const void *a2)
2321 {
2322         const spa_t *s1 = a1;
2323         const spa_t *s2 = a2;
2324         int s;
2325
2326         s = strcmp(s1->spa_name, s2->spa_name);
2327
2328         return (TREE_ISIGN(s));
2329 }
2330
2331 void
2332 spa_boot_init(void)
2333 {
2334         spa_config_load();
2335 }
2336
2337 void
2338 spa_init(spa_mode_t mode)
2339 {
2340         mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
2341         mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
2342         mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
2343         cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
2344
2345         avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
2346             offsetof(spa_t, spa_avl));
2347
2348         avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
2349             offsetof(spa_aux_t, aux_avl));
2350
2351         avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
2352             offsetof(spa_aux_t, aux_avl));
2353
2354         spa_mode_global = mode;
2355
2356 #ifndef _KERNEL
2357         if (spa_mode_global != SPA_MODE_READ && dprintf_find_string("watch")) {
2358                 struct sigaction sa;
2359
2360                 sa.sa_flags = SA_SIGINFO;
2361                 sigemptyset(&sa.sa_mask);
2362                 sa.sa_sigaction = arc_buf_sigsegv;
2363
2364                 if (sigaction(SIGSEGV, &sa, NULL) == -1) {
2365                         perror("could not enable watchpoints: "
2366                             "sigaction(SIGSEGV, ...) = ");
2367                 } else {
2368                         arc_watch = B_TRUE;
2369                 }
2370         }
2371 #endif
2372
2373         fm_init();
2374         zfs_refcount_init();
2375         unique_init();
2376         zfs_btree_init();
2377         metaslab_stat_init();
2378         ddt_init();
2379         zio_init();
2380         dmu_init();
2381         zil_init();
2382         vdev_cache_stat_init();
2383         vdev_mirror_stat_init();
2384         vdev_raidz_math_init();
2385         vdev_file_init();
2386         zfs_prop_init();
2387         zpool_prop_init();
2388         zpool_feature_init();
2389         spa_config_load();
2390         l2arc_start();
2391         scan_init();
2392         qat_init();
2393         spa_import_progress_init();
2394 }
2395
2396 void
2397 spa_fini(void)
2398 {
2399         l2arc_stop();
2400
2401         spa_evict_all();
2402
2403         vdev_file_fini();
2404         vdev_cache_stat_fini();
2405         vdev_mirror_stat_fini();
2406         vdev_raidz_math_fini();
2407         zil_fini();
2408         dmu_fini();
2409         zio_fini();
2410         ddt_fini();
2411         metaslab_stat_fini();
2412         zfs_btree_fini();
2413         unique_fini();
2414         zfs_refcount_fini();
2415         fm_fini();
2416         scan_fini();
2417         qat_fini();
2418         spa_import_progress_destroy();
2419
2420         avl_destroy(&spa_namespace_avl);
2421         avl_destroy(&spa_spare_avl);
2422         avl_destroy(&spa_l2cache_avl);
2423
2424         cv_destroy(&spa_namespace_cv);
2425         mutex_destroy(&spa_namespace_lock);
2426         mutex_destroy(&spa_spare_lock);
2427         mutex_destroy(&spa_l2cache_lock);
2428 }
2429
2430 /*
2431  * Return whether this pool has slogs. No locking needed.
2432  * It's not a problem if the wrong answer is returned as it's only for
2433  * performance and not correctness
2434  */
2435 boolean_t
2436 spa_has_slogs(spa_t *spa)
2437 {
2438         return (spa->spa_log_class->mc_rotor != NULL);
2439 }
2440
2441 spa_log_state_t
2442 spa_get_log_state(spa_t *spa)
2443 {
2444         return (spa->spa_log_state);
2445 }
2446
2447 void
2448 spa_set_log_state(spa_t *spa, spa_log_state_t state)
2449 {
2450         spa->spa_log_state = state;
2451 }
2452
2453 boolean_t
2454 spa_is_root(spa_t *spa)
2455 {
2456         return (spa->spa_is_root);
2457 }
2458
2459 boolean_t
2460 spa_writeable(spa_t *spa)
2461 {
2462         return (!!(spa->spa_mode & SPA_MODE_WRITE) && spa->spa_trust_config);
2463 }
2464
2465 /*
2466  * Returns true if there is a pending sync task in any of the current
2467  * syncing txg, the current quiescing txg, or the current open txg.
2468  */
2469 boolean_t
2470 spa_has_pending_synctask(spa_t *spa)
2471 {
2472         return (!txg_all_lists_empty(&spa->spa_dsl_pool->dp_sync_tasks) ||
2473             !txg_all_lists_empty(&spa->spa_dsl_pool->dp_early_sync_tasks));
2474 }
2475
2476 spa_mode_t
2477 spa_mode(spa_t *spa)
2478 {
2479         return (spa->spa_mode);
2480 }
2481
2482 uint64_t
2483 spa_bootfs(spa_t *spa)
2484 {
2485         return (spa->spa_bootfs);
2486 }
2487
2488 uint64_t
2489 spa_delegation(spa_t *spa)
2490 {
2491         return (spa->spa_delegation);
2492 }
2493
2494 objset_t *
2495 spa_meta_objset(spa_t *spa)
2496 {
2497         return (spa->spa_meta_objset);
2498 }
2499
2500 enum zio_checksum
2501 spa_dedup_checksum(spa_t *spa)
2502 {
2503         return (spa->spa_dedup_checksum);
2504 }
2505
2506 /*
2507  * Reset pool scan stat per scan pass (or reboot).
2508  */
2509 void
2510 spa_scan_stat_init(spa_t *spa)
2511 {
2512         /* data not stored on disk */
2513         spa->spa_scan_pass_start = gethrestime_sec();
2514         if (dsl_scan_is_paused_scrub(spa->spa_dsl_pool->dp_scan))
2515                 spa->spa_scan_pass_scrub_pause = spa->spa_scan_pass_start;
2516         else
2517                 spa->spa_scan_pass_scrub_pause = 0;
2518         spa->spa_scan_pass_scrub_spent_paused = 0;
2519         spa->spa_scan_pass_exam = 0;
2520         spa->spa_scan_pass_issued = 0;
2521         vdev_scan_stat_init(spa->spa_root_vdev);
2522 }
2523
2524 /*
2525  * Get scan stats for zpool status reports
2526  */
2527 int
2528 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
2529 {
2530         dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
2531
2532         if (scn == NULL || scn->scn_phys.scn_func == POOL_SCAN_NONE)
2533                 return (SET_ERROR(ENOENT));
2534         bzero(ps, sizeof (pool_scan_stat_t));
2535
2536         /* data stored on disk */
2537         ps->pss_func = scn->scn_phys.scn_func;
2538         ps->pss_state = scn->scn_phys.scn_state;
2539         ps->pss_start_time = scn->scn_phys.scn_start_time;
2540         ps->pss_end_time = scn->scn_phys.scn_end_time;
2541         ps->pss_to_examine = scn->scn_phys.scn_to_examine;
2542         ps->pss_examined = scn->scn_phys.scn_examined;
2543         ps->pss_to_process = scn->scn_phys.scn_to_process;
2544         ps->pss_processed = scn->scn_phys.scn_processed;
2545         ps->pss_errors = scn->scn_phys.scn_errors;
2546
2547         /* data not stored on disk */
2548         ps->pss_pass_exam = spa->spa_scan_pass_exam;
2549         ps->pss_pass_start = spa->spa_scan_pass_start;
2550         ps->pss_pass_scrub_pause = spa->spa_scan_pass_scrub_pause;
2551         ps->pss_pass_scrub_spent_paused = spa->spa_scan_pass_scrub_spent_paused;
2552         ps->pss_pass_issued = spa->spa_scan_pass_issued;
2553         ps->pss_issued =
2554             scn->scn_issued_before_pass + spa->spa_scan_pass_issued;
2555
2556         return (0);
2557 }
2558
2559 int
2560 spa_maxblocksize(spa_t *spa)
2561 {
2562         if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
2563                 return (SPA_MAXBLOCKSIZE);
2564         else
2565                 return (SPA_OLD_MAXBLOCKSIZE);
2566 }
2567
2568
2569 /*
2570  * Returns the txg that the last device removal completed. No indirect mappings
2571  * have been added since this txg.
2572  */
2573 uint64_t
2574 spa_get_last_removal_txg(spa_t *spa)
2575 {
2576         uint64_t vdevid;
2577         uint64_t ret = -1ULL;
2578
2579         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2580         /*
2581          * sr_prev_indirect_vdev is only modified while holding all the
2582          * config locks, so it is sufficient to hold SCL_VDEV as reader when
2583          * examining it.
2584          */
2585         vdevid = spa->spa_removing_phys.sr_prev_indirect_vdev;
2586
2587         while (vdevid != -1ULL) {
2588                 vdev_t *vd = vdev_lookup_top(spa, vdevid);
2589                 vdev_indirect_births_t *vib = vd->vdev_indirect_births;
2590
2591                 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
2592
2593                 /*
2594                  * If the removal did not remap any data, we don't care.
2595                  */
2596                 if (vdev_indirect_births_count(vib) != 0) {
2597                         ret = vdev_indirect_births_last_entry_txg(vib);
2598                         break;
2599                 }
2600
2601                 vdevid = vd->vdev_indirect_config.vic_prev_indirect_vdev;
2602         }
2603         spa_config_exit(spa, SCL_VDEV, FTAG);
2604
2605         IMPLY(ret != -1ULL,
2606             spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
2607
2608         return (ret);
2609 }
2610
2611 int
2612 spa_maxdnodesize(spa_t *spa)
2613 {
2614         if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE))
2615                 return (DNODE_MAX_SIZE);
2616         else
2617                 return (DNODE_MIN_SIZE);
2618 }
2619
2620 boolean_t
2621 spa_multihost(spa_t *spa)
2622 {
2623         return (spa->spa_multihost ? B_TRUE : B_FALSE);
2624 }
2625
2626 uint32_t
2627 spa_get_hostid(spa_t *spa)
2628 {
2629         return (spa->spa_hostid);
2630 }
2631
2632 boolean_t
2633 spa_trust_config(spa_t *spa)
2634 {
2635         return (spa->spa_trust_config);
2636 }
2637
2638 uint64_t
2639 spa_missing_tvds_allowed(spa_t *spa)
2640 {
2641         return (spa->spa_missing_tvds_allowed);
2642 }
2643
2644 space_map_t *
2645 spa_syncing_log_sm(spa_t *spa)
2646 {
2647         return (spa->spa_syncing_log_sm);
2648 }
2649
2650 void
2651 spa_set_missing_tvds(spa_t *spa, uint64_t missing)
2652 {
2653         spa->spa_missing_tvds = missing;
2654 }
2655
2656 /*
2657  * Return the pool state string ("ONLINE", "DEGRADED", "SUSPENDED", etc).
2658  */
2659 const char *
2660 spa_state_to_name(spa_t *spa)
2661 {
2662         ASSERT3P(spa, !=, NULL);
2663
2664         /*
2665          * it is possible for the spa to exist, without root vdev
2666          * as the spa transitions during import/export
2667          */
2668         vdev_t *rvd = spa->spa_root_vdev;
2669         if (rvd == NULL) {
2670                 return ("TRANSITIONING");
2671         }
2672         vdev_state_t state = rvd->vdev_state;
2673         vdev_aux_t aux = rvd->vdev_stat.vs_aux;
2674
2675         if (spa_suspended(spa) &&
2676             (spa_get_failmode(spa) != ZIO_FAILURE_MODE_CONTINUE))
2677                 return ("SUSPENDED");
2678
2679         switch (state) {
2680         case VDEV_STATE_CLOSED:
2681         case VDEV_STATE_OFFLINE:
2682                 return ("OFFLINE");
2683         case VDEV_STATE_REMOVED:
2684                 return ("REMOVED");
2685         case VDEV_STATE_CANT_OPEN:
2686                 if (aux == VDEV_AUX_CORRUPT_DATA || aux == VDEV_AUX_BAD_LOG)
2687                         return ("FAULTED");
2688                 else if (aux == VDEV_AUX_SPLIT_POOL)
2689                         return ("SPLIT");
2690                 else
2691                         return ("UNAVAIL");
2692         case VDEV_STATE_FAULTED:
2693                 return ("FAULTED");
2694         case VDEV_STATE_DEGRADED:
2695                 return ("DEGRADED");
2696         case VDEV_STATE_HEALTHY:
2697                 return ("ONLINE");
2698         default:
2699                 break;
2700         }
2701
2702         return ("UNKNOWN");
2703 }
2704
2705 boolean_t
2706 spa_top_vdevs_spacemap_addressable(spa_t *spa)
2707 {
2708         vdev_t *rvd = spa->spa_root_vdev;
2709         for (uint64_t c = 0; c < rvd->vdev_children; c++) {
2710                 if (!vdev_is_spacemap_addressable(rvd->vdev_child[c]))
2711                         return (B_FALSE);
2712         }
2713         return (B_TRUE);
2714 }
2715
2716 boolean_t
2717 spa_has_checkpoint(spa_t *spa)
2718 {
2719         return (spa->spa_checkpoint_txg != 0);
2720 }
2721
2722 boolean_t
2723 spa_importing_readonly_checkpoint(spa_t *spa)
2724 {
2725         return ((spa->spa_import_flags & ZFS_IMPORT_CHECKPOINT) &&
2726             spa->spa_mode == SPA_MODE_READ);
2727 }
2728
2729 uint64_t
2730 spa_min_claim_txg(spa_t *spa)
2731 {
2732         uint64_t checkpoint_txg = spa->spa_uberblock.ub_checkpoint_txg;
2733
2734         if (checkpoint_txg != 0)
2735                 return (checkpoint_txg + 1);
2736
2737         return (spa->spa_first_txg);
2738 }
2739
2740 /*
2741  * If there is a checkpoint, async destroys may consume more space from
2742  * the pool instead of freeing it. In an attempt to save the pool from
2743  * getting suspended when it is about to run out of space, we stop
2744  * processing async destroys.
2745  */
2746 boolean_t
2747 spa_suspend_async_destroy(spa_t *spa)
2748 {
2749         dsl_pool_t *dp = spa_get_dsl(spa);
2750
2751         uint64_t unreserved = dsl_pool_unreserved_space(dp,
2752             ZFS_SPACE_CHECK_EXTRA_RESERVED);
2753         uint64_t used = dsl_dir_phys(dp->dp_root_dir)->dd_used_bytes;
2754         uint64_t avail = (unreserved > used) ? (unreserved - used) : 0;
2755
2756         if (spa_has_checkpoint(spa) && avail == 0)
2757                 return (B_TRUE);
2758
2759         return (B_FALSE);
2760 }
2761
2762 #if defined(_KERNEL)
2763
2764 int
2765 param_set_deadman_failmode_common(const char *val)
2766 {
2767         spa_t *spa = NULL;
2768         char *p;
2769
2770         if (val == NULL)
2771                 return (SET_ERROR(EINVAL));
2772
2773         if ((p = strchr(val, '\n')) != NULL)
2774                 *p = '\0';
2775
2776         if (strcmp(val, "wait") != 0 && strcmp(val, "continue") != 0 &&
2777             strcmp(val, "panic"))
2778                 return (SET_ERROR(EINVAL));
2779
2780         if (spa_mode_global != SPA_MODE_UNINIT) {
2781                 mutex_enter(&spa_namespace_lock);
2782                 while ((spa = spa_next(spa)) != NULL)
2783                         spa_set_deadman_failmode(spa, val);
2784                 mutex_exit(&spa_namespace_lock);
2785         }
2786
2787         return (0);
2788 }
2789 #endif
2790
2791 /* Namespace manipulation */
2792 EXPORT_SYMBOL(spa_lookup);
2793 EXPORT_SYMBOL(spa_add);
2794 EXPORT_SYMBOL(spa_remove);
2795 EXPORT_SYMBOL(spa_next);
2796
2797 /* Refcount functions */
2798 EXPORT_SYMBOL(spa_open_ref);
2799 EXPORT_SYMBOL(spa_close);
2800 EXPORT_SYMBOL(spa_refcount_zero);
2801
2802 /* Pool configuration lock */
2803 EXPORT_SYMBOL(spa_config_tryenter);
2804 EXPORT_SYMBOL(spa_config_enter);
2805 EXPORT_SYMBOL(spa_config_exit);
2806 EXPORT_SYMBOL(spa_config_held);
2807
2808 /* Pool vdev add/remove lock */
2809 EXPORT_SYMBOL(spa_vdev_enter);
2810 EXPORT_SYMBOL(spa_vdev_exit);
2811
2812 /* Pool vdev state change lock */
2813 EXPORT_SYMBOL(spa_vdev_state_enter);
2814 EXPORT_SYMBOL(spa_vdev_state_exit);
2815
2816 /* Accessor functions */
2817 EXPORT_SYMBOL(spa_shutting_down);
2818 EXPORT_SYMBOL(spa_get_dsl);
2819 EXPORT_SYMBOL(spa_get_rootblkptr);
2820 EXPORT_SYMBOL(spa_set_rootblkptr);
2821 EXPORT_SYMBOL(spa_altroot);
2822 EXPORT_SYMBOL(spa_sync_pass);
2823 EXPORT_SYMBOL(spa_name);
2824 EXPORT_SYMBOL(spa_guid);
2825 EXPORT_SYMBOL(spa_last_synced_txg);
2826 EXPORT_SYMBOL(spa_first_txg);
2827 EXPORT_SYMBOL(spa_syncing_txg);
2828 EXPORT_SYMBOL(spa_version);
2829 EXPORT_SYMBOL(spa_state);
2830 EXPORT_SYMBOL(spa_load_state);
2831 EXPORT_SYMBOL(spa_freeze_txg);
2832 EXPORT_SYMBOL(spa_get_dspace);
2833 EXPORT_SYMBOL(spa_update_dspace);
2834 EXPORT_SYMBOL(spa_deflate);
2835 EXPORT_SYMBOL(spa_normal_class);
2836 EXPORT_SYMBOL(spa_log_class);
2837 EXPORT_SYMBOL(spa_special_class);
2838 EXPORT_SYMBOL(spa_preferred_class);
2839 EXPORT_SYMBOL(spa_max_replication);
2840 EXPORT_SYMBOL(spa_prev_software_version);
2841 EXPORT_SYMBOL(spa_get_failmode);
2842 EXPORT_SYMBOL(spa_suspended);
2843 EXPORT_SYMBOL(spa_bootfs);
2844 EXPORT_SYMBOL(spa_delegation);
2845 EXPORT_SYMBOL(spa_meta_objset);
2846 EXPORT_SYMBOL(spa_maxblocksize);
2847 EXPORT_SYMBOL(spa_maxdnodesize);
2848
2849 /* Miscellaneous support routines */
2850 EXPORT_SYMBOL(spa_guid_exists);
2851 EXPORT_SYMBOL(spa_strdup);
2852 EXPORT_SYMBOL(spa_strfree);
2853 EXPORT_SYMBOL(spa_get_random);
2854 EXPORT_SYMBOL(spa_generate_guid);
2855 EXPORT_SYMBOL(snprintf_blkptr);
2856 EXPORT_SYMBOL(spa_freeze);
2857 EXPORT_SYMBOL(spa_upgrade);
2858 EXPORT_SYMBOL(spa_evict_all);
2859 EXPORT_SYMBOL(spa_lookup_by_guid);
2860 EXPORT_SYMBOL(spa_has_spare);
2861 EXPORT_SYMBOL(dva_get_dsize_sync);
2862 EXPORT_SYMBOL(bp_get_dsize_sync);
2863 EXPORT_SYMBOL(bp_get_dsize);
2864 EXPORT_SYMBOL(spa_has_slogs);
2865 EXPORT_SYMBOL(spa_is_root);
2866 EXPORT_SYMBOL(spa_writeable);
2867 EXPORT_SYMBOL(spa_mode);
2868 EXPORT_SYMBOL(spa_namespace_lock);
2869 EXPORT_SYMBOL(spa_trust_config);
2870 EXPORT_SYMBOL(spa_missing_tvds_allowed);
2871 EXPORT_SYMBOL(spa_set_missing_tvds);
2872 EXPORT_SYMBOL(spa_state_to_name);
2873 EXPORT_SYMBOL(spa_importing_readonly_checkpoint);
2874 EXPORT_SYMBOL(spa_min_claim_txg);
2875 EXPORT_SYMBOL(spa_suspend_async_destroy);
2876 EXPORT_SYMBOL(spa_has_checkpoint);
2877 EXPORT_SYMBOL(spa_top_vdevs_spacemap_addressable);
2878
2879 ZFS_MODULE_PARAM(zfs, zfs_, flags, UINT, ZMOD_RW,
2880         "Set additional debugging flags");
2881
2882 ZFS_MODULE_PARAM(zfs, zfs_, recover, INT, ZMOD_RW,
2883         "Set to attempt to recover from fatal errors");
2884
2885 ZFS_MODULE_PARAM(zfs, zfs_, free_leak_on_eio, INT, ZMOD_RW,
2886         "Set to ignore IO errors during free and permanently leak the space");
2887
2888 ZFS_MODULE_PARAM(zfs, zfs_, deadman_checktime_ms, ULONG, ZMOD_RW,
2889         "Dead I/O check interval in milliseconds");
2890
2891 ZFS_MODULE_PARAM(zfs, zfs_, deadman_enabled, INT, ZMOD_RW,
2892         "Enable deadman timer");
2893
2894 ZFS_MODULE_PARAM(zfs_spa, spa_, asize_inflation, INT, ZMOD_RW,
2895         "SPA size estimate multiplication factor");
2896
2897 ZFS_MODULE_PARAM(zfs, zfs_, ddt_data_is_special, INT, ZMOD_RW,
2898         "Place DDT data into the special class");
2899
2900 ZFS_MODULE_PARAM(zfs, zfs_, user_indirect_is_special, INT, ZMOD_RW,
2901         "Place user data indirect blocks into the special class");
2902
2903 /* BEGIN CSTYLED */
2904 ZFS_MODULE_PARAM_CALL(zfs_deadman, zfs_deadman_, failmode,
2905         param_set_deadman_failmode, param_get_charp, ZMOD_RW,
2906         "Failmode for deadman timer");
2907
2908 ZFS_MODULE_PARAM_CALL(zfs_deadman, zfs_deadman_, synctime_ms,
2909         param_set_deadman_synctime, param_get_ulong, ZMOD_RW,
2910         "Pool sync expiration time in milliseconds");
2911
2912 ZFS_MODULE_PARAM_CALL(zfs_deadman, zfs_deadman_, ziotime_ms,
2913         param_set_deadman_ziotime, param_get_ulong, ZMOD_RW,
2914         "IO expiration time in milliseconds");
2915
2916 ZFS_MODULE_PARAM(zfs, zfs_, special_class_metadata_reserve_pct, INT, ZMOD_RW,
2917         "Small file blocks in special vdevs depends on this much "
2918         "free space available");
2919 /* END CSTYLED */
2920
2921 ZFS_MODULE_PARAM_CALL(zfs_spa, spa_, slop_shift, param_set_slop_shift,
2922         param_get_int, ZMOD_RW, "Reserved free space in pool");