tdb2: hash chaining
[ccan] / ccan / tdb2 / hash.c
1  /* 
2    Trivial Database 2: hash handling
3    Copyright (C) Rusty Russell 2010
4    
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.
9
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.
14
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/>.
17 */
18 #include "private.h"
19 #include <assert.h>
20 #include <ccan/hash/hash.h>
21
22 static uint64_t jenkins_hash(const void *key, size_t length, uint64_t seed,
23                              void *arg)
24 {
25         uint64_t ret;
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);
30 }
31
32 void tdb_hash_init(struct tdb_context *tdb)
33 {
34         tdb->khash = jenkins_hash;
35         tdb->hash_priv = NULL;
36 }
37
38 uint64_t tdb_hash(struct tdb_context *tdb, const void *ptr, size_t len)
39 {
40         return tdb->khash(ptr, len, tdb->hash_seed, tdb->hash_priv);
41 }
42
43 uint64_t hash_record(struct tdb_context *tdb, tdb_off_t off)
44 {
45         const struct tdb_used_record *r;
46         const void *key;
47         uint64_t klen, hash;
48
49         r = tdb_access_read(tdb, off, sizeof(*r), true);
50         if (!r)
51                 /* FIXME */
52                 return 0;
53
54         klen = rec_key_length(r);
55         tdb_access_release(tdb, r);
56
57         key = tdb_access_read(tdb, off + sizeof(*r), klen, false);
58         if (!key)
59                 return 0;
60
61         hash = tdb_hash(tdb, key, klen);
62         tdb_access_release(tdb, key);
63         return hash;
64 }
65
66 /* Get bits from a value. */
67 static uint32_t bits(uint64_t val, unsigned start, unsigned num)
68 {
69         assert(num <= 32);
70         return (val >> start) & ((1U << num) - 1);
71 }
72
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)
76 {
77         h->hash_used += num;
78         return bits(h->h, 64 - h->hash_used, num);
79 }
80
81 static bool key_matches(struct tdb_context *tdb,
82                         const struct tdb_used_record *rec,
83                         tdb_off_t off,
84                         const struct tdb_data *key)
85 {
86         bool ret = false;
87         const char *rkey;
88
89         if (rec_key_length(rec) != key->dsize) {
90                 add_stat(tdb, compare_wrong_keylen, 1);
91                 return ret;
92         }
93
94         rkey = tdb_access_read(tdb, off + sizeof(*rec), key->dsize, false);
95         if (!rkey)
96                 return ret;
97         if (memcmp(rkey, key->dptr, key->dsize) == 0)
98                 ret = true;
99         else
100                 add_stat(tdb, compare_wrong_keycmp, 1);
101         tdb_access_release(tdb, rkey);
102         return ret;
103 }
104
105 /* Does entry match? */
106 static bool match(struct tdb_context *tdb,
107                   struct hash_info *h,
108                   const struct tdb_data *key,
109                   tdb_off_t val,
110                   struct tdb_used_record *rec)
111 {
112         tdb_off_t off;
113
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);
118                 return false;
119         }
120
121         /* Top bits of offset == next bits of hash. */
122         if (bits(val, TDB_OFF_HASH_EXTRA_BIT, TDB_OFF_UPPER_STEAL_EXTRA)
123             != bits(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);
126                 return false;
127         }
128
129         off = val & TDB_OFF_MASK;
130         if (tdb_read_convert(tdb, off, rec, sizeof(*rec)) == -1)
131                 return false;
132
133         if ((h->h & ((1 << 11)-1)) != rec_hash(rec)) {
134                 add_stat(tdb, compare_wrong_rechash, 1);
135                 return false;
136         }
137
138         return key_matches(tdb, rec, off, key);
139 }
140
141 static tdb_off_t hbucket_off(tdb_off_t group_start, unsigned bucket)
142 {
143         return group_start
144                 + (bucket % (1 << TDB_HASH_GROUP_BITS)) * sizeof(tdb_off_t);
145 }
146
147 bool is_subhash(tdb_off_t val)
148 {
149         return (val >> TDB_OFF_UPPER_STEAL_SUBHASH_BIT) & 1;
150 }
151
152 /* FIXME: Guess the depth, don't over-lock! */
153 static tdb_off_t hlock_range(tdb_off_t group, tdb_off_t *size)
154 {
155         *size = 1ULL << (64 - (TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS));
156         return group << (64 - (TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS));
157 }
158
159 static tdb_off_t COLD find_in_chain(struct tdb_context *tdb,
160                                     struct tdb_data key,
161                                     tdb_off_t chain,
162                                     struct hash_info *h,
163                                     struct tdb_used_record *rec,
164                                     struct traverse_info *tinfo)
165 {
166         tdb_off_t off, next;
167
168         /* In case nothing is free, we set these to zero. */
169         h->home_bucket = h->found_bucket = 0;
170
171         for (off = chain; off; off = next) {
172                 unsigned int i;
173
174                 h->group_start = off;
175                 if (tdb_read_convert(tdb, off, h->group, sizeof(h->group)))
176                         return TDB_OFF_ERR;
177
178                 for (i = 0; i < (1 << TDB_HASH_GROUP_BITS); i++) {
179                         tdb_off_t recoff;
180                         if (!h->group[i]) {
181                                 /* Remember this empty bucket. */
182                                 h->home_bucket = h->found_bucket = i;
183                                 continue;
184                         }
185
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)))
190                                 return TDB_OFF_ERR;
191
192                         if (key_matches(tdb, rec, recoff, &key)) {
193                                 h->home_bucket = h->found_bucket = i;
194
195                                 if (tinfo) {
196                                         tinfo->levels[tinfo->num_levels]
197                                                 .hashtable = off;
198                                         tinfo->levels[tinfo->num_levels]
199                                                 .total_buckets
200                                                 = 1 << TDB_HASH_GROUP_BITS;
201                                         tinfo->levels[tinfo->num_levels].entry
202                                                 = i;
203                                         tinfo->num_levels++;
204                                 }
205                                 return recoff;
206                         }
207                 }
208                 next = tdb_read_off(tdb, off
209                                     + offsetof(struct tdb_chain, next));
210                 if (next == TDB_OFF_ERR)
211                         return TDB_OFF_ERR;
212                 if (next)
213                         next += sizeof(struct tdb_used_record);
214         }
215         return 0;
216 }
217
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,
224                         struct tdb_data key,
225                         int ltype,
226                         struct hash_info *h,
227                         struct tdb_used_record *rec,
228                         struct traverse_info *tinfo)
229 {
230         uint32_t i, group;
231         tdb_off_t hashtable;
232
233         h->h = tdb_hash(tdb, key.dptr, key.dsize);
234         h->hash_used = 0;
235         group = use_bits(h, TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS);
236         h->home_bucket = use_bits(h, TDB_HASH_GROUP_BITS);
237
238         h->hlock_start = hlock_range(group, &h->hlock_range);
239         if (tdb_lock_hashes(tdb, h->hlock_start, h->hlock_range, ltype,
240                             TDB_LOCK_WAIT))
241                 return TDB_OFF_ERR;
242
243         hashtable = offsetof(struct tdb_header, hashtable);
244         if (tinfo) {
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;
251         }
252
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);
257
258                 if (tdb_read_convert(tdb, h->group_start, &h->group,
259                                      sizeof(h->group)) == -1)
260                         goto fail;
261
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);
266                         if (tinfo) {
267                                 /* When we come back, use *next* bucket */
268                                 tinfo->levels[tinfo->num_levels-1].entry
269                                         += h->home_bucket + 1;
270                         }
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);
274                         if (tinfo) {
275                                 tinfo->levels[tinfo->num_levels].hashtable
276                                         = 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;
281                                 tinfo->num_levels++;
282                         }
283                         continue;
284                 }
285
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]))
292                                 continue;
293
294                         if (!h->group[h->found_bucket])
295                                 break;
296
297                         if (match(tdb, h, &key, h->group[h->found_bucket],
298                                   rec)) {
299                                 if (tinfo) {
300                                         tinfo->levels[tinfo->num_levels-1].entry
301                                                 += h->found_bucket;
302                                 }
303                                 return h->group[h->found_bucket] & TDB_OFF_MASK;
304                         }
305                 }
306                 /* Didn't find it: h indicates where it would go. */
307                 return 0;
308         }
309
310         return find_in_chain(tdb, key, hashtable, h, rec, tinfo);
311
312 fail:
313         tdb_unlock_hashes(tdb, h->hlock_start, h->hlock_range, ltype);
314         return TDB_OFF_ERR;
315 }
316
317 /* I wrote a simple test, expanding a hash to 2GB, for the following
318  * cases:
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,
322  *
323  * I measured the worst/average/best density during this process.
324  * 1) 3%/16%/30%
325  * 2) 4%/20%/38%
326  * 3) 6%/22%/41%
327  *
328  * So we figure out the busiest bucket for the moment.
329  */
330 static unsigned fullest_bucket(struct tdb_context *tdb,
331                                const tdb_off_t *group,
332                                unsigned new_bucket)
333 {
334         unsigned counts[1 << TDB_HASH_GROUP_BITS] = { 0 };
335         unsigned int i, best_bucket;
336
337         /* Count the new entry. */
338         counts[new_bucket]++;
339         best_bucket = new_bucket;
340
341         for (i = 0; i < (1 << TDB_HASH_GROUP_BITS); i++) {
342                 unsigned this_bucket;
343
344                 if (is_subhash(group[i]))
345                         continue;
346                 this_bucket = group[i] & TDB_OFF_HASH_GROUP_MASK;
347                 if (++counts[this_bucket] > counts[best_bucket])
348                         best_bucket = this_bucket;
349         }
350
351         return best_bucket;
352 }
353
354 static bool put_into_group(tdb_off_t *group,
355                            unsigned bucket, tdb_off_t encoded)
356 {
357         unsigned int i;
358
359         for (i = 0; i < (1 << TDB_HASH_GROUP_BITS); i++) {
360                 unsigned b = (bucket + i) % (1 << TDB_HASH_GROUP_BITS);
361
362                 if (group[b] == 0) {
363                         group[b] = encoded;
364                         return true;
365                 }
366         }
367         return false;
368 }
369
370 static void force_into_group(tdb_off_t *group,
371                              unsigned bucket, tdb_off_t encoded)
372 {
373         if (!put_into_group(group, bucket, encoded))
374                 abort();
375 }
376
377 static tdb_off_t encode_offset(tdb_off_t new_off, struct hash_info *h)
378 {
379         return h->home_bucket
380                 | new_off
381                 | ((uint64_t)bits(h->h,
382                                   64 - h->hash_used - TDB_OFF_UPPER_STEAL_EXTRA,
383                                   TDB_OFF_UPPER_STEAL_EXTRA)
384                    << TDB_OFF_HASH_EXTRA_BIT);
385 }
386
387 /* Simply overwrite the hash entry we found before. */ 
388 int replace_in_hash(struct tdb_context *tdb,
389                     struct hash_info *h,
390                     tdb_off_t new_off)
391 {
392         return tdb_write_off(tdb, hbucket_off(h->group_start, h->found_bucket),
393                              encode_offset(new_off, h));
394 }
395
396 /* We slot in anywhere that's empty in the chain. */
397 static int COLD add_to_chain(struct tdb_context *tdb,
398                              tdb_off_t subhash,
399                              tdb_off_t new_off)
400 {
401         size_t entry = tdb_find_zero_off(tdb, subhash, 1<<TDB_HASH_GROUP_BITS);
402
403         if (entry == 1 << TDB_HASH_GROUP_BITS) {
404                 tdb_off_t next;
405
406                 next = tdb_read_off(tdb, subhash
407                                     + offsetof(struct tdb_chain, next));
408                 if (next == TDB_OFF_ERR)
409                         return -1;
410
411                 if (!next) {
412                         next = alloc(tdb, 0, sizeof(struct tdb_chain), 2,
413                                      false);
414                         if (next == TDB_OFF_ERR)
415                                 return -1;
416                         if (zero_out(tdb, next+sizeof(struct tdb_used_record),
417                                      sizeof(struct tdb_chain)))
418                                 return -1;
419                         if (tdb_write_off(tdb, subhash
420                                           + offsetof(struct tdb_chain, next),
421                                           next) != 0)
422                                 return -1;
423                 }
424                 return add_to_chain(tdb, next, new_off);
425         }
426
427         return tdb_write_off(tdb, subhash + entry * sizeof(tdb_off_t),
428                              new_off);
429 }
430
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)
434 {
435         tdb_off_t off = (val & TDB_OFF_MASK), *group;
436         struct hash_info h;
437         unsigned int gnum;
438
439         h.hash_used = hash_used;
440
441         if (hash_used + TDB_SUBLEVEL_HASH_BITS > 64)
442                 return add_to_chain(tdb, subhash, off);
443
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);
449
450         group = tdb_access_write(tdb, h.group_start,
451                                  sizeof(*group) << TDB_HASH_GROUP_BITS, true);
452         if (!group)
453                 return -1;
454         force_into_group(group, h.home_bucket, encode_offset(off, &h));
455         return tdb_access_commit(tdb, group);
456 }
457
458 static int expand_group(struct tdb_context *tdb, struct hash_info *h)
459 {
460         unsigned bucket, num_vals, i, hash;
461         size_t subsize;
462         tdb_off_t subhash;
463         tdb_off_t vals[1 << TDB_HASH_GROUP_BITS];
464
465         /* Attach new empty subhash under fullest bucket. */
466         bucket = fullest_bucket(tdb, h->group, h->home_bucket);
467
468         if (h->hash_used == 64) {
469                 add_stat(tdb, alloc_chain, 1);
470                 subsize = sizeof(struct tdb_chain);
471                 hash = 2;
472         } else {
473                 add_stat(tdb, alloc_subhash, 1);
474                 subsize = (sizeof(tdb_off_t) << TDB_SUBLEVEL_HASH_BITS);
475                 hash = 0;
476         }
477
478         subhash = alloc(tdb, 0, subsize, hash, false);
479         if (subhash == TDB_OFF_ERR)
480                 return -1;
481
482         if (zero_out(tdb, subhash + sizeof(struct tdb_used_record), subsize))
483                 return -1;
484
485         /* Remove any which are destined for bucket or are in wrong place. */
486         num_vals = 0;
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]))
490                         continue;
491                 if (home_bucket == bucket || home_bucket != i) {
492                         vals[num_vals++] = h->group[i];
493                         h->group[i] = 0;
494                 }
495         }
496         /* FIXME: This assert is valid, but we do this during unit test :( */
497         /* assert(num_vals); */
498
499         /* Overwrite expanded bucket with subhash pointer. */
500         h->group[bucket] = subhash | (1ULL << TDB_OFF_UPPER_STEAL_SUBHASH_BIT);
501
502         /* Point to actual contents of record. */
503         subhash += sizeof(struct tdb_used_record);
504
505         /* Put values back. */
506         for (i = 0; i < num_vals; i++) {
507                 unsigned this_bucket = vals[i] & TDB_OFF_HASH_GROUP_MASK;
508
509                 if (this_bucket == bucket) {
510                         if (add_to_subhash(tdb, subhash, h->hash_used, vals[i]))
511                                 return -1;
512                 } else {
513                         /* There should be room to put this back. */
514                         force_into_group(h->group, this_bucket, vals[i]);
515                 }
516         }
517         return 0;
518 }
519
520 int delete_from_hash(struct tdb_context *tdb, struct hash_info *h)
521 {
522         unsigned int i, num_movers = 0;
523         tdb_off_t movers[1 << TDB_HASH_GROUP_BITS];
524
525         h->group[h->found_bucket] = 0;
526         for (i = 1; i < (1 << TDB_HASH_GROUP_BITS); i++) {
527                 unsigned this_bucket;
528
529                 this_bucket = (h->found_bucket+i) % (1 << TDB_HASH_GROUP_BITS);
530                 /* Empty bucket?  We're done. */
531                 if (!h->group[this_bucket])
532                         break;
533
534                 /* Ignore subhashes. */
535                 if (is_subhash(h->group[this_bucket]))
536                         continue;
537
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)
540                     != this_bucket) {
541                         movers[num_movers++] = h->group[this_bucket];
542                         h->group[this_bucket] = 0;
543                 }
544         }
545
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,
549                                  movers[i]);
550         }
551
552         /* Now we write back the hash group */
553         return tdb_write_convert(tdb, h->group_start,
554                                  h->group, sizeof(h->group));
555 }
556
557 int add_to_hash(struct tdb_context *tdb, struct hash_info *h, tdb_off_t new_off)
558 {
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));
565         }
566
567         if (h->hash_used > 64)
568                 return add_to_chain(tdb, h->group_start, new_off);
569
570         /* We're full.  Expand. */
571         if (expand_group(tdb, h) == -1)
572                 return -1;
573
574         if (is_subhash(h->group[h->home_bucket])) {
575                 /* We were expanded! */
576                 tdb_off_t hashtable;
577                 unsigned int gnum;
578
579                 /* Write back the modified group. */
580                 if (tdb_write_convert(tdb, h->group_start, h->group,
581                                       sizeof(h->group)))
582                         return -1;
583
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)
593                         return -1;
594         }
595
596         /* Expanding the group must have made room if it didn't choose this
597          * bucket. */
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));
601
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);
605 }
606
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)
610 {
611         tdb_off_t off, val;
612         unsigned int i;
613         struct traverse_level *tlevel;
614
615         tlevel = &tinfo->levels[tinfo->num_levels-1];
616
617 again:
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))
625                         return TDB_OFF_ERR;
626
627                 off = val & TDB_OFF_MASK;
628
629                 /* This makes the delete-all-in-traverse case work
630                  * (and simplifies our logic a little). */
631                 if (off == tinfo->prev)
632                         continue;
633
634                 tlevel->entry = i;
635
636                 if (!is_subhash(val)) {
637                         /* Found one. */
638                         tinfo->prev = off;
639                         return off;
640                 }
641
642                 /* When we come back, we want the next one */
643                 tlevel->entry++;
644                 tinfo->num_levels++;
645                 tlevel++;
646                 tlevel->hashtable = off + sizeof(struct tdb_used_record);
647                 tlevel->entry = 0;
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);
651                 else
652                         tlevel->total_buckets = (1 << TDB_SUBLEVEL_HASH_BITS);
653                 goto again;
654         }
655
656         /* Nothing there? */
657         if (tinfo->num_levels == 1)
658                 return 0;
659
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,
664                                                             next));
665                 if (tlevel->hashtable == TDB_OFF_ERR)
666                         return TDB_OFF_ERR;
667                 if (tlevel->hashtable) {
668                         tlevel->hashtable += sizeof(struct tdb_used_record);
669                         tlevel->entry = 0;
670                         goto again;
671                 }
672         }
673
674         /* Go back up and keep searching. */
675         tinfo->num_levels--;
676         tlevel--;
677         goto again;
678 }
679
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)
684 {
685         const unsigned group_bits = TDB_TOPLEVEL_HASH_BITS-TDB_HASH_GROUP_BITS;
686         tdb_off_t hlock_start, hlock_range, off;
687
688         while (tinfo->toplevel_group < (1 << group_bits)) {
689                 hlock_start = (tdb_off_t)tinfo->toplevel_group
690                         << (64 - group_bits);
691                 hlock_range = 1ULL << group_bits;
692                 if (tdb_lock_hashes(tdb, hlock_start, hlock_range, ltype,
693                                     TDB_LOCK_WAIT) != 0)
694                         return -1;
695
696                 off = iterate_hash(tdb, tinfo);
697                 if (off) {
698                         struct tdb_used_record rec;
699
700                         if (tdb_read_convert(tdb, off, &rec, sizeof(rec))) {
701                                 tdb_unlock_hashes(tdb,
702                                                   hlock_start, hlock_range,
703                                                   ltype);
704                                 return -1;
705                         }
706                         if (rec_magic(&rec) != TDB_MAGIC) {
707                                 tdb_logerr(tdb, TDB_ERR_CORRUPT,
708                                            TDB_DEBUG_FATAL,
709                                            "next_in_hash:"
710                                            " corrupt record at %llu",
711                                            (long long)off);
712                                 return -1;
713                         }
714
715                         kbuf->dsize = rec_key_length(&rec);
716
717                         /* They want data as well? */
718                         if (dlen) {
719                                 *dlen = rec_data_length(&rec);
720                                 kbuf->dptr = tdb_alloc_read(tdb, 
721                                                             off + sizeof(rec),
722                                                             kbuf->dsize
723                                                             + *dlen);
724                         } else {
725                                 kbuf->dptr = tdb_alloc_read(tdb, 
726                                                             off + sizeof(rec),
727                                                             kbuf->dsize);
728                         }
729                         tdb_unlock_hashes(tdb, hlock_start, hlock_range, ltype);
730                         return kbuf->dptr ? 1 : -1;
731                 }
732
733                 tdb_unlock_hashes(tdb, hlock_start, hlock_range, ltype);
734
735                 tinfo->toplevel_group++;
736                 tinfo->levels[0].hashtable
737                         += (sizeof(tdb_off_t) << TDB_HASH_GROUP_BITS);
738                 tinfo->levels[0].entry = 0;
739         }
740         return 0;
741 }
742
743 /* Return 1 if we find something, 0 if not, -1 on error. */
744 int first_in_hash(struct tdb_context *tdb, int ltype,
745                   struct traverse_info *tinfo,
746                   TDB_DATA *kbuf, size_t *dlen)
747 {
748         tinfo->prev = 0;
749         tinfo->toplevel_group = 0;
750         tinfo->num_levels = 1;
751         tinfo->levels[0].hashtable = offsetof(struct tdb_header, hashtable);
752         tinfo->levels[0].entry = 0;
753         tinfo->levels[0].total_buckets = (1 << TDB_HASH_GROUP_BITS);
754
755         return next_in_hash(tdb, ltype, tinfo, kbuf, dlen);
756 }
757
758 /* Even if the entry isn't in this hash bucket, you'd have to lock this
759  * bucket to find it. */
760 static int chainlock(struct tdb_context *tdb, const TDB_DATA *key,
761                      int ltype, enum tdb_lock_flags waitflag,
762                      const char *func)
763 {
764         int ret;
765         uint64_t h = tdb_hash(tdb, key->dptr, key->dsize);
766         tdb_off_t lockstart, locksize;
767         unsigned int group, gbits;
768
769         gbits = TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS;
770         group = bits(h, 64 - gbits, gbits);
771
772         lockstart = hlock_range(group, &locksize);
773
774         ret = tdb_lock_hashes(tdb, lockstart, locksize, ltype, waitflag);
775         tdb_trace_1rec(tdb, func, *key);
776         return ret;
777 }
778
779 /* lock/unlock one hash chain. This is meant to be used to reduce
780    contention - it cannot guarantee how many records will be locked */
781 int tdb_chainlock(struct tdb_context *tdb, TDB_DATA key)
782 {
783         return chainlock(tdb, &key, F_WRLCK, TDB_LOCK_WAIT, "tdb_chainlock");
784 }
785
786 int tdb_chainunlock(struct tdb_context *tdb, TDB_DATA key)
787 {
788         uint64_t h = tdb_hash(tdb, key.dptr, key.dsize);
789         tdb_off_t lockstart, locksize;
790         unsigned int group, gbits;
791
792         gbits = TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS;
793         group = bits(h, 64 - gbits, gbits);
794
795         lockstart = hlock_range(group, &locksize);
796
797         tdb_trace_1rec(tdb, "tdb_chainunlock", key);
798         return tdb_unlock_hashes(tdb, lockstart, locksize, F_WRLCK);
799 }