]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/tdb.c
tdb2: make valgrind happier.
[ccan] / ccan / tdb2 / tdb.c
1 #include "private.h"
2 #include <ccan/tdb2/tdb2.h>
3 #include <ccan/hash/hash.h>
4 #include <ccan/build_assert/build_assert.h>
5 #include <ccan/likely/likely.h>
6 #include <assert.h>
7
8 /* The null return. */
9 struct tdb_data tdb_null = { .dptr = NULL, .dsize = 0 };
10
11 /* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
12 static struct tdb_context *tdbs = NULL;
13
14 PRINTF_ATTRIBUTE(4, 5) static void
15 null_log_fn(struct tdb_context *tdb,
16             enum tdb_debug_level level, void *priv,
17             const char *fmt, ...)
18 {
19 }
20
21 /* We do a lot of work assuming our copy of the header volatile area
22  * is uptodate, and usually it is.  However, once we grab a lock, we have to
23  * re-check it. */
24 bool header_changed(struct tdb_context *tdb)
25 {
26         uint64_t gen;
27
28         if (!(tdb->flags & TDB_NOLOCK) && tdb->header_uptodate) {
29                 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
30                          "warning: header uptodate already\n");
31         }
32
33         /* We could get a partial update if we're not holding any locks. */
34         assert((tdb->flags & TDB_NOLOCK) || tdb_has_locks(tdb));
35
36         tdb->header_uptodate = true;
37         gen = tdb_read_off(tdb, offsetof(struct tdb_header, v.generation));
38         if (unlikely(gen != tdb->header.v.generation)) {
39                 tdb_read_convert(tdb, offsetof(struct tdb_header, v),
40                                  &tdb->header.v, sizeof(tdb->header.v));
41                 return true;
42         }
43         return false;
44 }
45
46 int write_header(struct tdb_context *tdb)
47 {
48         assert(tdb_read_off(tdb, offsetof(struct tdb_header, v.generation))
49                == tdb->header.v.generation);
50         tdb->header.v.generation++;
51         return tdb_write_convert(tdb, offsetof(struct tdb_header, v),
52                                  &tdb->header.v, sizeof(tdb->header.v));
53 }
54
55 static uint64_t jenkins_hash(const void *key, size_t length, uint64_t seed,
56                              void *arg)
57 {
58         return hash64_stable((const unsigned char *)key, length, seed);
59 }
60
61 uint64_t tdb_hash(struct tdb_context *tdb, const void *ptr, size_t len)
62 {
63         return tdb->khash(ptr, len, tdb->header.hash_seed, tdb->hash_priv);
64 }
65
66 static bool tdb_already_open(dev_t device, ino_t ino)
67 {
68         struct tdb_context *i;
69         
70         for (i = tdbs; i; i = i->next) {
71                 if (i->device == device && i->inode == ino) {
72                         return true;
73                 }
74         }
75
76         return false;
77 }
78
79 static uint64_t random_number(struct tdb_context *tdb)
80 {
81         int fd;
82         uint64_t ret = 0;
83         struct timeval now;
84
85         fd = open("/dev/urandom", O_RDONLY);
86         if (fd >= 0) {
87                 if (tdb_read_all(fd, &ret, sizeof(ret))) {
88                         tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
89                                  "tdb_open: random from /dev/urandom\n");
90                         close(fd);
91                         return ret;
92                 }
93                 close(fd);
94         }
95         /* FIXME: Untested!  Based on Wikipedia protocol description! */
96         fd = open("/dev/egd-pool", O_RDWR);
97         if (fd >= 0) {
98                 /* Command is 1, next byte is size we want to read. */
99                 char cmd[2] = { 1, sizeof(uint64_t) };
100                 if (write(fd, cmd, sizeof(cmd)) == sizeof(cmd)) {
101                         char reply[1 + sizeof(uint64_t)];
102                         int r = read(fd, reply, sizeof(reply));
103                         if (r > 1) {
104                                 tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
105                                          "tdb_open: %u random bytes from"
106                                          " /dev/egd-pool\n", r-1);
107                                 /* Copy at least some bytes. */
108                                 memcpy(&ret, reply+1, r - 1);
109                                 if (reply[0] == sizeof(uint64_t)
110                                     && r == sizeof(reply)) {
111                                         close(fd);
112                                         return ret;
113                                 }
114                         }
115                 }
116                 close(fd);
117         }
118
119         /* Fallback: pid and time. */
120         gettimeofday(&now, NULL);
121         ret = getpid() * 100132289ULL + now.tv_sec * 1000000ULL + now.tv_usec;
122         tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
123                  "tdb_open: random from getpid and time\n");
124         return ret;
125 }
126
127 struct new_db_head {
128         struct tdb_header hdr;
129         struct free_zone_header zhdr;
130         tdb_off_t free[BUCKETS_FOR_ZONE(INITIAL_ZONE_BITS) + 1];
131         struct tdb_used_record hrec;
132         tdb_off_t hash[1ULL << INITIAL_HASH_BITS];
133         struct tdb_free_record frec;
134 };
135
136 struct new_database {
137         struct new_db_head h;
138         /* Rest up to 1 << INITIAL_ZONE_BITS is empty. */
139         char space[(1 << INITIAL_ZONE_BITS)
140                    - (sizeof(struct new_db_head) - sizeof(struct tdb_header))];
141         uint8_t tailer;
142         /* Don't count final padding! */
143 };
144
145 /* initialise a new database */
146 static int tdb_new_database(struct tdb_context *tdb)
147 {
148         /* We make it up in memory, then write it out if not internal */
149         struct new_database newdb;
150         unsigned int bucket, magic_off, dbsize;
151
152         /* Don't want any extra padding! */
153         dbsize = offsetof(struct new_database, tailer) + sizeof(newdb.tailer);
154
155         /* Fill in the header */
156         newdb.h.hdr.version = TDB_VERSION;
157         newdb.h.hdr.hash_seed = random_number(tdb);
158         newdb.h.hdr.hash_test = TDB_HASH_MAGIC;
159         newdb.h.hdr.hash_test = tdb->khash(&newdb.h.hdr.hash_test,
160                                            sizeof(newdb.h.hdr.hash_test),
161                                            newdb.h.hdr.hash_seed,
162                                            tdb->hash_priv);
163         memset(newdb.h.hdr.reserved, 0, sizeof(newdb.h.hdr.reserved));
164         newdb.h.hdr.v.generation = 0;
165         /* Initial hashes are empty. */
166         newdb.h.hdr.v.hash_bits = INITIAL_HASH_BITS;
167         newdb.h.hdr.v.hash_off = offsetof(struct new_database, h.hash);
168         set_header(tdb, &newdb.h.hrec, 0,
169                    sizeof(newdb.h.hash), sizeof(newdb.h.hash), 0,
170                    INITIAL_ZONE_BITS);
171         memset(newdb.h.hash, 0, sizeof(newdb.h.hash));
172
173         /* Create the single free entry. */
174         newdb.h.frec.magic_and_meta = TDB_FREE_MAGIC | INITIAL_ZONE_BITS;
175         newdb.h.frec.data_len = (sizeof(newdb.h.frec)
176                                  - sizeof(struct tdb_used_record)
177                                  + sizeof(newdb.space));
178
179         /* Free is mostly empty... */
180         newdb.h.zhdr.zone_bits = INITIAL_ZONE_BITS;
181         memset(newdb.h.free, 0, sizeof(newdb.h.free));
182
183         /* ... except for this one bucket. */
184         bucket = size_to_bucket(INITIAL_ZONE_BITS, newdb.h.frec.data_len);
185         newdb.h.free[bucket] = offsetof(struct new_database, h.frec);
186         newdb.h.frec.next = newdb.h.frec.prev = 0;
187
188         /* Clear free space to keep valgrind happy, and avoid leaking stack. */
189         memset(newdb.space, 0, sizeof(newdb.space));
190
191         /* Tailer contains maximum number of free_zone bits. */
192         newdb.tailer = INITIAL_ZONE_BITS;
193
194         /* Magic food */
195         memset(newdb.h.hdr.magic_food, 0, sizeof(newdb.h.hdr.magic_food));
196         strcpy(newdb.h.hdr.magic_food, TDB_MAGIC_FOOD);
197
198         /* This creates an endian-converted database, as if read from disk */
199         magic_off = offsetof(struct tdb_header, magic_food);
200         tdb_convert(tdb,
201                     (char *)&newdb.h.hdr + magic_off,
202                     dbsize - 1 - magic_off);
203
204         tdb->header = newdb.h.hdr;
205
206         if (tdb->flags & TDB_INTERNAL) {
207                 tdb->map_size = dbsize;
208                 tdb->map_ptr = malloc(tdb->map_size);
209                 if (!tdb->map_ptr) {
210                         tdb->ecode = TDB_ERR_OOM;
211                         return -1;
212                 }
213                 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
214                 return 0;
215         }
216         if (lseek(tdb->fd, 0, SEEK_SET) == -1)
217                 return -1;
218
219         if (ftruncate(tdb->fd, 0) == -1)
220                 return -1;
221
222         if (!tdb_pwrite_all(tdb->fd, &newdb, dbsize, 0)) {
223                 tdb->ecode = TDB_ERR_IO;
224                 return -1;
225         }
226         return 0;
227 }
228
229 struct tdb_context *tdb_open(const char *name, int tdb_flags,
230                              int open_flags, mode_t mode,
231                              union tdb_attribute *attr)
232 {
233         struct tdb_context *tdb;
234         struct stat st;
235         int save_errno;
236         uint64_t hash_test;
237         unsigned v;
238
239         tdb = malloc(sizeof(*tdb));
240         if (!tdb) {
241                 /* Can't log this */
242                 errno = ENOMEM;
243                 goto fail;
244         }
245         tdb->name = NULL;
246         tdb->map_ptr = NULL;
247         tdb->fd = -1;
248         tdb->map_size = sizeof(struct tdb_header);
249         tdb->ecode = TDB_SUCCESS;
250         /* header will be read in below. */
251         tdb->header_uptodate = false;
252         tdb->flags = tdb_flags;
253         tdb->log = null_log_fn;
254         tdb->log_priv = NULL;
255         tdb->khash = jenkins_hash;
256         tdb->hash_priv = NULL;
257         tdb->transaction = NULL;
258         /* last_zone will be set below. */
259         tdb_io_init(tdb);
260         tdb_lock_init(tdb);
261
262         while (attr) {
263                 switch (attr->base.attr) {
264                 case TDB_ATTRIBUTE_LOG:
265                         tdb->log = attr->log.log_fn;
266                         tdb->log_priv = attr->log.log_private;
267                         break;
268                 case TDB_ATTRIBUTE_HASH:
269                         tdb->khash = attr->hash.hash_fn;
270                         tdb->hash_priv = attr->hash.hash_private;
271                         break;
272                 default:
273                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
274                                  "tdb_open: unknown attribute type %u\n",
275                                  attr->base.attr);
276                         errno = EINVAL;
277                         goto fail;
278                 }
279                 attr = attr->base.next;
280         }
281
282         if ((open_flags & O_ACCMODE) == O_WRONLY) {
283                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
284                          "tdb_open: can't open tdb %s write-only\n", name);
285                 errno = EINVAL;
286                 goto fail;
287         }
288
289         if ((open_flags & O_ACCMODE) == O_RDONLY) {
290                 tdb->read_only = true;
291                 /* read only databases don't do locking */
292                 tdb->flags |= TDB_NOLOCK;
293         } else
294                 tdb->read_only = false;
295
296         /* internal databases don't need any of the rest. */
297         if (tdb->flags & TDB_INTERNAL) {
298                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
299                 if (tdb_new_database(tdb) != 0) {
300                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
301                                  "tdb_open: tdb_new_database failed!");
302                         goto fail;
303                 }
304                 TEST_IT(tdb->flags & TDB_CONVERT);
305                 tdb_convert(tdb, &tdb->header, sizeof(tdb->header));
306                 tdb_zone_init(tdb);
307                 return tdb;
308         }
309
310         if ((tdb->fd = open(name, open_flags, mode)) == -1) {
311                 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
312                          "tdb_open: could not open file %s: %s\n",
313                          name, strerror(errno));
314                 goto fail;      /* errno set by open(2) */
315         }
316
317         /* on exec, don't inherit the fd */
318         v = fcntl(tdb->fd, F_GETFD, 0);
319         fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
320
321         /* ensure there is only one process initialising at once */
322         if (tdb_lock_open(tdb) == -1) {
323                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
324                          "tdb_open: failed to get open lock on %s: %s\n",
325                          name, strerror(errno));
326                 goto fail;      /* errno set by tdb_brlock */
327         }
328
329         if (!tdb_pread_all(tdb->fd, &tdb->header, sizeof(tdb->header), 0)
330             || strcmp(tdb->header.magic_food, TDB_MAGIC_FOOD) != 0) {
331                 if (!(open_flags & O_CREAT) || tdb_new_database(tdb) == -1) {
332                         if (errno == 0) {
333                                 errno = EIO; /* ie bad format or something */
334                         }
335                         goto fail;
336                 }
337         } else if (tdb->header.version != TDB_VERSION) {
338                 if (tdb->header.version == bswap_64(TDB_VERSION))
339                         tdb->flags |= TDB_CONVERT;
340                 else {
341                         /* wrong version */
342                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
343                                  "tdb_open: %s is unknown version 0x%llx\n",
344                                  name, (long long)tdb->header.version);
345                         errno = EIO;
346                         goto fail;
347                 }
348         }
349
350         tdb_convert(tdb, &tdb->header, sizeof(tdb->header));
351         hash_test = TDB_HASH_MAGIC;
352         hash_test = tdb->khash(&hash_test, sizeof(hash_test),
353                                tdb->header.hash_seed, tdb->hash_priv);
354         if (tdb->header.hash_test != hash_test) {
355                 /* wrong hash variant */
356                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
357                          "tdb_open: %s uses a different hash function\n",
358                          name);
359                 errno = EIO;
360                 goto fail;
361         }
362
363         if (fstat(tdb->fd, &st) == -1)
364                 goto fail;
365
366         /* Is it already in the open list?  If so, fail. */
367         if (tdb_already_open(st.st_dev, st.st_ino)) {
368                 /* FIXME */
369                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
370                          "tdb_open: %s (%d,%d) is already open in this process\n",
371                          name, (int)st.st_dev, (int)st.st_ino);
372                 errno = EBUSY;
373                 goto fail;
374         }
375
376         tdb->name = strdup(name);
377         if (!tdb->name) {
378                 errno = ENOMEM;
379                 goto fail;
380         }
381
382         tdb->device = st.st_dev;
383         tdb->inode = st.st_ino;
384         tdb_unlock_open(tdb);
385
386         /* This make sure we have current map_size and mmap. */
387         tdb->methods->oob(tdb, tdb->map_size + 1, true);
388
389         /* Now we can pick a random free zone to start from. */
390         if (tdb_zone_init(tdb) == -1)
391                 goto fail;
392
393         tdb->next = tdbs;
394         tdbs = tdb;
395         return tdb;
396
397  fail:
398         save_errno = errno;
399
400         if (!tdb)
401                 return NULL;
402
403 #ifdef TDB_TRACE
404         close(tdb->tracefd);
405 #endif
406         if (tdb->map_ptr) {
407                 if (tdb->flags & TDB_INTERNAL) {
408                         free(tdb->map_ptr);
409                 } else
410                         tdb_munmap(tdb);
411         }
412         free((char *)tdb->name);
413         if (tdb->fd != -1)
414                 if (close(tdb->fd) != 0)
415                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
416                                  "tdb_open: failed to close tdb->fd"
417                                  " on error!\n");
418         free(tdb);
419         errno = save_errno;
420         return NULL;
421 }
422
423 tdb_off_t hash_off(struct tdb_context *tdb, uint64_t list)
424 {
425         return tdb->header.v.hash_off
426                 + ((list & ((1ULL << tdb->header.v.hash_bits) - 1))
427                    * sizeof(tdb_off_t));
428 }
429
430 /* Returns 0 if the entry is a zero (definitely not a match).
431  * Returns a valid entry offset if it's a match.  Fills in rec.
432  * Otherwise returns TDB_OFF_ERR: keep searching. */
433 static tdb_off_t entry_matches(struct tdb_context *tdb,
434                                uint64_t list,
435                                uint64_t hash,
436                                const struct tdb_data *key,
437                                struct tdb_used_record *rec)
438 {
439         tdb_off_t off;
440         uint64_t keylen;
441         const unsigned char *rkey;
442
443         list &= ((1ULL << tdb->header.v.hash_bits) - 1);
444
445         off = tdb_read_off(tdb, tdb->header.v.hash_off
446                            + list * sizeof(tdb_off_t));
447         if (off == 0 || off == TDB_OFF_ERR)
448                 return off;
449
450 #if 0 /* FIXME: Check other bits. */
451         unsigned int bits, bitmask, hoffextra;
452         /* Bottom three bits show how many extra hash bits. */
453         bits = (off & ((1 << TDB_EXTRA_HASHBITS_NUM) - 1)) + 1;
454         bitmask = (1 << bits)-1;
455         hoffextra = ((off >> TDB_EXTRA_HASHBITS_NUM) & bitmask);
456         uint64_t hextra = hash >> tdb->header.v.hash_bits;
457         if ((hextra & bitmask) != hoffextra) 
458                 return TDB_OFF_ERR;
459         off &= ~...;
460 #endif
461
462         if (tdb_read_convert(tdb, off, rec, sizeof(*rec)) == -1)
463                 return TDB_OFF_ERR;
464
465         /* FIXME: check extra bits in header! */
466         keylen = rec_key_length(rec);
467         if (keylen != key->dsize)
468                 return TDB_OFF_ERR;
469
470         rkey = tdb_access_read(tdb, off + sizeof(*rec), keylen, false);
471         if (!rkey)
472                 return TDB_OFF_ERR;
473         if (memcmp(rkey, key->dptr, keylen) != 0)
474                 off = TDB_OFF_ERR;
475         tdb_access_release(tdb, rkey);
476         return off;
477 }
478
479 /* FIXME: Optimize? */
480 static void unlock_lists(struct tdb_context *tdb,
481                          tdb_off_t list, tdb_len_t num,
482                          int ltype)
483 {
484         tdb_off_t i;
485
486         for (i = list; i < list + num; i++)
487                 tdb_unlock_list(tdb, i, ltype);
488 }
489
490 /* FIXME: Optimize? */
491 static int lock_lists(struct tdb_context *tdb,
492                       tdb_off_t list, tdb_len_t num,
493                       int ltype)
494 {
495         tdb_off_t i;
496
497         for (i = list; i < list + num; i++) {
498                 if (tdb_lock_list(tdb, i, ltype, TDB_LOCK_WAIT)
499                     == TDB_OFF_ERR) {
500                         unlock_lists(tdb, list, i - list, ltype);
501                         return -1;
502                 }
503         }
504         return 0;
505 }
506
507 /* We lock hashes up to the next empty offset.  We already hold the
508  * lock on the start bucket, but we may need to release and re-grab
509  * it.  If we fail, we hold no locks at all! */
510 static tdb_len_t relock_hash_to_zero(struct tdb_context *tdb,
511                                      tdb_off_t start, int ltype)
512 {
513         tdb_len_t num, len;
514
515 again:
516         num = 1ULL << tdb->header.v.hash_bits;
517         len = tdb_find_zero_off(tdb, hash_off(tdb, start), num - start);
518         if (unlikely(len == num - start)) {
519                 /* We hit the end of the hash range.  Drop lock: we have
520                    to lock start of hash first. */
521                 tdb_len_t pre_locks;
522
523                 tdb_unlock_list(tdb, start, ltype);
524
525                 /* Grab something, so header is stable. */
526                 if (tdb_lock_list(tdb, 0, ltype, TDB_LOCK_WAIT))
527                         return TDB_OFF_ERR;
528                 pre_locks = tdb_find_zero_off(tdb, hash_off(tdb, 0), num);
529                 /* We want to lock the zero entry as well. */
530                 pre_locks++;
531                 if (lock_lists(tdb, 1, pre_locks - 1, ltype) == -1) {
532                         tdb_unlock_list(tdb, 0, ltype);
533                         return TDB_OFF_ERR;
534                 }
535
536                 /* Now lock later ones. */
537                 if (unlikely(lock_lists(tdb, start, len, ltype) == -1)) {
538                         unlock_lists(tdb, 0, pre_locks, ltype);
539                         return TDB_OFF_ERR;
540                 }
541                 len += pre_locks;
542         } else {
543                 /* We want to lock the zero entry as well. */
544                 len++;
545                 /* But we already have lock on start. */
546                 if (unlikely(lock_lists(tdb, start+1, len-1, ltype) == -1)) {
547                         tdb_unlock_list(tdb, start, ltype);
548                         return TDB_OFF_ERR;
549                 }
550         }
551
552         /* Now, did we lose the race, and it's not zero any more? */
553         if (unlikely(tdb_read_off(tdb, hash_off(tdb, start + len - 1)) != 0)) {
554                 /* Leave the start locked, as expected. */
555                 unlock_lists(tdb, start + 1, len - 1, ltype);
556                 goto again;
557         }
558
559         return len;
560 }
561
562 /* FIXME: modify, don't rewrite! */
563 static int update_rec_hdr(struct tdb_context *tdb,
564                           tdb_off_t off,
565                           tdb_len_t keylen,
566                           tdb_len_t datalen,
567                           struct tdb_used_record *rec,
568                           uint64_t h)
569 {
570         uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
571
572         if (set_header(tdb, rec, keylen, datalen, keylen + dataroom, h,
573                        rec_zone_bits(rec)))
574                 return -1;
575
576         return tdb_write_convert(tdb, off, rec, sizeof(*rec));
577 }
578
579 static int hash_add(struct tdb_context *tdb,
580                     uint64_t hash, tdb_off_t off)
581 {
582         tdb_off_t i, hoff, len, num;
583
584         /* Look for next space. */
585         i = (hash & ((1ULL << tdb->header.v.hash_bits) - 1));
586         len = (1ULL << tdb->header.v.hash_bits) - i;
587         num = tdb_find_zero_off(tdb, hash_off(tdb, i), len);
588
589         if (unlikely(num == len)) {
590                 /* We wrapped.  Look through start of hash table. */
591                 i = 0;
592                 hoff = hash_off(tdb, 0);
593                 len = (1ULL << tdb->header.v.hash_bits);
594                 num = tdb_find_zero_off(tdb, hoff, len);
595                 if (num == len) {
596                         tdb->ecode = TDB_ERR_CORRUPT;
597                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
598                                  "hash_add: full hash table!\n");
599                         return -1;
600                 }
601         }
602         if (tdb_read_off(tdb, hash_off(tdb, i + num)) != 0) {
603                 tdb->ecode = TDB_ERR_CORRUPT;
604                 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
605                          "hash_add: overwriting hash table?\n");
606                 return -1;
607         }
608
609         /* FIXME: Encode extra hash bits! */
610         return tdb_write_off(tdb, hash_off(tdb, i + num), off);
611 }
612
613 /* If we fail, others will try after us. */
614 static void enlarge_hash(struct tdb_context *tdb)
615 {
616         tdb_off_t newoff, oldoff, i;
617         tdb_len_t hlen;
618         uint64_t num = 1ULL << tdb->header.v.hash_bits;
619         struct tdb_used_record pad, *r;
620         unsigned int records = 0;
621
622         /* FIXME: We should do this without holding locks throughout. */
623         if (tdb_allrecord_lock(tdb, F_WRLCK, TDB_LOCK_WAIT, false) == -1)
624                 return;
625
626         /* Someone else enlarged for us?  Nothing to do. */
627         if ((1ULL << tdb->header.v.hash_bits) != num)
628                 goto unlock;
629
630         /* Allocate our new array. */
631         hlen = num * sizeof(tdb_off_t) * 2;
632         newoff = alloc(tdb, 0, hlen, 0, false);
633         if (unlikely(newoff == TDB_OFF_ERR))
634                 goto unlock;
635         /* Step over record header! */
636         newoff += sizeof(struct tdb_used_record);
637
638         /* Starts all zero. */
639         if (zero_out(tdb, newoff, hlen) == -1)
640                 goto unlock;
641
642         /* Update header now so we can use normal routines. */
643         oldoff = tdb->header.v.hash_off;
644
645         tdb->header.v.hash_bits++;
646         tdb->header.v.hash_off = newoff;
647
648         /* FIXME: If the space before is empty, we know this is in its ideal
649          * location.  Or steal a bit from the pointer to avoid rehash. */
650         for (i = 0; i < num; i++) {
651                 tdb_off_t off;
652                 off = tdb_read_off(tdb, oldoff + i * sizeof(tdb_off_t));
653                 if (unlikely(off == TDB_OFF_ERR))
654                         goto oldheader;
655                 if (off && hash_add(tdb, hash_record(tdb, off), off) == -1)
656                         goto oldheader;
657                 if (off)
658                         records++;
659         }
660
661         tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
662                  "enlarge_hash: moved %u records from %llu buckets.\n",
663                  records, (long long)num);
664
665         /* Free up old hash. */
666         r = tdb_get(tdb, oldoff - sizeof(*r), &pad, sizeof(*r));
667         if (!r)
668                 goto oldheader;
669         add_free_record(tdb, rec_zone_bits(r), oldoff - sizeof(*r),
670                         sizeof(*r)+rec_data_length(r)+rec_extra_padding(r));
671
672         /* Now we write the modified header. */
673         write_header(tdb);
674 unlock:
675         tdb_allrecord_unlock(tdb, F_WRLCK);
676         return;
677
678 oldheader:
679         tdb->header.v.hash_bits--;
680         tdb->header.v.hash_off = oldoff;
681         goto unlock;
682 }
683
684
685 /* This is the slow version of the routine which searches the
686  * hashtable for an entry.
687  * We lock every hash bucket up to and including the next zero one.
688  */
689 static tdb_off_t find_and_lock_slow(struct tdb_context *tdb,
690                                     struct tdb_data key,
691                                     uint64_t h,
692                                     int ltype,
693                                     tdb_off_t *start_lock,
694                                     tdb_len_t *num_locks,
695                                     tdb_off_t *bucket,
696                                     struct tdb_used_record *rec)
697 {
698         /* Warning: this may drop the lock on *bucket! */
699         *num_locks = relock_hash_to_zero(tdb, *start_lock, ltype);
700         if (*num_locks == TDB_OFF_ERR)
701                 return TDB_OFF_ERR;
702
703         for (*bucket = *start_lock;
704              *bucket < *start_lock + *num_locks;
705              (*bucket)++) {
706                 tdb_off_t off = entry_matches(tdb, *bucket, h, &key, rec);
707                 /* Empty entry or we found it? */
708                 if (off == 0 || off != TDB_OFF_ERR)
709                         return off;
710         }
711
712         /* We didn't find a zero entry?  Something went badly wrong... */
713         unlock_lists(tdb, *start_lock, *start_lock + *num_locks, ltype);
714         tdb->ecode = TDB_ERR_CORRUPT;
715         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
716                  "find_and_lock: expected to find an empty hash bucket!\n");
717         return TDB_OFF_ERR;
718 }
719
720 /* This is the core routine which searches the hashtable for an entry.
721  * On error, no locks are held and TDB_OFF_ERR is returned.
722  * Otherwise, *num_locks locks of type ltype from *start_lock are held.
723  * The bucket where the entry is (or would be) is in *bucket.
724  * If not found, the return value is 0.
725  * If found, the return value is the offset, and *rec is the record. */
726 static tdb_off_t find_and_lock(struct tdb_context *tdb,
727                                struct tdb_data key,
728                                uint64_t h,
729                                int ltype,
730                                tdb_off_t *start_lock,
731                                tdb_len_t *num_locks,
732                                tdb_off_t *bucket,
733                                struct tdb_used_record *rec)
734 {
735         tdb_off_t off;
736
737         /* FIXME: can we avoid locks for some fast paths? */
738         *start_lock = tdb_lock_list(tdb, h, ltype, TDB_LOCK_WAIT);
739         if (*start_lock == TDB_OFF_ERR)
740                 return TDB_OFF_ERR;
741
742         /* Fast path. */
743         off = entry_matches(tdb, *start_lock, h, &key, rec);
744         if (likely(off != TDB_OFF_ERR)) {
745                 *bucket = *start_lock;
746                 *num_locks = 1;
747                 return off;
748         }
749
750         /* Slow path, need to grab more locks and search. */
751         return find_and_lock_slow(tdb, key, h, ltype, start_lock, num_locks,
752                                   bucket, rec);
753 }
754
755 /* Returns -1 on error, 0 on OK" */
756 static int replace_data(struct tdb_context *tdb,
757                         uint64_t h, struct tdb_data key, struct tdb_data dbuf,
758                         tdb_off_t bucket,
759                         tdb_off_t old_off, tdb_len_t old_room,
760                         unsigned old_zone,
761                         bool growing)
762 {
763         tdb_off_t new_off;
764
765         /* Allocate a new record. */
766         new_off = alloc(tdb, key.dsize, dbuf.dsize, h, growing);
767         if (unlikely(new_off == TDB_OFF_ERR))
768                 return -1;
769
770         /* We didn't like the existing one: remove it. */
771         if (old_off)
772                 add_free_record(tdb, old_zone, old_off,
773                                 sizeof(struct tdb_used_record)
774                                 + key.dsize + old_room);
775
776         /* FIXME: Encode extra hash bits! */
777         if (tdb_write_off(tdb, hash_off(tdb, bucket), new_off) == -1)
778                 return -1;
779
780         new_off += sizeof(struct tdb_used_record);
781         if (tdb->methods->write(tdb, new_off, key.dptr, key.dsize) == -1)
782                 return -1;
783
784         new_off += key.dsize;
785         if (tdb->methods->write(tdb, new_off, dbuf.dptr, dbuf.dsize) == -1)
786                 return -1;
787
788         /* FIXME: tdb_increment_seqnum(tdb); */
789         return 0;
790 }
791
792 int tdb_store(struct tdb_context *tdb,
793               struct tdb_data key, struct tdb_data dbuf, int flag)
794 {
795         tdb_off_t off, bucket, start, num;
796         tdb_len_t old_room = 0;
797         struct tdb_used_record rec;
798         uint64_t h;
799         int ret;
800
801         h = tdb_hash(tdb, key.dptr, key.dsize);
802         off = find_and_lock(tdb, key, h, F_WRLCK, &start, &num, &bucket, &rec);
803         if (unlikely(off == TDB_OFF_ERR))
804                 return -1;
805
806         /* Now we have lock on this hash bucket. */
807         if (flag == TDB_INSERT) {
808                 if (off) {
809                         tdb->ecode = TDB_ERR_EXISTS;
810                         goto fail;
811                 }
812         } else {
813                 if (off) {
814                         old_room = rec_data_length(&rec)
815                                 + rec_extra_padding(&rec);
816                         if (old_room >= dbuf.dsize) {
817                                 /* Can modify in-place.  Easy! */
818                                 if (update_rec_hdr(tdb, off,
819                                                    key.dsize, dbuf.dsize,
820                                                    &rec, h))
821                                         goto fail;
822                                 if (tdb->methods->write(tdb, off + sizeof(rec)
823                                                         + key.dsize,
824                                                         dbuf.dptr, dbuf.dsize))
825                                         goto fail;
826                                 unlock_lists(tdb, start, num, F_WRLCK);
827                                 return 0;
828                         }
829                         /* FIXME: See if right record is free? */
830                 } else {
831                         if (flag == TDB_MODIFY) {
832                                 /* if the record doesn't exist and we
833                                    are in TDB_MODIFY mode then we should fail
834                                    the store */
835                                 tdb->ecode = TDB_ERR_NOEXIST;
836                                 goto fail;
837                         }
838                 }
839         }
840
841         /* If we didn't use the old record, this implies we're growing. */
842         ret = replace_data(tdb, h, key, dbuf, bucket, off, old_room,
843                            rec_zone_bits(&rec), off != 0);
844         unlock_lists(tdb, start, num, F_WRLCK);
845
846         /* FIXME: by simple simulation, this approximated 60% full.
847          * Check in real case! */
848         if (unlikely(num > 4 * tdb->header.v.hash_bits - 30))
849                 enlarge_hash(tdb);
850
851         return ret;
852
853 fail:
854         unlock_lists(tdb, start, num, F_WRLCK);
855         return -1;
856 }
857
858 int tdb_append(struct tdb_context *tdb,
859                struct tdb_data key, struct tdb_data dbuf)
860 {
861         tdb_off_t off, bucket, start, num;
862         struct tdb_used_record rec;
863         tdb_len_t old_room = 0, old_dlen;
864         uint64_t h;
865         unsigned char *newdata;
866         struct tdb_data new_dbuf;
867         int ret;
868
869         h = tdb_hash(tdb, key.dptr, key.dsize);
870         off = find_and_lock(tdb, key, h, F_WRLCK, &start, &num, &bucket, &rec);
871         if (unlikely(off == TDB_OFF_ERR))
872                 return -1;
873
874         if (off) {
875                 old_dlen = rec_data_length(&rec);
876                 old_room = old_dlen + rec_extra_padding(&rec);
877
878                 /* Fast path: can append in place. */
879                 if (rec_extra_padding(&rec) >= dbuf.dsize) {
880                         if (update_rec_hdr(tdb, off, key.dsize,
881                                            old_dlen + dbuf.dsize, &rec, h))
882                                 goto fail;
883
884                         off += sizeof(rec) + key.dsize + old_dlen;
885                         if (tdb->methods->write(tdb, off, dbuf.dptr,
886                                                 dbuf.dsize) == -1)
887                                 goto fail;
888
889                         /* FIXME: tdb_increment_seqnum(tdb); */
890                         unlock_lists(tdb, start, num, F_WRLCK);
891                         return 0;
892                 }
893                 /* FIXME: Check right record free? */
894
895                 /* Slow path. */
896                 newdata = malloc(key.dsize + old_dlen + dbuf.dsize);
897                 if (!newdata) {
898                         tdb->ecode = TDB_ERR_OOM;
899                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
900                                  "tdb_append: cannot allocate %llu bytes!\n",
901                                  (long long)key.dsize + old_dlen + dbuf.dsize);
902                         goto fail;
903                 }
904                 if (tdb->methods->read(tdb, off + sizeof(rec) + key.dsize,
905                                        newdata, old_dlen) != 0) {
906                         free(newdata);
907                         goto fail;
908                 }
909                 memcpy(newdata + old_dlen, dbuf.dptr, dbuf.dsize);
910                 new_dbuf.dptr = newdata;
911                 new_dbuf.dsize = old_dlen + dbuf.dsize;
912         } else {
913                 newdata = NULL;
914                 new_dbuf = dbuf;
915         }
916
917         /* If they're using tdb_append(), it implies they're growing record. */
918         ret = replace_data(tdb, h, key, new_dbuf, bucket, off, old_room,
919                            rec_zone_bits(&rec), true);
920         unlock_lists(tdb, start, num, F_WRLCK);
921         free(newdata);
922
923         /* FIXME: by simple simulation, this approximated 60% full.
924          * Check in real case! */
925         if (unlikely(num > 4 * tdb->header.v.hash_bits - 30))
926                 enlarge_hash(tdb);
927
928         return ret;
929
930 fail:
931         unlock_lists(tdb, start, num, F_WRLCK);
932         return -1;
933 }
934
935 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
936 {
937         tdb_off_t off, start, num, bucket;
938         struct tdb_used_record rec;
939         uint64_t h;
940         struct tdb_data ret;
941
942         h = tdb_hash(tdb, key.dptr, key.dsize);
943         off = find_and_lock(tdb, key, h, F_RDLCK, &start, &num, &bucket, &rec);
944         if (unlikely(off == TDB_OFF_ERR))
945                 return tdb_null;
946
947         if (!off) {
948                 tdb->ecode = TDB_ERR_NOEXIST;
949                 ret = tdb_null;
950         } else {
951                 ret.dsize = rec_data_length(&rec);
952                 ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
953                                           ret.dsize);
954         }
955
956         unlock_lists(tdb, start, num, F_RDLCK);
957         return ret;
958 }
959
960 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
961 {
962         tdb_off_t i, bucket, off, start, num;
963         struct tdb_used_record rec;
964         uint64_t h;
965
966         h = tdb_hash(tdb, key.dptr, key.dsize);
967         start = tdb_lock_list(tdb, h, F_WRLCK, TDB_LOCK_WAIT);
968         if (unlikely(start == TDB_OFF_ERR))
969                 return -1;
970
971         /* FIXME: Fastpath: if next is zero, we can delete without lock,
972          * since this lock protects us. */
973         off = find_and_lock_slow(tdb, key, h, F_WRLCK,
974                                  &start, &num, &bucket, &rec);
975         if (unlikely(off == TDB_OFF_ERR))
976                 return -1;
977
978         if (!off) {
979                 /* FIXME: We could optimize not found case if it mattered, by
980                  * reading offset after first lock: if it's zero, goto here. */
981                 unlock_lists(tdb, start, num, F_WRLCK);
982                 tdb->ecode = TDB_ERR_NOEXIST;
983                 return -1;
984         }
985         /* Since we found the entry, we must have locked it and a zero. */
986         assert(num >= 2);
987
988         /* This actually unlinks it. */
989         if (tdb_write_off(tdb, hash_off(tdb, bucket), 0) == -1)
990                 goto unlock_err;
991
992         /* Rehash anything following. */
993         for (i = bucket+1; i != bucket + num - 1; i++) {
994                 tdb_off_t hoff, off2;
995                 uint64_t h2;
996
997                 hoff = hash_off(tdb, i);
998                 off2 = tdb_read_off(tdb, hoff);
999                 if (unlikely(off2 == TDB_OFF_ERR))
1000                         goto unlock_err;
1001
1002                 /* This can happen if we raced. */
1003                 if (unlikely(off2 == 0))
1004                         break;
1005
1006                 /* Maybe use a bit to indicate it is in ideal place? */
1007                 h2 = hash_record(tdb, off2);
1008                 /* Is it happy where it is? */
1009                 if (hash_off(tdb, h2) == hoff)
1010                         continue;
1011
1012                 /* Remove it. */
1013                 if (tdb_write_off(tdb, hoff, 0) == -1)
1014                         goto unlock_err;
1015
1016                 /* Rehash it. */
1017                 if (hash_add(tdb, h2, off2) == -1)
1018                         goto unlock_err;
1019         }
1020
1021         /* Free the deleted entry. */
1022         if (add_free_record(tdb, rec_zone_bits(&rec), off,
1023                             sizeof(struct tdb_used_record)
1024                             + rec_key_length(&rec)
1025                             + rec_data_length(&rec)
1026                             + rec_extra_padding(&rec)) != 0)
1027                 goto unlock_err;
1028
1029         unlock_lists(tdb, start, num, F_WRLCK);
1030         return 0;
1031
1032 unlock_err:
1033         unlock_lists(tdb, start, num, F_WRLCK);
1034         return -1;
1035 }
1036
1037 int tdb_close(struct tdb_context *tdb)
1038 {
1039         struct tdb_context **i;
1040         int ret = 0;
1041
1042         /* FIXME:
1043         if (tdb->transaction) {
1044                 tdb_transaction_cancel(tdb);
1045         }
1046         */
1047         tdb_trace(tdb, "tdb_close");
1048
1049         if (tdb->map_ptr) {
1050                 if (tdb->flags & TDB_INTERNAL)
1051                         free(tdb->map_ptr);
1052                 else
1053                         tdb_munmap(tdb);
1054         }
1055         free((char *)tdb->name);
1056         if (tdb->fd != -1) {
1057                 ret = close(tdb->fd);
1058                 tdb->fd = -1;
1059         }
1060         free(tdb->lockrecs);
1061
1062         /* Remove from contexts list */
1063         for (i = &tdbs; *i; i = &(*i)->next) {
1064                 if (*i == tdb) {
1065                         *i = tdb->next;
1066                         break;
1067                 }
1068         }
1069
1070 #ifdef TDB_TRACE
1071         close(tdb->tracefd);
1072 #endif
1073         free(tdb);
1074
1075         return ret;
1076 }
1077
1078 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
1079 {
1080         return tdb->ecode;
1081 }