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>
24 /* We have to be able to fit a free record here. */
25 #define MIN_DATA_LEN \
26 (sizeof(struct tdb_free_record) - sizeof(struct tdb_used_record))
28 static unsigned fls64(uint64_t val)
31 if (val <= ULONG_MAX) {
32 /* This is significantly faster! */
33 return val ? sizeof(long) * CHAR_BIT - __builtin_clzl(val) : 0;
40 if (!(val & 0xffffffff00000000ull)) {
44 if (!(val & 0xffff000000000000ull)) {
48 if (!(val & 0xff00000000000000ull)) {
52 if (!(val & 0xf000000000000000ull)) {
56 if (!(val & 0xc000000000000000ull)) {
60 if (!(val & 0x8000000000000000ull)) {
70 /* In which bucket would we find a particular record size? (ignoring header) */
71 unsigned int size_to_bucket(unsigned int zone_bits, tdb_len_t data_len)
75 /* We can't have records smaller than this. */
76 assert(data_len >= MIN_DATA_LEN);
78 /* Ignoring the header... */
79 if (data_len - MIN_DATA_LEN <= 64) {
80 /* 0 in bucket 0, 8 in bucket 1... 64 in bucket 6. */
81 bucket = (data_len - MIN_DATA_LEN) / 8;
83 /* After that we go power of 2. */
84 bucket = fls64(data_len - MIN_DATA_LEN) + 2;
87 if (unlikely(bucket > BUCKETS_FOR_ZONE(zone_bits)))
88 bucket = BUCKETS_FOR_ZONE(zone_bits);
92 /* Subtract 1-byte tailer and header. Then round up to next power of 2. */
93 static unsigned max_zone_bits(struct tdb_context *tdb)
95 return fls64(tdb->map_size-1-sizeof(struct tdb_header)-1) + 1;
98 /* Start by using a random zone to spread the load: returns the offset. */
99 static uint64_t random_zone(struct tdb_context *tdb)
101 struct free_zone_header zhdr;
102 tdb_off_t off = sizeof(struct tdb_header);
104 uint64_t randbits = 0;
107 for (i = 0; i < 64; i += fls64(RAND_MAX))
108 randbits ^= ((uint64_t)random()) << i;
110 /* FIXME: Does this work? Test! */
111 half_bits = max_zone_bits(tdb) - 1;
113 /* Pick left or right side (not outside file) */
115 && !tdb->methods->oob(tdb, off + (1ULL << half_bits)
116 + sizeof(zhdr), true)) {
117 off += 1ULL << half_bits;
121 if (tdb_read_convert(tdb, off, &zhdr, sizeof(zhdr)) == -1)
124 if (zhdr.zone_bits == half_bits)
128 } while (half_bits >= INITIAL_ZONE_BITS);
130 tdb->ecode = TDB_ERR_CORRUPT;
131 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
132 "random_zone: zone at %llu smaller than %u bits?",
133 (long long)off, INITIAL_ZONE_BITS);
137 int tdb_zone_init(struct tdb_context *tdb)
139 tdb->zone_off = random_zone(tdb);
140 if (tdb->zone_off == TDB_OFF_ERR)
142 if (tdb_read_convert(tdb, tdb->zone_off,
143 &tdb->zhdr, sizeof(tdb->zhdr)) == -1)
148 /* Where's the header, given a zone size of 1 << zone_bits? */
149 static tdb_off_t zone_off(tdb_off_t off, unsigned int zone_bits)
151 off -= sizeof(struct tdb_header);
152 return (off & ~((1ULL << zone_bits) - 1)) + sizeof(struct tdb_header);
155 /* Offset of a given bucket. */
156 /* FIXME: bucket can be "unsigned" everywhere, or even uint8/16. */
157 tdb_off_t bucket_off(tdb_off_t zone_off, tdb_off_t bucket)
160 + sizeof(struct free_zone_header)
161 + bucket * sizeof(tdb_off_t);
164 /* Returns free_buckets + 1, or list number to search. */
165 static tdb_off_t find_free_head(struct tdb_context *tdb, tdb_off_t bucket)
169 /* Speculatively search for a non-zero bucket. */
170 b = tdb_find_nonzero_off(tdb, bucket_off(tdb->zone_off, bucket),
171 BUCKETS_FOR_ZONE(tdb->zhdr.zone_bits) + 1
176 /* Remove from free bucket. */
177 static int remove_from_list(struct tdb_context *tdb,
178 tdb_off_t b_off, struct tdb_free_record *r)
186 off = r->prev + offsetof(struct tdb_free_record, next);
188 /* r->prev->next = r->next */
189 if (tdb_write_off(tdb, off, r->next)) {
194 off = r->next + offsetof(struct tdb_free_record, prev);
195 /* r->next->prev = r->prev */
196 if (tdb_write_off(tdb, off, r->prev)) {
203 /* Enqueue in this free bucket. */
204 static int enqueue_in_free(struct tdb_context *tdb,
207 struct tdb_free_record *new)
210 /* new->next = head. */
211 new->next = tdb_read_off(tdb, b_off);
212 if (new->next == TDB_OFF_ERR)
216 /* next->prev = new. */
217 if (tdb_write_off(tdb, new->next
218 + offsetof(struct tdb_free_record, prev),
223 if (tdb_write_off(tdb, b_off, off) != 0)
226 return tdb_write_convert(tdb, off, new, sizeof(*new));
229 /* List need not be locked. */
230 int add_free_record(struct tdb_context *tdb,
231 unsigned int zone_bits,
232 tdb_off_t off, tdb_len_t len_with_header)
234 struct tdb_free_record new;
238 assert(len_with_header >= sizeof(new));
239 assert(zone_bits < (1 << 6));
241 new.magic_and_meta = TDB_FREE_MAGIC | zone_bits;
242 new.data_len = len_with_header - sizeof(struct tdb_used_record);
244 b_off = bucket_off(zone_off(off, zone_bits),
245 size_to_bucket(zone_bits, new.data_len));
246 if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) != 0)
249 ret = enqueue_in_free(tdb, b_off, off, &new);
250 tdb_unlock_free_bucket(tdb, b_off);
254 /* If we have enough left over to be useful, split that off. */
255 static int to_used_record(struct tdb_context *tdb,
256 unsigned int zone_bits,
262 struct tdb_used_record used;
265 leftover = total_len - needed;
266 if (leftover < sizeof(struct tdb_free_record))
269 *actual = total_len - leftover;
272 if (add_free_record(tdb, zone_bits,
273 off + sizeof(used) + *actual,
280 /* Note: we unlock the current bucket if we coalesce or fail. */
281 static int coalesce(struct tdb_context *tdb,
282 tdb_off_t zone_off, unsigned zone_bits,
283 tdb_off_t off, tdb_off_t b_off, tdb_len_t data_len)
285 struct tdb_free_record pad, *r;
286 tdb_off_t end = off + sizeof(struct tdb_used_record) + data_len;
288 while (end < (zone_off + (1ULL << zone_bits))) {
291 /* FIXME: do tdb_get here and below really win? */
292 r = tdb_get(tdb, end, &pad, sizeof(pad));
296 if (frec_magic(r) != TDB_FREE_MAGIC)
299 nb_off = bucket_off(zone_off,
300 size_to_bucket(zone_bits, r->data_len));
302 /* We may be violating lock order here, so best effort. */
303 if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT) == -1)
306 /* Now we have lock, re-check. */
307 r = tdb_get(tdb, end, &pad, sizeof(pad));
309 tdb_unlock_free_bucket(tdb, nb_off);
313 if (unlikely(frec_magic(r) != TDB_FREE_MAGIC)) {
314 tdb_unlock_free_bucket(tdb, nb_off);
318 if (remove_from_list(tdb, nb_off, r) == -1) {
319 tdb_unlock_free_bucket(tdb, nb_off);
323 end += sizeof(struct tdb_used_record) + r->data_len;
324 tdb_unlock_free_bucket(tdb, nb_off);
327 /* Didn't find any adjacent free? */
328 if (end == off + sizeof(struct tdb_used_record) + data_len)
331 /* OK, expand record */
332 r = tdb_get(tdb, off, &pad, sizeof(pad));
336 if (r->data_len != data_len) {
337 tdb->ecode = TDB_ERR_CORRUPT;
338 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
339 "coalesce: expected data len %llu not %llu\n",
340 (long long)data_len, (long long)r->data_len);
344 if (remove_from_list(tdb, b_off, r) == -1)
347 /* We have to drop this to avoid deadlocks. */
348 tdb_unlock_free_bucket(tdb, b_off);
350 if (add_free_record(tdb, zone_bits, off, end - off) == -1)
355 /* To unify error paths, we *always* unlock bucket on error. */
356 tdb_unlock_free_bucket(tdb, b_off);
360 /* We need size bytes to put our key and data in. */
361 static tdb_off_t lock_and_alloc(struct tdb_context *tdb,
368 tdb_off_t off, b_off,best_off;
369 struct tdb_free_record pad, best = { 0 }, *r;
373 b_off = bucket_off(zone_off, bucket);
375 /* Lock this bucket. */
376 if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) == -1) {
380 best.data_len = -1ULL;
382 /* FIXME: Start with larger multiplier if we're growing. */
385 /* Walk the list to see if any are large enough, getting less fussy
387 off = tdb_read_off(tdb, b_off);
388 if (unlikely(off == TDB_OFF_ERR))
392 /* FIXME: Does tdb_get win anything here? */
393 r = tdb_get(tdb, off, &pad, sizeof(*r));
397 if (frec_magic(r) != TDB_FREE_MAGIC) {
398 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
399 "lock_and_alloc: %llu non-free 0x%llx\n",
400 (long long)off, (long long)r->magic_and_meta);
404 if (r->data_len >= size && r->data_len < best.data_len) {
409 if (best.data_len < size * multiplier && best_off)
414 /* Since we're going slow anyway, try coalescing here. */
415 switch (coalesce(tdb, zone_off, zone_bits, off, b_off,
418 /* This has already unlocked on error. */
421 /* This has unlocked list, restart. */
427 /* If we found anything at all, use it. */
430 /* We're happy with this size: take it. */
431 if (remove_from_list(tdb, b_off, &best) != 0)
433 tdb_unlock_free_bucket(tdb, b_off);
435 if (to_used_record(tdb, zone_bits, best_off, size,
436 best.data_len, actual)) {
442 tdb_unlock_free_bucket(tdb, b_off);
446 tdb_unlock_free_bucket(tdb, b_off);
450 static bool next_zone(struct tdb_context *tdb)
452 tdb_off_t next = tdb->zone_off + (1ULL << tdb->zhdr.zone_bits);
454 /* We must have a header. */
455 if (tdb->methods->oob(tdb, next + sizeof(tdb->zhdr), true))
458 tdb->zone_off = next;
459 return tdb_read_convert(tdb, next, &tdb->zhdr, sizeof(tdb->zhdr)) == 0;
462 /* Offset returned is within current zone (which it may alter). */
463 static tdb_off_t get_free(struct tdb_context *tdb, size_t size,
466 tdb_off_t start_zone = tdb->zone_off, off;
467 bool wrapped = false;
469 while (!wrapped || tdb->zone_off != start_zone) {
472 /* Shortcut for really huge allocations... */
473 if ((size >> tdb->zhdr.zone_bits) != 0)
476 /* Start at exact size bucket, and search up... */
477 b = size_to_bucket(tdb->zhdr.zone_bits, size);
478 for (b = find_free_head(tdb, b);
479 b <= BUCKETS_FOR_ZONE(tdb->zhdr.zone_bits);
480 b += find_free_head(tdb, b + 1)) {
481 /* Try getting one from list. */
482 off = lock_and_alloc(tdb, tdb->zone_off,
485 if (off == TDB_OFF_ERR)
489 /* Didn't work. Try next bucket. */
492 /* Didn't work, try next zone, if it exists. */
493 if (!next_zone(tdb)) {
495 tdb->zone_off = sizeof(struct tdb_header);
496 if (tdb_read_convert(tdb, tdb->zone_off,
497 &tdb->zhdr, sizeof(tdb->zhdr))) {
505 int set_header(struct tdb_context *tdb,
506 struct tdb_used_record *rec,
507 uint64_t keylen, uint64_t datalen,
508 uint64_t actuallen, uint64_t hash,
509 unsigned int zone_bits)
511 uint64_t keybits = (fls64(keylen) + 1) / 2;
513 /* Use top bits of hash, so it's independent of hash table size. */
516 | ((hash >> 59) << 6)
517 | ((actuallen - (keylen + datalen)) << 11)
520 rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
522 /* Encoding can fail on big values. */
523 if (rec_key_length(rec) != keylen
524 || rec_data_length(rec) != datalen
525 || rec_extra_padding(rec) != actuallen - (keylen + datalen)) {
526 tdb->ecode = TDB_ERR_IO;
527 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
528 "Could not encode k=%llu,d=%llu,a=%llu\n",
529 (long long)keylen, (long long)datalen,
530 (long long)actuallen);
536 static tdb_len_t adjust_size(size_t keylen, size_t datalen, bool growing)
538 tdb_len_t size = keylen + datalen;
540 if (size < MIN_DATA_LEN)
543 /* Overallocate if this is coming from an enlarging store. */
547 /* Round to next uint64_t boundary. */
548 return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
551 /* If this fails, try tdb_expand. */
552 tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
553 uint64_t hash, bool growing)
556 tdb_len_t size, actual;
557 struct tdb_used_record rec;
559 /* We don't want header to change during this! */
560 assert(tdb->header_uptodate);
562 size = adjust_size(keylen, datalen, growing);
564 off = get_free(tdb, size, &actual);
565 if (unlikely(off == TDB_OFF_ERR || off == 0))
568 /* Some supergiant values can't be encoded. */
569 /* FIXME: Check before, and limit actual in get_free. */
570 if (set_header(tdb, &rec, keylen, datalen, actual, hash,
571 tdb->zhdr.zone_bits) != 0) {
572 add_free_record(tdb, tdb->zhdr.zone_bits, off,
573 sizeof(rec) + actual);
577 if (tdb_write_convert(tdb, off, &rec, sizeof(rec)) != 0)
583 static bool zones_happy(struct tdb_context *tdb)
585 /* FIXME: look at distribution of zones. */
589 /* Assume we want buckets up to the comfort factor. */
590 static tdb_len_t overhead(unsigned int zone_bits)
592 return sizeof(struct free_zone_header)
593 + (BUCKETS_FOR_ZONE(zone_bits) + 1) * sizeof(tdb_off_t);
596 /* Expand the database (by adding a zone). */
597 int tdb_expand(struct tdb_context *tdb, tdb_len_t klen, tdb_len_t dlen,
603 unsigned int num_buckets;
605 struct free_zone_header zhdr;
608 /* We need room for the record header too. */
609 wanted = sizeof(struct tdb_used_record)
610 + (adjust_size(klen, dlen, growing)<<TDB_COMFORT_FACTOR_BITS);
612 /* Only one person can expand file at a time. */
613 if (tdb_lock_expand(tdb, F_WRLCK) != 0)
616 /* Someone else may have expanded the file, so retry. */
617 old_size = tdb->map_size;
618 tdb->methods->oob(tdb, tdb->map_size + 1, true);
619 if (tdb->map_size != old_size)
622 /* zone bits tailer char is protected by EXPAND lock. */
623 if (tdb->methods->read(tdb, old_size - 1, &zone_bits, 1) == -1)
626 /* If zones aren't working well, add larger zone if possible. */
627 enlarge_zone = !zones_happy(tdb);
629 /* New zone can be between zone_bits or larger if we're on the right
632 /* Does this fit the allocation comfortably? */
633 if ((1ULL << zone_bits) >= overhead(zone_bits) + wanted) {
634 /* Only let enlarge_zone enlarge us once. */
637 enlarge_zone = false;
639 if ((old_size - 1 - sizeof(struct tdb_header))
645 zhdr.zone_bits = zone_bits;
646 num_buckets = BUCKETS_FOR_ZONE(zone_bits);
648 if (tdb->methods->expand_file(tdb, 1ULL << zone_bits) == -1)
651 /* Write new tailer. */
652 if (tdb->methods->write(tdb, tdb->map_size - 1, &zone_bits, 1) == -1)
655 /* Write new zone header (just before old tailer). */
657 if (tdb_write_convert(tdb, off, &zhdr, sizeof(zhdr)) == -1)
660 /* Now write empty buckets. */
662 if (zero_out(tdb, off, (num_buckets+1) * sizeof(tdb_off_t)) == -1)
664 off += (num_buckets+1) * sizeof(tdb_off_t);
666 /* Now add the rest as our free record. */
667 if (add_free_record(tdb, zone_bits, off, tdb->map_size-1-off) == -1)
671 tdb_unlock_expand(tdb, F_WRLCK);
675 tdb_unlock_expand(tdb, F_WRLCK);