1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3 * This file and its contents are supplied under the terms of the
4 * Common Development and Distribution License ("CDDL"), version 1.0.
5 * You may only use this file in accordance with the terms of version
6 * 1.0 of the CDDL.
7 *
8 * A full copy of the text of the CDDL should have accompanied this
9 * source. A copy of the CDDL is also available via the Internet at
10 * https://opensource.org/license/CDDL-1.0.
11 */
12 /*
13 * Copyright 2007 Sun Microsystems, Inc. All rights reserved.
14 * Use is subject to license terms.
15 */
16
17
18
19 #include <sys/zfs_context.h>
20 #include <sys/avl.h>
21 #include <sys/unique.h>
22
23 static avl_tree_t unique_avl;
24 static kmutex_t unique_mtx;
25
26 typedef struct unique {
27 avl_node_t un_link;
28 uint64_t un_value;
29 } unique_t;
30
31 #define UNIQUE_MASK ((1ULL << UNIQUE_BITS) - 1)
32
33 static int
unique_compare(const void * a,const void * b)34 unique_compare(const void *a, const void *b)
35 {
36 const unique_t *una = (const unique_t *)a;
37 const unique_t *unb = (const unique_t *)b;
38
39 return (TREE_CMP(una->un_value, unb->un_value));
40 }
41
42 void
unique_init(void)43 unique_init(void)
44 {
45 avl_create(&unique_avl, unique_compare,
46 sizeof (unique_t), offsetof(unique_t, un_link));
47 mutex_init(&unique_mtx, NULL, MUTEX_DEFAULT, NULL);
48 }
49
50 void
unique_fini(void)51 unique_fini(void)
52 {
53 avl_destroy(&unique_avl);
54 mutex_destroy(&unique_mtx);
55 }
56
57 uint64_t
unique_create(void)58 unique_create(void)
59 {
60 uint64_t value = unique_insert(0);
61 unique_remove(value);
62 return (value);
63 }
64
65 uint64_t
unique_insert(uint64_t value)66 unique_insert(uint64_t value)
67 {
68 avl_index_t idx;
69 unique_t *un = kmem_alloc(sizeof (unique_t), KM_SLEEP);
70
71 un->un_value = value;
72
73 mutex_enter(&unique_mtx);
74 while (un->un_value == 0 || un->un_value & ~UNIQUE_MASK ||
75 avl_find(&unique_avl, un, &idx)) {
76 mutex_exit(&unique_mtx);
77 (void) random_get_pseudo_bytes((void*)&un->un_value,
78 sizeof (un->un_value));
79 un->un_value &= UNIQUE_MASK;
80 mutex_enter(&unique_mtx);
81 }
82
83 avl_insert(&unique_avl, un, idx);
84 mutex_exit(&unique_mtx);
85
86 return (un->un_value);
87 }
88
89 void
unique_remove(uint64_t value)90 unique_remove(uint64_t value)
91 {
92 unique_t un_tofind;
93 unique_t *un;
94
95 un_tofind.un_value = value;
96 mutex_enter(&unique_mtx);
97 un = avl_find(&unique_avl, &un_tofind, NULL);
98 if (un != NULL) {
99 avl_remove(&unique_avl, un);
100 kmem_free(un, sizeof (unique_t));
101 }
102 mutex_exit(&unique_mtx);
103 }
104