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 enum TDB_ERROR 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 (TDB_OFF_IS_ERR(off)) {
78 tdb->ftable_off = off;
83 off = next_ftable(tdb, off);
89 /* Offset of a given bucket. */
90 tdb_off_t bucket_off(tdb_off_t ftable_off, unsigned bucket)
92 return ftable_off + offsetof(struct tdb_freetable, buckets)
93 + bucket * sizeof(tdb_off_t);
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,
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);
106 static void check_list(struct tdb_context *tdb, tdb_off_t b_off)
108 #ifdef CCAN_TDB2_DEBUG
109 tdb_off_t off, prev = 0, first;
110 struct tdb_free_record r;
112 first = off = tdb_read_off(tdb, b_off);
114 tdb_read_convert(tdb, off, &r, sizeof(r));
115 if (frec_magic(&r) != TDB_FREE_MAGIC)
117 if (prev && frec_prev(&r) != prev)
124 tdb_read_convert(tdb, first, &r, sizeof(r));
125 if (frec_prev(&r) != prev)
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)
136 tdb_off_t off, prev_next, head;
137 enum TDB_ERROR ecode;
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);
143 /* off = &r->prev->next */
144 off = frec_prev(r) + offsetof(struct tdb_free_record, next);
147 prev_next = tdb_read_off(tdb, off);
148 if (TDB_OFF_IS_ERR(prev_next))
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,
157 " %llu head %llu on list %llu",
159 (long long)tdb_read_off(tdb, b_off),
163 ecode = tdb_write_off(tdb, b_off, r->next);
164 if (ecode != TDB_SUCCESS)
167 /* r->prev->next = r->next */
168 ecode = tdb_write_off(tdb, off, r->next);
169 if (ecode != TDB_SUCCESS)
173 /* If we were the tail, off = &head->prev. */
175 head = tdb_read_off(tdb, b_off);
176 if (TDB_OFF_IS_ERR(head))
178 off = head + offsetof(struct tdb_free_record, magic_and_prev);
180 /* off = &r->next->prev */
181 off = r->next + offsetof(struct tdb_free_record,
185 #ifdef CCAN_TDB2_DEBUG
187 if ((tdb_read_off(tdb, off) & TDB_OFF_MASK) != r_off) {
188 return tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
190 " %llu bad prev in list %llu",
191 (long long)r_off, (long long)b_off);
194 /* r->next->prev = r->prev */
195 return tdb_write_off(tdb, off, r->magic_and_prev);
198 /* Enqueue in this free bucket. */
199 static enum TDB_ERROR enqueue_in_free(struct tdb_context *tdb,
204 struct tdb_free_record new;
205 enum TDB_ERROR ecode;
207 uint64_t magic = (TDB_FREE_MAGIC << (64 - TDB_OFF_UPPER_STEAL));
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))
213 /* new->next = head. */
214 new.next = tdb_read_off(tdb, b_off);
215 if (TDB_OFF_IS_ERR(new.next)) {
219 /* First element? Prev points to ourselves. */
221 new.magic_and_prev = (magic | off);
223 /* new->prev = next->prev */
224 prev = tdb_read_off(tdb,
225 new.next + offsetof(struct tdb_free_record,
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"
235 /* next->prev = new. */
236 ecode = tdb_write_off(tdb, new.next
237 + offsetof(struct tdb_free_record,
240 if (ecode != TDB_SUCCESS) {
244 #ifdef CCAN_TDB2_DEBUG
245 prev = tdb_read_off(tdb, frec_prev(&new)
246 + offsetof(struct tdb_free_record, next));
248 return tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
250 " %llu bad tail next ptr %llu",
251 (long long)frec_prev(&new)
252 + offsetof(struct tdb_free_record,
259 ecode = tdb_write_off(tdb, b_off, off);
260 if (ecode != TDB_SUCCESS) {
264 return tdb_write_convert(tdb, off, &new, sizeof(new));
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)
273 enum TDB_ERROR ecode;
275 assert(len_with_header >= sizeof(struct tdb_free_record));
277 len = len_with_header - sizeof(struct tdb_used_record);
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) {
285 ecode = enqueue_in_free(tdb, b_off, off, len);
286 check_list(tdb, b_off);
287 tdb_unlock_free_bucket(tdb, b_off);
291 static size_t adjust_size(size_t keylen, size_t datalen)
293 size_t size = keylen + datalen;
295 if (size < TDB_MIN_DATA_LEN)
296 size = TDB_MIN_DATA_LEN;
298 /* Round to next uint64_t boundary. */
299 return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
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)
309 datalen += datalen / 2;
310 leftover = total_len - adjust_size(keylen, datalen);
312 if (leftover < (ssize_t)sizeof(struct tdb_free_record))
318 static tdb_off_t ftable_offset(struct tdb_context *tdb, unsigned int ftable)
323 if (likely(tdb->ftable == ftable))
324 return tdb->ftable_off;
326 off = first_ftable(tdb);
327 for (i = 0; i < ftable; i++) {
328 if (TDB_OFF_IS_ERR(off)) {
331 off = next_ftable(tdb, off);
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,
342 struct tdb_free_record rec;
343 enum TDB_ERROR ecode;
345 add_stat(tdb, alloc_coalesce_tried, 1);
346 end = off + sizeof(struct tdb_used_record) + data_len;
348 while (end < tdb->file->map_size) {
349 const struct tdb_free_record *r;
351 unsigned ftable, bucket;
353 r = tdb_access_read(tdb, end, sizeof(*r), true);
354 if (TDB_PTR_IS_ERR(r)) {
355 ecode = TDB_PTR_ERR(r);
359 if (frec_magic(r) != TDB_FREE_MAGIC
360 || frec_ftable(r) == TDB_FTABLE_NONE) {
361 tdb_access_release(tdb, r);
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);
373 nb_off = bucket_off(nb_off, bucket);
374 tdb_access_release(tdb, r);
376 /* We may be violating lock order here, so best effort. */
377 if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT)
379 add_stat(tdb, alloc_coalesce_lockfail, 1);
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);
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);
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);
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);
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);
415 /* Didn't find any adjacent free? */
416 if (end == off + sizeof(struct tdb_used_record) + data_len)
419 /* OK, expand initial record */
420 ecode = tdb_read_convert(tdb, off, &rec, sizeof(rec));
421 if (ecode != TDB_SUCCESS) {
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));
432 ecode = remove_from_list(tdb, b_off, off, &rec);
433 check_list(tdb, b_off);
434 if (ecode != TDB_SUCCESS) {
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,
445 if (ecode != TDB_SUCCESS) {
449 add_stat(tdb, alloc_coalesce_succeeded, 1);
450 tdb_unlock_free_bucket(tdb, b_off);
452 ecode = add_free_record(tdb, off, end - off);
453 if (ecode != TDB_SUCCESS) {
459 /* To unify error paths, we *always* unlock bucket on error. */
460 tdb_unlock_free_bucket(tdb, b_off);
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,
468 size_t keylen, size_t datalen,
473 tdb_off_t off, b_off,best_off;
474 struct tdb_free_record best = { 0 };
476 size_t size = adjust_size(keylen, datalen);
477 enum TDB_ERROR ecode;
479 add_stat(tdb, allocs, 1);
481 b_off = bucket_off(ftable_off, bucket);
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) {
490 best.ftable_and_len = -1ULL;
493 /* Get slack if we're after extra. */
499 /* Walk the list to see if any are large enough, getting less fussy
501 off = tdb_read_off(tdb, b_off);
502 if (TDB_OFF_IS_ERR(off)) {
508 const struct tdb_free_record *r;
513 r = tdb_access_read(tdb, off, sizeof(*r), true);
514 if (TDB_PTR_IS_ERR(r)) {
515 ecode = TDB_PTR_ERR(r);
519 if (frec_magic(r) != TDB_FREE_MAGIC) {
520 ecode = tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
522 " %llu non-free 0x%llx",
524 (long long)r->magic_and_prev);
525 tdb_access_release(tdb, r);
529 if (frec_len(r) >= size && frec_len(r) < frec_len(&best)) {
534 if (frec_len(&best) <= size * multiplier && best_off) {
535 tdb_access_release(tdb, r);
543 tdb_access_release(tdb, r);
545 /* Since we're going slow anyway, try coalescing here. */
546 coal = coalesce(tdb, off, b_off, len);
548 /* This has unlocked list, restart. */
552 /* This has already unlocked on error. */
558 /* If we found anything at all, use it. */
560 struct tdb_used_record rec;
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) {
570 leftover = record_leftover(keylen, datalen, want_extra,
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) {
582 ecode = tdb_write_convert(tdb, best_off, &rec, sizeof(rec));
583 if (ecode != TDB_SUCCESS) {
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) {
596 /* Bucket of leftover will be <= current bucket, so nested
597 * locking is allowed. */
599 add_stat(tdb, alloc_leftover, 1);
600 ecode = add_free_record(tdb,
601 best_off + sizeof(rec)
602 + frec_len(&best) - leftover,
604 if (ecode != TDB_SUCCESS) {
608 tdb_unlock_free_bucket(tdb, b_off);
613 tdb_unlock_free_bucket(tdb, b_off);
617 tdb_unlock_free_bucket(tdb, b_off);
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)
626 tdb_off_t off, ftable_off;
627 tdb_off_t start_b, b, ftable;
628 bool wrapped = false;
630 /* If they are growing, add 50% to get to higher bucket. */
632 start_b = size_to_bucket(adjust_size(keylen,
633 datalen + datalen / 2));
635 start_b = size_to_bucket(adjust_size(keylen, datalen));
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,
648 if (TDB_OFF_IS_ERR(off))
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;
660 /* Didn't work. Try next bucket. */
663 if (TDB_OFF_IS_ERR(b)) {
667 /* Hmm, try next table. */
668 ftable_off = next_ftable(tdb, ftable_off);
669 if (TDB_OFF_IS_ERR(ftable_off)) {
674 if (ftable_off == 0) {
676 ftable_off = first_ftable(tdb);
677 if (TDB_OFF_IS_ERR(ftable_off)) {
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)
692 uint64_t keybits = (fls64(keylen) + 1) / 2;
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)
698 | ((uint64_t)magic << 48);
699 rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
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);
713 /* Expand the database. */
714 static enum TDB_ERROR tdb_expand(struct tdb_context *tdb, tdb_len_t size)
718 enum TDB_ERROR ecode;
720 /* We need room for the record header too. */
721 wanted = sizeof(struct tdb_used_record) + size;
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");
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;
735 wanted = tdb->file->map_size / 4;
736 wanted = adjust_size(0, wanted);
738 /* Only one person can expand file at a time. */
739 ecode = tdb_lock_expand(tdb, F_WRLCK);
740 if (ecode != TDB_SUCCESS) {
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);
752 ecode = tdb->methods->expand_file(tdb, wanted);
753 if (ecode != TDB_SUCCESS) {
754 tdb_unlock_expand(tdb, F_WRLCK);
758 /* We need to drop this lock before adding free record. */
759 tdb_unlock_expand(tdb, F_WRLCK);
761 add_stat(tdb, expands, 1);
762 return add_free_record(tdb, old_size, wanted);
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)
771 /* We can't hold pointers during this: we could unmap! */
772 assert(!tdb->direct_access);
775 enum TDB_ERROR ecode;
776 off = get_free(tdb, keylen, datalen, growing, magic, hash);
777 if (likely(off != 0))
780 ecode = tdb_expand(tdb, adjust_size(keylen, datalen));
781 if (ecode != TDB_SUCCESS) {