2 * Written by Josh Dybnis and released to the public domain, as explained at
3 * http://creativecommons.org/licenses/publicdomain
5 * C implementation of Cliff Click's lock-free hash table from
6 * http://www.azulsystems.com/events/javaone_2008/2008_CodingNonBlock.pdf
7 * http://sourceforge.net/projects/high-scale-lib
9 * Note: This is code uses synchronous atomic operations because that is all that x86 provides.
10 * Every atomic operation is also an implicit full memory barrier. The upshot is that it simplifies
11 * the code a bit, but it won't be as fast as it could be on platforms like SPARC that provide
12 * weaker operations which would still do the job.
21 #define GET_PTR(x) ((void *)((x) & MASK(48))) // low-order 48 bits is a pointer to a nstring_t
23 typedef struct ht_entry {
29 volatile entry_t *table;
30 hashtable_t *ht; // parent ht;
34 int count; // TODO: make these counters distributed
35 int num_entries_copied;
43 clone_fun_t clone_fun;
46 static const map_impl_t ht_map_impl = {
47 (map_alloc_t)ht_alloc, (map_cas_t)ht_cas, (map_get_t)ht_get, (map_remove_t)ht_remove,
48 (map_count_t)ht_count, (map_print_t)ht_print, (map_free_t)ht_free
51 const map_impl_t *MAP_TYPE_HASHTABLE = &ht_map_impl;
53 static const uint64_t COPIED_VALUE = -1;
54 static const uint64_t TOMBSTONE = STRIP_TAG(-1);
56 static const unsigned ENTRIES_PER_BUCKET = CACHE_LINE_SIZE/sizeof(entry_t);
57 static const unsigned ENTRIES_PER_COPY_CHUNK = CACHE_LINE_SIZE/sizeof(entry_t)*2;
58 static const unsigned MIN_SCALE = 4; // min 16 entries (4 buckets)
59 static const unsigned MAX_BUCKETS_TO_PROBE = 250;
61 static int hti_copy_entry (hti_t *ht1, volatile entry_t *ent, uint32_t ent_key_hash, hti_t *ht2);
63 // Choose the next bucket to probe using the high-order bits of <key_hash>.
64 static inline int get_next_ndx(int old_ndx, uint32_t key_hash, int ht_scale) {
65 int incr = (key_hash >> (32 - ht_scale));
66 incr += !incr; // If the increment is 0, make it 1.
67 return (old_ndx + incr) & MASK(ht_scale);
70 // Lookup <key> in <hti>.
72 // Return the entry that <key> is in, or if <key> isn't in <hti> return the entry that it would be
73 // in if it were inserted into <hti>. If there is no room for <key> in <hti> then return NULL, to
74 // indicate that the caller should look in <hti->next>.
76 // Record if the entry being returned is empty. Otherwise the caller will have to waste time
77 // re-comparing the keys to confirm that it did not lose a race to fill an empty entry.
78 static volatile entry_t *hti_lookup (hti_t *hti, void *key, uint32_t key_hash, int *is_empty) {
79 TRACE("h2", "hti_lookup(key %p in hti %p)", key, hti);
82 // Probe one cache line at a time
83 int ndx = key_hash & MASK(hti->scale); // the first entry to search
84 for (int i = 0; i < hti->max_probe; ++i) {
86 // The start of the bucket is the first entry in the cache line.
87 volatile entry_t *bucket = hti->table + (ndx & ~(ENTRIES_PER_BUCKET-1));
89 // Start searching at the indexed entry. Then loop around to the begining of the cache line.
90 for (int j = 0; j < ENTRIES_PER_BUCKET; ++j) {
91 volatile entry_t *ent = bucket + ((ndx + j) & (ENTRIES_PER_BUCKET-1));
93 uint64_t ent_key = ent->key;
94 if (ent_key == DOES_NOT_EXIST) {
95 TRACE("h1", "hti_lookup: entry %p for key %p is empty", ent,
96 (hti->ht->clone_fun == NULL) ? (void *)ent_key : GET_PTR(ent_key));
97 *is_empty = 1; // indicate an empty so the caller avoids an expensive key compare
101 // Compare <key> with the key in the entry.
102 if (EXPECT_TRUE(hti->ht->cmp_fun == NULL)) {
103 // fast path for integer keys
104 if (ent_key == (uint64_t)key) {
105 TRACE("h1", "hti_lookup: found entry %p with key %p", ent, ent_key);
109 // The key in <ent> is made up of two parts. The 48 low-order bits are a pointer. The
110 // high-order 16 bits are taken from the hash. The bits from the hash are used as a
111 // quick check to rule out non-equal keys without doing a complete compare.
112 if ((key_hash >> 16) == (ent_key >> 48) && hti->ht->cmp_fun(GET_PTR(ent_key), key) == 0) {
113 TRACE("h1", "hti_lookup: found entry %p with key %p", ent, GET_PTR(ent_key));
119 ndx = get_next_ndx(ndx, key_hash, hti->scale);
122 // maximum number of probes exceeded
123 TRACE("h1", "hti_lookup: maximum number of probes exceeded returning 0x0", 0, 0);
127 // Allocate and initialize a hti_t with 2^<scale> entries.
128 static hti_t *hti_alloc (hashtable_t *parent, int scale) {
129 // Include enough slop to align the actual table on a cache line boundry
130 size_t n = sizeof(hti_t)
131 + sizeof(entry_t) * (1 << scale)
132 + (CACHE_LINE_SIZE - 1);
133 hti_t *hti = (hti_t *)calloc(n, 1);
135 // Align the table of hash entries on a cache line boundry.
136 hti->table = (entry_t *)(((uint64_t)hti + sizeof(hti_t) + (CACHE_LINE_SIZE-1))
137 & ~(CACHE_LINE_SIZE-1));
141 // When searching for a key probe a maximum of 1/4 of the buckets up to 1000 buckets.
142 hti->max_probe = ((1 << (hti->scale - 2)) / ENTRIES_PER_BUCKET) + 4;
143 if (hti->max_probe > MAX_BUCKETS_TO_PROBE) {
144 hti->max_probe = MAX_BUCKETS_TO_PROBE;
149 assert(hti->scale >= MIN_SCALE && hti->scale < 63); // size must be a power of 2
150 assert(sizeof(entry_t) * ENTRIES_PER_BUCKET % CACHE_LINE_SIZE == 0); // divisible into cache
151 assert((size_t)hti->table % CACHE_LINE_SIZE == 0); // cache aligned
156 // Called when <hti> runs out of room for new keys.
158 // Initiates a copy by creating a larger hti_t and installing it in <hti->next>.
159 static void hti_start_copy (hti_t *hti) {
160 TRACE("h0", "hti_start_copy(hti %p scale %llu)", hti, hti->scale);
162 // heuristics to determine the size of the new table
163 uint64_t count = ht_count(hti->ht);
164 unsigned int new_scale = hti->scale;
165 new_scale += (count > (1 << (new_scale - 2))); // double size if more than 1/4 full
166 new_scale += (count > (1 << (new_scale - 2))); // double size again if more than 1/2 full
168 // Allocate the new table and attempt to install it.
169 hti_t *next = hti_alloc(hti->ht, new_scale);
170 hti_t *old_next = SYNC_CAS(&hti->next, NULL, next);
171 if (old_next != NULL) {
172 // Another thread beat us to it.
173 TRACE("h0", "hti_start_copy: lost race to install new hti; found %p", old_next, 0);
177 TRACE("h0", "hti_start_copy: new hti %p scale %llu", next, next->scale);
180 // Copy the key and value stored in <ht1_ent> (which must be an entry in <ht1>) to <ht2>.
182 // Return 1 unless <ht1_ent> is already copied (then return 0), so the caller can account for the total
183 // number of entries left to copy.
184 static int hti_copy_entry (hti_t *ht1, volatile entry_t *ht1_ent, uint32_t key_hash, hti_t *ht2) {
185 TRACE("h2", "hti_copy_entry: entry %p to table %p", ht1_ent, ht2);
189 assert(ht1_ent >= ht1->table && ht1_ent < ht1->table + (1 << ht1->scale));
190 assert(key_hash == 0 || ht1->ht->hash_fun == NULL || (key_hash >> 16) == (ht1_ent->key >> 48));
192 uint64_t ht1_ent_val = ht1_ent->val;
193 if (EXPECT_FALSE(ht1_ent_val == COPIED_VALUE)) {
194 TRACE("h1", "hti_copy_entry: entry %p already copied to table %p", ht1_ent, ht2);
195 return FALSE; // already copied
198 // Kill empty entries.
199 if (EXPECT_FALSE(ht1_ent_val == DOES_NOT_EXIST)) {
200 uint64_t ht1_ent_val = SYNC_CAS(&ht1_ent->val, DOES_NOT_EXIST, COPIED_VALUE);
201 if (ht1_ent_val == DOES_NOT_EXIST) {
202 TRACE("h1", "hti_copy_entry: empty entry %p killed", ht1_ent, 0);
205 if (ht1_ent_val == COPIED_VALUE) {
206 TRACE("h0", "hti_copy_entry: lost race to kill empty entry %p; the entry is already killed", ht1_ent, 0);
207 return FALSE; // another thread beat us to it
209 TRACE("h0", "hti_copy_entry: lost race to kill empty entry %p; the entry is not empty", ht1_ent, 0);
212 // Tag the value in the old entry to indicate a copy is in progress.
213 ht1_ent_val = SYNC_FETCH_AND_OR(&ht1_ent->val, TAG_VALUE(0));
214 TRACE("h2", "hti_copy_entry: tagged the value %p in old entry %p", ht1_ent_val, ht1_ent);
215 if (ht1_ent_val == COPIED_VALUE) {
216 TRACE("h1", "hti_copy_entry: entry %p already copied to table %p", ht1_ent, ht2);
217 return FALSE; // <value> was already copied by another thread.
220 // Install the key in the new table.
221 uint64_t ht1_ent_key = ht1_ent->key;
222 void *key = (ht1->ht->hash_fun == NULL) ? (void *)ht1_ent_key : GET_PTR(ht1_ent_key);
224 // The old table's dead entries don't need to be copied to the new table, but their keys need to be freed.
225 assert(COPIED_VALUE == TAG_VALUE(TOMBSTONE));
226 if (ht1_ent_val == TOMBSTONE) {
227 TRACE("h1", "hti_copy_entry: entry %p old value was deleted, now freeing key %p", ht1_ent, key);
228 if (EXPECT_FALSE(ht1->ht->clone_fun != NULL)) {
234 // We use 0 to indicate that <key_hash> is uninitiallized. Occasionally the key's hash will really be 0 and we
235 // waste time recomputing it every time. It is rare enough (1 in 65k) that it won't hurt performance.
237 key_hash = (ht1->ht->hash_fun == NULL) ? murmur32_8b(ht1_ent_key) : ht1->ht->hash_fun(key);
240 int ht2_ent_is_empty;
241 volatile entry_t *ht2_ent = hti_lookup(ht2, key, key_hash, &ht2_ent_is_empty);
242 TRACE("h0", "hti_copy_entry: copy entry %p to entry %p", ht1_ent, ht2_ent);
244 // It is possible that there isn't any room in the new table either.
245 if (EXPECT_FALSE(ht2_ent == NULL)) {
246 TRACE("h0", "hti_copy_entry: no room in table %p copy to next table %p", ht2, ht2->next);
247 if (ht2->next == NULL) {
248 hti_start_copy(ht2); // initiate nested copy, if not already started
250 return hti_copy_entry(ht1, ht1_ent, key_hash, ht2->next); // recursive tail-call
253 if (ht2_ent_is_empty) {
254 uint64_t old_ht2_ent_key = SYNC_CAS(&ht2_ent->key, DOES_NOT_EXIST, ht1_ent_key);
255 if (old_ht2_ent_key != DOES_NOT_EXIST) {
256 TRACE("h0", "hti_copy_entry: lost race to CAS key %p into new entry; found %p",
257 ht1_ent_key, old_ht2_ent_key);
258 return hti_copy_entry(ht1, ht1_ent, key_hash, ht2); // recursive tail-call
262 // Copy the value to the entry in the new table.
263 ht1_ent_val = STRIP_TAG(ht1_ent_val);
264 uint64_t old_ht2_ent_val = SYNC_CAS(&ht2_ent->val, DOES_NOT_EXIST, ht1_ent_val);
266 // If there is a nested copy in progress, we might have installed the key into a dead entry.
267 if (old_ht2_ent_val == COPIED_VALUE) {
268 TRACE("h0", "hti_copy_entry: nested copy in progress; copy %p to next table %p", ht2_ent, ht2->next);
269 return hti_copy_entry(ht1, ht1_ent, key_hash, ht2->next); // recursive tail-call
272 // Mark the old entry as dead.
273 ht1_ent->val = COPIED_VALUE;
275 // Update the count if we were the one that completed the copy.
276 if (old_ht2_ent_val == DOES_NOT_EXIST) {
277 TRACE("h0", "hti_copy_entry: key %p value %p copied to new entry", key, ht1_ent_val);
278 SYNC_ADD(&ht1->count, -1);
279 SYNC_ADD(&ht2->count, 1);
283 TRACE("h0", "hti_copy_entry: lost race to install value %p in new entry; found value %p",
284 ht1_ent_val, old_ht2_ent_val);
285 return FALSE; // another thread completed the copy
288 // Compare <expected> with the existing value associated with <key>. If the values match then
289 // replace the existing value with <new>. If <new> is TOMBSTONE, delete the value associated with
290 // the key by replacing it with a TOMBSTONE.
292 // Return the previous value associated with <key>, or DOES_NOT_EXIST if <key> is not in the table
293 // or associated with a TOMBSTONE. If a copy is in progress and <key> has been copied to the next
294 // table then return COPIED_VALUE.
296 // NOTE: the returned value matches <expected> iff the set succeeds
298 // Certain values of <expected> have special meaning. If <expected> is CAS_EXPECT_EXISTS then any
299 // real value matches (i.ent. not a TOMBSTONE or DOES_NOT_EXIST) as long as <key> is in the table. If
300 // <expected> is CAS_EXPECT_WHATEVER then skip the test entirely.
302 static uint64_t hti_cas (hti_t *hti, void *key, uint32_t key_hash, uint64_t expected, uint64_t new) {
303 TRACE("h1", "hti_cas: hti %p key %p", hti, key);
304 TRACE("h1", "hti_cas: value %p expect %p", new, expected);
306 assert(new != DOES_NOT_EXIST && !IS_TAGGED(new));
310 volatile entry_t *ent = hti_lookup(hti, key, key_hash, &is_empty);
312 // There is no room for <key>, grow the table and try again.
314 if (hti->next == NULL) {
320 // Install <key> in the table if it doesn't exist.
322 TRACE("h0", "hti_cas: entry %p is empty", ent, 0);
323 if (expected != CAS_EXPECT_WHATEVER && expected != CAS_EXPECT_DOES_NOT_EXIST)
324 return DOES_NOT_EXIST;
326 // No need to do anything, <key> is already deleted.
327 if (new == TOMBSTONE)
328 return DOES_NOT_EXIST;
330 // Allocate <new_key>.
331 uint64_t new_key = (uint64_t)((hti->ht->clone_fun == NULL) ? key : hti->ht->clone_fun(key));
332 if (EXPECT_FALSE(hti->ht->hash_fun != NULL)) {
333 // Combine <new_key> pointer with bits from its hash
334 new_key = ((uint64_t)(key_hash >> 16) << 48) | new_key;
337 // CAS the key into the table.
338 uint64_t old_ent_key = SYNC_CAS(&ent->key, DOES_NOT_EXIST, new_key);
340 // Retry if another thread stole the entry out from under us.
341 if (old_ent_key != DOES_NOT_EXIST) {
342 TRACE("h0", "hti_cas: lost race to install key %p in entry %p", new_key, ent);
343 TRACE("h0", "hti_cas: found %p instead of NULL",
344 (hti->ht->clone_fun != NULL) ? (void *)old_ent_key : GET_PTR(old_ent_key), 0);
345 if (hti->ht->clone_fun != NULL) {
346 nbd_free(GET_PTR(new_key));
348 return hti_cas(hti, key, key_hash, expected, new); // tail-call
350 TRACE("h2", "hti_cas: installed key %p in entry %p", new_key, ent);
353 TRACE("h0", "hti_cas: entry for key %p is %p",
354 (hti->ht->clone_fun != NULL) ? (void *)ent->key : GET_PTR(ent->key), ent);
356 // If the entry is in the middle of a copy, the copy must be completed first.
357 uint64_t ent_val = ent->val;
358 if (EXPECT_FALSE(IS_TAGGED(ent_val))) {
359 if (ent_val != COPIED_VALUE) {
360 int did_copy = hti_copy_entry(hti, ent, key_hash, ((volatile hti_t *)hti)->next);
362 SYNC_ADD(&hti->num_entries_copied, 1);
364 TRACE("h0", "hti_cas: value in the middle of a copy, copy completed by %s",
365 (did_copy ? "self" : "other"), 0);
367 TRACE("h0", "hti_cas: value copied to next table, retry on next table", 0, 0);
371 // Fail if the old value is not consistent with the caller's expectation.
372 int old_existed = (ent_val != TOMBSTONE && ent_val != DOES_NOT_EXIST);
373 if (EXPECT_FALSE(expected != CAS_EXPECT_WHATEVER && expected != ent_val)) {
374 if (EXPECT_FALSE(expected != (old_existed ? CAS_EXPECT_EXISTS : CAS_EXPECT_DOES_NOT_EXIST))) {
375 TRACE("h1", "hti_cas: value %p expected by caller not found; found value %p",
381 // No need to update if value is unchanged.
382 if ((new == TOMBSTONE && !old_existed) || ent_val == new) {
383 TRACE("h1", "hti_cas: old value and new value were the same", 0, 0);
387 // CAS the value into the entry. Retry if it fails.
388 uint64_t v = SYNC_CAS(&ent->val, ent_val, new);
389 if (EXPECT_FALSE(v != ent_val)) {
390 TRACE("h0", "hti_cas: value CAS failed; expected %p found %p", ent_val, v);
391 return hti_cas(hti, key, key_hash, expected, new); // recursive tail-call
394 // The set succeeded. Adjust the value count.
395 if (old_existed && new == TOMBSTONE) {
396 SYNC_ADD(&hti->count, -1);
397 } else if (!old_existed && new != TOMBSTONE) {
398 SYNC_ADD(&hti->count, 1);
401 // Return the previous value.
402 TRACE("h0", "hti_cas: CAS succeeded; old value %p new value %p", ent_val, new);
407 static uint64_t hti_get (hti_t *hti, void *key, uint32_t key_hash) {
409 volatile entry_t *ent = hti_lookup(hti, key, key_hash, &is_empty);
411 // When hti_lookup() returns NULL it means we hit the reprobe limit while
412 // searching the table. In that case, if a copy is in progress the key
413 // might exist in the copy.
414 if (EXPECT_FALSE(ent == NULL)) {
415 if (((volatile hti_t *)hti)->next != NULL)
416 return hti_get(hti->next, key, key_hash); // recursive tail-call
417 return DOES_NOT_EXIST;
421 return DOES_NOT_EXIST;
423 // If the entry is being copied, finish the copy and retry on the next table.
424 uint64_t ent_val = ent->val;
425 if (EXPECT_FALSE(IS_TAGGED(ent_val))) {
426 if (EXPECT_FALSE(ent_val != COPIED_VALUE)) {
427 int did_copy = hti_copy_entry(hti, ent, key_hash, ((volatile hti_t *)hti)->next);
429 SYNC_ADD(&hti->num_entries_copied, 1);
432 return hti_get(((volatile hti_t *)hti)->next, key, key_hash); // tail-call
435 return (ent_val == TOMBSTONE) ? DOES_NOT_EXIST : ent_val;
439 uint64_t ht_get (hashtable_t *ht, void *key) {
440 uint32_t hash = (ht->hash_fun == NULL) ? murmur32_8b((uint64_t)key) : ht->hash_fun(key);
441 return hti_get(ht->hti, key, hash);
445 uint64_t ht_cas (hashtable_t *ht, void *key, uint64_t expected_val, uint64_t new_val) {
447 TRACE("h2", "ht_cas: key %p ht %p", key, ht);
448 TRACE("h2", "ht_cas: expected val %p new val %p", expected_val, new_val);
449 assert(key != DOES_NOT_EXIST);
450 assert(!IS_TAGGED(new_val) && new_val != DOES_NOT_EXIST && new_val != TOMBSTONE);
452 hti_t *hti = ht->hti;
454 // Help with an ongoing copy.
455 if (EXPECT_FALSE(hti->next != NULL)) {
456 volatile entry_t *ent;
461 TRACE("h1", "ht_cas: help copy. scan is %llu, size is %llu", x, 1<<hti->scale);
462 // Panic if we've been around the array twice and still haven't finished the copy.
463 int panic = (x >= (1 << (hti->scale + 1)));
465 limit = ENTRIES_PER_COPY_CHUNK;
467 // Reserve some entries for this thread to copy. There is a race condition here because the
468 // fetch and add isn't atomic, but that is ok.
469 hti->scan = x + ENTRIES_PER_COPY_CHUNK;
471 // <hti->scan> might be larger than the size of the table, if some thread stalls while
472 // copying. In that case we just wrap around to the begining and make another pass through
474 ent = hti->table + (x & MASK(hti->scale));
476 TRACE("h1", "ht_cas: help copy panic", 0, 0);
477 // scan the whole table
478 limit = (1 << hti->scale);
483 for (int i = 0; i < limit; ++i) {
484 num_copied += hti_copy_entry(hti, ent++, 0, hti->next);
485 assert(ent <= hti->table + (1 << hti->scale));
487 if (num_copied != 0) {
488 SYNC_ADD(&hti->num_entries_copied, num_copied);
491 // Dispose of fully copied tables.
492 if (hti->num_entries_copied == (1 << hti->scale) || panic) {
494 if (SYNC_CAS(&ht->hti, hti, hti->next) == hti) {
501 uint32_t key_hash = (ht->hash_fun == NULL) ? murmur32_8b((uint64_t)key) : ht->hash_fun(key);
502 while ((old_val = hti_cas(hti, key, key_hash, expected_val, new_val)) == COPIED_VALUE) {
507 return old_val == TOMBSTONE ? DOES_NOT_EXIST : old_val;
510 // Remove the value in <ht> associated with <key>. Returns the value removed, or DOES_NOT_EXIST if there was
511 // no value for that key.
512 uint64_t ht_remove (hashtable_t *ht, void *key) {
513 hti_t *hti = ht->hti;
515 uint32_t key_hash = (ht->hash_fun == NULL) ? murmur32_8b((uint64_t)key) : ht->hash_fun(key);
517 val = hti_cas(hti, key, key_hash, CAS_EXPECT_WHATEVER, TOMBSTONE);
518 if (val != COPIED_VALUE)
519 return val == TOMBSTONE ? DOES_NOT_EXIST : val;
526 // Returns the number of key-values pairs in <ht>
527 uint64_t ht_count (hashtable_t *ht) {
528 hti_t *hti = ht->hti;
537 // Allocate and initialize a new hash table.
538 hashtable_t *ht_alloc (cmp_fun_t cmp_fun, hash_fun_t hash_fun, clone_fun_t clone_fun) {
539 hashtable_t *ht = nbd_malloc(sizeof(hashtable_t));
540 ht->cmp_fun = cmp_fun;
541 ht->hash_fun = hash_fun;
542 ht->clone_fun = clone_fun;
543 ht->hti = (hti_t *)hti_alloc(ht, MIN_SCALE);
547 // Free <ht> and its internal structures.
548 void ht_free (hashtable_t *ht) {
549 hti_t *hti = ht->hti;
551 for (uint32_t i = 0; i < (1 << hti->scale); ++i) {
552 assert(hti->table[i].val == COPIED_VALUE || !IS_TAGGED(hti->table[i].val));
553 if (ht->clone_fun != NULL && hti->table[i].key != DOES_NOT_EXIST) {
554 nbd_free(GET_PTR(hti->table[i].key));
557 hti_t *next = hti->next;
564 void ht_print (hashtable_t *ht) {
565 hti_t *hti = ht->hti;
567 printf("hti:%p scale:%u count:%d copied:%d\n", hti, hti->scale, hti->count, hti->num_entries_copied);
568 for (int i = 0; i < (1 << hti->scale); ++i) {
569 volatile entry_t *ent = hti->table + i;
570 printf("[0x%x] %p:%p\n", i, (void *)ent->key, (void *)ent->val);