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