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