]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/tdb.c
5d69eedcdc4ecf58079609628d59b902c4623b56
[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 update_header(struct tdb_context *tdb)
25 {
26         struct tdb_header_volatile pad, *v;
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         v = tdb_get(tdb, offsetof(struct tdb_header, v), &pad, sizeof(*v));
37         if (!v) {
38                 /* On failure, imply we updated header so they retry. */
39                 return true;
40         }
41         tdb->header_uptodate = true;
42         if (likely(memcmp(&tdb->header.v, v, sizeof(*v)) == 0)) {
43                 return false;
44         }
45         tdb->header.v = *v;
46         return true;
47 }
48
49 static uint64_t jenkins_hash(const void *key, size_t length, uint64_t seed,
50                              void *arg)
51 {
52         return hash64_stable((const unsigned char *)key, length, seed);
53 }
54
55 uint64_t tdb_hash(struct tdb_context *tdb, const void *ptr, size_t len)
56 {
57         return tdb->khash(ptr, len, tdb->header.hash_seed, tdb->hash_priv);
58 }
59
60 static bool tdb_already_open(dev_t device, ino_t ino)
61 {
62         struct tdb_context *i;
63         
64         for (i = tdbs; i; i = i->next) {
65                 if (i->device == device && i->inode == ino) {
66                         return true;
67                 }
68         }
69
70         return false;
71 }
72
73 static uint64_t random_number(struct tdb_context *tdb)
74 {
75         int fd;
76         uint64_t ret = 0;
77         struct timeval now;
78
79         fd = open("/dev/urandom", O_RDONLY);
80         if (fd >= 0) {
81                 if (tdb_read_all(fd, &ret, sizeof(ret))) {
82                         tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
83                                  "tdb_open: random from /dev/urandom\n");
84                         close(fd);
85                         return ret;
86                 }
87                 close(fd);
88         }
89         /* FIXME: Untested!  Based on Wikipedia protocol description! */
90         fd = open("/dev/egd-pool", O_RDWR);
91         if (fd >= 0) {
92                 /* Command is 1, next byte is size we want to read. */
93                 char cmd[2] = { 1, sizeof(uint64_t) };
94                 if (write(fd, cmd, sizeof(cmd)) == sizeof(cmd)) {
95                         char reply[1 + sizeof(uint64_t)];
96                         int r = read(fd, reply, sizeof(reply));
97                         if (r > 1) {
98                                 tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
99                                          "tdb_open: %u random bytes from"
100                                          " /dev/egd-pool\n", r-1);
101                                 /* Copy at least some bytes. */
102                                 memcpy(&ret, reply+1, r - 1);
103                                 if (reply[0] == sizeof(uint64_t)
104                                     && r == sizeof(reply)) {
105                                         close(fd);
106                                         return ret;
107                                 }
108                         }
109                 }
110                 close(fd);
111         }
112
113         /* Fallback: pid and time. */
114         gettimeofday(&now, NULL);
115         ret = getpid() * 100132289ULL + now.tv_sec * 1000000ULL + now.tv_usec;
116         tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
117                  "tdb_open: random from getpid and time\n");
118         return ret;
119 }
120
121 struct new_database {
122         struct tdb_header hdr;
123         struct tdb_used_record hrec;
124         tdb_off_t hash[1ULL << INITIAL_HASH_BITS];
125         struct tdb_used_record frec;
126         tdb_off_t free[INITIAL_FREE_BUCKETS + 1]; /* One overflow bucket */
127 };
128
129 /* initialise a new database */
130 static int tdb_new_database(struct tdb_context *tdb)
131 {
132         /* We make it up in memory, then write it out if not internal */
133         struct new_database newdb;
134         unsigned int magic_off = offsetof(struct tdb_header, magic_food);
135
136         /* Fill in the header */
137         newdb.hdr.version = TDB_VERSION;
138         newdb.hdr.hash_seed = random_number(tdb);
139         newdb.hdr.hash_test = TDB_HASH_MAGIC;
140         newdb.hdr.hash_test = tdb->khash(&newdb.hdr.hash_test,
141                                          sizeof(newdb.hdr.hash_test),
142                                          newdb.hdr.hash_seed,
143                                          tdb->hash_priv);
144
145         newdb.hdr.v.generation = 0;
146
147         /* The initial zone must cover the initial database size! */
148         BUILD_ASSERT((1ULL << INITIAL_ZONE_BITS) >= sizeof(newdb));
149
150         /* Free array has 1 zone, 10 buckets.  All buckets empty. */
151         newdb.hdr.v.num_zones = 1;
152         newdb.hdr.v.zone_bits = INITIAL_ZONE_BITS;
153         newdb.hdr.v.free_buckets = INITIAL_FREE_BUCKETS;
154         newdb.hdr.v.free_off = offsetof(struct new_database, free);
155         set_header(tdb, &newdb.frec, 0,
156                    sizeof(newdb.free), sizeof(newdb.free), 0);
157         memset(newdb.free, 0, sizeof(newdb.free));
158
159         /* Initial hashes are empty. */
160         newdb.hdr.v.hash_bits = INITIAL_HASH_BITS;
161         newdb.hdr.v.hash_off = offsetof(struct new_database, hash);
162         set_header(tdb, &newdb.hrec, 0,
163                    sizeof(newdb.hash), sizeof(newdb.hash), 0);
164         memset(newdb.hash, 0, sizeof(newdb.hash));
165
166         /* Magic food */
167         memset(newdb.hdr.magic_food, 0, sizeof(newdb.hdr.magic_food));
168         strcpy(newdb.hdr.magic_food, TDB_MAGIC_FOOD);
169
170         /* This creates an endian-converted database, as if read from disk */
171         tdb_convert(tdb,
172                     (char *)&newdb.hdr + magic_off,
173                     sizeof(newdb) - magic_off);
174
175         tdb->header = newdb.hdr;
176
177         if (tdb->flags & TDB_INTERNAL) {
178                 tdb->map_size = sizeof(newdb);
179                 tdb->map_ptr = malloc(tdb->map_size);
180                 if (!tdb->map_ptr) {
181                         tdb->ecode = TDB_ERR_OOM;
182                         return -1;
183                 }
184                 memcpy(tdb->map_ptr, &newdb, tdb->map_size);
185                 return 0;
186         }
187         if (lseek(tdb->fd, 0, SEEK_SET) == -1)
188                 return -1;
189
190         if (ftruncate(tdb->fd, 0) == -1)
191                 return -1;
192
193         if (!tdb_pwrite_all(tdb->fd, &newdb, sizeof(newdb), 0)) {
194                 tdb->ecode = TDB_ERR_IO;
195                 return -1;
196         }
197         return 0;
198 }
199
200 struct tdb_context *tdb_open(const char *name, int tdb_flags,
201                              int open_flags, mode_t mode,
202                              union tdb_attribute *attr)
203 {
204         struct tdb_context *tdb;
205         struct stat st;
206         int save_errno;
207         uint64_t hash_test;
208         unsigned v;
209
210         tdb = malloc(sizeof(*tdb));
211         if (!tdb) {
212                 /* Can't log this */
213                 errno = ENOMEM;
214                 goto fail;
215         }
216         tdb->name = NULL;
217         tdb->map_ptr = NULL;
218         tdb->fd = -1;
219         /* map_size will be set below. */
220         tdb->ecode = TDB_SUCCESS;
221         /* header will be read in below. */
222         tdb->header_uptodate = false;
223         tdb->flags = tdb_flags;
224         tdb->log = null_log_fn;
225         tdb->log_priv = NULL;
226         tdb->khash = jenkins_hash;
227         tdb->hash_priv = NULL;
228         tdb->transaction = NULL;
229         /* last_zone will be set below. */
230         tdb_io_init(tdb);
231         tdb_lock_init(tdb);
232
233         /* FIXME */
234         if (attr) {
235                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
236                          "tdb_open: attributes not yet supported\n");
237                 errno = EINVAL;
238                 goto fail;
239         }
240
241         if ((open_flags & O_ACCMODE) == O_WRONLY) {
242                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
243                          "tdb_open: can't open tdb %s write-only\n", name);
244                 errno = EINVAL;
245                 goto fail;
246         }
247
248         if ((open_flags & O_ACCMODE) == O_RDONLY) {
249                 tdb->read_only = true;
250                 /* read only databases don't do locking */
251                 tdb->flags |= TDB_NOLOCK;
252         } else
253                 tdb->read_only = false;
254
255         /* internal databases don't need any of the rest. */
256         if (tdb->flags & TDB_INTERNAL) {
257                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
258                 if (tdb_new_database(tdb) != 0) {
259                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
260                                  "tdb_open: tdb_new_database failed!");
261                         goto fail;
262                 }
263                 TEST_IT(tdb->flags & TDB_CONVERT);
264                 tdb_convert(tdb, &tdb->header, sizeof(tdb->header));
265                 return tdb;
266         }
267
268         if ((tdb->fd = open(name, open_flags, mode)) == -1) {
269                 tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
270                          "tdb_open: could not open file %s: %s\n",
271                          name, strerror(errno));
272                 goto fail;      /* errno set by open(2) */
273         }
274
275         /* on exec, don't inherit the fd */
276         v = fcntl(tdb->fd, F_GETFD, 0);
277         fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
278
279         /* ensure there is only one process initialising at once */
280         if (tdb_lock_open(tdb) == -1) {
281                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
282                          "tdb_open: failed to get open lock on %s: %s\n",
283                          name, strerror(errno));
284                 goto fail;      /* errno set by tdb_brlock */
285         }
286
287         if (!tdb_pread_all(tdb->fd, &tdb->header, sizeof(tdb->header), 0)
288             || strcmp(tdb->header.magic_food, TDB_MAGIC_FOOD) != 0) {
289                 if (!(open_flags & O_CREAT) || tdb_new_database(tdb) == -1) {
290                         if (errno == 0) {
291                                 errno = EIO; /* ie bad format or something */
292                         }
293                         goto fail;
294                 }
295         } else if (tdb->header.version != TDB_VERSION) {
296                 if (tdb->header.version == bswap_64(TDB_VERSION))
297                         tdb->flags |= TDB_CONVERT;
298                 else {
299                         /* wrong version */
300                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
301                                  "tdb_open: %s is unknown version 0x%llx\n",
302                                  name, (long long)tdb->header.version);
303                         errno = EIO;
304                         goto fail;
305                 }
306         }
307
308         tdb_convert(tdb, &tdb->header, sizeof(tdb->header));
309         hash_test = TDB_HASH_MAGIC;
310         hash_test = tdb->khash(&hash_test, sizeof(hash_test),
311                                tdb->header.hash_seed, tdb->hash_priv);
312         if (tdb->header.hash_test != hash_test) {
313                 /* wrong hash variant */
314                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
315                          "tdb_open: %s uses a different hash function\n",
316                          name);
317                 errno = EIO;
318                 goto fail;
319         }
320
321         if (fstat(tdb->fd, &st) == -1)
322                 goto fail;
323
324         /* Is it already in the open list?  If so, fail. */
325         if (tdb_already_open(st.st_dev, st.st_ino)) {
326                 /* FIXME */
327                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
328                          "tdb_open: %s (%d,%d) is already open in this process\n",
329                          name, (int)st.st_dev, (int)st.st_ino);
330                 errno = EBUSY;
331                 goto fail;
332         }
333
334         tdb->name = strdup(name);
335         if (!tdb->name) {
336                 errno = ENOMEM;
337                 goto fail;
338         }
339
340         tdb->map_size = st.st_size;
341         tdb->device = st.st_dev;
342         tdb->inode = st.st_ino;
343         tdb_mmap(tdb);
344         tdb_unlock_open(tdb);
345         tdb_zone_init(tdb);
346
347         tdb->next = tdbs;
348         tdbs = tdb;
349         return tdb;
350
351  fail:
352         save_errno = errno;
353
354         if (!tdb)
355                 return NULL;
356
357 #ifdef TDB_TRACE
358         close(tdb->tracefd);
359 #endif
360         if (tdb->map_ptr) {
361                 if (tdb->flags & TDB_INTERNAL) {
362                         free(tdb->map_ptr);
363                 } else
364                         tdb_munmap(tdb);
365         }
366         free((char *)tdb->name);
367         if (tdb->fd != -1)
368                 if (close(tdb->fd) != 0)
369                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
370                                  "tdb_open: failed to close tdb->fd"
371                                  " on error!\n");
372         free(tdb);
373         errno = save_errno;
374         return NULL;
375 }
376
377 static int tdb_key_compare(TDB_DATA key, TDB_DATA data, void *private_data)
378 {
379         return memcmp(data.dptr, key.dptr, data.dsize) == 0;
380 }
381
382 static void unlock_lists(struct tdb_context *tdb,
383                          uint64_t start, uint64_t end, int ltype)
384 {
385         do {
386                 tdb_unlock_list(tdb, start, ltype);
387                 start = (start + 1) & ((1ULL << tdb->header.v.hash_bits) - 1);
388         } while (start != end);
389 }
390
391 /* FIXME: Return header copy? */
392 /* Returns -1 or offset of entry (0 if not found).
393  * Locks hash entried from *start to *end (where the entry was found). */
394 static tdb_off_t find_bucket_and_lock(struct tdb_context *tdb,
395                                       const struct tdb_data *key,
396                                       uint64_t hash,
397                                       uint64_t *start,
398                                       uint64_t *end,
399                                       uint64_t *room,
400                                       int ltype)
401 {
402         uint64_t hextra;
403         tdb_off_t off;
404
405         /* hash_bits might be out of date... */
406 again:
407         *start = *end = hash & ((1ULL << tdb->header.v.hash_bits) - 1);
408         hextra = hash >> tdb->header.v.hash_bits;
409
410         /* FIXME: can we avoid locks for some fast paths? */
411         if (tdb_lock_list(tdb, *end, ltype, TDB_LOCK_WAIT) == -1)
412                 return TDB_OFF_ERR;
413
414         /* We only need to check this for first lock. */
415         if (unlikely(update_header(tdb))) {
416                 tdb_unlock_list(tdb, *end, ltype);
417                 goto again;
418         }
419
420         while ((off = tdb_read_off(tdb, tdb->header.v.hash_off
421                                    + *end * sizeof(tdb_off_t)))
422                != TDB_OFF_ERR) {
423                 struct tdb_used_record pad, *r;
424                 uint64_t keylen, next;
425
426                 /* Didn't find it? */
427                 if (!off)
428                         return 0;
429
430 #if 0 /* FIXME: Check other bits. */
431                 unsigned int bits, bitmask, hoffextra;
432                 /* Bottom three bits show how many extra hash bits. */
433                 bits = (off & ((1 << TDB_EXTRA_HASHBITS_NUM) - 1)) + 1;
434                 bitmask = (1 << bits)-1;
435                 hoffextra = ((off >> TDB_EXTRA_HASHBITS_NUM) & bitmask);
436                 if ((hextra & bitmask) != hoffextra) 
437                         goto lock_next;
438 #endif
439
440                 r = tdb_get(tdb, off, &pad, sizeof(*r));
441                 if (!r)
442                         goto unlock_err;
443
444                 if (rec_magic(r) != TDB_MAGIC) {
445                         tdb->ecode = TDB_ERR_CORRUPT;
446                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
447                                  "find_bucket_and_lock: bad magic 0x%llx"
448                                  " at offset %llu!\n",
449                                  (long long)rec_magic(r), (long long)off);
450                         goto unlock_err;
451                 }
452
453                 /* FIXME: check extra bits in header! */
454                 keylen = rec_key_length(r);
455                 if (keylen != key->dsize)
456                         goto lock_next;
457
458                 switch (tdb_parse_data(tdb, *key, off + sizeof(*r), key->dsize,
459                                        tdb_key_compare, NULL)) {
460                 case 1:
461                         /* Match! */
462                         *room = rec_data_length(r) + rec_extra_padding(r);
463                         return off >> TDB_EXTRA_HASHBITS_NUM;
464                 case 0:
465                         break;
466                 default:
467                         goto unlock_err;
468                 }
469
470         lock_next:
471                 /* Lock next bucket. */
472                 /* FIXME: We can deadlock if this wraps! */
473                 next = (*end + 1) & ((1ULL << tdb->header.v.hash_bits) - 1);
474                 if (next == *start) {
475                         tdb->ecode = TDB_ERR_CORRUPT;
476                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
477                                  "find_bucket_and_lock: full hash table!\n");
478                         goto unlock_err;
479                 }
480                 if (tdb_lock_list(tdb, next, ltype, TDB_LOCK_WAIT) == -1)
481                         goto unlock_err;
482                 *end = next;
483         }
484
485 unlock_err:
486         TEST_IT(*end < *start);
487         unlock_lists(tdb, *start, *end, ltype);
488         return TDB_OFF_ERR;
489 }
490
491 static int update_rec_hdr(struct tdb_context *tdb,
492                           tdb_off_t off,
493                           tdb_len_t keylen,
494                           tdb_len_t datalen,
495                           tdb_len_t room,
496                           uint64_t h)
497 {
498         struct tdb_used_record rec;
499
500         if (set_header(tdb, &rec, keylen, datalen, room - datalen, h))
501                 return -1;
502
503         return tdb_write_convert(tdb, off, &rec, sizeof(rec));
504 }
505
506 /* If we fail, others will try after us. */
507 static void enlarge_hash(struct tdb_context *tdb)
508 {
509         tdb_off_t newoff, i;
510         uint64_t h, num = 1ULL << tdb->header.v.hash_bits;
511         struct tdb_used_record pad, *r;
512
513         /* FIXME: We should do this without holding locks throughout. */
514         if (tdb_allrecord_lock(tdb, F_WRLCK, TDB_LOCK_WAIT, false) == -1)
515                 return;
516
517         if (unlikely(update_header(tdb))) {
518                 /* Someone else enlarged for us?  Nothing to do. */
519                 if ((1ULL << tdb->header.v.hash_bits) != num)
520                         goto unlock;
521         }
522
523         newoff = alloc(tdb, 0, num * 2, 0, false);
524         if (unlikely(newoff == TDB_OFF_ERR))
525                 goto unlock;
526         if (unlikely(newoff == 0)) {
527                 if (tdb_expand(tdb, 0, num * 2, false) == -1)
528                         goto unlock;
529                 newoff = alloc(tdb, 0, num * 2, 0, false);
530                 if (newoff == TDB_OFF_ERR || newoff == 0)
531                         goto unlock;
532         }
533
534         /* FIXME: If the space before is empty, we know this is in its ideal
535          * location.  We can steal a bit from the pointer to avoid rehash. */
536         for (i = tdb_find_nonzero_off(tdb, tdb->header.v.hash_off, num);
537              i < num;
538              i += tdb_find_nonzero_off(tdb, tdb->header.v.hash_off
539                                        + i*sizeof(tdb_off_t), num - i)) {
540                 tdb_off_t off;
541                 off = tdb_read_off(tdb, tdb->header.v.hash_off
542                                    + i*sizeof(tdb_off_t));
543                 if (unlikely(off == TDB_OFF_ERR))
544                         goto unlock;
545                 if (unlikely(!off)) {
546                         tdb->ecode = TDB_ERR_CORRUPT;
547                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
548                                  "find_bucket_and_lock: zero hash bucket!\n");
549                         goto unlock;
550                 }
551                 h = hash_record(tdb, off);
552                 /* FIXME: Encode extra hash bits! */
553                 if (tdb_write_off(tdb, newoff
554                                   + (h & ((num * 2) - 1)) * sizeof(uint64_t),
555                                   off) == -1)
556                         goto unlock;
557         }
558
559         /* Free up old hash. */
560         r = tdb_get(tdb, tdb->header.v.hash_off, &pad, sizeof(*r));
561         if (!r)
562                 goto unlock;
563         add_free_record(tdb, tdb->header.v.hash_off,
564                         rec_data_length(r) + rec_extra_padding(r));
565
566         /* Now we write the modified header. */
567         tdb->header.v.generation++;
568         tdb->header.v.hash_bits++;
569         tdb->header.v.hash_off = newoff;
570         tdb_write_convert(tdb, offsetof(struct tdb_header, v),
571                           &tdb->header.v, sizeof(tdb->header.v));
572 unlock:
573         tdb_allrecord_unlock(tdb, F_WRLCK);
574 }
575
576 int tdb_store(struct tdb_context *tdb,
577               struct tdb_data key, struct tdb_data dbuf, int flag)
578 {
579         tdb_off_t new_off, off, start, end, room;
580         uint64_t h;
581         bool growing = false;
582
583         h = tdb_hash(tdb, key.dptr, key.dsize);
584         off = find_bucket_and_lock(tdb, &key, h, &start, &end, &room, F_WRLCK);
585         if (off == TDB_OFF_ERR)
586                 return -1;
587
588         /* Now we have lock on this hash bucket. */
589         if (flag == TDB_INSERT) {
590                 if (off) {
591                         tdb->ecode = TDB_ERR_EXISTS;
592                         goto fail;
593                 }
594         } else {
595                 if (off) {
596                         if (room >= key.dsize + dbuf.dsize) {
597                                 new_off = off;
598                                 if (update_rec_hdr(tdb, off,
599                                                    key.dsize, dbuf.dsize,
600                                                    room, h))
601                                         goto fail;
602                                 goto write;
603                         }
604                         /* FIXME: See if right record is free? */
605                         /* Hint to allocator that we've realloced. */
606                         growing = true;
607                 } else {
608                         if (flag == TDB_MODIFY) {
609                                 /* if the record doesn't exist and we
610                                    are in TDB_MODIFY mode then we should fail
611                                    the store */
612                                 tdb->ecode = TDB_ERR_NOEXIST;
613                                 goto fail;
614                         }
615                 }
616         }
617
618         /* Allocate a new record. */
619         new_off = alloc(tdb, key.dsize, dbuf.dsize, h, growing);
620         if (new_off == 0) {
621                 unlock_lists(tdb, start, end, F_WRLCK);
622                 /* Expand, then try again... */
623                 if (tdb_expand(tdb, key.dsize, dbuf.dsize, growing) == -1)
624                         return -1;
625                 return tdb_store(tdb, key, dbuf, flag);
626         }
627
628         /* We didn't like the existing one: remove it. */
629         if (off) {
630                 add_free_record(tdb, off, sizeof(struct tdb_used_record)
631                                 + key.dsize + room);
632         }
633
634 write:
635         off = tdb->header.v.hash_off + end * sizeof(tdb_off_t);
636         /* FIXME: Encode extra hash bits! */
637         if (tdb_write_off(tdb, off, new_off) == -1)
638                 goto fail;
639
640         off = new_off + sizeof(struct tdb_used_record);
641         if (tdb->methods->write(tdb, off, key.dptr, key.dsize) == -1)
642                 goto fail;
643         off += key.dsize;
644         if (tdb->methods->write(tdb, off, dbuf.dptr, dbuf.dsize) == -1)
645                 goto fail;
646
647         /* FIXME: tdb_increment_seqnum(tdb); */
648         unlock_lists(tdb, start, end, F_WRLCK);
649
650         /* By simple trial and error, this roughly approximates a 60%
651          * full measure. */
652         if (unlikely(end - start > 4 * tdb->header.v.hash_bits - 32))
653                 enlarge_hash(tdb);
654
655         return 0;
656
657 fail:
658         unlock_lists(tdb, start, end, F_WRLCK);
659         return -1;
660 }
661
662 struct tdb_data tdb_fetch(struct tdb_context *tdb, struct tdb_data key)
663 {
664         tdb_off_t off, start, end, room;
665         uint64_t h;
666         struct tdb_used_record pad, *r;
667         struct tdb_data ret;
668
669         h = tdb_hash(tdb, key.dptr, key.dsize);
670         off = find_bucket_and_lock(tdb, &key, h, &start, &end, &room, F_RDLCK);
671         if (off == TDB_OFF_ERR)
672                 return tdb_null;
673
674         if (!off) {
675                 unlock_lists(tdb, start, end, F_RDLCK);
676                 tdb->ecode = TDB_SUCCESS;
677                 return tdb_null;
678         }
679
680         r = tdb_get(tdb, off, &pad, sizeof(*r));
681         if (!r) {
682                 unlock_lists(tdb, start, end, F_RDLCK);
683                 return tdb_null;
684         }
685
686         ret.dsize = rec_data_length(r);
687         ret.dptr = tdb_alloc_read(tdb, off + sizeof(*r) + key.dsize,
688                                   ret.dsize);
689         unlock_lists(tdb, start, end, F_RDLCK);
690         return ret;
691 }
692
693 static int hash_add(struct tdb_context *tdb, uint64_t h, tdb_off_t off)
694 {
695         tdb_off_t i, hoff, len, num;
696
697         i = (h & ((1ULL << tdb->header.v.hash_bits) - 1));
698         hoff = tdb->header.v.hash_off + i * sizeof(tdb_off_t);
699         len = (1ULL << tdb->header.v.hash_bits) - i;
700
701         /* Look for next space. */
702         num = tdb_find_zero_off(tdb, hoff, len);
703         if (unlikely(num == len)) {
704                 hoff = tdb->header.v.hash_off;
705                 len = (1ULL << tdb->header.v.hash_bits);
706                 num = tdb_find_zero_off(tdb, hoff, len);
707                 if (i == len)
708                         return -1;
709         }
710         /* FIXME: Encode extra hash bits! */
711         return tdb_write_off(tdb, hoff + num * sizeof(tdb_off_t), off);
712 }
713
714 static int unlink_used_record(struct tdb_context *tdb, tdb_off_t chain,
715                               uint64_t *extra_locks)
716 {
717         tdb_off_t num, len, i, hoff;
718
719         /* FIXME: Maybe lock more in search?  Maybe don't lock if scan
720          * finds none? */
721 again:
722         len = (1ULL << tdb->header.v.hash_bits) - (chain + 1);
723         hoff = tdb->header.v.hash_off + (chain + 1) * sizeof(tdb_off_t);
724         num = tdb_find_zero_off(tdb, hoff, len);
725
726         /* We want to lock the zero entry, too.  In the wrap case,
727          * this locks one extra.  That's harmless. */
728         num++;
729
730         for (i = chain + 1; i < chain + 1 + num; i++) {
731                 if (tdb_lock_list(tdb, i, F_WRLCK, TDB_LOCK_WAIT) == -1) {
732                         if (i != chain + 1)
733                                 unlock_lists(tdb, chain + 1, i-1, F_WRLCK);
734                         return -1;
735                 }
736         }
737
738         /* The wrap case: we need those locks out of order! */
739         if (unlikely(num == len + 1)) {
740                 *extra_locks = tdb_find_zero_off(tdb, tdb->header.v.hash_off,
741                                                  1ULL << tdb->header.v.hash_bits);
742                 (*extra_locks)++;
743                 for (i = 0; i < *extra_locks; i++) {
744                         if (tdb_lock_list(tdb, i, F_WRLCK, TDB_LOCK_NOWAIT)) {
745                                 /* Failed.  Caller must lock in order. */
746                                 if (i)
747                                         unlock_lists(tdb, 0, i-1, F_WRLCK);
748                                 unlock_lists(tdb, chain + 1, chain + num,
749                                              F_WRLCK);
750                                 return 1;
751                         }
752                 }
753                 num += *extra_locks;
754         }
755
756         /* Now we have the locks, be certain that offset is still 0! */
757         hoff = tdb->header.v.hash_off
758                 + (((chain + num) * sizeof(tdb_off_t))
759                    & ((1ULL << tdb->header.v.hash_bits) - 1));
760
761         if (unlikely(tdb_read_off(tdb, hoff) != 0)) {
762                 unlock_lists(tdb, chain + 1, chain + num, F_WRLCK);
763                 goto again;
764         }
765
766         /* OK, all locked.  Unlink first one. */
767         hoff = tdb->header.v.hash_off + chain * sizeof(tdb_off_t);
768         if (tdb_write_off(tdb, hoff, 0) == -1)
769                 goto unlock_err;
770
771         /* Rehash the rest. */
772         for (i = 1; i < num; i++) {
773                 tdb_off_t off;
774                 uint64_t h;
775
776                 hoff = tdb->header.v.hash_off
777                         + (((chain + i) * sizeof(tdb_off_t))
778                            & ((1ULL << tdb->header.v.hash_bits) - 1));
779                 off = tdb_read_off(tdb, hoff);
780                 if (unlikely(off == TDB_OFF_ERR))
781                         goto unlock_err;
782
783                 /* Maybe use a bit to indicate it is in ideal place? */
784                 h = hash_record(tdb, off);
785                 /* Is it happy where it is? */
786                 if ((h & ((1ULL << tdb->header.v.hash_bits)-1)) == (chain + i))
787                         continue;
788
789                 /* Remove it. */
790                 if (tdb_write_off(tdb, hoff, 0) == -1)
791                         goto unlock_err;
792
793                 /* Rehash it. */
794                 if (hash_add(tdb, h, off) == -1)
795                         goto unlock_err;
796         }
797         unlock_lists(tdb, chain + 1, chain + num, F_WRLCK);
798         return 0;
799
800 unlock_err:
801         unlock_lists(tdb, chain + 1, chain + num, F_WRLCK);
802         return -1;
803 }
804
805 int tdb_delete(struct tdb_context *tdb, struct tdb_data key)
806 {
807         tdb_off_t off, start, end, room, extra_locks = 0;
808         uint64_t h;
809         int ret;
810
811         h = tdb_hash(tdb, key.dptr, key.dsize);
812         off = find_bucket_and_lock(tdb, &key, h, &start, &end, &room, F_WRLCK);
813         if (off == TDB_OFF_ERR)
814                 return -1;
815
816         if (off == 0) {
817                 unlock_lists(tdb, start, end, F_WRLCK);
818                 tdb->ecode = TDB_ERR_NOEXIST;
819                 return -1;
820         }
821
822         ret = unlink_used_record(tdb, end, &extra_locks);
823         if (unlikely(ret == 1)) {
824                 unsigned int i;
825
826                 unlock_lists(tdb, start, end, F_WRLCK);
827
828                 /* We need extra locks at the start. */
829                 for (i = 0; i < extra_locks; i++) {
830                         if (tdb_lock_list(tdb, i, F_WRLCK, TDB_LOCK_WAIT)) {
831                                 if (i)
832                                         unlock_lists(tdb, 0, i-1, F_WRLCK);
833                                 return -1;
834                         }
835                 }
836                 /* Try again now we're holding more locks. */
837                 ret = tdb_delete(tdb, key);
838                 unlock_lists(tdb, 0, i, F_WRLCK);
839                 return ret;
840         }
841         unlock_lists(tdb, start, end, F_WRLCK);
842         return ret;
843 }
844
845 int tdb_close(struct tdb_context *tdb)
846 {
847         struct tdb_context **i;
848         int ret = 0;
849
850         /* FIXME:
851         if (tdb->transaction) {
852                 tdb_transaction_cancel(tdb);
853         }
854         */
855         tdb_trace(tdb, "tdb_close");
856
857         if (tdb->map_ptr) {
858                 if (tdb->flags & TDB_INTERNAL)
859                         free(tdb->map_ptr);
860                 else
861                         tdb_munmap(tdb);
862         }
863         free((char *)tdb->name);
864         if (tdb->fd != -1) {
865                 ret = close(tdb->fd);
866                 tdb->fd = -1;
867         }
868         free(tdb->lockrecs);
869
870         /* Remove from contexts list */
871         for (i = &tdbs; *i; i = &(*i)->next) {
872                 if (*i == tdb) {
873                         *i = tdb->next;
874                         break;
875                 }
876         }
877
878 #ifdef TDB_TRACE
879         close(tdb->tracefd);
880 #endif
881         free(tdb);
882
883         return ret;
884 }
885
886 enum TDB_ERROR tdb_error(struct tdb_context *tdb)
887 {
888         return tdb->ecode;
889 }