2 Trivial Database 2: free list/block handling
3 Copyright (C) Rusty Russell 2010
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 3 of the License, or (at your option) any later version.
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 #include <ccan/likely/likely.h>
20 #include <ccan/ilog/ilog.h>
25 static unsigned fls64(uint64_t val)
30 /* In which bucket would we find a particular record size? (ignoring header) */
31 unsigned int size_to_bucket(tdb_len_t data_len)
35 /* We can't have records smaller than this. */
36 assert(data_len >= TDB_MIN_DATA_LEN);
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;
43 /* After that we go power of 2. */
44 bucket = fls64(data_len - TDB_MIN_DATA_LEN) + 2;
47 if (unlikely(bucket >= TDB_FREE_BUCKETS))
48 bucket = TDB_FREE_BUCKETS - 1;
52 tdb_off_t first_ftable(struct tdb_context *tdb)
54 return tdb_read_off(tdb, offsetof(struct tdb_header, free_table));
57 tdb_off_t next_ftable(struct tdb_context *tdb, tdb_off_t ftable)
59 return tdb_read_off(tdb, ftable + offsetof(struct tdb_freetable,next));
62 int tdb_ftable_init(struct tdb_context *tdb)
64 /* Use reservoir sampling algorithm to select a free list at random. */
65 unsigned int rnd, max = 0, count = 0;
68 tdb->ftable_off = off = first_ftable(tdb);
72 if (off == TDB_OFF_ERR)
77 tdb->ftable_off = off;
82 off = next_ftable(tdb, off);
88 /* Offset of a given bucket. */
89 tdb_off_t bucket_off(tdb_off_t ftable_off, unsigned bucket)
91 return ftable_off + offsetof(struct tdb_freetable, buckets)
92 + bucket * sizeof(tdb_off_t);
95 /* Returns free_buckets + 1, or list number to search. */
96 static tdb_off_t find_free_head(struct tdb_context *tdb,
100 /* Speculatively search for a non-zero bucket. */
101 return tdb_find_nonzero_off(tdb, bucket_off(ftable_off, 0),
102 bucket, TDB_FREE_BUCKETS);
105 /* Remove from free bucket. */
106 static int remove_from_list(struct tdb_context *tdb,
107 tdb_off_t b_off, tdb_off_t r_off,
108 const struct tdb_free_record *r)
111 enum TDB_ERROR ecode;
114 if (frec_prev(r) == 0) {
117 off = frec_prev(r) + offsetof(struct tdb_free_record, next);
120 #ifdef CCAN_TDB2_DEBUG
121 if (tdb_read_off(tdb, off) != r_off) {
122 tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
123 "remove_from_list: %llu bad prev in list %llu",
124 (long long)r_off, (long long)b_off);
129 /* r->prev->next = r->next */
130 ecode = tdb_write_off(tdb, off, r->next);
131 if (ecode != TDB_SUCCESS) {
137 off = r->next + offsetof(struct tdb_free_record,magic_and_prev);
138 /* r->next->prev = r->prev */
140 #ifdef CCAN_TDB2_DEBUG
141 if (tdb_read_off(tdb, off) & TDB_OFF_MASK != r_off) {
142 tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
143 "remove_from_list: %llu bad list %llu",
144 (long long)r_off, (long long)b_off);
149 ecode = tdb_write_off(tdb, off, r->magic_and_prev);
150 if (ecode != TDB_SUCCESS) {
158 /* Enqueue in this free bucket. */
159 static int enqueue_in_free(struct tdb_context *tdb,
164 struct tdb_free_record new;
165 enum TDB_ERROR ecode;
166 uint64_t magic = (TDB_FREE_MAGIC << (64 - TDB_OFF_UPPER_STEAL));
168 /* We only need to set ftable_and_len; rest is set in enqueue_in_free */
169 new.ftable_and_len = ((uint64_t)tdb->ftable << (64 - TDB_OFF_UPPER_STEAL))
172 new.magic_and_prev = magic;
174 /* new->next = head. */
175 new.next = tdb_read_off(tdb, b_off);
176 if (new.next == TDB_OFF_ERR)
180 #ifdef CCAN_TDB2_DEBUG
181 if (tdb_read_off(tdb,
182 new.next + offsetof(struct tdb_free_record,
185 tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
186 "enqueue_in_free: %llu bad head"
188 (long long)new.next, (long long)b_off);
192 /* next->prev = new. */
193 ecode = tdb_write_off(tdb, new.next
194 + offsetof(struct tdb_free_record,
197 if (ecode != TDB_SUCCESS) {
203 ecode = tdb_write_off(tdb, b_off, off);
204 if (ecode != TDB_SUCCESS) {
209 ecode = tdb_write_convert(tdb, off, &new, sizeof(new));
210 if (ecode != TDB_SUCCESS) {
217 /* List need not be locked. */
218 int add_free_record(struct tdb_context *tdb,
219 tdb_off_t off, tdb_len_t len_with_header)
224 enum TDB_ERROR ecode;
226 assert(len_with_header >= sizeof(struct tdb_free_record));
228 len = len_with_header - sizeof(struct tdb_used_record);
230 b_off = bucket_off(tdb->ftable_off, size_to_bucket(len));
231 ecode = tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT);
232 if (ecode != TDB_SUCCESS) {
237 ret = enqueue_in_free(tdb, b_off, off, len);
238 tdb_unlock_free_bucket(tdb, b_off);
242 static size_t adjust_size(size_t keylen, size_t datalen)
244 size_t size = keylen + datalen;
246 if (size < TDB_MIN_DATA_LEN)
247 size = TDB_MIN_DATA_LEN;
249 /* Round to next uint64_t boundary. */
250 return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
253 /* If we have enough left over to be useful, split that off. */
254 static size_t record_leftover(size_t keylen, size_t datalen,
255 bool want_extra, size_t total_len)
260 datalen += datalen / 2;
261 leftover = total_len - adjust_size(keylen, datalen);
263 if (leftover < (ssize_t)sizeof(struct tdb_free_record))
269 static tdb_off_t ftable_offset(struct tdb_context *tdb, unsigned int ftable)
274 if (likely(tdb->ftable == ftable))
275 return tdb->ftable_off;
277 off = first_ftable(tdb);
278 for (i = 0; i < ftable; i++)
279 off = next_ftable(tdb, off);
283 /* Note: we unlock the current bucket if we coalesce or fail. */
284 static int coalesce(struct tdb_context *tdb,
285 tdb_off_t off, tdb_off_t b_off, tdb_len_t data_len)
288 struct tdb_free_record rec;
289 enum TDB_ERROR ecode;
291 add_stat(tdb, alloc_coalesce_tried, 1);
292 end = off + sizeof(struct tdb_used_record) + data_len;
294 while (end < tdb->map_size) {
295 const struct tdb_free_record *r;
297 unsigned ftable, bucket;
299 r = tdb_access_read(tdb, end, sizeof(*r), true);
303 if (frec_magic(r) != TDB_FREE_MAGIC
304 || frec_ftable(r) == TDB_FTABLE_NONE) {
305 tdb_access_release(tdb, r);
309 ftable = frec_ftable(r);
310 bucket = size_to_bucket(frec_len(r));
311 nb_off = bucket_off(ftable_offset(tdb, ftable), bucket);
312 tdb_access_release(tdb, r);
314 /* We may be violating lock order here, so best effort. */
315 if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT)
317 add_stat(tdb, alloc_coalesce_lockfail, 1);
321 /* Now we have lock, re-check. */
322 ecode = tdb_read_convert(tdb, end, &rec, sizeof(rec));
323 if (ecode != TDB_SUCCESS) {
325 tdb_unlock_free_bucket(tdb, nb_off);
329 if (unlikely(frec_magic(&rec) != TDB_FREE_MAGIC)) {
330 add_stat(tdb, alloc_coalesce_race, 1);
331 tdb_unlock_free_bucket(tdb, nb_off);
335 if (unlikely(frec_ftable(&rec) != ftable)
336 || unlikely(size_to_bucket(frec_len(&rec)) != bucket)) {
337 add_stat(tdb, alloc_coalesce_race, 1);
338 tdb_unlock_free_bucket(tdb, nb_off);
342 if (remove_from_list(tdb, nb_off, end, &rec) == -1) {
343 tdb_unlock_free_bucket(tdb, nb_off);
347 end += sizeof(struct tdb_used_record) + frec_len(&rec);
348 tdb_unlock_free_bucket(tdb, nb_off);
349 add_stat(tdb, alloc_coalesce_num_merged, 1);
352 /* Didn't find any adjacent free? */
353 if (end == off + sizeof(struct tdb_used_record) + data_len)
356 /* OK, expand initial record */
357 ecode = tdb_read_convert(tdb, off, &rec, sizeof(rec));
358 if (ecode != TDB_SUCCESS) {
363 if (frec_len(&rec) != data_len) {
364 tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
365 "coalesce: expected data len %zu not %zu",
366 (size_t)data_len, (size_t)frec_len(&rec));
370 if (remove_from_list(tdb, b_off, off, &rec) == -1)
373 /* We have to drop this to avoid deadlocks, so make sure record
374 * doesn't get coalesced by someone else! */
375 rec.ftable_and_len = (TDB_FTABLE_NONE << (64 - TDB_OFF_UPPER_STEAL))
376 | (end - off - sizeof(struct tdb_used_record));
377 ecode = tdb_write_off(tdb, off + offsetof(struct tdb_free_record,
380 if (ecode != TDB_SUCCESS) {
385 add_stat(tdb, alloc_coalesce_succeeded, 1);
386 tdb_unlock_free_bucket(tdb, b_off);
388 if (add_free_record(tdb, off, end - off) == -1)
393 /* To unify error paths, we *always* unlock bucket on error. */
394 tdb_unlock_free_bucket(tdb, b_off);
398 /* We need size bytes to put our key and data in. */
399 static tdb_off_t lock_and_alloc(struct tdb_context *tdb,
400 tdb_off_t ftable_off,
402 size_t keylen, size_t datalen,
407 tdb_off_t off, b_off,best_off;
408 struct tdb_free_record best = { 0 };
410 size_t size = adjust_size(keylen, datalen);
411 enum TDB_ERROR ecode;
413 add_stat(tdb, allocs, 1);
415 b_off = bucket_off(ftable_off, bucket);
417 /* FIXME: Try non-blocking wait first, to measure contention. */
418 /* Lock this bucket. */
419 ecode = tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT);
420 if (ecode != TDB_SUCCESS) {
425 best.ftable_and_len = -1ULL;
428 /* Get slack if we're after extra. */
434 /* Walk the list to see if any are large enough, getting less fussy
436 off = tdb_read_off(tdb, b_off);
437 if (unlikely(off == TDB_OFF_ERR))
441 const struct tdb_free_record *r;
445 r = tdb_access_read(tdb, off, sizeof(*r), true);
449 if (frec_magic(r) != TDB_FREE_MAGIC) {
450 tdb_access_release(tdb, r);
451 tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
452 "lock_and_alloc: %llu non-free 0x%llx",
453 (long long)off, (long long)r->magic_and_prev);
457 if (frec_len(r) >= size && frec_len(r) < frec_len(&best)) {
462 if (frec_len(&best) < size * multiplier && best_off) {
463 tdb_access_release(tdb, r);
471 tdb_access_release(tdb, r);
473 /* Since we're going slow anyway, try coalescing here. */
474 switch (coalesce(tdb, off, b_off, len)) {
476 /* This has already unlocked on error. */
479 /* This has unlocked list, restart. */
485 /* If we found anything at all, use it. */
487 struct tdb_used_record rec;
490 /* We're happy with this size: take it. */
491 if (remove_from_list(tdb, b_off, best_off, &best) != 0)
494 leftover = record_leftover(keylen, datalen, want_extra,
497 assert(keylen + datalen + leftover <= frec_len(&best));
498 /* We need to mark non-free before we drop lock, otherwise
499 * coalesce() could try to merge it! */
500 if (set_header(tdb, &rec, magic, keylen, datalen,
501 frec_len(&best) - leftover, hashlow) != 0)
504 ecode = tdb_write_convert(tdb, best_off, &rec, sizeof(rec));
505 if (ecode != TDB_SUCCESS) {
510 /* Bucket of leftover will be <= current bucket, so nested
511 * locking is allowed. */
513 add_stat(tdb, alloc_leftover, 1);
514 if (add_free_record(tdb,
515 best_off + sizeof(rec)
516 + frec_len(&best) - leftover,
518 best_off = TDB_OFF_ERR;
520 tdb_unlock_free_bucket(tdb, b_off);
525 tdb_unlock_free_bucket(tdb, b_off);
529 tdb_unlock_free_bucket(tdb, b_off);
533 /* Get a free block from current free list, or 0 if none. */
534 static tdb_off_t get_free(struct tdb_context *tdb,
535 size_t keylen, size_t datalen, bool want_extra,
536 unsigned magic, unsigned hashlow)
538 tdb_off_t off, ftable_off;
539 unsigned start_b, b, ftable;
540 bool wrapped = false;
542 /* If they are growing, add 50% to get to higher bucket. */
544 start_b = size_to_bucket(adjust_size(keylen,
545 datalen + datalen / 2));
547 start_b = size_to_bucket(adjust_size(keylen, datalen));
549 ftable_off = tdb->ftable_off;
550 ftable = tdb->ftable;
551 while (!wrapped || ftable_off != tdb->ftable_off) {
552 /* Start at exact size bucket, and search up... */
553 for (b = find_free_head(tdb, ftable_off, start_b);
554 b < TDB_FREE_BUCKETS;
555 b = find_free_head(tdb, ftable_off, b + 1)) {
556 /* Try getting one from list. */
557 off = lock_and_alloc(tdb, ftable_off,
558 b, keylen, datalen, want_extra,
560 if (off == TDB_OFF_ERR)
564 add_stat(tdb, alloc_bucket_exact, 1);
565 if (b == TDB_FREE_BUCKETS - 1)
566 add_stat(tdb, alloc_bucket_max, 1);
567 /* Worked? Stay using this list. */
568 tdb->ftable_off = ftable_off;
569 tdb->ftable = ftable;
572 /* Didn't work. Try next bucket. */
575 /* Hmm, try next table. */
576 ftable_off = next_ftable(tdb, ftable_off);
579 if (ftable_off == 0) {
581 ftable_off = first_ftable(tdb);
589 int set_header(struct tdb_context *tdb,
590 struct tdb_used_record *rec,
591 unsigned magic, uint64_t keylen, uint64_t datalen,
592 uint64_t actuallen, unsigned hashlow)
594 uint64_t keybits = (fls64(keylen) + 1) / 2;
596 /* Use bottom bits of hash, so it's independent of hash table size. */
597 rec->magic_and_meta = (hashlow & ((1 << 11)-1))
598 | ((actuallen - (keylen + datalen)) << 11)
600 | ((uint64_t)magic << 48);
601 rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
603 /* Encoding can fail on big values. */
604 if (rec_key_length(rec) != keylen
605 || rec_data_length(rec) != datalen
606 || rec_extra_padding(rec) != actuallen - (keylen + datalen)) {
607 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
608 "Could not encode k=%llu,d=%llu,a=%llu",
609 (long long)keylen, (long long)datalen,
610 (long long)actuallen);
616 /* Expand the database. */
617 static int tdb_expand(struct tdb_context *tdb, tdb_len_t size)
621 enum TDB_ERROR ecode;
623 /* We need room for the record header too. */
624 wanted = sizeof(struct tdb_used_record) + size;
626 /* Need to hold a hash lock to expand DB: transactions rely on it. */
627 if (!(tdb->flags & TDB_NOLOCK)
628 && !tdb->allrecord_lock.count && !tdb_has_hash_locks(tdb)) {
629 tdb_logerr(tdb, TDB_ERR_LOCK, TDB_LOG_ERROR,
630 "tdb_expand: must hold lock during expand");
634 /* always make room for at least 100 more records, and at
635 least 25% more space. */
636 if (size * TDB_EXTENSION_FACTOR > tdb->map_size / 4)
637 wanted = size * TDB_EXTENSION_FACTOR;
639 wanted = tdb->map_size / 4;
640 wanted = adjust_size(0, wanted);
642 /* Only one person can expand file at a time. */
643 ecode = tdb_lock_expand(tdb, F_WRLCK);
644 if (ecode != TDB_SUCCESS) {
649 /* Someone else may have expanded the file, so retry. */
650 old_size = tdb->map_size;
651 tdb->methods->oob(tdb, tdb->map_size + 1, true);
652 if (tdb->map_size != old_size) {
653 tdb_unlock_expand(tdb, F_WRLCK);
657 ecode = tdb->methods->expand_file(tdb, wanted);
658 if (ecode != TDB_SUCCESS) {
660 tdb_unlock_expand(tdb, F_WRLCK);
664 /* We need to drop this lock before adding free record. */
665 tdb_unlock_expand(tdb, F_WRLCK);
667 add_stat(tdb, expands, 1);
668 return add_free_record(tdb, old_size, wanted);
671 /* This won't fail: it will expand the database if it has to. */
672 tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
673 uint64_t hash, unsigned magic, bool growing)
677 /* We can't hold pointers during this: we could unmap! */
678 assert(!tdb->direct_access);
681 off = get_free(tdb, keylen, datalen, growing, magic, hash);
682 if (likely(off != 0))
685 if (tdb_expand(tdb, adjust_size(keylen, datalen)))