2 #include <ccan/tdb2/tdb2.h>
3 #include <ccan/build_assert/build_assert.h>
4 #include <ccan/likely/likely.h>
8 struct tdb_data tdb_null = { .dptr = NULL, .dsize = 0 };
10 /* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
11 static struct tdb_context *tdbs = NULL;
13 PRINTF_ATTRIBUTE(4, 5) static void
14 null_log_fn(struct tdb_context *tdb,
15 enum tdb_debug_level level, void *priv,
20 static bool tdb_already_open(dev_t device, ino_t ino)
22 struct tdb_context *i;
24 for (i = tdbs; i; i = i->next) {
25 if (i->device == device && i->inode == ino) {
33 static uint64_t random_number(struct tdb_context *tdb)
39 fd = open("/dev/urandom", O_RDONLY);
41 if (tdb_read_all(fd, &ret, sizeof(ret))) {
42 tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
43 "tdb_open: random from /dev/urandom\n");
49 /* FIXME: Untested! Based on Wikipedia protocol description! */
50 fd = open("/dev/egd-pool", O_RDWR);
52 /* Command is 1, next byte is size we want to read. */
53 char cmd[2] = { 1, sizeof(uint64_t) };
54 if (write(fd, cmd, sizeof(cmd)) == sizeof(cmd)) {
55 char reply[1 + sizeof(uint64_t)];
56 int r = read(fd, reply, sizeof(reply));
58 tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
59 "tdb_open: %u random bytes from"
60 " /dev/egd-pool\n", r-1);
61 /* Copy at least some bytes. */
62 memcpy(&ret, reply+1, r - 1);
63 if (reply[0] == sizeof(uint64_t)
64 && r == sizeof(reply)) {
73 /* Fallback: pid and time. */
74 gettimeofday(&now, NULL);
75 ret = getpid() * 100132289ULL + now.tv_sec * 1000000ULL + now.tv_usec;
76 tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
77 "tdb_open: random from getpid and time\n");
82 struct tdb_header hdr;
83 /* Initial free zone. */
84 struct free_zone_header zhdr;
85 tdb_off_t free[BUCKETS_FOR_ZONE(INITIAL_ZONE_BITS) + 1];
86 struct tdb_free_record frec;
87 /* Rest up to 1 << INITIAL_ZONE_BITS is empty. */
88 char space[(1 << INITIAL_ZONE_BITS)
89 - sizeof(struct free_zone_header)
90 - sizeof(tdb_off_t) * (BUCKETS_FOR_ZONE(INITIAL_ZONE_BITS)+1)
91 - sizeof(struct tdb_free_record)];
93 /* Don't count final padding! */
96 /* initialise a new database */
97 static int tdb_new_database(struct tdb_context *tdb, struct tdb_header *hdr)
99 /* We make it up in memory, then write it out if not internal */
100 struct new_database newdb;
101 unsigned int bucket, magic_len, dbsize;
103 /* Don't want any extra padding! */
104 dbsize = offsetof(struct new_database, tailer) + sizeof(newdb.tailer);
106 /* Fill in the header */
107 newdb.hdr.version = TDB_VERSION;
108 newdb.hdr.hash_seed = random_number(tdb);
109 newdb.hdr.hash_test = TDB_HASH_MAGIC;
110 newdb.hdr.hash_test = tdb->khash(&newdb.hdr.hash_test,
111 sizeof(newdb.hdr.hash_test),
114 memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
115 /* Initial hashes are empty. */
116 memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
118 /* Free is mostly empty... */
119 newdb.zhdr.zone_bits = INITIAL_ZONE_BITS;
120 memset(newdb.free, 0, sizeof(newdb.free));
122 /* Create the single free entry. */
123 newdb.frec.magic_and_meta = TDB_FREE_MAGIC | INITIAL_ZONE_BITS;
124 newdb.frec.data_len = (sizeof(newdb.frec)
125 - sizeof(struct tdb_used_record)
126 + sizeof(newdb.space));
128 /* Add it to the correct bucket. */
129 bucket = size_to_bucket(INITIAL_ZONE_BITS, newdb.frec.data_len);
130 newdb.free[bucket] = offsetof(struct new_database, frec);
131 newdb.frec.next = newdb.frec.prev = 0;
133 /* Clear free space to keep valgrind happy, and avoid leaking stack. */
134 memset(newdb.space, 0, sizeof(newdb.space));
136 /* Tailer contains maximum number of free_zone bits. */
137 newdb.tailer = INITIAL_ZONE_BITS;
140 memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
141 strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
143 /* This creates an endian-converted database, as if read from disk */
144 magic_len = sizeof(newdb.hdr.magic_food);
146 (char *)&newdb.hdr + magic_len,
147 offsetof(struct new_database, space) - magic_len);
151 if (tdb->flags & TDB_INTERNAL) {
152 tdb->map_size = dbsize;
153 tdb->map_ptr = malloc(tdb->map_size);
155 tdb->ecode = TDB_ERR_OOM;
158 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
161 if (lseek(tdb->fd, 0, SEEK_SET) == -1)
164 if (ftruncate(tdb->fd, 0) == -1)
167 if (!tdb_pwrite_all(tdb->fd, &newdb, dbsize, 0)) {
168 tdb->ecode = TDB_ERR_IO;
174 struct tdb_context *tdb_open(const char *name, int tdb_flags,
175 int open_flags, mode_t mode,
176 union tdb_attribute *attr)
178 struct tdb_context *tdb;
183 struct tdb_header hdr;
185 tdb = malloc(sizeof(*tdb));
193 tdb->direct_access = 0;
195 tdb->map_size = sizeof(struct tdb_header);
196 tdb->ecode = TDB_SUCCESS;
197 tdb->flags = tdb_flags;
198 tdb->log = null_log_fn;
199 tdb->log_priv = NULL;
200 tdb->transaction = NULL;
202 /* last_zone will be set below. */
207 switch (attr->base.attr) {
208 case TDB_ATTRIBUTE_LOG:
209 tdb->log = attr->log.log_fn;
210 tdb->log_priv = attr->log.log_private;
212 case TDB_ATTRIBUTE_HASH:
213 tdb->khash = attr->hash.hash_fn;
214 tdb->hash_priv = attr->hash.hash_private;
217 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
218 "tdb_open: unknown attribute type %u\n",
223 attr = attr->base.next;
226 if ((open_flags & O_ACCMODE) == O_WRONLY) {
227 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
228 "tdb_open: can't open tdb %s write-only\n", name);
233 if ((open_flags & O_ACCMODE) == O_RDONLY) {
234 tdb->read_only = true;
235 /* read only databases don't do locking */
236 tdb->flags |= TDB_NOLOCK;
237 tdb->mmap_flags = PROT_READ;
239 tdb->read_only = false;
240 tdb->mmap_flags = PROT_READ | PROT_WRITE;
243 /* internal databases don't need any of the rest. */
244 if (tdb->flags & TDB_INTERNAL) {
245 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
246 if (tdb_new_database(tdb, &hdr) != 0) {
247 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
248 "tdb_open: tdb_new_database failed!");
251 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
252 tdb->hash_seed = hdr.hash_seed;
257 if ((tdb->fd = open(name, open_flags, mode)) == -1) {
258 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
259 "tdb_open: could not open file %s: %s\n",
260 name, strerror(errno));
261 goto fail; /* errno set by open(2) */
264 /* on exec, don't inherit the fd */
265 v = fcntl(tdb->fd, F_GETFD, 0);
266 fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
268 /* ensure there is only one process initialising at once */
269 if (tdb_lock_open(tdb) == -1) {
270 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
271 "tdb_open: failed to get open lock on %s: %s\n",
272 name, strerror(errno));
273 goto fail; /* errno set by tdb_brlock */
276 if (!tdb_pread_all(tdb->fd, &hdr, sizeof(hdr), 0)
277 || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
278 if (!(open_flags & O_CREAT) || tdb_new_database(tdb, &hdr) == -1) {
280 errno = EIO; /* ie bad format or something */
284 } else if (hdr.version != TDB_VERSION) {
285 if (hdr.version == bswap_64(TDB_VERSION))
286 tdb->flags |= TDB_CONVERT;
289 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
290 "tdb_open: %s is unknown version 0x%llx\n",
291 name, (long long)hdr.version);
297 tdb_convert(tdb, &hdr, sizeof(hdr));
298 tdb->hash_seed = hdr.hash_seed;
299 hash_test = TDB_HASH_MAGIC;
300 hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
301 if (hdr.hash_test != hash_test) {
302 /* wrong hash variant */
303 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
304 "tdb_open: %s uses a different hash function\n",
310 if (fstat(tdb->fd, &st) == -1)
313 /* Is it already in the open list? If so, fail. */
314 if (tdb_already_open(st.st_dev, st.st_ino)) {
316 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
317 "tdb_open: %s (%d,%d) is already open in this process\n",
318 name, (int)st.st_dev, (int)st.st_ino);
323 tdb->name = strdup(name);
329 tdb->device = st.st_dev;
330 tdb->inode = st.st_ino;
331 tdb_unlock_open(tdb);
333 /* This make sure we have current map_size and mmap. */
334 tdb->methods->oob(tdb, tdb->map_size + 1, true);
336 /* Now we can pick a random free zone to start from. */
337 if (tdb_zone_init(tdb) == -1)
354 if (tdb->flags & TDB_INTERNAL) {
359 free((char *)tdb->name);
361 if (close(tdb->fd) != 0)
362 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
363 "tdb_open: failed to close tdb->fd"
370 /* FIXME: modify, don't rewrite! */
371 static int update_rec_hdr(struct tdb_context *tdb,
375 struct tdb_used_record *rec,
378 uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
380 if (set_header(tdb, rec, keylen, datalen, keylen + dataroom, h,
384 return tdb_write_convert(tdb, off, rec, sizeof(*rec));
387 /* Returns -1 on error, 0 on OK */
388 static int replace_data(struct tdb_context *tdb,
390 struct tdb_data key, struct tdb_data dbuf,
391 tdb_off_t old_off, tdb_len_t old_room,
397 /* Allocate a new record. */
398 new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, growing);
399 if (unlikely(new_off == TDB_OFF_ERR))
402 /* We didn't like the existing one: remove it. */
404 add_free_record(tdb, old_zone, old_off,
405 sizeof(struct tdb_used_record)
406 + key.dsize + old_room);
407 if (replace_in_hash(tdb, h, new_off) == -1)
410 if (add_to_hash(tdb, h, new_off) == -1)
414 new_off += sizeof(struct tdb_used_record);
415 if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
418 new_off += key.dsize;
419 if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
422 /* FIXME: tdb_increment_seqnum(tdb); */
426 int tdb_store(struct tdb_context *tdb,
427 struct tdb_data key, struct tdb_data dbuf, int flag)
431 tdb_len_t old_room = 0;
432 struct tdb_used_record rec;
435 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
436 if (unlikely(off == TDB_OFF_ERR))
439 /* Now we have lock on this hash bucket. */
440 if (flag == TDB_INSERT) {
442 tdb->ecode = TDB_ERR_EXISTS;
447 old_room = rec_data_length(&rec)
448 + rec_extra_padding(&rec);
449 if (old_room >= dbuf.dsize) {
450 /* Can modify in-place. Easy! */
451 if (update_rec_hdr(tdb, off,
452 key.dsize, dbuf.dsize,
455 if (tdb->methods->write(tdb, off + sizeof(rec)
457 dbuf.dptr, dbuf.dsize))
459 tdb_unlock_hashes(tdb, h.hlock_start,
460 h.hlock_range, F_WRLCK);
463 /* FIXME: See if right record is free? */
465 if (flag == TDB_MODIFY) {
466 /* if the record doesn't exist and we
467 are in TDB_MODIFY mode then we should fail
469 tdb->ecode = TDB_ERR_NOEXIST;
475 /* If we didn't use the old record, this implies we're growing. */
476 ret = replace_data(tdb, &h, key, dbuf, off, old_room,
477 rec_zone_bits(&rec), off != 0);
478 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
482 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
486 int tdb_append(struct tdb_context *tdb,
487 struct tdb_data key, struct tdb_data dbuf)
491 struct tdb_used_record rec;
492 tdb_len_t old_room = 0, old_dlen;
493 unsigned char *newdata;
494 struct tdb_data new_dbuf;
497 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
498 if (unlikely(off == TDB_OFF_ERR))
502 old_dlen = rec_data_length(&rec);
503 old_room = old_dlen + rec_extra_padding(&rec);
505 /* Fast path: can append in place. */
506 if (rec_extra_padding(&rec) >= dbuf.dsize) {
507 if (update_rec_hdr(tdb, off, key.dsize,
508 old_dlen + dbuf.dsize, &rec, h.h))
511 off += sizeof(rec) + key.dsize + old_dlen;
512 if (tdb->methods->write(tdb, off, dbuf.dptr,
516 /* FIXME: tdb_increment_seqnum(tdb); */
517 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
521 /* FIXME: Check right record free? */
524 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
526 tdb->ecode = TDB_ERR_OOM;
527 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
528 "tdb_append: cannot allocate %llu bytes!\n",
529 (long long)key.dsize + old_dlen + dbuf.dsize);
532 if (tdb->methods->read(tdb, off + sizeof(rec) + key.dsize,
533 newdata, old_dlen) != 0) {
537 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
538 new_dbuf.dptr = newdata;
539 new_dbuf.dsize = old_dlen + dbuf.dsize;
545 /* If they're using tdb_append(), it implies they're growing record. */
546 ret = replace_data(tdb, &h, key, new_dbuf, off,
547 old_room, rec_zone_bits(&rec), true);
548 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
554 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
558 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
561 struct tdb_used_record rec;
565 off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
566 if (unlikely(off == TDB_OFF_ERR))
570 tdb->ecode = TDB_ERR_NOEXIST;
573 ret.dsize = rec_data_length(&rec);
574 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
578 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
582 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
585 struct tdb_used_record rec;
588 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
589 if (unlikely(off == TDB_OFF_ERR))
593 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
594 tdb->ecode = TDB_ERR_NOEXIST;
598 if (delete_from_hash(tdb, &h) == -1)
601 /* Free the deleted entry. */
602 if (add_free_record(tdb, rec_zone_bits(&rec), off,
603 sizeof(struct tdb_used_record)
604 + rec_key_length(&rec)
605 + rec_data_length(&rec)
606 + rec_extra_padding(&rec)) != 0)
609 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
613 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
617 int tdb_close(struct tdb_context *tdb)
619 struct tdb_context **i;
623 if (tdb->transaction) {
624 tdb_transaction_cancel(tdb);
627 tdb_trace(tdb, "tdb_close");
630 if (tdb->flags & TDB_INTERNAL)
635 free((char *)tdb->name);
637 ret = close(tdb->fd);
642 /* Remove from contexts list */
643 for (i = &tdbs; *i; i = &(*i)->next) {
658 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
663 const char *tdb_errorstr(struct tdb_context *tdb)
665 /* Gcc warns if you miss a case in the switch, so use that. */
666 switch (tdb->ecode) {
667 case TDB_SUCCESS: return "Success";
668 case TDB_ERR_CORRUPT: return "Corrupt database";
669 case TDB_ERR_IO: return "IO Error";
670 case TDB_ERR_LOCK: return "Locking error";
671 case TDB_ERR_OOM: return "Out of memory";
672 case TDB_ERR_EXISTS: return "Record exists";
673 case TDB_ERR_NESTING: return "Transaction already started";
674 case TDB_ERR_EINVAL: return "Invalid parameter";
675 case TDB_ERR_NOEXIST: return "Record does not exist";
676 case TDB_ERR_RDONLY: return "write not permitted";
678 return "Invalid error code";