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)
167 /* Speculatively search for a non-zero bucket. */
168 return tdb_find_nonzero_off(tdb, bucket_off(tdb->zone_off, 0),
170 BUCKETS_FOR_ZONE(tdb->zhdr.zone_bits) + 1);
173 /* Remove from free bucket. */
174 static int remove_from_list(struct tdb_context *tdb,
175 tdb_off_t b_off, struct tdb_free_record *r)
183 off = r->prev + offsetof(struct tdb_free_record, next);
185 /* r->prev->next = r->next */
186 if (tdb_write_off(tdb, off, r->next)) {
191 off = r->next + offsetof(struct tdb_free_record, prev);
192 /* r->next->prev = r->prev */
193 if (tdb_write_off(tdb, off, r->prev)) {
200 /* Enqueue in this free bucket. */
201 static int enqueue_in_free(struct tdb_context *tdb,
204 struct tdb_free_record *new)
207 /* new->next = head. */
208 new->next = tdb_read_off(tdb, b_off);
209 if (new->next == TDB_OFF_ERR)
213 /* next->prev = new. */
214 if (tdb_write_off(tdb, new->next
215 + offsetof(struct tdb_free_record, prev),
220 if (tdb_write_off(tdb, b_off, off) != 0)
223 return tdb_write_convert(tdb, off, new, sizeof(*new));
226 /* List need not be locked. */
227 int add_free_record(struct tdb_context *tdb,
228 unsigned int zone_bits,
229 tdb_off_t off, tdb_len_t len_with_header)
231 struct tdb_free_record new;
235 assert(len_with_header >= sizeof(new));
236 assert(zone_bits < (1 << 6));
238 new.magic_and_meta = TDB_FREE_MAGIC | zone_bits;
239 new.data_len = len_with_header - sizeof(struct tdb_used_record);
241 b_off = bucket_off(zone_off(off, zone_bits),
242 size_to_bucket(zone_bits, new.data_len));
243 if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) != 0)
246 ret = enqueue_in_free(tdb, b_off, off, &new);
247 tdb_unlock_free_bucket(tdb, b_off);
251 /* If we have enough left over to be useful, split that off. */
252 static int to_used_record(struct tdb_context *tdb,
253 unsigned int zone_bits,
259 struct tdb_used_record used;
262 leftover = total_len - needed;
263 if (leftover < sizeof(struct tdb_free_record))
266 *actual = total_len - leftover;
269 if (add_free_record(tdb, zone_bits,
270 off + sizeof(used) + *actual,
277 /* Note: we unlock the current bucket if we coalesce or fail. */
278 static int coalesce(struct tdb_context *tdb,
279 tdb_off_t zone_off, unsigned zone_bits,
280 tdb_off_t off, tdb_off_t b_off, tdb_len_t data_len)
282 struct tdb_free_record pad, *r;
283 tdb_off_t end = off + sizeof(struct tdb_used_record) + data_len;
285 while (end < (zone_off + (1ULL << zone_bits))) {
288 /* FIXME: do tdb_get here and below really win? */
289 r = tdb_get(tdb, end, &pad, sizeof(pad));
293 if (frec_magic(r) != TDB_FREE_MAGIC)
296 nb_off = bucket_off(zone_off,
297 size_to_bucket(zone_bits, r->data_len));
299 /* We may be violating lock order here, so best effort. */
300 if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT) == -1)
303 /* Now we have lock, re-check. */
304 r = tdb_get(tdb, end, &pad, sizeof(pad));
306 tdb_unlock_free_bucket(tdb, nb_off);
310 if (unlikely(frec_magic(r) != TDB_FREE_MAGIC)) {
311 tdb_unlock_free_bucket(tdb, nb_off);
315 if (remove_from_list(tdb, nb_off, r) == -1) {
316 tdb_unlock_free_bucket(tdb, nb_off);
320 end += sizeof(struct tdb_used_record) + r->data_len;
321 tdb_unlock_free_bucket(tdb, nb_off);
324 /* Didn't find any adjacent free? */
325 if (end == off + sizeof(struct tdb_used_record) + data_len)
328 /* OK, expand record */
329 r = tdb_get(tdb, off, &pad, sizeof(pad));
333 if (r->data_len != data_len) {
334 tdb->ecode = TDB_ERR_CORRUPT;
335 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
336 "coalesce: expected data len %llu not %llu\n",
337 (long long)data_len, (long long)r->data_len);
341 if (remove_from_list(tdb, b_off, r) == -1)
344 /* We have to drop this to avoid deadlocks. */
345 tdb_unlock_free_bucket(tdb, b_off);
347 if (add_free_record(tdb, zone_bits, off, end - off) == -1)
352 /* To unify error paths, we *always* unlock bucket on error. */
353 tdb_unlock_free_bucket(tdb, b_off);
357 /* We need size bytes to put our key and data in. */
358 static tdb_off_t lock_and_alloc(struct tdb_context *tdb,
365 tdb_off_t off, b_off,best_off;
366 struct tdb_free_record pad, best = { 0 }, *r;
370 b_off = bucket_off(zone_off, bucket);
372 /* Lock this bucket. */
373 if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) == -1) {
377 best.data_len = -1ULL;
379 /* FIXME: Start with larger multiplier if we're growing. */
382 /* Walk the list to see if any are large enough, getting less fussy
384 off = tdb_read_off(tdb, b_off);
385 if (unlikely(off == TDB_OFF_ERR))
389 /* FIXME: Does tdb_get win anything here? */
390 r = tdb_get(tdb, off, &pad, sizeof(*r));
394 if (frec_magic(r) != TDB_FREE_MAGIC) {
395 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
396 "lock_and_alloc: %llu non-free 0x%llx\n",
397 (long long)off, (long long)r->magic_and_meta);
401 if (r->data_len >= size && r->data_len < best.data_len) {
406 if (best.data_len < size * multiplier && best_off)
411 /* Since we're going slow anyway, try coalescing here. */
412 switch (coalesce(tdb, zone_off, zone_bits, off, b_off,
415 /* This has already unlocked on error. */
418 /* This has unlocked list, restart. */
424 /* If we found anything at all, use it. */
427 /* We're happy with this size: take it. */
428 if (remove_from_list(tdb, b_off, &best) != 0)
430 tdb_unlock_free_bucket(tdb, b_off);
432 if (to_used_record(tdb, zone_bits, best_off, size,
433 best.data_len, actual)) {
439 tdb_unlock_free_bucket(tdb, b_off);
443 tdb_unlock_free_bucket(tdb, b_off);
447 static bool next_zone(struct tdb_context *tdb)
449 tdb_off_t next = tdb->zone_off + (1ULL << tdb->zhdr.zone_bits);
451 /* We must have a header. */
452 if (tdb->methods->oob(tdb, next + sizeof(tdb->zhdr), true))
455 tdb->zone_off = next;
456 return tdb_read_convert(tdb, next, &tdb->zhdr, sizeof(tdb->zhdr)) == 0;
459 /* Offset returned is within current zone (which it may alter). */
460 static tdb_off_t get_free(struct tdb_context *tdb, size_t size,
463 tdb_off_t start_zone = tdb->zone_off, off;
464 bool wrapped = false;
466 while (!wrapped || tdb->zone_off != start_zone) {
469 /* Shortcut for really huge allocations... */
470 if ((size >> tdb->zhdr.zone_bits) != 0)
473 /* Start at exact size bucket, and search up... */
474 b = size_to_bucket(tdb->zhdr.zone_bits, size);
475 for (b = find_free_head(tdb, b);
476 b <= BUCKETS_FOR_ZONE(tdb->zhdr.zone_bits);
477 b += find_free_head(tdb, b + 1)) {
478 /* Try getting one from list. */
479 off = lock_and_alloc(tdb, tdb->zone_off,
482 if (off == TDB_OFF_ERR)
486 /* Didn't work. Try next bucket. */
489 /* Didn't work, try next zone, if it exists. */
490 if (!next_zone(tdb)) {
492 tdb->zone_off = sizeof(struct tdb_header);
493 if (tdb_read_convert(tdb, tdb->zone_off,
494 &tdb->zhdr, sizeof(tdb->zhdr))) {
502 int set_header(struct tdb_context *tdb,
503 struct tdb_used_record *rec,
504 uint64_t keylen, uint64_t datalen,
505 uint64_t actuallen, uint64_t hash,
506 unsigned int zone_bits)
508 uint64_t keybits = (fls64(keylen) + 1) / 2;
510 /* Use bottom bits of hash, so it's independent of hash table size. */
513 | ((hash & ((1 << 5)-1)) << 6)
514 | ((actuallen - (keylen + datalen)) << 11)
517 rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
519 /* Encoding can fail on big values. */
520 if (rec_key_length(rec) != keylen
521 || rec_data_length(rec) != datalen
522 || rec_extra_padding(rec) != actuallen - (keylen + datalen)) {
523 tdb->ecode = TDB_ERR_IO;
524 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
525 "Could not encode k=%llu,d=%llu,a=%llu\n",
526 (long long)keylen, (long long)datalen,
527 (long long)actuallen);
533 static bool zones_happy(struct tdb_context *tdb)
535 /* FIXME: look at distribution of zones. */
539 /* Assume we want buckets up to the comfort factor. */
540 static tdb_len_t overhead(unsigned int zone_bits)
542 return sizeof(struct free_zone_header)
543 + (BUCKETS_FOR_ZONE(zone_bits) + 1) * sizeof(tdb_off_t);
546 /* Expand the database (by adding a zone). */
547 static int tdb_expand(struct tdb_context *tdb, tdb_len_t size)
552 unsigned int num_buckets;
554 struct free_zone_header zhdr;
557 /* We need room for the record header too. */
558 wanted = sizeof(struct tdb_used_record) + size;
560 /* Only one person can expand file at a time. */
561 if (tdb_lock_expand(tdb, F_WRLCK) != 0)
564 /* Someone else may have expanded the file, so retry. */
565 old_size = tdb->map_size;
566 tdb->methods->oob(tdb, tdb->map_size + 1, true);
567 if (tdb->map_size != old_size)
570 /* zone bits tailer char is protected by EXPAND lock. */
571 if (tdb->methods->read(tdb, old_size - 1, &zone_bits, 1) == -1)
574 /* If zones aren't working well, add larger zone if possible. */
575 enlarge_zone = !zones_happy(tdb);
577 /* New zone can be between zone_bits or larger if we're on the right
580 /* Does this fit the allocation comfortably? */
581 if ((1ULL << zone_bits) >= overhead(zone_bits) + wanted) {
582 /* Only let enlarge_zone enlarge us once. */
585 enlarge_zone = false;
587 if ((old_size - 1 - sizeof(struct tdb_header))
593 zhdr.zone_bits = zone_bits;
594 num_buckets = BUCKETS_FOR_ZONE(zone_bits);
596 if (tdb->methods->expand_file(tdb, 1ULL << zone_bits) == -1)
599 /* Write new tailer. */
600 if (tdb->methods->write(tdb, tdb->map_size - 1, &zone_bits, 1) == -1)
603 /* Write new zone header (just before old tailer). */
605 if (tdb_write_convert(tdb, off, &zhdr, sizeof(zhdr)) == -1)
608 /* Now write empty buckets. */
610 if (zero_out(tdb, off, (num_buckets+1) * sizeof(tdb_off_t)) == -1)
612 off += (num_buckets+1) * sizeof(tdb_off_t);
614 /* Now add the rest as our free record. */
615 if (add_free_record(tdb, zone_bits, off, tdb->map_size-1-off) == -1)
618 /* Try allocating from this zone now. */
619 tdb->zone_off = old_size - 1;
623 tdb_unlock_expand(tdb, F_WRLCK);
627 tdb_unlock_expand(tdb, F_WRLCK);
631 static tdb_len_t adjust_size(size_t keylen, size_t datalen, bool growing)
633 tdb_len_t size = keylen + datalen;
635 if (size < MIN_DATA_LEN)
638 /* Overallocate if this is coming from an enlarging store. */
642 /* Round to next uint64_t boundary. */
643 return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
646 /* This won't fail: it will expand the database if it has to. */
647 tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
648 uint64_t hash, bool growing)
651 tdb_len_t size, actual;
652 struct tdb_used_record rec;
654 /* We can't hold pointers during this: we could unmap! */
655 assert(!tdb->direct_access);
657 size = adjust_size(keylen, datalen, growing);
660 off = get_free(tdb, size, &actual);
661 if (unlikely(off == TDB_OFF_ERR))
664 if (unlikely(off == 0)) {
665 if (tdb_expand(tdb, size) == -1)
670 /* Some supergiant values can't be encoded. */
671 /* FIXME: Check before, and limit actual in get_free. */
672 if (set_header(tdb, &rec, keylen, datalen, actual, hash,
673 tdb->zhdr.zone_bits) != 0) {
674 add_free_record(tdb, tdb->zhdr.zone_bits, off,
675 sizeof(rec) + actual);
679 if (tdb_write_convert(tdb, off, &rec, sizeof(rec)) != 0)