xref: /titanic_50/usr/src/uts/common/fs/zfs/spa_misc.c (revision 582271e8d649568c83e9a016cc0d54265389c5d9)
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 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/zfs_context.h>
29 #include <sys/spa_impl.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/fs/zfs.h>
47 #include <sys/metaslab_impl.h>
48 #include "zfs_prop.h"
49 
50 /*
51  * SPA locking
52  *
53  * There are four basic locks for managing spa_t structures:
54  *
55  * spa_namespace_lock (global mutex)
56  *
57  *	This lock must be acquired to do any of the following:
58  *
59  *		- Lookup a spa_t by name
60  *		- Add or remove a spa_t from the namespace
61  *		- Increase spa_refcount from non-zero
62  *		- Check if spa_refcount is zero
63  *		- Rename a spa_t
64  *		- add/remove/attach/detach devices
65  *		- Held for the duration of create/destroy/import/export
66  *
67  *	It does not need to handle recursion.  A create or destroy may
68  *	reference objects (files or zvols) in other pools, but by
69  *	definition they must have an existing reference, and will never need
70  *	to lookup a spa_t by name.
71  *
72  * spa_refcount (per-spa refcount_t protected by mutex)
73  *
74  *	This reference count keep track of any active users of the spa_t.  The
75  *	spa_t cannot be destroyed or freed while this is non-zero.  Internally,
76  *	the refcount is never really 'zero' - opening a pool implicitly keeps
77  *	some references in the DMU.  Internally we check against SPA_MINREF, but
78  *	present the image of a zero/non-zero value to consumers.
79  *
80  * spa_config_lock (per-spa read-priority rwlock)
81  *
82  *	This protects the spa_t from config changes, and must be held in
83  *	the following circumstances:
84  *
85  *		- RW_READER to perform I/O to the spa
86  *		- RW_WRITER to change the vdev config
87  *
88  * spa_config_cache_lock (per-spa mutex)
89  *
90  *	This mutex prevents the spa_config nvlist from being updated.  No
91  *      other locks are required to obtain this lock, although implicitly you
92  *      must have the namespace lock or non-zero refcount to have any kind
93  *      of spa_t pointer at all.
94  *
95  * The locking order is fairly straightforward:
96  *
97  *		spa_namespace_lock	->	spa_refcount
98  *
99  *	The namespace lock must be acquired to increase the refcount from 0
100  *	or to check if it is zero.
101  *
102  *		spa_refcount		->	spa_config_lock
103  *
104  *	There must be at least one valid reference on the spa_t to acquire
105  *	the config lock.
106  *
107  *		spa_namespace_lock	->	spa_config_lock
108  *
109  *	The namespace lock must always be taken before the config lock.
110  *
111  *
112  * The spa_namespace_lock and spa_config_cache_lock can be acquired directly and
113  * are globally visible.
114  *
115  * The namespace is manipulated using the following functions, all which require
116  * the spa_namespace_lock to be held.
117  *
118  *	spa_lookup()		Lookup a spa_t by name.
119  *
120  *	spa_add()		Create a new spa_t in the namespace.
121  *
122  *	spa_remove()		Remove a spa_t from the namespace.  This also
123  *				frees up any memory associated with the spa_t.
124  *
125  *	spa_next()		Returns the next spa_t in the system, or the
126  *				first if NULL is passed.
127  *
128  *	spa_evict_all()		Shutdown and remove all spa_t structures in
129  *				the system.
130  *
131  *	spa_guid_exists()	Determine whether a pool/device guid exists.
132  *
133  * The spa_refcount is manipulated using the following functions:
134  *
135  *	spa_open_ref()		Adds a reference to the given spa_t.  Must be
136  *				called with spa_namespace_lock held if the
137  *				refcount is currently zero.
138  *
139  *	spa_close()		Remove a reference from the spa_t.  This will
140  *				not free the spa_t or remove it from the
141  *				namespace.  No locking is required.
142  *
143  *	spa_refcount_zero()	Returns true if the refcount is currently
144  *				zero.  Must be called with spa_namespace_lock
145  *				held.
146  *
147  * The spa_config_lock is manipulated using the following functions:
148  *
149  *	spa_config_enter()	Acquire the config lock as RW_READER or
150  *				RW_WRITER.  At least one reference on the spa_t
151  *				must exist.
152  *
153  *	spa_config_exit()	Release the config lock.
154  *
155  *	spa_config_held()	Returns true if the config lock is currently
156  *				held in the given state.
157  *
158  * The vdev configuration is protected by spa_vdev_enter() / spa_vdev_exit().
159  *
160  *	spa_vdev_enter()	Acquire the namespace lock and the config lock
161  *				for writing.
162  *
163  *	spa_vdev_exit()		Release the config lock, wait for all I/O
164  *				to complete, sync the updated configs to the
165  *				cache, and release the namespace lock.
166  *
167  * The spa_name() function also requires either the spa_namespace_lock
168  * or the spa_config_lock, as both are needed to do a rename.  spa_rename() is
169  * also implemented within this file since is requires manipulation of the
170  * namespace.
171  */
172 
173 static avl_tree_t spa_namespace_avl;
174 kmutex_t spa_namespace_lock;
175 static kcondvar_t spa_namespace_cv;
176 static int spa_active_count;
177 int spa_max_replication_override = SPA_DVAS_PER_BP;
178 
179 static kmutex_t spa_spare_lock;
180 static avl_tree_t spa_spare_avl;
181 
182 kmem_cache_t *spa_buffer_pool;
183 int spa_mode;
184 
185 #ifdef ZFS_DEBUG
186 /* Everything except dprintf is on by default in debug builds */
187 int zfs_flags = ~ZFS_DEBUG_DPRINTF;
188 #else
189 int zfs_flags = 0;
190 #endif
191 
192 /*
193  * zfs_recover can be set to nonzero to attempt to recover from
194  * otherwise-fatal errors, typically caused by on-disk corruption.  When
195  * set, calls to zfs_panic_recover() will turn into warning messages.
196  */
197 int zfs_recover = 0;
198 
199 #define	SPA_MINREF	5	/* spa_refcnt for an open-but-idle pool */
200 
201 /*
202  * ==========================================================================
203  * SPA namespace functions
204  * ==========================================================================
205  */
206 
207 /*
208  * Lookup the named spa_t in the AVL tree.  The spa_namespace_lock must be held.
209  * Returns NULL if no matching spa_t is found.
210  */
211 spa_t *
212 spa_lookup(const char *name)
213 {
214 	spa_t search, *spa;
215 	avl_index_t where;
216 	char c;
217 	char *cp;
218 
219 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
220 
221 	/*
222 	 * If it's a full dataset name, figure out the pool name and
223 	 * just use that.
224 	 */
225 	cp = strpbrk(name, "/@");
226 	if (cp) {
227 		c = *cp;
228 		*cp = '\0';
229 	}
230 
231 	search.spa_name = (char *)name;
232 	spa = avl_find(&spa_namespace_avl, &search, &where);
233 
234 	if (cp)
235 		*cp = c;
236 
237 	return (spa);
238 }
239 
240 /*
241  * Create an uninitialized spa_t with the given name.  Requires
242  * spa_namespace_lock.  The caller must ensure that the spa_t doesn't already
243  * exist by calling spa_lookup() first.
244  */
245 spa_t *
246 spa_add(const char *name, const char *altroot)
247 {
248 	spa_t *spa;
249 
250 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
251 
252 	spa = kmem_zalloc(sizeof (spa_t), KM_SLEEP);
253 
254 	rw_init(&spa->spa_traverse_lock, NULL, RW_DEFAULT, NULL);
255 
256 	mutex_init(&spa->spa_uberblock_lock, NULL, MUTEX_DEFAULT, NULL);
257 	mutex_init(&spa->spa_async_lock, NULL, MUTEX_DEFAULT, NULL);
258 	mutex_init(&spa->spa_config_cache_lock, NULL, MUTEX_DEFAULT, NULL);
259 	mutex_init(&spa->spa_scrub_lock, NULL, MUTEX_DEFAULT, NULL);
260 	mutex_init(&spa->spa_errlog_lock, NULL, MUTEX_DEFAULT, NULL);
261 	mutex_init(&spa->spa_errlist_lock, NULL, MUTEX_DEFAULT, NULL);
262 	mutex_init(&spa->spa_sync_bplist.bpl_lock, NULL, MUTEX_DEFAULT, NULL);
263 	mutex_init(&spa->spa_history_lock, NULL, MUTEX_DEFAULT, NULL);
264 	mutex_init(&spa->spa_props_lock, NULL, MUTEX_DEFAULT, NULL);
265 
266 	cv_init(&spa->spa_async_cv, NULL, CV_DEFAULT, NULL);
267 	cv_init(&spa->spa_scrub_cv, NULL, CV_DEFAULT, NULL);
268 	cv_init(&spa->spa_scrub_io_cv, NULL, CV_DEFAULT, NULL);
269 
270 	spa->spa_name = spa_strdup(name);
271 	spa->spa_state = POOL_STATE_UNINITIALIZED;
272 	spa->spa_freeze_txg = UINT64_MAX;
273 	spa->spa_final_txg = UINT64_MAX;
274 
275 	refcount_create(&spa->spa_refcount);
276 	rprw_init(&spa->spa_config_lock);
277 
278 	avl_add(&spa_namespace_avl, spa);
279 
280 	mutex_init(&spa->spa_zio_lock, NULL, MUTEX_DEFAULT, NULL);
281 
282 	/*
283 	 * Set the alternate root, if there is one.
284 	 */
285 	if (altroot) {
286 		spa->spa_root = spa_strdup(altroot);
287 		spa_active_count++;
288 	}
289 
290 	return (spa);
291 }
292 
293 /*
294  * Removes a spa_t from the namespace, freeing up any memory used.  Requires
295  * spa_namespace_lock.  This is called only after the spa_t has been closed and
296  * deactivated.
297  */
298 void
299 spa_remove(spa_t *spa)
300 {
301 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
302 	ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
303 	ASSERT(spa->spa_scrub_thread == NULL);
304 
305 	avl_remove(&spa_namespace_avl, spa);
306 	cv_broadcast(&spa_namespace_cv);
307 
308 	if (spa->spa_root) {
309 		spa_strfree(spa->spa_root);
310 		spa_active_count--;
311 	}
312 
313 	if (spa->spa_name)
314 		spa_strfree(spa->spa_name);
315 
316 	if (spa->spa_config_dir)
317 		spa_strfree(spa->spa_config_dir);
318 	if (spa->spa_config_file)
319 		spa_strfree(spa->spa_config_file);
320 
321 	spa_config_set(spa, NULL);
322 
323 	refcount_destroy(&spa->spa_refcount);
324 
325 	rprw_destroy(&spa->spa_config_lock);
326 
327 	rw_destroy(&spa->spa_traverse_lock);
328 
329 	cv_destroy(&spa->spa_async_cv);
330 	cv_destroy(&spa->spa_scrub_cv);
331 	cv_destroy(&spa->spa_scrub_io_cv);
332 
333 	mutex_destroy(&spa->spa_uberblock_lock);
334 	mutex_destroy(&spa->spa_async_lock);
335 	mutex_destroy(&spa->spa_config_cache_lock);
336 	mutex_destroy(&spa->spa_scrub_lock);
337 	mutex_destroy(&spa->spa_errlog_lock);
338 	mutex_destroy(&spa->spa_errlist_lock);
339 	mutex_destroy(&spa->spa_sync_bplist.bpl_lock);
340 	mutex_destroy(&spa->spa_history_lock);
341 	mutex_destroy(&spa->spa_props_lock);
342 	mutex_destroy(&spa->spa_zio_lock);
343 
344 	kmem_free(spa, sizeof (spa_t));
345 }
346 
347 /*
348  * Given a pool, return the next pool in the namespace, or NULL if there is
349  * none.  If 'prev' is NULL, return the first pool.
350  */
351 spa_t *
352 spa_next(spa_t *prev)
353 {
354 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
355 
356 	if (prev)
357 		return (AVL_NEXT(&spa_namespace_avl, prev));
358 	else
359 		return (avl_first(&spa_namespace_avl));
360 }
361 
362 /*
363  * ==========================================================================
364  * SPA refcount functions
365  * ==========================================================================
366  */
367 
368 /*
369  * Add a reference to the given spa_t.  Must have at least one reference, or
370  * have the namespace lock held.
371  */
372 void
373 spa_open_ref(spa_t *spa, void *tag)
374 {
375 	ASSERT(refcount_count(&spa->spa_refcount) > SPA_MINREF ||
376 	    MUTEX_HELD(&spa_namespace_lock));
377 
378 	(void) refcount_add(&spa->spa_refcount, tag);
379 }
380 
381 /*
382  * Remove a reference to the given spa_t.  Must have at least one reference, or
383  * have the namespace lock held.
384  */
385 void
386 spa_close(spa_t *spa, void *tag)
387 {
388 	ASSERT(refcount_count(&spa->spa_refcount) > SPA_MINREF ||
389 	    MUTEX_HELD(&spa_namespace_lock));
390 
391 	(void) refcount_remove(&spa->spa_refcount, tag);
392 }
393 
394 /*
395  * Check to see if the spa refcount is zero.  Must be called with
396  * spa_namespace_lock held.  We really compare against SPA_MINREF, which is the
397  * number of references acquired when opening a pool
398  */
399 boolean_t
400 spa_refcount_zero(spa_t *spa)
401 {
402 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
403 
404 	return (refcount_count(&spa->spa_refcount) == SPA_MINREF);
405 }
406 
407 /*
408  * ==========================================================================
409  * SPA spare tracking
410  * ==========================================================================
411  */
412 
413 /*
414  * Spares are tracked globally due to the following constraints:
415  *
416  * 	- A spare may be part of multiple pools.
417  * 	- A spare may be added to a pool even if it's actively in use within
418  *	  another pool.
419  * 	- A spare in use in any pool can only be the source of a replacement if
420  *	  the target is a spare in the same pool.
421  *
422  * We keep track of all spares on the system through the use of a reference
423  * counted AVL tree.  When a vdev is added as a spare, or used as a replacement
424  * spare, then we bump the reference count in the AVL tree.  In addition, we set
425  * the 'vdev_isspare' member to indicate that the device is a spare (active or
426  * inactive).  When a spare is made active (used to replace a device in the
427  * pool), we also keep track of which pool its been made a part of.
428  *
429  * The 'spa_spare_lock' protects the AVL tree.  These functions are normally
430  * called under the spa_namespace lock as part of vdev reconfiguration.  The
431  * separate spare lock exists for the status query path, which does not need to
432  * be completely consistent with respect to other vdev configuration changes.
433  */
434 
435 typedef struct spa_spare {
436 	uint64_t	spare_guid;
437 	uint64_t	spare_pool;
438 	avl_node_t	spare_avl;
439 	int		spare_count;
440 } spa_spare_t;
441 
442 static int
443 spa_spare_compare(const void *a, const void *b)
444 {
445 	const spa_spare_t *sa = a;
446 	const spa_spare_t *sb = b;
447 
448 	if (sa->spare_guid < sb->spare_guid)
449 		return (-1);
450 	else if (sa->spare_guid > sb->spare_guid)
451 		return (1);
452 	else
453 		return (0);
454 }
455 
456 void
457 spa_spare_add(vdev_t *vd)
458 {
459 	avl_index_t where;
460 	spa_spare_t search;
461 	spa_spare_t *spare;
462 
463 	mutex_enter(&spa_spare_lock);
464 	ASSERT(!vd->vdev_isspare);
465 
466 	search.spare_guid = vd->vdev_guid;
467 	if ((spare = avl_find(&spa_spare_avl, &search, &where)) != NULL) {
468 		spare->spare_count++;
469 	} else {
470 		spare = kmem_zalloc(sizeof (spa_spare_t), KM_SLEEP);
471 		spare->spare_guid = vd->vdev_guid;
472 		spare->spare_count = 1;
473 		avl_insert(&spa_spare_avl, spare, where);
474 	}
475 	vd->vdev_isspare = B_TRUE;
476 
477 	mutex_exit(&spa_spare_lock);
478 }
479 
480 void
481 spa_spare_remove(vdev_t *vd)
482 {
483 	spa_spare_t search;
484 	spa_spare_t *spare;
485 	avl_index_t where;
486 
487 	mutex_enter(&spa_spare_lock);
488 
489 	search.spare_guid = vd->vdev_guid;
490 	spare = avl_find(&spa_spare_avl, &search, &where);
491 
492 	ASSERT(vd->vdev_isspare);
493 	ASSERT(spare != NULL);
494 
495 	if (--spare->spare_count == 0) {
496 		avl_remove(&spa_spare_avl, spare);
497 		kmem_free(spare, sizeof (spa_spare_t));
498 	} else if (spare->spare_pool == spa_guid(vd->vdev_spa)) {
499 		spare->spare_pool = 0ULL;
500 	}
501 
502 	vd->vdev_isspare = B_FALSE;
503 	mutex_exit(&spa_spare_lock);
504 }
505 
506 boolean_t
507 spa_spare_exists(uint64_t guid, uint64_t *pool)
508 {
509 	spa_spare_t search, *found;
510 	avl_index_t where;
511 
512 	mutex_enter(&spa_spare_lock);
513 
514 	search.spare_guid = guid;
515 	found = avl_find(&spa_spare_avl, &search, &where);
516 
517 	if (pool) {
518 		if (found)
519 			*pool = found->spare_pool;
520 		else
521 			*pool = 0ULL;
522 	}
523 
524 	mutex_exit(&spa_spare_lock);
525 
526 	return (found != NULL);
527 }
528 
529 void
530 spa_spare_activate(vdev_t *vd)
531 {
532 	spa_spare_t search, *found;
533 	avl_index_t where;
534 
535 	mutex_enter(&spa_spare_lock);
536 	ASSERT(vd->vdev_isspare);
537 
538 	search.spare_guid = vd->vdev_guid;
539 	found = avl_find(&spa_spare_avl, &search, &where);
540 	ASSERT(found != NULL);
541 	ASSERT(found->spare_pool == 0ULL);
542 
543 	found->spare_pool = spa_guid(vd->vdev_spa);
544 	mutex_exit(&spa_spare_lock);
545 }
546 
547 /*
548  * ==========================================================================
549  * SPA config locking
550  * ==========================================================================
551  */
552 void
553 spa_config_enter(spa_t *spa, krw_t rw, void *tag)
554 {
555 	rprw_enter(&spa->spa_config_lock, rw, tag);
556 }
557 
558 void
559 spa_config_exit(spa_t *spa, void *tag)
560 {
561 	rprw_exit(&spa->spa_config_lock, tag);
562 }
563 
564 boolean_t
565 spa_config_held(spa_t *spa, krw_t rw)
566 {
567 	return (rprw_held(&spa->spa_config_lock, rw));
568 }
569 
570 /*
571  * ==========================================================================
572  * SPA vdev locking
573  * ==========================================================================
574  */
575 
576 /*
577  * Lock the given spa_t for the purpose of adding or removing a vdev.
578  * Grabs the global spa_namespace_lock plus the spa config lock for writing.
579  * It returns the next transaction group for the spa_t.
580  */
581 uint64_t
582 spa_vdev_enter(spa_t *spa)
583 {
584 	mutex_enter(&spa_namespace_lock);
585 
586 	/*
587 	 * Suspend scrub activity while we mess with the config.  We must do
588 	 * this after acquiring the namespace lock to avoid a 3-way deadlock
589 	 * with spa_scrub_stop() and the scrub thread.
590 	 */
591 	spa_scrub_suspend(spa);
592 
593 	spa_config_enter(spa, RW_WRITER, spa);
594 
595 	return (spa_last_synced_txg(spa) + 1);
596 }
597 
598 /*
599  * Unlock the spa_t after adding or removing a vdev.  Besides undoing the
600  * locking of spa_vdev_enter(), we also want make sure the transactions have
601  * synced to disk, and then update the global configuration cache with the new
602  * information.
603  */
604 int
605 spa_vdev_exit(spa_t *spa, vdev_t *vd, uint64_t txg, int error)
606 {
607 	int config_changed = B_FALSE;
608 
609 	ASSERT(txg > spa_last_synced_txg(spa));
610 
611 	/*
612 	 * Reassess the DTLs.
613 	 */
614 	vdev_dtl_reassess(spa->spa_root_vdev, 0, 0, B_FALSE);
615 
616 	/*
617 	 * If the config changed, notify the scrub thread that it must restart.
618 	 */
619 	if (error == 0 && !list_is_empty(&spa->spa_dirty_list)) {
620 		config_changed = B_TRUE;
621 		spa_scrub_restart(spa, txg);
622 	}
623 
624 	spa_config_exit(spa, spa);
625 
626 	/*
627 	 * Allow scrubbing to resume.
628 	 */
629 	spa_scrub_resume(spa);
630 
631 	/*
632 	 * Note: this txg_wait_synced() is important because it ensures
633 	 * that there won't be more than one config change per txg.
634 	 * This allows us to use the txg as the generation number.
635 	 */
636 	if (error == 0)
637 		txg_wait_synced(spa->spa_dsl_pool, txg);
638 
639 	if (vd != NULL) {
640 		ASSERT(!vd->vdev_detached || vd->vdev_dtl.smo_object == 0);
641 		vdev_free(vd);
642 	}
643 
644 	/*
645 	 * If the config changed, update the config cache.
646 	 */
647 	if (config_changed)
648 		spa_config_sync();
649 
650 	mutex_exit(&spa_namespace_lock);
651 
652 	return (error);
653 }
654 
655 /*
656  * ==========================================================================
657  * Miscellaneous functions
658  * ==========================================================================
659  */
660 
661 /*
662  * Rename a spa_t.
663  */
664 int
665 spa_rename(const char *name, const char *newname)
666 {
667 	spa_t *spa;
668 	int err;
669 
670 	/*
671 	 * Lookup the spa_t and grab the config lock for writing.  We need to
672 	 * actually open the pool so that we can sync out the necessary labels.
673 	 * It's OK to call spa_open() with the namespace lock held because we
674 	 * allow recursive calls for other reasons.
675 	 */
676 	mutex_enter(&spa_namespace_lock);
677 	if ((err = spa_open(name, &spa, FTAG)) != 0) {
678 		mutex_exit(&spa_namespace_lock);
679 		return (err);
680 	}
681 
682 	spa_config_enter(spa, RW_WRITER, FTAG);
683 
684 	avl_remove(&spa_namespace_avl, spa);
685 	spa_strfree(spa->spa_name);
686 	spa->spa_name = spa_strdup(newname);
687 	avl_add(&spa_namespace_avl, spa);
688 
689 	/*
690 	 * Sync all labels to disk with the new names by marking the root vdev
691 	 * dirty and waiting for it to sync.  It will pick up the new pool name
692 	 * during the sync.
693 	 */
694 	vdev_config_dirty(spa->spa_root_vdev);
695 
696 	spa_config_exit(spa, FTAG);
697 
698 	txg_wait_synced(spa->spa_dsl_pool, 0);
699 
700 	/*
701 	 * Sync the updated config cache.
702 	 */
703 	spa_config_sync();
704 
705 	spa_close(spa, FTAG);
706 
707 	mutex_exit(&spa_namespace_lock);
708 
709 	return (0);
710 }
711 
712 
713 /*
714  * Determine whether a pool with given pool_guid exists.  If device_guid is
715  * non-zero, determine whether the pool exists *and* contains a device with the
716  * specified device_guid.
717  */
718 boolean_t
719 spa_guid_exists(uint64_t pool_guid, uint64_t device_guid)
720 {
721 	spa_t *spa;
722 	avl_tree_t *t = &spa_namespace_avl;
723 
724 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
725 
726 	for (spa = avl_first(t); spa != NULL; spa = AVL_NEXT(t, spa)) {
727 		if (spa->spa_state == POOL_STATE_UNINITIALIZED)
728 			continue;
729 		if (spa->spa_root_vdev == NULL)
730 			continue;
731 		if (spa_guid(spa) == pool_guid) {
732 			if (device_guid == 0)
733 				break;
734 
735 			if (vdev_lookup_by_guid(spa->spa_root_vdev,
736 			    device_guid) != NULL)
737 				break;
738 
739 			/*
740 			 * Check any devices we may be in the process of adding.
741 			 */
742 			if (spa->spa_pending_vdev) {
743 				if (vdev_lookup_by_guid(spa->spa_pending_vdev,
744 				    device_guid) != NULL)
745 					break;
746 			}
747 		}
748 	}
749 
750 	return (spa != NULL);
751 }
752 
753 char *
754 spa_strdup(const char *s)
755 {
756 	size_t len;
757 	char *new;
758 
759 	len = strlen(s);
760 	new = kmem_alloc(len + 1, KM_SLEEP);
761 	bcopy(s, new, len);
762 	new[len] = '\0';
763 
764 	return (new);
765 }
766 
767 void
768 spa_strfree(char *s)
769 {
770 	kmem_free(s, strlen(s) + 1);
771 }
772 
773 uint64_t
774 spa_get_random(uint64_t range)
775 {
776 	uint64_t r;
777 
778 	ASSERT(range != 0);
779 
780 	(void) random_get_pseudo_bytes((void *)&r, sizeof (uint64_t));
781 
782 	return (r % range);
783 }
784 
785 void
786 sprintf_blkptr(char *buf, int len, const blkptr_t *bp)
787 {
788 	int d;
789 
790 	if (bp == NULL) {
791 		(void) snprintf(buf, len, "<NULL>");
792 		return;
793 	}
794 
795 	if (BP_IS_HOLE(bp)) {
796 		(void) snprintf(buf, len, "<hole>");
797 		return;
798 	}
799 
800 	(void) snprintf(buf, len, "[L%llu %s] %llxL/%llxP ",
801 	    (u_longlong_t)BP_GET_LEVEL(bp),
802 	    dmu_ot[BP_GET_TYPE(bp)].ot_name,
803 	    (u_longlong_t)BP_GET_LSIZE(bp),
804 	    (u_longlong_t)BP_GET_PSIZE(bp));
805 
806 	for (d = 0; d < BP_GET_NDVAS(bp); d++) {
807 		const dva_t *dva = &bp->blk_dva[d];
808 		(void) snprintf(buf + strlen(buf), len - strlen(buf),
809 		    "DVA[%d]=<%llu:%llx:%llx> ", d,
810 		    (u_longlong_t)DVA_GET_VDEV(dva),
811 		    (u_longlong_t)DVA_GET_OFFSET(dva),
812 		    (u_longlong_t)DVA_GET_ASIZE(dva));
813 	}
814 
815 	(void) snprintf(buf + strlen(buf), len - strlen(buf),
816 	    "%s %s %s %s birth=%llu fill=%llu cksum=%llx:%llx:%llx:%llx",
817 	    zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_name,
818 	    zio_compress_table[BP_GET_COMPRESS(bp)].ci_name,
819 	    BP_GET_BYTEORDER(bp) == 0 ? "BE" : "LE",
820 	    BP_IS_GANG(bp) ? "gang" : "contiguous",
821 	    (u_longlong_t)bp->blk_birth,
822 	    (u_longlong_t)bp->blk_fill,
823 	    (u_longlong_t)bp->blk_cksum.zc_word[0],
824 	    (u_longlong_t)bp->blk_cksum.zc_word[1],
825 	    (u_longlong_t)bp->blk_cksum.zc_word[2],
826 	    (u_longlong_t)bp->blk_cksum.zc_word[3]);
827 }
828 
829 void
830 spa_freeze(spa_t *spa)
831 {
832 	uint64_t freeze_txg = 0;
833 
834 	spa_config_enter(spa, RW_WRITER, FTAG);
835 	if (spa->spa_freeze_txg == UINT64_MAX) {
836 		freeze_txg = spa_last_synced_txg(spa) + TXG_SIZE;
837 		spa->spa_freeze_txg = freeze_txg;
838 	}
839 	spa_config_exit(spa, FTAG);
840 	if (freeze_txg != 0)
841 		txg_wait_synced(spa_get_dsl(spa), freeze_txg);
842 }
843 
844 void
845 zfs_panic_recover(const char *fmt, ...)
846 {
847 	va_list adx;
848 
849 	va_start(adx, fmt);
850 	vcmn_err(zfs_recover ? CE_WARN : CE_PANIC, fmt, adx);
851 	va_end(adx);
852 }
853 
854 /*
855  * ==========================================================================
856  * Accessor functions
857  * ==========================================================================
858  */
859 
860 krwlock_t *
861 spa_traverse_rwlock(spa_t *spa)
862 {
863 	return (&spa->spa_traverse_lock);
864 }
865 
866 int
867 spa_traverse_wanted(spa_t *spa)
868 {
869 	return (spa->spa_traverse_wanted);
870 }
871 
872 dsl_pool_t *
873 spa_get_dsl(spa_t *spa)
874 {
875 	return (spa->spa_dsl_pool);
876 }
877 
878 blkptr_t *
879 spa_get_rootblkptr(spa_t *spa)
880 {
881 	return (&spa->spa_ubsync.ub_rootbp);
882 }
883 
884 void
885 spa_set_rootblkptr(spa_t *spa, const blkptr_t *bp)
886 {
887 	spa->spa_uberblock.ub_rootbp = *bp;
888 }
889 
890 void
891 spa_altroot(spa_t *spa, char *buf, size_t buflen)
892 {
893 	if (spa->spa_root == NULL)
894 		buf[0] = '\0';
895 	else
896 		(void) strncpy(buf, spa->spa_root, buflen);
897 }
898 
899 int
900 spa_sync_pass(spa_t *spa)
901 {
902 	return (spa->spa_sync_pass);
903 }
904 
905 char *
906 spa_name(spa_t *spa)
907 {
908 	/*
909 	 * Accessing the name requires holding either the namespace lock or the
910 	 * config lock, both of which are required to do a rename.
911 	 */
912 	ASSERT(MUTEX_HELD(&spa_namespace_lock) ||
913 	    spa_config_held(spa, RW_READER) || spa_config_held(spa, RW_WRITER));
914 
915 	return (spa->spa_name);
916 }
917 
918 uint64_t
919 spa_guid(spa_t *spa)
920 {
921 	/*
922 	 * If we fail to parse the config during spa_load(), we can go through
923 	 * the error path (which posts an ereport) and end up here with no root
924 	 * vdev.  We stash the original pool guid in 'spa_load_guid' to handle
925 	 * this case.
926 	 */
927 	if (spa->spa_root_vdev != NULL)
928 		return (spa->spa_root_vdev->vdev_guid);
929 	else
930 		return (spa->spa_load_guid);
931 }
932 
933 uint64_t
934 spa_last_synced_txg(spa_t *spa)
935 {
936 	return (spa->spa_ubsync.ub_txg);
937 }
938 
939 uint64_t
940 spa_first_txg(spa_t *spa)
941 {
942 	return (spa->spa_first_txg);
943 }
944 
945 int
946 spa_state(spa_t *spa)
947 {
948 	return (spa->spa_state);
949 }
950 
951 uint64_t
952 spa_freeze_txg(spa_t *spa)
953 {
954 	return (spa->spa_freeze_txg);
955 }
956 
957 /*
958  * Return how much space is allocated in the pool (ie. sum of all asize)
959  */
960 uint64_t
961 spa_get_alloc(spa_t *spa)
962 {
963 	return (spa->spa_root_vdev->vdev_stat.vs_alloc);
964 }
965 
966 /*
967  * Return how much (raid-z inflated) space there is in the pool.
968  */
969 uint64_t
970 spa_get_space(spa_t *spa)
971 {
972 	return (spa->spa_root_vdev->vdev_stat.vs_space);
973 }
974 
975 /*
976  * Return the amount of raid-z-deflated space in the pool.
977  */
978 uint64_t
979 spa_get_dspace(spa_t *spa)
980 {
981 	if (spa->spa_deflate)
982 		return (spa->spa_root_vdev->vdev_stat.vs_dspace);
983 	else
984 		return (spa->spa_root_vdev->vdev_stat.vs_space);
985 }
986 
987 /* ARGSUSED */
988 uint64_t
989 spa_get_asize(spa_t *spa, uint64_t lsize)
990 {
991 	/*
992 	 * For now, the worst case is 512-byte RAID-Z blocks, in which
993 	 * case the space requirement is exactly 2x; so just assume that.
994 	 * Add to this the fact that we can have up to 3 DVAs per bp, and
995 	 * we have to multiply by a total of 6x.
996 	 */
997 	return (lsize * 6);
998 }
999 
1000 /*
1001  * Return the failure mode that has been set to this pool. The default
1002  * behavior will be to block all I/Os when a complete failure occurs.
1003  */
1004 uint8_t
1005 spa_get_failmode(spa_t *spa)
1006 {
1007 	return (spa->spa_failmode);
1008 }
1009 
1010 uint64_t
1011 spa_version(spa_t *spa)
1012 {
1013 	return (spa->spa_ubsync.ub_version);
1014 }
1015 
1016 int
1017 spa_max_replication(spa_t *spa)
1018 {
1019 	/*
1020 	 * As of SPA_VERSION == SPA_VERSION_DITTO_BLOCKS, we are able to
1021 	 * handle BPs with more than one DVA allocated.  Set our max
1022 	 * replication level accordingly.
1023 	 */
1024 	if (spa_version(spa) < SPA_VERSION_DITTO_BLOCKS)
1025 		return (1);
1026 	return (MIN(SPA_DVAS_PER_BP, spa_max_replication_override));
1027 }
1028 
1029 uint64_t
1030 bp_get_dasize(spa_t *spa, const blkptr_t *bp)
1031 {
1032 	int sz = 0, i;
1033 
1034 	if (!spa->spa_deflate)
1035 		return (BP_GET_ASIZE(bp));
1036 
1037 	spa_config_enter(spa, RW_READER, FTAG);
1038 	for (i = 0; i < SPA_DVAS_PER_BP; i++) {
1039 		vdev_t *vd =
1040 		    vdev_lookup_top(spa, DVA_GET_VDEV(&bp->blk_dva[i]));
1041 		if (vd)
1042 			sz += (DVA_GET_ASIZE(&bp->blk_dva[i]) >>
1043 			    SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio;
1044 	}
1045 	spa_config_exit(spa, FTAG);
1046 	return (sz);
1047 }
1048 
1049 /*
1050  * ==========================================================================
1051  * Initialization and Termination
1052  * ==========================================================================
1053  */
1054 
1055 static int
1056 spa_name_compare(const void *a1, const void *a2)
1057 {
1058 	const spa_t *s1 = a1;
1059 	const spa_t *s2 = a2;
1060 	int s;
1061 
1062 	s = strcmp(s1->spa_name, s2->spa_name);
1063 	if (s > 0)
1064 		return (1);
1065 	if (s < 0)
1066 		return (-1);
1067 	return (0);
1068 }
1069 
1070 int
1071 spa_busy(void)
1072 {
1073 	return (spa_active_count);
1074 }
1075 
1076 void
1077 spa_init(int mode)
1078 {
1079 	mutex_init(&spa_namespace_lock, NULL, MUTEX_DEFAULT, NULL);
1080 	mutex_init(&spa_spare_lock, NULL, MUTEX_DEFAULT, NULL);
1081 	cv_init(&spa_namespace_cv, NULL, CV_DEFAULT, NULL);
1082 
1083 	avl_create(&spa_namespace_avl, spa_name_compare, sizeof (spa_t),
1084 	    offsetof(spa_t, spa_avl));
1085 
1086 	avl_create(&spa_spare_avl, spa_spare_compare, sizeof (spa_spare_t),
1087 	    offsetof(spa_spare_t, spare_avl));
1088 
1089 	spa_mode = mode;
1090 
1091 	refcount_init();
1092 	unique_init();
1093 	zio_init();
1094 	dmu_init();
1095 	zil_init();
1096 	zfs_prop_init();
1097 	zpool_prop_init();
1098 	spa_config_load();
1099 }
1100 
1101 void
1102 spa_fini(void)
1103 {
1104 	spa_evict_all();
1105 
1106 	zil_fini();
1107 	dmu_fini();
1108 	zio_fini();
1109 	unique_fini();
1110 	refcount_fini();
1111 
1112 	avl_destroy(&spa_namespace_avl);
1113 	avl_destroy(&spa_spare_avl);
1114 
1115 	cv_destroy(&spa_namespace_cv);
1116 	mutex_destroy(&spa_namespace_lock);
1117 	mutex_destroy(&spa_spare_lock);
1118 }
1119 
1120 /*
1121  * Return whether this pool has slogs. No locking needed.
1122  * It's not a problem if the wrong answer is returned as it's only for
1123  * performance and not correctness
1124  */
1125 boolean_t
1126 spa_has_slogs(spa_t *spa)
1127 {
1128 	return (spa->spa_log_class->mc_rotor != NULL);
1129 }
1130