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