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