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