2 Trivial Database 2: hash handling
3 Copyright (C) Rusty Russell 2010
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 3 of the License, or (at your option) any later version.
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 #include <ccan/hash/hash.h>
22 static uint64_t jenkins_hash(const void *key, size_t length, uint64_t seed,
26 /* hash64_stable assumes lower bits are more important; they are a
27 * slightly better hash. We use the upper bits first, so swap them. */
28 ret = hash64_stable((const unsigned char *)key, length, seed);
29 return (ret >> 32) | (ret << 32);
32 void tdb_hash_init(struct tdb_context *tdb)
34 tdb->khash = jenkins_hash;
35 tdb->hash_priv = NULL;
38 uint64_t tdb_hash(struct tdb_context *tdb, const void *ptr, size_t len)
40 return tdb->khash(ptr, len, tdb->hash_seed, tdb->hash_priv);
43 uint64_t hash_record(struct tdb_context *tdb, tdb_off_t off)
45 const struct tdb_used_record *r;
49 r = tdb_access_read(tdb, off, sizeof(*r), true);
54 klen = rec_key_length(r);
55 tdb_access_release(tdb, r);
57 key = tdb_access_read(tdb, off + sizeof(*r), klen, false);
61 hash = tdb_hash(tdb, key, klen);
62 tdb_access_release(tdb, key);
66 /* Get bits from a value. */
67 static uint32_t bits_from(uint64_t val, unsigned start, unsigned num)
70 return (val >> start) & ((1U << num) - 1);
73 /* We take bits from the top: that way we can lock whole sections of the hash
74 * by using lock ranges. */
75 static uint32_t use_bits(struct hash_info *h, unsigned num)
78 return bits_from(h->h, 64 - h->hash_used, num);
81 static bool key_matches(struct tdb_context *tdb,
82 const struct tdb_used_record *rec,
84 const struct tdb_data *key)
89 if (rec_key_length(rec) != key->dsize) {
90 add_stat(tdb, compare_wrong_keylen, 1);
94 rkey = tdb_access_read(tdb, off + sizeof(*rec), key->dsize, false);
97 if (memcmp(rkey, key->dptr, key->dsize) == 0)
100 add_stat(tdb, compare_wrong_keycmp, 1);
101 tdb_access_release(tdb, rkey);
105 /* Does entry match? */
106 static bool match(struct tdb_context *tdb,
108 const struct tdb_data *key,
110 struct tdb_used_record *rec)
114 add_stat(tdb, compares, 1);
115 /* Desired bucket must match. */
116 if (h->home_bucket != (val & TDB_OFF_HASH_GROUP_MASK)) {
117 add_stat(tdb, compare_wrong_bucket, 1);
121 /* Top bits of offset == next bits of hash. */
122 if (bits_from(val, TDB_OFF_HASH_EXTRA_BIT, TDB_OFF_UPPER_STEAL_EXTRA)
123 != bits_from(h->h, 64 - h->hash_used - TDB_OFF_UPPER_STEAL_EXTRA,
124 TDB_OFF_UPPER_STEAL_EXTRA)) {
125 add_stat(tdb, compare_wrong_offsetbits, 1);
129 off = val & TDB_OFF_MASK;
130 if (tdb_read_convert(tdb, off, rec, sizeof(*rec)) == -1)
133 if ((h->h & ((1 << 11)-1)) != rec_hash(rec)) {
134 add_stat(tdb, compare_wrong_rechash, 1);
138 return key_matches(tdb, rec, off, key);
141 static tdb_off_t hbucket_off(tdb_off_t group_start, unsigned bucket)
144 + (bucket % (1 << TDB_HASH_GROUP_BITS)) * sizeof(tdb_off_t);
147 bool is_subhash(tdb_off_t val)
149 return (val >> TDB_OFF_UPPER_STEAL_SUBHASH_BIT) & 1;
152 /* FIXME: Guess the depth, don't over-lock! */
153 static tdb_off_t hlock_range(tdb_off_t group, tdb_off_t *size)
155 *size = 1ULL << (64 - (TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS));
156 return group << (64 - (TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS));
159 static tdb_off_t COLD find_in_chain(struct tdb_context *tdb,
163 struct tdb_used_record *rec,
164 struct traverse_info *tinfo)
168 /* In case nothing is free, we set these to zero. */
169 h->home_bucket = h->found_bucket = 0;
171 for (off = chain; off; off = next) {
174 h->group_start = off;
175 if (tdb_read_convert(tdb, off, h->group, sizeof(h->group)))
178 for (i = 0; i < (1 << TDB_HASH_GROUP_BITS); i++) {
181 /* Remember this empty bucket. */
182 h->home_bucket = h->found_bucket = i;
186 /* We can insert extra bits via add_to_hash
187 * empty bucket logic. */
188 recoff = h->group[i] & TDB_OFF_MASK;
189 if (tdb_read_convert(tdb, recoff, rec, sizeof(*rec)))
192 if (key_matches(tdb, rec, recoff, &key)) {
193 h->home_bucket = h->found_bucket = i;
196 tinfo->levels[tinfo->num_levels]
198 tinfo->levels[tinfo->num_levels]
200 = 1 << TDB_HASH_GROUP_BITS;
201 tinfo->levels[tinfo->num_levels].entry
208 next = tdb_read_off(tdb, off
209 + offsetof(struct tdb_chain, next));
210 if (next == TDB_OFF_ERR)
213 next += sizeof(struct tdb_used_record);
218 /* This is the core routine which searches the hashtable for an entry.
219 * On error, no locks are held and TDB_OFF_ERR is returned.
220 * Otherwise, hinfo is filled in (and the optional tinfo).
221 * If not found, the return value is 0.
222 * If found, the return value is the offset, and *rec is the record. */
223 tdb_off_t find_and_lock(struct tdb_context *tdb,
227 struct tdb_used_record *rec,
228 struct traverse_info *tinfo)
233 h->h = tdb_hash(tdb, key.dptr, key.dsize);
235 group = use_bits(h, TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS);
236 h->home_bucket = use_bits(h, TDB_HASH_GROUP_BITS);
238 h->hlock_start = hlock_range(group, &h->hlock_range);
239 if (tdb_lock_hashes(tdb, h->hlock_start, h->hlock_range, ltype,
243 hashtable = offsetof(struct tdb_header, hashtable);
245 tinfo->toplevel_group = group;
246 tinfo->num_levels = 1;
247 tinfo->levels[0].entry = 0;
248 tinfo->levels[0].hashtable = hashtable
249 + (group << TDB_HASH_GROUP_BITS) * sizeof(tdb_off_t);
250 tinfo->levels[0].total_buckets = 1 << TDB_HASH_GROUP_BITS;
253 while (h->hash_used <= 64) {
254 /* Read in the hash group. */
255 h->group_start = hashtable
256 + group * (sizeof(tdb_off_t) << TDB_HASH_GROUP_BITS);
258 if (tdb_read_convert(tdb, h->group_start, &h->group,
259 sizeof(h->group)) == -1)
262 /* Pointer to another hash table? Go down... */
263 if (is_subhash(h->group[h->home_bucket])) {
264 hashtable = (h->group[h->home_bucket] & TDB_OFF_MASK)
265 + sizeof(struct tdb_used_record);
267 /* When we come back, use *next* bucket */
268 tinfo->levels[tinfo->num_levels-1].entry
269 += h->home_bucket + 1;
271 group = use_bits(h, TDB_SUBLEVEL_HASH_BITS
272 - TDB_HASH_GROUP_BITS);
273 h->home_bucket = use_bits(h, TDB_HASH_GROUP_BITS);
275 tinfo->levels[tinfo->num_levels].hashtable
277 tinfo->levels[tinfo->num_levels].total_buckets
278 = 1 << TDB_SUBLEVEL_HASH_BITS;
279 tinfo->levels[tinfo->num_levels].entry
280 = group << TDB_HASH_GROUP_BITS;
286 /* It's in this group: search (until 0 or all searched) */
287 for (i = 0, h->found_bucket = h->home_bucket;
288 i < (1 << TDB_HASH_GROUP_BITS);
289 i++, h->found_bucket = ((h->found_bucket+1)
290 % (1 << TDB_HASH_GROUP_BITS))) {
291 if (is_subhash(h->group[h->found_bucket]))
294 if (!h->group[h->found_bucket])
297 if (match(tdb, h, &key, h->group[h->found_bucket],
300 tinfo->levels[tinfo->num_levels-1].entry
303 return h->group[h->found_bucket] & TDB_OFF_MASK;
306 /* Didn't find it: h indicates where it would go. */
310 return find_in_chain(tdb, key, hashtable, h, rec, tinfo);
313 tdb_unlock_hashes(tdb, h->hlock_start, h->hlock_range, ltype);
317 /* I wrote a simple test, expanding a hash to 2GB, for the following
319 * 1) Expanding all the buckets at once,
320 * 2) Expanding the bucket we wanted to place the new entry into.
321 * 3) Expanding the most-populated bucket,
323 * I measured the worst/average/best density during this process.
328 * So we figure out the busiest bucket for the moment.
330 static unsigned fullest_bucket(struct tdb_context *tdb,
331 const tdb_off_t *group,
334 unsigned counts[1 << TDB_HASH_GROUP_BITS] = { 0 };
335 unsigned int i, best_bucket;
337 /* Count the new entry. */
338 counts[new_bucket]++;
339 best_bucket = new_bucket;
341 for (i = 0; i < (1 << TDB_HASH_GROUP_BITS); i++) {
342 unsigned this_bucket;
344 if (is_subhash(group[i]))
346 this_bucket = group[i] & TDB_OFF_HASH_GROUP_MASK;
347 if (++counts[this_bucket] > counts[best_bucket])
348 best_bucket = this_bucket;
354 static bool put_into_group(tdb_off_t *group,
355 unsigned bucket, tdb_off_t encoded)
359 for (i = 0; i < (1 << TDB_HASH_GROUP_BITS); i++) {
360 unsigned b = (bucket + i) % (1 << TDB_HASH_GROUP_BITS);
370 static void force_into_group(tdb_off_t *group,
371 unsigned bucket, tdb_off_t encoded)
373 if (!put_into_group(group, bucket, encoded))
377 static tdb_off_t encode_offset(tdb_off_t new_off, struct hash_info *h)
379 return h->home_bucket
381 | ((uint64_t)bits_from(h->h,
382 64 - h->hash_used - TDB_OFF_UPPER_STEAL_EXTRA,
383 TDB_OFF_UPPER_STEAL_EXTRA)
384 << TDB_OFF_HASH_EXTRA_BIT);
387 /* Simply overwrite the hash entry we found before. */
388 int replace_in_hash(struct tdb_context *tdb,
392 return tdb_write_off(tdb, hbucket_off(h->group_start, h->found_bucket),
393 encode_offset(new_off, h));
396 /* We slot in anywhere that's empty in the chain. */
397 static int COLD add_to_chain(struct tdb_context *tdb,
401 size_t entry = tdb_find_zero_off(tdb, subhash, 1<<TDB_HASH_GROUP_BITS);
403 if (entry == 1 << TDB_HASH_GROUP_BITS) {
406 next = tdb_read_off(tdb, subhash
407 + offsetof(struct tdb_chain, next));
408 if (next == TDB_OFF_ERR)
412 next = alloc(tdb, 0, sizeof(struct tdb_chain), 0,
413 TDB_CHAIN_MAGIC, false);
414 if (next == TDB_OFF_ERR)
416 if (zero_out(tdb, next+sizeof(struct tdb_used_record),
417 sizeof(struct tdb_chain)))
419 if (tdb_write_off(tdb, subhash
420 + offsetof(struct tdb_chain, next),
424 return add_to_chain(tdb, next, new_off);
427 return tdb_write_off(tdb, subhash + entry * sizeof(tdb_off_t),
431 /* Add into a newly created subhash. */
432 static int add_to_subhash(struct tdb_context *tdb, tdb_off_t subhash,
433 unsigned hash_used, tdb_off_t val)
435 tdb_off_t off = (val & TDB_OFF_MASK), *group;
439 h.hash_used = hash_used;
441 if (hash_used + TDB_SUBLEVEL_HASH_BITS > 64)
442 return add_to_chain(tdb, subhash, off);
444 h.h = hash_record(tdb, off);
445 gnum = use_bits(&h, TDB_SUBLEVEL_HASH_BITS-TDB_HASH_GROUP_BITS);
446 h.group_start = subhash
447 + gnum * (sizeof(tdb_off_t) << TDB_HASH_GROUP_BITS);
448 h.home_bucket = use_bits(&h, TDB_HASH_GROUP_BITS);
450 group = tdb_access_write(tdb, h.group_start,
451 sizeof(*group) << TDB_HASH_GROUP_BITS, true);
454 force_into_group(group, h.home_bucket, encode_offset(off, &h));
455 return tdb_access_commit(tdb, group);
458 static int expand_group(struct tdb_context *tdb, struct hash_info *h)
460 unsigned bucket, num_vals, i, magic;
463 tdb_off_t vals[1 << TDB_HASH_GROUP_BITS];
465 /* Attach new empty subhash under fullest bucket. */
466 bucket = fullest_bucket(tdb, h->group, h->home_bucket);
468 if (h->hash_used == 64) {
469 add_stat(tdb, alloc_chain, 1);
470 subsize = sizeof(struct tdb_chain);
471 magic = TDB_CHAIN_MAGIC;
473 add_stat(tdb, alloc_subhash, 1);
474 subsize = (sizeof(tdb_off_t) << TDB_SUBLEVEL_HASH_BITS);
475 magic = TDB_HTABLE_MAGIC;
478 subhash = alloc(tdb, 0, subsize, 0, magic, false);
479 if (subhash == TDB_OFF_ERR)
482 if (zero_out(tdb, subhash + sizeof(struct tdb_used_record), subsize))
485 /* Remove any which are destined for bucket or are in wrong place. */
487 for (i = 0; i < (1 << TDB_HASH_GROUP_BITS); i++) {
488 unsigned home_bucket = h->group[i] & TDB_OFF_HASH_GROUP_MASK;
489 if (!h->group[i] || is_subhash(h->group[i]))
491 if (home_bucket == bucket || home_bucket != i) {
492 vals[num_vals++] = h->group[i];
496 /* FIXME: This assert is valid, but we do this during unit test :( */
497 /* assert(num_vals); */
499 /* Overwrite expanded bucket with subhash pointer. */
500 h->group[bucket] = subhash | (1ULL << TDB_OFF_UPPER_STEAL_SUBHASH_BIT);
502 /* Point to actual contents of record. */
503 subhash += sizeof(struct tdb_used_record);
505 /* Put values back. */
506 for (i = 0; i < num_vals; i++) {
507 unsigned this_bucket = vals[i] & TDB_OFF_HASH_GROUP_MASK;
509 if (this_bucket == bucket) {
510 if (add_to_subhash(tdb, subhash, h->hash_used, vals[i]))
513 /* There should be room to put this back. */
514 force_into_group(h->group, this_bucket, vals[i]);
520 int delete_from_hash(struct tdb_context *tdb, struct hash_info *h)
522 unsigned int i, num_movers = 0;
523 tdb_off_t movers[1 << TDB_HASH_GROUP_BITS];
525 h->group[h->found_bucket] = 0;
526 for (i = 1; i < (1 << TDB_HASH_GROUP_BITS); i++) {
527 unsigned this_bucket;
529 this_bucket = (h->found_bucket+i) % (1 << TDB_HASH_GROUP_BITS);
530 /* Empty bucket? We're done. */
531 if (!h->group[this_bucket])
534 /* Ignore subhashes. */
535 if (is_subhash(h->group[this_bucket]))
538 /* If this one is not happy where it is, we'll move it. */
539 if ((h->group[this_bucket] & TDB_OFF_HASH_GROUP_MASK)
541 movers[num_movers++] = h->group[this_bucket];
542 h->group[this_bucket] = 0;
546 /* Put back the ones we erased. */
547 for (i = 0; i < num_movers; i++) {
548 force_into_group(h->group, movers[i] & TDB_OFF_HASH_GROUP_MASK,
552 /* Now we write back the hash group */
553 return tdb_write_convert(tdb, h->group_start,
554 h->group, sizeof(h->group));
557 int add_to_hash(struct tdb_context *tdb, struct hash_info *h, tdb_off_t new_off)
559 /* We hit an empty bucket during search? That's where it goes. */
560 if (!h->group[h->found_bucket]) {
561 h->group[h->found_bucket] = encode_offset(new_off, h);
562 /* Write back the modified group. */
563 return tdb_write_convert(tdb, h->group_start,
564 h->group, sizeof(h->group));
567 if (h->hash_used > 64)
568 return add_to_chain(tdb, h->group_start, new_off);
570 /* We're full. Expand. */
571 if (expand_group(tdb, h) == -1)
574 if (is_subhash(h->group[h->home_bucket])) {
575 /* We were expanded! */
579 /* Write back the modified group. */
580 if (tdb_write_convert(tdb, h->group_start, h->group,
584 /* Move hashinfo down a level. */
585 hashtable = (h->group[h->home_bucket] & TDB_OFF_MASK)
586 + sizeof(struct tdb_used_record);
587 gnum = use_bits(h,TDB_SUBLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS);
588 h->home_bucket = use_bits(h, TDB_HASH_GROUP_BITS);
589 h->group_start = hashtable
590 + gnum * (sizeof(tdb_off_t) << TDB_HASH_GROUP_BITS);
591 if (tdb_read_convert(tdb, h->group_start, &h->group,
592 sizeof(h->group)) == -1)
596 /* Expanding the group must have made room if it didn't choose this
598 if (put_into_group(h->group, h->home_bucket, encode_offset(new_off, h)))
599 return tdb_write_convert(tdb, h->group_start,
600 h->group, sizeof(h->group));
602 /* This can happen if all hashes in group (and us) dropped into same
603 * group in subhash. */
604 return add_to_hash(tdb, h, new_off);
607 /* Traverse support: returns offset of record, or 0 or TDB_OFF_ERR. */
608 static tdb_off_t iterate_hash(struct tdb_context *tdb,
609 struct traverse_info *tinfo)
613 struct traverse_level *tlevel;
615 tlevel = &tinfo->levels[tinfo->num_levels-1];
618 for (i = tdb_find_nonzero_off(tdb, tlevel->hashtable,
619 tlevel->entry, tlevel->total_buckets);
620 i != tlevel->total_buckets;
621 i = tdb_find_nonzero_off(tdb, tlevel->hashtable,
622 i+1, tlevel->total_buckets)) {
623 val = tdb_read_off(tdb, tlevel->hashtable+sizeof(tdb_off_t)*i);
624 if (unlikely(val == TDB_OFF_ERR))
627 off = val & TDB_OFF_MASK;
629 /* This makes the delete-all-in-traverse case work
630 * (and simplifies our logic a little). */
631 if (off == tinfo->prev)
636 if (!is_subhash(val)) {
642 /* When we come back, we want the next one */
646 tlevel->hashtable = off + sizeof(struct tdb_used_record);
648 /* Next level is a chain? */
649 if (unlikely(tinfo->num_levels == TDB_MAX_LEVELS + 1))
650 tlevel->total_buckets = (1 << TDB_HASH_GROUP_BITS);
652 tlevel->total_buckets = (1 << TDB_SUBLEVEL_HASH_BITS);
657 if (tinfo->num_levels == 1)
660 /* Handle chained entries. */
661 if (unlikely(tinfo->num_levels == TDB_MAX_LEVELS + 1)) {
662 tlevel->hashtable = tdb_read_off(tdb, tlevel->hashtable
663 + offsetof(struct tdb_chain,
665 if (tlevel->hashtable == TDB_OFF_ERR)
667 if (tlevel->hashtable) {
668 tlevel->hashtable += sizeof(struct tdb_used_record);
674 /* Go back up and keep searching. */
680 /* Return 1 if we find something, 0 if not, -1 on error. */
681 int next_in_hash(struct tdb_context *tdb, int ltype,
682 struct traverse_info *tinfo,
683 TDB_DATA *kbuf, size_t *dlen)
685 const unsigned group_bits = TDB_TOPLEVEL_HASH_BITS-TDB_HASH_GROUP_BITS;
686 tdb_off_t hl_start, hl_range, off;
688 while (tinfo->toplevel_group < (1 << group_bits)) {
689 hl_start = (tdb_off_t)tinfo->toplevel_group
690 << (64 - group_bits);
691 hl_range = 1ULL << group_bits;
692 if (tdb_lock_hashes(tdb, hl_start, hl_range, ltype,
696 off = iterate_hash(tdb, tinfo);
698 struct tdb_used_record rec;
700 if (tdb_read_convert(tdb, off, &rec, sizeof(rec))) {
701 tdb_unlock_hashes(tdb,
702 hl_start, hl_range, ltype);
705 if (rec_magic(&rec) != TDB_USED_MAGIC) {
706 tdb_logerr(tdb, TDB_ERR_CORRUPT,
709 " corrupt record at %llu",
714 kbuf->dsize = rec_key_length(&rec);
716 /* They want data as well? */
718 *dlen = rec_data_length(&rec);
719 kbuf->dptr = tdb_alloc_read(tdb,
724 kbuf->dptr = tdb_alloc_read(tdb,
728 tdb_unlock_hashes(tdb, hl_start, hl_range, ltype);
729 return kbuf->dptr ? 1 : -1;
732 tdb_unlock_hashes(tdb, hl_start, hl_range, ltype);
734 tinfo->toplevel_group++;
735 tinfo->levels[0].hashtable
736 += (sizeof(tdb_off_t) << TDB_HASH_GROUP_BITS);
737 tinfo->levels[0].entry = 0;
742 /* Return 1 if we find something, 0 if not, -1 on error. */
743 int first_in_hash(struct tdb_context *tdb, int ltype,
744 struct traverse_info *tinfo,
745 TDB_DATA *kbuf, size_t *dlen)
748 tinfo->toplevel_group = 0;
749 tinfo->num_levels = 1;
750 tinfo->levels[0].hashtable = offsetof(struct tdb_header, hashtable);
751 tinfo->levels[0].entry = 0;
752 tinfo->levels[0].total_buckets = (1 << TDB_HASH_GROUP_BITS);
754 return next_in_hash(tdb, ltype, tinfo, kbuf, dlen);
757 /* Even if the entry isn't in this hash bucket, you'd have to lock this
758 * bucket to find it. */
759 static int chainlock(struct tdb_context *tdb, const TDB_DATA *key,
760 int ltype, enum tdb_lock_flags waitflag,
764 uint64_t h = tdb_hash(tdb, key->dptr, key->dsize);
765 tdb_off_t lockstart, locksize;
766 unsigned int group, gbits;
768 gbits = TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS;
769 group = bits_from(h, 64 - gbits, gbits);
771 lockstart = hlock_range(group, &locksize);
773 ret = tdb_lock_hashes(tdb, lockstart, locksize, ltype, waitflag);
774 tdb_trace_1rec(tdb, func, *key);
778 /* lock/unlock one hash chain. This is meant to be used to reduce
779 contention - it cannot guarantee how many records will be locked */
780 int tdb_chainlock(struct tdb_context *tdb, TDB_DATA key)
782 return chainlock(tdb, &key, F_WRLCK, TDB_LOCK_WAIT, "tdb_chainlock");
785 int tdb_chainunlock(struct tdb_context *tdb, TDB_DATA key)
787 uint64_t h = tdb_hash(tdb, key.dptr, key.dsize);
788 tdb_off_t lockstart, locksize;
789 unsigned int group, gbits;
791 gbits = TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS;
792 group = bits_from(h, 64 - gbits, gbits);
794 lockstart = hlock_range(group, &locksize);
796 tdb_trace_1rec(tdb, "tdb_chainunlock", key);
797 return tdb_unlock_hashes(tdb, lockstart, locksize, F_WRLCK);