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