]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/tdb.c
tdb2: allow nesting of read locks on top of write locks.
[ccan] / ccan / tdb2 / tdb.c
1 #include "private.h"
2 #include <ccan/tdb2/tdb2.h>
3 #include <ccan/build_assert/build_assert.h>
4 #include <ccan/likely/likely.h>
5 #include <assert.h>
6
7 /* The null return. */
8 struct tdb_data tdb_null = { .dptr = NULL, .dsize = 0 };
9
10 /* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
11 static struct tdb_context *tdbs = NULL;
12
13 PRINTF_FMT(4, 5) static void
14 null_log_fn(struct tdb_context *tdb,
15             enum tdb_debug_level level, void *priv,
16             const char *fmt, ...)
17 {
18 }
19
20 static bool tdb_already_open(dev_t device, ino_t ino)
21 {
22         struct tdb_context *i;
23         
24         for (i = tdbs; i; i = i->next) {
25                 if (i->device == device && i->inode == ino) {
26                         return true;
27                 }
28         }
29
30         return false;
31 }
32
33 static uint64_t random_number(struct tdb_context *tdb)
34 {
35         int fd;
36         uint64_t ret = 0;
37         struct timeval now;
38
39         fd = open("/dev/urandom", O_RDONLY);
40         if (fd >= 0) {
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");
44                         close(fd);
45                         return ret;
46                 }
47                 close(fd);
48         }
49         /* FIXME: Untested!  Based on Wikipedia protocol description! */
50         fd = open("/dev/egd-pool", O_RDWR);
51         if (fd >= 0) {
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));
57                         if (r > 1) {
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)) {
65                                         close(fd);
66                                         return ret;
67                                 }
68                         }
69                 }
70                 close(fd);
71         }
72
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");
78         return ret;
79 }
80
81 struct new_database {
82         struct tdb_header hdr;
83         struct tdb_freelist flist;
84 };
85
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)
90 {
91         /* We make it up in memory, then write it out if not internal */
92         struct new_database newdb;
93         unsigned int magic_len;
94
95         /* Fill in the header */
96         newdb.hdr.version = TDB_VERSION;
97         if (seed)
98                 newdb.hdr.hash_seed = seed->seed;
99         else
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),
104                                          newdb.hdr.hash_seed,
105                                          tdb->hash_priv);
106         memset(newdb.hdr.reserved, 0, sizeof(newdb.hdr.reserved));
107         /* Initial hashes are empty. */
108         memset(newdb.hdr.hashtable, 0, sizeof(newdb.hdr.hashtable));
109
110         /* Free is empty. */
111         newdb.hdr.free_list = offsetof(struct new_database, flist);
112         memset(&newdb.flist, 0, sizeof(newdb.flist));
113         set_header(NULL, &newdb.flist.hdr, 0,
114                    sizeof(newdb.flist) - sizeof(newdb.flist.hdr),
115                    sizeof(newdb.flist) - sizeof(newdb.flist.hdr), 1);
116
117         /* Magic food */
118         memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
119         strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
120
121         /* This creates an endian-converted database, as if read from disk */
122         magic_len = sizeof(newdb.hdr.magic_food);
123         tdb_convert(tdb,
124                     (char *)&newdb.hdr + magic_len, sizeof(newdb) - magic_len);
125
126         *hdr = newdb.hdr;
127
128         if (tdb->flags & TDB_INTERNAL) {
129                 tdb->map_size = sizeof(newdb);
130                 tdb->map_ptr = malloc(tdb->map_size);
131                 if (!tdb->map_ptr) {
132                         tdb->ecode = TDB_ERR_OOM;
133                         return -1;
134                 }
135                 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
136                 return 0;
137         }
138         if (lseek(tdb->fd, 0, SEEK_SET) == -1)
139                 return -1;
140
141         if (ftruncate(tdb->fd, 0) == -1)
142                 return -1;
143
144         if (!tdb_pwrite_all(tdb->fd, &newdb, sizeof(newdb), 0)) {
145                 tdb->ecode = TDB_ERR_IO;
146                 return -1;
147         }
148         return 0;
149 }
150
151 struct tdb_context *tdb_open(const char *name, int tdb_flags,
152                              int open_flags, mode_t mode,
153                              union tdb_attribute *attr)
154 {
155         struct tdb_context *tdb;
156         struct stat st;
157         int save_errno;
158         uint64_t hash_test;
159         unsigned v;
160         struct tdb_header hdr;
161         struct tdb_attribute_seed *seed = NULL;
162
163         tdb = malloc(sizeof(*tdb));
164         if (!tdb) {
165                 /* Can't log this */
166                 errno = ENOMEM;
167                 goto fail;
168         }
169         tdb->name = NULL;
170         tdb->map_ptr = NULL;
171         tdb->direct_access = 0;
172         tdb->fd = -1;
173         tdb->map_size = sizeof(struct tdb_header);
174         tdb->ecode = TDB_SUCCESS;
175         tdb->flags = tdb_flags;
176         tdb->log = null_log_fn;
177         tdb->log_priv = NULL;
178         tdb->transaction = NULL;
179         tdb_hash_init(tdb);
180         tdb_io_init(tdb);
181         tdb_lock_init(tdb);
182
183         while (attr) {
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;
188                         break;
189                 case TDB_ATTRIBUTE_HASH:
190                         tdb->khash = attr->hash.hash_fn;
191                         tdb->hash_priv = attr->hash.hash_private;
192                         break;
193                 case TDB_ATTRIBUTE_SEED:
194                         seed = &attr->seed;
195                         break;
196                 default:
197                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
198                                  "tdb_open: unknown attribute type %u\n",
199                                  attr->base.attr);
200                         errno = EINVAL;
201                         goto fail;
202                 }
203                 attr = attr->base.next;
204         }
205
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);
209                 errno = EINVAL;
210                 goto fail;
211         }
212
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;
218         } else {
219                 tdb->read_only = false;
220                 tdb->mmap_flags = PROT_READ | PROT_WRITE;
221         }
222
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!");
229                         goto fail;
230                 }
231                 tdb_convert(tdb, &hdr.hash_seed, sizeof(hdr.hash_seed));
232                 tdb->hash_seed = hdr.hash_seed;
233                 tdb_flist_init(tdb);
234                 return tdb;
235         }
236
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) */
242         }
243
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);
247
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 */
254         }
255
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) {
260                         if (errno == 0) {
261                                 errno = EIO; /* ie bad format or something */
262                         }
263                         goto fail;
264                 }
265         } else if (hdr.version != TDB_VERSION) {
266                 if (hdr.version == bswap_64(TDB_VERSION))
267                         tdb->flags |= TDB_CONVERT;
268                 else {
269                         /* wrong version */
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);
273                         errno = EIO;
274                         goto fail;
275                 }
276         }
277
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",
286                          name);
287                 errno = EIO;
288                 goto fail;
289         }
290
291         if (fstat(tdb->fd, &st) == -1)
292                 goto fail;
293
294         /* Is it already in the open list?  If so, fail. */
295         if (tdb_already_open(st.st_dev, st.st_ino)) {
296                 /* FIXME */
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);
300                 errno = EBUSY;
301                 goto fail;
302         }
303
304         tdb->name = strdup(name);
305         if (!tdb->name) {
306                 errno = ENOMEM;
307                 goto fail;
308         }
309
310         tdb->device = st.st_dev;
311         tdb->inode = st.st_ino;
312         tdb_unlock_open(tdb);
313
314         /* This make sure we have current map_size and mmap. */
315         tdb->methods->oob(tdb, tdb->map_size + 1, true);
316
317         if (tdb_flist_init(tdb) == -1)
318                 goto fail;
319
320         tdb->next = tdbs;
321         tdbs = tdb;
322         return tdb;
323
324  fail:
325         save_errno = errno;
326
327         if (!tdb)
328                 return NULL;
329
330 #ifdef TDB_TRACE
331         close(tdb->tracefd);
332 #endif
333         if (tdb->map_ptr) {
334                 if (tdb->flags & TDB_INTERNAL) {
335                         free(tdb->map_ptr);
336                 } else
337                         tdb_munmap(tdb);
338         }
339         free((char *)tdb->name);
340         if (tdb->fd != -1)
341                 if (close(tdb->fd) != 0)
342                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
343                                  "tdb_open: failed to close tdb->fd"
344                                  " on error!\n");
345         free(tdb);
346         errno = save_errno;
347         return NULL;
348 }
349
350 /* FIXME: modify, don't rewrite! */
351 static int update_rec_hdr(struct tdb_context *tdb,
352                           tdb_off_t off,
353                           tdb_len_t keylen,
354                           tdb_len_t datalen,
355                           struct tdb_used_record *rec,
356                           uint64_t h)
357 {
358         uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
359
360         if (set_header(tdb, rec, keylen, datalen, keylen + dataroom, h))
361                 return -1;
362
363         return tdb_write_convert(tdb, off, rec, sizeof(*rec));
364 }
365
366 /* Returns -1 on error, 0 on OK */
367 static int replace_data(struct tdb_context *tdb,
368                         struct hash_info *h,
369                         struct tdb_data key, struct tdb_data dbuf,
370                         tdb_off_t old_off, tdb_len_t old_room,
371                         bool growing)
372 {
373         tdb_off_t new_off;
374
375         /* Allocate a new record. */
376         new_off = alloc(tdb, key.dsize, dbuf.dsize, h->h, growing);
377         if (unlikely(new_off == TDB_OFF_ERR))
378                 return -1;
379
380         /* We didn't like the existing one: remove it. */
381         if (old_off) {
382                 add_free_record(tdb, old_off,
383                                 sizeof(struct tdb_used_record)
384                                 + key.dsize + old_room);
385                 if (replace_in_hash(tdb, h, new_off) == -1)
386                         return -1;
387         } else {
388                 if (add_to_hash(tdb, h, new_off) == -1)
389                         return -1;
390         }
391
392         new_off += sizeof(struct tdb_used_record);
393         if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
394                 return -1;
395
396         new_off += key.dsize;
397         if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
398                 return -1;
399
400         /* FIXME: tdb_increment_seqnum(tdb); */
401         return 0;
402 }
403
404 int tdb_store(struct tdb_context *tdb,
405               struct tdb_data key, struct tdb_data dbuf, int flag)
406 {
407         struct hash_info h;
408         tdb_off_t off;
409         tdb_len_t old_room = 0;
410         struct tdb_used_record rec;
411         int ret;
412
413         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
414         if (unlikely(off == TDB_OFF_ERR))
415                 return -1;
416
417         /* Now we have lock on this hash bucket. */
418         if (flag == TDB_INSERT) {
419                 if (off) {
420                         tdb->ecode = TDB_ERR_EXISTS;
421                         goto fail;
422                 }
423         } else {
424                 if (off) {
425                         old_room = rec_data_length(&rec)
426                                 + rec_extra_padding(&rec);
427                         if (old_room >= dbuf.dsize) {
428                                 /* Can modify in-place.  Easy! */
429                                 if (update_rec_hdr(tdb, off,
430                                                    key.dsize, dbuf.dsize,
431                                                    &rec, h.h))
432                                         goto fail;
433                                 if (tdb->methods->write(tdb, off + sizeof(rec)
434                                                         + key.dsize,
435                                                         dbuf.dptr, dbuf.dsize))
436                                         goto fail;
437                                 tdb_unlock_hashes(tdb, h.hlock_start,
438                                                   h.hlock_range, F_WRLCK);
439                                 return 0;
440                         }
441                         /* FIXME: See if right record is free? */
442                 } else {
443                         if (flag == TDB_MODIFY) {
444                                 /* if the record doesn't exist and we
445                                    are in TDB_MODIFY mode then we should fail
446                                    the store */
447                                 tdb->ecode = TDB_ERR_NOEXIST;
448                                 goto fail;
449                         }
450                 }
451         }
452
453         /* If we didn't use the old record, this implies we're growing. */
454         ret = replace_data(tdb, &h, key, dbuf, off, old_room, off != 0);
455         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
456         return ret;
457
458 fail:
459         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
460         return -1;
461 }
462
463 int tdb_append(struct tdb_context *tdb,
464                struct tdb_data key, struct tdb_data dbuf)
465 {
466         struct hash_info h;
467         tdb_off_t off;
468         struct tdb_used_record rec;
469         tdb_len_t old_room = 0, old_dlen;
470         unsigned char *newdata;
471         struct tdb_data new_dbuf;
472         int ret;
473
474         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
475         if (unlikely(off == TDB_OFF_ERR))
476                 return -1;
477
478         if (off) {
479                 old_dlen = rec_data_length(&rec);
480                 old_room = old_dlen + rec_extra_padding(&rec);
481
482                 /* Fast path: can append in place. */
483                 if (rec_extra_padding(&rec) >= dbuf.dsize) {
484                         if (update_rec_hdr(tdb, off, key.dsize,
485                                            old_dlen + dbuf.dsize, &rec, h.h))
486                                 goto fail;
487
488                         off += sizeof(rec) + key.dsize + old_dlen;
489                         if (tdb->methods->write(tdb, off, dbuf.dptr,
490                                                 dbuf.dsize) == -1)
491                                 goto fail;
492
493                         /* FIXME: tdb_increment_seqnum(tdb); */
494                         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range,
495                                           F_WRLCK);
496                         return 0;
497                 }
498                 /* FIXME: Check right record free? */
499
500                 /* Slow path. */
501                 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
502                 if (!newdata) {
503                         tdb->ecode = TDB_ERR_OOM;
504                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
505                                  "tdb_append: cannot allocate %llu bytes!\n",
506                                  (long long)key.dsize + old_dlen + dbuf.dsize);
507                         goto fail;
508                 }
509                 if (tdb->methods->read(tdb, off + sizeof(rec) + key.dsize,
510                                        newdata, old_dlen) != 0) {
511                         free(newdata);
512                         goto fail;
513                 }
514                 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
515                 new_dbuf.dptr = newdata;
516                 new_dbuf.dsize = old_dlen + dbuf.dsize;
517         } else {
518                 newdata = NULL;
519                 new_dbuf = dbuf;
520         }
521
522         /* If they're using tdb_append(), it implies they're growing record. */
523         ret = replace_data(tdb, &h, key, new_dbuf, off, old_room, true);
524         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
525         free(newdata);
526
527         return ret;
528
529 fail:
530         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
531         return -1;
532 }
533
534 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
535 {
536         tdb_off_t off;
537         struct tdb_used_record rec;
538         struct hash_info h;
539         struct tdb_data ret;
540
541         off = find_and_lock(tdb, key, F_RDLCK, &h, &rec, NULL);
542         if (unlikely(off == TDB_OFF_ERR))
543                 return tdb_null;
544
545         if (!off) {
546                 tdb->ecode = TDB_ERR_NOEXIST;
547                 ret = tdb_null;
548         } else {
549                 ret.dsize = rec_data_length(&rec);
550                 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
551                                           ret.dsize);
552         }
553
554         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_RDLCK);
555         return ret;
556 }
557
558 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
559 {
560         tdb_off_t off;
561         struct tdb_used_record rec;
562         struct hash_info h;
563
564         off = find_and_lock(tdb, key, F_WRLCK, &h, &rec, NULL);
565         if (unlikely(off == TDB_OFF_ERR))
566                 return -1;
567
568         if (!off) {
569                 tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
570                 tdb->ecode = TDB_ERR_NOEXIST;
571                 return -1;
572         }
573
574         if (delete_from_hash(tdb, &h) == -1)
575                 goto unlock_err;
576
577         /* Free the deleted entry. */
578         if (add_free_record(tdb, off,
579                             sizeof(struct tdb_used_record)
580                             + rec_key_length(&rec)
581                             + rec_data_length(&rec)
582                             + rec_extra_padding(&rec)) != 0)
583                 goto unlock_err;
584
585         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
586         return 0;
587
588 unlock_err:
589         tdb_unlock_hashes(tdb, h.hlock_start, h.hlock_range, F_WRLCK);
590         return -1;
591 }
592
593 int tdb_close(struct tdb_context *tdb)
594 {
595         struct tdb_context **i;
596         int ret = 0;
597
598         /* FIXME:
599         if (tdb->transaction) {
600                 tdb_transaction_cancel(tdb);
601         }
602         */
603         tdb_trace(tdb, "tdb_close");
604
605         if (tdb->map_ptr) {
606                 if (tdb->flags & TDB_INTERNAL)
607                         free(tdb->map_ptr);
608                 else
609                         tdb_munmap(tdb);
610         }
611         free((char *)tdb->name);
612         if (tdb->fd != -1) {
613                 ret = close(tdb->fd);
614                 tdb->fd = -1;
615         }
616         free(tdb->lockrecs);
617
618         /* Remove from contexts list */
619         for (i = &tdbs; *i; i = &(*i)->next) {
620                 if (*i == tdb) {
621                         *i = tdb->next;
622                         break;
623                 }
624         }
625
626 #ifdef TDB_TRACE
627         close(tdb->tracefd);
628 #endif
629         free(tdb);
630
631         return ret;
632 }
633
634 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
635 {
636         return tdb->ecode;
637 }
638
639 const char *tdb_errorstr(struct tdb_context *tdb)
640 {
641         /* Gcc warns if you miss a case in the switch, so use that. */
642         switch (tdb->ecode) {
643         case TDB_SUCCESS: return "Success";
644         case TDB_ERR_CORRUPT: return "Corrupt database";
645         case TDB_ERR_IO: return "IO Error";
646         case TDB_ERR_LOCK: return "Locking error";
647         case TDB_ERR_OOM: return "Out of memory";
648         case TDB_ERR_EXISTS: return "Record exists";
649         case TDB_ERR_NESTING: return "Transaction already started";
650         case TDB_ERR_EINVAL: return "Invalid parameter";
651         case TDB_ERR_NOEXIST: return "Record does not exist";
652         case TDB_ERR_RDONLY: return "write not permitted";
653         }
654         return "Invalid error code";
655 }