xref: /illumos-gate/usr/src/uts/common/fs/zfs/unique.c (revision f498645a3eecf2ddd304b4ea9c7f1b4c155ff79e)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/zfs_context.h>
30 #include <sys/avl.h>
31 #include <sys/unique.h>
32 
33 static avl_tree_t unique_avl;
34 static kmutex_t unique_mtx;
35 
36 typedef struct unique {
37 	avl_node_t un_link;
38 	uint64_t un_value;
39 } unique_t;
40 
41 #define	UNIQUE_MASK ((1ULL << UNIQUE_BITS) - 1)
42 
43 static int
44 unique_compare(const void *a, const void *b)
45 {
46 	const unique_t *una = a;
47 	const unique_t *unb = b;
48 
49 	if (una->un_value < unb->un_value)
50 		return (-1);
51 	if (una->un_value > unb->un_value)
52 		return (+1);
53 	return (0);
54 }
55 
56 void
57 unique_init(void)
58 {
59 	avl_create(&unique_avl, unique_compare,
60 	    sizeof (unique_t), offsetof(unique_t, un_link));
61 }
62 
63 uint64_t
64 unique_create(void)
65 {
66 	return (unique_insert(0));
67 }
68 
69 uint64_t
70 unique_insert(uint64_t value)
71 {
72 	avl_index_t idx;
73 	unique_t *un = kmem_alloc(sizeof (unique_t), KM_SLEEP);
74 
75 	un->un_value = value;
76 
77 	mutex_enter(&unique_mtx);
78 	while (un->un_value == 0 || un->un_value & ~UNIQUE_MASK ||
79 	    avl_find(&unique_avl, un, &idx)) {
80 		mutex_exit(&unique_mtx);
81 		(void) random_get_pseudo_bytes((void*)&un->un_value,
82 		    sizeof (un->un_value));
83 		un->un_value &= UNIQUE_MASK;
84 		mutex_enter(&unique_mtx);
85 	}
86 
87 	avl_insert(&unique_avl, un, idx);
88 	mutex_exit(&unique_mtx);
89 
90 	return (un->un_value);
91 }
92 
93 void
94 unique_remove(uint64_t value)
95 {
96 	unique_t un_tofind;
97 	unique_t *un;
98 
99 	un_tofind.un_value = value;
100 	mutex_enter(&unique_mtx);
101 	un = avl_find(&unique_avl, &un_tofind, NULL);
102 	if (un != NULL) {
103 		avl_remove(&unique_avl, un);
104 		kmem_free(un, sizeof (unique_t));
105 	}
106 	mutex_exit(&unique_mtx);
107 }
108