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