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