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