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