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