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