]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_misc.c
MFC r259813 + r259816: MFV r258374:
[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         if (!nvlist_exists(spa->spa_label_features, feature)) {
1199                 fnvlist_add_boolean(spa->spa_label_features, feature);
1200                 vdev_config_dirty(spa->spa_root_vdev);
1201         }
1202 }
1203
1204 void
1205 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1206 {
1207         if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1208                 vdev_config_dirty(spa->spa_root_vdev);
1209 }
1210
1211 /*
1212  * Rename a spa_t.
1213  */
1214 int
1215 spa_rename(const char *name, const char *newname)
1216 {
1217         spa_t *spa;
1218         int err;
1219
1220         /*
1221          * Lookup the spa_t and grab the config lock for writing.  We need to
1222          * actually open the pool so that we can sync out the necessary labels.
1223          * It's OK to call spa_open() with the namespace lock held because we
1224          * allow recursive calls for other reasons.
1225          */
1226         mutex_enter(&spa_namespace_lock);
1227         if ((err = spa_open(name, &spa, FTAG)) != 0) {
1228                 mutex_exit(&spa_namespace_lock);
1229                 return (err);
1230         }
1231
1232         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1233
1234         avl_remove(&spa_namespace_avl, spa);
1235         (void) strlcpy(spa->spa_name, newname, sizeof (spa->spa_name));
1236         avl_add(&spa_namespace_avl, spa);
1237
1238         /*
1239          * Sync all labels to disk with the new names by marking the root vdev
1240          * dirty and waiting for it to sync.  It will pick up the new pool name
1241          * during the sync.
1242          */
1243         vdev_config_dirty(spa->spa_root_vdev);
1244
1245         spa_config_exit(spa, SCL_ALL, FTAG);
1246
1247         txg_wait_synced(spa->spa_dsl_pool, 0);
1248
1249         /*
1250          * Sync the updated config cache.
1251          */
1252         spa_config_sync(spa, B_FALSE, B_TRUE);
1253
1254         spa_close(spa, FTAG);
1255
1256         mutex_exit(&spa_namespace_lock);
1257
1258         return (0);
1259 }
1260
1261 /*
1262  * Return the spa_t associated with given pool_guid, if it exists.  If
1263  * device_guid is non-zero, determine whether the pool exists *and* contains
1264  * a device with the specified device_guid.
1265  */
1266 spa_t *
1267 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1268 {
1269         spa_t *spa;
1270         avl_tree_t *t = &spa_namespace_avl;
1271
1272         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1273
1274         for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1275                 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1276                         continue;
1277                 if (spa->spa_root_vdev == NULL)
1278                         continue;
1279                 if (spa_guid(spa) == pool_guid) {
1280                         if (device_guid == 0)
1281                                 break;
1282
1283                         if (vdev_lookup_by_guid(spa->spa_root_vdev,
1284                             device_guid) != NULL)
1285                                 break;
1286
1287                         /*
1288                          * Check any devices we may be in the process of adding.
1289                          */
1290                         if (spa->spa_pending_vdev) {
1291                                 if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1292                                     device_guid) != NULL)
1293                                         break;
1294                         }
1295                 }
1296         }
1297
1298         return (spa);
1299 }
1300
1301 /*
1302  * Determine whether a pool with the given pool_guid exists.
1303  */
1304 boolean_t
1305 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1306 {
1307         return (spa_by_guid(pool_guid, device_guid) != NULL);
1308 }
1309
1310 char *
1311 spa_strdup(const char *s)
1312 {
1313         size_t len;
1314         char *new;
1315
1316         len = strlen(s);
1317         new = kmem_alloc(len + 1, KM_SLEEP);
1318         bcopy(s, new, len);
1319         new[len] = '\0';
1320
1321         return (new);
1322 }
1323
1324 void
1325 spa_strfree(char *s)
1326 {
1327         kmem_free(s, strlen(s) + 1);
1328 }
1329
1330 uint64_t
1331 spa_get_random(uint64_t range)
1332 {
1333         uint64_t r;
1334
1335         ASSERT(range != 0);
1336
1337         (void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
1338
1339         return (r % range);
1340 }
1341
1342 uint64_t
1343 spa_generate_guid(spa_t *spa)
1344 {
1345         uint64_t guid = spa_get_random(-1ULL);
1346
1347         if (spa != NULL) {
1348                 while (guid == 0 || spa_guid_exists(spa_guid(spa), guid))
1349                         guid = spa_get_random(-1ULL);
1350         } else {
1351                 while (guid == 0 || spa_guid_exists(guid, 0))
1352                         guid = spa_get_random(-1ULL);
1353         }
1354
1355         return (guid);
1356 }
1357
1358 void
1359 sprintf_blkptr(char *buf, const blkptr_t *bp)
1360 {
1361         char type[256];
1362         char *checksum = NULL;
1363         char *compress = NULL;
1364
1365         if (bp != NULL) {
1366                 if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1367                         dmu_object_byteswap_t bswap =
1368                             DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1369                         (void) snprintf(type, sizeof (type), "bswap %s %s",
1370                             DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1371                             "metadata" : "data",
1372                             dmu_ot_byteswap[bswap].ob_name);
1373                 } else {
1374                         (void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1375                             sizeof (type));
1376                 }
1377                 checksum = zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1378                 compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1379         }
1380
1381         SPRINTF_BLKPTR(snprintf, ' ', buf, bp, type, checksum, compress);
1382 }
1383
1384 void
1385 spa_freeze(spa_t *spa)
1386 {
1387         uint64_t freeze_txg = 0;
1388
1389         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1390         if (spa->spa_freeze_txg == UINT64_MAX) {
1391                 freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1392                 spa->spa_freeze_txg = freeze_txg;
1393         }
1394         spa_config_exit(spa, SCL_ALL, FTAG);
1395         if (freeze_txg != 0)
1396                 txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1397 }
1398
1399 void
1400 zfs_panic_recover(const char *fmt, ...)
1401 {
1402         va_list adx;
1403
1404         va_start(adx, fmt);
1405         vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1406         va_end(adx);
1407 }
1408
1409 /*
1410  * This is a stripped-down version of strtoull, suitable only for converting
1411  * lowercase hexadecimal numbers that don't overflow.
1412  */
1413 uint64_t
1414 zfs_strtonum(const char *str, char **nptr)
1415 {
1416         uint64_t val = 0;
1417         char c;
1418         int digit;
1419
1420         while ((c = *str) != '\0') {
1421                 if (c >= '0' && c <= '9')
1422                         digit = c - '0';
1423                 else if (c >= 'a' && c <= 'f')
1424                         digit = 10 + c - 'a';
1425                 else
1426                         break;
1427
1428                 val *= 16;
1429                 val += digit;
1430
1431                 str++;
1432         }
1433
1434         if (nptr)
1435                 *nptr = (char *)str;
1436
1437         return (val);
1438 }
1439
1440 /*
1441  * ==========================================================================
1442  * Accessor functions
1443  * ==========================================================================
1444  */
1445
1446 boolean_t
1447 spa_shutting_down(spa_t *spa)
1448 {
1449         return (spa->spa_async_suspended);
1450 }
1451
1452 dsl_pool_t *
1453 spa_get_dsl(spa_t *spa)
1454 {
1455         return (spa->spa_dsl_pool);
1456 }
1457
1458 boolean_t
1459 spa_is_initializing(spa_t *spa)
1460 {
1461         return (spa->spa_is_initializing);
1462 }
1463
1464 blkptr_t *
1465 spa_get_rootblkptr(spa_t *spa)
1466 {
1467         return (&spa->spa_ubsync.ub_rootbp);
1468 }
1469
1470 void
1471 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1472 {
1473         spa->spa_uberblock.ub_rootbp = *bp;
1474 }
1475
1476 void
1477 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1478 {
1479         if (spa->spa_root == NULL)
1480                 buf[0] = '\0';
1481         else
1482                 (void) strncpy(buf, spa->spa_root, buflen);
1483 }
1484
1485 int
1486 spa_sync_pass(spa_t *spa)
1487 {
1488         return (spa->spa_sync_pass);
1489 }
1490
1491 char *
1492 spa_name(spa_t *spa)
1493 {
1494         return (spa->spa_name);
1495 }
1496
1497 uint64_t
1498 spa_guid(spa_t *spa)
1499 {
1500         dsl_pool_t *dp = spa_get_dsl(spa);
1501         uint64_t guid;
1502
1503         /*
1504          * If we fail to parse the config during spa_load(), we can go through
1505          * the error path (which posts an ereport) and end up here with no root
1506          * vdev.  We stash the original pool guid in 'spa_config_guid' to handle
1507          * this case.
1508          */
1509         if (spa->spa_root_vdev == NULL)
1510                 return (spa->spa_config_guid);
1511
1512         guid = spa->spa_last_synced_guid != 0 ?
1513             spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1514
1515         /*
1516          * Return the most recently synced out guid unless we're
1517          * in syncing context.
1518          */
1519         if (dp && dsl_pool_sync_context(dp))
1520                 return (spa->spa_root_vdev->vdev_guid);
1521         else
1522                 return (guid);
1523 }
1524
1525 uint64_t
1526 spa_load_guid(spa_t *spa)
1527 {
1528         /*
1529          * This is a GUID that exists solely as a reference for the
1530          * purposes of the arc.  It is generated at load time, and
1531          * is never written to persistent storage.
1532          */
1533         return (spa->spa_load_guid);
1534 }
1535
1536 uint64_t
1537 spa_last_synced_txg(spa_t *spa)
1538 {
1539         return (spa->spa_ubsync.ub_txg);
1540 }
1541
1542 uint64_t
1543 spa_first_txg(spa_t *spa)
1544 {
1545         return (spa->spa_first_txg);
1546 }
1547
1548 uint64_t
1549 spa_syncing_txg(spa_t *spa)
1550 {
1551         return (spa->spa_syncing_txg);
1552 }
1553
1554 pool_state_t
1555 spa_state(spa_t *spa)
1556 {
1557         return (spa->spa_state);
1558 }
1559
1560 spa_load_state_t
1561 spa_load_state(spa_t *spa)
1562 {
1563         return (spa->spa_load_state);
1564 }
1565
1566 uint64_t
1567 spa_freeze_txg(spa_t *spa)
1568 {
1569         return (spa->spa_freeze_txg);
1570 }
1571
1572 /* ARGSUSED */
1573 uint64_t
1574 spa_get_asize(spa_t *spa, uint64_t lsize)
1575 {
1576         return (lsize * spa_asize_inflation);
1577 }
1578
1579 uint64_t
1580 spa_get_dspace(spa_t *spa)
1581 {
1582         return (spa->spa_dspace);
1583 }
1584
1585 void
1586 spa_update_dspace(spa_t *spa)
1587 {
1588         spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1589             ddt_get_dedup_dspace(spa);
1590 }
1591
1592 /*
1593  * Return the failure mode that has been set to this pool. The default
1594  * behavior will be to block all I/Os when a complete failure occurs.
1595  */
1596 uint8_t
1597 spa_get_failmode(spa_t *spa)
1598 {
1599         return (spa->spa_failmode);
1600 }
1601
1602 boolean_t
1603 spa_suspended(spa_t *spa)
1604 {
1605         return (spa->spa_suspended);
1606 }
1607
1608 uint64_t
1609 spa_version(spa_t *spa)
1610 {
1611         return (spa->spa_ubsync.ub_version);
1612 }
1613
1614 boolean_t
1615 spa_deflate(spa_t *spa)
1616 {
1617         return (spa->spa_deflate);
1618 }
1619
1620 metaslab_class_t *
1621 spa_normal_class(spa_t *spa)
1622 {
1623         return (spa->spa_normal_class);
1624 }
1625
1626 metaslab_class_t *
1627 spa_log_class(spa_t *spa)
1628 {
1629         return (spa->spa_log_class);
1630 }
1631
1632 int
1633 spa_max_replication(spa_t *spa)
1634 {
1635         /*
1636          * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1637          * handle BPs with more than one DVA allocated.  Set our max
1638          * replication level accordingly.
1639          */
1640         if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1641                 return (1);
1642         return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1643 }
1644
1645 int
1646 spa_prev_software_version(spa_t *spa)
1647 {
1648         return (spa->spa_prev_software_version);
1649 }
1650
1651 uint64_t
1652 spa_deadman_synctime(spa_t *spa)
1653 {
1654         return (spa->spa_deadman_synctime);
1655 }
1656
1657 uint64_t
1658 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
1659 {
1660         uint64_t asize = DVA_GET_ASIZE(dva);
1661         uint64_t dsize = asize;
1662
1663         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1664
1665         if (asize != 0 && spa->spa_deflate) {
1666                 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
1667                 dsize = (asize >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio;
1668         }
1669
1670         return (dsize);
1671 }
1672
1673 uint64_t
1674 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
1675 {
1676         uint64_t dsize = 0;
1677
1678         for (int d = 0; d < SPA_DVAS_PER_BP; d++)
1679                 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1680
1681         return (dsize);
1682 }
1683
1684 uint64_t
1685 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
1686 {
1687         uint64_t dsize = 0;
1688
1689         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1690
1691         for (int d = 0; d < SPA_DVAS_PER_BP; d++)
1692                 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1693
1694         spa_config_exit(spa, SCL_VDEV, FTAG);
1695
1696         return (dsize);
1697 }
1698
1699 /*
1700  * ==========================================================================
1701  * Initialization and Termination
1702  * ==========================================================================
1703  */
1704
1705 static int
1706 spa_name_compare(const void *a1, const void *a2)
1707 {
1708         const spa_t *s1 = a1;
1709         const spa_t *s2 = a2;
1710         int s;
1711
1712         s = strcmp(s1->spa_name, s2->spa_name);
1713         if (s > 0)
1714                 return (1);
1715         if (s < 0)
1716                 return (-1);
1717         return (0);
1718 }
1719
1720 int
1721 spa_busy(void)
1722 {
1723         return (spa_active_count);
1724 }
1725
1726 void
1727 spa_boot_init()
1728 {
1729         spa_config_load();
1730 }
1731
1732 #ifdef _KERNEL
1733 EVENTHANDLER_DEFINE(mountroot, spa_boot_init, NULL, 0);
1734 #endif
1735
1736 void
1737 spa_init(int mode)
1738 {
1739         mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
1740         mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
1741         mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
1742         cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
1743
1744         avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
1745             offsetof(spa_t, spa_avl));
1746
1747         avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
1748             offsetof(spa_aux_t, aux_avl));
1749
1750         avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
1751             offsetof(spa_aux_t, aux_avl));
1752
1753         spa_mode_global = mode;
1754
1755 #ifdef illumos
1756 #ifdef _KERNEL
1757         spa_arch_init();
1758 #else
1759         if (spa_mode_global != FREAD && dprintf_find_string("watch")) {
1760                 arc_procfd = open("/proc/self/ctl", O_WRONLY);
1761                 if (arc_procfd == -1) {
1762                         perror("could not enable watchpoints: "
1763                             "opening /proc/self/ctl failed: ");
1764                 } else {
1765                         arc_watch = B_TRUE;
1766                 }
1767         }
1768 #endif
1769 #endif /* illumos */
1770         refcount_sysinit();
1771         unique_init();
1772         range_tree_init();
1773         zio_init();
1774         lz4_init();
1775         dmu_init();
1776         zil_init();
1777         vdev_cache_stat_init();
1778         zfs_prop_init();
1779         zpool_prop_init();
1780         zpool_feature_init();
1781         spa_config_load();
1782         l2arc_start();
1783 #ifndef illumos
1784 #ifdef _KERNEL
1785         zfs_deadman_init();
1786 #endif
1787 #endif  /* !illumos */
1788 }
1789
1790 void
1791 spa_fini(void)
1792 {
1793         l2arc_stop();
1794
1795         spa_evict_all();
1796
1797         vdev_cache_stat_fini();
1798         zil_fini();
1799         dmu_fini();
1800         lz4_fini();
1801         zio_fini();
1802         range_tree_fini();
1803         unique_fini();
1804         refcount_fini();
1805
1806         avl_destroy(&spa_namespace_avl);
1807         avl_destroy(&spa_spare_avl);
1808         avl_destroy(&spa_l2cache_avl);
1809
1810         cv_destroy(&spa_namespace_cv);
1811         mutex_destroy(&spa_namespace_lock);
1812         mutex_destroy(&spa_spare_lock);
1813         mutex_destroy(&spa_l2cache_lock);
1814 }
1815
1816 /*
1817  * Return whether this pool has slogs. No locking needed.
1818  * It's not a problem if the wrong answer is returned as it's only for
1819  * performance and not correctness
1820  */
1821 boolean_t
1822 spa_has_slogs(spa_t *spa)
1823 {
1824         return (spa->spa_log_class->mc_rotor != NULL);
1825 }
1826
1827 spa_log_state_t
1828 spa_get_log_state(spa_t *spa)
1829 {
1830         return (spa->spa_log_state);
1831 }
1832
1833 void
1834 spa_set_log_state(spa_t *spa, spa_log_state_t state)
1835 {
1836         spa->spa_log_state = state;
1837 }
1838
1839 boolean_t
1840 spa_is_root(spa_t *spa)
1841 {
1842         return (spa->spa_is_root);
1843 }
1844
1845 boolean_t
1846 spa_writeable(spa_t *spa)
1847 {
1848         return (!!(spa->spa_mode & FWRITE));
1849 }
1850
1851 int
1852 spa_mode(spa_t *spa)
1853 {
1854         return (spa->spa_mode);
1855 }
1856
1857 uint64_t
1858 spa_bootfs(spa_t *spa)
1859 {
1860         return (spa->spa_bootfs);
1861 }
1862
1863 uint64_t
1864 spa_delegation(spa_t *spa)
1865 {
1866         return (spa->spa_delegation);
1867 }
1868
1869 objset_t *
1870 spa_meta_objset(spa_t *spa)
1871 {
1872         return (spa->spa_meta_objset);
1873 }
1874
1875 enum zio_checksum
1876 spa_dedup_checksum(spa_t *spa)
1877 {
1878         return (spa->spa_dedup_checksum);
1879 }
1880
1881 /*
1882  * Reset pool scan stat per scan pass (or reboot).
1883  */
1884 void
1885 spa_scan_stat_init(spa_t *spa)
1886 {
1887         /* data not stored on disk */
1888         spa->spa_scan_pass_start = gethrestime_sec();
1889         spa->spa_scan_pass_exam = 0;
1890         vdev_scan_stat_init(spa->spa_root_vdev);
1891 }
1892
1893 /*
1894  * Get scan stats for zpool status reports
1895  */
1896 int
1897 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
1898 {
1899         dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
1900
1901         if (scn == NULL || scn->scn_phys.scn_func == POOL_SCAN_NONE)
1902                 return (SET_ERROR(ENOENT));
1903         bzero(ps, sizeof (pool_scan_stat_t));
1904
1905         /* data stored on disk */
1906         ps->pss_func = scn->scn_phys.scn_func;
1907         ps->pss_start_time = scn->scn_phys.scn_start_time;
1908         ps->pss_end_time = scn->scn_phys.scn_end_time;
1909         ps->pss_to_examine = scn->scn_phys.scn_to_examine;
1910         ps->pss_examined = scn->scn_phys.scn_examined;
1911         ps->pss_to_process = scn->scn_phys.scn_to_process;
1912         ps->pss_processed = scn->scn_phys.scn_processed;
1913         ps->pss_errors = scn->scn_phys.scn_errors;
1914         ps->pss_state = scn->scn_phys.scn_state;
1915
1916         /* data not stored on disk */
1917         ps->pss_pass_start = spa->spa_scan_pass_start;
1918         ps->pss_pass_exam = spa->spa_scan_pass_exam;
1919
1920         return (0);
1921 }
1922
1923 boolean_t
1924 spa_debug_enabled(spa_t *spa)
1925 {
1926         return (spa->spa_debug);
1927 }