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(unsigned int zone_bits, 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 > BUCKETS_FOR_ZONE(zone_bits)))
48 bucket = BUCKETS_FOR_ZONE(zone_bits);
52 /* Subtract 1-byte tailer and header. Then round up to next power of 2. */
53 static unsigned max_zone_bits(struct tdb_context *tdb)
55 return fls64(tdb->map_size-1-sizeof(struct tdb_header)-1) + 1;
58 /* Start by using a random zone to spread the load: returns the offset. */
59 static uint64_t random_zone(struct tdb_context *tdb)
61 struct free_zone_header zhdr;
62 tdb_off_t off = sizeof(struct tdb_header);
64 uint64_t randbits = 0;
67 for (i = 0; i < 64; i += fls64(RAND_MAX))
68 randbits ^= ((uint64_t)random()) << i;
70 /* FIXME: Does this work? Test! */
71 half_bits = max_zone_bits(tdb) - 1;
73 /* Pick left or right side (not outside file) */
75 && !tdb->methods->oob(tdb, off + (1ULL << half_bits)
76 + sizeof(zhdr), true)) {
77 off += 1ULL << half_bits;
81 if (tdb_read_convert(tdb, off, &zhdr, sizeof(zhdr)) == -1)
84 if (zhdr.zone_bits == half_bits)
88 } while (half_bits >= INITIAL_ZONE_BITS);
90 tdb->ecode = TDB_ERR_CORRUPT;
91 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
92 "random_zone: zone at %llu smaller than %u bits?",
93 (long long)off, INITIAL_ZONE_BITS);
97 int tdb_zone_init(struct tdb_context *tdb)
99 tdb->zone_off = random_zone(tdb);
100 if (tdb->zone_off == TDB_OFF_ERR)
102 if (tdb_read_convert(tdb, tdb->zone_off,
103 &tdb->zhdr, sizeof(tdb->zhdr)) == -1)
108 /* Where's the header, given a zone size of 1 << zone_bits? */
109 static tdb_off_t zone_off(tdb_off_t off, unsigned int zone_bits)
111 off -= sizeof(struct tdb_header);
112 return (off & ~((1ULL << zone_bits) - 1)) + sizeof(struct tdb_header);
115 /* Offset of a given bucket. */
116 /* FIXME: bucket can be "unsigned" everywhere, or even uint8/16. */
117 tdb_off_t bucket_off(tdb_off_t zone_off, tdb_off_t bucket)
120 + sizeof(struct free_zone_header)
121 + bucket * sizeof(tdb_off_t);
124 /* Returns free_buckets + 1, or list number to search. */
125 static tdb_off_t find_free_head(struct tdb_context *tdb, tdb_off_t bucket)
127 /* Speculatively search for a non-zero bucket. */
128 return tdb_find_nonzero_off(tdb, bucket_off(tdb->zone_off, 0),
130 BUCKETS_FOR_ZONE(tdb->zhdr.zone_bits) + 1);
133 /* Remove from free bucket. */
134 static int remove_from_list(struct tdb_context *tdb,
135 tdb_off_t b_off, struct tdb_free_record *r)
143 off = r->prev + offsetof(struct tdb_free_record, next);
145 /* r->prev->next = r->next */
146 if (tdb_write_off(tdb, off, r->next)) {
151 off = r->next + offsetof(struct tdb_free_record, prev);
152 /* r->next->prev = r->prev */
153 if (tdb_write_off(tdb, off, r->prev)) {
160 /* Enqueue in this free bucket. */
161 static int enqueue_in_free(struct tdb_context *tdb,
164 struct tdb_free_record *new)
167 /* new->next = head. */
168 new->next = tdb_read_off(tdb, b_off);
169 if (new->next == TDB_OFF_ERR)
173 /* next->prev = new. */
174 if (tdb_write_off(tdb, new->next
175 + offsetof(struct tdb_free_record, prev),
180 if (tdb_write_off(tdb, b_off, off) != 0)
183 return tdb_write_convert(tdb, off, new, sizeof(*new));
186 /* List need not be locked. */
187 int add_free_record(struct tdb_context *tdb,
188 unsigned int zone_bits,
189 tdb_off_t off, tdb_len_t len_with_header)
191 struct tdb_free_record new;
195 assert(len_with_header >= sizeof(new));
196 assert(zone_bits < (1 << 6));
198 new.magic_and_meta = TDB_FREE_MAGIC | zone_bits;
199 new.data_len = len_with_header - sizeof(struct tdb_used_record);
201 b_off = bucket_off(zone_off(off, zone_bits),
202 size_to_bucket(zone_bits, new.data_len));
203 if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) != 0)
206 ret = enqueue_in_free(tdb, b_off, off, &new);
207 tdb_unlock_free_bucket(tdb, b_off);
211 /* If we have enough left over to be useful, split that off. */
212 static int to_used_record(struct tdb_context *tdb,
213 unsigned int zone_bits,
219 struct tdb_used_record used;
222 leftover = total_len - needed;
223 if (leftover < sizeof(struct tdb_free_record))
226 *actual = total_len - leftover;
229 if (add_free_record(tdb, zone_bits,
230 off + sizeof(used) + *actual,
237 /* Note: we unlock the current bucket if we coalesce or fail. */
238 static int coalesce(struct tdb_context *tdb,
239 tdb_off_t zone_off, unsigned zone_bits,
240 tdb_off_t off, tdb_off_t b_off, tdb_len_t data_len)
242 struct tdb_free_record pad, *r;
243 tdb_off_t end = off + sizeof(struct tdb_used_record) + data_len;
245 while (end < (zone_off + (1ULL << zone_bits))) {
248 /* FIXME: do tdb_get here and below really win? */
249 r = tdb_get(tdb, end, &pad, sizeof(pad));
253 if (frec_magic(r) != TDB_FREE_MAGIC)
256 nb_off = bucket_off(zone_off,
257 size_to_bucket(zone_bits, r->data_len));
259 /* We may be violating lock order here, so best effort. */
260 if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT) == -1)
263 /* Now we have lock, re-check. */
264 r = tdb_get(tdb, end, &pad, sizeof(pad));
266 tdb_unlock_free_bucket(tdb, nb_off);
270 if (unlikely(frec_magic(r) != TDB_FREE_MAGIC)) {
271 tdb_unlock_free_bucket(tdb, nb_off);
275 if (remove_from_list(tdb, nb_off, r) == -1) {
276 tdb_unlock_free_bucket(tdb, nb_off);
280 end += sizeof(struct tdb_used_record) + r->data_len;
281 tdb_unlock_free_bucket(tdb, nb_off);
284 /* Didn't find any adjacent free? */
285 if (end == off + sizeof(struct tdb_used_record) + data_len)
288 /* OK, expand record */
289 r = tdb_get(tdb, off, &pad, sizeof(pad));
293 if (r->data_len != data_len) {
294 tdb->ecode = TDB_ERR_CORRUPT;
295 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
296 "coalesce: expected data len %llu not %llu\n",
297 (long long)data_len, (long long)r->data_len);
301 if (remove_from_list(tdb, b_off, r) == -1)
304 /* We have to drop this to avoid deadlocks. */
305 tdb_unlock_free_bucket(tdb, b_off);
307 if (add_free_record(tdb, zone_bits, off, end - off) == -1)
312 /* To unify error paths, we *always* unlock bucket on error. */
313 tdb_unlock_free_bucket(tdb, b_off);
317 /* We need size bytes to put our key and data in. */
318 static tdb_off_t lock_and_alloc(struct tdb_context *tdb,
325 tdb_off_t off, b_off,best_off;
326 struct tdb_free_record pad, best = { 0 }, *r;
330 b_off = bucket_off(zone_off, bucket);
332 /* FIXME: Try non-blocking wait first, to measure contention.
333 * If we're contented, try switching zones, and don't enlarge zone
334 * next time (we want more zones). */
335 /* Lock this bucket. */
336 if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) == -1) {
340 best.data_len = -1ULL;
342 /* FIXME: Start with larger multiplier if we're growing. */
345 /* Walk the list to see if any are large enough, getting less fussy
347 off = tdb_read_off(tdb, b_off);
348 if (unlikely(off == TDB_OFF_ERR))
352 /* FIXME: Does tdb_get win anything here? */
353 r = tdb_get(tdb, off, &pad, sizeof(*r));
357 if (frec_magic(r) != TDB_FREE_MAGIC) {
358 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
359 "lock_and_alloc: %llu non-free 0x%llx\n",
360 (long long)off, (long long)r->magic_and_meta);
364 if (r->data_len >= size && r->data_len < best.data_len) {
369 if (best.data_len < size * multiplier && best_off)
374 /* Since we're going slow anyway, try coalescing here. */
375 switch (coalesce(tdb, zone_off, zone_bits, off, b_off,
378 /* This has already unlocked on error. */
381 /* This has unlocked list, restart. */
387 /* If we found anything at all, use it. */
390 /* We're happy with this size: take it. */
391 if (remove_from_list(tdb, b_off, &best) != 0)
393 tdb_unlock_free_bucket(tdb, b_off);
395 if (to_used_record(tdb, zone_bits, best_off, size,
396 best.data_len, actual)) {
402 tdb_unlock_free_bucket(tdb, b_off);
406 tdb_unlock_free_bucket(tdb, b_off);
410 static bool next_zone(struct tdb_context *tdb)
412 tdb_off_t next = tdb->zone_off + (1ULL << tdb->zhdr.zone_bits);
414 /* We must have a header. */
415 if (tdb->methods->oob(tdb, next + sizeof(tdb->zhdr), true))
418 tdb->zone_off = next;
419 return tdb_read_convert(tdb, next, &tdb->zhdr, sizeof(tdb->zhdr)) == 0;
422 /* Offset returned is within current zone (which it may alter). */
423 static tdb_off_t get_free(struct tdb_context *tdb, size_t size,
426 tdb_off_t start_zone = tdb->zone_off, off;
427 bool wrapped = false;
429 /* FIXME: If we don't get a hit in the first bucket we want,
430 * try changing zones for next time. That should help wear
431 * zones evenly, so we don't need to search all of them before
433 while (!wrapped || tdb->zone_off != start_zone) {
436 /* Shortcut for really huge allocations... */
437 if ((size >> tdb->zhdr.zone_bits) != 0)
440 /* Start at exact size bucket, and search up... */
441 b = size_to_bucket(tdb->zhdr.zone_bits, size);
442 for (b = find_free_head(tdb, b);
443 b <= BUCKETS_FOR_ZONE(tdb->zhdr.zone_bits);
444 b += find_free_head(tdb, b + 1)) {
445 /* Try getting one from list. */
446 off = lock_and_alloc(tdb, tdb->zone_off,
449 if (off == TDB_OFF_ERR)
453 /* Didn't work. Try next bucket. */
456 /* Didn't work, try next zone, if it exists. */
457 if (!next_zone(tdb)) {
459 tdb->zone_off = sizeof(struct tdb_header);
460 if (tdb_read_convert(tdb, tdb->zone_off,
461 &tdb->zhdr, sizeof(tdb->zhdr))) {
469 int set_header(struct tdb_context *tdb,
470 struct tdb_used_record *rec,
471 uint64_t keylen, uint64_t datalen,
472 uint64_t actuallen, uint64_t hash,
473 unsigned int zone_bits)
475 uint64_t keybits = (fls64(keylen) + 1) / 2;
477 /* Use bottom bits of hash, so it's independent of hash table size. */
480 | ((hash & ((1 << 5)-1)) << 6)
481 | ((actuallen - (keylen + datalen)) << 11)
484 rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
486 /* Encoding can fail on big values. */
487 if (rec_key_length(rec) != keylen
488 || rec_data_length(rec) != datalen
489 || rec_extra_padding(rec) != actuallen - (keylen + datalen)) {
490 tdb->ecode = TDB_ERR_IO;
491 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
492 "Could not encode k=%llu,d=%llu,a=%llu\n",
493 (long long)keylen, (long long)datalen,
494 (long long)actuallen);
500 static bool zones_happy(struct tdb_context *tdb)
502 /* FIXME: look at distribution of zones. */
506 /* Assume we want buckets up to the comfort factor. */
507 static tdb_len_t overhead(unsigned int zone_bits)
509 return sizeof(struct free_zone_header)
510 + (BUCKETS_FOR_ZONE(zone_bits) + 1) * sizeof(tdb_off_t);
513 /* Expand the database (by adding a zone). */
514 static int tdb_expand(struct tdb_context *tdb, tdb_len_t size)
519 unsigned int num_buckets;
521 struct free_zone_header zhdr;
524 /* We need room for the record header too. */
525 wanted = sizeof(struct tdb_used_record) + size;
527 /* Only one person can expand file at a time. */
528 if (tdb_lock_expand(tdb, F_WRLCK) != 0)
531 /* Someone else may have expanded the file, so retry. */
532 old_size = tdb->map_size;
533 tdb->methods->oob(tdb, tdb->map_size + 1, true);
534 if (tdb->map_size != old_size)
537 /* FIXME: Tailer is a bogus optimization, remove it. */
538 /* zone bits tailer char is protected by EXPAND lock. */
539 if (tdb->methods->read(tdb, old_size - 1, &zone_bits, 1) == -1)
542 /* If zones aren't working well, add larger zone if possible. */
543 enlarge_zone = !zones_happy(tdb);
545 /* New zone can be between zone_bits or larger if we're on the right
548 /* Does this fit the allocation comfortably? */
549 if ((1ULL << zone_bits) >= overhead(zone_bits) + wanted) {
550 /* Only let enlarge_zone enlarge us once. */
553 enlarge_zone = false;
555 if ((old_size - 1 - sizeof(struct tdb_header))
561 zhdr.zone_bits = zone_bits;
562 num_buckets = BUCKETS_FOR_ZONE(zone_bits);
564 /* FIXME: I don't think we need to expand to full zone, do we? */
565 if (tdb->methods->expand_file(tdb, 1ULL << zone_bits) == -1)
568 /* Write new tailer. */
569 if (tdb->methods->write(tdb, tdb->map_size - 1, &zone_bits, 1) == -1)
572 /* Write new zone header (just before old tailer). */
574 if (tdb_write_convert(tdb, off, &zhdr, sizeof(zhdr)) == -1)
577 /* Now write empty buckets. */
579 if (zero_out(tdb, off, (num_buckets+1) * sizeof(tdb_off_t)) == -1)
581 off += (num_buckets+1) * sizeof(tdb_off_t);
583 /* Now add the rest as our free record. */
584 if (add_free_record(tdb, zone_bits, off, tdb->map_size-1-off) == -1)
587 /* Try allocating from this zone now. */
588 tdb->zone_off = old_size - 1;
592 tdb_unlock_expand(tdb, F_WRLCK);
596 tdb_unlock_expand(tdb, F_WRLCK);
600 static tdb_len_t adjust_size(size_t keylen, size_t datalen, bool growing)
602 tdb_len_t size = keylen + datalen;
604 if (size < TDB_MIN_DATA_LEN)
605 size = TDB_MIN_DATA_LEN;
607 /* Overallocate if this is coming from an enlarging store. */
611 /* Round to next uint64_t boundary. */
612 return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
615 /* This won't fail: it will expand the database if it has to. */
616 tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
617 uint64_t hash, bool growing)
620 tdb_len_t size, actual;
621 struct tdb_used_record rec;
623 /* We can't hold pointers during this: we could unmap! */
624 assert(!tdb->direct_access);
626 size = adjust_size(keylen, datalen, growing);
629 off = get_free(tdb, size, &actual);
630 if (unlikely(off == TDB_OFF_ERR))
633 if (unlikely(off == 0)) {
634 if (tdb_expand(tdb, size) == -1)
639 /* Some supergiant values can't be encoded. */
640 /* FIXME: Check before, and limit actual in get_free. */
641 if (set_header(tdb, &rec, keylen, datalen, actual, hash,
642 tdb->zhdr.zone_bits) != 0) {
643 add_free_record(tdb, tdb->zhdr.zone_bits, off,
644 sizeof(rec) + actual);
648 if (tdb_write_convert(tdb, off, &rec, sizeof(rec)) != 0)