tdb2: expand lock now nests inside other locks.
[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 <time.h>
21 #include <assert.h>
22 #include <limits.h>
23
24 /* We have to be able to fit a free record here. */
25 #define MIN_DATA_LEN    \
26         (sizeof(struct tdb_free_record) - sizeof(struct tdb_used_record))
27
28 static unsigned fls64(uint64_t val)
29 {
30 #if HAVE_BUILTIN_CLZL
31         if (val <= ULONG_MAX) {
32                 /* This is significantly faster! */
33                 return val ? sizeof(long) * CHAR_BIT - __builtin_clzl(val) : 0;
34         } else {
35 #endif
36         uint64_t r = 64;
37
38         if (!val)
39                 return 0;
40         if (!(val & 0xffffffff00000000ull)) {
41                 val <<= 32;
42                 r -= 32;
43         }
44         if (!(val & 0xffff000000000000ull)) {
45                 val <<= 16;
46                 r -= 16;
47         }
48         if (!(val & 0xff00000000000000ull)) {
49                 val <<= 8;
50                 r -= 8;
51         }
52         if (!(val & 0xf000000000000000ull)) {
53                 val <<= 4;
54                 r -= 4;
55         }
56         if (!(val & 0xc000000000000000ull)) {
57                 val <<= 2;
58                 r -= 2;
59         }
60         if (!(val & 0x8000000000000000ull)) {
61                 val <<= 1;
62                 r -= 1;
63         }
64         return r;
65 #if HAVE_BUILTIN_CLZL
66         }
67 #endif
68 }
69
70 /* In which bucket would we find a particular record size? (ignoring header) */
71 unsigned int size_to_bucket(unsigned int zone_bits, tdb_len_t data_len)
72 {
73         unsigned int bucket;
74
75         /* We can't have records smaller than this. */
76         assert(data_len >= MIN_DATA_LEN);
77
78         /* Ignoring the header... */
79         if (data_len - MIN_DATA_LEN <= 64) {
80                 /* 0 in bucket 0, 8 in bucket 1... 64 in bucket 6. */
81                 bucket = (data_len - MIN_DATA_LEN) / 8;
82         } else {
83                 /* After that we go power of 2. */
84                 bucket = fls64(data_len - MIN_DATA_LEN) + 2;
85         }
86
87         if (unlikely(bucket > BUCKETS_FOR_ZONE(zone_bits)))
88                 bucket = BUCKETS_FOR_ZONE(zone_bits);
89         return bucket;
90 }
91
92 /* Subtract 1-byte tailer and header.  Then round up to next power of 2. */
93 static unsigned max_zone_bits(struct tdb_context *tdb)
94 {
95         return fls64(tdb->map_size-1-sizeof(struct tdb_header)-1) + 1;
96 }
97
98 /* Start by using a random zone to spread the load: returns the offset. */
99 static uint64_t random_zone(struct tdb_context *tdb)
100 {
101         struct free_zone_header zhdr;
102         tdb_off_t off = sizeof(struct tdb_header);
103         tdb_len_t half_bits;
104         uint64_t randbits = 0;
105         unsigned int i;
106
107         for (i = 0; i < 64; i += fls64(RAND_MAX)) 
108                 randbits ^= ((uint64_t)random()) << i;
109
110         /* FIXME: Does this work?  Test! */
111         half_bits = max_zone_bits(tdb) - 1;
112         do {
113                 /* Pick left or right side (not outside file) */
114                 if ((randbits & 1)
115                     && !tdb->methods->oob(tdb, off + (1ULL << half_bits)
116                                           + sizeof(zhdr), true)) {
117                         off += 1ULL << half_bits;
118                 }
119                 randbits >>= 1;
120
121                 if (tdb_read_convert(tdb, off, &zhdr, sizeof(zhdr)) == -1) 
122                         return TDB_OFF_ERR;
123
124                 if (zhdr.zone_bits == half_bits)
125                         return off;
126
127                 half_bits--;
128         } while (half_bits >= INITIAL_ZONE_BITS);
129
130         tdb->ecode = TDB_ERR_CORRUPT;
131         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
132                  "random_zone: zone at %llu smaller than %u bits?",
133                  (long long)off, INITIAL_ZONE_BITS);
134         return TDB_OFF_ERR;
135 }
136
137 int tdb_zone_init(struct tdb_context *tdb)
138 {
139         tdb->zone_off = random_zone(tdb);
140         if (tdb->zone_off == TDB_OFF_ERR)
141                 return -1;
142         if (tdb_read_convert(tdb, tdb->zone_off,
143                              &tdb->zhdr, sizeof(tdb->zhdr)) == -1) 
144                 return -1;
145         return 0;
146 }
147
148 /* Where's the header, given a zone size of 1 << zone_bits? */
149 static tdb_off_t zone_off(tdb_off_t off, unsigned int zone_bits)
150 {
151         off -= sizeof(struct tdb_header);
152         return (off & ~((1ULL << zone_bits) - 1)) + sizeof(struct tdb_header);
153 }
154
155 /* Offset of a given bucket. */
156 /* FIXME: bucket can be "unsigned" everywhere, or even uint8/16. */
157 tdb_off_t bucket_off(tdb_off_t zone_off, tdb_off_t bucket)
158 {
159         return zone_off
160                 + sizeof(struct free_zone_header)
161                 + bucket * sizeof(tdb_off_t);
162 }
163
164 /* Returns free_buckets + 1, or list number to search. */
165 static tdb_off_t find_free_head(struct tdb_context *tdb, tdb_off_t bucket)
166 {
167         tdb_off_t b;
168
169         /* Speculatively search for a non-zero bucket. */
170         b = tdb_find_nonzero_off(tdb, bucket_off(tdb->zone_off, bucket),
171                                  BUCKETS_FOR_ZONE(tdb->zhdr.zone_bits) + 1
172                                  - bucket);
173         return bucket + b;
174 }
175
176 /* Remove from free bucket. */
177 static int remove_from_list(struct tdb_context *tdb,
178                             tdb_off_t b_off, struct tdb_free_record *r)
179 {
180         tdb_off_t off;
181
182         /* Front of list? */
183         if (r->prev == 0) {
184                 off = b_off;
185         } else {
186                 off = r->prev + offsetof(struct tdb_free_record, next);
187         }
188         /* r->prev->next = r->next */
189         if (tdb_write_off(tdb, off, r->next)) {
190                 return -1;
191         }
192
193         if (r->next != 0) {
194                 off = r->next + offsetof(struct tdb_free_record, prev);
195                 /* r->next->prev = r->prev */
196                 if (tdb_write_off(tdb, off, r->prev)) {
197                         return -1;
198                 }
199         }
200         return 0;
201 }
202
203 /* Enqueue in this free bucket. */
204 static int enqueue_in_free(struct tdb_context *tdb,
205                            tdb_off_t b_off,
206                            tdb_off_t off,
207                            struct tdb_free_record *new)
208 {
209         new->prev = 0;
210         /* new->next = head. */
211         new->next = tdb_read_off(tdb, b_off);
212         if (new->next == TDB_OFF_ERR)
213                 return -1;
214
215         if (new->next) {
216                 /* next->prev = new. */
217                 if (tdb_write_off(tdb, new->next
218                                   + offsetof(struct tdb_free_record, prev),
219                                   off) != 0)
220                         return -1;
221         }
222         /* head = new */
223         if (tdb_write_off(tdb, b_off, off) != 0)
224                 return -1;
225
226         return tdb_write_convert(tdb, off, new, sizeof(*new));
227 }
228
229 /* List need not be locked. */
230 int add_free_record(struct tdb_context *tdb,
231                     unsigned int zone_bits,
232                     tdb_off_t off, tdb_len_t len_with_header)
233 {
234         struct tdb_free_record new;
235         tdb_off_t b_off;
236         int ret;
237
238         assert(len_with_header >= sizeof(new));
239         assert(zone_bits < (1 << 6));
240
241         new.magic_and_meta = TDB_FREE_MAGIC | zone_bits;
242         new.data_len = len_with_header - sizeof(struct tdb_used_record);
243
244         b_off = bucket_off(zone_off(off, zone_bits),
245                            size_to_bucket(zone_bits, new.data_len));
246         if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) != 0)
247                 return -1;
248
249         ret = enqueue_in_free(tdb, b_off, off, &new);
250         tdb_unlock_free_bucket(tdb, b_off);
251         return ret;
252 }
253
254 /* If we have enough left over to be useful, split that off. */
255 static int to_used_record(struct tdb_context *tdb,
256                           unsigned int zone_bits,
257                           tdb_off_t off,
258                           tdb_len_t needed,
259                           tdb_len_t total_len,
260                           tdb_len_t *actual)
261 {
262         struct tdb_used_record used;
263         tdb_len_t leftover;
264
265         leftover = total_len - needed;
266         if (leftover < sizeof(struct tdb_free_record))
267                 leftover = 0;
268
269         *actual = total_len - leftover;
270
271         if (leftover) {
272                 if (add_free_record(tdb, zone_bits,
273                                     off + sizeof(used) + *actual,
274                                     total_len - needed))
275                         return -1;
276         }
277         return 0;
278 }
279
280 /* Note: we unlock the current bucket if we coalesce or fail. */
281 static int coalesce(struct tdb_context *tdb,
282                     tdb_off_t zone_off, unsigned zone_bits,
283                     tdb_off_t off, tdb_off_t b_off, tdb_len_t data_len)
284 {
285         struct tdb_free_record pad, *r;
286         tdb_off_t end = off + sizeof(struct tdb_used_record) + data_len;
287
288         while (end < (zone_off + (1ULL << zone_bits))) {
289                 tdb_off_t nb_off;
290
291                 /* FIXME: do tdb_get here and below really win? */
292                 r = tdb_get(tdb, end, &pad, sizeof(pad));
293                 if (!r)
294                         goto err;
295
296                 if (frec_magic(r) != TDB_FREE_MAGIC)
297                         break;
298
299                 nb_off = bucket_off(zone_off,
300                                     size_to_bucket(zone_bits, r->data_len));
301
302                 /* We may be violating lock order here, so best effort. */
303                 if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT) == -1)
304                         break;
305
306                 /* Now we have lock, re-check. */
307                 r = tdb_get(tdb, end, &pad, sizeof(pad));
308                 if (!r) {
309                         tdb_unlock_free_bucket(tdb, nb_off);
310                         goto err;
311                 }
312
313                 if (unlikely(frec_magic(r) != TDB_FREE_MAGIC)) {
314                         tdb_unlock_free_bucket(tdb, nb_off);
315                         break;
316                 }
317
318                 if (remove_from_list(tdb, nb_off, r) == -1) {
319                         tdb_unlock_free_bucket(tdb, nb_off);
320                         goto err;
321                 }
322
323                 end += sizeof(struct tdb_used_record) + r->data_len;
324                 tdb_unlock_free_bucket(tdb, nb_off);
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 record */
332         r = tdb_get(tdb, off, &pad, sizeof(pad));
333         if (!r)
334                 goto err;
335
336         if (r->data_len != data_len) {
337                 tdb->ecode = TDB_ERR_CORRUPT;
338                 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
339                          "coalesce: expected data len %llu not %llu\n",
340                          (long long)data_len, (long long)r->data_len);
341                 goto err;
342         }
343
344         if (remove_from_list(tdb, b_off, r) == -1)
345                 goto err;
346
347         /* We have to drop this to avoid deadlocks. */
348         tdb_unlock_free_bucket(tdb, b_off);
349
350         if (add_free_record(tdb, zone_bits, off, end - off) == -1)
351                 return -1;
352         return 1;
353
354 err:
355         /* To unify error paths, we *always* unlock bucket on error. */
356         tdb_unlock_free_bucket(tdb, b_off);
357         return -1;
358 }
359
360 /* We need size bytes to put our key and data in. */
361 static tdb_off_t lock_and_alloc(struct tdb_context *tdb,
362                                 tdb_off_t zone_off,
363                                 unsigned zone_bits,
364                                 tdb_off_t bucket,
365                                 size_t size,
366                                 tdb_len_t *actual)
367 {
368         tdb_off_t off, b_off,best_off;
369         struct tdb_free_record pad, best = { 0 }, *r;
370         double multiplier;
371
372 again:
373         b_off = bucket_off(zone_off, bucket);
374
375         /* Lock this bucket. */
376         if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) == -1) {
377                 return TDB_OFF_ERR;
378         }
379
380         best.data_len = -1ULL;
381         best_off = 0;
382         /* FIXME: Start with larger multiplier if we're growing. */
383         multiplier = 1.0;
384
385         /* Walk the list to see if any are large enough, getting less fussy
386          * as we go. */
387         off = tdb_read_off(tdb, b_off);
388         if (unlikely(off == TDB_OFF_ERR))
389                 goto unlock_err;
390
391         while (off) {
392                 /* FIXME: Does tdb_get win anything here? */
393                 r = tdb_get(tdb, off, &pad, sizeof(*r));
394                 if (!r)
395                         goto unlock_err;
396
397                 if (frec_magic(r) != TDB_FREE_MAGIC) {
398                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
399                                  "lock_and_alloc: %llu non-free 0x%llx\n",
400                                  (long long)off, (long long)r->magic_and_meta);
401                         goto unlock_err;
402                 }
403
404                 if (r->data_len >= size && r->data_len < best.data_len) {
405                         best_off = off;
406                         best = *r;
407                 }
408
409                 if (best.data_len < size * multiplier && best_off)
410                         goto use_best;
411
412                 multiplier *= 1.01;
413
414                 /* Since we're going slow anyway, try coalescing here. */
415                 switch (coalesce(tdb, zone_off, zone_bits, off, b_off,
416                                  r->data_len)) {
417                 case -1:
418                         /* This has already unlocked on error. */
419                         return -1;
420                 case 1:
421                         /* This has unlocked list, restart. */
422                         goto again;
423                 }
424                 off = r->next;
425         }
426
427         /* If we found anything at all, use it. */
428         if (best_off) {
429         use_best:
430                 /* We're happy with this size: take it. */
431                 if (remove_from_list(tdb, b_off, &best) != 0)
432                         goto unlock_err;
433                 tdb_unlock_free_bucket(tdb, b_off);
434
435                 if (to_used_record(tdb, zone_bits, best_off, size,
436                                    best.data_len, actual)) {
437                         return -1;
438                 }
439                 return best_off;
440         }
441
442         tdb_unlock_free_bucket(tdb, b_off);
443         return 0;
444
445 unlock_err:
446         tdb_unlock_free_bucket(tdb, b_off);
447         return TDB_OFF_ERR;
448 }
449
450 static bool next_zone(struct tdb_context *tdb)
451 {
452         tdb_off_t next = tdb->zone_off + (1ULL << tdb->zhdr.zone_bits);
453
454         /* We must have a header. */
455         if (tdb->methods->oob(tdb, next + sizeof(tdb->zhdr), true))
456                 return false;
457
458         tdb->zone_off = next;
459         return tdb_read_convert(tdb, next, &tdb->zhdr, sizeof(tdb->zhdr)) == 0;
460 }
461
462 /* Offset returned is within current zone (which it may alter). */
463 static tdb_off_t get_free(struct tdb_context *tdb, size_t size,
464                           tdb_len_t *actual)
465 {
466         tdb_off_t start_zone = tdb->zone_off, off;
467         bool wrapped = false;
468
469         while (!wrapped || tdb->zone_off != start_zone) {
470                 tdb_off_t b;
471
472                 /* Shortcut for really huge allocations... */
473                 if ((size >> tdb->zhdr.zone_bits) != 0)
474                         continue;
475
476                 /* Start at exact size bucket, and search up... */
477                 b = size_to_bucket(tdb->zhdr.zone_bits, size);
478                 for (b = find_free_head(tdb, b);
479                      b <= BUCKETS_FOR_ZONE(tdb->zhdr.zone_bits);
480                      b += find_free_head(tdb, b + 1)) {
481                         /* Try getting one from list. */
482                         off = lock_and_alloc(tdb, tdb->zone_off,
483                                              tdb->zhdr.zone_bits,
484                                              b, size, actual);
485                         if (off == TDB_OFF_ERR)
486                                 return TDB_OFF_ERR;
487                         if (off != 0)
488                                 return off;
489                         /* Didn't work.  Try next bucket. */
490                 }
491
492                 /* Didn't work, try next zone, if it exists. */
493                 if (!next_zone(tdb)) {
494                         wrapped = true;
495                         tdb->zone_off = sizeof(struct tdb_header);
496                         if (tdb_read_convert(tdb, tdb->zone_off,
497                                              &tdb->zhdr, sizeof(tdb->zhdr))) {
498                                 return TDB_OFF_ERR;
499                         }
500                 }
501         }
502         return 0;
503 }
504
505 int set_header(struct tdb_context *tdb,
506                struct tdb_used_record *rec,
507                uint64_t keylen, uint64_t datalen,
508                uint64_t actuallen, uint64_t hash,
509                unsigned int zone_bits)
510 {
511         uint64_t keybits = (fls64(keylen) + 1) / 2;
512
513         /* Use top bits of hash, so it's independent of hash table size. */
514         rec->magic_and_meta
515                 = zone_bits
516                 | ((hash >> 59) << 6)
517                 | ((actuallen - (keylen + datalen)) << 11)
518                 | (keybits << 43)
519                 | (TDB_MAGIC << 48);
520         rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
521
522         /* Encoding can fail on big values. */
523         if (rec_key_length(rec) != keylen
524             || rec_data_length(rec) != datalen
525             || rec_extra_padding(rec) != actuallen - (keylen + datalen)) {
526                 tdb->ecode = TDB_ERR_IO;
527                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
528                          "Could not encode k=%llu,d=%llu,a=%llu\n",
529                          (long long)keylen, (long long)datalen,
530                          (long long)actuallen);
531                 return -1;
532         }
533         return 0;
534 }
535
536 static bool zones_happy(struct tdb_context *tdb)
537 {
538         /* FIXME: look at distribution of zones. */
539         return true;
540 }
541
542 /* Assume we want buckets up to the comfort factor. */
543 static tdb_len_t overhead(unsigned int zone_bits)
544 {
545         return sizeof(struct free_zone_header)
546                 + (BUCKETS_FOR_ZONE(zone_bits) + 1) * sizeof(tdb_off_t);
547 }
548
549 /* Expand the database (by adding a zone). */
550 static int tdb_expand(struct tdb_context *tdb, tdb_len_t size)
551 {
552         uint64_t old_size;
553         tdb_off_t off;
554         uint8_t zone_bits;
555         unsigned int num_buckets;
556         tdb_len_t wanted;
557         struct free_zone_header zhdr;
558         bool enlarge_zone;
559
560         /* We need room for the record header too. */
561         wanted = sizeof(struct tdb_used_record) + size;
562
563         /* Only one person can expand file at a time. */
564         if (tdb_lock_expand(tdb, F_WRLCK) != 0)
565                 return -1;
566
567         /* Someone else may have expanded the file, so retry. */
568         old_size = tdb->map_size;
569         tdb->methods->oob(tdb, tdb->map_size + 1, true);
570         if (tdb->map_size != old_size)
571                 goto success;
572
573         /* zone bits tailer char is protected by EXPAND lock. */
574         if (tdb->methods->read(tdb, old_size - 1, &zone_bits, 1) == -1)
575                 goto fail;
576
577         /* If zones aren't working well, add larger zone if possible. */
578         enlarge_zone = !zones_happy(tdb);
579
580         /* New zone can be between zone_bits or larger if we're on the right
581          * boundary. */
582         for (;;) {
583                 /* Does this fit the allocation comfortably? */
584                 if ((1ULL << zone_bits) >= overhead(zone_bits) + wanted) {
585                         /* Only let enlarge_zone enlarge us once. */
586                         if (!enlarge_zone)
587                                 break;
588                         enlarge_zone = false;
589                 }
590                 if ((old_size - 1 - sizeof(struct tdb_header))
591                     & (1 << zone_bits))
592                         break;
593                 zone_bits++;
594         }
595
596         zhdr.zone_bits = zone_bits;
597         num_buckets = BUCKETS_FOR_ZONE(zone_bits);
598
599         if (tdb->methods->expand_file(tdb, 1ULL << zone_bits) == -1)
600                 goto fail;
601
602         /* Write new tailer. */
603         if (tdb->methods->write(tdb, tdb->map_size - 1, &zone_bits, 1) == -1)
604                 goto fail;
605
606         /* Write new zone header (just before old tailer). */
607         off = old_size - 1;
608         if (tdb_write_convert(tdb, off, &zhdr, sizeof(zhdr)) == -1)
609                 goto fail;
610
611         /* Now write empty buckets. */
612         off += sizeof(zhdr);
613         if (zero_out(tdb, off, (num_buckets+1) * sizeof(tdb_off_t)) == -1)
614                 goto fail;
615         off += (num_buckets+1) * sizeof(tdb_off_t);
616
617         /* Now add the rest as our free record. */
618         if (add_free_record(tdb, zone_bits, off, tdb->map_size-1-off) == -1)
619                 goto fail;
620
621         /* Try allocating from this zone now. */
622         tdb->zone_off = old_size - 1;
623         tdb->zhdr = zhdr;
624
625 success:
626         tdb_unlock_expand(tdb, F_WRLCK);
627         return 0;
628
629 fail:
630         tdb_unlock_expand(tdb, F_WRLCK);
631         return -1;
632 }
633
634 static tdb_len_t adjust_size(size_t keylen, size_t datalen, bool growing)
635 {
636         tdb_len_t size = keylen + datalen;
637
638         if (size < MIN_DATA_LEN)
639                 size = MIN_DATA_LEN;
640
641         /* Overallocate if this is coming from an enlarging store. */
642         if (growing)
643                 size += datalen / 2;
644
645         /* Round to next uint64_t boundary. */
646         return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
647 }
648
649 /* This won't fail: it will expand the database if it has to. */
650 tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
651                 uint64_t hash, bool growing)
652 {
653         tdb_off_t off;
654         tdb_len_t size, actual;
655         struct tdb_used_record rec;
656
657         /* We don't want header to change during this! */
658         assert(tdb->header_uptodate);
659
660         size = adjust_size(keylen, datalen, growing);
661
662 again:
663         off = get_free(tdb, size, &actual);
664         if (unlikely(off == TDB_OFF_ERR))
665                 return off;
666
667         if (unlikely(off == 0)) {
668                 if (tdb_expand(tdb, size) == -1)
669                         return TDB_OFF_ERR;
670                 goto again;
671         }
672
673         /* Some supergiant values can't be encoded. */
674         /* FIXME: Check before, and limit actual in get_free. */
675         if (set_header(tdb, &rec, keylen, datalen, actual, hash,
676                        tdb->zhdr.zone_bits) != 0) {
677                 add_free_record(tdb, tdb->zhdr.zone_bits, off,
678                                 sizeof(rec) + actual);
679                 return TDB_OFF_ERR;
680         }
681
682         if (tdb_write_convert(tdb, off, &rec, sizeof(rec)) != 0)
683                 return TDB_OFF_ERR;
684         
685         return off;
686 }