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 /* Initial free zone. */
84 struct free_zone_header zhdr;
85 tdb_off_t free[BUCKETS_FOR_ZONE(INITIAL_ZONE_BITS) + 1];
88 /* initialise a new database */
89 static int tdb_new_database(struct tdb_context *tdb,
90 struct tdb_attribute_seed *seed,
91 struct tdb_header *hdr)
93 /* We make it up in memory, then write it out if not internal */
94 struct new_database newdb;
95 unsigned int magic_len;
97 /* Fill in the header */
98 newdb.hdr.version = TDB_VERSION;
100 newdb.hdr.hash_seed = seed->seed;
102 newdb.hdr.hash_seed = random_number(tdb);
103 newdb.hdr.hash_test = TDB_HASH_MAGIC;
104 newdb.hdr.hash_test = tdb->khash(&newdb.hdr.hash_test,
105 sizeof(newdb.hdr.hash_test),
108 memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
109 /* Initial hashes are empty. */
110 memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
113 newdb.zhdr.zone_bits = INITIAL_ZONE_BITS;
114 memset(newdb.free, 0, sizeof(newdb.free));
117 memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
118 strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
120 /* This creates an endian-converted database, as if read from disk */
121 magic_len = sizeof(newdb.hdr.magic_food);
123 (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
127 if (tdb->flags & TDB_INTERNAL) {
128 tdb->map_size = sizeof(newdb);
129 tdb->map_ptr = malloc(tdb->map_size);
131 tdb->ecode = TDB_ERR_OOM;
134 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
137 if (lseek(tdb->fd, 0, SEEK_SET) == -1)
140 if (ftruncate(tdb->fd, 0) == -1)
143 if (!tdb_pwrite_all(tdb->fd, &newdb, sizeof(newdb), 0)) {
144 tdb->ecode = TDB_ERR_IO;
150 struct tdb_context *tdb_open(const char *name, int tdb_flags,
151 int open_flags, mode_t mode,
152 union tdb_attribute *attr)
154 struct tdb_context *tdb;
159 struct tdb_header hdr;
160 struct tdb_attribute_seed *seed = NULL;
162 tdb = malloc(sizeof(*tdb));
170 tdb->direct_access = 0;
172 tdb->map_size = sizeof(struct tdb_header);
173 tdb->ecode = TDB_SUCCESS;
174 tdb->flags = tdb_flags;
175 tdb->log = null_log_fn;
176 tdb->log_priv = NULL;
177 tdb->transaction = NULL;
179 /* last_zone will be set below. */
184 switch (attr->base.attr) {
185 case TDB_ATTRIBUTE_LOG:
186 tdb->log = attr->log.log_fn;
187 tdb->log_priv = attr->log.log_private;
189 case TDB_ATTRIBUTE_HASH:
190 tdb->khash = attr->hash.hash_fn;
191 tdb->hash_priv = attr->hash.hash_private;
193 case TDB_ATTRIBUTE_SEED:
197 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
198 "tdb_open: unknown attribute type %u\n",
203 attr = attr->base.next;
206 if ((open_flags & O_ACCMODE) == O_WRONLY) {
207 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
208 "tdb_open: can't open tdb %s write-only\n", name);
213 if ((open_flags & O_ACCMODE) == O_RDONLY) {
214 tdb->read_only = true;
215 /* read only databases don't do locking */
216 tdb->flags |= TDB_NOLOCK;
217 tdb->mmap_flags = PROT_READ;
219 tdb->read_only = false;
220 tdb->mmap_flags = PROT_READ | PROT_WRITE;
223 /* internal databases don't need any of the rest. */
224 if (tdb->flags & TDB_INTERNAL) {
225 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
226 if (tdb_new_database(tdb, seed, &hdr) != 0) {
227 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
228 "tdb_open: tdb_new_database failed!");
231 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
232 tdb->hash_seed = hdr.hash_seed;
237 if ((tdb->fd = open(name, open_flags, mode)) == -1) {
238 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
239 "tdb_open: could not open file %s: %s\n",
240 name, strerror(errno));
241 goto fail; /* errno set by open(2) */
244 /* on exec, don't inherit the fd */
245 v = fcntl(tdb->fd, F_GETFD, 0);
246 fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
248 /* ensure there is only one process initialising at once */
249 if (tdb_lock_open(tdb) == -1) {
250 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
251 "tdb_open: failed to get open lock on %s: %s\n",
252 name, strerror(errno));
253 goto fail; /* errno set by tdb_brlock */
256 if (!tdb_pread_all(tdb->fd, &hdr, sizeof(hdr), 0)
257 || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
258 if (!(open_flags & O_CREAT)
259 || tdb_new_database(tdb, seed, &hdr) == -1) {
261 errno = EIO; /* ie bad format or something */
265 } else if (hdr.version != TDB_VERSION) {
266 if (hdr.version == bswap_64(TDB_VERSION))
267 tdb->flags |= TDB_CONVERT;
270 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
271 "tdb_open: %s is unknown version 0x%llx\n",
272 name, (long long)hdr.version);
278 tdb_convert(tdb, &hdr, sizeof(hdr));
279 tdb->hash_seed = hdr.hash_seed;
280 hash_test = TDB_HASH_MAGIC;
281 hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
282 if (hdr.hash_test != hash_test) {
283 /* wrong hash variant */
284 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
285 "tdb_open: %s uses a different hash function\n",
291 if (fstat(tdb->fd, &st) == -1)
294 /* Is it already in the open list? If so, fail. */
295 if (tdb_already_open(st.st_dev, st.st_ino)) {
297 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
298 "tdb_open: %s (%d,%d) is already open in this process\n",
299 name, (int)st.st_dev, (int)st.st_ino);
304 tdb->name = strdup(name);
310 tdb->device = st.st_dev;
311 tdb->inode = st.st_ino;
312 tdb_unlock_open(tdb);
314 /* This make sure we have current map_size and mmap. */
315 tdb->methods->oob(tdb, tdb->map_size + 1, true);
317 /* Now we can pick a random free zone to start from. */
318 if (tdb_zone_init(tdb) == -1)
335 if (tdb->flags & TDB_INTERNAL) {
340 free((char *)tdb->name);
342 if (close(tdb->fd) != 0)
343 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
344 "tdb_open: failed to close tdb->fd"
351 /* FIXME: modify, don't rewrite! */
352 static int update_rec_hdr(struct tdb_context *tdb,
356 struct tdb_used_record *rec,
359 uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
361 if (set_header(tdb, rec, keylen, datalen, keylen + dataroom, h,
365 return tdb_write_convert(tdb, off, rec, sizeof(*rec));
368 /* Returns -1 on error, 0 on OK */
369 static int replace_data(struct tdb_context *tdb,
371 struct tdb_data key, struct tdb_data dbuf,
372 tdb_off_t old_off, tdb_len_t old_room,
378 /* Allocate a new record. */
379 new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, growing);
380 if (unlikely(new_off == TDB_OFF_ERR))
383 /* We didn't like the existing one: remove it. */
385 add_free_record(tdb, old_zone, old_off,
386 sizeof(struct tdb_used_record)
387 + key.dsize + old_room);
388 if (replace_in_hash(tdb, h, new_off) == -1)
391 if (add_to_hash(tdb, h, new_off) == -1)
395 new_off += sizeof(struct tdb_used_record);
396 if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
399 new_off += key.dsize;
400 if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
403 /* FIXME: tdb_increment_seqnum(tdb); */
407 int tdb_store(struct tdb_context *tdb,
408 struct tdb_data key, struct tdb_data dbuf, int flag)
412 tdb_len_t old_room = 0;
413 struct tdb_used_record rec;
416 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
417 if (unlikely(off == TDB_OFF_ERR))
420 /* Now we have lock on this hash bucket. */
421 if (flag == TDB_INSERT) {
423 tdb->ecode = TDB_ERR_EXISTS;
428 old_room = rec_data_length(&rec)
429 + rec_extra_padding(&rec);
430 if (old_room >= dbuf.dsize) {
431 /* Can modify in-place. Easy! */
432 if (update_rec_hdr(tdb, off,
433 key.dsize, dbuf.dsize,
436 if (tdb->methods->write(tdb, off + sizeof(rec)
438 dbuf.dptr, dbuf.dsize))
440 tdb_unlock_hashes(tdb, h.hlock_start,
441 h.hlock_range, F_WRLCK);
444 /* FIXME: See if right record is free? */
446 if (flag == TDB_MODIFY) {
447 /* if the record doesn't exist and we
448 are in TDB_MODIFY mode then we should fail
450 tdb->ecode = TDB_ERR_NOEXIST;
456 /* If we didn't use the old record, this implies we're growing. */
457 ret = replace_data(tdb, &h, key, dbuf, off, old_room,
458 rec_zone_bits(&rec), off != 0);
459 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
463 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
467 int tdb_append(struct tdb_context *tdb,
468 struct tdb_data key, struct tdb_data dbuf)
472 struct tdb_used_record rec;
473 tdb_len_t old_room = 0, old_dlen;
474 unsigned char *newdata;
475 struct tdb_data new_dbuf;
478 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
479 if (unlikely(off == TDB_OFF_ERR))
483 old_dlen = rec_data_length(&rec);
484 old_room = old_dlen + rec_extra_padding(&rec);
486 /* Fast path: can append in place. */
487 if (rec_extra_padding(&rec) >= dbuf.dsize) {
488 if (update_rec_hdr(tdb, off, key.dsize,
489 old_dlen + dbuf.dsize, &rec, h.h))
492 off += sizeof(rec) + key.dsize + old_dlen;
493 if (tdb->methods->write(tdb, off, dbuf.dptr,
497 /* FIXME: tdb_increment_seqnum(tdb); */
498 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
502 /* FIXME: Check right record free? */
505 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
507 tdb->ecode = TDB_ERR_OOM;
508 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
509 "tdb_append: cannot allocate %llu bytes!\n",
510 (long long)key.dsize + old_dlen + dbuf.dsize);
513 if (tdb->methods->read(tdb, off + sizeof(rec) + key.dsize,
514 newdata, old_dlen) != 0) {
518 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
519 new_dbuf.dptr = newdata;
520 new_dbuf.dsize = old_dlen + dbuf.dsize;
526 /* If they're using tdb_append(), it implies they're growing record. */
527 ret = replace_data(tdb, &h, key, new_dbuf, off,
528 old_room, rec_zone_bits(&rec), true);
529 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
535 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
539 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
542 struct tdb_used_record rec;
546 off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
547 if (unlikely(off == TDB_OFF_ERR))
551 tdb->ecode = TDB_ERR_NOEXIST;
554 ret.dsize = rec_data_length(&rec);
555 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
559 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
563 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
566 struct tdb_used_record rec;
569 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
570 if (unlikely(off == TDB_OFF_ERR))
574 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
575 tdb->ecode = TDB_ERR_NOEXIST;
579 if (delete_from_hash(tdb, &h) == -1)
582 /* Free the deleted entry. */
583 if (add_free_record(tdb, rec_zone_bits(&rec), off,
584 sizeof(struct tdb_used_record)
585 + rec_key_length(&rec)
586 + rec_data_length(&rec)
587 + rec_extra_padding(&rec)) != 0)
590 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
594 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
598 int tdb_close(struct tdb_context *tdb)
600 struct tdb_context **i;
604 if (tdb->transaction) {
605 tdb_transaction_cancel(tdb);
608 tdb_trace(tdb, "tdb_close");
611 if (tdb->flags & TDB_INTERNAL)
616 free((char *)tdb->name);
618 ret = close(tdb->fd);
623 /* Remove from contexts list */
624 for (i = &tdbs; *i; i = &(*i)->next) {
639 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
644 const char *tdb_errorstr(struct tdb_context *tdb)
646 /* Gcc warns if you miss a case in the switch, so use that. */
647 switch (tdb->ecode) {
648 case TDB_SUCCESS: return "Success";
649 case TDB_ERR_CORRUPT: return "Corrupt database";
650 case TDB_ERR_IO: return "IO Error";
651 case TDB_ERR_LOCK: return "Locking error";
652 case TDB_ERR_OOM: return "Out of memory";
653 case TDB_ERR_EXISTS: return "Record exists";
654 case TDB_ERR_NESTING: return "Transaction already started";
655 case TDB_ERR_EINVAL: return "Invalid parameter";
656 case TDB_ERR_NOEXIST: return "Record does not exist";
657 case TDB_ERR_RDONLY: return "write not permitted";
659 return "Invalid error code";