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