49880f18dd51517601eca798d163e5e98b10b514
[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_flist(struct tdb_context *tdb)
53 {
54         return tdb_read_off(tdb, offsetof(struct tdb_header, free_list));
55 }
56
57 tdb_off_t next_flist(struct tdb_context *tdb, tdb_off_t flist)
58 {
59         return tdb_read_off(tdb, flist + offsetof(struct tdb_freelist, next));
60 }
61
62 int tdb_flist_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->flist_off = off = first_flist(tdb);
69         tdb->flist = 0;
70
71         while (off) {
72                 if (off == TDB_OFF_ERR)
73                         return -1;
74
75                 rnd = random();
76                 if (rnd >= max) {
77                         tdb->flist_off = off;
78                         tdb->flist = count;
79                         max = rnd;
80                 }
81
82                 off = next_flist(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 flist_off, unsigned bucket)
90 {
91         return flist_off + offsetof(struct tdb_freelist, 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 flist_off,
98                                 tdb_off_t bucket)
99 {
100         /* Speculatively search for a non-zero bucket. */
101         return tdb_find_nonzero_off(tdb, bucket_off(flist_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 DEBUG
120         if (tdb_read_off(tdb, off) != r_off) {
121                 tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_DEBUG_FATAL,
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 DEBUG
138                 if (tdb_read_off(tdb, off) & TDB_OFF_MASK != r_off) {
139                         tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_DEBUG_FATAL,
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 flist_and_len; rest is set in enqueue_in_free */
163         new.flist_and_len = ((uint64_t)tdb->flist << (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 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_DEBUG_FATAL,
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
208         assert(len_with_header >= sizeof(struct tdb_free_record));
209
210         len = len_with_header - sizeof(struct tdb_used_record);
211
212         b_off = bucket_off(tdb->flist_off, size_to_bucket(len));
213         if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) != 0)
214                 return -1;
215
216         ret = enqueue_in_free(tdb, b_off, off, len);
217         tdb_unlock_free_bucket(tdb, b_off);
218         return ret;
219 }
220
221 static size_t adjust_size(size_t keylen, size_t datalen)
222 {
223         size_t size = keylen + datalen;
224
225         if (size < TDB_MIN_DATA_LEN)
226                 size = TDB_MIN_DATA_LEN;
227
228         /* Round to next uint64_t boundary. */
229         return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
230 }
231
232 /* If we have enough left over to be useful, split that off. */
233 static size_t record_leftover(size_t keylen, size_t datalen,
234                               bool want_extra, size_t total_len)
235 {
236         ssize_t leftover;
237
238         if (want_extra)
239                 datalen += datalen / 2;
240         leftover = total_len - adjust_size(keylen, datalen);
241
242         if (leftover < (ssize_t)sizeof(struct tdb_free_record))
243                 return 0;
244
245         return leftover;
246 }
247
248 static tdb_off_t flist_offset(struct tdb_context *tdb, unsigned int flist)
249 {
250         tdb_off_t off;
251         unsigned int i;
252
253         if (likely(tdb->flist == flist))
254                 return tdb->flist_off;
255
256         off = first_flist(tdb);
257         for (i = 0; i < flist; i++)
258                 off = next_flist(tdb, off);
259         return off;
260 }
261
262 /* Note: we unlock the current bucket if we coalesce or fail. */
263 static int coalesce(struct tdb_context *tdb,
264                     tdb_off_t off, tdb_off_t b_off, tdb_len_t data_len)
265 {
266         tdb_off_t end;
267         struct tdb_free_record rec;
268
269         add_stat(tdb, alloc_coalesce_tried, 1);
270         end = off + sizeof(struct tdb_used_record) + data_len;
271
272         while (end < tdb->map_size) {
273                 const struct tdb_free_record *r;
274                 tdb_off_t nb_off;
275                 unsigned flist, bucket;
276
277                 r = tdb_access_read(tdb, end, sizeof(*r), true);
278                 if (!r)
279                         goto err;
280
281                 if (frec_magic(r) != TDB_FREE_MAGIC) {
282                         tdb_access_release(tdb, r);
283                         break;
284                 }
285
286                 flist = frec_flist(r);
287                 bucket = size_to_bucket(frec_len(r));
288                 nb_off = bucket_off(flist_offset(tdb, flist), bucket);
289                 tdb_access_release(tdb, r);
290
291                 /* We may be violating lock order here, so best effort. */
292                 if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT) == -1) {
293                         add_stat(tdb, alloc_coalesce_lockfail, 1);
294                         break;
295                 }
296
297                 /* Now we have lock, re-check. */
298                 if (tdb_read_convert(tdb, end, &rec, sizeof(rec))) {
299                         tdb_unlock_free_bucket(tdb, nb_off);
300                         goto err;
301                 }
302
303                 if (unlikely(frec_magic(&rec) != TDB_FREE_MAGIC)) {
304                         add_stat(tdb, alloc_coalesce_race, 1);
305                         tdb_unlock_free_bucket(tdb, nb_off);
306                         break;
307                 }
308
309                 if (unlikely(frec_flist(&rec) != flist)
310                     || unlikely(size_to_bucket(frec_len(&rec)) != bucket)) {
311                         add_stat(tdb, alloc_coalesce_race, 1);
312                         tdb_unlock_free_bucket(tdb, nb_off);
313                         break;
314                 }
315
316                 if (remove_from_list(tdb, nb_off, end, &rec) == -1) {
317                         tdb_unlock_free_bucket(tdb, nb_off);
318                         goto err;
319                 }
320
321                 end += sizeof(struct tdb_used_record) + frec_len(&rec);
322                 tdb_unlock_free_bucket(tdb, nb_off);
323                 add_stat(tdb, alloc_coalesce_num_merged, 1);
324         }
325
326         /* Didn't find any adjacent free? */
327         if (end == off + sizeof(struct tdb_used_record) + data_len)
328                 return 0;
329
330         /* OK, expand initial record */
331         if (tdb_read_convert(tdb, off, &rec, sizeof(rec)))
332                 goto err;
333
334         if (frec_len(&rec) != data_len) {
335                 tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_DEBUG_FATAL,
336                            "coalesce: expected data len %zu not %zu",
337                            (size_t)data_len, (size_t)frec_len(&rec));
338                 goto err;
339         }
340
341         if (remove_from_list(tdb, b_off, off, &rec) == -1)
342                 goto err;
343
344         /* We have to drop this to avoid deadlocks, so make sure record
345          * doesn't get coalesced by someone else! */
346         rec.magic_and_prev = TDB_COALESCING_MAGIC
347                 << (64 - TDB_OFF_UPPER_STEAL);
348         /* FIXME: Use 255 as invalid free list? */
349         rec.flist_and_len = end - off - sizeof(struct tdb_used_record);
350         if (tdb_write_convert(tdb, off, &rec, sizeof(rec)) != 0)
351                 goto err;
352
353         add_stat(tdb, alloc_coalesce_succeeded, 1);
354         tdb_unlock_free_bucket(tdb, b_off);
355
356         if (add_free_record(tdb, off, end - off) == -1)
357                 return -1;
358         return 1;
359
360 err:
361         /* To unify error paths, we *always* unlock bucket on error. */
362         tdb_unlock_free_bucket(tdb, b_off);
363         return -1;
364 }
365
366 /* We need size bytes to put our key and data in. */
367 static tdb_off_t lock_and_alloc(struct tdb_context *tdb,
368                                 tdb_off_t flist_off,
369                                 tdb_off_t bucket,
370                                 size_t keylen, size_t datalen,
371                                 bool want_extra,
372                                 unsigned hashlow)
373 {
374         tdb_off_t off, b_off,best_off;
375         struct tdb_free_record best = { 0 };
376         double multiplier;
377         size_t size = adjust_size(keylen, datalen);
378
379         add_stat(tdb, allocs, 1);
380 again:
381         b_off = bucket_off(flist_off, bucket);
382
383         /* FIXME: Try non-blocking wait first, to measure contention. */
384         /* Lock this bucket. */
385         if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) == -1) {
386                 return TDB_OFF_ERR;
387         }
388
389         best.flist_and_len = -1ULL;
390         best_off = 0;
391
392         /* Get slack if we're after extra. */
393         if (want_extra)
394                 multiplier = 1.5;
395         else
396                 multiplier = 1.0;
397
398         /* Walk the list to see if any are large enough, getting less fussy
399          * as we go. */
400         off = tdb_read_off(tdb, b_off);
401         if (unlikely(off == TDB_OFF_ERR))
402                 goto unlock_err;
403
404         while (off) {
405                 const struct tdb_free_record *r;
406                 tdb_len_t len;
407                 tdb_off_t next;
408
409                 r = tdb_access_read(tdb, off, sizeof(*r), true);
410                 if (!r)
411                         goto unlock_err;
412
413                 if (frec_magic(r) != TDB_FREE_MAGIC) {
414                         tdb_access_release(tdb, r);
415                         tdb_logerr(tdb, TDB_ERR_CORRUPT, TDB_DEBUG_FATAL,
416                                  "lock_and_alloc: %llu non-free 0x%llx",
417                                  (long long)off, (long long)r->magic_and_prev);
418                         goto unlock_err;
419                 }
420
421                 if (frec_len(r) >= size && frec_len(r) < frec_len(&best)) {
422                         best_off = off;
423                         best = *r;
424                 }
425
426                 if (frec_len(&best) < size * multiplier && best_off) {
427                         tdb_access_release(tdb, r);
428                         break;
429                 }
430
431                 multiplier *= 1.01;
432
433                 next = r->next;
434                 len = frec_len(r);
435                 tdb_access_release(tdb, r);
436
437                 /* Since we're going slow anyway, try coalescing here. */
438                 switch (coalesce(tdb, off, b_off, len)) {
439                 case -1:
440                         /* This has already unlocked on error. */
441                         return -1;
442                 case 1:
443                         /* This has unlocked list, restart. */
444                         goto again;
445                 }
446                 off = next;
447         }
448
449         /* If we found anything at all, use it. */
450         if (best_off) {
451                 struct tdb_used_record rec;
452                 size_t leftover;
453
454                 /* We're happy with this size: take it. */
455                 if (remove_from_list(tdb, b_off, best_off, &best) != 0)
456                         goto unlock_err;
457
458                 leftover = record_leftover(keylen, datalen, want_extra,
459                                            frec_len(&best));
460
461                 assert(keylen + datalen + leftover <= frec_len(&best));
462                 /* We need to mark non-free before we drop lock, otherwise
463                  * coalesce() could try to merge it! */
464                 if (set_used_header(tdb, &rec, keylen, datalen,
465                                     frec_len(&best) - leftover,
466                                     hashlow) != 0)
467                         goto unlock_err;
468
469                 if (tdb_write_convert(tdb, best_off, &rec, sizeof(rec)) != 0)
470                         goto unlock_err;
471
472                 /* Bucket of leftover will be <= current bucket, so nested
473                  * locking is allowed. */
474                 if (leftover) {
475                         add_stat(tdb, alloc_leftover, 1);
476                         if (add_free_record(tdb,
477                                             best_off + sizeof(rec)
478                                             + frec_len(&best) - leftover,
479                                             leftover))
480                                 best_off = TDB_OFF_ERR;
481                 }
482                 tdb_unlock_free_bucket(tdb, b_off);
483
484                 return best_off;
485         }
486
487         tdb_unlock_free_bucket(tdb, b_off);
488         return 0;
489
490 unlock_err:
491         tdb_unlock_free_bucket(tdb, b_off);
492         return TDB_OFF_ERR;
493 }
494
495 /* Get a free block from current free list, or 0 if none. */
496 static tdb_off_t get_free(struct tdb_context *tdb,
497                           size_t keylen, size_t datalen, bool want_extra,
498                           unsigned hashlow)
499 {
500         tdb_off_t off, flist_off;
501         unsigned start_b, b, flist;
502         bool wrapped = false;
503
504         /* If they are growing, add 50% to get to higher bucket. */
505         if (want_extra)
506                 start_b = size_to_bucket(adjust_size(keylen,
507                                                      datalen + datalen / 2));
508         else
509                 start_b = size_to_bucket(adjust_size(keylen, datalen));
510
511         flist_off = tdb->flist_off;
512         flist = tdb->flist;
513         while (!wrapped || flist_off != tdb->flist_off) {
514                 /* Start at exact size bucket, and search up... */
515                 for (b = find_free_head(tdb, flist_off, start_b);
516                      b < TDB_FREE_BUCKETS;
517                      b = find_free_head(tdb, flist_off, b + 1)) {
518                         /* Try getting one from list. */
519                         off = lock_and_alloc(tdb, flist_off,
520                                              b, keylen, datalen, want_extra,
521                                              hashlow);
522                         if (off == TDB_OFF_ERR)
523                                 return TDB_OFF_ERR;
524                         if (off != 0) {
525                                 if (b == start_b)
526                                         add_stat(tdb, alloc_bucket_exact, 1);
527                                 if (b == TDB_FREE_BUCKETS - 1)
528                                         add_stat(tdb, alloc_bucket_max, 1);
529                                 /* Worked?  Stay using this list. */
530                                 tdb->flist_off = flist_off;
531                                 tdb->flist = flist;
532                                 return off;
533                         }
534                         /* Didn't work.  Try next bucket. */
535                 }
536
537                 /* Hmm, try next list. */
538                 flist_off = next_flist(tdb, flist_off);
539                 flist++;
540
541                 if (flist_off == 0) {
542                         wrapped = true;
543                         flist_off = first_flist(tdb);
544                         flist = 0;
545                 }
546         }
547
548         return 0;
549 }
550
551 int set_used_header(struct tdb_context *tdb,
552                     struct tdb_used_record *rec,
553                     uint64_t keylen, uint64_t datalen,
554                     uint64_t actuallen, unsigned hashlow)
555 {
556         uint64_t keybits = (fls64(keylen) + 1) / 2;
557
558         /* Use bottom bits of hash, so it's independent of hash table size. */
559         rec->magic_and_meta = (hashlow & ((1 << 11)-1))
560                 | ((actuallen - (keylen + datalen)) << 11)
561                 | (keybits << 43)
562                 | (TDB_MAGIC << 48);
563         rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
564
565         /* Encoding can fail on big values. */
566         if (rec_key_length(rec) != keylen
567             || rec_data_length(rec) != datalen
568             || rec_extra_padding(rec) != actuallen - (keylen + datalen)) {
569                 tdb_logerr(tdb, TDB_ERR_IO, TDB_DEBUG_ERROR,
570                          "Could not encode k=%llu,d=%llu,a=%llu",
571                          (long long)keylen, (long long)datalen,
572                          (long long)actuallen);
573                 return -1;
574         }
575         return 0;
576 }
577
578 /* Expand the database. */
579 static int tdb_expand(struct tdb_context *tdb, tdb_len_t size)
580 {
581         uint64_t old_size;
582         tdb_len_t wanted;
583
584         /* We need room for the record header too. */
585         wanted = sizeof(struct tdb_used_record) + size;
586
587         /* Need to hold a hash lock to expand DB: transactions rely on it. */
588         if (!(tdb->flags & TDB_NOLOCK)
589             && !tdb->allrecord_lock.count && !tdb_has_hash_locks(tdb)) {
590                 tdb_logerr(tdb, TDB_ERR_LOCK, TDB_DEBUG_ERROR,
591                            "tdb_expand: must hold lock during expand");
592                 return -1;
593         }
594
595         /* always make room for at least 100 more records, and at
596            least 25% more space. */
597         if (size * TDB_EXTENSION_FACTOR > tdb->map_size / 4)
598                 wanted = size * TDB_EXTENSION_FACTOR;
599         else
600                 wanted = tdb->map_size / 4;
601         wanted = adjust_size(0, wanted);
602
603         /* Only one person can expand file at a time. */
604         if (tdb_lock_expand(tdb, F_WRLCK) != 0)
605                 return -1;
606
607         /* Someone else may have expanded the file, so retry. */
608         old_size = tdb->map_size;
609         tdb->methods->oob(tdb, tdb->map_size + 1, true);
610         if (tdb->map_size != old_size) {
611                 tdb_unlock_expand(tdb, F_WRLCK);
612                 return 0;
613         }
614
615         if (tdb->methods->expand_file(tdb, wanted) == -1) {
616                 tdb_unlock_expand(tdb, F_WRLCK);
617                 return -1;
618         }
619
620         /* We need to drop this lock before adding free record. */
621         tdb_unlock_expand(tdb, F_WRLCK);
622
623         add_stat(tdb, expands, 1);
624         return add_free_record(tdb, old_size, wanted);
625 }
626
627 /* This won't fail: it will expand the database if it has to. */
628 tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
629                 uint64_t hash, bool growing)
630 {
631         tdb_off_t off;
632
633         /* We can't hold pointers during this: we could unmap! */
634         assert(!tdb->direct_access);
635
636         for (;;) {
637                 off = get_free(tdb, keylen, datalen, growing, hash);
638                 if (likely(off != 0))
639                         break;
640
641                 if (tdb_expand(tdb, adjust_size(keylen, datalen)))
642                         return TDB_OFF_ERR;
643         }
644
645         return off;
646 }