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