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