]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/tdb.c
tests: now we run in tmp dir, always create temporary files in this dir.
[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_database {
128         struct tdb_header hdr;
129         struct tdb_used_record hrec;
130         tdb_off_t hash[1ULL << INITIAL_HASH_BITS];
131         struct tdb_used_record frec;
132         tdb_off_t free[INITIAL_FREE_BUCKETS + 1]; /* One overflow bucket */
133 };
134
135 /* initialise a new database */
136 static int tdb_new_database(struct tdb_context *tdb)
137 {
138         /* We make it up in memory, then write it out if not internal */
139         struct new_database newdb;
140         unsigned int magic_off = offsetof(struct tdb_header, magic_food);
141
142         /* Fill in the header */
143         newdb.hdr.version = TDB_VERSION;
144         newdb.hdr.hash_seed = random_number(tdb);
145         newdb.hdr.hash_test = TDB_HASH_MAGIC;
146         newdb.hdr.hash_test = tdb->khash(&newdb.hdr.hash_test,
147                                          sizeof(newdb.hdr.hash_test),
148                                          newdb.hdr.hash_seed,
149                                          tdb->hash_priv);
150
151         newdb.hdr.v.generation = 0;
152
153         /* The initial zone must cover the initial database size! */
154         BUILD_ASSERT((1ULL << INITIAL_ZONE_BITS) >= sizeof(newdb));
155
156         /* Free array has 1 zone, 10 buckets.  All buckets empty. */
157         newdb.hdr.v.num_zones = 1;
158         newdb.hdr.v.zone_bits = INITIAL_ZONE_BITS;
159         newdb.hdr.v.free_buckets = INITIAL_FREE_BUCKETS;
160         newdb.hdr.v.free_off = offsetof(struct new_database, free);
161         set_header(tdb, &newdb.frec, 0,
162                    sizeof(newdb.free), sizeof(newdb.free), 0);
163         memset(newdb.free, 0, sizeof(newdb.free));
164
165         /* Initial hashes are empty. */
166         newdb.hdr.v.hash_bits = INITIAL_HASH_BITS;
167         newdb.hdr.v.hash_off = offsetof(struct new_database, hash);
168         set_header(tdb, &newdb.hrec, 0,
169                    sizeof(newdb.hash), sizeof(newdb.hash), 0);
170         memset(newdb.hash, 0, sizeof(newdb.hash));
171
172         /* Magic food */
173         memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
174         strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
175
176         /* This creates an endian-converted database, as if read from disk */
177         tdb_convert(tdb,
178                     (char *)&newdb.hdr + magic_off,
179                     sizeof(newdb) - magic_off);
180
181         tdb->header = newdb.hdr;
182
183         if (tdb->flags & TDB_INTERNAL) {
184                 tdb->map_size = sizeof(newdb);
185                 tdb->map_ptr = malloc(tdb->map_size);
186                 if (!tdb->map_ptr) {
187                         tdb->ecode = TDB_ERR_OOM;
188                         return -1;
189                 }
190                 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
191                 return 0;
192         }
193         if (lseek(tdb->fd, 0, SEEK_SET) == -1)
194                 return -1;
195
196         if (ftruncate(tdb->fd, 0) == -1)
197                 return -1;
198
199         if (!tdb_pwrite_all(tdb->fd, &newdb, sizeof(newdb), 0)) {
200                 tdb->ecode = TDB_ERR_IO;
201                 return -1;
202         }
203         return 0;
204 }
205
206 struct tdb_context *tdb_open(const char *name, int tdb_flags,
207                              int open_flags, mode_t mode,
208                              union tdb_attribute *attr)
209 {
210         struct tdb_context *tdb;
211         struct stat st;
212         int save_errno;
213         uint64_t hash_test;
214         unsigned v;
215
216         tdb = malloc(sizeof(*tdb));
217         if (!tdb) {
218                 /* Can't log this */
219                 errno = ENOMEM;
220                 goto fail;
221         }
222         tdb->name = NULL;
223         tdb->map_ptr = NULL;
224         tdb->fd = -1;
225         /* map_size will be set below. */
226         tdb->ecode = TDB_SUCCESS;
227         /* header will be read in below. */
228         tdb->header_uptodate = false;
229         tdb->flags = tdb_flags;
230         tdb->log = null_log_fn;
231         tdb->log_priv = NULL;
232         tdb->khash = jenkins_hash;
233         tdb->hash_priv = NULL;
234         tdb->transaction = NULL;
235         /* last_zone will be set below. */
236         tdb_io_init(tdb);
237         tdb_lock_init(tdb);
238
239         /* FIXME */
240         if (attr) {
241                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
242                          "tdb_open: attributes not yet supported\n");
243                 errno = EINVAL;
244                 goto fail;
245         }
246
247         if ((open_flags & O_ACCMODE) == O_WRONLY) {
248                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
249                          "tdb_open: can't open tdb %s write-only\n", name);
250                 errno = EINVAL;
251                 goto fail;
252         }
253
254         if ((open_flags & O_ACCMODE) == O_RDONLY) {
255                 tdb->read_only = true;
256                 /* read only databases don't do locking */
257                 tdb->flags |= TDB_NOLOCK;
258         } else
259                 tdb->read_only = false;
260
261         /* internal databases don't need any of the rest. */
262         if (tdb->flags & TDB_INTERNAL) {
263                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
264                 if (tdb_new_database(tdb) != 0) {
265                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
266                                  "tdb_open: tdb_new_database failed!");
267                         goto fail;
268                 }
269                 TEST_IT(tdb->flags & TDB_CONVERT);
270                 tdb_convert(tdb, &tdb->header, sizeof(tdb->header));
271                 /* Zones don't matter for internal db. */
272                 tdb->last_zone = 0;
273                 return tdb;
274         }
275
276         if ((tdb->fd = open(name, open_flags, mode)) == -1) {
277                 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
278                          "tdb_open: could not open file %s: %s\n",
279                          name, strerror(errno));
280                 goto fail;      /* errno set by open(2) */
281         }
282
283         /* on exec, don't inherit the fd */
284         v = fcntl(tdb->fd, F_GETFD, 0);
285         fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
286
287         /* ensure there is only one process initialising at once */
288         if (tdb_lock_open(tdb) == -1) {
289                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
290                          "tdb_open: failed to get open lock on %s: %s\n",
291                          name, strerror(errno));
292                 goto fail;      /* errno set by tdb_brlock */
293         }
294
295         if (!tdb_pread_all(tdb->fd, &tdb->header, sizeof(tdb->header), 0)
296             || strcmp(tdb->header.magic_food, TDB_MAGIC_FOOD) != 0) {
297                 if (!(open_flags & O_CREAT) || tdb_new_database(tdb) == -1) {
298                         if (errno == 0) {
299                                 errno = EIO; /* ie bad format or something */
300                         }
301                         goto fail;
302                 }
303         } else if (tdb->header.version != TDB_VERSION) {
304                 if (tdb->header.version == bswap_64(TDB_VERSION))
305                         tdb->flags |= TDB_CONVERT;
306                 else {
307                         /* wrong version */
308                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
309                                  "tdb_open: %s is unknown version 0x%llx\n",
310                                  name, (long long)tdb->header.version);
311                         errno = EIO;
312                         goto fail;
313                 }
314         }
315
316         tdb_convert(tdb, &tdb->header, sizeof(tdb->header));
317         hash_test = TDB_HASH_MAGIC;
318         hash_test = tdb->khash(&hash_test, sizeof(hash_test),
319                                tdb->header.hash_seed, tdb->hash_priv);
320         if (tdb->header.hash_test != hash_test) {
321                 /* wrong hash variant */
322                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
323                          "tdb_open: %s uses a different hash function\n",
324                          name);
325                 errno = EIO;
326                 goto fail;
327         }
328
329         if (fstat(tdb->fd, &st) == -1)
330                 goto fail;
331
332         /* Is it already in the open list?  If so, fail. */
333         if (tdb_already_open(st.st_dev, st.st_ino)) {
334                 /* FIXME */
335                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
336                          "tdb_open: %s (%d,%d) is already open in this process\n",
337                          name, (int)st.st_dev, (int)st.st_ino);
338                 errno = EBUSY;
339                 goto fail;
340         }
341
342         tdb->name = strdup(name);
343         if (!tdb->name) {
344                 errno = ENOMEM;
345                 goto fail;
346         }
347
348         tdb->map_size = st.st_size;
349         tdb->device = st.st_dev;
350         tdb->inode = st.st_ino;
351         tdb_mmap(tdb);
352         tdb_unlock_open(tdb);
353         tdb_zone_init(tdb);
354
355         tdb->next = tdbs;
356         tdbs = tdb;
357         return tdb;
358
359  fail:
360         save_errno = errno;
361
362         if (!tdb)
363                 return NULL;
364
365 #ifdef TDB_TRACE
366         close(tdb->tracefd);
367 #endif
368         if (tdb->map_ptr) {
369                 if (tdb->flags & TDB_INTERNAL) {
370                         free(tdb->map_ptr);
371                 } else
372                         tdb_munmap(tdb);
373         }
374         free((char *)tdb->name);
375         if (tdb->fd != -1)
376                 if (close(tdb->fd) != 0)
377                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
378                                  "tdb_open: failed to close tdb->fd"
379                                  " on error!\n");
380         free(tdb);
381         errno = save_errno;
382         return NULL;
383 }
384
385 static tdb_off_t hash_off(struct tdb_context *tdb, uint64_t list)
386 {
387         return tdb->header.v.hash_off
388                 + ((list & ((1ULL << tdb->header.v.hash_bits) - 1))
389                    * sizeof(tdb_off_t));
390 }
391
392 /* Returns 0 if the entry is a zero (definitely not a match).
393  * Returns a valid entry offset if it's a match.  Fills in rec.
394  * Otherwise returns TDB_OFF_ERR: keep searching. */
395 static tdb_off_t entry_matches(struct tdb_context *tdb,
396                                uint64_t list,
397                                uint64_t hash,
398                                const struct tdb_data *key,
399                                struct tdb_used_record *rec)
400 {
401         tdb_off_t off;
402         uint64_t keylen;
403         const unsigned char *rkey;
404
405         off = tdb_read_off(tdb, tdb->header.v.hash_off
406                            + list * sizeof(tdb_off_t));
407         if (off == 0 || off == TDB_OFF_ERR)
408                 return off;
409
410 #if 0 /* FIXME: Check other bits. */
411         unsigned int bits, bitmask, hoffextra;
412         /* Bottom three bits show how many extra hash bits. */
413         bits = (off & ((1 << TDB_EXTRA_HASHBITS_NUM) - 1)) + 1;
414         bitmask = (1 << bits)-1;
415         hoffextra = ((off >> TDB_EXTRA_HASHBITS_NUM) & bitmask);
416         uint64_t hextra = hash >> tdb->header.v.hash_bits;
417         if ((hextra & bitmask) != hoffextra) 
418                 return TDB_OFF_ERR;
419         off &= ~...;
420 #endif
421
422         if (tdb_read_convert(tdb, off, rec, sizeof(*rec)) == -1)
423                 return TDB_OFF_ERR;
424
425         /* FIXME: check extra bits in header! */
426         keylen = rec_key_length(rec);
427         if (keylen != key->dsize)
428                 return TDB_OFF_ERR;
429
430         rkey = tdb_access_read(tdb, off + sizeof(*rec), keylen, false);
431         if (!rkey)
432                 return TDB_OFF_ERR;
433         if (memcmp(rkey, key->dptr, keylen) != 0)
434                 off = TDB_OFF_ERR;
435         tdb_access_release(tdb, rkey);
436         return off;
437 }
438
439 /* FIXME: Optimize? */
440 static void unlock_lists(struct tdb_context *tdb,
441                          tdb_off_t list, tdb_len_t num,
442                          int ltype)
443 {
444         tdb_off_t i;
445
446         for (i = list; i < list + num; i++)
447                 tdb_unlock_list(tdb, i, ltype);
448 }
449
450 /* FIXME: Optimize? */
451 static int lock_lists(struct tdb_context *tdb,
452                       tdb_off_t list, tdb_len_t num,
453                       int ltype)
454 {
455         tdb_off_t i;
456
457         for (i = list; i < list + num; i++) {
458                 if (tdb_lock_list(tdb, i, ltype, TDB_LOCK_WAIT) != 0) {
459                         unlock_lists(tdb, list, i - list, ltype);
460                         return -1;
461                 }
462         }
463         return 0;
464 }
465
466 /* We lock hashes up to the next empty offset.  We already hold the
467  * lock on the start bucket, but we may need to release and re-grab
468  * it.  If we fail, we hold no locks at all! */
469 static tdb_len_t relock_hash_to_zero(struct tdb_context *tdb,
470                                      tdb_off_t start, int ltype)
471 {
472         tdb_len_t num, len, pre_locks;
473
474 again:
475         num = 1ULL << tdb->header.v.hash_bits;
476         len = tdb_find_zero_off(tdb, hash_off(tdb, start), num - start);
477         if (unlikely(len == num - start)) {
478                 /* We hit the end of the hash range.  Drop lock: we have
479                    to lock start of hash first. */
480                 tdb_unlock_list(tdb, start, ltype);
481                 /* Grab something, so header is stable. */
482                 if (tdb_lock_list(tdb, 0, ltype, TDB_LOCK_WAIT))
483                         return TDB_OFF_ERR;
484                 len = tdb_find_zero_off(tdb, hash_off(tdb, 0), num);
485                 if (lock_lists(tdb, 1, len, ltype) == -1) {
486                         tdb_unlock_list(tdb, 0, ltype);
487                         return TDB_OFF_ERR;
488                 }
489                 pre_locks = len;
490                 len = num - start;
491         } else {
492                 /* We already have lock on start. */
493                 start++;
494                 pre_locks = 0;
495         }
496         if (unlikely(lock_lists(tdb, start, len, ltype) == -1)) {
497                 if (pre_locks)
498                         unlock_lists(tdb, 0, pre_locks, ltype);
499                 else
500                         tdb_unlock_list(tdb, start, ltype);
501                 return TDB_OFF_ERR;
502         }
503
504         /* Now, did we lose the race, and it's not zero any more? */
505         if (unlikely(tdb_read_off(tdb, hash_off(tdb, pre_locks + len)) != 0)) {
506                 unlock_lists(tdb, 0, pre_locks, ltype);
507                 /* Leave the start locked, as expected. */
508                 unlock_lists(tdb, start + 1, len - 1, ltype);
509                 goto again;
510         }
511
512         return pre_locks + len;
513 }
514
515 /* FIXME: modify, don't rewrite! */
516 static int update_rec_hdr(struct tdb_context *tdb,
517                           tdb_off_t off,
518                           tdb_len_t keylen,
519                           tdb_len_t datalen,
520                           struct tdb_used_record *rec,
521                           uint64_t h)
522 {
523         uint64_t dataroom = rec_data_length(rec) + rec_extra_padding(rec);
524
525         if (set_header(tdb, rec, keylen, datalen, keylen + dataroom, h))
526                 return -1;
527
528         return tdb_write_convert(tdb, off, rec, sizeof(*rec));
529 }
530
531 /* If we fail, others will try after us. */
532 static void enlarge_hash(struct tdb_context *tdb)
533 {
534         tdb_off_t newoff, oldoff, i;
535         tdb_len_t hlen;
536         uint64_t h, num = 1ULL << tdb->header.v.hash_bits;
537         struct tdb_used_record pad, *r;
538
539         /* FIXME: We should do this without holding locks throughout. */
540         if (tdb_allrecord_lock(tdb, F_WRLCK, TDB_LOCK_WAIT, false) == -1)
541                 return;
542
543         /* Someone else enlarged for us?  Nothing to do. */
544         if ((1ULL << tdb->header.v.hash_bits) != num)
545                 goto unlock;
546
547         /* Allocate our new array. */
548         hlen = num * sizeof(tdb_off_t) * 2;
549         newoff = alloc(tdb, 0, hlen, 0, false);
550         if (unlikely(newoff == TDB_OFF_ERR))
551                 goto unlock;
552         if (unlikely(newoff == 0)) {
553                 if (tdb_expand(tdb, 0, hlen, false) == -1)
554                         goto unlock;
555                 newoff = alloc(tdb, 0, hlen, 0, false);
556                 if (newoff == TDB_OFF_ERR || newoff == 0)
557                         goto unlock;
558         }
559         /* Step over record header! */
560         newoff += sizeof(struct tdb_used_record);
561
562         /* Starts all zero. */
563         if (zero_out(tdb, newoff, hlen) == -1)
564                 goto unlock;
565
566         /* FIXME: If the space before is empty, we know this is in its ideal
567          * location.  Or steal a bit from the pointer to avoid rehash. */
568         for (i = tdb_find_nonzero_off(tdb, hash_off(tdb, 0), num);
569              i < num;
570              i += tdb_find_nonzero_off(tdb, hash_off(tdb, i), num - i)) {
571                 tdb_off_t off;
572                 off = tdb_read_off(tdb, hash_off(tdb, i));
573                 if (unlikely(off == TDB_OFF_ERR))
574                         goto unlock;
575                 if (unlikely(!off)) {
576                         tdb->ecode = TDB_ERR_CORRUPT;
577                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
578                                  "find_bucket_and_lock: zero hash bucket!\n");
579                         goto unlock;
580                 }
581                 h = hash_record(tdb, off);
582                 /* FIXME: Encode extra hash bits! */
583                 if (tdb_write_off(tdb, newoff
584                                   + (h & ((num * 2) - 1)) * sizeof(uint64_t),
585                                   off) == -1)
586                         goto unlock;
587         }
588
589         /* Free up old hash. */
590         oldoff = tdb->header.v.hash_off - sizeof(*r);
591         r = tdb_get(tdb, oldoff, &pad, sizeof(*r));
592         if (!r)
593                 goto unlock;
594         add_free_record(tdb, oldoff,
595                         sizeof(*r)+rec_data_length(r)+rec_extra_padding(r));
596
597         /* Now we write the modified header. */
598         tdb->header.v.hash_bits++;
599         tdb->header.v.hash_off = newoff;
600         write_header(tdb);
601 unlock:
602         tdb_allrecord_unlock(tdb, F_WRLCK);
603 }
604
605 int tdb_store(struct tdb_context *tdb,
606               struct tdb_data key, struct tdb_data dbuf, int flag)
607 {
608         tdb_off_t new_off, off, old_bucket, start, num_locks = 1;
609         struct tdb_used_record rec;
610         uint64_t h;
611         bool growing = false;
612
613         h = tdb_hash(tdb, key.dptr, key.dsize);
614
615         /* FIXME: can we avoid locks for some fast paths? */
616         start = tdb_lock_list(tdb, h, F_WRLCK, TDB_LOCK_WAIT);
617         if (start == TDB_OFF_ERR)
618                 return -1;
619
620         /* Fast path. */
621         old_bucket = start;
622         off = entry_matches(tdb, start, h, &key, &rec);
623         if (unlikely(off == TDB_OFF_ERR)) {
624                 /* Slow path, need to grab more locks and search. */
625                 tdb_off_t i;
626
627                 /* Warning: this may drop the lock!  Does that on error. */
628                 num_locks = relock_hash_to_zero(tdb, start, F_WRLCK);
629                 if (num_locks == TDB_OFF_ERR)
630                         return -1;
631
632                 for (i = start; i < start + num_locks; i++) {
633                         off = entry_matches(tdb, i, h, &key, &rec);
634                         /* Empty entry or we found it? */
635                         if (off == 0 || off != TDB_OFF_ERR) {
636                                 old_bucket = i;
637                                 break;
638                         }
639                 }
640                 if (i == start + num_locks)
641                         off = 0;
642         }
643
644         /* Now we have lock on this hash bucket. */
645         if (flag == TDB_INSERT) {
646                 if (off) {
647                         tdb->ecode = TDB_ERR_EXISTS;
648                         goto fail;
649                 }
650         } else {
651                 if (off) {
652                         if (rec_data_length(&rec) + rec_extra_padding(&rec)
653                             >= dbuf.dsize) {
654                                 new_off = off;
655                                 if (update_rec_hdr(tdb, off,
656                                                    key.dsize, dbuf.dsize,
657                                                    &rec, h))
658                                         goto fail;
659                                 goto write;
660                         }
661                         /* FIXME: See if right record is free? */
662                         /* Hint to allocator that we've realloced. */
663                         growing = true;
664                 } else {
665                         if (flag == TDB_MODIFY) {
666                                 /* if the record doesn't exist and we
667                                    are in TDB_MODIFY mode then we should fail
668                                    the store */
669                                 tdb->ecode = TDB_ERR_NOEXIST;
670                                 goto fail;
671                         }
672                 }
673         }
674
675         /* Allocate a new record. */
676         new_off = alloc(tdb, key.dsize, dbuf.dsize, h, growing);
677         if (new_off == 0) {
678                 unlock_lists(tdb, start, num_locks, F_WRLCK);
679                 /* Expand, then try again... */
680                 if (tdb_expand(tdb, key.dsize, dbuf.dsize, growing) == -1)
681                         return -1;
682                 return tdb_store(tdb, key, dbuf, flag);
683         }
684
685         /* We didn't like the existing one: remove it. */
686         if (off) {
687                 add_free_record(tdb, off, sizeof(struct tdb_used_record)
688                                 + rec_key_length(&rec)
689                                 + rec_data_length(&rec)
690                                 + rec_extra_padding(&rec));
691         }
692
693         /* FIXME: Encode extra hash bits! */
694         if (tdb_write_off(tdb, hash_off(tdb, old_bucket), new_off) == -1)
695                 goto fail;
696
697 write:
698         off = new_off + sizeof(struct tdb_used_record);
699         if (tdb->methods->write(tdb, off, key.dptr, key.dsize) == -1)
700                 goto fail;
701         off += key.dsize;
702         if (tdb->methods->write(tdb, off, dbuf.dptr, dbuf.dsize) == -1)
703                 goto fail;
704
705         /* FIXME: tdb_increment_seqnum(tdb); */
706         unlock_lists(tdb, start, num_locks, F_WRLCK);
707
708         /* FIXME: by simple simulation, this approximated 60% full.
709          * Check in real case! */
710         if (unlikely(num_locks > 4 * tdb->header.v.hash_bits - 31))
711                 enlarge_hash(tdb);
712
713         return 0;
714
715 fail:
716         unlock_lists(tdb, start, num_locks, F_WRLCK);
717         return -1;
718 }
719
720 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
721 {
722         tdb_off_t off, start, num_locks = 1;
723         struct tdb_used_record rec;
724         uint64_t h;
725         struct tdb_data ret;
726
727         h = tdb_hash(tdb, key.dptr, key.dsize);
728
729         /* FIXME: can we avoid locks for some fast paths? */
730         start = tdb_lock_list(tdb, h, F_RDLCK, TDB_LOCK_WAIT);
731         if (start == TDB_OFF_ERR)
732                 return tdb_null;
733
734         /* Fast path. */
735         off = entry_matches(tdb, start, h, &key, &rec);
736         if (unlikely(off == TDB_OFF_ERR)) {
737                 /* Slow path, need to grab more locks and search. */
738                 tdb_off_t i;
739
740                 /* Warning: this may drop the lock!  Does that on error. */
741                 num_locks = relock_hash_to_zero(tdb, start, F_RDLCK);
742                 if (num_locks == TDB_OFF_ERR)
743                         return tdb_null;
744
745                 for (i = start; i < start + num_locks; i++) {
746                         off = entry_matches(tdb, i, h, &key, &rec);
747                         /* Empty entry or we found it? */
748                         if (off == 0 || off != TDB_OFF_ERR)
749                                 break;
750                 }
751                 if (i == start + num_locks)
752                         off = 0;
753         }
754
755         if (!off) {
756                 unlock_lists(tdb, start, num_locks, F_RDLCK);
757                 tdb->ecode = TDB_ERR_NOEXIST;
758                 return tdb_null;
759         }
760
761         ret.dsize = rec_data_length(&rec);
762         ret.dptr = tdb_alloc_read(tdb, off + sizeof(rec) + key.dsize,
763                                   ret.dsize);
764         unlock_lists(tdb, start, num_locks, F_RDLCK);
765         return ret;
766 }
767
768 static int hash_add(struct tdb_context *tdb, uint64_t h, tdb_off_t off)
769 {
770         tdb_off_t i, hoff, len, num;
771
772         /* Look for next space. */
773         i = (h & ((1ULL << tdb->header.v.hash_bits) - 1));
774         len = (1ULL << tdb->header.v.hash_bits) - i;
775         num = tdb_find_zero_off(tdb, hash_off(tdb, i), len);
776
777         if (unlikely(num == len)) {
778                 /* We wrapped.  Look through start of hash table. */
779                 hoff = hash_off(tdb, 0);
780                 len = (1ULL << tdb->header.v.hash_bits);
781                 num = tdb_find_zero_off(tdb, hoff, len);
782                 if (i == len) {
783                         tdb->ecode = TDB_ERR_CORRUPT;
784                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
785                                  "hash_add: full hash table!\n");
786                         return -1;
787                 }
788         }
789         /* FIXME: Encode extra hash bits! */
790         return tdb_write_off(tdb, hash_off(tdb, i + num), off);
791 }
792
793 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
794 {
795         tdb_off_t i, old_bucket, off, start, num_locks = 1;
796         struct tdb_used_record rec;
797         uint64_t h;
798
799         h = tdb_hash(tdb, key.dptr, key.dsize);
800
801         /* FIXME: can we avoid locks for some fast paths? */
802         start = tdb_lock_list(tdb, h, F_WRLCK, TDB_LOCK_WAIT);
803         if (start == TDB_OFF_ERR)
804                 return -1;
805
806         /* Fast path. */
807         old_bucket = start;
808         off = entry_matches(tdb, start, h, &key, &rec);
809         if (off && off != TDB_OFF_ERR) {
810                 /* We can only really fastpath delete if next bucket
811                  * is 0.  Note that we haven't locked it, but our lock
812                  * on this bucket stops anyone overflowing into it
813                  * while we look. */
814                 if (tdb_read_off(tdb, hash_off(tdb, h+1)) == 0)
815                         goto delete;
816                 /* Slow path. */
817                 off = TDB_OFF_ERR;
818         }
819
820         if (unlikely(off == TDB_OFF_ERR)) {
821                 /* Slow path, need to grab more locks and search. */
822                 tdb_off_t i;
823
824                 /* Warning: this may drop the lock!  Does that on error. */
825                 num_locks = relock_hash_to_zero(tdb, start, F_WRLCK);
826                 if (num_locks == TDB_OFF_ERR)
827                         return -1;
828
829                 for (i = start; i < start + num_locks; i++) {
830                         off = entry_matches(tdb, i, h, &key, &rec);
831                         /* Empty entry or we found it? */
832                         if (off == 0 || off != TDB_OFF_ERR) {
833                                 old_bucket = i;
834                                 break;
835                         }
836                 }
837                 if (i == start + num_locks)
838                         off = 0;
839         }
840
841         if (!off) {
842                 unlock_lists(tdb, start, num_locks, F_WRLCK);
843                 tdb->ecode = TDB_ERR_NOEXIST;
844                 return -1;
845         }
846
847 delete:
848         /* This actually unlinks it. */
849         if (tdb_write_off(tdb, hash_off(tdb, old_bucket), 0) == -1)
850                 goto unlock_err;
851
852         /* Rehash anything following. */
853         for (i = hash_off(tdb, old_bucket+1);
854              i != hash_off(tdb, h + num_locks);
855              i += sizeof(tdb_off_t)) {
856                 tdb_off_t off2;
857                 uint64_t h2;
858
859                 off2 = tdb_read_off(tdb, i);
860                 if (unlikely(off2 == TDB_OFF_ERR))
861                         goto unlock_err;
862
863                 /* Maybe use a bit to indicate it is in ideal place? */
864                 h2 = hash_record(tdb, off2);
865                 /* Is it happy where it is? */
866                 if (hash_off(tdb, h2) == i)
867                         continue;
868
869                 /* Remove it. */
870                 if (tdb_write_off(tdb, i, 0) == -1)
871                         goto unlock_err;
872
873                 /* Rehash it. */
874                 if (hash_add(tdb, h2, off2) == -1)
875                         goto unlock_err;
876         }
877
878         /* Free the deleted entry. */
879         if (add_free_record(tdb, off,
880                             sizeof(struct tdb_used_record)
881                             + rec_key_length(&rec)
882                             + rec_data_length(&rec)
883                             + rec_extra_padding(&rec)) != 0)
884                 goto unlock_err;
885
886         unlock_lists(tdb, start, num_locks, F_WRLCK);
887         return 0;
888
889 unlock_err:
890         unlock_lists(tdb, start, num_locks, F_WRLCK);
891         return -1;
892 }
893
894 int tdb_close(struct tdb_context *tdb)
895 {
896         struct tdb_context **i;
897         int ret = 0;
898
899         /* FIXME:
900         if (tdb->transaction) {
901                 tdb_transaction_cancel(tdb);
902         }
903         */
904         tdb_trace(tdb, "tdb_close");
905
906         if (tdb->map_ptr) {
907                 if (tdb->flags & TDB_INTERNAL)
908                         free(tdb->map_ptr);
909                 else
910                         tdb_munmap(tdb);
911         }
912         free((char *)tdb->name);
913         if (tdb->fd != -1) {
914                 ret = close(tdb->fd);
915                 tdb->fd = -1;
916         }
917         free(tdb->lockrecs);
918
919         /* Remove from contexts list */
920         for (i = &tdbs; *i; i = &(*i)->next) {
921                 if (*i == tdb) {
922                         *i = tdb->next;
923                         break;
924                 }
925         }
926
927 #ifdef TDB_TRACE
928         close(tdb->tracefd);
929 #endif
930         free(tdb);
931
932         return ret;
933 }
934
935 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
936 {
937         return tdb->ecode;
938 }