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