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 /* Remove from free bucket. */
107 static enum TDB_ERROR remove_from_list(struct tdb_context *tdb,
108 tdb_off_t b_off, tdb_off_t r_off,
109 const struct tdb_free_record *r)
112 enum TDB_ERROR ecode;
115 if (frec_prev(r) == 0) {
118 off = frec_prev(r) + offsetof(struct tdb_free_record, next);
121 #ifdef CCAN_TDB2_DEBUG
122 if (tdb_read_off(tdb, off) != r_off) {
123 return tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
125 " %llu bad prev in list %llu",
126 (long long)r_off, (long long)b_off);
130 /* r->prev->next = r->next */
131 ecode = tdb_write_off(tdb, off, r->next);
132 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 return tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
144 " %llu bad list %llu",
145 (long long)r_off, (long long)b_off);
149 ecode = tdb_write_off(tdb, off, r->magic_and_prev);
150 if (ecode != TDB_SUCCESS) {
157 /* Enqueue in this free bucket. */
158 static enum TDB_ERROR enqueue_in_free(struct tdb_context *tdb,
163 struct tdb_free_record new;
164 enum TDB_ERROR ecode;
165 uint64_t magic = (TDB_FREE_MAGIC << (64 - TDB_OFF_UPPER_STEAL));
167 /* We only need to set ftable_and_len; rest is set in enqueue_in_free */
168 new.ftable_and_len = ((uint64_t)tdb->ftable << (64 - TDB_OFF_UPPER_STEAL))
171 new.magic_and_prev = magic;
173 /* new->next = head. */
174 new.next = tdb_read_off(tdb, b_off);
175 if (TDB_OFF_IS_ERR(new.next)) {
180 #ifdef CCAN_TDB2_DEBUG
181 if (tdb_read_off(tdb,
182 new.next + offsetof(struct tdb_free_record,
185 return tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
186 "enqueue_in_free: %llu bad head"
192 /* next->prev = new. */
193 ecode = tdb_write_off(tdb, new.next
194 + offsetof(struct tdb_free_record,
197 if (ecode != TDB_SUCCESS) {
202 ecode = tdb_write_off(tdb, b_off, off);
203 if (ecode != TDB_SUCCESS) {
207 return tdb_write_convert(tdb, off, &new, sizeof(new));
210 /* List need not be locked. */
211 enum TDB_ERROR add_free_record(struct tdb_context *tdb,
212 tdb_off_t off, tdb_len_t len_with_header)
216 enum TDB_ERROR ecode;
218 assert(len_with_header >= sizeof(struct tdb_free_record));
220 len = len_with_header - sizeof(struct tdb_used_record);
222 b_off = bucket_off(tdb->ftable_off, size_to_bucket(len));
223 ecode = tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT);
224 if (ecode != TDB_SUCCESS) {
228 ecode = enqueue_in_free(tdb, b_off, off, len);
229 tdb_unlock_free_bucket(tdb, b_off);
233 static size_t adjust_size(size_t keylen, size_t datalen)
235 size_t size = keylen + datalen;
237 if (size < TDB_MIN_DATA_LEN)
238 size = TDB_MIN_DATA_LEN;
240 /* Round to next uint64_t boundary. */
241 return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
244 /* If we have enough left over to be useful, split that off. */
245 static size_t record_leftover(size_t keylen, size_t datalen,
246 bool want_extra, size_t total_len)
251 datalen += datalen / 2;
252 leftover = total_len - adjust_size(keylen, datalen);
254 if (leftover < (ssize_t)sizeof(struct tdb_free_record))
260 static tdb_off_t ftable_offset(struct tdb_context *tdb, unsigned int ftable)
265 if (likely(tdb->ftable == ftable))
266 return tdb->ftable_off;
268 off = first_ftable(tdb);
269 for (i = 0; i < ftable; i++) {
270 if (TDB_OFF_IS_ERR(off)) {
274 off = next_ftable(tdb, off);
279 /* Note: we unlock the current bucket if we coalesce or fail. */
280 static tdb_bool_err coalesce(struct tdb_context *tdb,
281 tdb_off_t off, tdb_off_t b_off,
285 struct tdb_free_record rec;
286 enum TDB_ERROR ecode;
288 add_stat(tdb, alloc_coalesce_tried, 1);
289 end = off + sizeof(struct tdb_used_record) + data_len;
291 while (end < tdb->map_size) {
292 const struct tdb_free_record *r;
294 unsigned ftable, bucket;
296 r = tdb_access_read(tdb, end, sizeof(*r), true);
297 if (TDB_PTR_IS_ERR(r)) {
298 ecode = TDB_PTR_ERR(r);
302 if (frec_magic(r) != TDB_FREE_MAGIC
303 || frec_ftable(r) == TDB_FTABLE_NONE) {
304 tdb_access_release(tdb, r);
308 ftable = frec_ftable(r);
309 bucket = size_to_bucket(frec_len(r));
310 nb_off = ftable_offset(tdb, ftable);
311 if (TDB_OFF_IS_ERR(nb_off)) {
312 tdb_access_release(tdb, r);
316 nb_off = bucket_off(nb_off, bucket);
317 tdb_access_release(tdb, r);
319 /* We may be violating lock order here, so best effort. */
320 if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT)
322 add_stat(tdb, alloc_coalesce_lockfail, 1);
326 /* Now we have lock, re-check. */
327 ecode = tdb_read_convert(tdb, end, &rec, sizeof(rec));
328 if (ecode != TDB_SUCCESS) {
329 tdb_unlock_free_bucket(tdb, nb_off);
333 if (unlikely(frec_magic(&rec) != TDB_FREE_MAGIC)) {
334 add_stat(tdb, alloc_coalesce_race, 1);
335 tdb_unlock_free_bucket(tdb, nb_off);
339 if (unlikely(frec_ftable(&rec) != ftable)
340 || unlikely(size_to_bucket(frec_len(&rec)) != bucket)) {
341 add_stat(tdb, alloc_coalesce_race, 1);
342 tdb_unlock_free_bucket(tdb, nb_off);
346 ecode = remove_from_list(tdb, nb_off, end, &rec);
347 if (ecode != TDB_SUCCESS) {
348 tdb_unlock_free_bucket(tdb, nb_off);
352 end += sizeof(struct tdb_used_record) + frec_len(&rec);
353 tdb_unlock_free_bucket(tdb, nb_off);
354 add_stat(tdb, alloc_coalesce_num_merged, 1);
357 /* Didn't find any adjacent free? */
358 if (end == off + sizeof(struct tdb_used_record) + data_len)
361 /* OK, expand initial record */
362 ecode = tdb_read_convert(tdb, off, &rec, sizeof(rec));
363 if (ecode != TDB_SUCCESS) {
367 if (frec_len(&rec) != data_len) {
368 ecode = tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
369 "coalesce: expected data len %zu not %zu",
370 (size_t)data_len, (size_t)frec_len(&rec));
374 ecode = remove_from_list(tdb, b_off, off, &rec);
375 if (ecode != TDB_SUCCESS) {
379 /* We have to drop this to avoid deadlocks, so make sure record
380 * doesn't get coalesced by someone else! */
381 rec.ftable_and_len = (TDB_FTABLE_NONE << (64 - TDB_OFF_UPPER_STEAL))
382 | (end - off - sizeof(struct tdb_used_record));
383 ecode = tdb_write_off(tdb, off + offsetof(struct tdb_free_record,
386 if (ecode != TDB_SUCCESS) {
390 add_stat(tdb, alloc_coalesce_succeeded, 1);
391 tdb_unlock_free_bucket(tdb, b_off);
393 ecode = add_free_record(tdb, off, end - off);
394 if (ecode != TDB_SUCCESS) {
401 /* To unify error paths, we *always* unlock bucket on error. */
402 tdb_unlock_free_bucket(tdb, b_off);
406 /* We need size bytes to put our key and data in. */
407 static tdb_off_t lock_and_alloc(struct tdb_context *tdb,
408 tdb_off_t ftable_off,
410 size_t keylen, size_t datalen,
415 tdb_off_t off, b_off,best_off;
416 struct tdb_free_record best = { 0 };
418 size_t size = adjust_size(keylen, datalen);
419 enum TDB_ERROR ecode;
421 add_stat(tdb, allocs, 1);
423 b_off = bucket_off(ftable_off, bucket);
425 /* FIXME: Try non-blocking wait first, to measure contention. */
426 /* Lock this bucket. */
427 ecode = tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT);
428 if (ecode != TDB_SUCCESS) {
432 best.ftable_and_len = -1ULL;
435 /* Get slack if we're after extra. */
441 /* Walk the list to see if any are large enough, getting less fussy
443 off = tdb_read_off(tdb, b_off);
444 if (TDB_OFF_IS_ERR(off)) {
450 const struct tdb_free_record *r;
455 r = tdb_access_read(tdb, off, sizeof(*r), true);
456 if (TDB_PTR_IS_ERR(r)) {
457 ecode = TDB_PTR_ERR(r);
461 if (frec_magic(r) != TDB_FREE_MAGIC) {
462 tdb_access_release(tdb, r);
463 ecode = tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
465 " %llu non-free 0x%llx",
467 (long long)r->magic_and_prev);
471 if (frec_len(r) >= size && frec_len(r) < frec_len(&best)) {
476 if (frec_len(&best) < size * multiplier && best_off) {
477 tdb_access_release(tdb, r);
485 tdb_access_release(tdb, r);
487 /* Since we're going slow anyway, try coalescing here. */
488 coal = coalesce(tdb, off, b_off, len);
490 /* This has unlocked list, restart. */
494 /* This has already unlocked on error. */
500 /* If we found anything at all, use it. */
502 struct tdb_used_record rec;
505 /* We're happy with this size: take it. */
506 ecode = remove_from_list(tdb, b_off, best_off, &best);
507 if (ecode != TDB_SUCCESS) {
511 leftover = record_leftover(keylen, datalen, want_extra,
514 assert(keylen + datalen + leftover <= frec_len(&best));
515 /* We need to mark non-free before we drop lock, otherwise
516 * coalesce() could try to merge it! */
517 ecode = set_header(tdb, &rec, magic, keylen, datalen,
518 frec_len(&best) - leftover, hashlow);
519 if (ecode != TDB_SUCCESS) {
523 ecode = tdb_write_convert(tdb, best_off, &rec, sizeof(rec));
524 if (ecode != TDB_SUCCESS) {
528 /* Bucket of leftover will be <= current bucket, so nested
529 * locking is allowed. */
531 add_stat(tdb, alloc_leftover, 1);
532 ecode = add_free_record(tdb,
533 best_off + sizeof(rec)
534 + frec_len(&best) - leftover,
536 if (ecode != TDB_SUCCESS) {
540 tdb_unlock_free_bucket(tdb, b_off);
545 tdb_unlock_free_bucket(tdb, b_off);
549 tdb_unlock_free_bucket(tdb, b_off);
553 /* Get a free block from current free list, or 0 if none, -ve on error. */
554 static tdb_off_t get_free(struct tdb_context *tdb,
555 size_t keylen, size_t datalen, bool want_extra,
556 unsigned magic, unsigned hashlow)
558 tdb_off_t off, ftable_off;
559 tdb_off_t start_b, b, ftable;
560 bool wrapped = false;
562 /* If they are growing, add 50% to get to higher bucket. */
564 start_b = size_to_bucket(adjust_size(keylen,
565 datalen + datalen / 2));
567 start_b = size_to_bucket(adjust_size(keylen, datalen));
569 ftable_off = tdb->ftable_off;
570 ftable = tdb->ftable;
571 while (!wrapped || ftable_off != tdb->ftable_off) {
572 /* Start at exact size bucket, and search up... */
573 for (b = find_free_head(tdb, ftable_off, start_b);
574 b < TDB_FREE_BUCKETS;
575 b = find_free_head(tdb, ftable_off, b + 1)) {
576 /* Try getting one from list. */
577 off = lock_and_alloc(tdb, ftable_off,
578 b, keylen, datalen, want_extra,
580 if (TDB_OFF_IS_ERR(off))
584 add_stat(tdb, alloc_bucket_exact, 1);
585 if (b == TDB_FREE_BUCKETS - 1)
586 add_stat(tdb, alloc_bucket_max, 1);
587 /* Worked? Stay using this list. */
588 tdb->ftable_off = ftable_off;
589 tdb->ftable = ftable;
592 /* Didn't work. Try next bucket. */
595 if (TDB_OFF_IS_ERR(b)) {
599 /* Hmm, try next table. */
600 ftable_off = next_ftable(tdb, ftable_off);
601 if (TDB_OFF_IS_ERR(ftable_off)) {
606 if (ftable_off == 0) {
608 ftable_off = first_ftable(tdb);
609 if (TDB_OFF_IS_ERR(ftable_off)) {
619 enum TDB_ERROR set_header(struct tdb_context *tdb,
620 struct tdb_used_record *rec,
621 unsigned magic, uint64_t keylen, uint64_t datalen,
622 uint64_t actuallen, unsigned hashlow)
624 uint64_t keybits = (fls64(keylen) + 1) / 2;
626 /* Use bottom bits of hash, so it's independent of hash table size. */
627 rec->magic_and_meta = (hashlow & ((1 << 11)-1))
628 | ((actuallen - (keylen + datalen)) << 11)
630 | ((uint64_t)magic << 48);
631 rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
633 /* Encoding can fail on big values. */
634 if (rec_key_length(rec) != keylen
635 || rec_data_length(rec) != datalen
636 || rec_extra_padding(rec) != actuallen - (keylen + datalen)) {
637 return tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
638 "Could not encode k=%llu,d=%llu,a=%llu",
639 (long long)keylen, (long long)datalen,
640 (long long)actuallen);
645 /* Expand the database. */
646 static enum TDB_ERROR tdb_expand(struct tdb_context *tdb, tdb_len_t size)
650 enum TDB_ERROR ecode;
652 /* We need room for the record header too. */
653 wanted = sizeof(struct tdb_used_record) + size;
655 /* Need to hold a hash lock to expand DB: transactions rely on it. */
656 if (!(tdb->flags & TDB_NOLOCK)
657 && !tdb->allrecord_lock.count && !tdb_has_hash_locks(tdb)) {
658 return tdb_logerr(tdb, TDB_ERR_LOCK, TDB_LOG_ERROR,
659 "tdb_expand: must hold lock during expand");
662 /* always make room for at least 100 more records, and at
663 least 25% more space. */
664 if (size * TDB_EXTENSION_FACTOR > tdb->map_size / 4)
665 wanted = size * TDB_EXTENSION_FACTOR;
667 wanted = tdb->map_size / 4;
668 wanted = adjust_size(0, wanted);
670 /* Only one person can expand file at a time. */
671 ecode = tdb_lock_expand(tdb, F_WRLCK);
672 if (ecode != TDB_SUCCESS) {
676 /* Someone else may have expanded the file, so retry. */
677 old_size = tdb->map_size;
678 tdb->methods->oob(tdb, tdb->map_size + 1, true);
679 if (tdb->map_size != old_size) {
680 tdb_unlock_expand(tdb, F_WRLCK);
684 ecode = tdb->methods->expand_file(tdb, wanted);
685 if (ecode != TDB_SUCCESS) {
686 tdb_unlock_expand(tdb, F_WRLCK);
690 /* We need to drop this lock before adding free record. */
691 tdb_unlock_expand(tdb, F_WRLCK);
693 add_stat(tdb, expands, 1);
694 return add_free_record(tdb, old_size, wanted);
697 /* This won't fail: it will expand the database if it has to. */
698 tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
699 uint64_t hash, unsigned magic, bool growing)
703 /* We can't hold pointers during this: we could unmap! */
704 assert(!tdb->direct_access);
707 enum TDB_ERROR ecode;
708 off = get_free(tdb, keylen, datalen, growing, magic, hash);
709 if (likely(off != 0))
712 ecode = tdb_expand(tdb, adjust_size(keylen, datalen));
713 if (ecode != TDB_SUCCESS) {