]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/free.c
c78d138943b108550dbf886f4aa599e5310a1e7c
[ccan] / ccan / tdb2 / free.c
1  /*
2    Trivial Database 2: free list/block 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 <ccan/likely/likely.h>
20 #include <ccan/ilog/ilog.h>
21 #include <time.h>
22 #include <assert.h>
23 #include <limits.h>
24
25 static unsigned fls64(uint64_t val)
26 {
27         return ilog64(val);
28 }
29
30 /* In which bucket would we find a particular record size? (ignoring header) */
31 unsigned int size_to_bucket(tdb_len_t data_len)
32 {
33         unsigned int bucket;
34
35         /* We can't have records smaller than this. */
36         assert(data_len >= TDB_MIN_DATA_LEN);
37
38         /* Ignoring the header... */
39         if (data_len - TDB_MIN_DATA_LEN <= 64) {
40                 /* 0 in bucket 0, 8 in bucket 1... 64 in bucket 8. */
41                 bucket = (data_len - TDB_MIN_DATA_LEN) / 8;
42         } else {
43                 /* After that we go power of 2. */
44                 bucket = fls64(data_len - TDB_MIN_DATA_LEN) + 2;
45         }
46
47         if (unlikely(bucket >= TDB_FREE_BUCKETS))
48                 bucket = TDB_FREE_BUCKETS - 1;
49         return bucket;
50 }
51
52 tdb_off_t first_ftable(struct tdb_context *tdb)
53 {
54         return tdb_read_off(tdb, offsetof(struct tdb_header, free_table));
55 }
56
57 tdb_off_t next_ftable(struct tdb_context *tdb, tdb_off_t ftable)
58 {
59         return tdb_read_off(tdb, ftable + offsetof(struct tdb_freetable,next));
60 }
61
62 enum TDB_ERROR tdb_ftable_init(struct tdb_context *tdb)
63 {
64         /* Use reservoir sampling algorithm to select a free list at random. */
65         unsigned int rnd, max = 0, count = 0;
66         tdb_off_t off;
67
68         tdb->ftable_off = off = first_ftable(tdb);
69         tdb->ftable = 0;
70
71         while (off) {
72                 if (TDB_OFF_IS_ERR(off)) {
73                         return off;
74                 }
75
76                 rnd = random();
77                 if (rnd >= max) {
78                         tdb->ftable_off = off;
79                         tdb->ftable = count;
80                         max = rnd;
81                 }
82
83                 off = next_ftable(tdb, off);
84                 count++;
85         }
86         return TDB_SUCCESS;
87 }
88
89 /* Offset of a given bucket. */
90 tdb_off_t bucket_off(tdb_off_t ftable_off, unsigned bucket)
91 {
92         return ftable_off + offsetof(struct tdb_freetable, buckets)
93                 + bucket * sizeof(tdb_off_t);
94 }
95
96 /* Returns free_buckets + 1, or list number to search, or -ve error. */
97 static tdb_off_t find_free_head(struct tdb_context *tdb,
98                                 tdb_off_t ftable_off,
99                                 tdb_off_t bucket)
100 {
101         /* Speculatively search for a non-zero bucket. */
102         return tdb_find_nonzero_off(tdb, bucket_off(ftable_off, 0),
103                                     bucket, TDB_FREE_BUCKETS);
104 }
105
106 static void check_list(struct tdb_context *tdb, tdb_off_t b_off)
107 {
108 #ifdef CCAN_TDB2_DEBUG
109         tdb_off_t off, prev = 0, first;
110         struct tdb_free_record r;
111
112         first = off = tdb_read_off(tdb, b_off);
113         while (off != 0) {
114                 tdb_read_convert(tdb, off, &r, sizeof(r));
115                 if (frec_magic(&r) != TDB_FREE_MAGIC)
116                         abort();
117                 if (prev && frec_prev(&r) != prev)
118                         abort();
119                 prev = off;
120                 off = r.next;
121         }
122
123         if (first) {
124                 tdb_read_convert(tdb, first, &r, sizeof(r));
125                 if (frec_prev(&r) != prev)
126                         abort();
127         }
128 #endif
129 }
130
131 /* Remove from free bucket. */
132 static enum TDB_ERROR remove_from_list(struct tdb_context *tdb,
133                                        tdb_off_t b_off, tdb_off_t r_off,
134                                        const struct tdb_free_record *r)
135 {
136         tdb_off_t off, prev_next, head;
137         enum TDB_ERROR ecode;
138
139         /* Is this only element in list?  Zero out bucket, and we're done. */
140         if (frec_prev(r) == r_off)
141                 return tdb_write_off(tdb, b_off, 0);
142
143         /* off = &r->prev->next */
144         off = frec_prev(r) + offsetof(struct tdb_free_record, next);
145
146         /* Get prev->next */
147         prev_next = tdb_read_off(tdb, off);
148         if (TDB_OFF_IS_ERR(prev_next))
149                 return prev_next;
150
151         /* If prev->next == 0, we were head: update bucket to point to next. */
152         if (prev_next == 0) {
153 #ifdef CCAN_TDB2_DEBUG
154                 if (tdb_read_off(tdb, b_off) != r_off) {
155                         return tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
156                                           "remove_from_list:"
157                                           " %llu head %llu on list %llu",
158                                           (long long)r_off,
159                                           (long long)tdb_read_off(tdb, b_off),
160                                           (long long)b_off);
161                 }
162 #endif
163                 ecode = tdb_write_off(tdb, b_off, r->next);
164                 if (ecode != TDB_SUCCESS)
165                         return ecode;
166         } else {
167                 /* r->prev->next = r->next */
168                 ecode = tdb_write_off(tdb, off, r->next);
169                 if (ecode != TDB_SUCCESS)
170                         return ecode;
171         }
172
173         /* If we were the tail, off = &head->prev. */
174         if (r->next == 0) {
175                 head = tdb_read_off(tdb, b_off);
176                 if (TDB_OFF_IS_ERR(head))
177                         return head;
178                 off = head + offsetof(struct tdb_free_record, magic_and_prev);
179         } else {
180                 /* off = &r->next->prev */
181                 off = r->next + offsetof(struct tdb_free_record,
182                                          magic_and_prev);
183         }
184
185 #ifdef CCAN_TDB2_DEBUG
186         /* *off == r */
187         if ((tdb_read_off(tdb, off) & TDB_OFF_MASK) != r_off) {
188                 return tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
189                                   "remove_from_list:"
190                                   " %llu bad prev in list %llu",
191                                   (long long)r_off, (long long)b_off);
192         }
193 #endif
194         /* r->next->prev = r->prev */
195         return tdb_write_off(tdb, off, r->magic_and_prev);
196 }
197
198 /* Enqueue in this free bucket. */
199 static enum TDB_ERROR enqueue_in_free(struct tdb_context *tdb,
200                                       tdb_off_t b_off,
201                                       tdb_off_t off,
202                                       tdb_len_t len)
203 {
204         struct tdb_free_record new;
205         enum TDB_ERROR ecode;
206         tdb_off_t prev;
207         uint64_t magic = (TDB_FREE_MAGIC << (64 - TDB_OFF_UPPER_STEAL));
208
209         /* We only need to set ftable_and_len; rest is set in enqueue_in_free */
210         new.ftable_and_len = ((uint64_t)tdb->ftable << (64 - TDB_OFF_UPPER_STEAL))
211                 | len;
212
213         /* new->next = head. */
214         new.next = tdb_read_off(tdb, b_off);
215         if (TDB_OFF_IS_ERR(new.next)) {
216                 return new.next;
217         }
218
219         /* First element?  Prev points to ourselves. */
220         if (!new.next) {
221                 new.magic_and_prev = (magic | off);
222         } else {
223                 /* new->prev = next->prev */
224                 prev = tdb_read_off(tdb,
225                                     new.next + offsetof(struct tdb_free_record,
226                                                         magic_and_prev));
227                 new.magic_and_prev = prev;
228                 if (frec_magic(&new) != TDB_FREE_MAGIC) {
229                         return tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
230                                           "enqueue_in_free: %llu bad head"
231                                           " prev %llu",
232                                           (long long)new.next,
233                                           (long long)prev);
234                 }
235                 /* next->prev = new. */
236                 ecode = tdb_write_off(tdb, new.next
237                                       + offsetof(struct tdb_free_record,
238                                                  magic_and_prev),
239                                       off | magic);
240                 if (ecode != TDB_SUCCESS) {
241                         return ecode;
242                 }
243
244 #ifdef CCAN_TDB2_DEBUG
245                 prev = tdb_read_off(tdb, frec_prev(&new)
246                                     + offsetof(struct tdb_free_record, next));
247                 if (prev != 0) {
248                         return tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
249                                           "enqueue_in_free:"
250                                           " %llu bad tail next ptr %llu",
251                                           (long long)frec_prev(&new)
252                                           + offsetof(struct tdb_free_record,
253                                                      next),
254                                           (long long)prev);
255                 }
256 #endif
257         }
258         /* head = new */
259         ecode = tdb_write_off(tdb, b_off, off);
260         if (ecode != TDB_SUCCESS) {
261                 return ecode;
262         }
263
264         return tdb_write_convert(tdb, off, &new, sizeof(new));
265 }
266
267 /* List need not be locked. */
268 enum TDB_ERROR add_free_record(struct tdb_context *tdb,
269                                tdb_off_t off, tdb_len_t len_with_header)
270 {
271         tdb_off_t b_off;
272         tdb_len_t len;
273         enum TDB_ERROR ecode;
274
275         assert(len_with_header >= sizeof(struct tdb_free_record));
276
277         len = len_with_header - sizeof(struct tdb_used_record);
278
279         b_off = bucket_off(tdb->ftable_off, size_to_bucket(len));
280         ecode = tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT);
281         if (ecode != TDB_SUCCESS) {
282                 return ecode;
283         }
284
285         ecode = enqueue_in_free(tdb, b_off, off, len);
286         check_list(tdb, b_off);
287         tdb_unlock_free_bucket(tdb, b_off);
288         return ecode;
289 }
290
291 static size_t adjust_size(size_t keylen, size_t datalen)
292 {
293         size_t size = keylen + datalen;
294
295         if (size < TDB_MIN_DATA_LEN)
296                 size = TDB_MIN_DATA_LEN;
297
298         /* Round to next uint64_t boundary. */
299         return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
300 }
301
302 /* If we have enough left over to be useful, split that off. */
303 static size_t record_leftover(size_t keylen, size_t datalen,
304                               bool want_extra, size_t total_len)
305 {
306         ssize_t leftover;
307
308         if (want_extra)
309                 datalen += datalen / 2;
310         leftover = total_len - adjust_size(keylen, datalen);
311
312         if (leftover < (ssize_t)sizeof(struct tdb_free_record))
313                 return 0;
314
315         return leftover;
316 }
317
318 static tdb_off_t ftable_offset(struct tdb_context *tdb, unsigned int ftable)
319 {
320         tdb_off_t off;
321         unsigned int i;
322
323         if (likely(tdb->ftable == ftable))
324                 return tdb->ftable_off;
325
326         off = first_ftable(tdb);
327         for (i = 0; i < ftable; i++) {
328                 if (TDB_OFF_IS_ERR(off)) {
329                         break;
330                 }
331                 off = next_ftable(tdb, off);
332         }
333         return off;
334 }
335
336 /* Note: we unlock the current bucket if we coalesce or fail. */
337 static tdb_bool_err coalesce(struct tdb_context *tdb,
338                              tdb_off_t off, tdb_off_t b_off,
339                              tdb_len_t data_len)
340 {
341         tdb_off_t end;
342         struct tdb_free_record rec;
343         enum TDB_ERROR ecode;
344
345         add_stat(tdb, alloc_coalesce_tried, 1);
346         end = off + sizeof(struct tdb_used_record) + data_len;
347
348         while (end < tdb->file->map_size) {
349                 const struct tdb_free_record *r;
350                 tdb_off_t nb_off;
351                 unsigned ftable, bucket;
352
353                 r = tdb_access_read(tdb, end, sizeof(*r), true);
354                 if (TDB_PTR_IS_ERR(r)) {
355                         ecode = TDB_PTR_ERR(r);
356                         goto err;
357                 }
358
359                 if (frec_magic(r) != TDB_FREE_MAGIC
360                     || frec_ftable(r) == TDB_FTABLE_NONE) {
361                         tdb_access_release(tdb, r);
362                         break;
363                 }
364
365                 ftable = frec_ftable(r);
366                 bucket = size_to_bucket(frec_len(r));
367                 nb_off = ftable_offset(tdb, ftable);
368                 if (TDB_OFF_IS_ERR(nb_off)) {
369                         tdb_access_release(tdb, r);
370                         ecode = nb_off;
371                         goto err;
372                 }
373                 nb_off = bucket_off(nb_off, bucket);
374                 tdb_access_release(tdb, r);
375
376                 /* We may be violating lock order here, so best effort. */
377                 if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT)
378                     != TDB_SUCCESS) {
379                         add_stat(tdb, alloc_coalesce_lockfail, 1);
380                         break;
381                 }
382
383                 /* Now we have lock, re-check. */
384                 ecode = tdb_read_convert(tdb, end, &rec, sizeof(rec));
385                 if (ecode != TDB_SUCCESS) {
386                         tdb_unlock_free_bucket(tdb, nb_off);
387                         goto err;
388                 }
389
390                 if (unlikely(frec_magic(&rec) != TDB_FREE_MAGIC)) {
391                         add_stat(tdb, alloc_coalesce_race, 1);
392                         tdb_unlock_free_bucket(tdb, nb_off);
393                         break;
394                 }
395
396                 if (unlikely(frec_ftable(&rec) != ftable)
397                     || unlikely(size_to_bucket(frec_len(&rec)) != bucket)) {
398                         add_stat(tdb, alloc_coalesce_race, 1);
399                         tdb_unlock_free_bucket(tdb, nb_off);
400                         break;
401                 }
402
403                 ecode = remove_from_list(tdb, nb_off, end, &rec);
404                 check_list(tdb, nb_off);
405                 if (ecode != TDB_SUCCESS) {
406                         tdb_unlock_free_bucket(tdb, nb_off);
407                         goto err;
408                 }
409
410                 end += sizeof(struct tdb_used_record) + frec_len(&rec);
411                 tdb_unlock_free_bucket(tdb, nb_off);
412                 add_stat(tdb, alloc_coalesce_num_merged, 1);
413         }
414
415         /* Didn't find any adjacent free? */
416         if (end == off + sizeof(struct tdb_used_record) + data_len)
417                 return false;
418
419         /* OK, expand initial record */
420         ecode = tdb_read_convert(tdb, off, &rec, sizeof(rec));
421         if (ecode != TDB_SUCCESS) {
422                 goto err;
423         }
424
425         if (frec_len(&rec) != data_len) {
426                 ecode = tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
427                                    "coalesce: expected data len %zu not %zu",
428                                    (size_t)data_len, (size_t)frec_len(&rec));
429                 goto err;
430         }
431
432         ecode = remove_from_list(tdb, b_off, off, &rec);
433         check_list(tdb, b_off);
434         if (ecode != TDB_SUCCESS) {
435                 goto err;
436         }
437
438         /* We have to drop this to avoid deadlocks, so make sure record
439          * doesn't get coalesced by someone else! */
440         rec.ftable_and_len = (TDB_FTABLE_NONE << (64 - TDB_OFF_UPPER_STEAL))
441                 | (end - off - sizeof(struct tdb_used_record));
442         ecode = tdb_write_off(tdb, off + offsetof(struct tdb_free_record,
443                                                   ftable_and_len),
444                               rec.ftable_and_len);
445         if (ecode != TDB_SUCCESS) {
446                 goto err;
447         }
448
449         add_stat(tdb, alloc_coalesce_succeeded, 1);
450         tdb_unlock_free_bucket(tdb, b_off);
451
452         ecode = add_free_record(tdb, off, end - off);
453         if (ecode != TDB_SUCCESS) {
454                 return ecode;
455         }
456         return true;
457
458 err:
459         /* To unify error paths, we *always* unlock bucket on error. */
460         tdb_unlock_free_bucket(tdb, b_off);
461         return ecode;
462 }
463
464 /* We need size bytes to put our key and data in. */
465 static tdb_off_t lock_and_alloc(struct tdb_context *tdb,
466                                 tdb_off_t ftable_off,
467                                 tdb_off_t bucket,
468                                 size_t keylen, size_t datalen,
469                                 bool want_extra,
470                                 unsigned magic,
471                                 unsigned hashlow)
472 {
473         tdb_off_t off, b_off,best_off;
474         struct tdb_free_record best = { 0 };
475         double multiplier;
476         size_t size = adjust_size(keylen, datalen);
477         enum TDB_ERROR ecode;
478
479         add_stat(tdb, allocs, 1);
480 again:
481         b_off = bucket_off(ftable_off, bucket);
482
483         /* FIXME: Try non-blocking wait first, to measure contention. */
484         /* Lock this bucket. */
485         ecode = tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT);
486         if (ecode != TDB_SUCCESS) {
487                 return ecode;
488         }
489
490         best.ftable_and_len = -1ULL;
491         best_off = 0;
492
493         /* Get slack if we're after extra. */
494         if (want_extra)
495                 multiplier = 1.5;
496         else
497                 multiplier = 1.0;
498
499         /* Walk the list to see if any are large enough, getting less fussy
500          * as we go. */
501         off = tdb_read_off(tdb, b_off);
502         if (TDB_OFF_IS_ERR(off)) {
503                 ecode = off;
504                 goto unlock_err;
505         }
506
507         while (off) {
508                 const struct tdb_free_record *r;
509                 tdb_len_t len;
510                 tdb_off_t next;
511                 int coal;
512
513                 r = tdb_access_read(tdb, off, sizeof(*r), true);
514                 if (TDB_PTR_IS_ERR(r)) {
515                         ecode = TDB_PTR_ERR(r);
516                         goto unlock_err;
517                 }
518
519                 if (frec_magic(r) != TDB_FREE_MAGIC) {
520                         ecode = tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
521                                            "lock_and_alloc:"
522                                            " %llu non-free 0x%llx",
523                                            (long long)off,
524                                            (long long)r->magic_and_prev);
525                         tdb_access_release(tdb, r);
526                         goto unlock_err;
527                 }
528
529                 if (frec_len(r) >= size && frec_len(r) < frec_len(&best)) {
530                         best_off = off;
531                         best = *r;
532                 }
533
534                 if (frec_len(&best) <= size * multiplier && best_off) {
535                         tdb_access_release(tdb, r);
536                         break;
537                 }
538
539                 multiplier *= 1.01;
540
541                 next = r->next;
542                 len = frec_len(r);
543                 tdb_access_release(tdb, r);
544
545                 /* Since we're going slow anyway, try coalescing here. */
546                 coal = coalesce(tdb, off, b_off, len);
547                 if (coal == 1) {
548                         /* This has unlocked list, restart. */
549                         goto again;
550                 }
551                 if (coal < 0) {
552                         /* This has already unlocked on error. */
553                         return coal;
554                 }
555                 off = next;
556         }
557
558         /* If we found anything at all, use it. */
559         if (best_off) {
560                 struct tdb_used_record rec;
561                 size_t leftover;
562
563                 /* We're happy with this size: take it. */
564                 ecode = remove_from_list(tdb, b_off, best_off, &best);
565                 check_list(tdb, b_off);
566                 if (ecode != TDB_SUCCESS) {
567                         goto unlock_err;
568                 }
569
570                 leftover = record_leftover(keylen, datalen, want_extra,
571                                            frec_len(&best));
572
573                 assert(keylen + datalen + leftover <= frec_len(&best));
574                 /* We need to mark non-free before we drop lock, otherwise
575                  * coalesce() could try to merge it! */
576                 ecode = set_header(tdb, &rec, magic, keylen, datalen,
577                                    frec_len(&best) - leftover, hashlow);
578                 if (ecode != TDB_SUCCESS) {
579                         goto unlock_err;
580                 }
581
582                 ecode = tdb_write_convert(tdb, best_off, &rec, sizeof(rec));
583                 if (ecode != TDB_SUCCESS) {
584                         goto unlock_err;
585                 }
586
587                 /* For futureproofing, we put a 0 in any unused space. */
588                 if (rec_extra_padding(&rec)) {
589                         ecode = tdb->methods->twrite(tdb, best_off + sizeof(rec)
590                                                      + keylen + datalen, "", 1);
591                         if (ecode != TDB_SUCCESS) {
592                                 goto unlock_err;
593                         }
594                 }
595
596                 /* Bucket of leftover will be <= current bucket, so nested
597                  * locking is allowed. */
598                 if (leftover) {
599                         add_stat(tdb, alloc_leftover, 1);
600                         ecode = add_free_record(tdb,
601                                                 best_off + sizeof(rec)
602                                                 + frec_len(&best) - leftover,
603                                                 leftover);
604                         if (ecode != TDB_SUCCESS) {
605                                 best_off = ecode;
606                         }
607                 }
608                 tdb_unlock_free_bucket(tdb, b_off);
609
610                 return best_off;
611         }
612
613         tdb_unlock_free_bucket(tdb, b_off);
614         return 0;
615
616 unlock_err:
617         tdb_unlock_free_bucket(tdb, b_off);
618         return ecode;
619 }
620
621 /* Get a free block from current free list, or 0 if none, -ve on error. */
622 static tdb_off_t get_free(struct tdb_context *tdb,
623                           size_t keylen, size_t datalen, bool want_extra,
624                           unsigned magic, unsigned hashlow)
625 {
626         tdb_off_t off, ftable_off;
627         tdb_off_t start_b, b, ftable;
628         bool wrapped = false;
629
630         /* If they are growing, add 50% to get to higher bucket. */
631         if (want_extra)
632                 start_b = size_to_bucket(adjust_size(keylen,
633                                                      datalen + datalen / 2));
634         else
635                 start_b = size_to_bucket(adjust_size(keylen, datalen));
636
637         ftable_off = tdb->ftable_off;
638         ftable = tdb->ftable;
639         while (!wrapped || ftable_off != tdb->ftable_off) {
640                 /* Start at exact size bucket, and search up... */
641                 for (b = find_free_head(tdb, ftable_off, start_b);
642                      b < TDB_FREE_BUCKETS;
643                      b = find_free_head(tdb, ftable_off, b + 1)) {
644                         /* Try getting one from list. */
645                         off = lock_and_alloc(tdb, ftable_off,
646                                              b, keylen, datalen, want_extra,
647                                              magic, hashlow);
648                         if (TDB_OFF_IS_ERR(off))
649                                 return off;
650                         if (off != 0) {
651                                 if (b == start_b)
652                                         add_stat(tdb, alloc_bucket_exact, 1);
653                                 if (b == TDB_FREE_BUCKETS - 1)
654                                         add_stat(tdb, alloc_bucket_max, 1);
655                                 /* Worked?  Stay using this list. */
656                                 tdb->ftable_off = ftable_off;
657                                 tdb->ftable = ftable;
658                                 return off;
659                         }
660                         /* Didn't work.  Try next bucket. */
661                 }
662
663                 if (TDB_OFF_IS_ERR(b)) {
664                         return b;
665                 }
666
667                 /* Hmm, try next table. */
668                 ftable_off = next_ftable(tdb, ftable_off);
669                 if (TDB_OFF_IS_ERR(ftable_off)) {
670                         return ftable_off;
671                 }
672                 ftable++;
673
674                 if (ftable_off == 0) {
675                         wrapped = true;
676                         ftable_off = first_ftable(tdb);
677                         if (TDB_OFF_IS_ERR(ftable_off)) {
678                                 return ftable_off;
679                         }
680                         ftable = 0;
681                 }
682         }
683
684         return 0;
685 }
686
687 enum TDB_ERROR set_header(struct tdb_context *tdb,
688                           struct tdb_used_record *rec,
689                           unsigned magic, uint64_t keylen, uint64_t datalen,
690                           uint64_t actuallen, unsigned hashlow)
691 {
692         uint64_t keybits = (fls64(keylen) + 1) / 2;
693
694         /* Use bottom bits of hash, so it's independent of hash table size. */
695         rec->magic_and_meta = (hashlow & ((1 << 11)-1))
696                 | ((actuallen - (keylen + datalen)) << 11)
697                 | (keybits << 43)
698                 | ((uint64_t)magic << 48);
699         rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
700
701         /* Encoding can fail on big values. */
702         if (rec_key_length(rec) != keylen
703             || rec_data_length(rec) != datalen
704             || rec_extra_padding(rec) != actuallen - (keylen + datalen)) {
705                 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
706                                   "Could not encode k=%llu,d=%llu,a=%llu",
707                                   (long long)keylen, (long long)datalen,
708                                   (long long)actuallen);
709         }
710         return TDB_SUCCESS;
711 }
712
713 /* Expand the database. */
714 static enum TDB_ERROR tdb_expand(struct tdb_context *tdb, tdb_len_t size)
715 {
716         uint64_t old_size;
717         tdb_len_t wanted;
718         enum TDB_ERROR ecode;
719
720         /* We need room for the record header too. */
721         wanted = sizeof(struct tdb_used_record) + size;
722
723         /* Need to hold a hash lock to expand DB: transactions rely on it. */
724         if (!(tdb->flags & TDB_NOLOCK)
725             && !tdb->file->allrecord_lock.count && !tdb_has_hash_locks(tdb)) {
726                 return tdb_logerr(tdb, TDB_ERR_LOCK, TDB_LOG_ERROR,
727                                   "tdb_expand: must hold lock during expand");
728         }
729
730         /* always make room for at least 100 more records, and at
731            least 25% more space. */
732         if (size * TDB_EXTENSION_FACTOR > tdb->file->map_size / 4)
733                 wanted = size * TDB_EXTENSION_FACTOR;
734         else
735                 wanted = tdb->file->map_size / 4;
736         wanted = adjust_size(0, wanted);
737
738         /* Only one person can expand file at a time. */
739         ecode = tdb_lock_expand(tdb, F_WRLCK);
740         if (ecode != TDB_SUCCESS) {
741                 return ecode;
742         }
743
744         /* Someone else may have expanded the file, so retry. */
745         old_size = tdb->file->map_size;
746         tdb->methods->oob(tdb, tdb->file->map_size + 1, true);
747         if (tdb->file->map_size != old_size) {
748                 tdb_unlock_expand(tdb, F_WRLCK);
749                 return TDB_SUCCESS;
750         }
751
752         ecode = tdb->methods->expand_file(tdb, wanted);
753         if (ecode != TDB_SUCCESS) {
754                 tdb_unlock_expand(tdb, F_WRLCK);
755                 return ecode;
756         }
757
758         /* We need to drop this lock before adding free record. */
759         tdb_unlock_expand(tdb, F_WRLCK);
760
761         add_stat(tdb, expands, 1);
762         return add_free_record(tdb, old_size, wanted);
763 }
764
765 /* This won't fail: it will expand the database if it has to. */
766 tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
767                 uint64_t hash, unsigned magic, bool growing)
768 {
769         tdb_off_t off;
770
771         /* We can't hold pointers during this: we could unmap! */
772         assert(!tdb->direct_access);
773
774         for (;;) {
775                 enum TDB_ERROR ecode;
776                 off = get_free(tdb, keylen, datalen, growing, magic, hash);
777                 if (likely(off != 0))
778                         break;
779
780                 ecode = tdb_expand(tdb, adjust_size(keylen, datalen));
781                 if (ecode != TDB_SUCCESS) {
782                         return ecode;
783                 }
784         }
785
786         return off;
787 }