]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/free.c
tdb2: get rid of zones
[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 int tdb_flist_init(struct tdb_context *tdb)
53 {
54         tdb->flist_off = tdb_read_off(tdb,
55                                       offsetof(struct tdb_header, free_list));
56         if (tdb->flist_off == TDB_OFF_ERR)
57                 return -1;
58         return 0;
59 }
60
61 /* Offset of a given bucket. */
62 tdb_off_t bucket_off(tdb_off_t flist_off, unsigned bucket)
63 {
64         return flist_off + offsetof(struct tdb_freelist, buckets)
65                 + bucket * sizeof(tdb_off_t);
66 }
67
68 /* Returns free_buckets + 1, or list number to search. */
69 static tdb_off_t find_free_head(struct tdb_context *tdb, tdb_off_t bucket)
70 {
71         /* Speculatively search for a non-zero bucket. */
72         return tdb_find_nonzero_off(tdb, bucket_off(tdb->flist_off, 0),
73                                     bucket, TDB_FREE_BUCKETS);
74 }
75
76 /* Remove from free bucket. */
77 static int remove_from_list(struct tdb_context *tdb,
78                             tdb_off_t b_off, tdb_off_t r_off,
79                             struct tdb_free_record *r)
80 {
81         tdb_off_t off;
82
83         /* Front of list? */
84         if (r->prev == 0) {
85                 off = b_off;
86         } else {
87                 off = r->prev + offsetof(struct tdb_free_record, next);
88         }
89
90 #ifdef DEBUG
91         if (tdb_read_off(tdb, off) != r_off) {
92                 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
93                          "remove_from_list: %llu bad prev in list %llu\n",
94                          (long long)r_off, (long long)b_off);
95                 return -1;
96         }
97 #endif
98
99         /* r->prev->next = r->next */
100         if (tdb_write_off(tdb, off, r->next)) {
101                 return -1;
102         }
103
104         if (r->next != 0) {
105                 off = r->next + offsetof(struct tdb_free_record, prev);
106                 /* r->next->prev = r->prev */
107
108 #ifdef DEBUG
109                 if (tdb_read_off(tdb, off) != r_off) {
110                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
111                                  "remove_from_list: %llu bad list %llu\n",
112                                  (long long)r_off, (long long)b_off);
113                         return -1;
114                 }
115 #endif
116
117                 if (tdb_write_off(tdb, off, r->prev)) {
118                         return -1;
119                 }
120         }
121         return 0;
122 }
123
124 /* Enqueue in this free bucket. */
125 static int enqueue_in_free(struct tdb_context *tdb,
126                            tdb_off_t b_off,
127                            tdb_off_t off,
128                            struct tdb_free_record *new)
129 {
130         new->prev = 0;
131         /* new->next = head. */
132         new->next = tdb_read_off(tdb, b_off);
133         if (new->next == TDB_OFF_ERR)
134                 return -1;
135
136         if (new->next) {
137 #ifdef DEBUG
138                 if (tdb_read_off(tdb,
139                                  new->next
140                                  + offsetof(struct tdb_free_record, prev))
141                     != 0) {
142                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
143                                  "enqueue_in_free: %llu bad head prev %llu\n",
144                                  (long long)new->next, (long long)b_off);
145                         return -1;
146                 }
147 #endif
148                 /* next->prev = new. */
149                 if (tdb_write_off(tdb, new->next
150                                   + offsetof(struct tdb_free_record, prev),
151                                   off) != 0)
152                         return -1;
153         }
154         /* head = new */
155         if (tdb_write_off(tdb, b_off, off) != 0)
156                 return -1;
157
158         return tdb_write_convert(tdb, off, new, sizeof(*new));
159 }
160
161 /* List need not be locked. */
162 int add_free_record(struct tdb_context *tdb,
163                     tdb_off_t off, tdb_len_t len_with_header)
164 {
165         struct tdb_free_record new;
166         tdb_off_t b_off;
167         int ret;
168
169         assert(len_with_header >= sizeof(new));
170
171         new.magic_and_meta = TDB_FREE_MAGIC;
172         new.data_len = len_with_header - sizeof(struct tdb_used_record);
173
174         b_off = bucket_off(tdb->flist_off, size_to_bucket(new.data_len));
175         if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) != 0)
176                 return -1;
177
178         ret = enqueue_in_free(tdb, b_off, off, &new);
179         tdb_unlock_free_bucket(tdb, b_off);
180         return ret;
181 }
182
183 static size_t adjust_size(size_t keylen, size_t datalen)
184 {
185         size_t size = keylen + datalen;
186
187         if (size < TDB_MIN_DATA_LEN)
188                 size = TDB_MIN_DATA_LEN;
189
190         /* Round to next uint64_t boundary. */
191         return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
192 }
193
194 /* If we have enough left over to be useful, split that off. */
195 static size_t record_leftover(size_t keylen, size_t datalen,
196                               bool want_extra, size_t total_len)
197 {
198         ssize_t leftover;
199
200         if (want_extra)
201                 datalen += datalen / 2;
202         leftover = total_len - adjust_size(keylen, datalen);
203
204         if (leftover < (ssize_t)sizeof(struct tdb_free_record))
205                 return 0;
206
207         return leftover;
208 }
209
210 /* Note: we unlock the current bucket if we coalesce or fail. */
211 static int coalesce(struct tdb_context *tdb,
212                     tdb_off_t off, tdb_off_t b_off, tdb_len_t data_len)
213 {
214         struct tdb_free_record pad, *r;
215         tdb_off_t end;
216
217         end = off + sizeof(struct tdb_used_record) + data_len;
218
219         while (end < tdb->map_size) {
220                 tdb_off_t nb_off;
221
222                 /* FIXME: do tdb_get here and below really win? */
223                 r = tdb_get(tdb, end, &pad, sizeof(pad));
224                 if (!r)
225                         goto err;
226
227                 if (frec_magic(r) != TDB_FREE_MAGIC)
228                         break;
229
230                 /* FIXME: Use flist from record */
231                 nb_off = bucket_off(tdb->flist_off,size_to_bucket(r->data_len));
232
233                 /* We may be violating lock order here, so best effort. */
234                 if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT) == -1)
235                         break;
236
237                 /* Now we have lock, re-check. */
238                 r = tdb_get(tdb, end, &pad, sizeof(pad));
239                 if (!r) {
240                         tdb_unlock_free_bucket(tdb, nb_off);
241                         goto err;
242                 }
243
244                 if (unlikely(frec_magic(r) != TDB_FREE_MAGIC)) {
245                         tdb_unlock_free_bucket(tdb, nb_off);
246                         break;
247                 }
248
249                 if (unlikely(bucket_off(tdb->flist_off,
250                                         size_to_bucket(r->data_len))
251                              != nb_off)) {
252                         tdb_unlock_free_bucket(tdb, nb_off);
253                         break;
254                 }
255
256                 if (remove_from_list(tdb, nb_off, end, r) == -1) {
257                         tdb_unlock_free_bucket(tdb, nb_off);
258                         goto err;
259                 }
260
261                 end += sizeof(struct tdb_used_record) + r->data_len;
262                 tdb_unlock_free_bucket(tdb, nb_off);
263         }
264
265         /* Didn't find any adjacent free? */
266         if (end == off + sizeof(struct tdb_used_record) + data_len)
267                 return 0;
268
269         /* OK, expand record */
270         r = tdb_get(tdb, off, &pad, sizeof(pad));
271         if (!r)
272                 goto err;
273
274         if (r->data_len != data_len) {
275                 tdb->ecode = TDB_ERR_CORRUPT;
276                 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
277                          "coalesce: expected data len %llu not %llu\n",
278                          (long long)data_len, (long long)r->data_len);
279                 goto err;
280         }
281
282         if (remove_from_list(tdb, b_off, off, r) == -1)
283                 goto err;
284
285         r = tdb_access_write(tdb, off, sizeof(*r), true);
286         if (!r)
287                 goto err;
288
289         /* We have to drop this to avoid deadlocks, so make sure record
290          * doesn't get coalesced by someone else! */
291         r->magic_and_meta = TDB_COALESCING_MAGIC;
292         r->data_len = end - off - sizeof(struct tdb_used_record);
293         if (tdb_access_commit(tdb, r) != 0)
294                 goto err;
295
296         tdb_unlock_free_bucket(tdb, b_off);
297
298         if (add_free_record(tdb, off, end - off) == -1)
299                 return -1;
300         return 1;
301
302 err:
303         /* To unify error paths, we *always* unlock bucket on error. */
304         tdb_unlock_free_bucket(tdb, b_off);
305         return -1;
306 }
307
308 /* We need size bytes to put our key and data in. */
309 static tdb_off_t lock_and_alloc(struct tdb_context *tdb,
310                                 tdb_off_t flist_off,
311                                 tdb_off_t bucket,
312                                 size_t keylen, size_t datalen,
313                                 bool want_extra,
314                                 unsigned hashlow)
315 {
316         tdb_off_t off, b_off,best_off;
317         struct tdb_free_record pad, best = { 0 }, *r;
318         double multiplier;
319         size_t size = adjust_size(keylen, datalen);
320
321 again:
322         b_off = bucket_off(flist_off, bucket);
323
324         /* FIXME: Try non-blocking wait first, to measure contention. */
325         /* Lock this bucket. */
326         if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) == -1) {
327                 return TDB_OFF_ERR;
328         }
329
330         best.data_len = -1ULL;
331         best_off = 0;
332
333         /* Get slack if we're after extra. */
334         if (want_extra)
335                 multiplier = 1.5;
336         else
337                 multiplier = 1.0;
338
339         /* Walk the list to see if any are large enough, getting less fussy
340          * as we go. */
341         off = tdb_read_off(tdb, b_off);
342         if (unlikely(off == TDB_OFF_ERR))
343                 goto unlock_err;
344
345         while (off) {
346                 /* FIXME: Does tdb_get win anything here? */
347                 r = tdb_get(tdb, off, &pad, sizeof(*r));
348                 if (!r)
349                         goto unlock_err;
350
351                 if (frec_magic(r) != TDB_FREE_MAGIC) {
352                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
353                                  "lock_and_alloc: %llu non-free 0x%llx\n",
354                                  (long long)off, (long long)r->magic_and_meta);
355                         goto unlock_err;
356                 }
357
358                 if (r->data_len >= size && r->data_len < best.data_len) {
359                         best_off = off;
360                         best = *r;
361                 }
362
363                 if (best.data_len < size * multiplier && best_off)
364                         break;
365
366                 multiplier *= 1.01;
367
368                 /* Since we're going slow anyway, try coalescing here. */
369                 switch (coalesce(tdb, off, b_off, r->data_len)) {
370                 case -1:
371                         /* This has already unlocked on error. */
372                         return -1;
373                 case 1:
374                         /* This has unlocked list, restart. */
375                         goto again;
376                 }
377                 off = r->next;
378         }
379
380         /* If we found anything at all, use it. */
381         if (best_off) {
382                 struct tdb_used_record rec;
383                 size_t leftover;
384
385                 /* We're happy with this size: take it. */
386                 if (remove_from_list(tdb, b_off, best_off, &best) != 0)
387                         goto unlock_err;
388
389                 leftover = record_leftover(keylen, datalen, want_extra,
390                                            best.data_len);
391
392                 assert(keylen + datalen + leftover <= best.data_len);
393                 /* We need to mark non-free before we drop lock, otherwise
394                  * coalesce() could try to merge it! */
395                 if (set_header(tdb, &rec, keylen, datalen,
396                                best.data_len - leftover,
397                                hashlow) != 0)
398                         goto unlock_err;
399
400                 if (tdb_write_convert(tdb, best_off, &rec, sizeof(rec)) != 0)
401                         goto unlock_err;
402
403                 tdb_unlock_free_bucket(tdb, b_off);
404
405                 if (leftover) {
406                         if (add_free_record(tdb,
407                                             best_off + sizeof(rec)
408                                             + best.data_len - leftover,
409                                             leftover))
410                                 return TDB_OFF_ERR;
411                 }
412                 return best_off;
413         }
414
415         tdb_unlock_free_bucket(tdb, b_off);
416         return 0;
417
418 unlock_err:
419         tdb_unlock_free_bucket(tdb, b_off);
420         return TDB_OFF_ERR;
421 }
422
423 /* Get a free block from current free list, or 0 if none. */
424 static tdb_off_t get_free(struct tdb_context *tdb,
425                           size_t keylen, size_t datalen, bool want_extra,
426                           unsigned hashlow)
427 {
428         tdb_off_t off;
429         unsigned start_b, b;
430
431         /* If they are growing, add 50% to get to higher bucket. */
432         if (want_extra)
433                 start_b = size_to_bucket(adjust_size(keylen,
434                                                      datalen + datalen / 2));
435         else
436                 start_b = size_to_bucket(adjust_size(keylen, datalen));
437
438         /* Start at exact size bucket, and search up... */
439         for (b = find_free_head(tdb, start_b);
440              b < TDB_FREE_BUCKETS;
441              b = find_free_head(tdb, b + 1)) {
442                 /* Try getting one from list. */
443                 off = lock_and_alloc(tdb, tdb->flist_off,
444                                      b, keylen, datalen, want_extra,
445                                      hashlow);
446                 if (off == TDB_OFF_ERR)
447                         return TDB_OFF_ERR;
448                 if (off != 0)
449                         return off;
450                 /* Didn't work.  Try next bucket. */
451         }
452         return 0;
453 }
454
455 int set_header(struct tdb_context *tdb,
456                struct tdb_used_record *rec,
457                uint64_t keylen, uint64_t datalen,
458                uint64_t actuallen, unsigned hashlow)
459 {
460         uint64_t keybits = (fls64(keylen) + 1) / 2;
461
462         /* Use bottom bits of hash, so it's independent of hash table size. */
463         rec->magic_and_meta = (hashlow & ((1 << 11)-1))
464                 | ((actuallen - (keylen + datalen)) << 11)
465                 | (keybits << 43)
466                 | (TDB_MAGIC << 48);
467         rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
468
469         /* Encoding can fail on big values. */
470         if (rec_key_length(rec) != keylen
471             || rec_data_length(rec) != datalen
472             || rec_extra_padding(rec) != actuallen - (keylen + datalen)) {
473                 tdb->ecode = TDB_ERR_IO;
474                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
475                          "Could not encode k=%llu,d=%llu,a=%llu\n",
476                          (long long)keylen, (long long)datalen,
477                          (long long)actuallen);
478                 return -1;
479         }
480         return 0;
481 }
482
483 /* Expand the database. */
484 static int tdb_expand(struct tdb_context *tdb, tdb_len_t size)
485 {
486         uint64_t old_size;
487         tdb_len_t wanted;
488
489         /* We need room for the record header too. */
490         wanted = sizeof(struct tdb_used_record) + size;
491
492         /* Only one person can expand file at a time. */
493         if (tdb_lock_expand(tdb, F_WRLCK) != 0)
494                 return -1;
495
496         /* Someone else may have expanded the file, so retry. */
497         old_size = tdb->map_size;
498         tdb->methods->oob(tdb, tdb->map_size + 1, true);
499         if (tdb->map_size != old_size) {
500                 tdb_unlock_expand(tdb, F_WRLCK);
501                 return 0;
502         }
503
504         if (tdb->methods->expand_file(tdb, wanted*TDB_EXTENSION_FACTOR) == -1) {
505                 tdb_unlock_expand(tdb, F_WRLCK);
506                 return -1;
507         }
508
509         /* We need to drop this lock before adding free record. */
510         tdb_unlock_expand(tdb, F_WRLCK);
511
512         return add_free_record(tdb, old_size, wanted * TDB_EXTENSION_FACTOR);
513 }
514
515 /* This won't fail: it will expand the database if it has to. */
516 tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
517                 uint64_t hash, bool growing)
518 {
519         tdb_off_t off;
520
521         /* We can't hold pointers during this: we could unmap! */
522         assert(!tdb->direct_access);
523
524         for (;;) {
525                 off = get_free(tdb, keylen, datalen, growing, hash);
526                 if (likely(off != 0))
527                         break;
528
529                 if (tdb_expand(tdb, adjust_size(keylen, datalen)))
530                         return TDB_OFF_ERR;
531         }
532
533         return off;
534 }