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