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