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