]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_misc.c
MFC r260183:
[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         /*
640          * As a pool is being created, treat all features as disabled by
641          * setting SPA_FEATURE_DISABLED for all entries in the feature
642          * refcount cache.
643          */
644         for (int i = 0; i < SPA_FEATURES; i++) {
645                 spa->spa_feat_refcount_cache[i] = SPA_FEATURE_DISABLED;
646         }
647
648         return (spa);
649 }
650
651 /*
652  * Removes a spa_t from the namespace, freeing up any memory used.  Requires
653  * spa_namespace_lock.  This is called only after the spa_t has been closed and
654  * deactivated.
655  */
656 void
657 spa_remove(spa_t *spa)
658 {
659         spa_config_dirent_t *dp;
660
661         ASSERT(MUTEX_HELD(&spa_namespace_lock));
662         ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
663
664         nvlist_free(spa->spa_config_splitting);
665
666         avl_remove(&spa_namespace_avl, spa);
667         cv_broadcast(&spa_namespace_cv);
668
669         if (spa->spa_root) {
670                 spa_strfree(spa->spa_root);
671                 spa_active_count--;
672         }
673
674         while ((dp = list_head(&spa->spa_config_list)) != NULL) {
675                 list_remove(&spa->spa_config_list, dp);
676                 if (dp->scd_path != NULL)
677                         spa_strfree(dp->scd_path);
678                 kmem_free(dp, sizeof (spa_config_dirent_t));
679         }
680
681         list_destroy(&spa->spa_config_list);
682
683         nvlist_free(spa->spa_label_features);
684         nvlist_free(spa->spa_load_info);
685         spa_config_set(spa, NULL);
686
687 #ifdef illumos
688         mutex_enter(&cpu_lock);
689         if (spa->spa_deadman_cycid != CYCLIC_NONE)
690                 cyclic_remove(spa->spa_deadman_cycid);
691         mutex_exit(&cpu_lock);
692         spa->spa_deadman_cycid = CYCLIC_NONE;
693 #else   /* !illumos */
694 #ifdef _KERNEL
695         callout_drain(&spa->spa_deadman_cycid);
696 #endif
697 #endif
698
699         refcount_destroy(&spa->spa_refcount);
700
701         spa_config_lock_destroy(spa);
702
703         for (int t = 0; t < TXG_SIZE; t++)
704                 bplist_destroy(&spa->spa_free_bplist[t]);
705
706         cv_destroy(&spa->spa_async_cv);
707         cv_destroy(&spa->spa_proc_cv);
708         cv_destroy(&spa->spa_scrub_io_cv);
709         cv_destroy(&spa->spa_suspend_cv);
710
711         mutex_destroy(&spa->spa_async_lock);
712         mutex_destroy(&spa->spa_errlist_lock);
713         mutex_destroy(&spa->spa_errlog_lock);
714         mutex_destroy(&spa->spa_history_lock);
715         mutex_destroy(&spa->spa_proc_lock);
716         mutex_destroy(&spa->spa_props_lock);
717         mutex_destroy(&spa->spa_scrub_lock);
718         mutex_destroy(&spa->spa_suspend_lock);
719         mutex_destroy(&spa->spa_vdev_top_lock);
720
721         kmem_free(spa, sizeof (spa_t));
722 }
723
724 /*
725  * Given a pool, return the next pool in the namespace, or NULL if there is
726  * none.  If 'prev' is NULL, return the first pool.
727  */
728 spa_t *
729 spa_next(spa_t *prev)
730 {
731         ASSERT(MUTEX_HELD(&spa_namespace_lock));
732
733         if (prev)
734                 return (AVL_NEXT(&spa_namespace_avl, prev));
735         else
736                 return (avl_first(&spa_namespace_avl));
737 }
738
739 /*
740  * ==========================================================================
741  * SPA refcount functions
742  * ==========================================================================
743  */
744
745 /*
746  * Add a reference to the given spa_t.  Must have at least one reference, or
747  * have the namespace lock held.
748  */
749 void
750 spa_open_ref(spa_t *spa, void *tag)
751 {
752         ASSERT(refcount_count(&spa->spa_refcount) >= spa->spa_minref ||
753             MUTEX_HELD(&spa_namespace_lock));
754         (void) refcount_add(&spa->spa_refcount, tag);
755 }
756
757 /*
758  * Remove a reference to the given spa_t.  Must have at least one reference, or
759  * have the namespace lock held.
760  */
761 void
762 spa_close(spa_t *spa, void *tag)
763 {
764         ASSERT(refcount_count(&spa->spa_refcount) > spa->spa_minref ||
765             MUTEX_HELD(&spa_namespace_lock));
766         (void) refcount_remove(&spa->spa_refcount, tag);
767 }
768
769 /*
770  * Check to see if the spa refcount is zero.  Must be called with
771  * spa_namespace_lock held.  We really compare against spa_minref, which is the
772  * number of references acquired when opening a pool
773  */
774 boolean_t
775 spa_refcount_zero(spa_t *spa)
776 {
777         ASSERT(MUTEX_HELD(&spa_namespace_lock));
778
779         return (refcount_count(&spa->spa_refcount) == spa->spa_minref);
780 }
781
782 /*
783  * ==========================================================================
784  * SPA spare and l2cache tracking
785  * ==========================================================================
786  */
787
788 /*
789  * Hot spares and cache devices are tracked using the same code below,
790  * for 'auxiliary' devices.
791  */
792
793 typedef struct spa_aux {
794         uint64_t        aux_guid;
795         uint64_t        aux_pool;
796         avl_node_t      aux_avl;
797         int             aux_count;
798 } spa_aux_t;
799
800 static int
801 spa_aux_compare(const void *a, const void *b)
802 {
803         const spa_aux_t *sa = a;
804         const spa_aux_t *sb = b;
805
806         if (sa->aux_guid < sb->aux_guid)
807                 return (-1);
808         else if (sa->aux_guid > sb->aux_guid)
809                 return (1);
810         else
811                 return (0);
812 }
813
814 void
815 spa_aux_add(vdev_t *vd, avl_tree_t *avl)
816 {
817         avl_index_t where;
818         spa_aux_t search;
819         spa_aux_t *aux;
820
821         search.aux_guid = vd->vdev_guid;
822         if ((aux = avl_find(avl, &search, &where)) != NULL) {
823                 aux->aux_count++;
824         } else {
825                 aux = kmem_zalloc(sizeof (spa_aux_t), KM_SLEEP);
826                 aux->aux_guid = vd->vdev_guid;
827                 aux->aux_count = 1;
828                 avl_insert(avl, aux, where);
829         }
830 }
831
832 void
833 spa_aux_remove(vdev_t *vd, avl_tree_t *avl)
834 {
835         spa_aux_t search;
836         spa_aux_t *aux;
837         avl_index_t where;
838
839         search.aux_guid = vd->vdev_guid;
840         aux = avl_find(avl, &search, &where);
841
842         ASSERT(aux != NULL);
843
844         if (--aux->aux_count == 0) {
845                 avl_remove(avl, aux);
846                 kmem_free(aux, sizeof (spa_aux_t));
847         } else if (aux->aux_pool == spa_guid(vd->vdev_spa)) {
848                 aux->aux_pool = 0ULL;
849         }
850 }
851
852 boolean_t
853 spa_aux_exists(uint64_t guid, uint64_t *pool, int *refcnt, avl_tree_t *avl)
854 {
855         spa_aux_t search, *found;
856
857         search.aux_guid = guid;
858         found = avl_find(avl, &search, NULL);
859
860         if (pool) {
861                 if (found)
862                         *pool = found->aux_pool;
863                 else
864                         *pool = 0ULL;
865         }
866
867         if (refcnt) {
868                 if (found)
869                         *refcnt = found->aux_count;
870                 else
871                         *refcnt = 0;
872         }
873
874         return (found != NULL);
875 }
876
877 void
878 spa_aux_activate(vdev_t *vd, avl_tree_t *avl)
879 {
880         spa_aux_t search, *found;
881         avl_index_t where;
882
883         search.aux_guid = vd->vdev_guid;
884         found = avl_find(avl, &search, &where);
885         ASSERT(found != NULL);
886         ASSERT(found->aux_pool == 0ULL);
887
888         found->aux_pool = spa_guid(vd->vdev_spa);
889 }
890
891 /*
892  * Spares are tracked globally due to the following constraints:
893  *
894  *      - A spare may be part of multiple pools.
895  *      - A spare may be added to a pool even if it's actively in use within
896  *        another pool.
897  *      - A spare in use in any pool can only be the source of a replacement if
898  *        the target is a spare in the same pool.
899  *
900  * We keep track of all spares on the system through the use of a reference
901  * counted AVL tree.  When a vdev is added as a spare, or used as a replacement
902  * spare, then we bump the reference count in the AVL tree.  In addition, we set
903  * the 'vdev_isspare' member to indicate that the device is a spare (active or
904  * inactive).  When a spare is made active (used to replace a device in the
905  * pool), we also keep track of which pool its been made a part of.
906  *
907  * The 'spa_spare_lock' protects the AVL tree.  These functions are normally
908  * called under the spa_namespace lock as part of vdev reconfiguration.  The
909  * separate spare lock exists for the status query path, which does not need to
910  * be completely consistent with respect to other vdev configuration changes.
911  */
912
913 static int
914 spa_spare_compare(const void *a, const void *b)
915 {
916         return (spa_aux_compare(a, b));
917 }
918
919 void
920 spa_spare_add(vdev_t *vd)
921 {
922         mutex_enter(&spa_spare_lock);
923         ASSERT(!vd->vdev_isspare);
924         spa_aux_add(vd, &spa_spare_avl);
925         vd->vdev_isspare = B_TRUE;
926         mutex_exit(&spa_spare_lock);
927 }
928
929 void
930 spa_spare_remove(vdev_t *vd)
931 {
932         mutex_enter(&spa_spare_lock);
933         ASSERT(vd->vdev_isspare);
934         spa_aux_remove(vd, &spa_spare_avl);
935         vd->vdev_isspare = B_FALSE;
936         mutex_exit(&spa_spare_lock);
937 }
938
939 boolean_t
940 spa_spare_exists(uint64_t guid, uint64_t *pool, int *refcnt)
941 {
942         boolean_t found;
943
944         mutex_enter(&spa_spare_lock);
945         found = spa_aux_exists(guid, pool, refcnt, &spa_spare_avl);
946         mutex_exit(&spa_spare_lock);
947
948         return (found);
949 }
950
951 void
952 spa_spare_activate(vdev_t *vd)
953 {
954         mutex_enter(&spa_spare_lock);
955         ASSERT(vd->vdev_isspare);
956         spa_aux_activate(vd, &spa_spare_avl);
957         mutex_exit(&spa_spare_lock);
958 }
959
960 /*
961  * Level 2 ARC devices are tracked globally for the same reasons as spares.
962  * Cache devices currently only support one pool per cache device, and so
963  * for these devices the aux reference count is currently unused beyond 1.
964  */
965
966 static int
967 spa_l2cache_compare(const void *a, const void *b)
968 {
969         return (spa_aux_compare(a, b));
970 }
971
972 void
973 spa_l2cache_add(vdev_t *vd)
974 {
975         mutex_enter(&spa_l2cache_lock);
976         ASSERT(!vd->vdev_isl2cache);
977         spa_aux_add(vd, &spa_l2cache_avl);
978         vd->vdev_isl2cache = B_TRUE;
979         mutex_exit(&spa_l2cache_lock);
980 }
981
982 void
983 spa_l2cache_remove(vdev_t *vd)
984 {
985         mutex_enter(&spa_l2cache_lock);
986         ASSERT(vd->vdev_isl2cache);
987         spa_aux_remove(vd, &spa_l2cache_avl);
988         vd->vdev_isl2cache = B_FALSE;
989         mutex_exit(&spa_l2cache_lock);
990 }
991
992 boolean_t
993 spa_l2cache_exists(uint64_t guid, uint64_t *pool)
994 {
995         boolean_t found;
996
997         mutex_enter(&spa_l2cache_lock);
998         found = spa_aux_exists(guid, pool, NULL, &spa_l2cache_avl);
999         mutex_exit(&spa_l2cache_lock);
1000
1001         return (found);
1002 }
1003
1004 void
1005 spa_l2cache_activate(vdev_t *vd)
1006 {
1007         mutex_enter(&spa_l2cache_lock);
1008         ASSERT(vd->vdev_isl2cache);
1009         spa_aux_activate(vd, &spa_l2cache_avl);
1010         mutex_exit(&spa_l2cache_lock);
1011 }
1012
1013 /*
1014  * ==========================================================================
1015  * SPA vdev locking
1016  * ==========================================================================
1017  */
1018
1019 /*
1020  * Lock the given spa_t for the purpose of adding or removing a vdev.
1021  * Grabs the global spa_namespace_lock plus the spa config lock for writing.
1022  * It returns the next transaction group for the spa_t.
1023  */
1024 uint64_t
1025 spa_vdev_enter(spa_t *spa)
1026 {
1027         mutex_enter(&spa->spa_vdev_top_lock);
1028         mutex_enter(&spa_namespace_lock);
1029         return (spa_vdev_config_enter(spa));
1030 }
1031
1032 /*
1033  * Internal implementation for spa_vdev_enter().  Used when a vdev
1034  * operation requires multiple syncs (i.e. removing a device) while
1035  * keeping the spa_namespace_lock held.
1036  */
1037 uint64_t
1038 spa_vdev_config_enter(spa_t *spa)
1039 {
1040         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1041
1042         spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1043
1044         return (spa_last_synced_txg(spa) + 1);
1045 }
1046
1047 /*
1048  * Used in combination with spa_vdev_config_enter() to allow the syncing
1049  * of multiple transactions without releasing the spa_namespace_lock.
1050  */
1051 void
1052 spa_vdev_config_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error, char *tag)
1053 {
1054         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1055
1056         int config_changed = B_FALSE;
1057
1058         ASSERT(txg > spa_last_synced_txg(spa));
1059
1060         spa->spa_pending_vdev = NULL;
1061
1062         /*
1063          * Reassess the DTLs.
1064          */
1065         vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE);
1066
1067         if (error == 0 && !list_is_empty(&spa->spa_config_dirty_list)) {
1068                 config_changed = B_TRUE;
1069                 spa->spa_config_generation++;
1070         }
1071
1072         /*
1073          * Verify the metaslab classes.
1074          */
1075         ASSERT(metaslab_class_validate(spa_normal_class(spa)) == 0);
1076         ASSERT(metaslab_class_validate(spa_log_class(spa)) == 0);
1077
1078         spa_config_exit(spa, SCL_ALL, spa);
1079
1080         /*
1081          * Panic the system if the specified tag requires it.  This
1082          * is useful for ensuring that configurations are updated
1083          * transactionally.
1084          */
1085         if (zio_injection_enabled)
1086                 zio_handle_panic_injection(spa, tag, 0);
1087
1088         /*
1089          * Note: this txg_wait_synced() is important because it ensures
1090          * that there won't be more than one config change per txg.
1091          * This allows us to use the txg as the generation number.
1092          */
1093         if (error == 0)
1094                 txg_wait_synced(spa->spa_dsl_pool, txg);
1095
1096         if (vd != NULL) {
1097                 ASSERT(!vd->vdev_detached || vd->vdev_dtl_sm == NULL);
1098                 spa_config_enter(spa, SCL_ALL, spa, RW_WRITER);
1099                 vdev_free(vd);
1100                 spa_config_exit(spa, SCL_ALL, spa);
1101         }
1102
1103         /*
1104          * If the config changed, update the config cache.
1105          */
1106         if (config_changed)
1107                 spa_config_sync(spa, B_FALSE, B_TRUE);
1108 }
1109
1110 /*
1111  * Unlock the spa_t after adding or removing a vdev.  Besides undoing the
1112  * locking of spa_vdev_enter(), we also want make sure the transactions have
1113  * synced to disk, and then update the global configuration cache with the new
1114  * information.
1115  */
1116 int
1117 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
1118 {
1119         spa_vdev_config_exit(spa, vd, txg, error, FTAG);
1120         mutex_exit(&spa_namespace_lock);
1121         mutex_exit(&spa->spa_vdev_top_lock);
1122
1123         return (error);
1124 }
1125
1126 /*
1127  * Lock the given spa_t for the purpose of changing vdev state.
1128  */
1129 void
1130 spa_vdev_state_enter(spa_t *spa, int oplocks)
1131 {
1132         int locks = SCL_STATE_ALL | oplocks;
1133
1134         /*
1135          * Root pools may need to read of the underlying devfs filesystem
1136          * when opening up a vdev.  Unfortunately if we're holding the
1137          * SCL_ZIO lock it will result in a deadlock when we try to issue
1138          * the read from the root filesystem.  Instead we "prefetch"
1139          * the associated vnodes that we need prior to opening the
1140          * underlying devices and cache them so that we can prevent
1141          * any I/O when we are doing the actual open.
1142          */
1143         if (spa_is_root(spa)) {
1144                 int low = locks & ~(SCL_ZIO - 1);
1145                 int high = locks & ~low;
1146
1147                 spa_config_enter(spa, high, spa, RW_WRITER);
1148                 vdev_hold(spa->spa_root_vdev);
1149                 spa_config_enter(spa, low, spa, RW_WRITER);
1150         } else {
1151                 spa_config_enter(spa, locks, spa, RW_WRITER);
1152         }
1153         spa->spa_vdev_locks = locks;
1154 }
1155
1156 int
1157 spa_vdev_state_exit(spa_t *spa, vdev_t *vd, int error)
1158 {
1159         boolean_t config_changed = B_FALSE;
1160
1161         if (vd != NULL || error == 0)
1162                 vdev_dtl_reassess(vd ? vd->vdev_top : spa->spa_root_vdev,
1163                     0, 0, B_FALSE);
1164
1165         if (vd != NULL) {
1166                 vdev_state_dirty(vd->vdev_top);
1167                 config_changed = B_TRUE;
1168                 spa->spa_config_generation++;
1169         }
1170
1171         if (spa_is_root(spa))
1172                 vdev_rele(spa->spa_root_vdev);
1173
1174         ASSERT3U(spa->spa_vdev_locks, >=, SCL_STATE_ALL);
1175         spa_config_exit(spa, spa->spa_vdev_locks, spa);
1176
1177         /*
1178          * If anything changed, wait for it to sync.  This ensures that,
1179          * from the system administrator's perspective, zpool(1M) commands
1180          * are synchronous.  This is important for things like zpool offline:
1181          * when the command completes, you expect no further I/O from ZFS.
1182          */
1183         if (vd != NULL)
1184                 txg_wait_synced(spa->spa_dsl_pool, 0);
1185
1186         /*
1187          * If the config changed, update the config cache.
1188          */
1189         if (config_changed) {
1190                 mutex_enter(&spa_namespace_lock);
1191                 spa_config_sync(spa, B_FALSE, B_TRUE);
1192                 mutex_exit(&spa_namespace_lock);
1193         }
1194
1195         return (error);
1196 }
1197
1198 /*
1199  * ==========================================================================
1200  * Miscellaneous functions
1201  * ==========================================================================
1202  */
1203
1204 void
1205 spa_activate_mos_feature(spa_t *spa, const char *feature, dmu_tx_t *tx)
1206 {
1207         if (!nvlist_exists(spa->spa_label_features, feature)) {
1208                 fnvlist_add_boolean(spa->spa_label_features, feature);
1209                 /*
1210                  * When we are creating the pool (tx_txg==TXG_INITIAL), we can't
1211                  * dirty the vdev config because lock SCL_CONFIG is not held.
1212                  * Thankfully, in this case we don't need to dirty the config
1213                  * because it will be written out anyway when we finish
1214                  * creating the pool.
1215                  */
1216                 if (tx->tx_txg != TXG_INITIAL)
1217                         vdev_config_dirty(spa->spa_root_vdev);
1218         }
1219 }
1220
1221 void
1222 spa_deactivate_mos_feature(spa_t *spa, const char *feature)
1223 {
1224         if (nvlist_remove_all(spa->spa_label_features, feature) == 0)
1225                 vdev_config_dirty(spa->spa_root_vdev);
1226 }
1227
1228 /*
1229  * Rename a spa_t.
1230  */
1231 int
1232 spa_rename(const char *name, const char *newname)
1233 {
1234         spa_t *spa;
1235         int err;
1236
1237         /*
1238          * Lookup the spa_t and grab the config lock for writing.  We need to
1239          * actually open the pool so that we can sync out the necessary labels.
1240          * It's OK to call spa_open() with the namespace lock held because we
1241          * allow recursive calls for other reasons.
1242          */
1243         mutex_enter(&spa_namespace_lock);
1244         if ((err = spa_open(name, &spa, FTAG)) != 0) {
1245                 mutex_exit(&spa_namespace_lock);
1246                 return (err);
1247         }
1248
1249         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1250
1251         avl_remove(&spa_namespace_avl, spa);
1252         (void) strlcpy(spa->spa_name, newname, sizeof (spa->spa_name));
1253         avl_add(&spa_namespace_avl, spa);
1254
1255         /*
1256          * Sync all labels to disk with the new names by marking the root vdev
1257          * dirty and waiting for it to sync.  It will pick up the new pool name
1258          * during the sync.
1259          */
1260         vdev_config_dirty(spa->spa_root_vdev);
1261
1262         spa_config_exit(spa, SCL_ALL, FTAG);
1263
1264         txg_wait_synced(spa->spa_dsl_pool, 0);
1265
1266         /*
1267          * Sync the updated config cache.
1268          */
1269         spa_config_sync(spa, B_FALSE, B_TRUE);
1270
1271         spa_close(spa, FTAG);
1272
1273         mutex_exit(&spa_namespace_lock);
1274
1275         return (0);
1276 }
1277
1278 /*
1279  * Return the spa_t associated with given pool_guid, if it exists.  If
1280  * device_guid is non-zero, determine whether the pool exists *and* contains
1281  * a device with the specified device_guid.
1282  */
1283 spa_t *
1284 spa_by_guid(uint64_t pool_guid, uint64_t device_guid)
1285 {
1286         spa_t *spa;
1287         avl_tree_t *t = &spa_namespace_avl;
1288
1289         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1290
1291         for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
1292                 if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1293                         continue;
1294                 if (spa->spa_root_vdev == NULL)
1295                         continue;
1296                 if (spa_guid(spa) == pool_guid) {
1297                         if (device_guid == 0)
1298                                 break;
1299
1300                         if (vdev_lookup_by_guid(spa->spa_root_vdev,
1301                             device_guid) != NULL)
1302                                 break;
1303
1304                         /*
1305                          * Check any devices we may be in the process of adding.
1306                          */
1307                         if (spa->spa_pending_vdev) {
1308                                 if (vdev_lookup_by_guid(spa->spa_pending_vdev,
1309                                     device_guid) != NULL)
1310                                         break;
1311                         }
1312                 }
1313         }
1314
1315         return (spa);
1316 }
1317
1318 /*
1319  * Determine whether a pool with the given pool_guid exists.
1320  */
1321 boolean_t
1322 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
1323 {
1324         return (spa_by_guid(pool_guid, device_guid) != NULL);
1325 }
1326
1327 char *
1328 spa_strdup(const char *s)
1329 {
1330         size_t len;
1331         char *new;
1332
1333         len = strlen(s);
1334         new = kmem_alloc(len + 1, KM_SLEEP);
1335         bcopy(s, new, len);
1336         new[len] = '\0';
1337
1338         return (new);
1339 }
1340
1341 void
1342 spa_strfree(char *s)
1343 {
1344         kmem_free(s, strlen(s) + 1);
1345 }
1346
1347 uint64_t
1348 spa_get_random(uint64_t range)
1349 {
1350         uint64_t r;
1351
1352         ASSERT(range != 0);
1353
1354         (void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
1355
1356         return (r % range);
1357 }
1358
1359 uint64_t
1360 spa_generate_guid(spa_t *spa)
1361 {
1362         uint64_t guid = spa_get_random(-1ULL);
1363
1364         if (spa != NULL) {
1365                 while (guid == 0 || spa_guid_exists(spa_guid(spa), guid))
1366                         guid = spa_get_random(-1ULL);
1367         } else {
1368                 while (guid == 0 || spa_guid_exists(guid, 0))
1369                         guid = spa_get_random(-1ULL);
1370         }
1371
1372         return (guid);
1373 }
1374
1375 void
1376 snprintf_blkptr(char *buf, size_t buflen, const blkptr_t *bp)
1377 {
1378         char type[256];
1379         char *checksum = NULL;
1380         char *compress = NULL;
1381
1382         if (bp != NULL) {
1383                 if (BP_GET_TYPE(bp) & DMU_OT_NEWTYPE) {
1384                         dmu_object_byteswap_t bswap =
1385                             DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
1386                         (void) snprintf(type, sizeof (type), "bswap %s %s",
1387                             DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) ?
1388                             "metadata" : "data",
1389                             dmu_ot_byteswap[bswap].ob_name);
1390                 } else {
1391                         (void) strlcpy(type, dmu_ot[BP_GET_TYPE(bp)].ot_name,
1392                             sizeof (type));
1393                 }
1394                 checksum = zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name;
1395                 compress = zio_compress_table[BP_GET_COMPRESS(bp)].ci_name;
1396         }
1397
1398         SNPRINTF_BLKPTR(snprintf, ' ', buf, buflen, bp, type, checksum,
1399             compress);
1400 }
1401
1402 void
1403 spa_freeze(spa_t *spa)
1404 {
1405         uint64_t freeze_txg = 0;
1406
1407         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1408         if (spa->spa_freeze_txg == UINT64_MAX) {
1409                 freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
1410                 spa->spa_freeze_txg = freeze_txg;
1411         }
1412         spa_config_exit(spa, SCL_ALL, FTAG);
1413         if (freeze_txg != 0)
1414                 txg_wait_synced(spa_get_dsl(spa), freeze_txg);
1415 }
1416
1417 void
1418 zfs_panic_recover(const char *fmt, ...)
1419 {
1420         va_list adx;
1421
1422         va_start(adx, fmt);
1423         vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
1424         va_end(adx);
1425 }
1426
1427 /*
1428  * This is a stripped-down version of strtoull, suitable only for converting
1429  * lowercase hexadecimal numbers that don't overflow.
1430  */
1431 uint64_t
1432 zfs_strtonum(const char *str, char **nptr)
1433 {
1434         uint64_t val = 0;
1435         char c;
1436         int digit;
1437
1438         while ((c = *str) != '\0') {
1439                 if (c >= '0' && c <= '9')
1440                         digit = c - '0';
1441                 else if (c >= 'a' && c <= 'f')
1442                         digit = 10 + c - 'a';
1443                 else
1444                         break;
1445
1446                 val *= 16;
1447                 val += digit;
1448
1449                 str++;
1450         }
1451
1452         if (nptr)
1453                 *nptr = (char *)str;
1454
1455         return (val);
1456 }
1457
1458 /*
1459  * ==========================================================================
1460  * Accessor functions
1461  * ==========================================================================
1462  */
1463
1464 boolean_t
1465 spa_shutting_down(spa_t *spa)
1466 {
1467         return (spa->spa_async_suspended);
1468 }
1469
1470 dsl_pool_t *
1471 spa_get_dsl(spa_t *spa)
1472 {
1473         return (spa->spa_dsl_pool);
1474 }
1475
1476 boolean_t
1477 spa_is_initializing(spa_t *spa)
1478 {
1479         return (spa->spa_is_initializing);
1480 }
1481
1482 blkptr_t *
1483 spa_get_rootblkptr(spa_t *spa)
1484 {
1485         return (&spa->spa_ubsync.ub_rootbp);
1486 }
1487
1488 void
1489 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
1490 {
1491         spa->spa_uberblock.ub_rootbp = *bp;
1492 }
1493
1494 void
1495 spa_altroot(spa_t *spa, char *buf, size_t buflen)
1496 {
1497         if (spa->spa_root == NULL)
1498                 buf[0] = '\0';
1499         else
1500                 (void) strncpy(buf, spa->spa_root, buflen);
1501 }
1502
1503 int
1504 spa_sync_pass(spa_t *spa)
1505 {
1506         return (spa->spa_sync_pass);
1507 }
1508
1509 char *
1510 spa_name(spa_t *spa)
1511 {
1512         return (spa->spa_name);
1513 }
1514
1515 uint64_t
1516 spa_guid(spa_t *spa)
1517 {
1518         dsl_pool_t *dp = spa_get_dsl(spa);
1519         uint64_t guid;
1520
1521         /*
1522          * If we fail to parse the config during spa_load(), we can go through
1523          * the error path (which posts an ereport) and end up here with no root
1524          * vdev.  We stash the original pool guid in 'spa_config_guid' to handle
1525          * this case.
1526          */
1527         if (spa->spa_root_vdev == NULL)
1528                 return (spa->spa_config_guid);
1529
1530         guid = spa->spa_last_synced_guid != 0 ?
1531             spa->spa_last_synced_guid : spa->spa_root_vdev->vdev_guid;
1532
1533         /*
1534          * Return the most recently synced out guid unless we're
1535          * in syncing context.
1536          */
1537         if (dp && dsl_pool_sync_context(dp))
1538                 return (spa->spa_root_vdev->vdev_guid);
1539         else
1540                 return (guid);
1541 }
1542
1543 uint64_t
1544 spa_load_guid(spa_t *spa)
1545 {
1546         /*
1547          * This is a GUID that exists solely as a reference for the
1548          * purposes of the arc.  It is generated at load time, and
1549          * is never written to persistent storage.
1550          */
1551         return (spa->spa_load_guid);
1552 }
1553
1554 uint64_t
1555 spa_last_synced_txg(spa_t *spa)
1556 {
1557         return (spa->spa_ubsync.ub_txg);
1558 }
1559
1560 uint64_t
1561 spa_first_txg(spa_t *spa)
1562 {
1563         return (spa->spa_first_txg);
1564 }
1565
1566 uint64_t
1567 spa_syncing_txg(spa_t *spa)
1568 {
1569         return (spa->spa_syncing_txg);
1570 }
1571
1572 pool_state_t
1573 spa_state(spa_t *spa)
1574 {
1575         return (spa->spa_state);
1576 }
1577
1578 spa_load_state_t
1579 spa_load_state(spa_t *spa)
1580 {
1581         return (spa->spa_load_state);
1582 }
1583
1584 uint64_t
1585 spa_freeze_txg(spa_t *spa)
1586 {
1587         return (spa->spa_freeze_txg);
1588 }
1589
1590 /* ARGSUSED */
1591 uint64_t
1592 spa_get_asize(spa_t *spa, uint64_t lsize)
1593 {
1594         return (lsize * spa_asize_inflation);
1595 }
1596
1597 uint64_t
1598 spa_get_dspace(spa_t *spa)
1599 {
1600         return (spa->spa_dspace);
1601 }
1602
1603 void
1604 spa_update_dspace(spa_t *spa)
1605 {
1606         spa->spa_dspace = metaslab_class_get_dspace(spa_normal_class(spa)) +
1607             ddt_get_dedup_dspace(spa);
1608 }
1609
1610 /*
1611  * Return the failure mode that has been set to this pool. The default
1612  * behavior will be to block all I/Os when a complete failure occurs.
1613  */
1614 uint8_t
1615 spa_get_failmode(spa_t *spa)
1616 {
1617         return (spa->spa_failmode);
1618 }
1619
1620 boolean_t
1621 spa_suspended(spa_t *spa)
1622 {
1623         return (spa->spa_suspended);
1624 }
1625
1626 uint64_t
1627 spa_version(spa_t *spa)
1628 {
1629         return (spa->spa_ubsync.ub_version);
1630 }
1631
1632 boolean_t
1633 spa_deflate(spa_t *spa)
1634 {
1635         return (spa->spa_deflate);
1636 }
1637
1638 metaslab_class_t *
1639 spa_normal_class(spa_t *spa)
1640 {
1641         return (spa->spa_normal_class);
1642 }
1643
1644 metaslab_class_t *
1645 spa_log_class(spa_t *spa)
1646 {
1647         return (spa->spa_log_class);
1648 }
1649
1650 int
1651 spa_max_replication(spa_t *spa)
1652 {
1653         /*
1654          * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1655          * handle BPs with more than one DVA allocated.  Set our max
1656          * replication level accordingly.
1657          */
1658         if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1659                 return (1);
1660         return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1661 }
1662
1663 int
1664 spa_prev_software_version(spa_t *spa)
1665 {
1666         return (spa->spa_prev_software_version);
1667 }
1668
1669 uint64_t
1670 spa_deadman_synctime(spa_t *spa)
1671 {
1672         return (spa->spa_deadman_synctime);
1673 }
1674
1675 uint64_t
1676 dva_get_dsize_sync(spa_t *spa, const dva_t *dva)
1677 {
1678         uint64_t asize = DVA_GET_ASIZE(dva);
1679         uint64_t dsize = asize;
1680
1681         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1682
1683         if (asize != 0 && spa->spa_deflate) {
1684                 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
1685                 dsize = (asize >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio;
1686         }
1687
1688         return (dsize);
1689 }
1690
1691 uint64_t
1692 bp_get_dsize_sync(spa_t *spa, const blkptr_t *bp)
1693 {
1694         uint64_t dsize = 0;
1695
1696         for (int d = 0; d < SPA_DVAS_PER_BP; d++)
1697                 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1698
1699         return (dsize);
1700 }
1701
1702 uint64_t
1703 bp_get_dsize(spa_t *spa, const blkptr_t *bp)
1704 {
1705         uint64_t dsize = 0;
1706
1707         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1708
1709         for (int d = 0; d < SPA_DVAS_PER_BP; d++)
1710                 dsize += dva_get_dsize_sync(spa, &bp->blk_dva[d]);
1711
1712         spa_config_exit(spa, SCL_VDEV, FTAG);
1713
1714         return (dsize);
1715 }
1716
1717 /*
1718  * ==========================================================================
1719  * Initialization and Termination
1720  * ==========================================================================
1721  */
1722
1723 static int
1724 spa_name_compare(const void *a1, const void *a2)
1725 {
1726         const spa_t *s1 = a1;
1727         const spa_t *s2 = a2;
1728         int s;
1729
1730         s = strcmp(s1->spa_name, s2->spa_name);
1731         if (s > 0)
1732                 return (1);
1733         if (s < 0)
1734                 return (-1);
1735         return (0);
1736 }
1737
1738 int
1739 spa_busy(void)
1740 {
1741         return (spa_active_count);
1742 }
1743
1744 void
1745 spa_boot_init()
1746 {
1747         spa_config_load();
1748 }
1749
1750 #ifdef _KERNEL
1751 EVENTHANDLER_DEFINE(mountroot, spa_boot_init, NULL, 0);
1752 #endif
1753
1754 void
1755 spa_init(int mode)
1756 {
1757         mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
1758         mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
1759         mutex_init(&spa_l2cache_lock, NULL, MUTEX_DEFAULT, NULL);
1760         cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
1761
1762         avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
1763             offsetof(spa_t, spa_avl));
1764
1765         avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_aux_t),
1766             offsetof(spa_aux_t, aux_avl));
1767
1768         avl_create(&spa_l2cache_avl, spa_l2cache_compare, sizeof (spa_aux_t),
1769             offsetof(spa_aux_t, aux_avl));
1770
1771         spa_mode_global = mode;
1772
1773 #ifdef illumos
1774 #ifdef _KERNEL
1775         spa_arch_init();
1776 #else
1777         if (spa_mode_global != FREAD && dprintf_find_string("watch")) {
1778                 arc_procfd = open("/proc/self/ctl", O_WRONLY);
1779                 if (arc_procfd == -1) {
1780                         perror("could not enable watchpoints: "
1781                             "opening /proc/self/ctl failed: ");
1782                 } else {
1783                         arc_watch = B_TRUE;
1784                 }
1785         }
1786 #endif
1787 #endif /* illumos */
1788         refcount_sysinit();
1789         unique_init();
1790         range_tree_init();
1791         zio_init();
1792         lz4_init();
1793         dmu_init();
1794         zil_init();
1795         vdev_cache_stat_init();
1796         zfs_prop_init();
1797         zpool_prop_init();
1798         zpool_feature_init();
1799         spa_config_load();
1800         l2arc_start();
1801 #ifndef illumos
1802 #ifdef _KERNEL
1803         zfs_deadman_init();
1804 #endif
1805 #endif  /* !illumos */
1806 }
1807
1808 void
1809 spa_fini(void)
1810 {
1811         l2arc_stop();
1812
1813         spa_evict_all();
1814
1815         vdev_cache_stat_fini();
1816         zil_fini();
1817         dmu_fini();
1818         lz4_fini();
1819         zio_fini();
1820         range_tree_fini();
1821         unique_fini();
1822         refcount_fini();
1823
1824         avl_destroy(&spa_namespace_avl);
1825         avl_destroy(&spa_spare_avl);
1826         avl_destroy(&spa_l2cache_avl);
1827
1828         cv_destroy(&spa_namespace_cv);
1829         mutex_destroy(&spa_namespace_lock);
1830         mutex_destroy(&spa_spare_lock);
1831         mutex_destroy(&spa_l2cache_lock);
1832 }
1833
1834 /*
1835  * Return whether this pool has slogs. No locking needed.
1836  * It's not a problem if the wrong answer is returned as it's only for
1837  * performance and not correctness
1838  */
1839 boolean_t
1840 spa_has_slogs(spa_t *spa)
1841 {
1842         return (spa->spa_log_class->mc_rotor != NULL);
1843 }
1844
1845 spa_log_state_t
1846 spa_get_log_state(spa_t *spa)
1847 {
1848         return (spa->spa_log_state);
1849 }
1850
1851 void
1852 spa_set_log_state(spa_t *spa, spa_log_state_t state)
1853 {
1854         spa->spa_log_state = state;
1855 }
1856
1857 boolean_t
1858 spa_is_root(spa_t *spa)
1859 {
1860         return (spa->spa_is_root);
1861 }
1862
1863 boolean_t
1864 spa_writeable(spa_t *spa)
1865 {
1866         return (!!(spa->spa_mode & FWRITE));
1867 }
1868
1869 int
1870 spa_mode(spa_t *spa)
1871 {
1872         return (spa->spa_mode);
1873 }
1874
1875 uint64_t
1876 spa_bootfs(spa_t *spa)
1877 {
1878         return (spa->spa_bootfs);
1879 }
1880
1881 uint64_t
1882 spa_delegation(spa_t *spa)
1883 {
1884         return (spa->spa_delegation);
1885 }
1886
1887 objset_t *
1888 spa_meta_objset(spa_t *spa)
1889 {
1890         return (spa->spa_meta_objset);
1891 }
1892
1893 enum zio_checksum
1894 spa_dedup_checksum(spa_t *spa)
1895 {
1896         return (spa->spa_dedup_checksum);
1897 }
1898
1899 /*
1900  * Reset pool scan stat per scan pass (or reboot).
1901  */
1902 void
1903 spa_scan_stat_init(spa_t *spa)
1904 {
1905         /* data not stored on disk */
1906         spa->spa_scan_pass_start = gethrestime_sec();
1907         spa->spa_scan_pass_exam = 0;
1908         vdev_scan_stat_init(spa->spa_root_vdev);
1909 }
1910
1911 /*
1912  * Get scan stats for zpool status reports
1913  */
1914 int
1915 spa_scan_get_stats(spa_t *spa, pool_scan_stat_t *ps)
1916 {
1917         dsl_scan_t *scn = spa->spa_dsl_pool ? spa->spa_dsl_pool->dp_scan : NULL;
1918
1919         if (scn == NULL || scn->scn_phys.scn_func == POOL_SCAN_NONE)
1920                 return (SET_ERROR(ENOENT));
1921         bzero(ps, sizeof (pool_scan_stat_t));
1922
1923         /* data stored on disk */
1924         ps->pss_func = scn->scn_phys.scn_func;
1925         ps->pss_start_time = scn->scn_phys.scn_start_time;
1926         ps->pss_end_time = scn->scn_phys.scn_end_time;
1927         ps->pss_to_examine = scn->scn_phys.scn_to_examine;
1928         ps->pss_examined = scn->scn_phys.scn_examined;
1929         ps->pss_to_process = scn->scn_phys.scn_to_process;
1930         ps->pss_processed = scn->scn_phys.scn_processed;
1931         ps->pss_errors = scn->scn_phys.scn_errors;
1932         ps->pss_state = scn->scn_phys.scn_state;
1933
1934         /* data not stored on disk */
1935         ps->pss_pass_start = spa->spa_scan_pass_start;
1936         ps->pss_pass_exam = spa->spa_scan_pass_exam;
1937
1938         return (0);
1939 }
1940
1941 boolean_t
1942 spa_debug_enabled(spa_t *spa)
1943 {
1944         return (spa->spa_debug);
1945 }