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;
238 tdb->read_only = false;
240 /* internal databases don't need any of the rest. */
241 if (tdb->flags & TDB_INTERNAL) {
242 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
243 if (tdb_new_database(tdb, &hdr) != 0) {
244 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
245 "tdb_open: tdb_new_database failed!");
248 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
249 tdb->hash_seed = hdr.hash_seed;
254 if ((tdb->fd = open(name, open_flags, mode)) == -1) {
255 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
256 "tdb_open: could not open file %s: %s\n",
257 name, strerror(errno));
258 goto fail; /* errno set by open(2) */
261 /* on exec, don't inherit the fd */
262 v = fcntl(tdb->fd, F_GETFD, 0);
263 fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
265 /* ensure there is only one process initialising at once */
266 if (tdb_lock_open(tdb) == -1) {
267 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
268 "tdb_open: failed to get open lock on %s: %s\n",
269 name, strerror(errno));
270 goto fail; /* errno set by tdb_brlock */
273 if (!tdb_pread_all(tdb->fd, &hdr, sizeof(hdr), 0)
274 || strcmp(hdr.magic_food, TDB_MAGIC_FOOD) != 0) {
275 if (!(open_flags & O_CREAT) || tdb_new_database(tdb, &hdr) == -1) {
277 errno = EIO; /* ie bad format or something */
281 } else if (hdr.version != TDB_VERSION) {
282 if (hdr.version == bswap_64(TDB_VERSION))
283 tdb->flags |= TDB_CONVERT;
286 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
287 "tdb_open: %s is unknown version 0x%llx\n",
288 name, (long long)hdr.version);
294 tdb_convert(tdb, &hdr, sizeof(hdr));
295 tdb->hash_seed = hdr.hash_seed;
296 hash_test = TDB_HASH_MAGIC;
297 hash_test = tdb_hash(tdb, &hash_test, sizeof(hash_test));
298 if (hdr.hash_test != hash_test) {
299 /* wrong hash variant */
300 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
301 "tdb_open: %s uses a different hash function\n",
307 if (fstat(tdb->fd, &st) == -1)
310 /* Is it already in the open list? If so, fail. */
311 if (tdb_already_open(st.st_dev, st.st_ino)) {
313 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
314 "tdb_open: %s (%d,%d) is already open in this process\n",
315 name, (int)st.st_dev, (int)st.st_ino);
320 tdb->name = strdup(name);
326 tdb->device = st.st_dev;
327 tdb->inode = st.st_ino;
328 tdb_unlock_open(tdb);
330 /* This make sure we have current map_size and mmap. */
331 tdb->methods->oob(tdb, tdb->map_size + 1, true);
333 /* Now we can pick a random free zone to start from. */
334 if (tdb_zone_init(tdb) == -1)
351 if (tdb->flags & TDB_INTERNAL) {
356 free((char *)tdb->name);
358 if (close(tdb->fd) != 0)
359 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
360 "tdb_open: failed to close tdb->fd"
367 /* FIXME: modify, don't rewrite! */
368 static int update_rec_hdr(struct tdb_context *tdb,
372 struct tdb_used_record *rec,
375 uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
377 if (set_header(tdb, rec, keylen, datalen, keylen + dataroom, h,
381 return tdb_write_convert(tdb, off, rec, sizeof(*rec));
384 /* Returns -1 on error, 0 on OK */
385 static int replace_data(struct tdb_context *tdb,
387 struct tdb_data key, struct tdb_data dbuf,
388 tdb_off_t old_off, tdb_len_t old_room,
394 /* Allocate a new record. */
395 new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, growing);
396 if (unlikely(new_off == TDB_OFF_ERR))
399 /* We didn't like the existing one: remove it. */
401 add_free_record(tdb, old_zone, old_off,
402 sizeof(struct tdb_used_record)
403 + key.dsize + old_room);
404 if (replace_in_hash(tdb, h, new_off) == -1)
407 if (add_to_hash(tdb, h, new_off) == -1)
411 new_off += sizeof(struct tdb_used_record);
412 if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
415 new_off += key.dsize;
416 if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
419 /* FIXME: tdb_increment_seqnum(tdb); */
423 int tdb_store(struct tdb_context *tdb,
424 struct tdb_data key, struct tdb_data dbuf, int flag)
428 tdb_len_t old_room = 0;
429 struct tdb_used_record rec;
432 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec);
433 if (unlikely(off == TDB_OFF_ERR))
436 /* Now we have lock on this hash bucket. */
437 if (flag == TDB_INSERT) {
439 tdb->ecode = TDB_ERR_EXISTS;
444 old_room = rec_data_length(&rec)
445 + rec_extra_padding(&rec);
446 if (old_room >= dbuf.dsize) {
447 /* Can modify in-place. Easy! */
448 if (update_rec_hdr(tdb, off,
449 key.dsize, dbuf.dsize,
452 if (tdb->methods->write(tdb, off + sizeof(rec)
454 dbuf.dptr, dbuf.dsize))
456 tdb_unlock_hashes(tdb, h.hlock_start,
457 h.hlock_range, F_WRLCK);
460 /* FIXME: See if right record is free? */
462 if (flag == TDB_MODIFY) {
463 /* if the record doesn't exist and we
464 are in TDB_MODIFY mode then we should fail
466 tdb->ecode = TDB_ERR_NOEXIST;
472 /* If we didn't use the old record, this implies we're growing. */
473 ret = replace_data(tdb, &h, key, dbuf, off, old_room,
474 rec_zone_bits(&rec), off != 0);
475 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
479 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
483 int tdb_append(struct tdb_context *tdb,
484 struct tdb_data key, struct tdb_data dbuf)
488 struct tdb_used_record rec;
489 tdb_len_t old_room = 0, old_dlen;
490 unsigned char *newdata;
491 struct tdb_data new_dbuf;
494 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec);
495 if (unlikely(off == TDB_OFF_ERR))
499 old_dlen = rec_data_length(&rec);
500 old_room = old_dlen + rec_extra_padding(&rec);
502 /* Fast path: can append in place. */
503 if (rec_extra_padding(&rec) >= dbuf.dsize) {
504 if (update_rec_hdr(tdb, off, key.dsize,
505 old_dlen + dbuf.dsize, &rec, h.h))
508 off += sizeof(rec) + key.dsize + old_dlen;
509 if (tdb->methods->write(tdb, off, dbuf.dptr,
513 /* FIXME: tdb_increment_seqnum(tdb); */
514 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
518 /* FIXME: Check right record free? */
521 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
523 tdb->ecode = TDB_ERR_OOM;
524 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
525 "tdb_append: cannot allocate %llu bytes!\n",
526 (long long)key.dsize + old_dlen + dbuf.dsize);
529 if (tdb->methods->read(tdb, off + sizeof(rec) + key.dsize,
530 newdata, old_dlen) != 0) {
534 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
535 new_dbuf.dptr = newdata;
536 new_dbuf.dsize = old_dlen + dbuf.dsize;
542 /* If they're using tdb_append(), it implies they're growing record. */
543 ret = replace_data(tdb, &h, key, new_dbuf, off,
544 old_room, rec_zone_bits(&rec), true);
545 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
551 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
555 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
558 struct tdb_used_record rec;
562 off = find_and_lock(tdb, key, F_RDLCK, &h, &rec);
563 if (unlikely(off == TDB_OFF_ERR))
567 tdb->ecode = TDB_ERR_NOEXIST;
570 ret.dsize = rec_data_length(&rec);
571 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
575 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
579 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
582 struct tdb_used_record rec;
585 off = find_and_lock(tdb, key, F_WRLCK, &h, &rec);
586 if (unlikely(off == TDB_OFF_ERR))
590 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
591 tdb->ecode = TDB_ERR_NOEXIST;
595 if (delete_from_hash(tdb, &h) == -1)
598 /* Free the deleted entry. */
599 if (add_free_record(tdb, rec_zone_bits(&rec), off,
600 sizeof(struct tdb_used_record)
601 + rec_key_length(&rec)
602 + rec_data_length(&rec)
603 + rec_extra_padding(&rec)) != 0)
606 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
610 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
614 int tdb_close(struct tdb_context *tdb)
616 struct tdb_context **i;
620 if (tdb->transaction) {
621 tdb_transaction_cancel(tdb);
624 tdb_trace(tdb, "tdb_close");
627 if (tdb->flags & TDB_INTERNAL)
632 free((char *)tdb->name);
634 ret = close(tdb->fd);
639 /* Remove from contexts list */
640 for (i = &tdbs; *i; i = &(*i)->next) {
655 enum TDB_ERROR tdb_error(struct tdb_context *tdb)