]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/private.h
01172732980689ba3dd62a699ded3b38580ad9a9
[ccan] / ccan / tdb2 / private.h
1 #ifndef TDB_PRIVATE_H
2 #define TDB_PRIVATE_H
3  /* 
4    Trivial Database 2: private types and prototypes
5    Copyright (C) Rusty Russell 2010
6
7    This library is free software; you can redistribute it and/or
8    modify it under the terms of the GNU Lesser General Public
9    License as published by the Free Software Foundation; either
10    version 3 of the License, or (at your option) any later version.
11
12    This library is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15    Lesser General Public License for more details.
16
17    You should have received a copy of the GNU Lesser General Public
18    License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #define _XOPEN_SOURCE 500
22 #define _FILE_OFFSET_BITS 64
23 #include <stdint.h>
24 #include <stdbool.h>
25 #include <stdlib.h>
26 #include <stddef.h>
27 #include <sys/time.h>
28 #include <sys/mman.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <stdio.h>
34 #include <utime.h>
35 #include <unistd.h>
36 #include "config.h"
37 #include <ccan/tdb2/tdb2.h>
38 #include <ccan/likely/likely.h>
39 #include <ccan/compiler/compiler.h>
40 #ifdef HAVE_BYTESWAP_H
41 #include <byteswap.h>
42 #endif
43
44 #ifndef TEST_IT
45 #define TEST_IT(cond)
46 #endif
47
48 /* #define TDB_TRACE 1 */
49
50 #ifndef __STRING
51 #define __STRING(x)    #x
52 #endif
53
54 #ifndef __STRINGSTRING
55 #define __STRINGSTRING(x) __STRING(x)
56 #endif
57
58 #ifndef __location__
59 #define __location__ __FILE__ ":" __STRINGSTRING(__LINE__)
60 #endif
61
62 typedef uint64_t tdb_len_t;
63 typedef uint64_t tdb_off_t;
64
65 #define TDB_MAGIC_FOOD "TDB file\n"
66 #define TDB_VERSION ((uint64_t)(0x26011967 + 7))
67 #define TDB_MAGIC ((uint64_t)0x1999)
68 #define TDB_FREE_MAGIC ((uint64_t)0xFE)
69 #define TDB_HASH_MAGIC (0xA1ABE11A01092008ULL)
70 #define TDB_RECOVERY_MAGIC (0xf53bc0e7ad124589ULL)
71 #define TDB_RECOVERY_INVALID_MAGIC (0x0ULL)
72
73 #define TDB_OFF_ERR ((tdb_off_t)-1)
74
75 /* Prevent others from opening the file. */
76 #define TDB_OPEN_LOCK 0
77 /* Doing a transaction. */
78 #define TDB_TRANSACTION_LOCK 1
79 /* Expanding file. */
80 #define TDB_EXPANSION_LOCK 2
81 /* Hash chain locks. */
82 #define TDB_HASH_LOCK_START 3
83
84 /* Range for hash locks. */
85 #define TDB_HASH_LOCK_RANGE_BITS 30
86 #define TDB_HASH_LOCK_RANGE (1 << TDB_HASH_LOCK_RANGE_BITS)
87
88 /* We have 1024 entries in the top level. */
89 #define TDB_TOPLEVEL_HASH_BITS 10
90 /* And 64 entries in each sub-level: thus 64 bits exactly after 9 levels. */
91 #define TDB_SUBLEVEL_HASH_BITS 6
92 /* And 8 entries in each group, ie 8 groups per sublevel. */
93 #define TDB_HASH_GROUP_BITS 3
94 /* This is currently 10: beyond this we chain. */
95 #define TDB_MAX_LEVELS (1+(64-TDB_TOPLEVEL_HASH_BITS) / TDB_SUBLEVEL_HASH_BITS)
96
97 /* Extend file by least 100 times larger than needed. */
98 #define TDB_EXTENSION_FACTOR 100
99
100 /* We steal bits from the offsets to store hash info. */
101 #define TDB_OFF_HASH_GROUP_MASK ((1ULL << TDB_HASH_GROUP_BITS) - 1)
102 /* We steal this many upper bits, giving a maximum offset of 64 exabytes. */
103 #define TDB_OFF_UPPER_STEAL 8
104 #define   TDB_OFF_UPPER_STEAL_EXTRA 7
105 /* The bit number where we store extra hash bits. */
106 #define TDB_OFF_HASH_EXTRA_BIT 57
107 #define TDB_OFF_UPPER_STEAL_SUBHASH_BIT 56
108
109 /* The bit number where we store the extra hash bits. */
110 /* Convenience mask to get actual offset. */
111 #define TDB_OFF_MASK \
112         (((1ULL << (64 - TDB_OFF_UPPER_STEAL)) - 1) - TDB_OFF_HASH_GROUP_MASK)
113
114 /* How many buckets in a free list: see size_to_bucket(). */
115 #define TDB_FREE_BUCKETS (64 - TDB_OFF_UPPER_STEAL)
116
117 /* We have to be able to fit a free record here. */
118 #define TDB_MIN_DATA_LEN        \
119         (sizeof(struct tdb_free_record) - sizeof(struct tdb_used_record))
120
121 /* Indicates this entry is not on an flist (can happen during coalescing) */
122 #define TDB_FLIST_NONE ((1ULL << TDB_OFF_UPPER_STEAL) - 1)
123
124 #if !HAVE_BSWAP_64
125 static inline uint64_t bswap_64(uint64_t x)
126 {
127         return (((x&0x000000FFULL)<<56)
128                 | ((x&0x0000FF00ULL)<<48)
129                 | ((x&0x00FF0000ULL)<<40)
130                 | ((x&0xFF000000ULL)<<32)
131                 | ((x>>8)&0xFF000000ULL)
132                 | ((x>>16)&0x00FF0000ULL)
133                 | ((x>>24)&0x0000FF00ULL)
134                 | ((x>>32)&0x000000FFULL));
135 }
136 #endif
137
138 struct tdb_used_record {
139         /* For on-disk compatibility, we avoid bitfields:
140            magic: 16,        (highest)
141            key_len_bits: 5,
142            extra_padding: 32
143            hash_bits: 11
144         */
145         uint64_t magic_and_meta;
146         /* The bottom key_len_bits*2 are key length, rest is data length. */
147         uint64_t key_and_data_len;
148 };
149
150 static inline unsigned rec_key_bits(const struct tdb_used_record *r)
151 {
152         return ((r->magic_and_meta >> 43) & ((1 << 5)-1)) * 2;
153 }
154
155 static inline uint64_t rec_key_length(const struct tdb_used_record *r)
156 {
157         return r->key_and_data_len & ((1ULL << rec_key_bits(r)) - 1);
158 }
159
160 static inline uint64_t rec_data_length(const struct tdb_used_record *r)
161 {
162         return r->key_and_data_len >> rec_key_bits(r);
163 }
164
165 static inline uint64_t rec_extra_padding(const struct tdb_used_record *r)
166 {
167         return (r->magic_and_meta >> 11) & 0xFFFFFFFF;
168 }
169
170 static inline uint32_t rec_hash(const struct tdb_used_record *r)
171 {
172         return r->magic_and_meta & ((1 << 11) - 1);
173 }
174
175 static inline uint16_t rec_magic(const struct tdb_used_record *r)
176 {
177         return (r->magic_and_meta >> 48);
178 }
179
180 struct tdb_free_record {
181         uint64_t magic_and_prev; /* TDB_OFF_UPPER_STEAL bits magic, then prev */
182         uint64_t flist_and_len; /* Len not counting these two fields. */
183         /* This is why the minimum record size is 8 bytes.  */
184         uint64_t next;
185 };
186
187 static inline uint64_t frec_prev(const struct tdb_free_record *f)
188 {
189         return f->magic_and_prev & ((1ULL << (64 - TDB_OFF_UPPER_STEAL)) - 1);
190 }
191
192 static inline uint64_t frec_magic(const struct tdb_free_record *f)
193 {
194         return f->magic_and_prev >> (64 - TDB_OFF_UPPER_STEAL);
195 }
196
197 static inline uint64_t frec_len(const struct tdb_free_record *f)
198 {
199         return f->flist_and_len & ((1ULL << (64 - TDB_OFF_UPPER_STEAL))-1);
200 }
201
202 static inline unsigned frec_flist(const struct tdb_free_record *f)
203 {
204         return f->flist_and_len >> (64 - TDB_OFF_UPPER_STEAL);
205 }
206
207 struct tdb_recovery_record {
208         uint64_t magic;
209         /* Length of record. */
210         uint64_t max_len;
211         /* Length used. */
212         uint64_t len;
213         /* Old length of file before transaction. */
214         uint64_t eof;
215 };
216
217 /* If we bottom out of the subhashes, we chain. */
218 struct tdb_chain {
219         tdb_off_t rec[1 << TDB_HASH_GROUP_BITS];
220         tdb_off_t next;
221 };
222
223 /* this is stored at the front of every database */
224 struct tdb_header {
225         char magic_food[64]; /* for /etc/magic */
226         /* FIXME: Make me 32 bit? */
227         uint64_t version; /* version of the code */
228         uint64_t hash_test; /* result of hashing HASH_MAGIC. */
229         uint64_t hash_seed; /* "random" seed written at creation time. */
230         tdb_off_t free_list; /* (First) free list. */
231         tdb_off_t recovery; /* Transaction recovery area. */
232
233         tdb_off_t reserved[26];
234
235         /* Top level hash table. */
236         tdb_off_t hashtable[1ULL << TDB_TOPLEVEL_HASH_BITS];
237 };
238
239 struct tdb_freelist {
240         struct tdb_used_record hdr;
241         tdb_off_t next;
242         tdb_off_t buckets[TDB_FREE_BUCKETS];
243 };
244
245 /* Information about a particular (locked) hash entry. */
246 struct hash_info {
247         /* Full hash value of entry. */
248         uint64_t h;
249         /* Start and length of lock acquired. */
250         tdb_off_t hlock_start;
251         tdb_len_t hlock_range;
252         /* Start of hash group. */
253         tdb_off_t group_start;
254         /* Bucket we belong in. */
255         unsigned int home_bucket;
256         /* Bucket we (or an empty space) were found in. */
257         unsigned int found_bucket;
258         /* How many bits of the hash are already used. */
259         unsigned int hash_used;
260         /* Current working group. */
261         tdb_off_t group[1 << TDB_HASH_GROUP_BITS];
262 };
263
264 struct traverse_info {
265         struct traverse_level {
266                 tdb_off_t hashtable;
267                 /* We ignore groups here, and treat it as a big array. */
268                 unsigned entry;
269                 unsigned int total_buckets;
270         } levels[TDB_MAX_LEVELS + 1];
271         unsigned int num_levels;
272         unsigned int toplevel_group;
273         /* This makes delete-everything-inside-traverse work as expected. */
274         tdb_off_t prev;
275 };
276
277 enum tdb_lock_flags {
278         /* WAIT == F_SETLKW, NOWAIT == F_SETLK */
279         TDB_LOCK_NOWAIT = 0,
280         TDB_LOCK_WAIT = 1,
281         /* If set, don't log an error on failure. */
282         TDB_LOCK_PROBE = 2,
283         /* If set, don't check for recovery (used by recovery code). */
284         TDB_LOCK_NOCHECK = 4,
285 };
286
287 struct tdb_lock_type {
288         uint32_t off;
289         uint32_t count;
290         uint32_t ltype;
291 };
292
293 /* This is only needed for tdb_access_commit, but used everywhere to
294  * simplify. */
295 struct tdb_access_hdr {
296         struct tdb_access_hdr *next;
297         tdb_off_t off;
298         tdb_len_t len;
299         bool convert;
300 };
301
302 struct tdb_context {
303         /* Filename of the database. */
304         const char *name;
305
306         /* Mmap (if any), or malloc (for TDB_INTERNAL). */
307         void *map_ptr;
308
309         /* Are we accessing directly? (debugging check). */
310         int direct_access;
311
312          /* Open file descriptor (undefined for TDB_INTERNAL). */
313         int fd;
314
315         /* How much space has been mapped (<= current file size) */
316         tdb_len_t map_size;
317
318         /* Operating read-only? (Opened O_RDONLY, or in traverse_read) */
319         bool read_only;
320
321         /* mmap read only? */
322         int mmap_flags;
323
324         /* Error code for last tdb error. */
325         enum TDB_ERROR ecode; 
326
327         /* the flags passed to tdb_open, for tdb_reopen. */
328         uint32_t flags;
329
330         /* Logging function */
331         tdb_logfn_t logfn;
332         void *log_private;
333
334         /* Hash function. */
335         tdb_hashfn_t khash;
336         void *hash_priv;
337         uint64_t hash_seed;
338
339         /* Set if we are in a transaction. */
340         struct tdb_transaction *transaction;
341         
342         /* What freelist are we using? */
343         uint64_t flist_off;
344         unsigned int flist;
345
346         /* IO methods: changes for transactions. */
347         const struct tdb_methods *methods;
348
349         /* Lock information */
350         struct tdb_lock_type allrecord_lock;
351         size_t num_lockrecs;
352         struct tdb_lock_type *lockrecs;
353
354         struct tdb_attribute_stats *stats;
355
356         /* Direct access information */
357         struct tdb_access_hdr *access;
358
359         /* Single list of all TDBs, to avoid multiple opens. */
360         struct tdb_context *next;
361         dev_t device;   
362         ino_t inode;
363 };
364
365 struct tdb_methods {
366         int (*read)(struct tdb_context *, tdb_off_t, void *, tdb_len_t);
367         int (*write)(struct tdb_context *, tdb_off_t, const void *, tdb_len_t);
368         int (*oob)(struct tdb_context *, tdb_off_t, bool);
369         int (*expand_file)(struct tdb_context *, tdb_len_t);
370         void *(*direct)(struct tdb_context *, tdb_off_t, size_t, bool);
371 };
372
373 /*
374   internal prototypes
375 */
376 /* hash.c: */
377 void tdb_hash_init(struct tdb_context *tdb);
378
379 /* Hash random memory. */
380 uint64_t tdb_hash(struct tdb_context *tdb, const void *ptr, size_t len);
381
382 /* Hash on disk. */
383 uint64_t hash_record(struct tdb_context *tdb, tdb_off_t off);
384
385 /* Find and lock a hash entry (or where it would be). */
386 tdb_off_t find_and_lock(struct tdb_context *tdb,
387                         struct tdb_data key,
388                         int ltype,
389                         struct hash_info *h,
390                         struct tdb_used_record *rec,
391                         struct traverse_info *tinfo);
392
393 int replace_in_hash(struct tdb_context *tdb,
394                     struct hash_info *h,
395                     tdb_off_t new_off);
396
397 int add_to_hash(struct tdb_context *tdb, struct hash_info *h,
398                 tdb_off_t new_off);
399
400 int delete_from_hash(struct tdb_context *tdb, struct hash_info *h);
401
402 /* For tdb_check */
403 bool is_subhash(tdb_off_t val);
404
405 /* free.c: */
406 int tdb_flist_init(struct tdb_context *tdb);
407
408 /* check.c needs these to iterate through free lists. */
409 tdb_off_t first_flist(struct tdb_context *tdb);
410 tdb_off_t next_flist(struct tdb_context *tdb, tdb_off_t flist);
411
412 /* If this fails, try tdb_expand. */
413 tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
414                 uint64_t hash, bool growing);
415
416 /* Put this record in a free list. */
417 int add_free_record(struct tdb_context *tdb,
418                     tdb_off_t off, tdb_len_t len_with_header);
419
420 /* Set up header for a used record. */
421 int set_used_header(struct tdb_context *tdb,
422                     struct tdb_used_record *rec,
423                     uint64_t keylen, uint64_t datalen,
424                     uint64_t actuallen, unsigned hashlow);
425
426 /* Used by tdb_check to verify. */
427 unsigned int size_to_bucket(tdb_len_t data_len);
428 tdb_off_t bucket_off(tdb_off_t flist_off, unsigned bucket);
429
430 /* Used by tdb_summary */
431 size_t dead_space(struct tdb_context *tdb, tdb_off_t off);
432
433 /* io.c: */
434 /* Initialize tdb->methods. */
435 void tdb_io_init(struct tdb_context *tdb);
436
437 /* Convert endian of the buffer if required. */
438 void *tdb_convert(const struct tdb_context *tdb, void *buf, tdb_len_t size);
439
440 /* Unmap and try to map the tdb. */
441 void tdb_munmap(struct tdb_context *tdb);
442 void tdb_mmap(struct tdb_context *tdb);
443
444 /* Either alloc a copy, or give direct access.  Release frees or noop. */
445 const void *tdb_access_read(struct tdb_context *tdb,
446                             tdb_off_t off, tdb_len_t len, bool convert);
447 void *tdb_access_write(struct tdb_context *tdb,
448                        tdb_off_t off, tdb_len_t len, bool convert);
449
450 /* Release result of tdb_access_read/write. */
451 void tdb_access_release(struct tdb_context *tdb, const void *p);
452 /* Commit result of tdb_acces_write. */
453 int tdb_access_commit(struct tdb_context *tdb, void *p);
454
455 /* Convenience routine to get an offset. */
456 tdb_off_t tdb_read_off(struct tdb_context *tdb, tdb_off_t off);
457
458 /* Write an offset at an offset. */
459 int tdb_write_off(struct tdb_context *tdb, tdb_off_t off, tdb_off_t val);
460
461 /* Clear an ondisk area. */
462 int zero_out(struct tdb_context *tdb, tdb_off_t off, tdb_len_t len);
463
464 /* Return a non-zero offset between >= start < end in this array (or end). */
465 tdb_off_t tdb_find_nonzero_off(struct tdb_context *tdb,
466                                tdb_off_t base,
467                                uint64_t start,
468                                uint64_t end);
469
470 /* Return a zero offset in this array, or num. */
471 tdb_off_t tdb_find_zero_off(struct tdb_context *tdb, tdb_off_t off,
472                             uint64_t num);
473
474 /* Even on files, we can get partial writes due to signals. */
475 bool tdb_pwrite_all(int fd, const void *buf, size_t len, tdb_off_t off);
476 bool tdb_pread_all(int fd, void *buf, size_t len, tdb_off_t off);
477 bool tdb_read_all(int fd, void *buf, size_t len);
478
479 /* Allocate and make a copy of some offset. */
480 void *tdb_alloc_read(struct tdb_context *tdb, tdb_off_t offset, tdb_len_t len);
481
482 /* Writes a converted copy of a record. */
483 int tdb_write_convert(struct tdb_context *tdb, tdb_off_t off,
484                       const void *rec, size_t len);
485
486 /* Reads record and converts it */
487 int tdb_read_convert(struct tdb_context *tdb, tdb_off_t off,
488                      void *rec, size_t len);
489
490 /* Adds a stat, if it's in range. */
491 void add_stat_(struct tdb_context *tdb, uint64_t *stat, size_t val);
492 #define add_stat(tdb, statname, val)                                    \
493         do {                                                            \
494                 if (unlikely((tdb)->stats))                             \
495                         add_stat_((tdb), &(tdb)->stats->statname, (val)); \
496         } while (0)
497
498 /* lock.c: */
499 void tdb_lock_init(struct tdb_context *tdb);
500
501 /* Lock/unlock a range of hashes. */
502 int tdb_lock_hashes(struct tdb_context *tdb,
503                     tdb_off_t hash_lock, tdb_len_t hash_range,
504                     int ltype, enum tdb_lock_flags waitflag);
505 int tdb_unlock_hashes(struct tdb_context *tdb,
506                       tdb_off_t hash_lock,
507                       tdb_len_t hash_range, int ltype);
508
509 /* Lock/unlock a particular free bucket. */
510 int tdb_lock_free_bucket(struct tdb_context *tdb, tdb_off_t b_off,
511                          enum tdb_lock_flags waitflag);
512 void tdb_unlock_free_bucket(struct tdb_context *tdb, tdb_off_t b_off);
513
514 /* Serialize transaction start. */
515 int tdb_transaction_lock(struct tdb_context *tdb, int ltype);
516 int tdb_transaction_unlock(struct tdb_context *tdb, int ltype);
517
518 /* Do we have any hash locks (ie. via tdb_chainlock) ? */
519 bool tdb_has_hash_locks(struct tdb_context *tdb);
520
521 /* Lock entire database. */
522 int tdb_allrecord_lock(struct tdb_context *tdb, int ltype,
523                        enum tdb_lock_flags flags, bool upgradable);
524 int tdb_allrecord_unlock(struct tdb_context *tdb, int ltype);
525 int tdb_allrecord_upgrade(struct tdb_context *tdb);
526
527 /* Serialize db open. */
528 int tdb_lock_open(struct tdb_context *tdb, enum tdb_lock_flags flags);
529 void tdb_unlock_open(struct tdb_context *tdb);
530 bool tdb_has_open_lock(struct tdb_context *tdb);
531
532 /* Serialize db expand. */
533 int tdb_lock_expand(struct tdb_context *tdb, int ltype);
534 void tdb_unlock_expand(struct tdb_context *tdb, int ltype);
535 bool tdb_has_expansion_lock(struct tdb_context *tdb);
536
537 /* If it needs recovery, grab all the locks and do it. */
538 int tdb_lock_and_recover(struct tdb_context *tdb);
539
540 /* traverse.c: */
541 int first_in_hash(struct tdb_context *tdb, int ltype,
542                   struct traverse_info *tinfo,
543                   TDB_DATA *kbuf, size_t *dlen);
544 int next_in_hash(struct tdb_context *tdb, int ltype,
545                  struct traverse_info *tinfo,
546                  TDB_DATA *kbuf, size_t *dlen);
547
548 /* transaction.c: */
549 int tdb_transaction_recover(struct tdb_context *tdb);
550 bool tdb_needs_recovery(struct tdb_context *tdb);
551
552 /* tdb.c: */
553 void COLD tdb_logerr(struct tdb_context *tdb,
554                      enum TDB_ERROR ecode,
555                      enum tdb_debug_level level,
556                      const char *fmt, ...);
557
558 #ifdef TDB_TRACE
559 void tdb_trace(struct tdb_context *tdb, const char *op);
560 void tdb_trace_seqnum(struct tdb_context *tdb, uint32_t seqnum, const char *op);
561 void tdb_trace_open(struct tdb_context *tdb, const char *op,
562                     unsigned hash_size, unsigned tdb_flags, unsigned open_flags);
563 void tdb_trace_ret(struct tdb_context *tdb, const char *op, int ret);
564 void tdb_trace_retrec(struct tdb_context *tdb, const char *op, TDB_DATA ret);
565 void tdb_trace_1rec(struct tdb_context *tdb, const char *op,
566                     TDB_DATA rec);
567 void tdb_trace_1rec_ret(struct tdb_context *tdb, const char *op,
568                         TDB_DATA rec, int ret);
569 void tdb_trace_1rec_retrec(struct tdb_context *tdb, const char *op,
570                            TDB_DATA rec, TDB_DATA ret);
571 void tdb_trace_2rec_flag_ret(struct tdb_context *tdb, const char *op,
572                              TDB_DATA rec1, TDB_DATA rec2, unsigned flag,
573                              int ret);
574 void tdb_trace_2rec_retrec(struct tdb_context *tdb, const char *op,
575                            TDB_DATA rec1, TDB_DATA rec2, TDB_DATA ret);
576 #else
577 #define tdb_trace(tdb, op)
578 #define tdb_trace_seqnum(tdb, seqnum, op)
579 #define tdb_trace_open(tdb, op, hash_size, tdb_flags, open_flags)
580 #define tdb_trace_ret(tdb, op, ret)
581 #define tdb_trace_retrec(tdb, op, ret)
582 #define tdb_trace_1rec(tdb, op, rec)
583 #define tdb_trace_1rec_ret(tdb, op, rec, ret)
584 #define tdb_trace_1rec_retrec(tdb, op, rec, ret)
585 #define tdb_trace_2rec_flag_ret(tdb, op, rec1, rec2, flag, ret)
586 #define tdb_trace_2rec_retrec(tdb, op, rec1, rec2, ret)
587 #endif /* !TDB_TRACE */
588
589 #endif