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