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