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_FMT(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 struct tdb_freelist flist;
86 /* initialise a new database */
87 static int tdb_new_database(struct tdb_context *tdb,
88 struct tdb_attribute_seed *seed,
89 struct tdb_header *hdr)
91 /* We make it up in memory, then write it out if not internal */
92 struct new_database newdb;
93 unsigned int magic_len;
95 /* Fill in the header */
96 newdb.hdr.version = TDB_VERSION;
98 newdb.hdr.hash_seed = seed->seed;
100 newdb.hdr.hash_seed = random_number(tdb);
101 newdb.hdr.hash_test = TDB_HASH_MAGIC;
102 newdb.hdr.hash_test = tdb->khash(&newdb.hdr.hash_test,
103 sizeof(newdb.hdr.hash_test),
106 newdb.hdr.recovery = 0;
107 memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
108 /* Initial hashes are empty. */
109 memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
112 newdb.hdr.free_list = offsetof(struct new_database, flist);
113 memset(&newdb.flist, 0, sizeof(newdb.flist));
114 set_used_header(NULL, &newdb.flist.hdr, 0,
115 sizeof(newdb.flist) - sizeof(newdb.flist.hdr),
116 sizeof(newdb.flist) - sizeof(newdb.flist.hdr), 1);
119 memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
120 strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
122 /* This creates an endian-converted database, as if read from disk */
123 magic_len = sizeof(newdb.hdr.magic_food);
125 (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
129 if (tdb->flags & TDB_INTERNAL) {
130 tdb->map_size = sizeof(newdb);
131 tdb->map_ptr = malloc(tdb->map_size);
133 tdb->ecode = TDB_ERR_OOM;
136 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
139 if (lseek(tdb->fd, 0, SEEK_SET) == -1)
142 if (ftruncate(tdb->fd, 0) == -1)
145 if (!tdb_pwrite_all(tdb->fd, &newdb, sizeof(newdb), 0)) {
146 tdb->ecode = TDB_ERR_IO;
152 struct tdb_context *tdb_open(const char *name, int tdb_flags,
153 int open_flags, mode_t mode,
154 union tdb_attribute *attr)
156 struct tdb_context *tdb;
161 struct tdb_header hdr;
162 struct tdb_attribute_seed *seed = NULL;
164 tdb = malloc(sizeof(*tdb));
172 tdb->direct_access = 0;
174 tdb->map_size = sizeof(struct tdb_header);
175 tdb->ecode = TDB_SUCCESS;
176 tdb->flags = tdb_flags;
177 tdb->log = null_log_fn;
178 tdb->log_priv = NULL;
179 tdb->transaction = NULL;
186 switch (attr->base.attr) {
187 case TDB_ATTRIBUTE_LOG:
188 tdb->log = attr->log.log_fn;
189 tdb->log_priv = attr->log.log_private;
191 case TDB_ATTRIBUTE_HASH:
192 tdb->khash = attr->hash.hash_fn;
193 tdb->hash_priv = attr->hash.hash_private;
195 case TDB_ATTRIBUTE_SEED:
198 case TDB_ATTRIBUTE_STATS:
199 tdb->stats = &attr->stats;
200 /* They have stats we don't know about? Tell them. */
201 if (tdb->stats->size > sizeof(attr->stats))
202 tdb->stats->size = sizeof(attr->stats);
205 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
206 "tdb_open: unknown attribute type %u\n",
211 attr = attr->base.next;
214 if ((open_flags & O_ACCMODE) == O_WRONLY) {
215 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
216 "tdb_open: can't open tdb %s write-only\n", name);
221 if ((open_flags & O_ACCMODE) == O_RDONLY) {
222 tdb->read_only = true;
223 /* read only databases don't do locking */
224 tdb->flags |= TDB_NOLOCK;
225 tdb->mmap_flags = PROT_READ;
227 tdb->read_only = false;
228 tdb->mmap_flags = PROT_READ | PROT_WRITE;
231 /* internal databases don't need any of the rest. */
232 if (tdb->flags & TDB_INTERNAL) {
233 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
234 if (tdb_new_database(tdb, seed, &hdr) != 0) {
235 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
236 "tdb_open: tdb_new_database failed!");
239 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
240 tdb->hash_seed = hdr.hash_seed;
245 if ((tdb->fd = open(name, open_flags, mode)) == -1) {
246 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
247 "tdb_open: could not open file %s: %s\n",
248 name, strerror(errno));
249 goto fail; /* errno set by open(2) */
252 /* on exec, don't inherit the fd */
253 v = fcntl(tdb->fd, F_GETFD, 0);
254 fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
256 /* ensure there is only one process initialising at once */
257 if (tdb_lock_open(tdb, TDB_LOCK_WAIT|TDB_LOCK_NOCHECK) == -1) {
258 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
259 "tdb_open: failed to get open lock on %s: %s\n",
260 name, strerror(errno));
261 goto fail; /* errno set by tdb_brlock */
264 if (!tdb_pread_all(tdb->fd, &hdr, sizeof(hdr), 0)
265 || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
266 if (!(open_flags & O_CREAT)
267 || tdb_new_database(tdb, seed, &hdr) == -1) {
269 errno = EIO; /* ie bad format or something */
273 } else if (hdr.version != TDB_VERSION) {
274 if (hdr.version == bswap_64(TDB_VERSION))
275 tdb->flags |= TDB_CONVERT;
278 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
279 "tdb_open: %s is unknown version 0x%llx\n",
280 name, (long long)hdr.version);
286 tdb_convert(tdb, &hdr, sizeof(hdr));
287 tdb->hash_seed = hdr.hash_seed;
288 hash_test = TDB_HASH_MAGIC;
289 hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
290 if (hdr.hash_test != hash_test) {
291 /* wrong hash variant */
292 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
293 "tdb_open: %s uses a different hash function\n",
299 if (fstat(tdb->fd, &st) == -1)
302 /* Is it already in the open list? If so, fail. */
303 if (tdb_already_open(st.st_dev, st.st_ino)) {
305 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
306 "tdb_open: %s (%d,%d) is already open in this process\n",
307 name, (int)st.st_dev, (int)st.st_ino);
312 tdb->name = strdup(name);
318 tdb->device = st.st_dev;
319 tdb->inode = st.st_ino;
320 tdb_unlock_open(tdb);
322 /* This make sure we have current map_size and mmap. */
323 tdb->methods->oob(tdb, tdb->map_size + 1, true);
325 /* Now it's fully formed, recover if necessary. */
326 if (tdb_needs_recovery(tdb) && tdb_lock_and_recover(tdb) == -1) {
331 if (tdb_flist_init(tdb) == -1)
348 if (tdb->flags & TDB_INTERNAL) {
353 free((char *)tdb->name);
355 if (close(tdb->fd) != 0)
356 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
357 "tdb_open: failed to close tdb->fd"
364 /* FIXME: modify, don't rewrite! */
365 static int update_rec_hdr(struct tdb_context *tdb,
369 struct tdb_used_record *rec,
372 uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
374 if (set_used_header(tdb, rec, keylen, datalen, keylen + dataroom, h))
377 return tdb_write_convert(tdb, off, rec, sizeof(*rec));
380 /* Returns -1 on error, 0 on OK */
381 static int replace_data(struct tdb_context *tdb,
383 struct tdb_data key, struct tdb_data dbuf,
384 tdb_off_t old_off, tdb_len_t old_room,
389 /* Allocate a new record. */
390 new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, growing);
391 if (unlikely(new_off == TDB_OFF_ERR))
394 /* We didn't like the existing one: remove it. */
396 add_stat(tdb, frees, 1);
397 add_free_record(tdb, old_off,
398 sizeof(struct tdb_used_record)
399 + key.dsize + old_room);
400 if (replace_in_hash(tdb, h, new_off) == -1)
403 if (add_to_hash(tdb, h, new_off) == -1)
407 new_off += sizeof(struct tdb_used_record);
408 if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
411 new_off += key.dsize;
412 if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
415 /* FIXME: tdb_increment_seqnum(tdb); */
419 int tdb_store(struct tdb_context *tdb,
420 struct tdb_data key, struct tdb_data dbuf, int flag)
424 tdb_len_t old_room = 0;
425 struct tdb_used_record rec;
428 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
429 if (unlikely(off == TDB_OFF_ERR))
432 /* Now we have lock on this hash bucket. */
433 if (flag == TDB_INSERT) {
435 tdb->ecode = TDB_ERR_EXISTS;
440 old_room = rec_data_length(&rec)
441 + rec_extra_padding(&rec);
442 if (old_room >= dbuf.dsize) {
443 /* Can modify in-place. Easy! */
444 if (update_rec_hdr(tdb, off,
445 key.dsize, dbuf.dsize,
448 if (tdb->methods->write(tdb, off + sizeof(rec)
450 dbuf.dptr, dbuf.dsize))
452 tdb_unlock_hashes(tdb, h.hlock_start,
453 h.hlock_range, F_WRLCK);
456 /* FIXME: See if right record is free? */
458 if (flag == TDB_MODIFY) {
459 /* if the record doesn't exist and we
460 are in TDB_MODIFY mode then we should fail
462 tdb->ecode = TDB_ERR_NOEXIST;
468 /* If we didn't use the old record, this implies we're growing. */
469 ret = replace_data(tdb, &h, key, dbuf, off, old_room, off != 0);
470 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
474 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
478 int tdb_append(struct tdb_context *tdb,
479 struct tdb_data key, struct tdb_data dbuf)
483 struct tdb_used_record rec;
484 tdb_len_t old_room = 0, old_dlen;
485 unsigned char *newdata;
486 struct tdb_data new_dbuf;
489 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
490 if (unlikely(off == TDB_OFF_ERR))
494 old_dlen = rec_data_length(&rec);
495 old_room = old_dlen + rec_extra_padding(&rec);
497 /* Fast path: can append in place. */
498 if (rec_extra_padding(&rec) >= dbuf.dsize) {
499 if (update_rec_hdr(tdb, off, key.dsize,
500 old_dlen + dbuf.dsize, &rec, h.h))
503 off += sizeof(rec) + key.dsize + old_dlen;
504 if (tdb->methods->write(tdb, off, dbuf.dptr,
508 /* FIXME: tdb_increment_seqnum(tdb); */
509 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
513 /* FIXME: Check right record free? */
516 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
518 tdb->ecode = TDB_ERR_OOM;
519 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
520 "tdb_append: cannot allocate %llu bytes!\n",
521 (long long)key.dsize + old_dlen + dbuf.dsize);
524 if (tdb->methods->read(tdb, off + sizeof(rec) + key.dsize,
525 newdata, old_dlen) != 0) {
529 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
530 new_dbuf.dptr = newdata;
531 new_dbuf.dsize = old_dlen + dbuf.dsize;
537 /* If they're using tdb_append(), it implies they're growing record. */
538 ret = replace_data(tdb, &h, key, new_dbuf, off, old_room, true);
539 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
545 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
549 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
552 struct tdb_used_record rec;
556 off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
557 if (unlikely(off == TDB_OFF_ERR))
561 tdb->ecode = TDB_ERR_NOEXIST;
564 ret.dsize = rec_data_length(&rec);
565 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
569 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
573 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
576 struct tdb_used_record rec;
579 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
580 if (unlikely(off == TDB_OFF_ERR))
584 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
585 tdb->ecode = TDB_ERR_NOEXIST;
589 if (delete_from_hash(tdb, &h) == -1)
592 /* Free the deleted entry. */
593 add_stat(tdb, frees, 1);
594 if (add_free_record(tdb, off,
595 sizeof(struct tdb_used_record)
596 + rec_key_length(&rec)
597 + rec_data_length(&rec)
598 + rec_extra_padding(&rec)) != 0)
601 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
605 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
609 int tdb_close(struct tdb_context *tdb)
611 struct tdb_context **i;
614 tdb_trace(tdb, "tdb_close");
616 if (tdb->transaction) {
617 tdb_transaction_cancel(tdb);
621 if (tdb->flags & TDB_INTERNAL)
626 free((char *)tdb->name);
628 ret = close(tdb->fd);
633 /* Remove from contexts list */
634 for (i = &tdbs; *i; i = &(*i)->next) {
649 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
654 const char *tdb_errorstr(struct tdb_context *tdb)
656 /* Gcc warns if you miss a case in the switch, so use that. */
657 switch (tdb->ecode) {
658 case TDB_SUCCESS: return "Success";
659 case TDB_ERR_CORRUPT: return "Corrupt database";
660 case TDB_ERR_IO: return "IO Error";
661 case TDB_ERR_LOCK: return "Locking error";
662 case TDB_ERR_OOM: return "Out of memory";
663 case TDB_ERR_EXISTS: return "Record exists";
664 case TDB_ERR_NESTING: return "Transaction already started";
665 case TDB_ERR_EINVAL: return "Invalid parameter";
666 case TDB_ERR_NOEXIST: return "Record does not exist";
667 case TDB_ERR_RDONLY: return "write not permitted";
669 return "Invalid error code";