]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_misc.c
MFC ZFS version 28 and related revisions:
[FreeBSD/stable/8.git] / sys / cddl / contrib / opensolaris / uts / common / fs / 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  */
24
25 #include <sys/zfs_context.h>
26 #include <sys/spa_impl.h>
27 #include <sys/zio.h>
28 #include <sys/zio_checksum.h>
29 #include <sys/zio_compress.h>
30 #include <sys/dmu.h>
31 #include <sys/dmu_tx.h>
32 #include <sys/zap.h>
33 #include <sys/zil.h>
34 #include <sys/vdev_impl.h>
35 #include <sys/metaslab.h>
36 #include <sys/uberblock_impl.h>
37 #include <sys/txg.h>
38 #include <sys/avl.h>
39 #include <sys/unique.h>
40 #include <sys/dsl_pool.h>
41 #include <sys/dsl_dir.h>
42 #include <sys/dsl_prop.h>
43 #include <sys/dsl_scan.h>
44 #include <sys/fs/zfs.h>
45 #include <sys/metaslab_impl.h>
46 #include <sys/arc.h>
47 #include <sys/ddt.h>
48 #include "zfs_prop.h"
49
50 /*
51  * SPA locking
52  *
53  * There are four basic locks for managing spa_t structures:
54  *
55  * spa_namespace_lock (global mutex)
56  *
57  *      This lock must be acquired to do any of the following:
58  *
59  *              - Lookup a spa_t by name
60  *              - Add or remove a spa_t from the namespace
61  *              - Increase spa_refcount from non-zero
62  *              - Check if spa_refcount is zero
63  *              - Rename a spa_t
64  *              - add/remove/attach/detach devices
65  *              - Held for the duration of create/destroy/import/export
66  *
67  *      It does not need to handle recursion.  A create or destroy may
68  *      reference objects (files or zvols) in other pools, but by
69  *      definition they must have an existing reference, and will never need
70  *      to lookup a spa_t by name.
71  *
72  * spa_refcount (per-spa refcount_t protected by mutex)
73  *
74  *      This reference count keep track of any active users of the spa_t.  The
75  *      spa_t cannot be destroyed or freed while this is non-zero.  Internally,
76  *      the refcount is never really 'zero' - opening a pool implicitly keeps
77  *      some references in the DMU.  Internally we check against spa_minref, but
78  *      present the image of a zero/non-zero value to consumers.
79  *
80  * spa_config_lock[] (per-spa array of rwlocks)
81  *
82  *      This protects the spa_t from config changes, and must be held in
83  *      the following circumstances:
84  *
85  *              - RW_READER to perform I/O to the spa
86  *              - RW_WRITER to change the vdev config
87  *
88  * The locking order is fairly straightforward:
89  *
90  *              spa_namespace_lock      ->      spa_refcount
91  *
92  *      The namespace lock must be acquired to increase the refcount from 0
93  *      or to check if it is zero.
94  *
95  *              spa_refcount            ->      spa_config_lock[]
96  *
97  *      There must be at least one valid reference on the spa_t to acquire
98  *      the config lock.
99  *
100  *              spa_namespace_lock      ->      spa_config_lock[]
101  *
102  *      The namespace lock must always be taken before the config lock.
103  *
104  *
105  * The spa_namespace_lock can be acquired directly and is globally visible.
106  *
107  * The namespace is manipulated using the following functions, all of which
108  * require the spa_namespace_lock to be held.
109  *
110  *      spa_lookup()            Lookup a spa_t by name.
111  *
112  *      spa_add()               Create a new spa_t in the namespace.
113  *
114  *      spa_remove()            Remove a spa_t from the namespace.  This also
115  *                              frees up any memory associated with the spa_t.
116  *
117  *      spa_next()              Returns the next spa_t in the system, or the
118  *                              first if NULL is passed.
119  *
120  *      spa_evict_all()         Shutdown and remove all spa_t structures in
121  *                              the system.
122  *
123  *      spa_guid_exists()       Determine whether a pool/device guid exists.
124  *
125  * The spa_refcount is manipulated using the following functions:
126  *
127  *      spa_open_ref()          Adds a reference to the given spa_t.  Must be
128  *                              called with spa_namespace_lock held if the
129  *                              refcount is currently zero.
130  *
131  *      spa_close()             Remove a reference from the spa_t.  This will
132  *                              not free the spa_t or remove it from the
133  *                              namespace.  No locking is required.
134  *
135  *      spa_refcount_zero()     Returns true if the refcount is currently
136  *                              zero.  Must be called with spa_namespace_lock
137  *                              held.
138  *
139  * The spa_config_lock[] is an array of rwlocks, ordered as follows:
140  * SCL_CONFIG > SCL_STATE > SCL_ALLOC > SCL_ZIO > SCL_FREE > SCL_VDEV.
141  * spa_config_lock[] is manipulated with spa_config_{enter,exit,held}().
142  *
143  * To read the configuration, it suffices to hold one of these locks as reader.
144  * To modify the configuration, you must hold all locks as writer.  To modify
145  * vdev state without altering the vdev tree's topology (e.g. online/offline),
146  * you must hold SCL_STATE and SCL_ZIO as writer.
147  *
148  * We use these distinct config locks to avoid recursive lock entry.
149  * For example, spa_sync() (which holds SCL_CONFIG as reader) induces
150  * block allocations (SCL_ALLOC), which may require reading space maps
151  * from disk (dmu_read() -> zio_read() -> SCL_ZIO).
152  *
153  * The spa config locks cannot be normal rwlocks because we need the
154  * ability to hand off ownership.  For example, SCL_ZIO is acquired
155  * by the issuing thread and later released by an interrupt thread.
156  * They do, however, obey the usual write-wanted semantics to prevent
157  * writer (i.e. system administrator) starvation.
158  *
159  * The lock acquisition rules are as follows:
160  *
161  * SCL_CONFIG
162  *      Protects changes to the vdev tree topology, such as vdev
163  *      add/remove/attach/detach.  Protects the dirty config list
164  *      (spa_config_dirty_list) and the set of spares and l2arc devices.
165  *
166  * SCL_STATE
167  *      Protects changes to pool state and vdev state, such as vdev
168  *      online/offline/fault/degrade/clear.  Protects the dirty state list
169  *      (spa_state_dirty_list) and global pool state (spa_state).
170  *
171  * SCL_ALLOC
172  *      Protects changes to metaslab groups and classes.
173  *      Held as reader by metaslab_alloc() and metaslab_claim().
174  *
175  * SCL_ZIO
176  *      Held by bp-level zios (those which have no io_vd upon entry)
177  *      to prevent changes to the vdev tree.  The bp-level zio implicitly
178  *      protects all of its vdev child zios, which do not hold SCL_ZIO.
179  *
180  * SCL_FREE
181  *      Protects changes to metaslab groups and classes.
182  *      Held as reader by metaslab_free().  SCL_FREE is distinct from
183  *      SCL_ALLOC, and lower than SCL_ZIO, so that we can safely free
184  *      blocks in zio_done() while another i/o that holds either
185  *      SCL_ALLOC or SCL_ZIO is waiting for this i/o to complete.
186  *
187  * SCL_VDEV
188  *      Held as reader to prevent changes to the vdev tree during trivial
189  *      inquiries such as bp_get_dsize().  SCL_VDEV is distinct from the
190  *      other locks, and lower than all of them, to ensure that it's safe
191  *      to acquire regardless of caller context.
192  *
193  * In addition, the following rules apply:
194  *
195  * (a)  spa_props_lock protects pool properties, spa_config and spa_config_list.
196  *      The lock ordering is SCL_CONFIG > spa_props_lock.
197  *
198  * (b)  I/O operations on leaf vdevs.  For any zio operation that takes
199  *      an explicit vdev_t argument -- such as zio_ioctl(), zio_read_phys(),
200  *      or zio_write_phys() -- the caller must ensure that the config cannot
201  *      cannot change in the interim, and that the vdev cannot be reopened.
202  *      SCL_STATE as reader suffices for both.
203  *
204  * The vdev configuration is protected by spa_vdev_enter() / spa_vdev_exit().
205  *
206  *      spa_vdev_enter()        Acquire the namespace lock and the config lock
207  *                              for writing.
208  *
209  *      spa_vdev_exit()         Release the config lock, wait for all I/O
210  *                              to complete, sync the updated configs to the
211  *                              cache, and release the namespace lock.
212  *
213  * vdev state is protected by spa_vdev_state_enter() / spa_vdev_state_exit().
214  * Like spa_vdev_enter/exit, these are convenience wrappers -- the actual
215  * locking is, always, based on spa_namespace_lock and spa_config_lock[].
216  *
217  * spa_rename() is also implemented within this file since is requires
218  * manipulation of the namespace.
219  */
220
221 static avl_tree_t spa_namespace_avl;
222 kmutex_t spa_namespace_lock;
223 static kcondvar_t spa_namespace_cv;
224 static int spa_active_count;
225 int spa_max_replication_override = SPA_DVAS_PER_BP;
226
227 static kmutex_t spa_spare_lock;
228 static avl_tree_t spa_spare_avl;
229 static kmutex_t spa_l2cache_lock;
230 static avl_tree_t spa_l2cache_avl;
231
232 kmem_cache_t *spa_buffer_pool;
233 int spa_mode_global;
234
235 #ifdef ZFS_DEBUG
236 /* Everything except dprintf is on by default in debug builds */
237 int zfs_flags = ~ZFS_DEBUG_DPRINTF;
238 #else
239 int zfs_flags = 0;
240 #endif
241
242 /*
243  * zfs_recover can be set to nonzero to attempt to recover from
244  * otherwise-fatal errors, typically caused by on-disk corruption.  When
245  * set, calls to zfs_panic_recover() will turn into warning messages.
246  */
247 int zfs_recover = 0;
248 SYSCTL_DECL(_vfs_zfs);
249 TUNABLE_INT("vfs.zfs.recover", &zfs_recover);
250 SYSCTL_INT(_vfs_zfs, OID_AUTO, recover, CTLFLAG_RDTUN, &zfs_recover, 0,
251     "Try to recover from otherwise-fatal errors.");
252
253
254 /*
255  * ==========================================================================
256  * SPA config locking
257  * ==========================================================================
258  */
259 static void
260 spa_config_lock_init(spa_t *spa)
261 {
262         for (int i = 0; i < SCL_LOCKS; i++) {
263                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
264                 mutex_init(&scl->scl_lock, NULL, MUTEX_DEFAULT, NULL);
265                 cv_init(&scl->scl_cv, NULL, CV_DEFAULT, NULL);
266                 refcount_create(&scl->scl_count);
267                 scl->scl_writer = NULL;
268                 scl->scl_write_wanted = 0;
269         }
270 }
271
272 static void
273 spa_config_lock_destroy(spa_t *spa)
274 {
275         for (int i = 0; i < SCL_LOCKS; i++) {
276                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
277                 mutex_destroy(&scl->scl_lock);
278                 cv_destroy(&scl->scl_cv);
279                 refcount_destroy(&scl->scl_count);
280                 ASSERT(scl->scl_writer == NULL);
281                 ASSERT(scl->scl_write_wanted == 0);
282         }
283 }
284
285 int
286 spa_config_tryenter(spa_t *spa, int locks, void *tag, krw_t rw)
287 {
288         for (int i = 0; i < SCL_LOCKS; i++) {
289                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
290                 if (!(locks & (1 << i)))
291                         continue;
292                 mutex_enter(&scl->scl_lock);
293                 if (rw == RW_READER) {
294                         if (scl->scl_writer || scl->scl_write_wanted) {
295                                 mutex_exit(&scl->scl_lock);
296                                 spa_config_exit(spa, locks ^ (1 << i), tag);
297                                 return (0);
298                         }
299                 } else {
300                         ASSERT(scl->scl_writer != curthread);
301                         if (!refcount_is_zero(&scl->scl_count)) {
302                                 mutex_exit(&scl->scl_lock);
303                                 spa_config_exit(spa, locks ^ (1 << i), tag);
304                                 return (0);
305                         }
306                         scl->scl_writer = curthread;
307                 }
308                 (void) refcount_add(&scl->scl_count, tag);
309                 mutex_exit(&scl->scl_lock);
310         }
311         return (1);
312 }
313
314 void
315 spa_config_enter(spa_t *spa, int locks, void *tag, krw_t rw)
316 {
317         int wlocks_held = 0;
318
319         for (int i = 0; i < SCL_LOCKS; i++) {
320                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
321                 if (scl->scl_writer == curthread)
322                         wlocks_held |= (1 << i);
323                 if (!(locks & (1 << i)))
324                         continue;
325                 mutex_enter(&scl->scl_lock);
326                 if (rw == RW_READER) {
327                         while (scl->scl_writer || scl->scl_write_wanted) {
328                                 cv_wait(&scl->scl_cv, &scl->scl_lock);
329                         }
330                 } else {
331                         ASSERT(scl->scl_writer != curthread);
332                         while (!refcount_is_zero(&scl->scl_count)) {
333                                 scl->scl_write_wanted++;
334                                 cv_wait(&scl->scl_cv, &scl->scl_lock);
335                                 scl->scl_write_wanted--;
336                         }
337                         scl->scl_writer = curthread;
338                 }
339                 (void) refcount_add(&scl->scl_count, tag);
340                 mutex_exit(&scl->scl_lock);
341         }
342         ASSERT(wlocks_held <= locks);
343 }
344
345 void
346 spa_config_exit(spa_t *spa, int locks, void *tag)
347 {
348         for (int i = SCL_LOCKS - 1; i >= 0; i--) {
349                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
350                 if (!(locks & (1 << i)))
351                         continue;
352                 mutex_enter(&scl->scl_lock);
353                 ASSERT(!refcount_is_zero(&scl->scl_count));
354                 if (refcount_remove(&scl->scl_count, tag) == 0) {
355                         ASSERT(scl->scl_writer == NULL ||
356                             scl->scl_writer == curthread);
357                         scl->scl_writer = NULL; /* OK in either case */
358                         cv_broadcast(&scl->scl_cv);
359                 }
360                 mutex_exit(&scl->scl_lock);
361         }
362 }
363
364 int
365 spa_config_held(spa_t *spa, int locks, krw_t rw)
366 {
367         int locks_held = 0;
368
369         for (int i = 0; i < SCL_LOCKS; i++) {
370                 spa_config_lock_t *scl = &spa->spa_config_lock[i];
371                 if (!(locks & (1 << i)))
372                         continue;
373                 if ((rw == RW_READER && !refcount_is_zero(&scl->scl_count)) ||
374                     (rw == RW_WRITER && scl->scl_writer == curthread))
375                         locks_held |= 1 << i;
376         }
377
378         return (locks_held);
379 }
380
381 /*
382  * ==========================================================================
383  * SPA namespace functions
384  * ==========================================================================
385  */
386
387 /*
388  * Lookup the named spa_t in the AVL tree.  The spa_namespace_lock must be held.
389  * Returns NULL if no matching spa_t is found.
390  */
391 spa_t *
392 spa_lookup(const char *name)
393 {
394         static spa_t search;    /* spa_t is large; don't allocate on stack */
395         spa_t *spa;
396         avl_index_t where;
397         char c;
398         char *cp;
399
400         ASSERT(MUTEX_HELD(&spa_namespace_lock));
401
402         /*
403          * If it's a full dataset name, figure out the pool name and
404          * just use that.
405          */
406         cp = strpbrk(name, "/@");
407         if (cp) {
408                 c = *cp;
409                 *cp = '\0';
410         }
411
412         (void) strlcpy(search.spa_name, name, sizeof (search.spa_name));
413         spa = avl_find(&spa_namespace_avl, &search, &where);
414
415         if (cp)
416                 *cp = c;
417
418         return (spa);
419 }
420
421 /*
422  * Create an uninitialized spa_t with the given name.  Requires
423  * spa_namespace_lock.  The caller must ensure that the spa_t doesn't already
424  * exist by calling spa_lookup() first.
425  */
426 spa_t *
427 spa_add(const char *name, nvlist_t *config, const char *altroot)
428 {
429         spa_t *spa;
430         spa_config_dirent_t *dp;
431
432         ASSERT(MUTEX_HELD(&spa_namespace_lock));
433
434         spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
435
436         mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
437         mutex_init(&spa->spa_errlist_lock, NULL, MUTEX_DEFAULT, NULL);
438         mutex_init(&spa->spa_errlog_lock, NULL, MUTEX_DEFAULT, NULL);
439         mutex_init(&spa->spa_history_lock, NULL, MUTEX_DEFAULT, NULL);
440         mutex_init(&spa->spa_proc_lock, NULL, MUTEX_DEFAULT, NULL);
441         mutex_init(&spa->spa_props_lock, NULL, MUTEX_DEFAULT, NULL);
442         mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
443         mutex_init(&spa->spa_suspend_lock, NULL, MUTEX_DEFAULT, NULL);
444         mutex_init(&spa->spa_vdev_top_lock, NULL, MUTEX_DEFAULT, NULL);
445
446         cv_init(&spa->spa_async_cv, NULL, CV_DEFAULT, NULL);
447         cv_init(&spa->spa_proc_cv, NULL, CV_DEFAULT, NULL);
448         cv_init(&spa->spa_scrub_io_cv, NULL, CV_DEFAULT, NULL);
449         cv_init(&spa->spa_suspend_cv, NULL, CV_DEFAULT, NULL);
450
451         for (int t = 0; t < TXG_SIZE; t++)
452                 bplist_create(&spa->spa_free_bplist[t]);
453
454         (void) strlcpy(spa->spa_name, name, sizeof (spa->spa_name));
455         spa->spa_state = POOL_STATE_UNINITIALIZED;
456         spa->spa_freeze_txg = UINT64_MAX;
457         spa->spa_final_txg = UINT64_MAX;
458         spa->spa_load_max_txg = UINT64_MAX;
459         spa->spa_proc = &p0;
460         spa->spa_proc_state = SPA_PROC_NONE;
461
462         refcount_create(&spa->spa_refcount);
463         spa_config_lock_init(spa);
464
465         avl_add(&spa_namespace_avl, spa);
466
467         /*
468          * Set the alternate root, if there is one.
469          */
470         if (altroot) {
471                 spa->spa_root = spa_strdup(altroot);
472                 spa_active_count++;
473         }
474
475         /*
476          * Every pool starts with the default cachefile
477          */
478         list_create(&spa->spa_config_list, sizeof (spa_config_dirent_t),
479             offsetof(spa_config_dirent_t, scd_link));
480
481         dp = kmem_zalloc(sizeof (spa_config_dirent_t), KM_SLEEP);
482         dp->scd_path = altroot ? NULL : spa_strdup(spa_config_path);
483         list_insert_head(&spa->spa_config_list, dp);
484
485         VERIFY(nvlist_alloc(&spa->spa_load_info, NV_UNIQUE_NAME,
486             KM_SLEEP) == 0);
487
488         if (config != NULL)
489                 VERIFY(nvlist_dup(config, &spa->spa_config, 0) == 0);
490
491         return (spa);
492 }
493
494 /*
495  * Removes a spa_t from the namespace, freeing up any memory used.  Requires
496  * spa_namespace_lock.  This is called only after the spa_t has been closed and
497  * deactivated.
498  */
499 void
500 spa_remove(spa_t *spa)
501 {
502         spa_config_dirent_t *dp;
503
504         ASSERT(MUTEX_HELD(&spa_namespace_lock));
505         ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
506
507         nvlist_free(spa->spa_config_splitting);
508
509         avl_remove(&spa_namespace_avl, spa);
510         cv_broadcast(&spa_namespace_cv);
511
512         if (spa->spa_root) {
513                 spa_strfree(spa->spa_root);
514                 spa_active_count--;
515         }
516
517         while ((dp = list_head(&spa->spa_config_list)) != NULL) {
518                 list_remove(&spa->spa_config_list, dp);
519                 if (dp->scd_path != NULL)
520                         spa_strfree(dp->scd_path);
521                 kmem_free(dp, sizeof (spa_config_dirent_t));
522         }
523
524         list_destroy(&spa->spa_config_list);
525
526         nvlist_free(spa->spa_load_info);
527         spa_config_set(spa, NULL);
528
529         refcount_destroy(&spa->spa_refcount);
530
531         spa_config_lock_destroy(spa);
532
533         for (int t = 0; t < TXG_SIZE; t++)
534                 bplist_destroy(&spa->spa_free_bplist[t]);
535
536         cv_destroy(&spa->spa_async_cv);
537         cv_destroy(&spa->spa_proc_cv);
538         cv_destroy(&spa->spa_scrub_io_cv);
539         cv_destroy(&spa->spa_suspend_cv);
540
541         mutex_destroy(&spa->spa_async_lock);
542         mutex_destroy(&spa->spa_errlist_lock);
543         mutex_destroy(&spa->spa_errlog_lock);
544         mutex_destroy(&spa->spa_history_lock);
545         mutex_destroy(&spa->spa_proc_lock);
546         mutex_destroy(&spa->spa_props_lock);
547         mutex_destroy(&spa->spa_scrub_lock);
548         mutex_destroy(&spa->spa_suspend_lock);
549         mutex_destroy(&spa->spa_vdev_top_lock);
550
551         kmem_free(spa, sizeof (spa_t));
552 }
553
554 /*
555  * Given a pool, return the next pool in the namespace, or NULL if there is
556  * none.  If 'prev' is NULL, return the first pool.
557  */
558 spa_t *
559 spa_next(spa_t *prev)
560 {
561         ASSERT(MUTEX_HELD(&spa_namespace_lock));
562
563         if (prev)
564                 return (AVL_NEXT(&spa_namespace_avl, prev));
565         else
566                 return (avl_first(&spa_namespace_avl));
567 }
568
569 /*
570  * ==========================================================================
571  * SPA refcount functions
572  * ==========================================================================
573  */
574
575 /*
576  * Add a reference to the given spa_t.  Must have at least one reference, or
577  * have the namespace lock held.
578  */
579 void
580 spa_open_ref(spa_t *spa, void *tag)
581 {
582         ASSERT(refcount_count(&spa->spa_refcount) >= spa->spa_minref ||
583             MUTEX_HELD(&spa_namespace_lock));
584         (void) refcount_add(&spa->spa_refcount, tag);
585 }
586
587 /*
588  * Remove a reference to the given spa_t.  Must have at least one reference, or
589  * have the namespace lock held.
590  */
591 void
592 spa_close(spa_t *spa, void *tag)
593 {
594         ASSERT(refcount_count(&spa->spa_refcount) > spa->spa_minref ||
595             MUTEX_HELD(&spa_namespace_lock));
596         (void) refcount_remove(&spa->spa_refcount, tag);
597 }
598
599 /*
600  * Check to see if the spa refcount is zero.  Must be called with
601  * spa_namespace_lock held.  We really compare against spa_minref, which is the
602  * number of references acquired when opening a pool
603  */
604 boolean_t
605 spa_refcount_zero(spa_t *spa)
606 {
607         ASSERT(MUTEX_HELD(&spa_namespace_lock));
608
609         return (refcount_count(&spa->spa_refcount) == spa->spa_minref);
610 }
611
612 /*
613  * ==========================================================================
614  * SPA spare and l2cache tracking
615  * ==========================================================================
616  */
617
618 /*
619  * Hot spares and cache devices are tracked using the same code below,
620  * for 'auxiliary' devices.
621  */
622
623 typedef struct spa_aux {
624         uint64_t        aux_guid;
625         uint64_t        aux_pool;
626         avl_node_t      aux_avl;
627         int             aux_count;
628 } spa_aux_t;
629
630 static int
631 spa_aux_compare(const void *a, const void *b)
632 {
633         const spa_aux_t *sa = a;
634         const spa_aux_t *sb = b;
635
636         if (sa->aux_guid < sb->aux_guid)
637                 return (-1);
638         else if (sa->aux_guid > sb->aux_guid)
639                 return (1);
640         else
641                 return (0);
642 }
643
644 void
645 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
646 {
647         avl_index_t where;
648         spa_aux_t search;
649         spa_aux_t *aux;
650
651         search.aux_guid = vd->vdev_guid;
652         if ((aux = avl_find(avl, &search, &where)) != NULL) {
653                 aux->aux_count++;
654         } else {
655                 aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
656                 aux->aux_guid = vd->vdev_guid;
657                 aux->aux_count = 1;
658                 avl_insert(avl, aux, where);
659         }
660 }
661
662 void
663 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
664 {
665         spa_aux_t search;
666         spa_aux_t *aux;
667         avl_index_t where;
668
669         search.aux_guid = vd->vdev_guid;
670         aux = avl_find(avl, &search, &where);
671
672         ASSERT(aux != NULL);
673
674         if (--aux->aux_count == 0) {
675                 avl_remove(avl, aux);
676                 kmem_free(aux, sizeof (spa_aux_t));
677         } else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
678                 aux->aux_pool = 0ULL;
679         }
680 }
681
682 boolean_t
683 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
684 {
685         spa_aux_t search, *found;
686
687         search.aux_guid = guid;
688         found = avl_find(avl, &search, NULL);
689
690         if (pool) {
691                 if (found)
692                         *pool = found->aux_pool;
693                 else
694                         *pool = 0ULL;
695         }
696
697         if (refcnt) {
698                 if (found)
699                         *refcnt = found->aux_count;
700                 else
701                         *refcnt = 0;
702         }
703
704         return (found != NULL);
705 }
706
707 void
708 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
709 {
710         spa_aux_t search, *found;
711         avl_index_t where;
712
713         search.aux_guid = vd->vdev_guid;
714         found = avl_find(avl, &search, &where);
715         ASSERT(found != NULL);
716         ASSERT(found->aux_pool == 0ULL);
717
718         found->aux_pool = spa_guid(vd->vdev_spa);
719 }
720
721 /*
722  * Spares are tracked globally due to the following constraints:
723  *
724  *      - A spare may be part of multiple pools.
725  *      - A spare may be added to a pool even if it's actively in use within
726  *        another pool.
727  *      - A spare in use in any pool can only be the source of a replacement if
728  *        the target is a spare in the same pool.
729  *
730  * We keep track of all spares on the system through the use of a reference
731  * counted AVL tree.  When a vdev is added as a spare, or used as a replacement
732  * spare, then we bump the reference count in the AVL tree.  In addition, we set
733  * the 'vdev_isspare' member to indicate that the device is a spare (active or
734  * inactive).  When a spare is made active (used to replace a device in the
735  * pool), we also keep track of which pool its been made a part of.
736  *
737  * The 'spa_spare_lock' protects the AVL tree.  These functions are normally
738  * called under the spa_namespace lock as part of vdev reconfiguration.  The
739  * separate spare lock exists for the status query path, which does not need to
740  * be completely consistent with respect to other vdev configuration changes.
741  */
742
743 static int
744 spa_spare_compare(const void *a, const void *b)
745 {
746         return (spa_aux_compare(a, b));
747 }
748
749 void
750 spa_spare_add(vdev_t *vd)
751 {
752         mutex_enter(&spa_spare_lock);
753         ASSERT(!vd->vdev_isspare);
754         spa_aux_add(vd, &spa_spare_avl);
755         vd->vdev_isspare = B_TRUE;
756         mutex_exit(&spa_spare_lock);
757 }
758
759 void
760 spa_spare_remove(vdev_t *vd)
761 {
762         mutex_enter(&spa_spare_lock);
763         ASSERT(vd->vdev_isspare);
764         spa_aux_remove(vd, &spa_spare_avl);
765         vd->vdev_isspare = B_FALSE;
766         mutex_exit(&spa_spare_lock);
767 }
768
769 boolean_t
770 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
771 {
772         boolean_t found;
773
774         mutex_enter(&spa_spare_lock);
775         found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
776         mutex_exit(&spa_spare_lock);
777
778         return (found);
779 }
780
781 void
782 spa_spare_activate(vdev_t *vd)
783 {
784         mutex_enter(&spa_spare_lock);
785         ASSERT(vd->vdev_isspare);
786         spa_aux_activate(vd, &spa_spare_avl);
787         mutex_exit(&spa_spare_lock);
788 }
789
790 /*
791  * Level 2 ARC devices are tracked globally for the same reasons as spares.
792  * Cache devices currently only support one pool per cache device, and so
793  * for these devices the aux reference count is currently unused beyond 1.
794  */
795
796 static int
797 spa_l2cache_compare(const void *a, const void *b)
798 {
799         return (spa_aux_compare(a, b));
800 }
801
802 void
803 spa_l2cache_add(vdev_t *vd)
804 {
805         mutex_enter(&spa_l2cache_lock);
806         ASSERT(!vd->vdev_isl2cache);
807         spa_aux_add(vd, &spa_l2cache_avl);
808         vd->vdev_isl2cache = B_TRUE;
809         mutex_exit(&spa_l2cache_lock);
810 }
811
812 void
813 spa_l2cache_remove(vdev_t *vd)
814 {
815         mutex_enter(&spa_l2cache_lock);
816         ASSERT(vd->vdev_isl2cache);
817         spa_aux_remove(vd, &spa_l2cache_avl);
818         vd->vdev_isl2cache = B_FALSE;
819         mutex_exit(&spa_l2cache_lock);
820 }
821
822 boolean_t
823 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
824 {
825         boolean_t found;
826
827         mutex_enter(&spa_l2cache_lock);
828         found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
829         mutex_exit(&spa_l2cache_lock);
830
831         return (found);
832 }
833
834 void
835 spa_l2cache_activate(vdev_t *vd)
836 {
837         mutex_enter(&spa_l2cache_lock);
838         ASSERT(vd->vdev_isl2cache);
839         spa_aux_activate(vd, &spa_l2cache_avl);
840         mutex_exit(&spa_l2cache_lock);
841 }
842
843 /*
844  * ==========================================================================
845  * SPA vdev locking
846  * ==========================================================================
847  */
848
849 /*
850  * Lock the given spa_t for the purpose of adding or removing a vdev.
851  * Grabs the global spa_namespace_lock plus the spa config lock for writing.
852  * It returns the next transaction group for the spa_t.
853  */
854 uint64_t
855 spa_vdev_enter(spa_t *spa)
856 {
857         mutex_enter(&spa->spa_vdev_top_lock);
858         mutex_enter(&spa_namespace_lock);
859         return (spa_vdev_config_enter(spa));
860 }
861
862 /*
863  * Internal implementation for spa_vdev_enter().  Used when a vdev
864  * operation requires multiple syncs (i.e. removing a device) while
865  * keeping the spa_namespace_lock held.
866  */
867 uint64_t
868 spa_vdev_config_enter(spa_t *spa)
869 {
870         ASSERT(MUTEX_HELD(&spa_namespace_lock));
871
872         spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
873
874         return (spa_last_synced_txg(spa) + 1);
875 }
876
877 /*
878  * Used in combination with spa_vdev_config_enter() to allow the syncing
879  * of multiple transactions without releasing the spa_namespace_lock.
880  */
881 void
882 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error, char *tag)
883 {
884         ASSERT(MUTEX_HELD(&spa_namespace_lock));
885
886         int config_changed = B_FALSE;
887
888         ASSERT(txg > spa_last_synced_txg(spa));
889
890         spa->spa_pending_vdev = NULL;
891
892         /*
893          * Reassess the DTLs.
894          */
895         vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE);
896
897         if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
898                 config_changed = B_TRUE;
899                 spa->spa_config_generation++;
900         }
901
902         /*
903          * Verify the metaslab classes.
904          */
905         ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
906         ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
907
908         spa_config_exit(spa, SCL_ALL, spa);
909
910         /*
911          * Panic the system if the specified tag requires it.  This
912          * is useful for ensuring that configurations are updated
913          * transactionally.
914          */
915         if (zio_injection_enabled)
916                 zio_handle_panic_injection(spa, tag, 0);
917
918         /*
919          * Note: this txg_wait_synced() is important because it ensures
920          * that there won't be more than one config change per txg.
921          * This allows us to use the txg as the generation number.
922          */
923         if (error == 0)
924                 txg_wait_synced(spa->spa_dsl_pool, txg);
925
926         if (vd != NULL) {
927                 ASSERT(!vd->vdev_detached || vd->vdev_dtl_smo.smo_object == 0);
928                 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
929                 vdev_free(vd);
930                 spa_config_exit(spa, SCL_ALL, spa);
931         }
932
933         /*
934          * If the config changed, update the config cache.
935          */
936         if (config_changed)
937                 spa_config_sync(spa, B_FALSE, B_TRUE);
938 }
939
940 /*
941  * Unlock the spa_t after adding or removing a vdev.  Besides undoing the
942  * locking of spa_vdev_enter(), we also want make sure the transactions have
943  * synced to disk, and then update the global configuration cache with the new
944  * information.
945  */
946 int
947 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
948 {
949         spa_vdev_config_exit(spa, vd, txg, error, FTAG);
950         mutex_exit(&spa_namespace_lock);
951         mutex_exit(&spa->spa_vdev_top_lock);
952
953         return (error);
954 }
955
956 /*
957  * Lock the given spa_t for the purpose of changing vdev state.
958  */
959 void
960 spa_vdev_state_enter(spa_t *spa, int oplocks)
961 {
962         int locks = SCL_STATE_ALL | oplocks;
963
964         /*
965          * Root pools may need to read of the underlying devfs filesystem
966          * when opening up a vdev.  Unfortunately if we're holding the
967          * SCL_ZIO lock it will result in a deadlock when we try to issue
968          * the read from the root filesystem.  Instead we "prefetch"
969          * the associated vnodes that we need prior to opening the
970          * underlying devices and cache them so that we can prevent
971          * any I/O when we are doing the actual open.
972          */
973         if (spa_is_root(spa)) {
974                 int low = locks & ~(SCL_ZIO - 1);
975                 int high = locks & ~low;
976
977                 spa_config_enter(spa, high, spa, RW_WRITER);
978                 vdev_hold(spa->spa_root_vdev);
979                 spa_config_enter(spa, low, spa, RW_WRITER);
980         } else {
981                 spa_config_enter(spa, locks, spa, RW_WRITER);
982         }
983         spa->spa_vdev_locks = locks;
984 }
985
986 int
987 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
988 {
989         boolean_t config_changed = B_FALSE;
990
991         if (vd != NULL || error == 0)
992                 vdev_dtl_reassess(vd ? vd->vdev_top : spa->spa_root_vdev,
993                     0, 0, B_FALSE);
994
995         if (vd != NULL) {
996                 vdev_state_dirty(vd->vdev_top);
997                 config_changed = B_TRUE;
998                 spa->spa_config_generation++;
999         }
1000
1001         if (spa_is_root(spa))
1002                 vdev_rele(spa->spa_root_vdev);
1003
1004         ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1005         spa_config_exit(spa, spa->spa_vdev_locks, spa);
1006
1007         /*
1008          * If anything changed, wait for it to sync.  This ensures that,
1009          * from the system administrator's perspective, zpool(1M) commands
1010          * are synchronous.  This is important for things like zpool offline:
1011          * when the command completes, you expect no further I/O from ZFS.
1012          */
1013         if (vd != NULL)
1014                 txg_wait_synced(spa->spa_dsl_pool, 0);
1015
1016         /*
1017          * If the config changed, update the config cache.
1018          */
1019         if (config_changed) {
1020                 mutex_enter(&spa_namespace_lock);
1021                 spa_config_sync(spa, B_FALSE, B_TRUE);
1022                 mutex_exit(&spa_namespace_lock);
1023         }
1024
1025         return (error);
1026 }
1027
1028 /*
1029  * ==========================================================================
1030  * Miscellaneous functions
1031  * ==========================================================================
1032  */
1033
1034 /*
1035  * Rename a spa_t.
1036  */
1037 int
1038 spa_rename(const char *name, const char *newname)
1039 {
1040         spa_t *spa;
1041         int err;
1042
1043         /*
1044          * Lookup the spa_t and grab the config lock for writing.  We need to
1045          * actually open the pool so that we can sync out the necessary labels.
1046          * It's OK to call spa_open() with the namespace lock held because we
1047          * allow recursive calls for other reasons.
1048          */
1049         mutex_enter(&spa_namespace_lock);
1050         if ((err = spa_open(name, &spa, FTAG)) != 0) {
1051                 mutex_exit(&spa_namespace_lock);
1052                 return (err);
1053         }
1054
1055         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1056
1057         avl_remove(&spa_namespace_avl, spa);
1058         (void) strlcpy(spa->spa_name, newname, sizeof (spa->spa_name));
1059         avl_add(&spa_namespace_avl, spa);
1060
1061         /*
1062          * Sync all labels to disk with the new names by marking the root vdev
1063          * dirty and waiting for it to sync.  It will pick up the new pool name
1064          * during the sync.
1065          */
1066         vdev_config_dirty(spa->spa_root_vdev);
1067
1068         spa_config_exit(spa, SCL_ALL, FTAG);
1069
1070         txg_wait_synced(spa->spa_dsl_pool, 0);
1071
1072         /*
1073          * Sync the updated config cache.
1074          */
1075         spa_config_sync(spa, B_FALSE, B_TRUE);
1076
1077         spa_close(spa, FTAG);
1078
1079         mutex_exit(&spa_namespace_lock);
1080
1081         return (0);
1082 }
1083
1084 /*
1085  * Return the spa_t associated with given pool_guid, if it exists.  If
1086  * device_guid is non-zero, determine whether the pool exists *and* contains
1087  * a device with the specified device_guid.
1088  */
1089 spa_t *
1090 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1091 {
1092         spa_t *spa;
1093         avl_tree_t *t = &spa_namespace_avl;
1094
1095         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1096
1097         for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1098                 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1099                         continue;
1100                 if (spa->spa_root_vdev == NULL)
1101                         continue;
1102                 if (spa_guid(spa) == pool_guid) {
1103                         if (device_guid == 0)
1104                                 break;
1105
1106                         if (vdev_lookup_by_guid(spa->spa_root_vdev,
1107                             device_guid) != NULL)
1108                                 break;
1109
1110                         /*
1111                          * Check any devices we may be in the process of adding.
1112                          */
1113                         if (spa->spa_pending_vdev) {
1114                                 if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1115                                     device_guid) != NULL)
1116                                         break;
1117                         }
1118                 }
1119         }
1120
1121         return (spa);
1122 }
1123
1124 /*
1125  * Determine whether a pool with the given pool_guid exists.
1126  */
1127 boolean_t
1128 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1129 {
1130         return (spa_by_guid(pool_guid, device_guid) != NULL);
1131 }
1132
1133 char *
1134 spa_strdup(const char *s)
1135 {
1136         size_t len;
1137         char *new;
1138
1139         len = strlen(s);
1140         new = kmem_alloc(len + 1, KM_SLEEP);
1141         bcopy(s, new, len);
1142         new[len] = '\0';
1143
1144         return (new);
1145 }
1146
1147 void
1148 spa_strfree(char *s)
1149 {
1150         kmem_free(s, strlen(s) + 1);
1151 }
1152
1153 uint64_t
1154 spa_get_random(uint64_t range)
1155 {
1156         uint64_t r;
1157
1158         ASSERT(range != 0);
1159
1160         (void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
1161
1162         return (r % range);
1163 }
1164
1165 uint64_t
1166 spa_generate_guid(spa_t *spa)
1167 {
1168         uint64_t guid = spa_get_random(-1ULL);
1169
1170         if (spa != NULL) {
1171                 while (guid == 0 || spa_guid_exists(spa_guid(spa), guid))
1172                         guid = spa_get_random(-1ULL);
1173         } else {
1174                 while (guid == 0 || spa_guid_exists(guid, 0))
1175                         guid = spa_get_random(-1ULL);
1176         }
1177
1178         return (guid);
1179 }
1180
1181 void
1182 sprintf_blkptr(char *buf, const blkptr_t *bp)
1183 {
1184         char *type = NULL;
1185         char *checksum = NULL;
1186         char *compress = NULL;
1187
1188         if (bp != NULL) {
1189                 type = dmu_ot[BP_GET_TYPE(bp)].ot_name;
1190                 checksum = zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1191                 compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1192         }
1193
1194         SPRINTF_BLKPTR(snprintf, ' ', buf, bp, type, checksum, compress);
1195 }
1196
1197 void
1198 spa_freeze(spa_t *spa)
1199 {
1200         uint64_t freeze_txg = 0;
1201
1202         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1203         if (spa->spa_freeze_txg == UINT64_MAX) {
1204                 freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1205                 spa->spa_freeze_txg = freeze_txg;
1206         }
1207         spa_config_exit(spa, SCL_ALL, FTAG);
1208         if (freeze_txg != 0)
1209                 txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1210 }
1211
1212 void
1213 zfs_panic_recover(const char *fmt, ...)
1214 {
1215         va_list adx;
1216
1217         va_start(adx, fmt);
1218         vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1219         va_end(adx);
1220 }
1221
1222 /*
1223  * This is a stripped-down version of strtoull, suitable only for converting
1224  * lowercase hexidecimal numbers that don't overflow.
1225  */
1226 uint64_t
1227 zfs_strtonum(const char *str, char **nptr)
1228 {
1229         uint64_t val = 0;
1230         char c;
1231         int digit;
1232
1233         while ((c = *str) != '\0') {
1234                 if (c >= '0' && c <= '9')
1235                         digit = c - '0';
1236                 else if (c >= 'a' && c <= 'f')
1237                         digit = 10 + c - 'a';
1238                 else
1239                         break;
1240
1241                 val *= 16;
1242                 val += digit;
1243
1244                 str++;
1245         }
1246
1247         if (nptr)
1248                 *nptr = (char *)str;
1249
1250         return (val);
1251 }
1252
1253 /*
1254  * ==========================================================================
1255  * Accessor functions
1256  * ==========================================================================
1257  */
1258
1259 boolean_t
1260 spa_shutting_down(spa_t *spa)
1261 {
1262         return (spa->spa_async_suspended);
1263 }
1264
1265 dsl_pool_t *
1266 spa_get_dsl(spa_t *spa)
1267 {
1268         return (spa->spa_dsl_pool);
1269 }
1270
1271 blkptr_t *
1272 spa_get_rootblkptr(spa_t *spa)
1273 {
1274         return (&spa->spa_ubsync.ub_rootbp);
1275 }
1276
1277 void
1278 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1279 {
1280         spa->spa_uberblock.ub_rootbp = *bp;
1281 }
1282
1283 void
1284 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1285 {
1286         if (spa->spa_root == NULL)
1287                 buf[0] = '\0';
1288         else
1289                 (void) strncpy(buf, spa->spa_root, buflen);
1290 }
1291
1292 int
1293 spa_sync_pass(spa_t *spa)
1294 {
1295         return (spa->spa_sync_pass);
1296 }
1297
1298 char *
1299 spa_name(spa_t *spa)
1300 {
1301         return (spa->spa_name);
1302 }
1303
1304 uint64_t
1305 spa_guid(spa_t *spa)
1306 {
1307         /*
1308          * If we fail to parse the config during spa_load(), we can go through
1309          * the error path (which posts an ereport) and end up here with no root
1310          * vdev.  We stash the original pool guid in 'spa_load_guid' to handle
1311          * this case.
1312          */
1313         if (spa->spa_root_vdev != NULL)
1314                 return (spa->spa_root_vdev->vdev_guid);
1315         else
1316                 return (spa->spa_load_guid);
1317 }
1318
1319 uint64_t
1320 spa_last_synced_txg(spa_t *spa)
1321 {
1322         return (spa->spa_ubsync.ub_txg);
1323 }
1324
1325 uint64_t
1326 spa_first_txg(spa_t *spa)
1327 {
1328         return (spa->spa_first_txg);
1329 }
1330
1331 uint64_t
1332 spa_syncing_txg(spa_t *spa)
1333 {
1334         return (spa->spa_syncing_txg);
1335 }
1336
1337 pool_state_t
1338 spa_state(spa_t *spa)
1339 {
1340         return (spa->spa_state);
1341 }
1342
1343 spa_load_state_t
1344 spa_load_state(spa_t *spa)
1345 {
1346         return (spa->spa_load_state);
1347 }
1348
1349 uint64_t
1350 spa_freeze_txg(spa_t *spa)
1351 {
1352         return (spa->spa_freeze_txg);
1353 }
1354
1355 /* ARGSUSED */
1356 uint64_t
1357 spa_get_asize(spa_t *spa, uint64_t lsize)
1358 {
1359         /*
1360          * The worst case is single-sector max-parity RAID-Z blocks, in which
1361          * case the space requirement is exactly (VDEV_RAIDZ_MAXPARITY + 1)
1362          * times the size; so just assume that.  Add to this the fact that
1363          * we can have up to 3 DVAs per bp, and one more factor of 2 because
1364          * the block may be dittoed with up to 3 DVAs by ddt_sync().
1365          */
1366         return (lsize * (VDEV_RAIDZ_MAXPARITY + 1) * SPA_DVAS_PER_BP * 2);
1367 }
1368
1369 uint64_t
1370 spa_get_dspace(spa_t *spa)
1371 {
1372         return (spa->spa_dspace);
1373 }
1374
1375 void
1376 spa_update_dspace(spa_t *spa)
1377 {
1378         spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1379             ddt_get_dedup_dspace(spa);
1380 }
1381
1382 /*
1383  * Return the failure mode that has been set to this pool. The default
1384  * behavior will be to block all I/Os when a complete failure occurs.
1385  */
1386 uint8_t
1387 spa_get_failmode(spa_t *spa)
1388 {
1389         return (spa->spa_failmode);
1390 }
1391
1392 boolean_t
1393 spa_suspended(spa_t *spa)
1394 {
1395         return (spa->spa_suspended);
1396 }
1397
1398 uint64_t
1399 spa_version(spa_t *spa)
1400 {
1401         return (spa->spa_ubsync.ub_version);
1402 }
1403
1404 boolean_t
1405 spa_deflate(spa_t *spa)
1406 {
1407         return (spa->spa_deflate);
1408 }
1409
1410 metaslab_class_t *
1411 spa_normal_class(spa_t *spa)
1412 {
1413         return (spa->spa_normal_class);
1414 }
1415
1416 metaslab_class_t *
1417 spa_log_class(spa_t *spa)
1418 {
1419         return (spa->spa_log_class);
1420 }
1421
1422 int
1423 spa_max_replication(spa_t *spa)
1424 {
1425         /*
1426          * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1427          * handle BPs with more than one DVA allocated.  Set our max
1428          * replication level accordingly.
1429          */
1430         if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1431                 return (1);
1432         return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1433 }
1434
1435 int
1436 spa_prev_software_version(spa_t *spa)
1437 {
1438         return (spa->spa_prev_software_version);
1439 }
1440
1441 uint64_t
1442 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
1443 {
1444         uint64_t asize = DVA_GET_ASIZE(dva);
1445         uint64_t dsize = asize;
1446
1447         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1448
1449         if (asize != 0 && spa->spa_deflate) {
1450                 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
1451                 dsize = (asize >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio;
1452         }
1453
1454         return (dsize);
1455 }
1456
1457 uint64_t
1458 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
1459 {
1460         uint64_t dsize = 0;
1461
1462         for (int d = 0; d < SPA_DVAS_PER_BP; d++)
1463                 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1464
1465         return (dsize);
1466 }
1467
1468 uint64_t
1469 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
1470 {
1471         uint64_t dsize = 0;
1472
1473         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1474
1475         for (int d = 0; d < SPA_DVAS_PER_BP; d++)
1476                 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1477
1478         spa_config_exit(spa, SCL_VDEV, FTAG);
1479
1480         return (dsize);
1481 }
1482
1483 /*
1484  * ==========================================================================
1485  * Initialization and Termination
1486  * ==========================================================================
1487  */
1488
1489 static int
1490 spa_name_compare(const void *a1, const void *a2)
1491 {
1492         const spa_t *s1 = a1;
1493         const spa_t *s2 = a2;
1494         int s;
1495
1496         s = strcmp(s1->spa_name, s2->spa_name);
1497         if (s > 0)
1498                 return (1);
1499         if (s < 0)
1500                 return (-1);
1501         return (0);
1502 }
1503
1504 int
1505 spa_busy(void)
1506 {
1507         return (spa_active_count);
1508 }
1509
1510 void
1511 spa_boot_init()
1512 {
1513         spa_config_load();
1514 }
1515
1516 void
1517 spa_init(int mode)
1518 {
1519         mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
1520         mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
1521         mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
1522         cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
1523
1524         avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
1525             offsetof(spa_t, spa_avl));
1526
1527         avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
1528             offsetof(spa_aux_t, aux_avl));
1529
1530         avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
1531             offsetof(spa_aux_t, aux_avl));
1532
1533         spa_mode_global = mode;
1534
1535         refcount_sysinit();
1536         unique_init();
1537         zio_init();
1538         dmu_init();
1539         zil_init();
1540         vdev_cache_stat_init();
1541         zfs_prop_init();
1542         zpool_prop_init();
1543         spa_config_load();
1544         l2arc_start();
1545 }
1546
1547 void
1548 spa_fini(void)
1549 {
1550         l2arc_stop();
1551
1552         spa_evict_all();
1553
1554         vdev_cache_stat_fini();
1555         zil_fini();
1556         dmu_fini();
1557         zio_fini();
1558         unique_fini();
1559         refcount_fini();
1560
1561         avl_destroy(&spa_namespace_avl);
1562         avl_destroy(&spa_spare_avl);
1563         avl_destroy(&spa_l2cache_avl);
1564
1565         cv_destroy(&spa_namespace_cv);
1566         mutex_destroy(&spa_namespace_lock);
1567         mutex_destroy(&spa_spare_lock);
1568         mutex_destroy(&spa_l2cache_lock);
1569 }
1570
1571 /*
1572  * Return whether this pool has slogs. No locking needed.
1573  * It's not a problem if the wrong answer is returned as it's only for
1574  * performance and not correctness
1575  */
1576 boolean_t
1577 spa_has_slogs(spa_t *spa)
1578 {
1579         return (spa->spa_log_class->mc_rotor != NULL);
1580 }
1581
1582 spa_log_state_t
1583 spa_get_log_state(spa_t *spa)
1584 {
1585         return (spa->spa_log_state);
1586 }
1587
1588 void
1589 spa_set_log_state(spa_t *spa, spa_log_state_t state)
1590 {
1591         spa->spa_log_state = state;
1592 }
1593
1594 boolean_t
1595 spa_is_root(spa_t *spa)
1596 {
1597         return (spa->spa_is_root);
1598 }
1599
1600 boolean_t
1601 spa_writeable(spa_t *spa)
1602 {
1603         return (!!(spa->spa_mode & FWRITE));
1604 }
1605
1606 int
1607 spa_mode(spa_t *spa)
1608 {
1609         return (spa->spa_mode);
1610 }
1611
1612 uint64_t
1613 spa_bootfs(spa_t *spa)
1614 {
1615         return (spa->spa_bootfs);
1616 }
1617
1618 uint64_t
1619 spa_delegation(spa_t *spa)
1620 {
1621         return (spa->spa_delegation);
1622 }
1623
1624 objset_t *
1625 spa_meta_objset(spa_t *spa)
1626 {
1627         return (spa->spa_meta_objset);
1628 }
1629
1630 enum zio_checksum
1631 spa_dedup_checksum(spa_t *spa)
1632 {
1633         return (spa->spa_dedup_checksum);
1634 }
1635
1636 /*
1637  * Reset pool scan stat per scan pass (or reboot).
1638  */
1639 void
1640 spa_scan_stat_init(spa_t *spa)
1641 {
1642         /* data not stored on disk */
1643         spa->spa_scan_pass_start = gethrestime_sec();
1644         spa->spa_scan_pass_exam = 0;
1645         vdev_scan_stat_init(spa->spa_root_vdev);
1646 }
1647
1648 /*
1649  * Get scan stats for zpool status reports
1650  */
1651 int
1652 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
1653 {
1654         dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
1655
1656         if (scn == NULL || scn->scn_phys.scn_func == POOL_SCAN_NONE)
1657                 return (ENOENT);
1658         bzero(ps, sizeof (pool_scan_stat_t));
1659
1660         /* data stored on disk */
1661         ps->pss_func = scn->scn_phys.scn_func;
1662         ps->pss_start_time = scn->scn_phys.scn_start_time;
1663         ps->pss_end_time = scn->scn_phys.scn_end_time;
1664         ps->pss_to_examine = scn->scn_phys.scn_to_examine;
1665         ps->pss_examined = scn->scn_phys.scn_examined;
1666         ps->pss_to_process = scn->scn_phys.scn_to_process;
1667         ps->pss_processed = scn->scn_phys.scn_processed;
1668         ps->pss_errors = scn->scn_phys.scn_errors;
1669         ps->pss_state = scn->scn_phys.scn_state;
1670
1671         /* data not stored on disk */
1672         ps->pss_pass_start = spa->spa_scan_pass_start;
1673         ps->pss_pass_exam = spa->spa_scan_pass_exam;
1674
1675         return (0);
1676 }