]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_misc.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.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 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25
26 #pragma ident   "%Z%%M% %I%     %E% SMI"
27
28 #include <sys/zfs_context.h>
29 #include <sys/spa_impl.h>
30 #include <sys/zio.h>
31 #include <sys/zio_checksum.h>
32 #include <sys/zio_compress.h>
33 #include <sys/dmu.h>
34 #include <sys/dmu_tx.h>
35 #include <sys/zap.h>
36 #include <sys/zil.h>
37 #include <sys/vdev_impl.h>
38 #include <sys/metaslab.h>
39 #include <sys/uberblock_impl.h>
40 #include <sys/txg.h>
41 #include <sys/avl.h>
42 #include <sys/unique.h>
43 #include <sys/dsl_pool.h>
44 #include <sys/dsl_dir.h>
45 #include <sys/dsl_prop.h>
46 #include <sys/fs/zfs.h>
47
48 /*
49  * SPA locking
50  *
51  * There are four basic locks for managing spa_t structures:
52  *
53  * spa_namespace_lock (global mutex)
54  *
55  *      This lock must be acquired to do any of the following:
56  *
57  *              - Lookup a spa_t by name
58  *              - Add or remove a spa_t from the namespace
59  *              - Increase spa_refcount from non-zero
60  *              - Check if spa_refcount is zero
61  *              - Rename a spa_t
62  *              - add/remove/attach/detach devices
63  *              - Held for the duration of create/destroy/import/export
64  *
65  *      It does not need to handle recursion.  A create or destroy may
66  *      reference objects (files or zvols) in other pools, but by
67  *      definition they must have an existing reference, and will never need
68  *      to lookup a spa_t by name.
69  *
70  * spa_refcount (per-spa refcount_t protected by mutex)
71  *
72  *      This reference count keep track of any active users of the spa_t.  The
73  *      spa_t cannot be destroyed or freed while this is non-zero.  Internally,
74  *      the refcount is never really 'zero' - opening a pool implicitly keeps
75  *      some references in the DMU.  Internally we check against SPA_MINREF, but
76  *      present the image of a zero/non-zero value to consumers.
77  *
78  * spa_config_lock (per-spa crazy rwlock)
79  *
80  *      This SPA special is a recursive rwlock, capable of being acquired from
81  *      asynchronous threads.  It has protects the spa_t from config changes,
82  *      and must be held in the following circumstances:
83  *
84  *              - RW_READER to perform I/O to the spa
85  *              - RW_WRITER to change the vdev config
86  *
87  * spa_config_cache_lock (per-spa mutex)
88  *
89  *      This mutex prevents the spa_config nvlist from being updated.  No
90  *      other locks are required to obtain this lock, although implicitly you
91  *      must have the namespace lock or non-zero refcount to have any kind
92  *      of spa_t pointer at all.
93  *
94  * The locking order is fairly straightforward:
95  *
96  *              spa_namespace_lock      ->      spa_refcount
97  *
98  *      The namespace lock must be acquired to increase the refcount from 0
99  *      or to check if it is zero.
100  *
101  *              spa_refcount            ->      spa_config_lock
102  *
103  *      There must be at least one valid reference on the spa_t to acquire
104  *      the config lock.
105  *
106  *              spa_namespace_lock      ->      spa_config_lock
107  *
108  *      The namespace lock must always be taken before the config lock.
109  *
110  *
111  * The spa_namespace_lock and spa_config_cache_lock can be acquired directly and
112  * are globally visible.
113  *
114  * The namespace is manipulated using the following functions, all which require
115  * the spa_namespace_lock to be held.
116  *
117  *      spa_lookup()            Lookup a spa_t by name.
118  *
119  *      spa_add()               Create a new spa_t in the namespace.
120  *
121  *      spa_remove()            Remove a spa_t from the namespace.  This also
122  *                              frees up any memory associated with the spa_t.
123  *
124  *      spa_next()              Returns the next spa_t in the system, or the
125  *                              first if NULL is passed.
126  *
127  *      spa_evict_all()         Shutdown and remove all spa_t structures in
128  *                              the system.
129  *
130  *      spa_guid_exists()       Determine whether a pool/device guid exists.
131  *
132  * The spa_refcount is manipulated using the following functions:
133  *
134  *      spa_open_ref()          Adds a reference to the given spa_t.  Must be
135  *                              called with spa_namespace_lock held if the
136  *                              refcount is currently zero.
137  *
138  *      spa_close()             Remove a reference from the spa_t.  This will
139  *                              not free the spa_t or remove it from the
140  *                              namespace.  No locking is required.
141  *
142  *      spa_refcount_zero()     Returns true if the refcount is currently
143  *                              zero.  Must be called with spa_namespace_lock
144  *                              held.
145  *
146  * The spa_config_lock is manipulated using the following functions:
147  *
148  *      spa_config_enter()      Acquire the config lock as RW_READER or
149  *                              RW_WRITER.  At least one reference on the spa_t
150  *                              must exist.
151  *
152  *      spa_config_exit()       Release the config lock.
153  *
154  *      spa_config_held()       Returns true if the config lock is currently
155  *                              held in the given state.
156  *
157  * The vdev configuration is protected by spa_vdev_enter() / spa_vdev_exit().
158  *
159  *      spa_vdev_enter()        Acquire the namespace lock and the config lock
160  *                              for writing.
161  *
162  *      spa_vdev_exit()         Release the config lock, wait for all I/O
163  *                              to complete, sync the updated configs to the
164  *                              cache, and release the namespace lock.
165  *
166  * The spa_name() function also requires either the spa_namespace_lock
167  * or the spa_config_lock, as both are needed to do a rename.  spa_rename() is
168  * also implemented within this file since is requires manipulation of the
169  * namespace.
170  */
171
172 static avl_tree_t spa_namespace_avl;
173 kmutex_t spa_namespace_lock;
174 static kcondvar_t spa_namespace_cv;
175 static int spa_active_count;
176 int spa_max_replication_override = SPA_DVAS_PER_BP;
177
178 static kmutex_t spa_spare_lock;
179 static avl_tree_t spa_spare_avl;
180
181 kmem_cache_t *spa_buffer_pool;
182 int spa_mode;
183
184 #ifdef ZFS_DEBUG
185 int zfs_flags = ~0;
186 #else
187 int zfs_flags = 0;
188 #endif
189
190 /*
191  * zfs_recover can be set to nonzero to attempt to recover from
192  * otherwise-fatal errors, typically caused by on-disk corruption.  When
193  * set, calls to zfs_panic_recover() will turn into warning messages.
194  */
195 int zfs_recover = 0;
196 SYSCTL_DECL(_vfs_zfs);
197 TUNABLE_INT("vfs.zfs.recover", &zfs_recover);
198 SYSCTL_INT(_vfs_zfs, OID_AUTO, recover, CTLFLAG_RDTUN, &zfs_recover, 0,
199     "Try to recover from otherwise-fatal errors.");
200
201 #define SPA_MINREF      5       /* spa_refcnt for an open-but-idle pool */
202
203 /*
204  * ==========================================================================
205  * SPA namespace functions
206  * ==========================================================================
207  */
208
209 /*
210  * Lookup the named spa_t in the AVL tree.  The spa_namespace_lock must be held.
211  * Returns NULL if no matching spa_t is found.
212  */
213 spa_t *
214 spa_lookup(const char *name)
215 {
216         spa_t search, *spa;
217         avl_index_t where;
218
219         ASSERT(MUTEX_HELD(&spa_namespace_lock));
220
221         search.spa_name = (char *)name;
222         spa = avl_find(&spa_namespace_avl, &search, &where);
223
224         return (spa);
225 }
226
227 /*
228  * Create an uninitialized spa_t with the given name.  Requires
229  * spa_namespace_lock.  The caller must ensure that the spa_t doesn't already
230  * exist by calling spa_lookup() first.
231  */
232 spa_t *
233 spa_add(const char *name, const char *altroot)
234 {
235         spa_t *spa;
236
237         ASSERT(MUTEX_HELD(&spa_namespace_lock));
238
239         spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
240
241         spa->spa_name = spa_strdup(name);
242         spa->spa_state = POOL_STATE_UNINITIALIZED;
243         spa->spa_freeze_txg = UINT64_MAX;
244         spa->spa_final_txg = UINT64_MAX;
245
246         mutex_init(&spa->spa_config_cache_lock, NULL, MUTEX_DEFAULT, NULL);
247         mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
248         mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
249
250         cv_init(&spa->spa_scrub_cv, NULL, CV_DEFAULT, NULL);
251         cv_init(&spa->spa_scrub_io_cv, NULL, CV_DEFAULT, NULL);
252         cv_init(&spa->spa_async_cv, NULL, CV_DEFAULT, NULL);
253
254         refcount_create(&spa->spa_refcount);
255         refcount_create(&spa->spa_config_lock.scl_count);
256
257         avl_add(&spa_namespace_avl, spa);
258
259         /*
260          * Set the alternate root, if there is one.
261          */
262         if (altroot) {
263                 spa->spa_root = spa_strdup(altroot);
264                 spa_active_count++;
265         }
266
267         return (spa);
268 }
269
270 /*
271  * Removes a spa_t from the namespace, freeing up any memory used.  Requires
272  * spa_namespace_lock.  This is called only after the spa_t has been closed and
273  * deactivated.
274  */
275 void
276 spa_remove(spa_t *spa)
277 {
278         ASSERT(MUTEX_HELD(&spa_namespace_lock));
279         ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
280         ASSERT(spa->spa_scrub_thread == NULL);
281
282         avl_remove(&spa_namespace_avl, spa);
283         cv_broadcast(&spa_namespace_cv);
284
285         if (spa->spa_root) {
286                 spa_strfree(spa->spa_root);
287                 spa_active_count--;
288         }
289
290         if (spa->spa_name)
291                 spa_strfree(spa->spa_name);
292
293         spa_config_set(spa, NULL);
294
295         refcount_destroy(&spa->spa_refcount);
296         refcount_destroy(&spa->spa_config_lock.scl_count);
297
298         cv_destroy(&spa->spa_async_cv);
299         cv_destroy(&spa->spa_scrub_io_cv);
300         cv_destroy(&spa->spa_scrub_cv);
301
302         mutex_destroy(&spa->spa_scrub_lock);
303         mutex_destroy(&spa->spa_async_lock);
304         mutex_destroy(&spa->spa_config_cache_lock);
305
306         kmem_free(spa, sizeof (spa_t));
307 }
308
309 /*
310  * Given a pool, return the next pool in the namespace, or NULL if there is
311  * none.  If 'prev' is NULL, return the first pool.
312  */
313 spa_t *
314 spa_next(spa_t *prev)
315 {
316         ASSERT(MUTEX_HELD(&spa_namespace_lock));
317
318         if (prev)
319                 return (AVL_NEXT(&spa_namespace_avl, prev));
320         else
321                 return (avl_first(&spa_namespace_avl));
322 }
323
324 /*
325  * ==========================================================================
326  * SPA refcount functions
327  * ==========================================================================
328  */
329
330 /*
331  * Add a reference to the given spa_t.  Must have at least one reference, or
332  * have the namespace lock held.
333  */
334 void
335 spa_open_ref(spa_t *spa, void *tag)
336 {
337         ASSERT(refcount_count(&spa->spa_refcount) > SPA_MINREF ||
338             MUTEX_HELD(&spa_namespace_lock));
339
340         (void) refcount_add(&spa->spa_refcount, tag);
341 }
342
343 /*
344  * Remove a reference to the given spa_t.  Must have at least one reference, or
345  * have the namespace lock held.
346  */
347 void
348 spa_close(spa_t *spa, void *tag)
349 {
350         ASSERT(refcount_count(&spa->spa_refcount) > SPA_MINREF ||
351             MUTEX_HELD(&spa_namespace_lock));
352
353         (void) refcount_remove(&spa->spa_refcount, tag);
354 }
355
356 /*
357  * Check to see if the spa refcount is zero.  Must be called with
358  * spa_namespace_lock held.  We really compare against SPA_MINREF, which is the
359  * number of references acquired when opening a pool
360  */
361 boolean_t
362 spa_refcount_zero(spa_t *spa)
363 {
364         ASSERT(MUTEX_HELD(&spa_namespace_lock));
365
366         return (refcount_count(&spa->spa_refcount) == SPA_MINREF);
367 }
368
369 /*
370  * ==========================================================================
371  * SPA spare tracking
372  * ==========================================================================
373  */
374
375 /*
376  * Spares are tracked globally due to the following constraints:
377  *
378  *      - A spare may be part of multiple pools.
379  *      - A spare may be added to a pool even if it's actively in use within
380  *        another pool.
381  *      - A spare in use in any pool can only be the source of a replacement if
382  *        the target is a spare in the same pool.
383  *
384  * We keep track of all spares on the system through the use of a reference
385  * counted AVL tree.  When a vdev is added as a spare, or used as a replacement
386  * spare, then we bump the reference count in the AVL tree.  In addition, we set
387  * the 'vdev_isspare' member to indicate that the device is a spare (active or
388  * inactive).  When a spare is made active (used to replace a device in the
389  * pool), we also keep track of which pool its been made a part of.
390  *
391  * The 'spa_spare_lock' protects the AVL tree.  These functions are normally
392  * called under the spa_namespace lock as part of vdev reconfiguration.  The
393  * separate spare lock exists for the status query path, which does not need to
394  * be completely consistent with respect to other vdev configuration changes.
395  */
396
397 typedef struct spa_spare {
398         uint64_t        spare_guid;
399         uint64_t        spare_pool;
400         avl_node_t      spare_avl;
401         int             spare_count;
402 } spa_spare_t;
403
404 static int
405 spa_spare_compare(const void *a, const void *b)
406 {
407         const spa_spare_t *sa = a;
408         const spa_spare_t *sb = b;
409
410         if (sa->spare_guid < sb->spare_guid)
411                 return (-1);
412         else if (sa->spare_guid > sb->spare_guid)
413                 return (1);
414         else
415                 return (0);
416 }
417
418 void
419 spa_spare_add(vdev_t *vd)
420 {
421         avl_index_t where;
422         spa_spare_t search;
423         spa_spare_t *spare;
424
425         mutex_enter(&spa_spare_lock);
426         ASSERT(!vd->vdev_isspare);
427
428         search.spare_guid = vd->vdev_guid;
429         if ((spare = avl_find(&spa_spare_avl, &search, &where)) != NULL) {
430                 spare->spare_count++;
431         } else {
432                 spare = kmem_zalloc(sizeof (spa_spare_t), KM_SLEEP);
433                 spare->spare_guid = vd->vdev_guid;
434                 spare->spare_count = 1;
435                 avl_insert(&spa_spare_avl, spare, where);
436         }
437         vd->vdev_isspare = B_TRUE;
438
439         mutex_exit(&spa_spare_lock);
440 }
441
442 void
443 spa_spare_remove(vdev_t *vd)
444 {
445         spa_spare_t search;
446         spa_spare_t *spare;
447         avl_index_t where;
448
449         mutex_enter(&spa_spare_lock);
450
451         search.spare_guid = vd->vdev_guid;
452         spare = avl_find(&spa_spare_avl, &search, &where);
453
454         ASSERT(vd->vdev_isspare);
455         ASSERT(spare != NULL);
456
457         if (--spare->spare_count == 0) {
458                 avl_remove(&spa_spare_avl, spare);
459                 kmem_free(spare, sizeof (spa_spare_t));
460         } else if (spare->spare_pool == spa_guid(vd->vdev_spa)) {
461                 spare->spare_pool = 0ULL;
462         }
463
464         vd->vdev_isspare = B_FALSE;
465         mutex_exit(&spa_spare_lock);
466 }
467
468 boolean_t
469 spa_spare_exists(uint64_t guid, uint64_t *pool)
470 {
471         spa_spare_t search, *found;
472         avl_index_t where;
473
474         mutex_enter(&spa_spare_lock);
475
476         search.spare_guid = guid;
477         found = avl_find(&spa_spare_avl, &search, &where);
478
479         if (pool) {
480                 if (found)
481                         *pool = found->spare_pool;
482                 else
483                         *pool = 0ULL;
484         }
485
486         mutex_exit(&spa_spare_lock);
487
488         return (found != NULL);
489 }
490
491 void
492 spa_spare_activate(vdev_t *vd)
493 {
494         spa_spare_t search, *found;
495         avl_index_t where;
496
497         mutex_enter(&spa_spare_lock);
498         ASSERT(vd->vdev_isspare);
499
500         search.spare_guid = vd->vdev_guid;
501         found = avl_find(&spa_spare_avl, &search, &where);
502         ASSERT(found != NULL);
503         ASSERT(found->spare_pool == 0ULL);
504
505         found->spare_pool = spa_guid(vd->vdev_spa);
506         mutex_exit(&spa_spare_lock);
507 }
508
509 /*
510  * ==========================================================================
511  * SPA config locking
512  * ==========================================================================
513  */
514
515 /*
516  * Acquire the config lock.  The config lock is a special rwlock that allows for
517  * recursive enters.  Because these enters come from the same thread as well as
518  * asynchronous threads working on behalf of the owner, we must unilaterally
519  * allow all reads access as long at least one reader is held (even if a write
520  * is requested).  This has the side effect of write starvation, but write locks
521  * are extremely rare, and a solution to this problem would be significantly
522  * more complex (if even possible).
523  *
524  * We would like to assert that the namespace lock isn't held, but this is a
525  * valid use during create.
526  */
527 void
528 spa_config_enter(spa_t *spa, krw_t rw, void *tag)
529 {
530         spa_config_lock_t *scl = &spa->spa_config_lock;
531
532         mutex_enter(&scl->scl_lock);
533
534         if (scl->scl_writer != curthread) {
535                 if (rw == RW_READER) {
536                         while (scl->scl_writer != NULL)
537                                 cv_wait(&scl->scl_cv, &scl->scl_lock);
538                 } else {
539                         while (scl->scl_writer != NULL ||
540                             !refcount_is_zero(&scl->scl_count))
541                                 cv_wait(&scl->scl_cv, &scl->scl_lock);
542                         scl->scl_writer = curthread;
543                 }
544         }
545
546         (void) refcount_add(&scl->scl_count, tag);
547
548         mutex_exit(&scl->scl_lock);
549 }
550
551 /*
552  * Release the spa config lock, notifying any waiters in the process.
553  */
554 void
555 spa_config_exit(spa_t *spa, void *tag)
556 {
557         spa_config_lock_t *scl = &spa->spa_config_lock;
558
559         mutex_enter(&scl->scl_lock);
560
561         ASSERT(!refcount_is_zero(&scl->scl_count));
562         if (refcount_remove(&scl->scl_count, tag) == 0) {
563                 cv_broadcast(&scl->scl_cv);
564                 scl->scl_writer = NULL;  /* OK in either case */
565         }
566
567         mutex_exit(&scl->scl_lock);
568 }
569
570 /*
571  * Returns true if the config lock is held in the given manner.
572  */
573 boolean_t
574 spa_config_held(spa_t *spa, krw_t rw)
575 {
576         spa_config_lock_t *scl = &spa->spa_config_lock;
577         boolean_t held;
578
579         mutex_enter(&scl->scl_lock);
580         if (rw == RW_WRITER)
581                 held = (scl->scl_writer == curthread);
582         else
583                 held = !refcount_is_zero(&scl->scl_count);
584         mutex_exit(&scl->scl_lock);
585
586         return (held);
587 }
588
589 /*
590  * ==========================================================================
591  * SPA vdev locking
592  * ==========================================================================
593  */
594
595 /*
596  * Lock the given spa_t for the purpose of adding or removing a vdev.
597  * Grabs the global spa_namespace_lock plus the spa config lock for writing.
598  * It returns the next transaction group for the spa_t.
599  */
600 uint64_t
601 spa_vdev_enter(spa_t *spa)
602 {
603         /*
604          * Suspend scrub activity while we mess with the config.
605          */
606         spa_scrub_suspend(spa);
607
608         mutex_enter(&spa_namespace_lock);
609
610         spa_config_enter(spa, RW_WRITER, spa);
611
612         return (spa_last_synced_txg(spa) + 1);
613 }
614
615 /*
616  * Unlock the spa_t after adding or removing a vdev.  Besides undoing the
617  * locking of spa_vdev_enter(), we also want make sure the transactions have
618  * synced to disk, and then update the global configuration cache with the new
619  * information.
620  */
621 int
622 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
623 {
624         int config_changed = B_FALSE;
625
626         ASSERT(txg > spa_last_synced_txg(spa));
627
628         /*
629          * Reassess the DTLs.
630          */
631         vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE);
632
633         /*
634          * If the config changed, notify the scrub thread that it must restart.
635          */
636         if (error == 0 && !list_is_empty(&spa->spa_dirty_list)) {
637                 config_changed = B_TRUE;
638                 spa_scrub_restart(spa, txg);
639         }
640
641         spa_config_exit(spa, spa);
642
643         /*
644          * Allow scrubbing to resume.
645          */
646         spa_scrub_resume(spa);
647
648         /*
649          * Note: this txg_wait_synced() is important because it ensures
650          * that there won't be more than one config change per txg.
651          * This allows us to use the txg as the generation number.
652          */
653         if (error == 0)
654                 txg_wait_synced(spa->spa_dsl_pool, txg);
655
656         if (vd != NULL) {
657                 ASSERT(!vd->vdev_detached || vd->vdev_dtl.smo_object == 0);
658                 vdev_free(vd);
659         }
660
661         /*
662          * If the config changed, update the config cache.
663          */
664         if (config_changed)
665                 spa_config_sync();
666
667         mutex_exit(&spa_namespace_lock);
668
669         return (error);
670 }
671
672 /*
673  * ==========================================================================
674  * Miscellaneous functions
675  * ==========================================================================
676  */
677
678 /*
679  * Rename a spa_t.
680  */
681 int
682 spa_rename(const char *name, const char *newname)
683 {
684         spa_t *spa;
685         int err;
686
687         /*
688          * Lookup the spa_t and grab the config lock for writing.  We need to
689          * actually open the pool so that we can sync out the necessary labels.
690          * It's OK to call spa_open() with the namespace lock held because we
691          * allow recursive calls for other reasons.
692          */
693         mutex_enter(&spa_namespace_lock);
694         if ((err = spa_open(name, &spa, FTAG)) != 0) {
695                 mutex_exit(&spa_namespace_lock);
696                 return (err);
697         }
698
699         spa_config_enter(spa, RW_WRITER, FTAG);
700
701         avl_remove(&spa_namespace_avl, spa);
702         spa_strfree(spa->spa_name);
703         spa->spa_name = spa_strdup(newname);
704         avl_add(&spa_namespace_avl, spa);
705
706         /*
707          * Sync all labels to disk with the new names by marking the root vdev
708          * dirty and waiting for it to sync.  It will pick up the new pool name
709          * during the sync.
710          */
711         vdev_config_dirty(spa->spa_root_vdev);
712
713         spa_config_exit(spa, FTAG);
714
715         txg_wait_synced(spa->spa_dsl_pool, 0);
716
717         /*
718          * Sync the updated config cache.
719          */
720         spa_config_sync();
721
722         spa_close(spa, FTAG);
723
724         mutex_exit(&spa_namespace_lock);
725
726         return (0);
727 }
728
729
730 /*
731  * Determine whether a pool with given pool_guid exists.  If device_guid is
732  * non-zero, determine whether the pool exists *and* contains a device with the
733  * specified device_guid.
734  */
735 boolean_t
736 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
737 {
738         spa_t *spa;
739         avl_tree_t *t = &spa_namespace_avl;
740
741         ASSERT(MUTEX_HELD(&spa_namespace_lock));
742
743         for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
744                 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
745                         continue;
746                 if (spa->spa_root_vdev == NULL)
747                         continue;
748                 if (spa_guid(spa) == pool_guid) {
749                         if (device_guid == 0)
750                                 break;
751
752                         if (vdev_lookup_by_guid(spa->spa_root_vdev,
753                             device_guid) != NULL)
754                                 break;
755
756                         /*
757                          * Check any devices we may in the process of adding.
758                          */
759                         if (spa->spa_pending_vdev) {
760                                 if (vdev_lookup_by_guid(spa->spa_pending_vdev,
761                                     device_guid) != NULL)
762                                         break;
763                         }
764                 }
765         }
766
767         return (spa != NULL);
768 }
769
770 char *
771 spa_strdup(const char *s)
772 {
773         size_t len;
774         char *new;
775
776         len = strlen(s);
777         new = kmem_alloc(len + 1, KM_SLEEP);
778         bcopy(s, new, len);
779         new[len] = '\0';
780
781         return (new);
782 }
783
784 void
785 spa_strfree(char *s)
786 {
787         kmem_free(s, strlen(s) + 1);
788 }
789
790 uint64_t
791 spa_get_random(uint64_t range)
792 {
793         uint64_t r;
794
795         ASSERT(range != 0);
796
797         (void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
798
799         return (r % range);
800 }
801
802 void
803 sprintf_blkptr(char *buf, int len, const blkptr_t *bp)
804 {
805         int d;
806
807         if (bp == NULL) {
808                 (void) snprintf(buf, len, "<NULL>");
809                 return;
810         }
811
812         if (BP_IS_HOLE(bp)) {
813                 (void) snprintf(buf, len, "<hole>");
814                 return;
815         }
816
817         (void) snprintf(buf, len, "[L%llu %s] %llxL/%llxP ",
818             (u_longlong_t)BP_GET_LEVEL(bp),
819             dmu_ot[BP_GET_TYPE(bp)].ot_name,
820             (u_longlong_t)BP_GET_LSIZE(bp),
821             (u_longlong_t)BP_GET_PSIZE(bp));
822
823         for (d = 0; d < BP_GET_NDVAS(bp); d++) {
824                 const dva_t *dva = &bp->blk_dva[d];
825                 (void) snprintf(buf + strlen(buf), len - strlen(buf),
826                     "DVA[%d]=<%llu:%llx:%llx> ", d,
827                     (u_longlong_t)DVA_GET_VDEV(dva),
828                     (u_longlong_t)DVA_GET_OFFSET(dva),
829                     (u_longlong_t)DVA_GET_ASIZE(dva));
830         }
831
832         (void) snprintf(buf + strlen(buf), len - strlen(buf),
833             "%s %s %s %s birth=%llu fill=%llu cksum=%llx:%llx:%llx:%llx",
834             zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
835             zio_compress_table[BP_GET_COMPRESS(bp)].ci_name,
836             BP_GET_BYTEORDER(bp) == 0 ? "BE" : "LE",
837             BP_IS_GANG(bp) ? "gang" : "contiguous",
838             (u_longlong_t)bp->blk_birth,
839             (u_longlong_t)bp->blk_fill,
840             (u_longlong_t)bp->blk_cksum.zc_word[0],
841             (u_longlong_t)bp->blk_cksum.zc_word[1],
842             (u_longlong_t)bp->blk_cksum.zc_word[2],
843             (u_longlong_t)bp->blk_cksum.zc_word[3]);
844 }
845
846 void
847 spa_freeze(spa_t *spa)
848 {
849         uint64_t freeze_txg = 0;
850
851         spa_config_enter(spa, RW_WRITER, FTAG);
852         if (spa->spa_freeze_txg == UINT64_MAX) {
853                 freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
854                 spa->spa_freeze_txg = freeze_txg;
855         }
856         spa_config_exit(spa, FTAG);
857         if (freeze_txg != 0)
858                 txg_wait_synced(spa_get_dsl(spa), freeze_txg);
859 }
860
861 void
862 zfs_panic_recover(const char *fmt, ...)
863 {
864         va_list adx;
865
866         va_start(adx, fmt);
867         vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
868         va_end(adx);
869 }
870
871 /*
872  * ==========================================================================
873  * Accessor functions
874  * ==========================================================================
875  */
876
877 krwlock_t *
878 spa_traverse_rwlock(spa_t *spa)
879 {
880         return (&spa->spa_traverse_lock);
881 }
882
883 int
884 spa_traverse_wanted(spa_t *spa)
885 {
886         return (spa->spa_traverse_wanted);
887 }
888
889 dsl_pool_t *
890 spa_get_dsl(spa_t *spa)
891 {
892         return (spa->spa_dsl_pool);
893 }
894
895 blkptr_t *
896 spa_get_rootblkptr(spa_t *spa)
897 {
898         return (&spa->spa_ubsync.ub_rootbp);
899 }
900
901 void
902 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
903 {
904         spa->spa_uberblock.ub_rootbp = *bp;
905 }
906
907 void
908 spa_altroot(spa_t *spa, char *buf, size_t buflen)
909 {
910         if (spa->spa_root == NULL)
911                 buf[0] = '\0';
912         else
913                 (void) strncpy(buf, spa->spa_root, buflen);
914 }
915
916 int
917 spa_sync_pass(spa_t *spa)
918 {
919         return (spa->spa_sync_pass);
920 }
921
922 char *
923 spa_name(spa_t *spa)
924 {
925         /*
926          * Accessing the name requires holding either the namespace lock or the
927          * config lock, both of which are required to do a rename.
928          */
929         ASSERT(MUTEX_HELD(&spa_namespace_lock) ||
930             spa_config_held(spa, RW_READER) || spa_config_held(spa, RW_WRITER));
931
932         return (spa->spa_name);
933 }
934
935 uint64_t
936 spa_guid(spa_t *spa)
937 {
938         /*
939          * If we fail to parse the config during spa_load(), we can go through
940          * the error path (which posts an ereport) and end up here with no root
941          * vdev.  We stash the original pool guid in 'spa_load_guid' to handle
942          * this case.
943          */
944         if (spa->spa_root_vdev != NULL)
945                 return (spa->spa_root_vdev->vdev_guid);
946         else
947                 return (spa->spa_load_guid);
948 }
949
950 uint64_t
951 spa_last_synced_txg(spa_t *spa)
952 {
953         return (spa->spa_ubsync.ub_txg);
954 }
955
956 uint64_t
957 spa_first_txg(spa_t *spa)
958 {
959         return (spa->spa_first_txg);
960 }
961
962 int
963 spa_state(spa_t *spa)
964 {
965         return (spa->spa_state);
966 }
967
968 uint64_t
969 spa_freeze_txg(spa_t *spa)
970 {
971         return (spa->spa_freeze_txg);
972 }
973
974 /*
975  * In the future, this may select among different metaslab classes
976  * depending on the zdp.  For now, there's no such distinction.
977  */
978 metaslab_class_t *
979 spa_metaslab_class_select(spa_t *spa)
980 {
981         return (spa->spa_normal_class);
982 }
983
984 /*
985  * Return how much space is allocated in the pool (ie. sum of all asize)
986  */
987 uint64_t
988 spa_get_alloc(spa_t *spa)
989 {
990         return (spa->spa_root_vdev->vdev_stat.vs_alloc);
991 }
992
993 /*
994  * Return how much (raid-z inflated) space there is in the pool.
995  */
996 uint64_t
997 spa_get_space(spa_t *spa)
998 {
999         return (spa->spa_root_vdev->vdev_stat.vs_space);
1000 }
1001
1002 /*
1003  * Return the amount of raid-z-deflated space in the pool.
1004  */
1005 uint64_t
1006 spa_get_dspace(spa_t *spa)
1007 {
1008         if (spa->spa_deflate)
1009                 return (spa->spa_root_vdev->vdev_stat.vs_dspace);
1010         else
1011                 return (spa->spa_root_vdev->vdev_stat.vs_space);
1012 }
1013
1014 /* ARGSUSED */
1015 uint64_t
1016 spa_get_asize(spa_t *spa, uint64_t lsize)
1017 {
1018         /*
1019          * For now, the worst case is 512-byte RAID-Z blocks, in which
1020          * case the space requirement is exactly 2x; so just assume that.
1021          * Add to this the fact that we can have up to 3 DVAs per bp, and
1022          * we have to multiply by a total of 6x.
1023          */
1024         return (lsize * 6);
1025 }
1026
1027 uint64_t
1028 spa_version(spa_t *spa)
1029 {
1030         return (spa->spa_ubsync.ub_version);
1031 }
1032
1033 int
1034 spa_max_replication(spa_t *spa)
1035 {
1036         /*
1037          * As of ZFS_VERSION == ZFS_VERSION_DITTO_BLOCKS, we are able to
1038          * handle BPs with more than one DVA allocated.  Set our max
1039          * replication level accordingly.
1040          */
1041         if (spa_version(spa) < ZFS_VERSION_DITTO_BLOCKS)
1042                 return (1);
1043         return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1044 }
1045
1046 uint64_t
1047 bp_get_dasize(spa_t *spa, const blkptr_t *bp)
1048 {
1049         int sz = 0, i;
1050
1051         if (!spa->spa_deflate)
1052                 return (BP_GET_ASIZE(bp));
1053
1054         for (i = 0; i < SPA_DVAS_PER_BP; i++) {
1055                 vdev_t *vd =
1056                     vdev_lookup_top(spa, DVA_GET_VDEV(&bp->blk_dva[i]));
1057                 sz += (DVA_GET_ASIZE(&bp->blk_dva[i]) >> SPA_MINBLOCKSHIFT) *
1058                     vd->vdev_deflate_ratio;
1059         }
1060         return (sz);
1061 }
1062
1063 /*
1064  * ==========================================================================
1065  * Initialization and Termination
1066  * ==========================================================================
1067  */
1068
1069 static int
1070 spa_name_compare(const void *a1, const void *a2)
1071 {
1072         const spa_t *s1 = a1;
1073         const spa_t *s2 = a2;
1074         int s;
1075
1076         s = strcmp(s1->spa_name, s2->spa_name);
1077         if (s > 0)
1078                 return (1);
1079         if (s < 0)
1080                 return (-1);
1081         return (0);
1082 }
1083
1084 int
1085 spa_busy(void)
1086 {
1087         return (spa_active_count);
1088 }
1089
1090 void
1091 spa_init(int mode)
1092 {
1093         mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
1094         cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
1095
1096         avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
1097             offsetof(spa_t, spa_avl));
1098
1099         mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
1100
1101         avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_spare_t),
1102             offsetof(spa_spare_t, spare_avl));
1103
1104         spa_mode = mode;
1105
1106         refcount_sysinit();
1107         unique_init();
1108         zio_init();
1109         dmu_init();
1110         zil_init();
1111         spa_config_load();
1112 }
1113
1114 void
1115 spa_fini(void)
1116 {
1117         spa_evict_all();
1118
1119         zil_fini();
1120         dmu_fini();
1121         zio_fini();
1122         refcount_fini();
1123
1124         avl_destroy(&spa_namespace_avl);
1125         avl_destroy(&spa_spare_avl);
1126
1127         cv_destroy(&spa_namespace_cv);
1128         mutex_destroy(&spa_namespace_lock);
1129         mutex_destroy(&spa_spare_lock);
1130 }