]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/hash.c
67bb56f45a1988495ca0d96667462ad96a8c67b6
[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 (TDB_PTR_IS_ERR(r)) {
51                 tdb->ecode = TDB_PTR_ERR(r);
52                 /* FIXME */
53                 return 0;
54         }
55
56         klen = rec_key_length(r);
57         tdb_access_release(tdb, r);
58
59         key = tdb_access_read(tdb, off + sizeof(*r), klen, false);
60         if (TDB_PTR_IS_ERR(key)) {
61                 tdb->ecode = TDB_PTR_ERR(key);
62                 return 0;
63         }
64
65         hash = tdb_hash(tdb, key, klen);
66         tdb_access_release(tdb, key);
67         return hash;
68 }
69
70 /* Get bits from a value. */
71 static uint32_t bits_from(uint64_t val, unsigned start, unsigned num)
72 {
73         assert(num <= 32);
74         return (val >> start) & ((1U << num) - 1);
75 }
76
77 /* We take bits from the top: that way we can lock whole sections of the hash
78  * by using lock ranges. */
79 static uint32_t use_bits(struct hash_info *h, unsigned num)
80 {
81         h->hash_used += num;
82         return bits_from(h->h, 64 - h->hash_used, num);
83 }
84
85 static bool key_matches(struct tdb_context *tdb,
86                         const struct tdb_used_record *rec,
87                         tdb_off_t off,
88                         const struct tdb_data *key)
89 {
90         bool ret = false;
91         const char *rkey;
92
93         if (rec_key_length(rec) != key->dsize) {
94                 add_stat(tdb, compare_wrong_keylen, 1);
95                 return ret;
96         }
97
98         rkey = tdb_access_read(tdb, off + sizeof(*rec), key->dsize, false);
99         if (TDB_PTR_IS_ERR(rkey)) {
100                 tdb->ecode = TDB_PTR_ERR(rkey);
101                 return ret;
102         }
103         if (memcmp(rkey, key->dptr, key->dsize) == 0)
104                 ret = true;
105         else
106                 add_stat(tdb, compare_wrong_keycmp, 1);
107         tdb_access_release(tdb, rkey);
108         return ret;
109 }
110
111 /* Does entry match? */
112 static bool match(struct tdb_context *tdb,
113                   struct hash_info *h,
114                   const struct tdb_data *key,
115                   tdb_off_t val,
116                   struct tdb_used_record *rec)
117 {
118         tdb_off_t off;
119         enum TDB_ERROR ecode;
120
121         add_stat(tdb, compares, 1);
122         /* Desired bucket must match. */
123         if (h->home_bucket != (val & TDB_OFF_HASH_GROUP_MASK)) {
124                 add_stat(tdb, compare_wrong_bucket, 1);
125                 return false;
126         }
127
128         /* Top bits of offset == next bits of hash. */
129         if (bits_from(val, TDB_OFF_HASH_EXTRA_BIT, TDB_OFF_UPPER_STEAL_EXTRA)
130             != bits_from(h->h, 64 - h->hash_used - TDB_OFF_UPPER_STEAL_EXTRA,
131                     TDB_OFF_UPPER_STEAL_EXTRA)) {
132                 add_stat(tdb, compare_wrong_offsetbits, 1);
133                 return false;
134         }
135
136         off = val & TDB_OFF_MASK;
137         ecode = tdb_read_convert(tdb, off, rec, sizeof(*rec));
138         if (ecode != TDB_SUCCESS) {
139                 tdb->ecode = ecode;
140                 return false;
141         }
142
143         if ((h->h & ((1 << 11)-1)) != rec_hash(rec)) {
144                 add_stat(tdb, compare_wrong_rechash, 1);
145                 return false;
146         }
147
148         return key_matches(tdb, rec, off, key);
149 }
150
151 static tdb_off_t hbucket_off(tdb_off_t group_start, unsigned bucket)
152 {
153         return group_start
154                 + (bucket % (1 << TDB_HASH_GROUP_BITS)) * sizeof(tdb_off_t);
155 }
156
157 bool is_subhash(tdb_off_t val)
158 {
159         return (val >> TDB_OFF_UPPER_STEAL_SUBHASH_BIT) & 1;
160 }
161
162 /* FIXME: Guess the depth, don't over-lock! */
163 static tdb_off_t hlock_range(tdb_off_t group, tdb_off_t *size)
164 {
165         *size = 1ULL << (64 - (TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS));
166         return group << (64 - (TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS));
167 }
168
169 static tdb_off_t COLD find_in_chain(struct tdb_context *tdb,
170                                     struct tdb_data key,
171                                     tdb_off_t chain,
172                                     struct hash_info *h,
173                                     struct tdb_used_record *rec,
174                                     struct traverse_info *tinfo)
175 {
176         tdb_off_t off, next;
177         enum TDB_ERROR ecode;
178
179         /* In case nothing is free, we set these to zero. */
180         h->home_bucket = h->found_bucket = 0;
181
182         for (off = chain; off; off = next) {
183                 unsigned int i;
184
185                 h->group_start = off;
186                 ecode = tdb_read_convert(tdb, off, h->group, sizeof(h->group));
187                 if (ecode != TDB_SUCCESS) {
188                         tdb->ecode = ecode;
189                         return TDB_OFF_ERR;
190                 }
191
192                 for (i = 0; i < (1 << TDB_HASH_GROUP_BITS); i++) {
193                         tdb_off_t recoff;
194                         if (!h->group[i]) {
195                                 /* Remember this empty bucket. */
196                                 h->home_bucket = h->found_bucket = i;
197                                 continue;
198                         }
199
200                         /* We can insert extra bits via add_to_hash
201                          * empty bucket logic. */
202                         recoff = h->group[i] & TDB_OFF_MASK;
203                         ecode = tdb_read_convert(tdb, recoff, rec,
204                                                  sizeof(*rec));
205                         if (ecode != TDB_SUCCESS) {
206                                 tdb->ecode = ecode;
207                                 return TDB_OFF_ERR;
208                         }
209
210                         if (key_matches(tdb, rec, recoff, &key)) {
211                                 h->home_bucket = h->found_bucket = i;
212
213                                 if (tinfo) {
214                                         tinfo->levels[tinfo->num_levels]
215                                                 .hashtable = off;
216                                         tinfo->levels[tinfo->num_levels]
217                                                 .total_buckets
218                                                 = 1 << TDB_HASH_GROUP_BITS;
219                                         tinfo->levels[tinfo->num_levels].entry
220                                                 = i;
221                                         tinfo->num_levels++;
222                                 }
223                                 return recoff;
224                         }
225                 }
226                 next = tdb_read_off(tdb, off
227                                     + offsetof(struct tdb_chain, next));
228                 if (TDB_OFF_IS_ERR(next)) {
229                         tdb->ecode = next;
230                         return TDB_OFF_ERR;
231                 }
232                 if (next)
233                         next += sizeof(struct tdb_used_record);
234         }
235         return 0;
236 }
237
238 /* This is the core routine which searches the hashtable for an entry.
239  * On error, no locks are held and TDB_OFF_ERR is returned.
240  * Otherwise, hinfo is filled in (and the optional tinfo).
241  * If not found, the return value is 0.
242  * If found, the return value is the offset, and *rec is the record. */
243 tdb_off_t find_and_lock(struct tdb_context *tdb,
244                         struct tdb_data key,
245                         int ltype,
246                         struct hash_info *h,
247                         struct tdb_used_record *rec,
248                         struct traverse_info *tinfo)
249 {
250         uint32_t i, group;
251         tdb_off_t hashtable;
252         enum TDB_ERROR ecode;
253
254         h->h = tdb_hash(tdb, key.dptr, key.dsize);
255         h->hash_used = 0;
256         group = use_bits(h, TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS);
257         h->home_bucket = use_bits(h, TDB_HASH_GROUP_BITS);
258
259         h->hlock_start = hlock_range(group, &h->hlock_range);
260         ecode = tdb_lock_hashes(tdb, h->hlock_start, h->hlock_range, ltype,
261                                 TDB_LOCK_WAIT);
262         if (ecode != TDB_SUCCESS) {
263                 tdb->ecode = ecode;
264                 return TDB_OFF_ERR;
265         }
266
267         hashtable = offsetof(struct tdb_header, hashtable);
268         if (tinfo) {
269                 tinfo->toplevel_group = group;
270                 tinfo->num_levels = 1;
271                 tinfo->levels[0].entry = 0;
272                 tinfo->levels[0].hashtable = hashtable
273                         + (group << TDB_HASH_GROUP_BITS) * sizeof(tdb_off_t);
274                 tinfo->levels[0].total_buckets = 1 << TDB_HASH_GROUP_BITS;
275         }
276
277         while (h->hash_used <= 64) {
278                 /* Read in the hash group. */
279                 h->group_start = hashtable
280                         + group * (sizeof(tdb_off_t) << TDB_HASH_GROUP_BITS);
281
282                 ecode = tdb_read_convert(tdb, h->group_start, &h->group,
283                                          sizeof(h->group));
284                 if (ecode != TDB_SUCCESS) {
285                         tdb->ecode = ecode;
286                         goto fail;
287                 }
288
289                 /* Pointer to another hash table?  Go down... */
290                 if (is_subhash(h->group[h->home_bucket])) {
291                         hashtable = (h->group[h->home_bucket] & TDB_OFF_MASK)
292                                 + sizeof(struct tdb_used_record);
293                         if (tinfo) {
294                                 /* When we come back, use *next* bucket */
295                                 tinfo->levels[tinfo->num_levels-1].entry
296                                         += h->home_bucket + 1;
297                         }
298                         group = use_bits(h, TDB_SUBLEVEL_HASH_BITS
299                                          - TDB_HASH_GROUP_BITS);
300                         h->home_bucket = use_bits(h, TDB_HASH_GROUP_BITS);
301                         if (tinfo) {
302                                 tinfo->levels[tinfo->num_levels].hashtable
303                                         = hashtable;
304                                 tinfo->levels[tinfo->num_levels].total_buckets
305                                         = 1 << TDB_SUBLEVEL_HASH_BITS;
306                                 tinfo->levels[tinfo->num_levels].entry
307                                         = group << TDB_HASH_GROUP_BITS;
308                                 tinfo->num_levels++;
309                         }
310                         continue;
311                 }
312
313                 /* It's in this group: search (until 0 or all searched) */
314                 for (i = 0, h->found_bucket = h->home_bucket;
315                      i < (1 << TDB_HASH_GROUP_BITS);
316                      i++, h->found_bucket = ((h->found_bucket+1)
317                                              % (1 << TDB_HASH_GROUP_BITS))) {
318                         if (is_subhash(h->group[h->found_bucket]))
319                                 continue;
320
321                         if (!h->group[h->found_bucket])
322                                 break;
323
324                         if (match(tdb, h, &key, h->group[h->found_bucket],
325                                   rec)) {
326                                 if (tinfo) {
327                                         tinfo->levels[tinfo->num_levels-1].entry
328                                                 += h->found_bucket;
329                                 }
330                                 return h->group[h->found_bucket] & TDB_OFF_MASK;
331                         }
332                 }
333                 /* Didn't find it: h indicates where it would go. */
334                 return 0;
335         }
336
337         return find_in_chain(tdb, key, hashtable, h, rec, tinfo);
338
339 fail:
340         tdb_unlock_hashes(tdb, h->hlock_start, h->hlock_range, ltype);
341         return TDB_OFF_ERR;
342 }
343
344 /* I wrote a simple test, expanding a hash to 2GB, for the following
345  * cases:
346  * 1) Expanding all the buckets at once,
347  * 2) Expanding the bucket we wanted to place the new entry into.
348  * 3) Expanding the most-populated bucket,
349  *
350  * I measured the worst/average/best density during this process.
351  * 1) 3%/16%/30%
352  * 2) 4%/20%/38%
353  * 3) 6%/22%/41%
354  *
355  * So we figure out the busiest bucket for the moment.
356  */
357 static unsigned fullest_bucket(struct tdb_context *tdb,
358                                const tdb_off_t *group,
359                                unsigned new_bucket)
360 {
361         unsigned counts[1 << TDB_HASH_GROUP_BITS] = { 0 };
362         unsigned int i, best_bucket;
363
364         /* Count the new entry. */
365         counts[new_bucket]++;
366         best_bucket = new_bucket;
367
368         for (i = 0; i < (1 << TDB_HASH_GROUP_BITS); i++) {
369                 unsigned this_bucket;
370
371                 if (is_subhash(group[i]))
372                         continue;
373                 this_bucket = group[i] & TDB_OFF_HASH_GROUP_MASK;
374                 if (++counts[this_bucket] > counts[best_bucket])
375                         best_bucket = this_bucket;
376         }
377
378         return best_bucket;
379 }
380
381 static bool put_into_group(tdb_off_t *group,
382                            unsigned bucket, tdb_off_t encoded)
383 {
384         unsigned int i;
385
386         for (i = 0; i < (1 << TDB_HASH_GROUP_BITS); i++) {
387                 unsigned b = (bucket + i) % (1 << TDB_HASH_GROUP_BITS);
388
389                 if (group[b] == 0) {
390                         group[b] = encoded;
391                         return true;
392                 }
393         }
394         return false;
395 }
396
397 static void force_into_group(tdb_off_t *group,
398                              unsigned bucket, tdb_off_t encoded)
399 {
400         if (!put_into_group(group, bucket, encoded))
401                 abort();
402 }
403
404 static tdb_off_t encode_offset(tdb_off_t new_off, struct hash_info *h)
405 {
406         return h->home_bucket
407                 | new_off
408                 | ((uint64_t)bits_from(h->h,
409                                   64 - h->hash_used - TDB_OFF_UPPER_STEAL_EXTRA,
410                                   TDB_OFF_UPPER_STEAL_EXTRA)
411                    << TDB_OFF_HASH_EXTRA_BIT);
412 }
413
414 /* Simply overwrite the hash entry we found before. */
415 int replace_in_hash(struct tdb_context *tdb,
416                     struct hash_info *h,
417                     tdb_off_t new_off)
418 {
419         enum TDB_ERROR ecode;
420
421         ecode = tdb_write_off(tdb, hbucket_off(h->group_start, h->found_bucket),
422                               encode_offset(new_off, h));
423         if (ecode != TDB_SUCCESS) {
424                 tdb->ecode = ecode;
425                 return -1;
426         }
427         return 0;
428 }
429
430 /* We slot in anywhere that's empty in the chain. */
431 static int COLD add_to_chain(struct tdb_context *tdb,
432                              tdb_off_t subhash,
433                              tdb_off_t new_off)
434 {
435         tdb_off_t entry;
436         enum TDB_ERROR ecode;
437
438         entry = tdb_find_zero_off(tdb, subhash, 1<<TDB_HASH_GROUP_BITS);
439         if (TDB_OFF_IS_ERR(entry)) {
440                 tdb->ecode = entry;
441                 return -1;
442         }
443
444         if (entry == 1 << TDB_HASH_GROUP_BITS) {
445                 tdb_off_t next;
446
447                 next = tdb_read_off(tdb, subhash
448                                     + offsetof(struct tdb_chain, next));
449                 if (TDB_OFF_IS_ERR(next)) {
450                         tdb->ecode = next;
451                         return -1;
452                 }
453
454                 if (!next) {
455                         next = alloc(tdb, 0, sizeof(struct tdb_chain), 0,
456                                      TDB_CHAIN_MAGIC, false);
457                         if (next == TDB_OFF_ERR)
458                                 return -1;
459                         ecode = zero_out(tdb,
460                                          next+sizeof(struct tdb_used_record),
461                                          sizeof(struct tdb_chain));
462                         if (ecode != TDB_SUCCESS) {
463                                 tdb->ecode = ecode;
464                                 return -1;
465                         }
466                         ecode = tdb_write_off(tdb, subhash
467                                               + offsetof(struct tdb_chain,
468                                                          next),
469                                               next);
470                         if (ecode != TDB_SUCCESS) {
471                                 tdb->ecode = ecode;
472                                 return -1;
473                         }
474                 }
475                 return add_to_chain(tdb, next, new_off);
476         }
477
478         ecode = tdb_write_off(tdb, subhash + entry * sizeof(tdb_off_t),
479                               new_off);
480         if (ecode != TDB_SUCCESS) {
481                 tdb->ecode = ecode;
482                 return -1;
483         }
484         return 0;
485 }
486
487 /* Add into a newly created subhash. */
488 static int add_to_subhash(struct tdb_context *tdb, tdb_off_t subhash,
489                           unsigned hash_used, tdb_off_t val)
490 {
491         tdb_off_t off = (val & TDB_OFF_MASK), *group;
492         struct hash_info h;
493         unsigned int gnum;
494         enum TDB_ERROR ecode;
495
496         h.hash_used = hash_used;
497
498         if (hash_used + TDB_SUBLEVEL_HASH_BITS > 64)
499                 return add_to_chain(tdb, subhash, off);
500
501         h.h = hash_record(tdb, off);
502         gnum = use_bits(&h, TDB_SUBLEVEL_HASH_BITS-TDB_HASH_GROUP_BITS);
503         h.group_start = subhash
504                 + gnum * (sizeof(tdb_off_t) << TDB_HASH_GROUP_BITS);
505         h.home_bucket = use_bits(&h, TDB_HASH_GROUP_BITS);
506
507         group = tdb_access_write(tdb, h.group_start,
508                                  sizeof(*group) << TDB_HASH_GROUP_BITS, true);
509         if (TDB_PTR_IS_ERR(group)) {
510                 tdb->ecode = TDB_PTR_ERR(group);
511                 return -1;
512         }
513         force_into_group(group, h.home_bucket, encode_offset(off, &h));
514         ecode = tdb_access_commit(tdb, group);
515         if (ecode != TDB_SUCCESS) {
516                 tdb->ecode = ecode;
517                 return -1;
518         }
519         return 0;
520 }
521
522 static int expand_group(struct tdb_context *tdb, struct hash_info *h)
523 {
524         unsigned bucket, num_vals, i, magic;
525         size_t subsize;
526         tdb_off_t subhash;
527         tdb_off_t vals[1 << TDB_HASH_GROUP_BITS];
528         enum TDB_ERROR ecode;
529
530         /* Attach new empty subhash under fullest bucket. */
531         bucket = fullest_bucket(tdb, h->group, h->home_bucket);
532
533         if (h->hash_used == 64) {
534                 add_stat(tdb, alloc_chain, 1);
535                 subsize = sizeof(struct tdb_chain);
536                 magic = TDB_CHAIN_MAGIC;
537         } else {
538                 add_stat(tdb, alloc_subhash, 1);
539                 subsize = (sizeof(tdb_off_t) << TDB_SUBLEVEL_HASH_BITS);
540                 magic = TDB_HTABLE_MAGIC;
541         }
542
543         subhash = alloc(tdb, 0, subsize, 0, magic, false);
544         if (subhash == TDB_OFF_ERR)
545                 return -1;
546
547         ecode = zero_out(tdb, subhash + sizeof(struct tdb_used_record),
548                          subsize);
549         if (ecode != TDB_SUCCESS) {
550                 tdb->ecode = ecode;
551                 return -1;
552         }
553
554         /* Remove any which are destined for bucket or are in wrong place. */
555         num_vals = 0;
556         for (i = 0; i < (1 << TDB_HASH_GROUP_BITS); i++) {
557                 unsigned home_bucket = h->group[i] & TDB_OFF_HASH_GROUP_MASK;
558                 if (!h->group[i] || is_subhash(h->group[i]))
559                         continue;
560                 if (home_bucket == bucket || home_bucket != i) {
561                         vals[num_vals++] = h->group[i];
562                         h->group[i] = 0;
563                 }
564         }
565         /* FIXME: This assert is valid, but we do this during unit test :( */
566         /* assert(num_vals); */
567
568         /* Overwrite expanded bucket with subhash pointer. */
569         h->group[bucket] = subhash | (1ULL << TDB_OFF_UPPER_STEAL_SUBHASH_BIT);
570
571         /* Point to actual contents of record. */
572         subhash += sizeof(struct tdb_used_record);
573
574         /* Put values back. */
575         for (i = 0; i < num_vals; i++) {
576                 unsigned this_bucket = vals[i] & TDB_OFF_HASH_GROUP_MASK;
577
578                 if (this_bucket == bucket) {
579                         if (add_to_subhash(tdb, subhash, h->hash_used, vals[i]))
580                                 return -1;
581                 } else {
582                         /* There should be room to put this back. */
583                         force_into_group(h->group, this_bucket, vals[i]);
584                 }
585         }
586         return 0;
587 }
588
589 int delete_from_hash(struct tdb_context *tdb, struct hash_info *h)
590 {
591         unsigned int i, num_movers = 0;
592         tdb_off_t movers[1 << TDB_HASH_GROUP_BITS];
593         enum TDB_ERROR ecode;
594
595         h->group[h->found_bucket] = 0;
596         for (i = 1; i < (1 << TDB_HASH_GROUP_BITS); i++) {
597                 unsigned this_bucket;
598
599                 this_bucket = (h->found_bucket+i) % (1 << TDB_HASH_GROUP_BITS);
600                 /* Empty bucket?  We're done. */
601                 if (!h->group[this_bucket])
602                         break;
603
604                 /* Ignore subhashes. */
605                 if (is_subhash(h->group[this_bucket]))
606                         continue;
607
608                 /* If this one is not happy where it is, we'll move it. */
609                 if ((h->group[this_bucket] & TDB_OFF_HASH_GROUP_MASK)
610                     != this_bucket) {
611                         movers[num_movers++] = h->group[this_bucket];
612                         h->group[this_bucket] = 0;
613                 }
614         }
615
616         /* Put back the ones we erased. */
617         for (i = 0; i < num_movers; i++) {
618                 force_into_group(h->group, movers[i] & TDB_OFF_HASH_GROUP_MASK,
619                                  movers[i]);
620         }
621
622         /* Now we write back the hash group */
623         ecode = tdb_write_convert(tdb, h->group_start,
624                                   h->group, sizeof(h->group));
625         if (ecode != TDB_SUCCESS) {
626                 tdb->ecode = ecode;
627                 return -1;
628         }
629         return 0;
630 }
631
632 int add_to_hash(struct tdb_context *tdb, struct hash_info *h, tdb_off_t new_off)
633 {
634         enum TDB_ERROR ecode;
635
636         /* We hit an empty bucket during search?  That's where it goes. */
637         if (!h->group[h->found_bucket]) {
638                 h->group[h->found_bucket] = encode_offset(new_off, h);
639                 /* Write back the modified group. */
640                 ecode = tdb_write_convert(tdb, h->group_start,
641                                           h->group, sizeof(h->group));
642                 if (ecode != TDB_SUCCESS) {
643                         tdb->ecode = ecode;
644                         return -1;
645                 }
646                 return 0;
647         }
648
649         if (h->hash_used > 64)
650                 return add_to_chain(tdb, h->group_start, new_off);
651
652         /* We're full.  Expand. */
653         if (expand_group(tdb, h) == -1)
654                 return -1;
655
656         if (is_subhash(h->group[h->home_bucket])) {
657                 /* We were expanded! */
658                 tdb_off_t hashtable;
659                 unsigned int gnum;
660
661                 /* Write back the modified group. */
662                 ecode = tdb_write_convert(tdb, h->group_start, h->group,
663                                           sizeof(h->group));
664                 if (ecode != TDB_SUCCESS) {
665                         tdb->ecode = ecode;
666                         return -1;
667                 }
668
669                 /* Move hashinfo down a level. */
670                 hashtable = (h->group[h->home_bucket] & TDB_OFF_MASK)
671                         + sizeof(struct tdb_used_record);
672                 gnum = use_bits(h,TDB_SUBLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS);
673                 h->home_bucket = use_bits(h, TDB_HASH_GROUP_BITS);
674                 h->group_start = hashtable
675                         + gnum * (sizeof(tdb_off_t) << TDB_HASH_GROUP_BITS);
676                 ecode = tdb_read_convert(tdb, h->group_start, &h->group,
677                                          sizeof(h->group));
678                 if (ecode != TDB_SUCCESS) {
679                         tdb->ecode = ecode;
680                         return -1;
681                 }
682         }
683
684         /* Expanding the group must have made room if it didn't choose this
685          * bucket. */
686         if (put_into_group(h->group, h->home_bucket, encode_offset(new_off,h))){
687                 ecode = tdb_write_convert(tdb, h->group_start,
688                                           h->group, sizeof(h->group));
689                 if (ecode != TDB_SUCCESS) {
690                         tdb->ecode = ecode;
691                         return -1;
692                 }
693                 return 0;
694         }
695
696         /* This can happen if all hashes in group (and us) dropped into same
697          * group in subhash. */
698         return add_to_hash(tdb, h, new_off);
699 }
700
701 /* Traverse support: returns offset of record, or 0 or TDB_OFF_ERR. */
702 static tdb_off_t iterate_hash(struct tdb_context *tdb,
703                               struct traverse_info *tinfo)
704 {
705         tdb_off_t off, val, i;
706         struct traverse_level *tlevel;
707
708         tlevel = &tinfo->levels[tinfo->num_levels-1];
709
710 again:
711         for (i = tdb_find_nonzero_off(tdb, tlevel->hashtable,
712                                       tlevel->entry, tlevel->total_buckets);
713              i != tlevel->total_buckets;
714              i = tdb_find_nonzero_off(tdb, tlevel->hashtable,
715                                       i+1, tlevel->total_buckets)) {
716                 if (TDB_OFF_IS_ERR(i)) {
717                         tdb->ecode = i;
718                         return TDB_OFF_ERR;
719                 }
720
721                 val = tdb_read_off(tdb, tlevel->hashtable+sizeof(tdb_off_t)*i);
722                 if (TDB_OFF_IS_ERR(val)) {
723                         tdb->ecode = val;
724                         return TDB_OFF_ERR;
725                 }
726
727                 off = val & TDB_OFF_MASK;
728
729                 /* This makes the delete-all-in-traverse case work
730                  * (and simplifies our logic a little). */
731                 if (off == tinfo->prev)
732                         continue;
733
734                 tlevel->entry = i;
735
736                 if (!is_subhash(val)) {
737                         /* Found one. */
738                         tinfo->prev = off;
739                         return off;
740                 }
741
742                 /* When we come back, we want the next one */
743                 tlevel->entry++;
744                 tinfo->num_levels++;
745                 tlevel++;
746                 tlevel->hashtable = off + sizeof(struct tdb_used_record);
747                 tlevel->entry = 0;
748                 /* Next level is a chain? */
749                 if (unlikely(tinfo->num_levels == TDB_MAX_LEVELS + 1))
750                         tlevel->total_buckets = (1 << TDB_HASH_GROUP_BITS);
751                 else
752                         tlevel->total_buckets = (1 << TDB_SUBLEVEL_HASH_BITS);
753                 goto again;
754         }
755
756         /* Nothing there? */
757         if (tinfo->num_levels == 1)
758                 return 0;
759
760         /* Handle chained entries. */
761         if (unlikely(tinfo->num_levels == TDB_MAX_LEVELS + 1)) {
762                 tlevel->hashtable = tdb_read_off(tdb, tlevel->hashtable
763                                                  + offsetof(struct tdb_chain,
764                                                             next));
765                 if (TDB_OFF_IS_ERR(tlevel->hashtable)) {
766                         tdb->ecode = tlevel->hashtable;
767                         return TDB_OFF_ERR;
768                 }
769                 if (tlevel->hashtable) {
770                         tlevel->hashtable += sizeof(struct tdb_used_record);
771                         tlevel->entry = 0;
772                         goto again;
773                 }
774         }
775
776         /* Go back up and keep searching. */
777         tinfo->num_levels--;
778         tlevel--;
779         goto again;
780 }
781
782 /* Return 1 if we find something, 0 if not, -1 on error. */
783 int next_in_hash(struct tdb_context *tdb,
784                  struct traverse_info *tinfo,
785                  TDB_DATA *kbuf, size_t *dlen)
786 {
787         const unsigned group_bits = TDB_TOPLEVEL_HASH_BITS-TDB_HASH_GROUP_BITS;
788         tdb_off_t hl_start, hl_range, off;
789         enum TDB_ERROR ecode;
790
791         while (tinfo->toplevel_group < (1 << group_bits)) {
792                 hl_start = (tdb_off_t)tinfo->toplevel_group
793                         << (64 - group_bits);
794                 hl_range = 1ULL << group_bits;
795                 ecode = tdb_lock_hashes(tdb, hl_start, hl_range, F_RDLCK,
796                                         TDB_LOCK_WAIT);
797                 if (ecode != TDB_SUCCESS) {
798                         tdb->ecode = ecode;
799                         return -1;
800                 }
801
802                 off = iterate_hash(tdb, tinfo);
803                 if (off) {
804                         struct tdb_used_record rec;
805
806                         ecode = tdb_read_convert(tdb, off, &rec, sizeof(rec));
807                         if (ecode != TDB_SUCCESS) {
808                                 tdb->ecode = ecode;
809                                 tdb_unlock_hashes(tdb,
810                                                   hl_start, hl_range, F_RDLCK);
811                                 return -1;
812                         }
813                         if (rec_magic(&rec) != TDB_USED_MAGIC) {
814                                 tdb_logerr(tdb, TDB_ERR_CORRUPT,
815                                            TDB_LOG_ERROR,
816                                            "next_in_hash:"
817                                            " corrupt record at %llu",
818                                            (long long)off);
819                                 return -1;
820                         }
821
822                         kbuf->dsize = rec_key_length(&rec);
823
824                         /* They want data as well? */
825                         if (dlen) {
826                                 *dlen = rec_data_length(&rec);
827                                 kbuf->dptr = tdb_alloc_read(tdb,
828                                                             off + sizeof(rec),
829                                                             kbuf->dsize
830                                                             + *dlen);
831                         } else {
832                                 kbuf->dptr = tdb_alloc_read(tdb,
833                                                             off + sizeof(rec),
834                                                             kbuf->dsize);
835                         }
836                         tdb_unlock_hashes(tdb, hl_start, hl_range, F_RDLCK);
837                         if (TDB_PTR_IS_ERR(kbuf->dptr)) {
838                                 tdb->ecode = TDB_PTR_ERR(kbuf->dptr);
839                                 return -1;
840                         }
841                         return 1;
842                 }
843
844                 tdb_unlock_hashes(tdb, hl_start, hl_range, F_RDLCK);
845
846                 tinfo->toplevel_group++;
847                 tinfo->levels[0].hashtable
848                         += (sizeof(tdb_off_t) << TDB_HASH_GROUP_BITS);
849                 tinfo->levels[0].entry = 0;
850         }
851         return 0;
852 }
853
854 /* Return 1 if we find something, 0 if not, -1 on error. */
855 int first_in_hash(struct tdb_context *tdb,
856                   struct traverse_info *tinfo,
857                   TDB_DATA *kbuf, size_t *dlen)
858 {
859         tinfo->prev = 0;
860         tinfo->toplevel_group = 0;
861         tinfo->num_levels = 1;
862         tinfo->levels[0].hashtable = offsetof(struct tdb_header, hashtable);
863         tinfo->levels[0].entry = 0;
864         tinfo->levels[0].total_buckets = (1 << TDB_HASH_GROUP_BITS);
865
866         return next_in_hash(tdb, tinfo, kbuf, dlen);
867 }
868
869 /* Even if the entry isn't in this hash bucket, you'd have to lock this
870  * bucket to find it. */
871 static int chainlock(struct tdb_context *tdb, const TDB_DATA *key,
872                      int ltype, enum tdb_lock_flags waitflag,
873                      const char *func)
874 {
875         enum TDB_ERROR ecode;
876         uint64_t h = tdb_hash(tdb, key->dptr, key->dsize);
877         tdb_off_t lockstart, locksize;
878         unsigned int group, gbits;
879
880         gbits = TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS;
881         group = bits_from(h, 64 - gbits, gbits);
882
883         lockstart = hlock_range(group, &locksize);
884
885         ecode = tdb_lock_hashes(tdb, lockstart, locksize, ltype, waitflag);
886         tdb_trace_1rec(tdb, func, *key);
887         if (ecode != TDB_SUCCESS) {
888                 tdb->ecode = ecode;
889                 return -1;
890         }
891         return 0;
892 }
893
894 /* lock/unlock one hash chain. This is meant to be used to reduce
895    contention - it cannot guarantee how many records will be locked */
896 int tdb_chainlock(struct tdb_context *tdb, TDB_DATA key)
897 {
898         return chainlock(tdb, &key, F_WRLCK, TDB_LOCK_WAIT, "tdb_chainlock");
899 }
900
901 int tdb_chainunlock(struct tdb_context *tdb, TDB_DATA key)
902 {
903         uint64_t h = tdb_hash(tdb, key.dptr, key.dsize);
904         tdb_off_t lockstart, locksize;
905         unsigned int group, gbits;
906         enum TDB_ERROR ecode;
907
908         gbits = TDB_TOPLEVEL_HASH_BITS - TDB_HASH_GROUP_BITS;
909         group = bits_from(h, 64 - gbits, gbits);
910
911         lockstart = hlock_range(group, &locksize);
912
913         tdb_trace_1rec(tdb, "tdb_chainunlock", key);
914         ecode = tdb_unlock_hashes(tdb, lockstart, locksize, F_WRLCK);
915         if (ecode != TDB_SUCCESS) {
916                 tdb->ecode = ecode;
917                 return -1;
918         }
919         return 0;
920 }