83ad7ff5d60ac81deb55d564f09296b28ee5812a
[ccan] / ccan / tdb2 / free.c
1  /*
2    Trivial Database 2: free list/block handling
3    Copyright (C) Rusty Russell 2010
4
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.
9
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.
14
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/>.
17 */
18 #include "private.h"
19 #include <ccan/likely/likely.h>
20 #include <ccan/ilog/ilog.h>
21 #include <time.h>
22 #include <assert.h>
23 #include <limits.h>
24
25 static unsigned fls64(uint64_t val)
26 {
27         return ilog64(val);
28 }
29
30 /* In which bucket would we find a particular record size? (ignoring header) */
31 unsigned int size_to_bucket(tdb_len_t data_len)
32 {
33         unsigned int bucket;
34
35         /* We can't have records smaller than this. */
36         assert(data_len >= TDB_MIN_DATA_LEN);
37
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;
42         } else {
43                 /* After that we go power of 2. */
44                 bucket = fls64(data_len - TDB_MIN_DATA_LEN) + 2;
45         }
46
47         if (unlikely(bucket >= TDB_FREE_BUCKETS))
48                 bucket = TDB_FREE_BUCKETS - 1;
49         return bucket;
50 }
51
52 tdb_off_t first_ftable(struct tdb_context *tdb)
53 {
54         return tdb_read_off(tdb, offsetof(struct tdb_header, free_table));
55 }
56
57 tdb_off_t next_ftable(struct tdb_context *tdb, tdb_off_t ftable)
58 {
59         return tdb_read_off(tdb, ftable + offsetof(struct tdb_freetable,next));
60 }
61
62 int tdb_ftable_init(struct tdb_context *tdb)
63 {
64         /* Use reservoir sampling algorithm to select a free list at random. */
65         unsigned int rnd, max = 0, count = 0;
66         tdb_off_t off;
67
68         tdb->ftable_off = off = first_ftable(tdb);
69         tdb->ftable = 0;
70
71         while (off) {
72                 if (off == TDB_OFF_ERR)
73                         return -1;
74
75                 rnd = random();
76                 if (rnd >= max) {
77                         tdb->ftable_off = off;
78                         tdb->ftable = count;
79                         max = rnd;
80                 }
81
82                 off = next_ftable(tdb, off);
83                 count++;
84         }
85         return 0;
86 }
87
88 /* Offset of a given bucket. */
89 tdb_off_t bucket_off(tdb_off_t ftable_off, unsigned bucket)
90 {
91         return ftable_off + offsetof(struct tdb_freetable, buckets)
92                 + bucket * sizeof(tdb_off_t);
93 }
94
95 /* Returns free_buckets + 1, or list number to search. */
96 static tdb_off_t find_free_head(struct tdb_context *tdb,
97                                 tdb_off_t ftable_off,
98                                 tdb_off_t bucket)
99 {
100         /* Speculatively search for a non-zero bucket. */
101         return tdb_find_nonzero_off(tdb, bucket_off(ftable_off, 0),
102                                     bucket, TDB_FREE_BUCKETS);
103 }
104
105 /* Remove from free bucket. */
106 static int remove_from_list(struct tdb_context *tdb,
107                             tdb_off_t b_off, tdb_off_t r_off,
108                             const struct tdb_free_record *r)
109 {
110         tdb_off_t off;
111
112         /* Front of list? */
113         if (frec_prev(r) == 0) {
114                 off = b_off;
115         } else {
116                 off = frec_prev(r) + offsetof(struct tdb_free_record, next);
117         }
118
119 #ifdef CCAN_TDB2_DEBUG
120         if (tdb_read_off(tdb, off) != r_off) {
121                 tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
122                          "remove_from_list: %llu bad prev in list %llu",
123                          (long long)r_off, (long long)b_off);
124                 return -1;
125         }
126 #endif
127
128         /* r->prev->next = r->next */
129         if (tdb_write_off(tdb, off, r->next)) {
130                 return -1;
131         }
132
133         if (r->next != 0) {
134                 off = r->next + offsetof(struct tdb_free_record,magic_and_prev);
135                 /* r->next->prev = r->prev */
136
137 #ifdef CCAN_TDB2_DEBUG
138                 if (tdb_read_off(tdb, off) & TDB_OFF_MASK != r_off) {
139                         tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
140                                    "remove_from_list: %llu bad list %llu",
141                                    (long long)r_off, (long long)b_off);
142                         return -1;
143                 }
144 #endif
145
146                 if (tdb_write_off(tdb, off, r->magic_and_prev)) {
147                         return -1;
148                 }
149         }
150         return 0;
151 }
152
153 /* Enqueue in this free bucket. */
154 static int enqueue_in_free(struct tdb_context *tdb,
155                            tdb_off_t b_off,
156                            tdb_off_t off,
157                            tdb_len_t len)
158 {
159         struct tdb_free_record new;
160         uint64_t magic = (TDB_FREE_MAGIC << (64 - TDB_OFF_UPPER_STEAL));
161
162         /* We only need to set ftable_and_len; rest is set in enqueue_in_free */
163         new.ftable_and_len = ((uint64_t)tdb->ftable << (64 - TDB_OFF_UPPER_STEAL))
164                 | len;
165         /* prev = 0. */
166         new.magic_and_prev = magic;
167
168         /* new->next = head. */
169         new.next = tdb_read_off(tdb, b_off);
170         if (new.next == TDB_OFF_ERR)
171                 return -1;
172
173         if (new.next) {
174 #ifdef CCAN_TDB2_DEBUG
175                 if (tdb_read_off(tdb,
176                                  new.next + offsetof(struct tdb_free_record,
177                                                      magic_and_prev))
178                     != magic) {
179                         tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
180                                    "enqueue_in_free: %llu bad head"
181                                    " prev %llu",
182                                    (long long)new.next, (long long)b_off);
183                         return -1;
184                 }
185 #endif
186                 /* next->prev = new. */
187                 if (tdb_write_off(tdb, new.next
188                                   + offsetof(struct tdb_free_record,
189                                              magic_and_prev),
190                                   off | magic) != 0)
191                         return -1;
192         }
193         /* head = new */
194         if (tdb_write_off(tdb, b_off, off) != 0)
195                 return -1;
196
197         return tdb_write_convert(tdb, off, &new, sizeof(new));
198 }
199
200 /* List need not be locked. */
201 int add_free_record(struct tdb_context *tdb,
202                     tdb_off_t off, tdb_len_t len_with_header)
203 {
204         tdb_off_t b_off;
205         tdb_len_t len;
206         int ret;
207         enum TDB_ERROR ecode;
208
209         assert(len_with_header >= sizeof(struct tdb_free_record));
210
211         len = len_with_header - sizeof(struct tdb_used_record);
212
213         b_off = bucket_off(tdb->ftable_off, size_to_bucket(len));
214         ecode = tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT);
215         if (ecode != TDB_SUCCESS) {
216                 tdb->ecode = ecode;
217                 return -1;
218         }
219
220         ret = enqueue_in_free(tdb, b_off, off, len);
221         tdb_unlock_free_bucket(tdb, b_off);
222         return ret;
223 }
224
225 static size_t adjust_size(size_t keylen, size_t datalen)
226 {
227         size_t size = keylen + datalen;
228
229         if (size < TDB_MIN_DATA_LEN)
230                 size = TDB_MIN_DATA_LEN;
231
232         /* Round to next uint64_t boundary. */
233         return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
234 }
235
236 /* If we have enough left over to be useful, split that off. */
237 static size_t record_leftover(size_t keylen, size_t datalen,
238                               bool want_extra, size_t total_len)
239 {
240         ssize_t leftover;
241
242         if (want_extra)
243                 datalen += datalen / 2;
244         leftover = total_len - adjust_size(keylen, datalen);
245
246         if (leftover < (ssize_t)sizeof(struct tdb_free_record))
247                 return 0;
248
249         return leftover;
250 }
251
252 static tdb_off_t ftable_offset(struct tdb_context *tdb, unsigned int ftable)
253 {
254         tdb_off_t off;
255         unsigned int i;
256
257         if (likely(tdb->ftable == ftable))
258                 return tdb->ftable_off;
259
260         off = first_ftable(tdb);
261         for (i = 0; i < ftable; i++)
262                 off = next_ftable(tdb, off);
263         return off;
264 }
265
266 /* Note: we unlock the current bucket if we coalesce or fail. */
267 static int coalesce(struct tdb_context *tdb,
268                     tdb_off_t off, tdb_off_t b_off, tdb_len_t data_len)
269 {
270         tdb_off_t end;
271         struct tdb_free_record rec;
272
273         add_stat(tdb, alloc_coalesce_tried, 1);
274         end = off + sizeof(struct tdb_used_record) + data_len;
275
276         while (end < tdb->map_size) {
277                 const struct tdb_free_record *r;
278                 tdb_off_t nb_off;
279                 unsigned ftable, bucket;
280
281                 r = tdb_access_read(tdb, end, sizeof(*r), true);
282                 if (!r)
283                         goto err;
284
285                 if (frec_magic(r) != TDB_FREE_MAGIC
286                     || frec_ftable(r) == TDB_FTABLE_NONE) {
287                         tdb_access_release(tdb, r);
288                         break;
289                 }
290
291                 ftable = frec_ftable(r);
292                 bucket = size_to_bucket(frec_len(r));
293                 nb_off = bucket_off(ftable_offset(tdb, ftable), bucket);
294                 tdb_access_release(tdb, r);
295
296                 /* We may be violating lock order here, so best effort. */
297                 if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT)
298                     != TDB_SUCCESS) {
299                         add_stat(tdb, alloc_coalesce_lockfail, 1);
300                         break;
301                 }
302
303                 /* Now we have lock, re-check. */
304                 if (tdb_read_convert(tdb, end, &rec, sizeof(rec))) {
305                         tdb_unlock_free_bucket(tdb, nb_off);
306                         goto err;
307                 }
308
309                 if (unlikely(frec_magic(&rec) != TDB_FREE_MAGIC)) {
310                         add_stat(tdb, alloc_coalesce_race, 1);
311                         tdb_unlock_free_bucket(tdb, nb_off);
312                         break;
313                 }
314
315                 if (unlikely(frec_ftable(&rec) != ftable)
316                     || unlikely(size_to_bucket(frec_len(&rec)) != bucket)) {
317                         add_stat(tdb, alloc_coalesce_race, 1);
318                         tdb_unlock_free_bucket(tdb, nb_off);
319                         break;
320                 }
321
322                 if (remove_from_list(tdb, nb_off, end, &rec) == -1) {
323                         tdb_unlock_free_bucket(tdb, nb_off);
324                         goto err;
325                 }
326
327                 end += sizeof(struct tdb_used_record) + frec_len(&rec);
328                 tdb_unlock_free_bucket(tdb, nb_off);
329                 add_stat(tdb, alloc_coalesce_num_merged, 1);
330         }
331
332         /* Didn't find any adjacent free? */
333         if (end == off + sizeof(struct tdb_used_record) + data_len)
334                 return 0;
335
336         /* OK, expand initial record */
337         if (tdb_read_convert(tdb, off, &rec, sizeof(rec)))
338                 goto err;
339
340         if (frec_len(&rec) != data_len) {
341                 tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
342                            "coalesce: expected data len %zu not %zu",
343                            (size_t)data_len, (size_t)frec_len(&rec));
344                 goto err;
345         }
346
347         if (remove_from_list(tdb, b_off, off, &rec) == -1)
348                 goto err;
349
350         /* We have to drop this to avoid deadlocks, so make sure record
351          * doesn't get coalesced by someone else! */
352         rec.ftable_and_len = (TDB_FTABLE_NONE << (64 - TDB_OFF_UPPER_STEAL))
353                 | (end - off - sizeof(struct tdb_used_record));
354         if (tdb_write_off(tdb, off + offsetof(struct tdb_free_record,
355                                               ftable_and_len),
356                           rec.ftable_and_len) != 0)
357                 goto err;
358
359         add_stat(tdb, alloc_coalesce_succeeded, 1);
360         tdb_unlock_free_bucket(tdb, b_off);
361
362         if (add_free_record(tdb, off, end - off) == -1)
363                 return -1;
364         return 1;
365
366 err:
367         /* To unify error paths, we *always* unlock bucket on error. */
368         tdb_unlock_free_bucket(tdb, b_off);
369         return -1;
370 }
371
372 /* We need size bytes to put our key and data in. */
373 static tdb_off_t lock_and_alloc(struct tdb_context *tdb,
374                                 tdb_off_t ftable_off,
375                                 tdb_off_t bucket,
376                                 size_t keylen, size_t datalen,
377                                 bool want_extra,
378                                 unsigned magic,
379                                 unsigned hashlow)
380 {
381         tdb_off_t off, b_off,best_off;
382         struct tdb_free_record best = { 0 };
383         double multiplier;
384         size_t size = adjust_size(keylen, datalen);
385         enum TDB_ERROR ecode;
386
387         add_stat(tdb, allocs, 1);
388 again:
389         b_off = bucket_off(ftable_off, bucket);
390
391         /* FIXME: Try non-blocking wait first, to measure contention. */
392         /* Lock this bucket. */
393         ecode = tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT);
394         if (ecode != TDB_SUCCESS) {
395                 tdb->ecode = ecode;
396                 return TDB_OFF_ERR;
397         }
398
399         best.ftable_and_len = -1ULL;
400         best_off = 0;
401
402         /* Get slack if we're after extra. */
403         if (want_extra)
404                 multiplier = 1.5;
405         else
406                 multiplier = 1.0;
407
408         /* Walk the list to see if any are large enough, getting less fussy
409          * as we go. */
410         off = tdb_read_off(tdb, b_off);
411         if (unlikely(off == TDB_OFF_ERR))
412                 goto unlock_err;
413
414         while (off) {
415                 const struct tdb_free_record *r;
416                 tdb_len_t len;
417                 tdb_off_t next;
418
419                 r = tdb_access_read(tdb, off, sizeof(*r), true);
420                 if (!r)
421                         goto unlock_err;
422
423                 if (frec_magic(r) != TDB_FREE_MAGIC) {
424                         tdb_access_release(tdb, r);
425                         tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_LOG_ERROR,
426                                  "lock_and_alloc: %llu non-free 0x%llx",
427                                  (long long)off, (long long)r->magic_and_prev);
428                         goto unlock_err;
429                 }
430
431                 if (frec_len(r) >= size && frec_len(r) < frec_len(&best)) {
432                         best_off = off;
433                         best = *r;
434                 }
435
436                 if (frec_len(&best) < size * multiplier && best_off) {
437                         tdb_access_release(tdb, r);
438                         break;
439                 }
440
441                 multiplier *= 1.01;
442
443                 next = r->next;
444                 len = frec_len(r);
445                 tdb_access_release(tdb, r);
446
447                 /* Since we're going slow anyway, try coalescing here. */
448                 switch (coalesce(tdb, off, b_off, len)) {
449                 case -1:
450                         /* This has already unlocked on error. */
451                         return -1;
452                 case 1:
453                         /* This has unlocked list, restart. */
454                         goto again;
455                 }
456                 off = next;
457         }
458
459         /* If we found anything at all, use it. */
460         if (best_off) {
461                 struct tdb_used_record rec;
462                 size_t leftover;
463
464                 /* We're happy with this size: take it. */
465                 if (remove_from_list(tdb, b_off, best_off, &best) != 0)
466                         goto unlock_err;
467
468                 leftover = record_leftover(keylen, datalen, want_extra,
469                                            frec_len(&best));
470
471                 assert(keylen + datalen + leftover <= frec_len(&best));
472                 /* We need to mark non-free before we drop lock, otherwise
473                  * coalesce() could try to merge it! */
474                 if (set_header(tdb, &rec, magic, keylen, datalen,
475                                frec_len(&best) - leftover, hashlow) != 0)
476                         goto unlock_err;
477
478                 if (tdb_write_convert(tdb, best_off, &rec, sizeof(rec)) != 0)
479                         goto unlock_err;
480
481                 /* Bucket of leftover will be <= current bucket, so nested
482                  * locking is allowed. */
483                 if (leftover) {
484                         add_stat(tdb, alloc_leftover, 1);
485                         if (add_free_record(tdb,
486                                             best_off + sizeof(rec)
487                                             + frec_len(&best) - leftover,
488                                             leftover))
489                                 best_off = TDB_OFF_ERR;
490                 }
491                 tdb_unlock_free_bucket(tdb, b_off);
492
493                 return best_off;
494         }
495
496         tdb_unlock_free_bucket(tdb, b_off);
497         return 0;
498
499 unlock_err:
500         tdb_unlock_free_bucket(tdb, b_off);
501         return TDB_OFF_ERR;
502 }
503
504 /* Get a free block from current free list, or 0 if none. */
505 static tdb_off_t get_free(struct tdb_context *tdb,
506                           size_t keylen, size_t datalen, bool want_extra,
507                           unsigned magic, unsigned hashlow)
508 {
509         tdb_off_t off, ftable_off;
510         unsigned start_b, b, ftable;
511         bool wrapped = false;
512
513         /* If they are growing, add 50% to get to higher bucket. */
514         if (want_extra)
515                 start_b = size_to_bucket(adjust_size(keylen,
516                                                      datalen + datalen / 2));
517         else
518                 start_b = size_to_bucket(adjust_size(keylen, datalen));
519
520         ftable_off = tdb->ftable_off;
521         ftable = tdb->ftable;
522         while (!wrapped || ftable_off != tdb->ftable_off) {
523                 /* Start at exact size bucket, and search up... */
524                 for (b = find_free_head(tdb, ftable_off, start_b);
525                      b < TDB_FREE_BUCKETS;
526                      b = find_free_head(tdb, ftable_off, b + 1)) {
527                         /* Try getting one from list. */
528                         off = lock_and_alloc(tdb, ftable_off,
529                                              b, keylen, datalen, want_extra,
530                                              magic, hashlow);
531                         if (off == TDB_OFF_ERR)
532                                 return TDB_OFF_ERR;
533                         if (off != 0) {
534                                 if (b == start_b)
535                                         add_stat(tdb, alloc_bucket_exact, 1);
536                                 if (b == TDB_FREE_BUCKETS - 1)
537                                         add_stat(tdb, alloc_bucket_max, 1);
538                                 /* Worked?  Stay using this list. */
539                                 tdb->ftable_off = ftable_off;
540                                 tdb->ftable = ftable;
541                                 return off;
542                         }
543                         /* Didn't work.  Try next bucket. */
544                 }
545
546                 /* Hmm, try next table. */
547                 ftable_off = next_ftable(tdb, ftable_off);
548                 ftable++;
549
550                 if (ftable_off == 0) {
551                         wrapped = true;
552                         ftable_off = first_ftable(tdb);
553                         ftable = 0;
554                 }
555         }
556
557         return 0;
558 }
559
560 int set_header(struct tdb_context *tdb,
561                struct tdb_used_record *rec,
562                unsigned magic, uint64_t keylen, uint64_t datalen,
563                uint64_t actuallen, unsigned hashlow)
564 {
565         uint64_t keybits = (fls64(keylen) + 1) / 2;
566
567         /* Use bottom bits of hash, so it's independent of hash table size. */
568         rec->magic_and_meta = (hashlow & ((1 << 11)-1))
569                 | ((actuallen - (keylen + datalen)) << 11)
570                 | (keybits << 43)
571                 | ((uint64_t)magic << 48);
572         rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
573
574         /* Encoding can fail on big values. */
575         if (rec_key_length(rec) != keylen
576             || rec_data_length(rec) != datalen
577             || rec_extra_padding(rec) != actuallen - (keylen + datalen)) {
578                 tdb_logerr(tdb, TDB_ERR_IO, TDB_LOG_ERROR,
579                          "Could not encode k=%llu,d=%llu,a=%llu",
580                          (long long)keylen, (long long)datalen,
581                          (long long)actuallen);
582                 return -1;
583         }
584         return 0;
585 }
586
587 /* Expand the database. */
588 static int tdb_expand(struct tdb_context *tdb, tdb_len_t size)
589 {
590         uint64_t old_size;
591         tdb_len_t wanted;
592         enum TDB_ERROR ecode;
593
594         /* We need room for the record header too. */
595         wanted = sizeof(struct tdb_used_record) + size;
596
597         /* Need to hold a hash lock to expand DB: transactions rely on it. */
598         if (!(tdb->flags & TDB_NOLOCK)
599             && !tdb->allrecord_lock.count && !tdb_has_hash_locks(tdb)) {
600                 tdb_logerr(tdb, TDB_ERR_LOCK, TDB_LOG_ERROR,
601                            "tdb_expand: must hold lock during expand");
602                 return -1;
603         }
604
605         /* always make room for at least 100 more records, and at
606            least 25% more space. */
607         if (size * TDB_EXTENSION_FACTOR > tdb->map_size / 4)
608                 wanted = size * TDB_EXTENSION_FACTOR;
609         else
610                 wanted = tdb->map_size / 4;
611         wanted = adjust_size(0, wanted);
612
613         /* Only one person can expand file at a time. */
614         ecode = tdb_lock_expand(tdb, F_WRLCK);
615         if (ecode != TDB_SUCCESS) {
616                 tdb->ecode = ecode;
617                 return -1;
618         }
619
620         /* Someone else may have expanded the file, so retry. */
621         old_size = tdb->map_size;
622         tdb->methods->oob(tdb, tdb->map_size + 1, true);
623         if (tdb->map_size != old_size) {
624                 tdb_unlock_expand(tdb, F_WRLCK);
625                 return 0;
626         }
627
628         ecode = tdb->methods->expand_file(tdb, wanted);
629         if (ecode != TDB_SUCCESS) {
630                 tdb->ecode = ecode;
631                 tdb_unlock_expand(tdb, F_WRLCK);
632                 return -1;
633         }
634
635         /* We need to drop this lock before adding free record. */
636         tdb_unlock_expand(tdb, F_WRLCK);
637
638         add_stat(tdb, expands, 1);
639         return add_free_record(tdb, old_size, wanted);
640 }
641
642 /* This won't fail: it will expand the database if it has to. */
643 tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
644                 uint64_t hash, unsigned magic, bool growing)
645 {
646         tdb_off_t off;
647
648         /* We can't hold pointers during this: we could unmap! */
649         assert(!tdb->direct_access);
650
651         for (;;) {
652                 off = get_free(tdb, keylen, datalen, growing, magic, hash);
653                 if (likely(off != 0))
654                         break;
655
656                 if (tdb_expand(tdb, adjust_size(keylen, datalen)))
657                         return TDB_OFF_ERR;
658         }
659
660         return off;
661 }