]> pd.if.org Git - nbds/blob - struct/ht.c
f444af0a3350440a3355b6daed1c8e28199cc50c
[nbds] / struct / ht.c
1 /* 
2  * Written by Josh Dybnis and released to the public domain, as explained at
3  * http://creativecommons.org/licenses/publicdomain
4  * 
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
8  *
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.
13  */
14
15 #include "common.h"
16 #include "ht.h"
17 #include "murmur.h"
18 #include "mem.h"
19
20 #define GET_PTR(x) ((string_t *)((x) & MASK(48))) // low-order 48 bits is a pointer to a string_t
21
22 typedef struct ht_entry {
23     uint64_t key;
24     uint64_t value;
25 } entry_t;
26
27 typedef struct string {
28     uint32_t len;
29     char val[];
30 } string_t;
31
32 typedef struct hash_table_i {
33     volatile entry_t *table;
34     hash_table_t *ht; // parent ht;
35     struct hash_table_i *next;
36     struct hash_table_i *next_free;
37     unsigned int scale;
38     int max_probe;
39     int count; // TODO: make these counters distributed
40     int num_entries_copied;
41     int scan;
42 } hash_table_i_t;
43
44 static const uint64_t COPIED_VALUE           = -1;
45 static const uint64_t TOMBSTONE              = STRIP_TAG(-1);
46
47 static const unsigned ENTRIES_PER_BUCKET     = CACHE_LINE_SIZE/sizeof(entry_t);
48 static const unsigned ENTRIES_PER_COPY_CHUNK = CACHE_LINE_SIZE/sizeof(entry_t)*2;
49 static const unsigned MIN_SCALE              = 4; // min 16 entries (4 buckets)
50 static const unsigned MAX_BUCKETS_TO_PROBE   = 250;
51
52 static int hti_copy_entry 
53     (hash_table_i_t *ht1, volatile entry_t *e, uint32_t e_key_hash, hash_table_i_t *ht2);
54
55 // Choose the next bucket to probe using the high-order bits of <key_hash>.
56 static inline int get_next_ndx(int old_ndx, uint32_t key_hash, int ht_scale) {
57     int incr = (key_hash >> (32 - ht_scale));
58     incr += !incr; // If the increment is 0, make it 1.
59     return (old_ndx + incr) & MASK(ht_scale);
60 }
61
62 // Compare two keys.
63 //
64 // A key is made up of two parts. The 48 low-order bits are a pointer to a null terminated string.
65 // The high-order 16 bits are taken from the hash of that string. The bits from the hash are used 
66 // as a quick check to rule out non-equal keys without doing a complete string compare.
67 static inline int ht_key_equals (uint64_t a, uint32_t b_hash, const char *b_value, uint32_t b_len) {
68     if ((b_hash >> 16) != (a >> 48)) // high-order 16 bits are from the hash value
69         return FALSE;
70     const string_t *a_key = GET_PTR(a); 
71     assert(a_key);
72     return a_key->len == b_len && memcmp(a_key->val, b_value, b_len) == 0;
73 }
74
75 // Lookup <key> in <hti>. 
76 //
77 // Return the entry that <key> is in, or if <key> isn't in <hti> return the entry that it would be 
78 // in if it were inserted into <hti>. If there is no room for <key> in <hti> then return NULL, to 
79 // indicate that the caller should look in <hti->next>.
80 //
81 // Record if the entry being returned is empty. Otherwise the caller will have to waste time with
82 // ht_key_equals() to confirm that it did not lose a race to fill an empty entry.
83 static volatile entry_t *hti_lookup (hash_table_i_t *hti, uint32_t key_hash, const char *key_val, uint32_t key_len, int *is_empty) {
84     TRACE("h2", "hti_lookup(key %p in hti %p)", key_val, hti);
85     *is_empty = 0;
86
87     // Probe one cache line at a time
88     int ndx = key_hash & MASK(hti->scale); // the first entry to search
89     for (int i = 0; i < hti->max_probe; ++i) {
90
91         // The start of the bucket is the first entry in the cache line.
92         volatile entry_t *bucket = hti->table + (ndx & ~(ENTRIES_PER_BUCKET-1)); 
93
94         // Start searching at the indexed entry. Then loop around to the begining of the cache line.
95         for (int j = 0; j < ENTRIES_PER_BUCKET; ++j) {
96             volatile entry_t *e = bucket + ((ndx + j) & (ENTRIES_PER_BUCKET-1));
97
98             uint64_t e_key = e->key;
99             if (e_key == DOES_NOT_EXIST) {
100                 TRACE("h1", "hti_lookup: entry %p for key \"%s\" is empty", e, GET_PTR(e_key)->val);
101                 *is_empty = 1; // indicate an empty so the caller avoids an expensive ht_key_equals
102                 return e;
103             }
104
105             if (ht_key_equals(e_key, key_hash, key_val, key_len)) {
106                 TRACE("h1", "hti_lookup: entry %p key \"%s\"", e, GET_PTR(e_key)->val);
107                 TRACE("h2", "hti_lookup: entry key len %llu, value %p", GET_PTR(e_key)->len, e->value);
108                 return e;
109             }
110         }
111
112         ndx = get_next_ndx(ndx, key_hash, hti->scale);
113     }
114
115     // maximum number of probes exceeded
116     TRACE("h1", "hti_lookup: maximum number of probes exceeded returning 0x0", 0, 0);
117     return NULL;
118 }
119
120 // Allocate and initialize a hash_table_i_t with 2^<scale> entries.
121 static hash_table_i_t *hti_alloc (hash_table_t *parent, int scale) {
122     // Include enough slop to align the actual table on a cache line boundry
123     size_t n = sizeof(hash_table_i_t) 
124              + sizeof(entry_t) * (1 << scale) 
125              + (CACHE_LINE_SIZE - 1);
126     hash_table_i_t *hti = (hash_table_i_t *)calloc(n, 1);
127
128     // Align the table of hash entries on a cache line boundry.
129     hti->table = (entry_t *)(((uint64_t)hti + sizeof(hash_table_i_t) + (CACHE_LINE_SIZE-1)) 
130                             & ~(CACHE_LINE_SIZE-1));
131
132     hti->scale = scale;
133
134     // When searching for a key probe a maximum of 1/4 of the buckets up to 1000 buckets.
135     hti->max_probe = ((1 << (hti->scale - 2)) / ENTRIES_PER_BUCKET) + 2;
136     if (hti->max_probe > MAX_BUCKETS_TO_PROBE) {
137         hti->max_probe = MAX_BUCKETS_TO_PROBE;
138     }
139
140     hti->ht = parent;
141
142     assert(hti->scale >= MIN_SCALE && hti->scale < 63); // size must be a power of 2
143     assert(sizeof(entry_t) * ENTRIES_PER_BUCKET % CACHE_LINE_SIZE == 0); // divisible into cache
144     assert((size_t)hti->table % CACHE_LINE_SIZE == 0); // cache aligned
145
146     return hti;
147 }
148
149 // Called when <hti> runs out of room for new keys.
150 //
151 // Initiates a copy by creating a larger hash_table_i_t and installing it in <hti->next>.
152 static void hti_start_copy (hash_table_i_t *hti) {
153     TRACE("h0", "hti_start_copy(hti %p scale %llu)", hti, hti->scale);
154
155     // heuristics to determine the size of the new table
156     uint64_t count = ht_count(hti->ht);
157     unsigned int new_scale = hti->scale;
158     new_scale += (count > (1 << (new_scale - 2))); // double size if more than 1/4 full
159     new_scale += (count > (1 << (new_scale - 2))); // double size again if more than 1/2 full
160
161     // Allocate the new table and attempt to install it.
162     hash_table_i_t *next = hti_alloc(hti->ht, new_scale);
163     hash_table_i_t *old_next = SYNC_CAS(&hti->next, NULL, next);
164     if (old_next != NULL) {
165         // Another thread beat us to it.
166         TRACE("h0", "hti_start_copy: lost race to install new hti; found %p", old_next, 0);
167         nbd_free(next);
168         return;
169     }
170     TRACE("h0", "hti_start_copy: new hti %p scale %llu", next, next->scale);
171 }
172
173 // Copy the key and value stored in <ht1_e> (which must be an entry in <ht1>) to <ht2>. 
174 //
175 // Return 1 unless <ht1_e> is already copied (then return 0), so the caller can account for the total
176 // number of entries left to copy.
177 static int hti_copy_entry (hash_table_i_t *ht1, volatile entry_t *ht1_e, uint32_t key_hash, 
178                            hash_table_i_t *ht2) {
179     TRACE("h2", "hti_copy_entry: entry %p to table %p", ht1_e, ht2);
180     assert(ht1);
181     assert(ht1->next);
182     assert(ht2);
183     assert(ht1_e >= ht1->table && ht1_e < ht1->table + (1 << ht1->scale));
184     assert(key_hash == 0 || (key_hash >> 16) == (ht1_e->key >> 48));
185
186     uint64_t ht1_e_value = ht1_e->value;
187     if (EXPECT_FALSE(ht1_e_value == COPIED_VALUE)) {
188         TRACE("h1", "hti_copy_entry: entry %p already copied to table %p", ht1_e, ht2);
189         return FALSE; // already copied
190     }
191
192     // Kill empty entries.
193     if (EXPECT_FALSE(ht1_e_value == DOES_NOT_EXIST)) {
194         uint64_t ht1_e_value = SYNC_CAS(&ht1_e->value, DOES_NOT_EXIST, COPIED_VALUE);
195         if (ht1_e_value == DOES_NOT_EXIST) {
196             TRACE("h1", "hti_copy_entry: empty entry %p killed", ht1_e, 0);
197             return TRUE;
198         }
199         if (ht1_e_value == COPIED_VALUE) {
200             TRACE("h0", "hti_copy_entry: lost race to kill empty entry %p", ht1_e, 0);
201             return FALSE; // another thread beat us to it
202         }
203         TRACE("h0", "hti_copy_entry: lost race to kill empty entry %p; the entry is now"
204                     "in use and should be copied", ht1_e, 0);
205     }
206
207     // Tag the value in the old entry to indicate a copy is in progress.
208     ht1_e_value = SYNC_FETCH_AND_OR(&ht1_e->value, TAG_VALUE(0));
209     TRACE("h2", "hti_copy_entry: tagged the value %p in old entry %p", ht1_e_value, ht1_e);
210     if (ht1_e_value == COPIED_VALUE) {
211         TRACE("h1", "hti_copy_entry: entry %p already copied to table %p", ht1_e, ht2);
212         return FALSE; // <value> was already copied by another thread.
213     }
214
215     // The old table's deleted entries don't need to be copied to the new table, but their keys need
216     // to be freed.
217     assert(COPIED_VALUE == TAG_VALUE(TOMBSTONE));
218     if (ht1_e_value == TOMBSTONE) {
219         TRACE("h1", "hti_copy_entry: entry %p old value was deleted, now freeing key %p", ht1_e, 
220                     GET_PTR(ht1_e->key));
221         nbd_defer_free(GET_PTR(ht1_e->key));
222         return TRUE; 
223     }
224
225     // Install the key in the new table.
226     uint64_t key = ht1_e->key;
227     string_t *key_string = GET_PTR(key);
228     uint64_t value = STRIP_TAG(ht1_e_value);
229
230     // We use 0 to indicate that <key_hash> isn't initiallized. Occasionally the <key_hash> will
231     // really be 0 and we will waste time recomputing it. That is rare enough that it is OK. 
232     if (key_hash == 0) { 
233         key_hash = murmur32(key_string->val, key_string->len);
234     }
235
236     int is_empty;
237     volatile entry_t *ht2_e = hti_lookup(ht2, key_hash, key_string->val, key_string->len, &is_empty);
238     TRACE("h0", "hti_copy_entry: copy entry %p to entry %p", ht1_e, ht2_e);
239
240     // it is possible that there is not any room in the new table either
241     if (EXPECT_FALSE(ht2_e == NULL)) {
242         TRACE("h0", "hti_copy_entry: no room in table %p copy to next table %p", ht2, ht2->next);
243         if (ht2->next == NULL) {
244             hti_start_copy(ht2); // initiate nested copy, if not already started
245         }
246         return hti_copy_entry(ht1, ht1_e, key_hash, ht2->next); // recursive tail-call
247     }
248
249     // a tagged entry returned from hti_lookup() means it is either empty or has a new key
250     if (is_empty) {
251         uint64_t old_ht2_e_key = SYNC_CAS(&ht2_e->key, DOES_NOT_EXIST, key);
252         if (old_ht2_e_key != DOES_NOT_EXIST) {
253             TRACE("h0", "hti_copy_entry: lost race to CAS key %p into new entry; found %p",
254                     key, old_ht2_e_key);
255             return hti_copy_entry(ht1, ht1_e, key_hash, ht2); // recursive tail-call
256         }
257     }
258
259     // Copy the value to the entry in the new table.
260     uint64_t old_ht2_e_value = SYNC_CAS(&ht2_e->value, DOES_NOT_EXIST, value);
261
262     // If there is a nested copy in progress, we might have installed the key into a dead entry.
263     if (old_ht2_e_value == COPIED_VALUE) {
264         TRACE("h0", "hti_copy_entry: nested copy in progress; copy %p to next table %p", ht2_e, ht2->next);
265         return hti_copy_entry(ht1, ht1_e, key_hash, ht2->next); // recursive tail-call
266     }
267
268     // Mark the old entry as dead.
269     ht1_e->value = COPIED_VALUE;
270
271     // Update the count if we were the one that completed the copy.
272     if (old_ht2_e_value == DOES_NOT_EXIST) {
273         TRACE("h0", "hti_copy_entry: key \"%s\" value %p copied to new entry", key_string->val, value);
274         SYNC_ADD(&ht1->count, -1);
275         SYNC_ADD(&ht2->count, 1);
276         return TRUE;
277     }
278
279     TRACE("h0", "hti_copy_entry: lost race to install value %p in new entry; found value %p", 
280                 value, old_ht2_e_value);
281     return FALSE; // another thread completed the copy
282 }
283
284 // Compare <expected> with the existing value associated with <key>. If the values match then 
285 // replace the existing value with <new>. If <new> is TOMBSTONE, delete the value associated with 
286 // the key by replacing it with a TOMBSTONE.
287 //
288 // Return the previous value associated with <key>, or DOES_NOT_EXIST if <key> is not in the table
289 // or associated with a TOMBSTONE. If a copy is in progress and <key> has been copied to the next 
290 // table then return COPIED_VALUE. 
291 //
292 // NOTE: the returned value matches <expected> iff the set succeeds
293 //
294 // Certain values of <expected> have special meaning. If <expected> is HT_EXPECT_EXISTS then any 
295 // real value matches (i.e. not a TOMBSTONE or DOES_NOT_EXIST) as long as <key> is in the table. If
296 // <expected> is HT_EXPECT_WHATEVER then skip the test entirely.
297 //
298 static uint64_t hti_compare_and_set (hash_table_i_t *hti, uint32_t key_hash, const char *key_val, 
299                                     uint32_t key_len, uint64_t expected, uint64_t new) {
300     TRACE("h1", "hti_compare_and_set: hti %p key %p", hti, key_val);
301     TRACE("h1", "hti_compare_and_set: value %p expect %p", new, expected);
302     assert(hti);
303     assert(new != DOES_NOT_EXIST && !IS_TAGGED(new));
304     assert(key_val);
305
306     int is_empty;
307     volatile entry_t *e = hti_lookup(hti, key_hash, key_val, key_len, &is_empty);
308
309     // There is no room for <key>, grow the table and try again.
310     if (e == NULL) {
311         if (hti->next == NULL) {
312             hti_start_copy(hti);
313         }
314         return COPIED_VALUE;
315     }
316
317     // Install <key> in the table if it doesn't exist.
318     if (is_empty) {
319         TRACE("h0", "hti_compare_and_set: entry %p is empty", e, 0);
320         if (expected != HT_EXPECT_WHATEVER && expected != HT_EXPECT_NOT_EXISTS)
321             return DOES_NOT_EXIST;
322
323         // No need to do anything, <key> is already deleted.
324         if (new == TOMBSTONE)
325             return DOES_NOT_EXIST;
326
327         // Allocate <key>.
328         string_t *key = nbd_malloc(sizeof(uint32_t) + key_len);
329         key->len = key_len;
330         memcpy(key->val, key_val, key_len);
331
332         // Combine <key> pointer with bits from its hash, CAS it into the table. 
333         uint64_t temp = ((uint64_t)(key_hash >> 16) << 48) | (uint64_t)key; 
334         uint64_t e_key = SYNC_CAS(&e->key, DOES_NOT_EXIST, temp);
335
336         // Retry if another thread stole the entry out from under us.
337         if (e_key != DOES_NOT_EXIST) {
338             TRACE("h0", "hti_compare_and_set: lost race to install key %p in entry %p", key, e);
339             TRACE("h0", "hti_compare_and_set: found %p instead of NULL", GET_PTR(e_key), 0);
340             nbd_free(key);
341             return hti_compare_and_set(hti, key_hash, key_val, key_len, expected, new); // tail-call
342         }
343         TRACE("h2", "hti_compare_and_set: installed key %p in entry %p", key, e);
344     }
345
346     TRACE("h0", "hti_compare_and_set: entry for key \"%s\" is %p", GET_PTR(e->key)->val, e);
347
348     // If the entry is in the middle of a copy, the copy must be completed first.
349     uint64_t e_value = e->value;
350     if (EXPECT_FALSE(IS_TAGGED(e_value))) {
351         if (e_value != COPIED_VALUE) {
352             int did_copy = hti_copy_entry(hti, e, key_hash, ((volatile hash_table_i_t *)hti)->next);
353             if (did_copy) {
354                 SYNC_ADD(&hti->num_entries_copied, 1);
355             }
356             TRACE("h0", "hti_compare_and_set: value in the middle of a copy, copy completed by %s", 
357                         (did_copy ? "self" : "other"), 0);
358         }
359         TRACE("h0", "hti_compare_and_set: value copied to next table, retry on next table", 0, 0);
360         return COPIED_VALUE;
361     }
362
363     // Fail if the old value is not consistent with the caller's expectation.
364     int old_existed = (e_value != TOMBSTONE && e_value != DOES_NOT_EXIST);
365     if (EXPECT_FALSE(expected != HT_EXPECT_WHATEVER && expected != e_value)) {
366         if (EXPECT_FALSE(expected != (old_existed ? HT_EXPECT_EXISTS : HT_EXPECT_NOT_EXISTS))) {
367             TRACE("h1", "hti_compare_and_set: value %p expected by caller not found; found value %p",
368                         expected, e_value);
369             return e_value;
370         }
371     }
372
373     // No need to update if value is unchanged.
374     if ((new == TOMBSTONE && !old_existed) || e_value == new) {
375         TRACE("h1", "hti_compare_and_set: old value and new value were the same", 0, 0);
376         return e_value;
377     }
378
379     // CAS the value into the entry. Retry if it fails.
380     uint64_t v = SYNC_CAS(&e->value, e_value, new);
381     if (EXPECT_FALSE(v != e_value)) {
382         TRACE("h0", "hti_compare_and_set: value CAS failed; expected %p found %p", e_value, v);
383         return hti_compare_and_set(hti, key_hash, key_val, key_len, expected, new); // recursive tail-call
384     }
385
386     // The set succeeded. Adjust the value count.
387     if (old_existed && new == TOMBSTONE) {
388         SYNC_ADD(&hti->count, -1);
389     } else if (!old_existed && new != TOMBSTONE) {
390         SYNC_ADD(&hti->count, 1);
391     }
392
393     // Return the previous value.
394     TRACE("h0", "hti_compare_and_set: CAS succeeded; old value %p new value %p", e_value, new);
395     return e_value;
396 }
397
398 //
399 static uint64_t hti_get (hash_table_i_t *hti, uint32_t key_hash, const char *key_val, uint32_t key_len) {
400     assert(key_val);
401
402     int is_empty;
403     volatile entry_t *e = hti_lookup(hti, key_hash, key_val, key_len, &is_empty);
404
405     // When hti_lookup() returns NULL it means we hit the reprobe limit while
406     // searching the table. In that case, if a copy is in progress the key 
407     // might exist in the copy.
408     if (EXPECT_FALSE(e == NULL)) {
409         if (((volatile hash_table_i_t *)hti)->next != NULL)
410             return hti_get(hti->next, key_hash, key_val, key_len); // recursive tail-call
411         return DOES_NOT_EXIST;
412     }
413
414     if (is_empty)
415         return DOES_NOT_EXIST;
416
417     // If the entry is being copied, finish the copy and retry on the next table.
418     uint64_t e_value = e->value;
419     if (EXPECT_FALSE(IS_TAGGED(e_value))) {
420         if (EXPECT_FALSE(e_value != COPIED_VALUE)) {
421             int did_copy = hti_copy_entry(hti, e, key_hash, ((volatile hash_table_i_t *)hti)->next);
422             if (did_copy) {
423                 SYNC_ADD(&hti->num_entries_copied, 1);
424             }
425         }
426         return hti_get(((volatile hash_table_i_t *)hti)->next, key_hash, key_val, key_len); // tail-call
427     }
428
429     return (e_value == TOMBSTONE) ? DOES_NOT_EXIST : e_value;
430 }
431
432 //
433 uint64_t ht_get (hash_table_t *ht, const char *key_val, uint32_t key_len) {
434     return hti_get(*ht, murmur32(key_val, key_len), key_val, key_len);
435 }
436
437 //
438 uint64_t ht_compare_and_set (hash_table_t *ht, const char *key_val, uint32_t key_len, 
439                             uint64_t expected_val, uint64_t new_val) {
440
441     TRACE("h2", "ht_compare_and_set: key %p len %u", key_val, key_len);
442     TRACE("h2", "ht_compare_and_set: expected val %p new val %p", expected_val, new_val);
443     assert(key_val);
444     assert(!IS_TAGGED(new_val) && new_val != DOES_NOT_EXIST);
445
446     hash_table_i_t *hti = *ht;
447
448     // Help with an ongoing copy.
449     if (EXPECT_FALSE(hti->next != NULL)) {
450         volatile entry_t *e;
451         uint64_t limit; 
452         int num_copied = 0;
453         int x = hti->scan; 
454
455         TRACE("h1", "ht_compare_and_set: help copy. scan is %llu, size is %llu", x, 1<<hti->scale);
456         // Panic if we've been around the array twice and still haven't finished the copy.
457         int panic = (x >= (1 << (hti->scale + 1))); 
458         if (!panic) {
459             limit = ENTRIES_PER_COPY_CHUNK;
460
461             // Reserve some entries for this thread to copy. There is a race condition here because the
462             // fetch and add isn't atomic, but that is ok.
463             hti->scan = x + ENTRIES_PER_COPY_CHUNK; 
464
465             // <hti->scan> might be larger than the size of the table, if some thread stalls while 
466             // copying. In that case we just wrap around to the begining and make another pass through
467             // the table.
468             e = hti->table + (x & MASK(hti->scale));
469         } else {
470             TRACE("h1", "ht_compare_and_set: help copy panic", 0, 0);
471             // scan the whole table
472             limit = (1 << hti->scale);
473             e = hti->table;
474         }
475
476         // Copy the entries
477         for (int i = 0; i < limit; ++i) {
478             num_copied += hti_copy_entry(hti, e++, 0, hti->next);
479             assert(e <= hti->table + (1 << hti->scale));
480         }
481         if (num_copied != 0) {
482             SYNC_ADD(&hti->num_entries_copied, num_copied);
483         }
484
485         // Dispose of fully copied tables.
486         if (hti->num_entries_copied == (1 << hti->scale) || panic) {
487             assert(hti->next);
488             if (SYNC_CAS(ht, hti, hti->next) == hti) {
489                 nbd_defer_free(hti); 
490             }
491         }
492     }
493
494     uint64_t old_val;
495     uint32_t key_hash = murmur32(key_val, key_len);
496     while ((old_val = hti_compare_and_set(hti, key_hash, key_val, key_len, expected_val, new_val)) 
497            == COPIED_VALUE) {
498         assert(hti->next);
499         hti = hti->next;
500     }
501
502     return old_val == TOMBSTONE ? DOES_NOT_EXIST : old_val;
503 }
504
505 // Remove the value in <ht> associated with <key_val>. Returns the value removed, or 
506 // DOES_NOT_EXIST if there was no value for that key.
507 uint64_t ht_remove (hash_table_t *ht, const char *key_val, uint32_t key_len) {
508     hash_table_i_t *hti = *ht;
509     uint64_t val;
510     uint32_t key_hash = murmur32(key_val, key_len);
511     do {
512         val = hti_compare_and_set(hti, key_hash, key_val, key_len, HT_EXPECT_WHATEVER, TOMBSTONE);
513         if (val != COPIED_VALUE)
514             return val == TOMBSTONE ? DOES_NOT_EXIST : val;
515         assert(hti->next);
516         hti = hti->next;
517         assert(hti);
518     } while (1);
519 }
520
521 // Returns the number of key-values pairs in <ht>
522 uint64_t ht_count (hash_table_t *ht) {
523     hash_table_i_t *hti = *ht;
524     uint64_t count = 0;
525     while (hti) {
526         count += hti->count;
527         hti = hti->next; 
528     }
529     return count;
530 }
531
532 // Allocate and initialize a new hash table.
533 hash_table_t *ht_alloc (void) {
534     hash_table_t *ht = nbd_malloc(sizeof(hash_table_t));
535     *ht = (hash_table_i_t *)hti_alloc(ht, MIN_SCALE);
536     return ht;
537 }
538
539 // Free <ht> and its internal structures.
540 void ht_free (hash_table_t *ht) {
541     hash_table_i_t *hti = *ht;
542     do {
543         for (uint32_t i = 0; i < (1 << hti->scale); ++i) {
544             assert(hti->table[i].value == COPIED_VALUE || !IS_TAGGED(hti->table[i].value));
545             if (hti->table[i].key != DOES_NOT_EXIST) {
546                 nbd_free(GET_PTR(hti->table[i].key));
547             }
548         }
549         hash_table_i_t *next = hti->next;
550         nbd_free(hti);
551         hti = next;
552     } while (hti);
553     nbd_free(ht);
554 }