tdb2: import TDB1 code.
authorRusty Russell <rusty@rustcorp.com.au>
Wed, 31 Aug 2011 05:39:16 +0000 (15:09 +0930)
committerRusty Russell <rusty@rustcorp.com.au>
Wed, 31 Aug 2011 05:39:16 +0000 (15:09 +0930)
We import the entire codebase, putting a "tdb1_" prefix on the files
and changing the "tdb_" prefix to "tdb1_" everywhere.

The next patches will gradually merge it with the TDB2 code where
necessary.

15 files changed:
ccan/tdb2/tdb1.h [new file with mode: 0644]
ccan/tdb2/tdb1_check.c [new file with mode: 0644]
ccan/tdb2/tdb1_dump.c [new file with mode: 0644]
ccan/tdb2/tdb1_error.c [new file with mode: 0644]
ccan/tdb2/tdb1_freelist.c [new file with mode: 0644]
ccan/tdb2/tdb1_freelistcheck.c [new file with mode: 0644]
ccan/tdb2/tdb1_hash.c [new file with mode: 0644]
ccan/tdb2/tdb1_io.c [new file with mode: 0644]
ccan/tdb2/tdb1_lock.c [new file with mode: 0644]
ccan/tdb2/tdb1_open.c [new file with mode: 0644]
ccan/tdb2/tdb1_private.h [new file with mode: 0644]
ccan/tdb2/tdb1_summary.c [new file with mode: 0644]
ccan/tdb2/tdb1_tdb.c [new file with mode: 0644]
ccan/tdb2/tdb1_transaction.c [new file with mode: 0644]
ccan/tdb2/tdb1_traverse.c [new file with mode: 0644]

diff --git a/ccan/tdb2/tdb1.h b/ccan/tdb2/tdb1.h
new file mode 100644 (file)
index 0000000..12c13ef
--- /dev/null
@@ -0,0 +1,226 @@
+#ifndef TDB1_H
+#define TDB1_H
+
+/*
+   Unix SMB/CIFS implementation.
+
+   trivial database library (version 1 compat functions)
+
+   Copyright (C) Andrew Tridgell 1999-2004
+   Copyright (C) Rusty Russell 2011
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef _SAMBA_BUILD_
+/* For mode_t */
+#include <sys/types.h>
+/* For O_* flags. */
+#include <sys/stat.h>
+/* For sig_atomic_t. */
+#include <signal.h>
+#endif
+
+/** Flags to tdb1_store() */
+#define TDB1_REPLACE 1         /** Unused */
+#define TDB1_INSERT 2          /** Don't overwrite an existing entry */
+#define TDB1_MODIFY 3          /** Don't create an existing entry    */
+
+/** Flags for tdb1_open() */
+#define TDB1_DEFAULT 0 /** just a readability place holder */
+#define TDB1_CLEAR_IF_FIRST 1 /** If this is the first open, wipe the db */
+#define TDB1_INTERNAL 2 /** Don't store on disk */
+#define TDB1_NOLOCK   4 /** Don't do any locking */
+#define TDB1_NOMMAP   8 /** Don't use mmap */
+#define TDB1_CONVERT 16 /** Convert endian (internal use) */
+#define TDB1_BIGENDIAN 32 /** Header is big-endian (internal use) */
+#define TDB1_NOSYNC   64 /** Don't use synchronous transactions */
+#define TDB1_SEQNUM   128 /** Maintain a sequence number */
+#define TDB1_VOLATILE   256 /** Activate the per-hashchain freelist, default 5 */
+#define TDB1_ALLOW_NESTING 512 /** Allow transactions to nest */
+#define TDB1_DISALLOW_NESTING 1024 /** Disallow transactions to nest */
+#define TDB1_INCOMPATIBLE_HASH 2048 /** Better hashing: can't be opened by tdb < 1.2.6. */
+
+/** The tdb error codes */
+enum TDB1_ERROR {TDB1_SUCCESS=0, TDB1_ERR_CORRUPT, TDB1_ERR_IO, TDB1_ERR_LOCK,
+               TDB1_ERR_OOM, TDB1_ERR_EXISTS, TDB1_ERR_NOLOCK, TDB1_ERR_LOCK_TIMEOUT,
+               TDB1_ERR_NOEXIST, TDB1_ERR_EINVAL, TDB1_ERR_RDONLY,
+               TDB1_ERR_NESTING};
+
+/** Debugging uses one of the following levels */
+enum tdb1_debug_level {TDB1_DEBUG_FATAL = 0, TDB1_DEBUG_ERROR,
+                     TDB1_DEBUG_WARNING, TDB1_DEBUG_TRACE};
+
+/** The tdb data structure */
+typedef struct TDB1_DATA {
+       unsigned char *dptr;
+       size_t dsize;
+} TDB1_DATA;
+
+#ifndef PRINTF_ATTRIBUTE
+#if (__GNUC__ >= 3)
+/** Use gcc attribute to check printf fns.  a1 is the 1-based index of
+ * the parameter containing the format, and a2 the index of the first
+ * argument. Note that some gcc 2.x versions don't handle this
+ * properly **/
+#define PRINTF_ATTRIBUTE(a1, a2) __attribute__ ((format (__printf__, a1, a2)))
+#else
+#define PRINTF_ATTRIBUTE(a1, a2)
+#endif
+#endif
+
+/** This is the context structure that is returned from a db open. */
+typedef struct tdb1_context TDB1_CONTEXT;
+
+typedef int (*tdb1_traverse_func)(struct tdb1_context *, TDB1_DATA, TDB1_DATA, void *);
+typedef void (*tdb1_log_func)(struct tdb1_context *, enum tdb1_debug_level, const char *, ...) PRINTF_ATTRIBUTE(3, 4);
+typedef unsigned int (*tdb1_hash_func)(TDB1_DATA *key);
+
+struct tdb1_logging_context {
+        tdb1_log_func log_fn;
+        void *log_private;
+};
+
+struct tdb1_context *tdb1_open(const char *name, int hash_size, int tdb1_flags,
+                     int open_flags, mode_t mode);
+
+struct tdb1_context *tdb1_open_ex(const char *name, int hash_size, int tdb1_flags,
+                        int open_flags, mode_t mode,
+                        const struct tdb1_logging_context *log_ctx,
+                        tdb1_hash_func hash_fn);
+
+void tdb1_set_max_dead(struct tdb1_context *tdb, int max_dead);
+
+int tdb1_reopen(struct tdb1_context *tdb);
+
+int tdb1_reopen_all(int parent_longlived);
+
+void tdb1_set_logging_function(struct tdb1_context *tdb, const struct tdb1_logging_context *log_ctx);
+
+enum TDB1_ERROR tdb1_error(struct tdb1_context *tdb);
+
+const char *tdb1_errorstr(struct tdb1_context *tdb);
+
+TDB1_DATA tdb1_fetch(struct tdb1_context *tdb, TDB1_DATA key);
+
+int tdb1_parse_record(struct tdb1_context *tdb, TDB1_DATA key,
+                             int (*parser)(TDB1_DATA key, TDB1_DATA data,
+                                           void *private_data),
+                             void *private_data);
+
+int tdb1_delete(struct tdb1_context *tdb, TDB1_DATA key);
+
+int tdb1_store(struct tdb1_context *tdb, TDB1_DATA key, TDB1_DATA dbuf, int flag);
+
+int tdb1_append(struct tdb1_context *tdb, TDB1_DATA key, TDB1_DATA new_dbuf);
+
+int tdb1_close(struct tdb1_context *tdb);
+
+TDB1_DATA tdb1_firstkey(struct tdb1_context *tdb);
+
+TDB1_DATA tdb1_nextkey(struct tdb1_context *tdb, TDB1_DATA key);
+
+int tdb1_traverse(struct tdb1_context *tdb, tdb1_traverse_func fn, void *private_data);
+
+int tdb1_traverse_read(struct tdb1_context *tdb, tdb1_traverse_func fn, void *private_data);
+
+int tdb1_exists(struct tdb1_context *tdb, TDB1_DATA key);
+
+int tdb1_lockall(struct tdb1_context *tdb);
+
+int tdb1_lockall_nonblock(struct tdb1_context *tdb);
+
+int tdb1_unlockall(struct tdb1_context *tdb);
+
+int tdb1_lockall_read(struct tdb1_context *tdb);
+
+int tdb1_lockall_read_nonblock(struct tdb1_context *tdb);
+
+int tdb1_unlockall_read(struct tdb1_context *tdb);
+
+int tdb1_lockall_mark(struct tdb1_context *tdb);
+
+int tdb1_lockall_unmark(struct tdb1_context *tdb);
+
+const char *tdb1_name(struct tdb1_context *tdb);
+
+int tdb1_fd(struct tdb1_context *tdb);
+
+tdb1_log_func tdb1_log_fn(struct tdb1_context *tdb);
+
+void *tdb1_get_logging_private(struct tdb1_context *tdb);
+
+int tdb1_transaction_start(struct tdb1_context *tdb);
+
+int tdb1_transaction_start_nonblock(struct tdb1_context *tdb);
+
+int tdb1_transaction_prepare_commit(struct tdb1_context *tdb);
+
+int tdb1_transaction_commit(struct tdb1_context *tdb);
+
+int tdb1_transaction_cancel(struct tdb1_context *tdb);
+
+int tdb1_get_seqnum(struct tdb1_context *tdb);
+
+int tdb1_hash_size(struct tdb1_context *tdb);
+
+size_t tdb1_map_size(struct tdb1_context *tdb);
+
+int tdb1_get_flags(struct tdb1_context *tdb);
+
+void tdb1_add_flags(struct tdb1_context *tdb, unsigned flag);
+
+void tdb1_remove_flags(struct tdb1_context *tdb, unsigned flag);
+
+void tdb1_enable_seqnum(struct tdb1_context *tdb);
+
+void tdb1_increment_seqnum_nonblock(struct tdb1_context *tdb);
+
+unsigned int tdb1_jenkins_hash(TDB1_DATA *key);
+
+int tdb1_check(struct tdb1_context *tdb,
+             int (*check) (TDB1_DATA key, TDB1_DATA data, void *private_data),
+             void *private_data);
+
+/* @} ******************************************************************/
+
+/* Low level locking functions: use with care */
+int tdb1_chainlock(struct tdb1_context *tdb, TDB1_DATA key);
+int tdb1_chainlock_nonblock(struct tdb1_context *tdb, TDB1_DATA key);
+int tdb1_chainunlock(struct tdb1_context *tdb, TDB1_DATA key);
+int tdb1_chainlock_read(struct tdb1_context *tdb, TDB1_DATA key);
+int tdb1_chainunlock_read(struct tdb1_context *tdb, TDB1_DATA key);
+int tdb1_chainlock_mark(struct tdb1_context *tdb, TDB1_DATA key);
+int tdb1_chainlock_unmark(struct tdb1_context *tdb, TDB1_DATA key);
+
+void tdb1_setalarm_sigptr(struct tdb1_context *tdb, volatile sig_atomic_t *sigptr);
+
+/* wipe and repack */
+int tdb1_wipe_all(struct tdb1_context *tdb);
+int tdb1_repack(struct tdb1_context *tdb);
+
+/* Debug functions. Not used in production. */
+void tdb1_dump_all(struct tdb1_context *tdb);
+int tdb1_printfreelist(struct tdb1_context *tdb);
+int tdb1_validate_freelist(struct tdb1_context *tdb, int *pnum_entries);
+int tdb1_freelist_size(struct tdb1_context *tdb);
+char *tdb1_summary(struct tdb1_context *tdb);
+
+extern TDB1_DATA tdb1_null;
+
+#endif /* tdb1.h */
diff --git a/ccan/tdb2/tdb1_check.c b/ccan/tdb2/tdb1_check.c
new file mode 100644 (file)
index 0000000..d62a4b9
--- /dev/null
@@ -0,0 +1,472 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Rusty Russell            2009
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+#include "tdb1_private.h"
+
+/* Since we opened it, these shouldn't fail unless it's recent corruption. */
+static bool tdb1_check_header(struct tdb1_context *tdb, tdb1_off_t *recovery)
+{
+       struct tdb1_header hdr;
+       uint32_t h1, h2;
+
+       if (tdb->methods->tdb1_read(tdb, 0, &hdr, sizeof(hdr), 0) == -1)
+               return false;
+       if (strcmp(hdr.magic_food, TDB1_MAGIC_FOOD) != 0)
+               goto corrupt;
+
+       TDB1_CONV(hdr);
+       if (hdr.version != TDB1_VERSION)
+               goto corrupt;
+
+       if (hdr.rwlocks != 0 && hdr.rwlocks != TDB1_HASH_RWLOCK_MAGIC)
+               goto corrupt;
+
+       tdb1_header_hash(tdb, &h1, &h2);
+       if (hdr.magic1_hash && hdr.magic2_hash &&
+           (hdr.magic1_hash != h1 || hdr.magic2_hash != h2))
+               goto corrupt;
+
+       if (hdr.hash_size == 0)
+               goto corrupt;
+
+       if (hdr.hash_size != tdb->header.hash_size)
+               goto corrupt;
+
+       if (hdr.recovery_start != 0 &&
+           hdr.recovery_start < TDB1_DATA_START(tdb->header.hash_size))
+               goto corrupt;
+
+       *recovery = hdr.recovery_start;
+       return true;
+
+corrupt:
+       tdb->ecode = TDB1_ERR_CORRUPT;
+       TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "Header is corrupt\n"));
+       return false;
+}
+
+/* Generic record header check. */
+static bool tdb1_check_record(struct tdb1_context *tdb,
+                            tdb1_off_t off,
+                            const struct tdb1_record *rec)
+{
+       tdb1_off_t tailer;
+
+       /* Check rec->next: 0 or points to record offset, aligned. */
+       if (rec->next > 0 && rec->next < TDB1_DATA_START(tdb->header.hash_size)){
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                        "Record offset %d too small next %d\n",
+                        off, rec->next));
+               goto corrupt;
+       }
+       if (rec->next + sizeof(*rec) < rec->next) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                        "Record offset %d too large next %d\n",
+                        off, rec->next));
+               goto corrupt;
+       }
+       if ((rec->next % TDB1_ALIGNMENT) != 0) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                        "Record offset %d misaligned next %d\n",
+                        off, rec->next));
+               goto corrupt;
+       }
+       if (tdb->methods->tdb1_oob(tdb, rec->next+sizeof(*rec), 0))
+               goto corrupt;
+
+       /* Check rec_len: similar to rec->next, implies next record. */
+       if ((rec->rec_len % TDB1_ALIGNMENT) != 0) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                        "Record offset %d misaligned length %d\n",
+                        off, rec->rec_len));
+               goto corrupt;
+       }
+       /* Must fit tailer. */
+       if (rec->rec_len < sizeof(tailer)) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                        "Record offset %d too short length %d\n",
+                        off, rec->rec_len));
+               goto corrupt;
+       }
+       /* OOB allows "right at the end" access, so this works for last rec. */
+       if (tdb->methods->tdb1_oob(tdb, off+sizeof(*rec)+rec->rec_len, 0))
+               goto corrupt;
+
+       /* Check tailer. */
+       if (tdb1_ofs_read(tdb, off+sizeof(*rec)+rec->rec_len-sizeof(tailer),
+                        &tailer) == -1)
+               goto corrupt;
+       if (tailer != sizeof(*rec) + rec->rec_len) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                        "Record offset %d invalid tailer\n", off));
+               goto corrupt;
+       }
+
+       return true;
+
+corrupt:
+       tdb->ecode = TDB1_ERR_CORRUPT;
+       return false;
+}
+
+/* Grab some bytes: may copy if can't use mmap.
+   Caller has already done bounds check. */
+static TDB1_DATA get_bytes(struct tdb1_context *tdb,
+                         tdb1_off_t off, tdb1_len_t len)
+{
+       TDB1_DATA d;
+
+       d.dsize = len;
+
+       if (tdb->transaction == NULL && tdb->map_ptr != NULL)
+               d.dptr = (unsigned char *)tdb->map_ptr + off;
+       else
+               d.dptr = tdb1_alloc_read(tdb, off, d.dsize);
+       return d;
+}
+
+/* Frees data if we're not able to simply use mmap. */
+static void put_bytes(struct tdb1_context *tdb, TDB1_DATA d)
+{
+       if (tdb->transaction == NULL && tdb->map_ptr != NULL)
+               return;
+       free(d.dptr);
+}
+
+/* We use the excellent Jenkins lookup3 hash; this is based on hash_word2.
+ * See: http://burtleburtle.net/bob/c/lookup3.c
+ */
+#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
+static void jhash(uint32_t key, uint32_t *pc, uint32_t *pb)
+{
+       uint32_t a,b,c;
+
+       /* Set up the internal state */
+       a = b = c = 0xdeadbeef + *pc;
+       c += *pb;
+       a += key;
+       c ^= b; c -= rot(b,14);
+       a ^= c; a -= rot(c,11);
+       b ^= a; b -= rot(a,25);
+       c ^= b; c -= rot(b,16);
+       a ^= c; a -= rot(c,4);
+       b ^= a; b -= rot(a,14);
+       c ^= b; c -= rot(b,24);
+       *pc=c; *pb=b;
+}
+
+/*
+  We want to check that all free records are in the free list
+  (only once), and all free list entries are free records.  Similarly
+  for each hash chain of used records.
+
+  Doing that naively (without walking hash chains, since we want to be
+  linear) means keeping a list of records which have been seen in each
+  hash chain, and another of records pointed to (ie. next pointers
+  from records and the initial hash chain heads).  These two lists
+  should be equal.  This will take 8 bytes per record, and require
+  sorting at the end.
+
+  So instead, we record each offset in a bitmap such a way that
+  recording it twice will cancel out.  Since each offset should appear
+  exactly twice, the bitmap should be zero at the end.
+
+  The approach was inspired by Bloom Filters (see Wikipedia).  For
+  each value, we flip K bits in a bitmap of size N.  The number of
+  distinct arrangements is:
+
+       N! / (K! * (N-K)!)
+
+  Of course, not all arrangements are actually distinct, but testing
+  shows this formula to be close enough.
+
+  So, if K == 8 and N == 256, the probability of two things flipping the same
+  bits is 1 in 409,663,695,276,000.
+
+  Given that ldb uses a hash size of 10000, using 32 bytes per hash chain
+  (320k) seems reasonable.
+*/
+#define NUM_HASHES 8
+#define BITMAP_BITS 256
+
+static void bit_flip(unsigned char bits[], unsigned int idx)
+{
+       bits[idx / CHAR_BIT] ^= (1 << (idx % CHAR_BIT));
+}
+
+/* We record offsets in a bitmap for the particular chain it should be in.  */
+static void record_offset(unsigned char bits[], tdb1_off_t off)
+{
+       uint32_t h1 = off, h2 = 0;
+       unsigned int i;
+
+       /* We get two good hash values out of jhash2, so we use both.  Then
+        * we keep going to produce further hash values. */
+       for (i = 0; i < NUM_HASHES / 2; i++) {
+               jhash(off, &h1, &h2);
+               bit_flip(bits, h1 % BITMAP_BITS);
+               bit_flip(bits, h2 % BITMAP_BITS);
+               h2++;
+       }
+}
+
+/* Check that an in-use record is valid. */
+static bool tdb1_check_used_record(struct tdb1_context *tdb,
+                                 tdb1_off_t off,
+                                 const struct tdb1_record *rec,
+                                 unsigned char **hashes,
+                                 int (*check)(TDB1_DATA, TDB1_DATA, void *),
+                                 void *private_data)
+{
+       TDB1_DATA key, data;
+
+       if (!tdb1_check_record(tdb, off, rec))
+               return false;
+
+       /* key + data + tailer must fit in record */
+       if (rec->key_len + rec->data_len + sizeof(tdb1_off_t) > rec->rec_len) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                        "Record offset %d too short for contents\n", off));
+               return false;
+       }
+
+       key = get_bytes(tdb, off + sizeof(*rec), rec->key_len);
+       if (!key.dptr)
+               return false;
+
+       if (tdb->hash_fn(&key) != rec->full_hash) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                        "Record offset %d has incorrect hash\n", off));
+               goto fail_put_key;
+       }
+
+       /* Mark this offset as a known value for this hash bucket. */
+       record_offset(hashes[TDB1_BUCKET(rec->full_hash)+1], off);
+       /* And similarly if the next pointer is valid. */
+       if (rec->next)
+               record_offset(hashes[TDB1_BUCKET(rec->full_hash)+1], rec->next);
+
+       /* If they supply a check function and this record isn't dead,
+          get data and feed it. */
+       if (check && rec->magic != TDB1_DEAD_MAGIC) {
+               data = get_bytes(tdb, off + sizeof(*rec) + rec->key_len,
+                                rec->data_len);
+               if (!data.dptr)
+                       goto fail_put_key;
+
+               if (check(key, data, private_data) == -1)
+                       goto fail_put_data;
+               put_bytes(tdb, data);
+       }
+
+       put_bytes(tdb, key);
+       return true;
+
+fail_put_data:
+       put_bytes(tdb, data);
+fail_put_key:
+       put_bytes(tdb, key);
+       return false;
+}
+
+/* Check that an unused record is valid. */
+static bool tdb1_check_free_record(struct tdb1_context *tdb,
+                                 tdb1_off_t off,
+                                 const struct tdb1_record *rec,
+                                 unsigned char **hashes)
+{
+       if (!tdb1_check_record(tdb, off, rec))
+               return false;
+
+       /* Mark this offset as a known value for the free list. */
+       record_offset(hashes[0], off);
+       /* And similarly if the next pointer is valid. */
+       if (rec->next)
+               record_offset(hashes[0], rec->next);
+       return true;
+}
+
+/* Slow, but should be very rare. */
+size_t tdb1_dead_space(struct tdb1_context *tdb, tdb1_off_t off)
+{
+       size_t len;
+
+       for (len = 0; off + len < tdb->map_size; len++) {
+               char c;
+               if (tdb->methods->tdb1_read(tdb, off, &c, 1, 0))
+                       return 0;
+               if (c != 0 && c != 0x42)
+                       break;
+       }
+       return len;
+}
+
+_PUBLIC_ int tdb1_check(struct tdb1_context *tdb,
+             int (*check)(TDB1_DATA key, TDB1_DATA data, void *private_data),
+             void *private_data)
+{
+       unsigned int h;
+       unsigned char **hashes;
+       tdb1_off_t off, recovery_start;
+       struct tdb1_record rec;
+       bool found_recovery = false;
+       tdb1_len_t dead;
+       bool locked;
+
+       /* Read-only databases use no locking at all: it's best-effort.
+        * We may have a write lock already, so skip that case too. */
+       if (tdb->read_only || tdb->allrecord_lock.count != 0) {
+               locked = false;
+       } else {
+               if (tdb1_lockall_read(tdb) == -1)
+                       return -1;
+               locked = true;
+       }
+
+       /* Make sure we know true size of the underlying file. */
+       tdb->methods->tdb1_oob(tdb, tdb->map_size + 1, 1);
+
+       /* Header must be OK: also gets us the recovery ptr, if any. */
+       if (!tdb1_check_header(tdb, &recovery_start))
+               goto unlock;
+
+       /* We should have the whole header, too. */
+       if (tdb->map_size < TDB1_DATA_START(tdb->header.hash_size)) {
+               tdb->ecode = TDB1_ERR_CORRUPT;
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "File too short for hashes\n"));
+               goto unlock;
+       }
+
+       /* One big malloc: pointers then bit arrays. */
+       hashes = (unsigned char **)calloc(
+                       1, sizeof(hashes[0]) * (1+tdb->header.hash_size)
+                       + BITMAP_BITS / CHAR_BIT * (1+tdb->header.hash_size));
+       if (!hashes) {
+               tdb->ecode = TDB1_ERR_OOM;
+               goto unlock;
+       }
+
+       /* Initialize pointers */
+       hashes[0] = (unsigned char *)(&hashes[1+tdb->header.hash_size]);
+       for (h = 1; h < 1+tdb->header.hash_size; h++)
+               hashes[h] = hashes[h-1] + BITMAP_BITS / CHAR_BIT;
+
+       /* Freelist and hash headers are all in a row: read them. */
+       for (h = 0; h < 1+tdb->header.hash_size; h++) {
+               if (tdb1_ofs_read(tdb, TDB1_FREELIST_TOP + h*sizeof(tdb1_off_t),
+                                &off) == -1)
+                       goto free;
+               if (off)
+                       record_offset(hashes[h], off);
+       }
+
+       /* For each record, read it in and check it's ok. */
+       for (off = TDB1_DATA_START(tdb->header.hash_size);
+            off < tdb->map_size;
+            off += sizeof(rec) + rec.rec_len) {
+               if (tdb->methods->tdb1_read(tdb, off, &rec, sizeof(rec),
+                                          TDB1_DOCONV()) == -1)
+                       goto free;
+               switch (rec.magic) {
+               case TDB1_MAGIC:
+               case TDB1_DEAD_MAGIC:
+                       if (!tdb1_check_used_record(tdb, off, &rec, hashes,
+                                                  check, private_data))
+                               goto free;
+                       break;
+               case TDB1_FREE_MAGIC:
+                       if (!tdb1_check_free_record(tdb, off, &rec, hashes))
+                               goto free;
+                       break;
+               /* If we crash after ftruncate, we can get zeroes or fill. */
+               case TDB1_RECOVERY_INVALID_MAGIC:
+               case 0x42424242:
+                       if (recovery_start == off) {
+                               found_recovery = true;
+                               break;
+                       }
+                       dead = tdb1_dead_space(tdb, off);
+                       if (dead < sizeof(rec))
+                               goto corrupt;
+
+                       TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                                "Dead space at %d-%d (of %u)\n",
+                                off, off + dead, tdb->map_size));
+                       rec.rec_len = dead - sizeof(rec);
+                       break;
+               case TDB1_RECOVERY_MAGIC:
+                       if (recovery_start != off) {
+                               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                                        "Unexpected recovery record at offset %d\n",
+                                        off));
+                               goto free;
+                       }
+                       found_recovery = true;
+                       break;
+               default: ;
+               corrupt:
+                       tdb->ecode = TDB1_ERR_CORRUPT;
+                       TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                                "Bad magic 0x%x at offset %d\n",
+                                rec.magic, off));
+                       goto free;
+               }
+       }
+
+       /* Now, hashes should all be empty: each record exists and is referred
+        * to by one other. */
+       for (h = 0; h < 1+tdb->header.hash_size; h++) {
+               unsigned int i;
+               for (i = 0; i < BITMAP_BITS / CHAR_BIT; i++) {
+                       if (hashes[h][i] != 0) {
+                               tdb->ecode = TDB1_ERR_CORRUPT;
+                               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                                        "Hashes do not match records\n"));
+                               goto free;
+                       }
+               }
+       }
+
+       /* We must have found recovery area if there was one. */
+       if (recovery_start != 0 && !found_recovery) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                        "Expected a recovery area at %u\n",
+                        recovery_start));
+               goto free;
+       }
+
+       free(hashes);
+       if (locked) {
+               tdb1_unlockall_read(tdb);
+       }
+       return 0;
+
+free:
+       free(hashes);
+unlock:
+       if (locked) {
+               tdb1_unlockall_read(tdb);
+       }
+       return -1;
+}
diff --git a/ccan/tdb2/tdb1_dump.c b/ccan/tdb2/tdb1_dump.c
new file mode 100644 (file)
index 0000000..435a706
--- /dev/null
@@ -0,0 +1,136 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb1_private.h"
+
+static tdb1_off_t tdb1_dump_record(struct tdb1_context *tdb, int hash,
+                                tdb1_off_t offset)
+{
+       struct tdb1_record rec;
+       tdb1_off_t tailer_ofs, tailer;
+
+       if (tdb->methods->tdb1_read(tdb, offset, (char *)&rec,
+                                  sizeof(rec), TDB1_DOCONV()) == -1) {
+               printf("ERROR: failed to read record at %u\n", offset);
+               return 0;
+       }
+
+       printf(" rec: hash=%d offset=0x%08x next=0x%08x rec_len=%d "
+              "key_len=%d data_len=%d full_hash=0x%x magic=0x%x\n",
+              hash, offset, rec.next, rec.rec_len, rec.key_len, rec.data_len,
+              rec.full_hash, rec.magic);
+
+       tailer_ofs = offset + sizeof(rec) + rec.rec_len - sizeof(tdb1_off_t);
+
+       if (tdb1_ofs_read(tdb, tailer_ofs, &tailer) == -1) {
+               printf("ERROR: failed to read tailer at %u\n", tailer_ofs);
+               return rec.next;
+       }
+
+       if (tailer != rec.rec_len + sizeof(rec)) {
+               printf("ERROR: tailer does not match record! tailer=%u totalsize=%u\n",
+                               (unsigned int)tailer, (unsigned int)(rec.rec_len + sizeof(rec)));
+       }
+       return rec.next;
+}
+
+static int tdb1_dump_chain(struct tdb1_context *tdb, int i)
+{
+       tdb1_off_t rec_ptr, top;
+
+       top = TDB1_HASH_TOP(i);
+
+       if (tdb1_lock(tdb, i, F_WRLCK) != 0)
+               return -1;
+
+       if (tdb1_ofs_read(tdb, top, &rec_ptr) == -1)
+               return tdb1_unlock(tdb, i, F_WRLCK);
+
+       if (rec_ptr)
+               printf("hash=%d\n", i);
+
+       while (rec_ptr) {
+               rec_ptr = tdb1_dump_record(tdb, i, rec_ptr);
+       }
+
+       return tdb1_unlock(tdb, i, F_WRLCK);
+}
+
+_PUBLIC_ void tdb1_dump_all(struct tdb1_context *tdb)
+{
+       int i;
+       for (i=0;i<tdb->header.hash_size;i++) {
+               tdb1_dump_chain(tdb, i);
+       }
+       printf("freelist:\n");
+       tdb1_dump_chain(tdb, -1);
+}
+
+_PUBLIC_ int tdb1_printfreelist(struct tdb1_context *tdb)
+{
+       int ret;
+       long total_free = 0;
+       tdb1_off_t offset, rec_ptr;
+       struct tdb1_record rec;
+
+       if ((ret = tdb1_lock(tdb, -1, F_WRLCK)) != 0)
+               return ret;
+
+       offset = TDB1_FREELIST_TOP;
+
+       /* read in the freelist top */
+       if (tdb1_ofs_read(tdb, offset, &rec_ptr) == -1) {
+               tdb1_unlock(tdb, -1, F_WRLCK);
+               return 0;
+       }
+
+       printf("freelist top=[0x%08x]\n", rec_ptr );
+       while (rec_ptr) {
+               if (tdb->methods->tdb1_read(tdb, rec_ptr, (char *)&rec,
+                                          sizeof(rec), TDB1_DOCONV()) == -1) {
+                       tdb1_unlock(tdb, -1, F_WRLCK);
+                       return -1;
+               }
+
+               if (rec.magic != TDB1_FREE_MAGIC) {
+                       printf("bad magic 0x%08x in free list\n", rec.magic);
+                       tdb1_unlock(tdb, -1, F_WRLCK);
+                       return -1;
+               }
+
+               printf("entry offset=[0x%08x], rec.rec_len = [0x%08x (%d)] (end = 0x%08x)\n",
+                      rec_ptr, rec.rec_len, rec.rec_len, rec_ptr + rec.rec_len);
+               total_free += rec.rec_len;
+
+               /* move to the next record */
+               rec_ptr = rec.next;
+       }
+       printf("total rec_len = [0x%08x (%d)]\n", (int)total_free,
+               (int)total_free);
+
+       return tdb1_unlock(tdb, -1, F_WRLCK);
+}
diff --git a/ccan/tdb2/tdb1_error.c b/ccan/tdb2/tdb1_error.c
new file mode 100644 (file)
index 0000000..e555805
--- /dev/null
@@ -0,0 +1,56 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb1_private.h"
+
+_PUBLIC_ enum TDB1_ERROR tdb1_error(struct tdb1_context *tdb)
+{
+       return tdb->ecode;
+}
+
+static struct tdb1_errname {
+       enum TDB1_ERROR ecode; const char *estring;
+} emap[] = { {TDB1_SUCCESS, "Success"},
+            {TDB1_ERR_CORRUPT, "Corrupt database"},
+            {TDB1_ERR_IO, "IO Error"},
+            {TDB1_ERR_LOCK, "Locking error"},
+            {TDB1_ERR_OOM, "Out of memory"},
+            {TDB1_ERR_EXISTS, "Record exists"},
+            {TDB1_ERR_NOLOCK, "Lock exists on other keys"},
+            {TDB1_ERR_EINVAL, "Invalid parameter"},
+            {TDB1_ERR_NOEXIST, "Record does not exist"},
+            {TDB1_ERR_RDONLY, "write not permitted"} };
+
+/* Error string for the last tdb error */
+_PUBLIC_ const char *tdb1_errorstr(struct tdb1_context *tdb)
+{
+       uint32_t i;
+       for (i = 0; i < sizeof(emap) / sizeof(struct tdb1_errname); i++)
+               if (tdb->ecode == emap[i].ecode)
+                       return emap[i].estring;
+       return "Invalid error code";
+}
diff --git a/ccan/tdb2/tdb1_freelist.c b/ccan/tdb2/tdb1_freelist.c
new file mode 100644 (file)
index 0000000..9c40bc9
--- /dev/null
@@ -0,0 +1,386 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb1_private.h"
+
+/* 'right' merges can involve O(n^2) cost when combined with a
+   traverse, so they are disabled until we find a way to do them in
+   O(1) time
+*/
+#define USE_RIGHT_MERGES 0
+
+/* read a freelist record and check for simple errors */
+int tdb1_rec_free_read(struct tdb1_context *tdb, tdb1_off_t off, struct tdb1_record *rec)
+{
+       if (tdb->methods->tdb1_read(tdb, off, rec, sizeof(*rec),TDB1_DOCONV()) == -1)
+               return -1;
+
+       if (rec->magic == TDB1_MAGIC) {
+               /* this happens when a app is showdown while deleting a record - we should
+                  not completely fail when this happens */
+               TDB1_LOG((tdb, TDB1_DEBUG_WARNING, "tdb1_rec_free_read non-free magic 0x%x at offset=%d - fixing\n",
+                        rec->magic, off));
+               rec->magic = TDB1_FREE_MAGIC;
+               if (tdb->methods->tdb1_write(tdb, off, rec, sizeof(*rec)) == -1)
+                       return -1;
+       }
+
+       if (rec->magic != TDB1_FREE_MAGIC) {
+               /* Ensure ecode is set for log fn. */
+               tdb->ecode = TDB1_ERR_CORRUPT;
+               TDB1_LOG((tdb, TDB1_DEBUG_WARNING, "tdb1_rec_free_read bad magic 0x%x at offset=%d\n",
+                          rec->magic, off));
+               return -1;
+       }
+       if (tdb->methods->tdb1_oob(tdb, rec->next+sizeof(*rec), 0) != 0)
+               return -1;
+       return 0;
+}
+
+
+#if USE_RIGHT_MERGES
+/* Remove an element from the freelist.  Must have alloc lock. */
+static int remove_from_freelist(struct tdb1_context *tdb, tdb1_off_t off, tdb1_off_t next)
+{
+       tdb1_off_t last_ptr, i;
+
+       /* read in the freelist top */
+       last_ptr = TDB1_FREELIST_TOP;
+       while (tdb1_ofs_read(tdb, last_ptr, &i) != -1 && i != 0) {
+               if (i == off) {
+                       /* We've found it! */
+                       return tdb1_ofs_write(tdb, last_ptr, &next);
+               }
+               /* Follow chain (next offset is at start of record) */
+               last_ptr = i;
+       }
+       tdb->ecode = TDB1_ERR_CORRUPT;
+       TDB1_LOG((tdb, TDB1_DEBUG_FATAL,"remove_from_freelist: not on list at off=%d\n", off));
+       return -1;
+}
+#endif
+
+
+/* update a record tailer (must hold allocation lock) */
+static int update_tailer(struct tdb1_context *tdb, tdb1_off_t offset,
+                        const struct tdb1_record *rec)
+{
+       tdb1_off_t totalsize;
+
+       /* Offset of tailer from record header */
+       totalsize = sizeof(*rec) + rec->rec_len;
+       return tdb1_ofs_write(tdb, offset + totalsize - sizeof(tdb1_off_t),
+                        &totalsize);
+}
+
+/* Add an element into the freelist. Merge adjacent records if
+   necessary. */
+int tdb1_free(struct tdb1_context *tdb, tdb1_off_t offset, struct tdb1_record *rec)
+{
+       /* Allocation and tailer lock */
+       if (tdb1_lock(tdb, -1, F_WRLCK) != 0)
+               return -1;
+
+       /* set an initial tailer, so if we fail we don't leave a bogus record */
+       if (update_tailer(tdb, offset, rec) != 0) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_free: update_tailer failed!\n"));
+               goto fail;
+       }
+
+#if USE_RIGHT_MERGES
+       /* Look right first (I'm an Australian, dammit) */
+       if (offset + sizeof(*rec) + rec->rec_len + sizeof(*rec) <= tdb->map_size) {
+               tdb1_off_t right = offset + sizeof(*rec) + rec->rec_len;
+               struct tdb1_record r;
+
+               if (tdb->methods->tdb1_read(tdb, right, &r, sizeof(r), TDB1_DOCONV()) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_free: right read failed at %u\n", right));
+                       goto left;
+               }
+
+               /* If it's free, expand to include it. */
+               if (r.magic == TDB1_FREE_MAGIC) {
+                       if (remove_from_freelist(tdb, right, r.next) == -1) {
+                               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_free: right free failed at %u\n", right));
+                               goto left;
+                       }
+                       rec->rec_len += sizeof(r) + r.rec_len;
+                       if (update_tailer(tdb, offset, rec) == -1) {
+                               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_free: update_tailer failed at %u\n", offset));
+                               goto fail;
+                       }
+               }
+       }
+left:
+#endif
+
+       /* Look left */
+       if (offset - sizeof(tdb1_off_t) > TDB1_DATA_START(tdb->header.hash_size)) {
+               tdb1_off_t left = offset - sizeof(tdb1_off_t);
+               struct tdb1_record l;
+               tdb1_off_t leftsize;
+
+               /* Read in tailer and jump back to header */
+               if (tdb1_ofs_read(tdb, left, &leftsize) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_free: left offset read failed at %u\n", left));
+                       goto update;
+               }
+
+               /* it could be uninitialised data */
+               if (leftsize == 0 || leftsize == TDB1_PAD_U32) {
+                       goto update;
+               }
+
+               left = offset - leftsize;
+
+               if (leftsize > offset ||
+                   left < TDB1_DATA_START(tdb->header.hash_size)) {
+                       goto update;
+               }
+
+               /* Now read in the left record */
+               if (tdb->methods->tdb1_read(tdb, left, &l, sizeof(l), TDB1_DOCONV()) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_free: left read failed at %u (%u)\n", left, leftsize));
+                       goto update;
+               }
+
+               /* If it's free, expand to include it. */
+               if (l.magic == TDB1_FREE_MAGIC) {
+                       /* we now merge the new record into the left record, rather than the other
+                          way around. This makes the operation O(1) instead of O(n). This change
+                          prevents traverse from being O(n^2) after a lot of deletes */
+                       l.rec_len += sizeof(*rec) + rec->rec_len;
+                       if (tdb1_rec_write(tdb, left, &l) == -1) {
+                               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_free: update_left failed at %u\n", left));
+                               goto fail;
+                       }
+                       if (update_tailer(tdb, left, &l) == -1) {
+                               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_free: update_tailer failed at %u\n", offset));
+                               goto fail;
+                       }
+                       tdb1_unlock(tdb, -1, F_WRLCK);
+                       return 0;
+               }
+       }
+
+update:
+
+       /* Now, prepend to free list */
+       rec->magic = TDB1_FREE_MAGIC;
+
+       if (tdb1_ofs_read(tdb, TDB1_FREELIST_TOP, &rec->next) == -1 ||
+           tdb1_rec_write(tdb, offset, rec) == -1 ||
+           tdb1_ofs_write(tdb, TDB1_FREELIST_TOP, &offset) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_free record write failed at offset=%d\n", offset));
+               goto fail;
+       }
+
+       /* And we're done. */
+       tdb1_unlock(tdb, -1, F_WRLCK);
+       return 0;
+
+ fail:
+       tdb1_unlock(tdb, -1, F_WRLCK);
+       return -1;
+}
+
+
+
+/*
+   the core of tdb1_allocate - called when we have decided which
+   free list entry to use
+
+   Note that we try to allocate by grabbing data from the end of an existing record,
+   not the beginning. This is so the left merge in a free is more likely to be
+   able to free up the record without fragmentation
+ */
+static tdb1_off_t tdb1_allocate_ofs(struct tdb1_context *tdb,
+                                 tdb1_len_t length, tdb1_off_t rec_ptr,
+                                 struct tdb1_record *rec, tdb1_off_t last_ptr)
+{
+#define MIN_REC_SIZE (sizeof(struct tdb1_record) + sizeof(tdb1_off_t) + 8)
+
+       if (rec->rec_len < length + MIN_REC_SIZE) {
+               /* we have to grab the whole record */
+
+               /* unlink it from the previous record */
+               if (tdb1_ofs_write(tdb, last_ptr, &rec->next) == -1) {
+                       return 0;
+               }
+
+               /* mark it not free */
+               rec->magic = TDB1_MAGIC;
+               if (tdb1_rec_write(tdb, rec_ptr, rec) == -1) {
+                       return 0;
+               }
+               return rec_ptr;
+       }
+
+       /* we're going to just shorten the existing record */
+       rec->rec_len -= (length + sizeof(*rec));
+       if (tdb1_rec_write(tdb, rec_ptr, rec) == -1) {
+               return 0;
+       }
+       if (update_tailer(tdb, rec_ptr, rec) == -1) {
+               return 0;
+       }
+
+       /* and setup the new record */
+       rec_ptr += sizeof(*rec) + rec->rec_len;
+
+       memset(rec, '\0', sizeof(*rec));
+       rec->rec_len = length;
+       rec->magic = TDB1_MAGIC;
+
+       if (tdb1_rec_write(tdb, rec_ptr, rec) == -1) {
+               return 0;
+       }
+
+       if (update_tailer(tdb, rec_ptr, rec) == -1) {
+               return 0;
+       }
+
+       return rec_ptr;
+}
+
+/* allocate some space from the free list. The offset returned points
+   to a unconnected tdb1_record within the database with room for at
+   least length bytes of total data
+
+   0 is returned if the space could not be allocated
+ */
+tdb1_off_t tdb1_allocate(struct tdb1_context *tdb, tdb1_len_t length, struct tdb1_record *rec)
+{
+       tdb1_off_t rec_ptr, last_ptr, newrec_ptr;
+       struct {
+               tdb1_off_t rec_ptr, last_ptr;
+               tdb1_len_t rec_len;
+       } bestfit;
+       float multiplier = 1.0;
+
+       if (tdb1_lock(tdb, -1, F_WRLCK) == -1)
+               return 0;
+
+       /* over-allocate to reduce fragmentation */
+       length *= 1.25;
+
+       /* Extra bytes required for tailer */
+       length += sizeof(tdb1_off_t);
+       length = TDB1_ALIGN(length, TDB1_ALIGNMENT);
+
+ again:
+       last_ptr = TDB1_FREELIST_TOP;
+
+       /* read in the freelist top */
+       if (tdb1_ofs_read(tdb, TDB1_FREELIST_TOP, &rec_ptr) == -1)
+               goto fail;
+
+       bestfit.rec_ptr = 0;
+       bestfit.last_ptr = 0;
+       bestfit.rec_len = 0;
+
+       /*
+          this is a best fit allocation strategy. Originally we used
+          a first fit strategy, but it suffered from massive fragmentation
+          issues when faced with a slowly increasing record size.
+        */
+       while (rec_ptr) {
+               if (tdb1_rec_free_read(tdb, rec_ptr, rec) == -1) {
+                       goto fail;
+               }
+
+               if (rec->rec_len >= length) {
+                       if (bestfit.rec_ptr == 0 ||
+                           rec->rec_len < bestfit.rec_len) {
+                               bestfit.rec_len = rec->rec_len;
+                               bestfit.rec_ptr = rec_ptr;
+                               bestfit.last_ptr = last_ptr;
+                       }
+               }
+
+               /* move to the next record */
+               last_ptr = rec_ptr;
+               rec_ptr = rec->next;
+
+               /* if we've found a record that is big enough, then
+                  stop searching if its also not too big. The
+                  definition of 'too big' changes as we scan
+                  through */
+               if (bestfit.rec_len > 0 &&
+                   bestfit.rec_len < length * multiplier) {
+                       break;
+               }
+
+               /* this multiplier means we only extremely rarely
+                  search more than 50 or so records. At 50 records we
+                  accept records up to 11 times larger than what we
+                  want */
+               multiplier *= 1.05;
+       }
+
+       if (bestfit.rec_ptr != 0) {
+               if (tdb1_rec_free_read(tdb, bestfit.rec_ptr, rec) == -1) {
+                       goto fail;
+               }
+
+               newrec_ptr = tdb1_allocate_ofs(tdb, length, bestfit.rec_ptr,
+                                             rec, bestfit.last_ptr);
+               tdb1_unlock(tdb, -1, F_WRLCK);
+               return newrec_ptr;
+       }
+
+       /* we didn't find enough space. See if we can expand the
+          database and if we can then try again */
+       if (tdb1_expand(tdb, length + sizeof(*rec)) == 0)
+               goto again;
+ fail:
+       tdb1_unlock(tdb, -1, F_WRLCK);
+       return 0;
+}
+
+
+
+/*
+   return the size of the freelist - used to decide if we should repack
+*/
+_PUBLIC_ int tdb1_freelist_size(struct tdb1_context *tdb)
+{
+       tdb1_off_t ptr;
+       int count=0;
+
+       if (tdb1_lock(tdb, -1, F_RDLCK) == -1) {
+               return -1;
+       }
+
+       ptr = TDB1_FREELIST_TOP;
+       while (tdb1_ofs_read(tdb, ptr, &ptr) == 0 && ptr != 0) {
+               count++;
+       }
+
+       tdb1_unlock(tdb, -1, F_RDLCK);
+       return count;
+}
diff --git a/ccan/tdb2/tdb1_freelistcheck.c b/ccan/tdb2/tdb1_freelistcheck.c
new file mode 100644 (file)
index 0000000..c095ea5
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Jeremy Allison                    2006
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb1_private.h"
+
+/* Check the freelist is good and contains no loops.
+   Very memory intensive - only do this as a consistency
+   checker. Heh heh - uses an in memory tdb as the storage
+   for the "seen" record list. For some reason this strikes
+   me as extremely clever as I don't have to write another tree
+   data structure implementation :-).
+ */
+
+static int seen_insert(struct tdb1_context *mem_tdb, tdb1_off_t rec_ptr)
+{
+       TDB1_DATA key, data;
+
+       memset(&data, '\0', sizeof(data));
+       key.dptr = (unsigned char *)&rec_ptr;
+       key.dsize = sizeof(rec_ptr);
+       return tdb1_store(mem_tdb, key, data, TDB1_INSERT);
+}
+
+_PUBLIC_ int tdb1_validate_freelist(struct tdb1_context *tdb, int *pnum_entries)
+{
+       struct tdb1_context *mem_tdb = NULL;
+       struct tdb1_record rec;
+       tdb1_off_t rec_ptr, last_ptr;
+       int ret = -1;
+
+       *pnum_entries = 0;
+
+       mem_tdb = tdb1_open("flval", tdb->header.hash_size,
+                               TDB1_INTERNAL, O_RDWR, 0600);
+       if (!mem_tdb) {
+               return -1;
+       }
+
+       if (tdb1_lock(tdb, -1, F_WRLCK) == -1) {
+               tdb1_close(mem_tdb);
+               return 0;
+       }
+
+       last_ptr = TDB1_FREELIST_TOP;
+
+       /* Store the TDB1_FREELIST_TOP record. */
+       if (seen_insert(mem_tdb, last_ptr) == -1) {
+               tdb->ecode = TDB1_ERR_CORRUPT;
+               ret = -1;
+               goto fail;
+       }
+
+       /* read in the freelist top */
+       if (tdb1_ofs_read(tdb, TDB1_FREELIST_TOP, &rec_ptr) == -1) {
+               goto fail;
+       }
+
+       while (rec_ptr) {
+
+               /* If we can't store this record (we've seen it
+                  before) then the free list has a loop and must
+                  be corrupt. */
+
+               if (seen_insert(mem_tdb, rec_ptr)) {
+                       tdb->ecode = TDB1_ERR_CORRUPT;
+                       ret = -1;
+                       goto fail;
+               }
+
+               if (tdb1_rec_free_read(tdb, rec_ptr, &rec) == -1) {
+                       goto fail;
+               }
+
+               /* move to the next record */
+               last_ptr = rec_ptr;
+               rec_ptr = rec.next;
+               *pnum_entries += 1;
+       }
+
+       ret = 0;
+
+  fail:
+
+       tdb1_close(mem_tdb);
+       tdb1_unlock(tdb, -1, F_WRLCK);
+       return ret;
+}
diff --git a/ccan/tdb2/tdb1_hash.c b/ccan/tdb2/tdb1_hash.c
new file mode 100644 (file)
index 0000000..8a33e8a
--- /dev/null
@@ -0,0 +1,345 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Rusty Russell            2010
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+#include "tdb1_private.h"
+
+/* This is based on the hash algorithm from gdbm */
+unsigned int tdb1_old_hash(TDB1_DATA *key)
+{
+       uint32_t value; /* Used to compute the hash value.  */
+       uint32_t   i;   /* Used to cycle through random values. */
+
+       /* Set the initial value from the key size. */
+       for (value = 0x238F13AF * key->dsize, i=0; i < key->dsize; i++)
+               value = (value + (key->dptr[i] << (i*5 % 24)));
+
+       return (1103515243 * value + 12345);
+}
+
+#ifndef WORDS_BIGENDIAN
+# define HASH_LITTLE_ENDIAN 1
+# define HASH_BIG_ENDIAN 0
+#else
+# define HASH_LITTLE_ENDIAN 0
+# define HASH_BIG_ENDIAN 1
+#endif
+
+/*
+-------------------------------------------------------------------------------
+lookup3.c, by Bob Jenkins, May 2006, Public Domain.
+
+These are functions for producing 32-bit hashes for hash table lookup.
+hash_word(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
+are externally useful functions.  Routines to test the hash are included
+if SELF_TEST is defined.  You can use this free for any purpose.  It's in
+the public domain.  It has no warranty.
+
+You probably want to use hashlittle().  hashlittle() and hashbig()
+hash byte arrays.  hashlittle() is is faster than hashbig() on
+little-endian machines.  Intel and AMD are little-endian machines.
+On second thought, you probably want hashlittle2(), which is identical to
+hashlittle() except it returns two 32-bit hashes for the price of one.
+You could implement hashbig2() if you wanted but I haven't bothered here.
+
+If you want to find a hash of, say, exactly 7 integers, do
+  a = i1;  b = i2;  c = i3;
+  mix(a,b,c);
+  a += i4; b += i5; c += i6;
+  mix(a,b,c);
+  a += i7;
+  final(a,b,c);
+then use c as the hash value.  If you have a variable length array of
+4-byte integers to hash, use hash_word().  If you have a byte array (like
+a character string), use hashlittle().  If you have several byte arrays, or
+a mix of things, see the comments above hashlittle().
+
+Why is this so big?  I read 12 bytes at a time into 3 4-byte integers,
+then mix those integers.  This is fast (you can do a lot more thorough
+mixing with 12*3 instructions on 3 integers than you can with 3 instructions
+on 1 byte), but shoehorning those bytes into integers efficiently is messy.
+*/
+
+#define hashsize(n) ((uint32_t)1<<(n))
+#define hashmask(n) (hashsize(n)-1)
+#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
+
+/*
+-------------------------------------------------------------------------------
+mix -- mix 3 32-bit values reversibly.
+
+This is reversible, so any information in (a,b,c) before mix() is
+still in (a,b,c) after mix().
+
+If four pairs of (a,b,c) inputs are run through mix(), or through
+mix() in reverse, there are at least 32 bits of the output that
+are sometimes the same for one pair and different for another pair.
+This was tested for:
+* pairs that differed by one bit, by two bits, in any combination
+  of top bits of (a,b,c), or in any combination of bottom bits of
+  (a,b,c).
+* "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
+  the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+  is commonly produced by subtraction) look like a single 1-bit
+  difference.
+* the base values were pseudorandom, all zero but one bit set, or
+  all zero plus a counter that starts at zero.
+
+Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
+satisfy this are
+    4  6  8 16 19  4
+    9 15  3 18 27 15
+   14  9  3  7 17  3
+Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
+for "differ" defined as + with a one-bit base and a two-bit delta.  I
+used http://burtleburtle.net/bob/hash/avalanche.html to choose
+the operations, constants, and arrangements of the variables.
+
+This does not achieve avalanche.  There are input bits of (a,b,c)
+that fail to affect some output bits of (a,b,c), especially of a.  The
+most thoroughly mixed value is c, but it doesn't really even achieve
+avalanche in c.
+
+This allows some parallelism.  Read-after-writes are good at doubling
+the number of bits affected, so the goal of mixing pulls in the opposite
+direction as the goal of parallelism.  I did what I could.  Rotates
+seem to cost as much as shifts on every machine I could lay my hands
+on, and rotates are much kinder to the top and bottom bits, so I used
+rotates.
+-------------------------------------------------------------------------------
+*/
+#define mix(a,b,c) \
+{ \
+  a -= c;  a ^= rot(c, 4);  c += b; \
+  b -= a;  b ^= rot(a, 6);  a += c; \
+  c -= b;  c ^= rot(b, 8);  b += a; \
+  a -= c;  a ^= rot(c,16);  c += b; \
+  b -= a;  b ^= rot(a,19);  a += c; \
+  c -= b;  c ^= rot(b, 4);  b += a; \
+}
+
+/*
+-------------------------------------------------------------------------------
+final -- final mixing of 3 32-bit values (a,b,c) into c
+
+Pairs of (a,b,c) values differing in only a few bits will usually
+produce values of c that look totally different.  This was tested for
+* pairs that differed by one bit, by two bits, in any combination
+  of top bits of (a,b,c), or in any combination of bottom bits of
+  (a,b,c).
+* "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
+  the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+  is commonly produced by subtraction) look like a single 1-bit
+  difference.
+* the base values were pseudorandom, all zero but one bit set, or
+  all zero plus a counter that starts at zero.
+
+These constants passed:
+ 14 11 25 16 4 14 24
+ 12 14 25 16 4 14 24
+and these came close:
+  4  8 15 26 3 22 24
+ 10  8 15 26 3 22 24
+ 11  8 15 26 3 22 24
+-------------------------------------------------------------------------------
+*/
+#define final(a,b,c) \
+{ \
+  c ^= b; c -= rot(b,14); \
+  a ^= c; a -= rot(c,11); \
+  b ^= a; b -= rot(a,25); \
+  c ^= b; c -= rot(b,16); \
+  a ^= c; a -= rot(c,4);  \
+  b ^= a; b -= rot(a,14); \
+  c ^= b; c -= rot(b,24); \
+}
+
+
+/*
+-------------------------------------------------------------------------------
+hashlittle() -- hash a variable-length key into a 32-bit value
+  k       : the key (the unaligned variable-length array of bytes)
+  length  : the length of the key, counting by bytes
+  val2    : IN: can be any 4-byte value OUT: second 32 bit hash.
+Returns a 32-bit value.  Every bit of the key affects every bit of
+the return value.  Two keys differing by one or two bits will have
+totally different hash values.  Note that the return value is better
+mixed than val2, so use that first.
+
+The best hash table sizes are powers of 2.  There is no need to do
+mod a prime (mod is sooo slow!).  If you need less than 32 bits,
+use a bitmask.  For example, if you need only 10 bits, do
+  h = (h & hashmask(10));
+In which case, the hash table should have hashsize(10) elements.
+
+If you are hashing n strings (uint8_t **)k, do it like this:
+  for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
+
+By Bob Jenkins, 2006.  bob_jenkins@burtleburtle.net.  You may use this
+code any way you wish, private, educational, or commercial.  It's free.
+
+Use for hash table lookup, or anything where one collision in 2^^32 is
+acceptable.  Do NOT use for cryptographic purposes.
+-------------------------------------------------------------------------------
+*/
+
+static uint32_t hashlittle( const void *key, size_t length )
+{
+  uint32_t a,b,c;                                          /* internal state */
+  union { const void *ptr; size_t i; } u;     /* needed for Mac Powerbook G4 */
+
+  /* Set up the internal state */
+  a = b = c = 0xdeadbeef + ((uint32_t)length);
+
+  u.ptr = key;
+  if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
+    const uint32_t *k = (const uint32_t *)key;         /* read 32-bit chunks */
+    const uint8_t  *k8;
+
+    /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+    while (length > 12)
+    {
+      a += k[0];
+      b += k[1];
+      c += k[2];
+      mix(a,b,c);
+      length -= 12;
+      k += 3;
+    }
+
+    /*----------------------------- handle the last (probably partial) block */
+    k8 = (const uint8_t *)k;
+    switch(length)
+    {
+    case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+    case 11: c+=((uint32_t)k8[10])<<16;  /* fall through */
+    case 10: c+=((uint32_t)k8[9])<<8;    /* fall through */
+    case 9 : c+=k8[8];                   /* fall through */
+    case 8 : b+=k[1]; a+=k[0]; break;
+    case 7 : b+=((uint32_t)k8[6])<<16;   /* fall through */
+    case 6 : b+=((uint32_t)k8[5])<<8;    /* fall through */
+    case 5 : b+=k8[4];                   /* fall through */
+    case 4 : a+=k[0]; break;
+    case 3 : a+=((uint32_t)k8[2])<<16;   /* fall through */
+    case 2 : a+=((uint32_t)k8[1])<<8;    /* fall through */
+    case 1 : a+=k8[0]; break;
+    case 0 : return c;
+    }
+  } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
+    const uint16_t *k = (const uint16_t *)key;         /* read 16-bit chunks */
+    const uint8_t  *k8;
+
+    /*--------------- all but last block: aligned reads and different mixing */
+    while (length > 12)
+    {
+      a += k[0] + (((uint32_t)k[1])<<16);
+      b += k[2] + (((uint32_t)k[3])<<16);
+      c += k[4] + (((uint32_t)k[5])<<16);
+      mix(a,b,c);
+      length -= 12;
+      k += 6;
+    }
+
+    /*----------------------------- handle the last (probably partial) block */
+    k8 = (const uint8_t *)k;
+    switch(length)
+    {
+    case 12: c+=k[4]+(((uint32_t)k[5])<<16);
+             b+=k[2]+(((uint32_t)k[3])<<16);
+             a+=k[0]+(((uint32_t)k[1])<<16);
+             break;
+    case 11: c+=((uint32_t)k8[10])<<16;     /* fall through */
+    case 10: c+=k[4];
+             b+=k[2]+(((uint32_t)k[3])<<16);
+             a+=k[0]+(((uint32_t)k[1])<<16);
+             break;
+    case 9 : c+=k8[8];                      /* fall through */
+    case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
+             a+=k[0]+(((uint32_t)k[1])<<16);
+             break;
+    case 7 : b+=((uint32_t)k8[6])<<16;      /* fall through */
+    case 6 : b+=k[2];
+             a+=k[0]+(((uint32_t)k[1])<<16);
+             break;
+    case 5 : b+=k8[4];                      /* fall through */
+    case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
+             break;
+    case 3 : a+=((uint32_t)k8[2])<<16;      /* fall through */
+    case 2 : a+=k[0];
+             break;
+    case 1 : a+=k8[0];
+             break;
+    case 0 : return c;                     /* zero length requires no mixing */
+    }
+
+  } else {                        /* need to read the key one byte at a time */
+    const uint8_t *k = (const uint8_t *)key;
+
+    /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+    while (length > 12)
+    {
+      a += k[0];
+      a += ((uint32_t)k[1])<<8;
+      a += ((uint32_t)k[2])<<16;
+      a += ((uint32_t)k[3])<<24;
+      b += k[4];
+      b += ((uint32_t)k[5])<<8;
+      b += ((uint32_t)k[6])<<16;
+      b += ((uint32_t)k[7])<<24;
+      c += k[8];
+      c += ((uint32_t)k[9])<<8;
+      c += ((uint32_t)k[10])<<16;
+      c += ((uint32_t)k[11])<<24;
+      mix(a,b,c);
+      length -= 12;
+      k += 12;
+    }
+
+    /*-------------------------------- last block: affect all 32 bits of (c) */
+    switch(length)                   /* all the case statements fall through */
+    {
+    case 12: c+=((uint32_t)k[11])<<24;
+    case 11: c+=((uint32_t)k[10])<<16;
+    case 10: c+=((uint32_t)k[9])<<8;
+    case 9 : c+=k[8];
+    case 8 : b+=((uint32_t)k[7])<<24;
+    case 7 : b+=((uint32_t)k[6])<<16;
+    case 6 : b+=((uint32_t)k[5])<<8;
+    case 5 : b+=k[4];
+    case 4 : a+=((uint32_t)k[3])<<24;
+    case 3 : a+=((uint32_t)k[2])<<16;
+    case 2 : a+=((uint32_t)k[1])<<8;
+    case 1 : a+=k[0];
+             break;
+    case 0 : return c;
+    }
+  }
+
+  final(a,b,c);
+  return c;
+}
+
+_PUBLIC_ unsigned int tdb1_jenkins_hash(TDB1_DATA *key)
+{
+       return hashlittle(key->dptr, key->dsize);
+}
diff --git a/ccan/tdb2/tdb1_io.c b/ccan/tdb2/tdb1_io.c
new file mode 100644 (file)
index 0000000..212e94a
--- /dev/null
@@ -0,0 +1,490 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+
+#include "tdb1_private.h"
+#ifndef MAX
+#define MAX(a,b) ((a) > (b) ? (a) : (b))
+#endif
+
+/* check for an out of bounds access - if it is out of bounds then
+   see if the database has been expanded by someone else and expand
+   if necessary
+   note that "len" is the minimum length needed for the db
+*/
+static int tdb1_oob(struct tdb1_context *tdb, tdb1_off_t len, int probe)
+{
+       struct stat st;
+       if (len <= tdb->map_size)
+               return 0;
+       if (tdb->flags & TDB1_INTERNAL) {
+               if (!probe) {
+                       /* Ensure ecode is set for log fn. */
+                       tdb->ecode = TDB1_ERR_IO;
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL,"tdb1_oob len %d beyond internal malloc size %d\n",
+                                (int)len, (int)tdb->map_size));
+               }
+               return -1;
+       }
+
+       if (fstat(tdb->fd, &st) == -1) {
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+
+       if (st.st_size < (size_t)len) {
+               if (!probe) {
+                       /* Ensure ecode is set for log fn. */
+                       tdb->ecode = TDB1_ERR_IO;
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL,"tdb1_oob len %d beyond eof at %d\n",
+                                (int)len, (int)st.st_size));
+               }
+               return -1;
+       }
+
+       /* Unmap, update size, remap */
+       if (tdb1_munmap(tdb) == -1) {
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+       tdb->map_size = st.st_size;
+       tdb1_mmap(tdb);
+       return 0;
+}
+
+/* write a lump of data at a specified offset */
+static int tdb1_write(struct tdb1_context *tdb, tdb1_off_t off,
+                    const void *buf, tdb1_len_t len)
+{
+       if (len == 0) {
+               return 0;
+       }
+
+       if (tdb->read_only || tdb->traverse_read) {
+               tdb->ecode = TDB1_ERR_RDONLY;
+               return -1;
+       }
+
+       if (tdb->methods->tdb1_oob(tdb, off + len, 0) != 0)
+               return -1;
+
+       if (tdb->map_ptr) {
+               memcpy(off + (char *)tdb->map_ptr, buf, len);
+       } else {
+               ssize_t written = pwrite(tdb->fd, buf, len, off);
+               if ((written != (ssize_t)len) && (written != -1)) {
+                       /* try once more */
+                       tdb->ecode = TDB1_ERR_IO;
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_write: wrote only "
+                                "%d of %d bytes at %d, trying once more\n",
+                                (int)written, len, off));
+                       written = pwrite(tdb->fd, (const char *)buf+written,
+                                        len-written,
+                                        off+written);
+               }
+               if (written == -1) {
+                       /* Ensure ecode is set for log fn. */
+                       tdb->ecode = TDB1_ERR_IO;
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL,"tdb1_write failed at %d "
+                                "len=%d (%s)\n", off, len, strerror(errno)));
+                       return -1;
+               } else if (written != (ssize_t)len) {
+                       tdb->ecode = TDB1_ERR_IO;
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_write: failed to "
+                                "write %d bytes at %d in two attempts\n",
+                                len, off));
+                       return -1;
+               }
+       }
+       return 0;
+}
+
+/* Endian conversion: we only ever deal with 4 byte quantities */
+void *tdb1_convert(void *buf, uint32_t size)
+{
+       uint32_t i, *p = (uint32_t *)buf;
+       for (i = 0; i < size / 4; i++)
+               p[i] = TDB1_BYTEREV(p[i]);
+       return buf;
+}
+
+
+/* read a lump of data at a specified offset, maybe convert */
+static int tdb1_read(struct tdb1_context *tdb, tdb1_off_t off, void *buf,
+                   tdb1_len_t len, int cv)
+{
+       if (tdb->methods->tdb1_oob(tdb, off + len, 0) != 0) {
+               return -1;
+       }
+
+       if (tdb->map_ptr) {
+               memcpy(buf, off + (char *)tdb->map_ptr, len);
+       } else {
+               ssize_t ret = pread(tdb->fd, buf, len, off);
+               if (ret != (ssize_t)len) {
+                       /* Ensure ecode is set for log fn. */
+                       tdb->ecode = TDB1_ERR_IO;
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL,"tdb1_read failed at %d "
+                                "len=%d ret=%d (%s) map_size=%d\n",
+                                (int)off, (int)len, (int)ret, strerror(errno),
+                                (int)tdb->map_size));
+                       return -1;
+               }
+       }
+       if (cv) {
+               tdb1_convert(buf, len);
+       }
+       return 0;
+}
+
+
+
+/*
+  do an unlocked scan of the hash table heads to find the next non-zero head. The value
+  will then be confirmed with the lock held
+*/
+static void tdb1_next_hash_chain(struct tdb1_context *tdb, uint32_t *chain)
+{
+       uint32_t h = *chain;
+       if (tdb->map_ptr) {
+               for (;h < tdb->header.hash_size;h++) {
+                       if (0 != *(uint32_t *)(TDB1_HASH_TOP(h) + (unsigned char *)tdb->map_ptr)) {
+                               break;
+                       }
+               }
+       } else {
+               uint32_t off=0;
+               for (;h < tdb->header.hash_size;h++) {
+                       if (tdb1_ofs_read(tdb, TDB1_HASH_TOP(h), &off) != 0 || off != 0) {
+                               break;
+                       }
+               }
+       }
+       (*chain) = h;
+}
+
+
+int tdb1_munmap(struct tdb1_context *tdb)
+{
+       if (tdb->flags & TDB1_INTERNAL)
+               return 0;
+
+#if HAVE_MMAP
+       if (tdb->map_ptr) {
+               int ret;
+
+               ret = munmap(tdb->map_ptr, tdb->map_size);
+               if (ret != 0)
+                       return ret;
+       }
+#endif
+       tdb->map_ptr = NULL;
+       return 0;
+}
+
+void tdb1_mmap(struct tdb1_context *tdb)
+{
+       if (tdb->flags & TDB1_INTERNAL)
+               return;
+
+#if HAVE_MMAP
+       if (!(tdb->flags & TDB1_NOMMAP)) {
+               tdb->map_ptr = mmap(NULL, tdb->map_size,
+                                   PROT_READ|(tdb->read_only? 0:PROT_WRITE),
+                                   MAP_SHARED|MAP_FILE, tdb->fd, 0);
+
+               /*
+                * NB. When mmap fails it returns MAP_FAILED *NOT* NULL !!!!
+                */
+
+               if (tdb->map_ptr == MAP_FAILED) {
+                       tdb->map_ptr = NULL;
+                       TDB1_LOG((tdb, TDB1_DEBUG_WARNING, "tdb1_mmap failed for size %d (%s)\n",
+                                tdb->map_size, strerror(errno)));
+               }
+       } else {
+               tdb->map_ptr = NULL;
+       }
+#else
+       tdb->map_ptr = NULL;
+#endif
+}
+
+/* expand a file.  we prefer to use ftruncate, as that is what posix
+  says to use for mmap expansion */
+static int tdb1_expand_file(struct tdb1_context *tdb, tdb1_off_t size, tdb1_off_t addition)
+{
+       char buf[8192];
+
+       if (tdb->read_only || tdb->traverse_read) {
+               tdb->ecode = TDB1_ERR_RDONLY;
+               return -1;
+       }
+
+       if (ftruncate(tdb->fd, size+addition) == -1) {
+               char b = 0;
+               ssize_t written = pwrite(tdb->fd,  &b, 1, (size+addition) - 1);
+               if (written == 0) {
+                       /* try once more, potentially revealing errno */
+                       written = pwrite(tdb->fd,  &b, 1, (size+addition) - 1);
+               }
+               if (written == 0) {
+                       /* again - give up, guessing errno */
+                       errno = ENOSPC;
+               }
+               if (written != 1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "expand_file to %d failed (%s)\n",
+                                size+addition, strerror(errno)));
+                       return -1;
+               }
+       }
+
+       /* now fill the file with something. This ensures that the
+          file isn't sparse, which would be very bad if we ran out of
+          disk. This must be done with write, not via mmap */
+       memset(buf, TDB1_PAD_BYTE, sizeof(buf));
+       while (addition) {
+               size_t n = addition>sizeof(buf)?sizeof(buf):addition;
+               ssize_t written = pwrite(tdb->fd, buf, n, size);
+               if (written == 0) {
+                       /* prevent infinite loops: try _once_ more */
+                       written = pwrite(tdb->fd, buf, n, size);
+               }
+               if (written == 0) {
+                       /* give up, trying to provide a useful errno */
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "expand_file write "
+                               "returned 0 twice: giving up!\n"));
+                       errno = ENOSPC;
+                       return -1;
+               } else if (written == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "expand_file write of "
+                                "%d bytes failed (%s)\n", (int)n,
+                                strerror(errno)));
+                       return -1;
+               } else if (written != n) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_WARNING, "expand_file: wrote "
+                                "only %d of %d bytes - retrying\n", (int)written,
+                                (int)n));
+               }
+               addition -= written;
+               size += written;
+       }
+       return 0;
+}
+
+
+/* expand the database at least size bytes by expanding the underlying
+   file and doing the mmap again if necessary */
+int tdb1_expand(struct tdb1_context *tdb, tdb1_off_t size)
+{
+       struct tdb1_record rec;
+       tdb1_off_t offset, new_size, top_size, map_size;
+
+       if (tdb1_lock(tdb, -1, F_WRLCK) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "lock failed in tdb1_expand\n"));
+               return -1;
+       }
+
+       /* must know about any previous expansions by another process */
+       tdb->methods->tdb1_oob(tdb, tdb->map_size + 1, 1);
+
+       /* limit size in order to avoid using up huge amounts of memory for
+        * in memory tdbs if an oddball huge record creeps in */
+       if (size > 100 * 1024) {
+               top_size = tdb->map_size + size * 2;
+       } else {
+               top_size = tdb->map_size + size * 100;
+       }
+
+       /* always make room for at least top_size more records, and at
+          least 25% more space. if the DB is smaller than 100MiB,
+          otherwise grow it by 10% only. */
+       if (tdb->map_size > 100 * 1024 * 1024) {
+               map_size = tdb->map_size * 1.10;
+       } else {
+               map_size = tdb->map_size * 1.25;
+       }
+
+       /* Round the database up to a multiple of the page size */
+       new_size = MAX(top_size, map_size);
+       size = TDB1_ALIGN(new_size, tdb->page_size) - tdb->map_size;
+
+       if (!(tdb->flags & TDB1_INTERNAL))
+               tdb1_munmap(tdb);
+
+       /*
+        * We must ensure the file is unmapped before doing this
+        * to ensure consistency with systems like OpenBSD where
+        * writes and mmaps are not consistent.
+        */
+
+       /* expand the file itself */
+       if (!(tdb->flags & TDB1_INTERNAL)) {
+               if (tdb->methods->tdb1_expand_file(tdb, tdb->map_size, size) != 0)
+                       goto fail;
+       }
+
+       tdb->map_size += size;
+
+       if (tdb->flags & TDB1_INTERNAL) {
+               char *new_map_ptr = (char *)realloc(tdb->map_ptr,
+                                                   tdb->map_size);
+               if (!new_map_ptr) {
+                       tdb->map_size -= size;
+                       goto fail;
+               }
+               tdb->map_ptr = new_map_ptr;
+       } else {
+               /*
+                * We must ensure the file is remapped before adding the space
+                * to ensure consistency with systems like OpenBSD where
+                * writes and mmaps are not consistent.
+                */
+
+               /* We're ok if the mmap fails as we'll fallback to read/write */
+               tdb1_mmap(tdb);
+       }
+
+       /* form a new freelist record */
+       memset(&rec,'\0',sizeof(rec));
+       rec.rec_len = size - sizeof(rec);
+
+       /* link it into the free list */
+       offset = tdb->map_size - size;
+       if (tdb1_free(tdb, offset, &rec) == -1)
+               goto fail;
+
+       tdb1_unlock(tdb, -1, F_WRLCK);
+       return 0;
+ fail:
+       tdb1_unlock(tdb, -1, F_WRLCK);
+       return -1;
+}
+
+/* read/write a tdb1_off_t */
+int tdb1_ofs_read(struct tdb1_context *tdb, tdb1_off_t offset, tdb1_off_t *d)
+{
+       return tdb->methods->tdb1_read(tdb, offset, (char*)d, sizeof(*d), TDB1_DOCONV());
+}
+
+int tdb1_ofs_write(struct tdb1_context *tdb, tdb1_off_t offset, tdb1_off_t *d)
+{
+       tdb1_off_t off = *d;
+       return tdb->methods->tdb1_write(tdb, offset, TDB1_CONV(off), sizeof(*d));
+}
+
+
+/* read a lump of data, allocating the space for it */
+unsigned char *tdb1_alloc_read(struct tdb1_context *tdb, tdb1_off_t offset, tdb1_len_t len)
+{
+       unsigned char *buf;
+
+       /* some systems don't like zero length malloc */
+
+       if (!(buf = (unsigned char *)malloc(len ? len : 1))) {
+               /* Ensure ecode is set for log fn. */
+               tdb->ecode = TDB1_ERR_OOM;
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,"tdb1_alloc_read malloc failed len=%d (%s)\n",
+                          len, strerror(errno)));
+               return NULL;
+       }
+       if (tdb->methods->tdb1_read(tdb, offset, buf, len, 0) == -1) {
+               SAFE_FREE(buf);
+               return NULL;
+       }
+       return buf;
+}
+
+/* Give a piece of tdb data to a parser */
+
+int tdb1_parse_data(struct tdb1_context *tdb, TDB1_DATA key,
+                  tdb1_off_t offset, tdb1_len_t len,
+                  int (*parser)(TDB1_DATA key, TDB1_DATA data,
+                                void *private_data),
+                  void *private_data)
+{
+       TDB1_DATA data;
+       int result;
+
+       data.dsize = len;
+
+       if ((tdb->transaction == NULL) && (tdb->map_ptr != NULL)) {
+               /*
+                * Optimize by avoiding the malloc/memcpy/free, point the
+                * parser directly at the mmap area.
+                */
+               if (tdb->methods->tdb1_oob(tdb, offset+len, 0) != 0) {
+                       return -1;
+               }
+               data.dptr = offset + (unsigned char *)tdb->map_ptr;
+               return parser(key, data, private_data);
+       }
+
+       if (!(data.dptr = tdb1_alloc_read(tdb, offset, len))) {
+               return -1;
+       }
+
+       result = parser(key, data, private_data);
+       free(data.dptr);
+       return result;
+}
+
+/* read/write a record */
+int tdb1_rec_read(struct tdb1_context *tdb, tdb1_off_t offset, struct tdb1_record *rec)
+{
+       if (tdb->methods->tdb1_read(tdb, offset, rec, sizeof(*rec),TDB1_DOCONV()) == -1)
+               return -1;
+       if (TDB1_BAD_MAGIC(rec)) {
+               /* Ensure ecode is set for log fn. */
+               tdb->ecode = TDB1_ERR_CORRUPT;
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL,"tdb1_rec_read bad magic 0x%x at offset=%d\n", rec->magic, offset));
+               return -1;
+       }
+       return tdb->methods->tdb1_oob(tdb, rec->next+sizeof(*rec), 0);
+}
+
+int tdb1_rec_write(struct tdb1_context *tdb, tdb1_off_t offset, struct tdb1_record *rec)
+{
+       struct tdb1_record r = *rec;
+       return tdb->methods->tdb1_write(tdb, offset, TDB1_CONV(r), sizeof(r));
+}
+
+static const struct tdb1_methods io1_methods = {
+       tdb1_read,
+       tdb1_write,
+       tdb1_next_hash_chain,
+       tdb1_oob,
+       tdb1_expand_file,
+};
+
+/*
+  initialise the default methods table
+*/
+void tdb1_io_init(struct tdb1_context *tdb)
+{
+       tdb->methods = &io1_methods;
+}
diff --git a/ccan/tdb2/tdb1_lock.c b/ccan/tdb2/tdb1_lock.c
new file mode 100644 (file)
index 0000000..bed70ba
--- /dev/null
@@ -0,0 +1,847 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb1_private.h"
+
+_PUBLIC_ void tdb1_setalarm_sigptr(struct tdb1_context *tdb, volatile sig_atomic_t *ptr)
+{
+       tdb->interrupt_sig_ptr = ptr;
+}
+
+static int fcntl_lock(struct tdb1_context *tdb,
+                     int rw, off_t off, off_t len, bool waitflag)
+{
+       struct flock fl;
+
+       fl.l_type = rw;
+       fl.l_whence = SEEK_SET;
+       fl.l_start = off;
+       fl.l_len = len;
+       fl.l_pid = 0;
+
+       if (waitflag)
+               return fcntl(tdb->fd, F_SETLKW, &fl);
+       else
+               return fcntl(tdb->fd, F_SETLK, &fl);
+}
+
+static int fcntl_unlock(struct tdb1_context *tdb, int rw, off_t off, off_t len)
+{
+       struct flock fl;
+#if 0 /* Check they matched up locks and unlocks correctly. */
+       char line[80];
+       FILE *locks;
+       bool found = false;
+
+       locks = fopen("/proc/locks", "r");
+
+       while (fgets(line, 80, locks)) {
+               char *p;
+               int type, start, l;
+
+               /* eg. 1: FLOCK  ADVISORY  WRITE 2440 08:01:2180826 0 EOF */
+               p = strchr(line, ':') + 1;
+               if (strncmp(p, " POSIX  ADVISORY  ", strlen(" POSIX  ADVISORY  ")))
+                       continue;
+               p += strlen(" FLOCK  ADVISORY  ");
+               if (strncmp(p, "READ  ", strlen("READ  ")) == 0)
+                       type = F_RDLCK;
+               else if (strncmp(p, "WRITE ", strlen("WRITE ")) == 0)
+                       type = F_WRLCK;
+               else
+                       abort();
+               p += 6;
+               if (atoi(p) != getpid())
+                       continue;
+               p = strchr(strchr(p, ' ') + 1, ' ') + 1;
+               start = atoi(p);
+               p = strchr(p, ' ') + 1;
+               if (strncmp(p, "EOF", 3) == 0)
+                       l = 0;
+               else
+                       l = atoi(p) - start + 1;
+
+               if (off == start) {
+                       if (len != l) {
+                               fprintf(stderr, "Len %u should be %u: %s",
+                                       (int)len, l, line);
+                               abort();
+                       }
+                       if (type != rw) {
+                               fprintf(stderr, "Type %s wrong: %s",
+                                       rw == F_RDLCK ? "READ" : "WRITE", line);
+                               abort();
+                       }
+                       found = true;
+                       break;
+               }
+       }
+
+       if (!found) {
+               fprintf(stderr, "Unlock on %u@%u not found!\n",
+                       (int)off, (int)len);
+               abort();
+       }
+
+       fclose(locks);
+#endif
+
+       fl.l_type = F_UNLCK;
+       fl.l_whence = SEEK_SET;
+       fl.l_start = off;
+       fl.l_len = len;
+       fl.l_pid = 0;
+
+       return fcntl(tdb->fd, F_SETLKW, &fl);
+}
+
+/* list -1 is the alloc list, otherwise a hash chain. */
+static tdb1_off_t lock_offset(int list)
+{
+       return TDB1_FREELIST_TOP + 4*list;
+}
+
+/* a byte range locking function - return 0 on success
+   this functions locks/unlocks 1 byte at the specified offset.
+
+   On error, errno is also set so that errors are passed back properly
+   through tdb1_open().
+
+   note that a len of zero means lock to end of file
+*/
+int tdb1_brlock(struct tdb1_context *tdb,
+              int rw_type, tdb1_off_t offset, size_t len,
+              enum tdb1_lock_flags flags)
+{
+       int ret;
+
+       if (tdb->flags & TDB1_NOLOCK) {
+               return 0;
+       }
+
+       if (flags & TDB1_LOCK_MARK_ONLY) {
+               return 0;
+       }
+
+       if ((rw_type == F_WRLCK) && (tdb->read_only || tdb->traverse_read)) {
+               tdb->ecode = TDB1_ERR_RDONLY;
+               return -1;
+       }
+
+       do {
+               ret = fcntl_lock(tdb, rw_type, offset, len,
+                                flags & TDB1_LOCK_WAIT);
+               /* Check for a sigalarm break. */
+               if (ret == -1 && errno == EINTR &&
+                               tdb->interrupt_sig_ptr &&
+                               *tdb->interrupt_sig_ptr) {
+                       break;
+               }
+       } while (ret == -1 && errno == EINTR);
+
+       if (ret == -1) {
+               tdb->ecode = TDB1_ERR_LOCK;
+               /* Generic lock error. errno set by fcntl.
+                * EAGAIN is an expected return from non-blocking
+                * locks. */
+               if (!(flags & TDB1_LOCK_PROBE) && errno != EAGAIN) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_TRACE,"tdb1_brlock failed (fd=%d) at offset %d rw_type=%d flags=%d len=%d\n",
+                                tdb->fd, offset, rw_type, flags, (int)len));
+               }
+               return -1;
+       }
+       return 0;
+}
+
+int tdb1_brunlock(struct tdb1_context *tdb,
+                int rw_type, tdb1_off_t offset, size_t len)
+{
+       int ret;
+
+       if (tdb->flags & TDB1_NOLOCK) {
+               return 0;
+       }
+
+       do {
+               ret = fcntl_unlock(tdb, rw_type, offset, len);
+       } while (ret == -1 && errno == EINTR);
+
+       if (ret == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_TRACE,"tdb1_brunlock failed (fd=%d) at offset %d rw_type=%d len=%d\n",
+                        tdb->fd, offset, rw_type, (int)len));
+       }
+       return ret;
+}
+
+/*
+  upgrade a read lock to a write lock. This needs to be handled in a
+  special way as some OSes (such as solaris) have too conservative
+  deadlock detection and claim a deadlock when progress can be
+  made. For those OSes we may loop for a while.
+*/
+int tdb1_allrecord_upgrade(struct tdb1_context *tdb)
+{
+       int count = 1000;
+
+       if (tdb->allrecord_lock.count != 1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                        "tdb1_allrecord_upgrade failed: count %u too high\n",
+                        tdb->allrecord_lock.count));
+               return -1;
+       }
+
+       if (tdb->allrecord_lock.off != 1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                        "tdb1_allrecord_upgrade failed: already upgraded?\n"));
+               return -1;
+       }
+
+       while (count--) {
+               struct timeval tv;
+               if (tdb1_brlock(tdb, F_WRLCK, TDB1_FREELIST_TOP, 0,
+                              TDB1_LOCK_WAIT|TDB1_LOCK_PROBE) == 0) {
+                       tdb->allrecord_lock.ltype = F_WRLCK;
+                       tdb->allrecord_lock.off = 0;
+                       return 0;
+               }
+               if (errno != EDEADLK) {
+                       break;
+               }
+               /* sleep for as short a time as we can - more portable than usleep() */
+               tv.tv_sec = 0;
+               tv.tv_usec = 1;
+               select(0, NULL, NULL, NULL, &tv);
+       }
+       TDB1_LOG((tdb, TDB1_DEBUG_TRACE,"tdb1_allrecord_upgrade failed\n"));
+       return -1;
+}
+
+static struct tdb1_lock_type *tdb1_find_nestlock(struct tdb1_context *tdb,
+                                                tdb1_off_t offset)
+{
+       unsigned int i;
+
+       for (i=0; i<tdb->num_lockrecs; i++) {
+               if (tdb->lockrecs[i].off == offset) {
+                       return &tdb->lockrecs[i];
+               }
+       }
+       return NULL;
+}
+
+/* lock an offset in the database. */
+int tdb1_nest_lock(struct tdb1_context *tdb, uint32_t offset, int ltype,
+                 enum tdb1_lock_flags flags)
+{
+       struct tdb1_lock_type *new_lck;
+
+       if (offset >= lock_offset(tdb->header.hash_size)) {
+               tdb->ecode = TDB1_ERR_LOCK;
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR,"tdb1_lock: invalid offset %u for ltype=%d\n",
+                        offset, ltype));
+               return -1;
+       }
+       if (tdb->flags & TDB1_NOLOCK)
+               return 0;
+
+       new_lck = tdb1_find_nestlock(tdb, offset);
+       if (new_lck) {
+               /*
+                * Just increment the in-memory struct, posix locks
+                * don't stack.
+                */
+               new_lck->count++;
+               return 0;
+       }
+
+       new_lck = (struct tdb1_lock_type *)realloc(
+               tdb->lockrecs,
+               sizeof(*tdb->lockrecs) * (tdb->num_lockrecs+1));
+       if (new_lck == NULL) {
+               errno = ENOMEM;
+               return -1;
+       }
+       tdb->lockrecs = new_lck;
+
+       /* Since fcntl locks don't nest, we do a lock for the first one,
+          and simply bump the count for future ones */
+       if (tdb1_brlock(tdb, ltype, offset, 1, flags)) {
+               return -1;
+       }
+
+       tdb->lockrecs[tdb->num_lockrecs].off = offset;
+       tdb->lockrecs[tdb->num_lockrecs].count = 1;
+       tdb->lockrecs[tdb->num_lockrecs].ltype = ltype;
+       tdb->num_lockrecs++;
+
+       return 0;
+}
+
+static int tdb1_lock_and_recover(struct tdb1_context *tdb)
+{
+       int ret;
+
+       /* We need to match locking order in transaction commit. */
+       if (tdb1_brlock(tdb, F_WRLCK, TDB1_FREELIST_TOP, 0, TDB1_LOCK_WAIT)) {
+               return -1;
+       }
+
+       if (tdb1_brlock(tdb, F_WRLCK, TDB1_OPEN_LOCK, 1, TDB1_LOCK_WAIT)) {
+               tdb1_brunlock(tdb, F_WRLCK, TDB1_FREELIST_TOP, 0);
+               return -1;
+       }
+
+       ret = tdb1_transaction_recover(tdb);
+
+       tdb1_brunlock(tdb, F_WRLCK, TDB1_OPEN_LOCK, 1);
+       tdb1_brunlock(tdb, F_WRLCK, TDB1_FREELIST_TOP, 0);
+
+       return ret;
+}
+
+static bool have_data_locks(const struct tdb1_context *tdb)
+{
+       unsigned int i;
+
+       for (i = 0; i < tdb->num_lockrecs; i++) {
+               if (tdb->lockrecs[i].off >= lock_offset(-1))
+                       return true;
+       }
+       return false;
+}
+
+static int tdb1_lock_list(struct tdb1_context *tdb, int list, int ltype,
+                        enum tdb1_lock_flags waitflag)
+{
+       int ret;
+       bool check = false;
+
+       /* a allrecord lock allows us to avoid per chain locks */
+       if (tdb->allrecord_lock.count &&
+           (ltype == tdb->allrecord_lock.ltype || ltype == F_RDLCK)) {
+               return 0;
+       }
+
+       if (tdb->allrecord_lock.count) {
+               tdb->ecode = TDB1_ERR_LOCK;
+               ret = -1;
+       } else {
+               /* Only check when we grab first data lock. */
+               check = !have_data_locks(tdb);
+               ret = tdb1_nest_lock(tdb, lock_offset(list), ltype, waitflag);
+
+               if (ret == 0 && check && tdb1_needs_recovery(tdb)) {
+                       tdb1_nest_unlock(tdb, lock_offset(list), ltype, false);
+
+                       if (tdb1_lock_and_recover(tdb) == -1) {
+                               return -1;
+                       }
+                       return tdb1_lock_list(tdb, list, ltype, waitflag);
+               }
+       }
+       return ret;
+}
+
+/* lock a list in the database. list -1 is the alloc list */
+int tdb1_lock(struct tdb1_context *tdb, int list, int ltype)
+{
+       int ret;
+
+       ret = tdb1_lock_list(tdb, list, ltype, TDB1_LOCK_WAIT);
+       if (ret) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_lock failed on list %d "
+                        "ltype=%d (%s)\n",  list, ltype, strerror(errno)));
+       }
+       return ret;
+}
+
+/* lock a list in the database. list -1 is the alloc list. non-blocking lock */
+int tdb1_lock_nonblock(struct tdb1_context *tdb, int list, int ltype)
+{
+       return tdb1_lock_list(tdb, list, ltype, TDB1_LOCK_NOWAIT);
+}
+
+
+int tdb1_nest_unlock(struct tdb1_context *tdb, uint32_t offset, int ltype,
+                   bool mark_lock)
+{
+       int ret = -1;
+       struct tdb1_lock_type *lck;
+
+       if (tdb->flags & TDB1_NOLOCK)
+               return 0;
+
+       /* Sanity checks */
+       if (offset >= lock_offset(tdb->header.hash_size)) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_unlock: offset %u invalid (%d)\n", offset, tdb->header.hash_size));
+               return ret;
+       }
+
+       lck = tdb1_find_nestlock(tdb, offset);
+       if ((lck == NULL) || (lck->count == 0)) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_unlock: count is 0\n"));
+               return -1;
+       }
+
+       if (lck->count > 1) {
+               lck->count--;
+               return 0;
+       }
+
+       /*
+        * This lock has count==1 left, so we need to unlock it in the
+        * kernel. We don't bother with decrementing the in-memory array
+        * element, we're about to overwrite it with the last array element
+        * anyway.
+        */
+
+       if (mark_lock) {
+               ret = 0;
+       } else {
+               ret = tdb1_brunlock(tdb, ltype, offset, 1);
+       }
+
+       /*
+        * Shrink the array by overwriting the element just unlocked with the
+        * last array element.
+        */
+       *lck = tdb->lockrecs[--tdb->num_lockrecs];
+
+       /*
+        * We don't bother with realloc when the array shrinks, but if we have
+        * a completely idle tdb we should get rid of the locked array.
+        */
+
+       if (tdb->num_lockrecs == 0) {
+               SAFE_FREE(tdb->lockrecs);
+       }
+
+       if (ret)
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_unlock: An error occurred unlocking!\n"));
+       return ret;
+}
+
+int tdb1_unlock(struct tdb1_context *tdb, int list, int ltype)
+{
+       /* a global lock allows us to avoid per chain locks */
+       if (tdb->allrecord_lock.count &&
+           (ltype == tdb->allrecord_lock.ltype || ltype == F_RDLCK)) {
+               return 0;
+       }
+
+       if (tdb->allrecord_lock.count) {
+               tdb->ecode = TDB1_ERR_LOCK;
+               return -1;
+       }
+
+       return tdb1_nest_unlock(tdb, lock_offset(list), ltype, false);
+}
+
+/*
+  get the transaction lock
+ */
+int tdb1_transaction_lock(struct tdb1_context *tdb, int ltype,
+                        enum tdb1_lock_flags lockflags)
+{
+       return tdb1_nest_lock(tdb, TDB1_TRANSACTION_LOCK, ltype, lockflags);
+}
+
+/*
+  release the transaction lock
+ */
+int tdb1_transaction_unlock(struct tdb1_context *tdb, int ltype)
+{
+       return tdb1_nest_unlock(tdb, TDB1_TRANSACTION_LOCK, ltype, false);
+}
+
+/* Returns 0 if all done, -1 if error, 1 if ok. */
+static int tdb1_allrecord_check(struct tdb1_context *tdb, int ltype,
+                              enum tdb1_lock_flags flags, bool upgradable)
+{
+       /* There are no locks on read-only dbs */
+       if (tdb->read_only || tdb->traverse_read) {
+               tdb->ecode = TDB1_ERR_LOCK;
+               return -1;
+       }
+
+       if (tdb->allrecord_lock.count && tdb->allrecord_lock.ltype == ltype) {
+               tdb->allrecord_lock.count++;
+               return 0;
+       }
+
+       if (tdb->allrecord_lock.count) {
+               /* a global lock of a different type exists */
+               tdb->ecode = TDB1_ERR_LOCK;
+               return -1;
+       }
+
+       if (tdb1_have_extra_locks(tdb)) {
+               /* can't combine global and chain locks */
+               tdb->ecode = TDB1_ERR_LOCK;
+               return -1;
+       }
+
+       if (upgradable && ltype != F_RDLCK) {
+               /* tdb error: you can't upgrade a write lock! */
+               tdb->ecode = TDB1_ERR_LOCK;
+               return -1;
+       }
+       return 1;
+}
+
+/* We only need to lock individual bytes, but Linux merges consecutive locks
+ * so we lock in contiguous ranges. */
+static int tdb1_chainlock_gradual(struct tdb1_context *tdb,
+                                int ltype, enum tdb1_lock_flags flags,
+                                size_t off, size_t len)
+{
+       int ret;
+       enum tdb1_lock_flags nb_flags = (flags & ~TDB1_LOCK_WAIT);
+
+       if (len <= 4) {
+               /* Single record.  Just do blocking lock. */
+               return tdb1_brlock(tdb, ltype, off, len, flags);
+       }
+
+       /* First we try non-blocking. */
+       ret = tdb1_brlock(tdb, ltype, off, len, nb_flags);
+       if (ret == 0) {
+               return 0;
+       }
+
+       /* Try locking first half, then second. */
+       ret = tdb1_chainlock_gradual(tdb, ltype, flags, off, len / 2);
+       if (ret == -1)
+               return -1;
+
+       ret = tdb1_chainlock_gradual(tdb, ltype, flags,
+                                   off + len / 2, len - len / 2);
+       if (ret == -1) {
+               tdb1_brunlock(tdb, ltype, off, len / 2);
+               return -1;
+       }
+       return 0;
+}
+
+/* lock/unlock entire database.  It can only be upgradable if you have some
+ * other way of guaranteeing exclusivity (ie. transaction write lock).
+ * We do the locking gradually to avoid being starved by smaller locks. */
+int tdb1_allrecord_lock(struct tdb1_context *tdb, int ltype,
+                      enum tdb1_lock_flags flags, bool upgradable)
+{
+       switch (tdb1_allrecord_check(tdb, ltype, flags, upgradable)) {
+       case -1:
+               return -1;
+       case 0:
+               return 0;
+       }
+
+       /* We cover two kinds of locks:
+        * 1) Normal chain locks.  Taken for almost all operations.
+        * 3) Individual records locks.  Taken after normal or free
+        *    chain locks.
+        *
+        * It is (1) which cause the starvation problem, so we're only
+        * gradual for that. */
+       if (tdb1_chainlock_gradual(tdb, ltype, flags, TDB1_FREELIST_TOP,
+                                 tdb->header.hash_size * 4) == -1) {
+               return -1;
+       }
+
+       /* Grab individual record locks. */
+       if (tdb1_brlock(tdb, ltype, lock_offset(tdb->header.hash_size), 0,
+                      flags) == -1) {
+               tdb1_brunlock(tdb, ltype, TDB1_FREELIST_TOP,
+                            tdb->header.hash_size * 4);
+               return -1;
+       }
+
+       tdb->allrecord_lock.count = 1;
+       /* If it's upgradable, it's actually exclusive so we can treat
+        * it as a write lock. */
+       tdb->allrecord_lock.ltype = upgradable ? F_WRLCK : ltype;
+       tdb->allrecord_lock.off = upgradable;
+
+       if (tdb1_needs_recovery(tdb)) {
+               bool mark = flags & TDB1_LOCK_MARK_ONLY;
+               tdb1_allrecord_unlock(tdb, ltype, mark);
+               if (mark) {
+                       tdb->ecode = TDB1_ERR_LOCK;
+                       TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                                "tdb1_lockall_mark cannot do recovery\n"));
+                       return -1;
+               }
+               if (tdb1_lock_and_recover(tdb) == -1) {
+                       return -1;
+               }
+               return tdb1_allrecord_lock(tdb, ltype, flags, upgradable);
+       }
+
+       return 0;
+}
+
+
+
+/* unlock entire db */
+int tdb1_allrecord_unlock(struct tdb1_context *tdb, int ltype, bool mark_lock)
+{
+       /* There are no locks on read-only dbs */
+       if (tdb->read_only || tdb->traverse_read) {
+               tdb->ecode = TDB1_ERR_LOCK;
+               return -1;
+       }
+
+       if (tdb->allrecord_lock.count == 0) {
+               tdb->ecode = TDB1_ERR_LOCK;
+               return -1;
+       }
+
+       /* Upgradable locks are marked as write locks. */
+       if (tdb->allrecord_lock.ltype != ltype
+           && (!tdb->allrecord_lock.off || ltype != F_RDLCK)) {
+               tdb->ecode = TDB1_ERR_LOCK;
+               return -1;
+       }
+
+       if (tdb->allrecord_lock.count > 1) {
+               tdb->allrecord_lock.count--;
+               return 0;
+       }
+
+       if (!mark_lock && tdb1_brunlock(tdb, ltype, TDB1_FREELIST_TOP, 0)) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_unlockall failed (%s)\n", strerror(errno)));
+               return -1;
+       }
+
+       tdb->allrecord_lock.count = 0;
+       tdb->allrecord_lock.ltype = 0;
+
+       return 0;
+}
+
+/* lock entire database with write lock */
+_PUBLIC_ int tdb1_lockall(struct tdb1_context *tdb)
+{
+       return tdb1_allrecord_lock(tdb, F_WRLCK, TDB1_LOCK_WAIT, false);
+}
+
+/* lock entire database with write lock - mark only */
+_PUBLIC_ int tdb1_lockall_mark(struct tdb1_context *tdb)
+{
+       return tdb1_allrecord_lock(tdb, F_WRLCK, TDB1_LOCK_MARK_ONLY, false);
+}
+
+/* unlock entire database with write lock - unmark only */
+_PUBLIC_ int tdb1_lockall_unmark(struct tdb1_context *tdb)
+{
+       return tdb1_allrecord_unlock(tdb, F_WRLCK, true);
+}
+
+/* lock entire database with write lock - nonblocking varient */
+_PUBLIC_ int tdb1_lockall_nonblock(struct tdb1_context *tdb)
+{
+       int ret = tdb1_allrecord_lock(tdb, F_WRLCK, TDB1_LOCK_NOWAIT, false);
+       return ret;
+}
+
+/* unlock entire database with write lock */
+_PUBLIC_ int tdb1_unlockall(struct tdb1_context *tdb)
+{
+       return tdb1_allrecord_unlock(tdb, F_WRLCK, false);
+}
+
+/* lock entire database with read lock */
+_PUBLIC_ int tdb1_lockall_read(struct tdb1_context *tdb)
+{
+       return tdb1_allrecord_lock(tdb, F_RDLCK, TDB1_LOCK_WAIT, false);
+}
+
+/* lock entire database with read lock - nonblock varient */
+_PUBLIC_ int tdb1_lockall_read_nonblock(struct tdb1_context *tdb)
+{
+       int ret = tdb1_allrecord_lock(tdb, F_RDLCK, TDB1_LOCK_NOWAIT, false);
+       return ret;
+}
+
+/* unlock entire database with read lock */
+_PUBLIC_ int tdb1_unlockall_read(struct tdb1_context *tdb)
+{
+       return tdb1_allrecord_unlock(tdb, F_RDLCK, false);
+}
+
+/* lock/unlock one hash chain. This is meant to be used to reduce
+   contention - it cannot guarantee how many records will be locked */
+_PUBLIC_ int tdb1_chainlock(struct tdb1_context *tdb, TDB1_DATA key)
+{
+       int ret = tdb1_lock(tdb, TDB1_BUCKET(tdb->hash_fn(&key)), F_WRLCK);
+       return ret;
+}
+
+/* lock/unlock one hash chain, non-blocking. This is meant to be used
+   to reduce contention - it cannot guarantee how many records will be
+   locked */
+_PUBLIC_ int tdb1_chainlock_nonblock(struct tdb1_context *tdb, TDB1_DATA key)
+{
+       int ret = tdb1_lock_nonblock(tdb, TDB1_BUCKET(tdb->hash_fn(&key)), F_WRLCK);
+       return ret;
+}
+
+/* mark a chain as locked without actually locking it. Warning! use with great caution! */
+_PUBLIC_ int tdb1_chainlock_mark(struct tdb1_context *tdb, TDB1_DATA key)
+{
+       int ret = tdb1_nest_lock(tdb, lock_offset(TDB1_BUCKET(tdb->hash_fn(&key))),
+                               F_WRLCK, TDB1_LOCK_MARK_ONLY);
+       return ret;
+}
+
+/* unmark a chain as locked without actually locking it. Warning! use with great caution! */
+_PUBLIC_ int tdb1_chainlock_unmark(struct tdb1_context *tdb, TDB1_DATA key)
+{
+       return tdb1_nest_unlock(tdb, lock_offset(TDB1_BUCKET(tdb->hash_fn(&key))),
+                              F_WRLCK, true);
+}
+
+_PUBLIC_ int tdb1_chainunlock(struct tdb1_context *tdb, TDB1_DATA key)
+{
+       return tdb1_unlock(tdb, TDB1_BUCKET(tdb->hash_fn(&key)), F_WRLCK);
+}
+
+_PUBLIC_ int tdb1_chainlock_read(struct tdb1_context *tdb, TDB1_DATA key)
+{
+       int ret;
+       ret = tdb1_lock(tdb, TDB1_BUCKET(tdb->hash_fn(&key)), F_RDLCK);
+       return ret;
+}
+
+_PUBLIC_ int tdb1_chainunlock_read(struct tdb1_context *tdb, TDB1_DATA key)
+{
+       return tdb1_unlock(tdb, TDB1_BUCKET(tdb->hash_fn(&key)), F_RDLCK);
+}
+
+/* record lock stops delete underneath */
+int tdb1_lock_record(struct tdb1_context *tdb, tdb1_off_t off)
+{
+       if (tdb->allrecord_lock.count) {
+               return 0;
+       }
+       return off ? tdb1_brlock(tdb, F_RDLCK, off, 1, TDB1_LOCK_WAIT) : 0;
+}
+
+/*
+  Write locks override our own fcntl readlocks, so check it here.
+  Note this is meant to be F_SETLK, *not* F_SETLKW, as it's not
+  an error to fail to get the lock here.
+*/
+int tdb1_write_lock_record(struct tdb1_context *tdb, tdb1_off_t off)
+{
+       struct tdb1_traverse_lock *i;
+       for (i = &tdb->travlocks; i; i = i->next)
+               if (i->off == off)
+                       return -1;
+       if (tdb->allrecord_lock.count) {
+               if (tdb->allrecord_lock.ltype == F_WRLCK) {
+                       return 0;
+               }
+               return -1;
+       }
+       return tdb1_brlock(tdb, F_WRLCK, off, 1, TDB1_LOCK_NOWAIT|TDB1_LOCK_PROBE);
+}
+
+int tdb1_write_unlock_record(struct tdb1_context *tdb, tdb1_off_t off)
+{
+       if (tdb->allrecord_lock.count) {
+               return 0;
+       }
+       return tdb1_brunlock(tdb, F_WRLCK, off, 1);
+}
+
+/* fcntl locks don't stack: avoid unlocking someone else's */
+int tdb1_unlock_record(struct tdb1_context *tdb, tdb1_off_t off)
+{
+       struct tdb1_traverse_lock *i;
+       uint32_t count = 0;
+
+       if (tdb->allrecord_lock.count) {
+               return 0;
+       }
+
+       if (off == 0)
+               return 0;
+       for (i = &tdb->travlocks; i; i = i->next)
+               if (i->off == off)
+                       count++;
+       return (count == 1 ? tdb1_brunlock(tdb, F_RDLCK, off, 1) : 0);
+}
+
+bool tdb1_have_extra_locks(struct tdb1_context *tdb)
+{
+       unsigned int extra = tdb->num_lockrecs;
+
+       /* A transaction holds the lock for all records. */
+       if (!tdb->transaction && tdb->allrecord_lock.count) {
+               return true;
+       }
+
+       /* We always hold the active lock if CLEAR_IF_FIRST. */
+       if (tdb1_find_nestlock(tdb, TDB1_ACTIVE_LOCK)) {
+               extra--;
+       }
+
+       /* In a transaction, we expect to hold the transaction lock */
+       if (tdb->transaction
+           && tdb1_find_nestlock(tdb, TDB1_TRANSACTION_LOCK)) {
+               extra--;
+       }
+
+       return extra;
+}
+
+/* The transaction code uses this to remove all locks. */
+void tdb1_release_transaction_locks(struct tdb1_context *tdb)
+{
+       unsigned int i, active = 0;
+
+       if (tdb->allrecord_lock.count != 0) {
+               tdb1_brunlock(tdb, tdb->allrecord_lock.ltype, TDB1_FREELIST_TOP, 0);
+               tdb->allrecord_lock.count = 0;
+       }
+
+       for (i=0;i<tdb->num_lockrecs;i++) {
+               struct tdb1_lock_type *lck = &tdb->lockrecs[i];
+
+               /* Don't release the active lock!  Copy it to first entry. */
+               if (lck->off == TDB1_ACTIVE_LOCK) {
+                       tdb->lockrecs[active++] = *lck;
+               } else {
+                       tdb1_brunlock(tdb, lck->ltype, lck->off, 1);
+               }
+       }
+       tdb->num_lockrecs = active;
+       if (tdb->num_lockrecs == 0) {
+               SAFE_FREE(tdb->lockrecs);
+       }
+}
diff --git a/ccan/tdb2/tdb1_open.c b/ccan/tdb2/tdb1_open.c
new file mode 100644 (file)
index 0000000..e7dbddd
--- /dev/null
@@ -0,0 +1,609 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb1_private.h"
+
+/* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
+static struct tdb1_context *tdb1s = NULL;
+
+/* We use two hashes to double-check they're using the right hash function. */
+void tdb1_header_hash(struct tdb1_context *tdb,
+                    uint32_t *magic1_hash, uint32_t *magic2_hash)
+{
+       TDB1_DATA hash_key;
+       uint32_t tdb1_magic = TDB1_MAGIC;
+
+       hash_key.dptr = (unsigned char *)TDB1_MAGIC_FOOD;
+       hash_key.dsize = sizeof(TDB1_MAGIC_FOOD);
+       *magic1_hash = tdb->hash_fn(&hash_key);
+
+       hash_key.dptr = (unsigned char *)TDB1_CONV(tdb1_magic);
+       hash_key.dsize = sizeof(tdb1_magic);
+       *magic2_hash = tdb->hash_fn(&hash_key);
+
+       /* Make sure at least one hash is non-zero! */
+       if (*magic1_hash == 0 && *magic2_hash == 0)
+               *magic1_hash = 1;
+}
+
+/* initialise a new database with a specified hash size */
+static int tdb1_new_database(struct tdb1_context *tdb, int hash_size)
+{
+       struct tdb1_header *newdb;
+       size_t size;
+       int ret = -1;
+
+       /* We make it up in memory, then write it out if not internal */
+       size = sizeof(struct tdb1_header) + (hash_size+1)*sizeof(tdb1_off_t);
+       if (!(newdb = (struct tdb1_header *)calloc(size, 1))) {
+               tdb->ecode = TDB1_ERR_OOM;
+               return -1;
+       }
+
+       /* Fill in the header */
+       newdb->version = TDB1_VERSION;
+       newdb->hash_size = hash_size;
+
+       tdb1_header_hash(tdb, &newdb->magic1_hash, &newdb->magic2_hash);
+
+       /* Make sure older tdbs (which don't check the magic hash fields)
+        * will refuse to open this TDB. */
+       if (tdb->flags & TDB1_INCOMPATIBLE_HASH)
+               newdb->rwlocks = TDB1_HASH_RWLOCK_MAGIC;
+
+       if (tdb->flags & TDB1_INTERNAL) {
+               tdb->map_size = size;
+               tdb->map_ptr = (char *)newdb;
+               memcpy(&tdb->header, newdb, sizeof(tdb->header));
+               /* Convert the `ondisk' version if asked. */
+               TDB1_CONV(*newdb);
+               return 0;
+       }
+       if (lseek(tdb->fd, 0, SEEK_SET) == -1)
+               goto fail;
+
+       if (ftruncate(tdb->fd, 0) == -1)
+               goto fail;
+
+       /* This creates an endian-converted header, as if read from disk */
+       TDB1_CONV(*newdb);
+       memcpy(&tdb->header, newdb, sizeof(tdb->header));
+       /* Don't endian-convert the magic food! */
+       memcpy(newdb->magic_food, TDB1_MAGIC_FOOD, strlen(TDB1_MAGIC_FOOD)+1);
+       /* we still have "ret == -1" here */
+       if (tdb1_write_all(tdb->fd, newdb, size))
+               ret = 0;
+
+  fail:
+       SAFE_FREE(newdb);
+       return ret;
+}
+
+
+
+static int tdb1_already_open(dev_t device,
+                           ino_t ino)
+{
+       struct tdb1_context *i;
+
+       for (i = tdb1s; i; i = i->next) {
+               if (i->device == device && i->inode == ino) {
+                       return 1;
+               }
+       }
+
+       return 0;
+}
+
+/* open the database, creating it if necessary
+
+   The open_flags and mode are passed straight to the open call on the
+   database file. A flags value of O_WRONLY is invalid. The hash size
+   is advisory, use zero for a default value.
+
+   Return is NULL on error, in which case errno is also set.  Don't
+   try to call tdb1_error or tdb1_errname, just do strerror(errno).
+
+   @param name may be NULL for internal databases. */
+_PUBLIC_ struct tdb1_context *tdb1_open(const char *name, int hash_size, int tdb1_flags,
+                     int open_flags, mode_t mode)
+{
+       return tdb1_open_ex(name, hash_size, tdb1_flags, open_flags, mode, NULL, NULL);
+}
+
+/* a default logging function */
+static void null_log_fn(struct tdb1_context *tdb, enum tdb1_debug_level level, const char *fmt, ...) PRINTF_ATTRIBUTE(3, 4);
+static void null_log_fn(struct tdb1_context *tdb, enum tdb1_debug_level level, const char *fmt, ...)
+{
+}
+
+static bool check_header_hash(struct tdb1_context *tdb,
+                             bool default_hash, uint32_t *m1, uint32_t *m2)
+{
+       tdb1_header_hash(tdb, m1, m2);
+       if (tdb->header.magic1_hash == *m1 &&
+           tdb->header.magic2_hash == *m2) {
+               return true;
+       }
+
+       /* If they explicitly set a hash, always respect it. */
+       if (!default_hash)
+               return false;
+
+       /* Otherwise, try the other inbuilt hash. */
+       if (tdb->hash_fn == tdb1_old_hash)
+               tdb->hash_fn = tdb1_jenkins_hash;
+       else
+               tdb->hash_fn = tdb1_old_hash;
+       return check_header_hash(tdb, false, m1, m2);
+}
+
+_PUBLIC_ struct tdb1_context *tdb1_open_ex(const char *name, int hash_size, int tdb1_flags,
+                               int open_flags, mode_t mode,
+                               const struct tdb1_logging_context *log_ctx,
+                               tdb1_hash_func hash_fn)
+{
+       struct tdb1_context *tdb;
+       struct stat st;
+       int rev = 0, locked = 0;
+       unsigned char *vp;
+       uint32_t vertest;
+       unsigned v;
+       const char *hash_alg;
+       uint32_t magic1, magic2;
+
+       if (!(tdb = (struct tdb1_context *)calloc(1, sizeof *tdb))) {
+               /* Can't log this */
+               errno = ENOMEM;
+               goto fail;
+       }
+       tdb1_io_init(tdb);
+       tdb->fd = -1;
+       tdb->name = NULL;
+       tdb->map_ptr = NULL;
+       tdb->flags = tdb1_flags;
+       tdb->open_flags = open_flags;
+       if (log_ctx) {
+               tdb->log = *log_ctx;
+       } else {
+               tdb->log.log_fn = null_log_fn;
+               tdb->log.log_private = NULL;
+       }
+
+       if (name == NULL && (tdb1_flags & TDB1_INTERNAL)) {
+               name = "__TDB1_INTERNAL__";
+       }
+
+       if (name == NULL) {
+               tdb->name = (char *)"__NULL__";
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_open_ex: called with name == NULL\n"));
+               tdb->name = NULL;
+               errno = EINVAL;
+               goto fail;
+       }
+
+       /* now make a copy of the name, as the caller memory might went away */
+       if (!(tdb->name = (char *)strdup(name))) {
+               /*
+                * set the name as the given string, so that tdb1_name() will
+                * work in case of an error.
+                */
+               tdb->name = (char *)name;
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: can't strdup(%s)\n",
+                        name));
+               tdb->name = NULL;
+               errno = ENOMEM;
+               goto fail;
+       }
+
+       if (hash_fn) {
+               tdb->hash_fn = hash_fn;
+               hash_alg = "the user defined";
+       } else {
+               /* This controls what we use when creating a tdb. */
+               if (tdb->flags & TDB1_INCOMPATIBLE_HASH) {
+                       tdb->hash_fn = tdb1_jenkins_hash;
+               } else {
+                       tdb->hash_fn = tdb1_old_hash;
+               }
+               hash_alg = "either default";
+       }
+
+       /* cache the page size */
+       tdb->page_size = getpagesize();
+       if (tdb->page_size <= 0) {
+               tdb->page_size = 0x2000;
+       }
+
+       tdb->max_dead_records = (tdb1_flags & TDB1_VOLATILE) ? 5 : 0;
+
+       if ((open_flags & O_ACCMODE) == O_WRONLY) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: can't open tdb %s write-only\n",
+                        name));
+               errno = EINVAL;
+               goto fail;
+       }
+
+       if (hash_size == 0)
+               hash_size = TDB1_DEFAULT_HASH_SIZE;
+       if ((open_flags & O_ACCMODE) == O_RDONLY) {
+               tdb->read_only = 1;
+               /* read only databases don't do locking or clear if first */
+               tdb->flags |= TDB1_NOLOCK;
+               tdb->flags &= ~TDB1_CLEAR_IF_FIRST;
+       }
+
+       if ((tdb->flags & TDB1_ALLOW_NESTING) &&
+           (tdb->flags & TDB1_DISALLOW_NESTING)) {
+               tdb->ecode = TDB1_ERR_NESTING;
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_open_ex: "
+                       "allow_nesting and disallow_nesting are not allowed together!"));
+               errno = EINVAL;
+               goto fail;
+       }
+
+       if (getenv("TDB_NO_FSYNC")) {
+               tdb->flags |= TDB1_NOSYNC;
+       }
+
+       /*
+        * TDB1_ALLOW_NESTING is the default behavior.
+        * Note: this may change in future versions!
+        */
+       if (!(tdb->flags & TDB1_DISALLOW_NESTING)) {
+               tdb->flags |= TDB1_ALLOW_NESTING;
+       }
+
+       /* internal databases don't mmap or lock, and start off cleared */
+       if (tdb->flags & TDB1_INTERNAL) {
+               tdb->flags |= (TDB1_NOLOCK | TDB1_NOMMAP);
+               tdb->flags &= ~TDB1_CLEAR_IF_FIRST;
+               if (tdb1_new_database(tdb, hash_size) != 0) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: tdb1_new_database failed!"));
+                       goto fail;
+               }
+               goto internal;
+       }
+
+       if ((tdb->fd = open(name, open_flags, mode)) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_WARNING, "tdb1_open_ex: could not open file %s: %s\n",
+                        name, strerror(errno)));
+               goto fail;      /* errno set by open(2) */
+       }
+
+       /* on exec, don't inherit the fd */
+       v = fcntl(tdb->fd, F_GETFD, 0);
+        fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
+
+       /* ensure there is only one process initialising at once */
+       if (tdb1_nest_lock(tdb, TDB1_OPEN_LOCK, F_WRLCK, TDB1_LOCK_WAIT) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: failed to get open lock on %s: %s\n",
+                        name, strerror(errno)));
+               goto fail;      /* errno set by tdb1_brlock */
+       }
+
+       /* we need to zero database if we are the only one with it open */
+       if ((tdb1_flags & TDB1_CLEAR_IF_FIRST) &&
+           (!tdb->read_only) &&
+           (locked = (tdb1_nest_lock(tdb, TDB1_ACTIVE_LOCK, F_WRLCK, TDB1_LOCK_NOWAIT|TDB1_LOCK_PROBE) == 0))) {
+               open_flags |= O_CREAT;
+               if (ftruncate(tdb->fd, 0) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_open_ex: "
+                                "failed to truncate %s: %s\n",
+                                name, strerror(errno)));
+                       goto fail; /* errno set by ftruncate */
+               }
+       }
+
+       errno = 0;
+       if (read(tdb->fd, &tdb->header, sizeof(tdb->header)) != sizeof(tdb->header)
+           || strcmp(tdb->header.magic_food, TDB1_MAGIC_FOOD) != 0) {
+               if (!(open_flags & O_CREAT) || tdb1_new_database(tdb, hash_size) == -1) {
+                       if (errno == 0) {
+                               errno = EIO; /* ie bad format or something */
+                       }
+                       goto fail;
+               }
+               rev = (tdb->flags & TDB1_CONVERT);
+       } else if (tdb->header.version != TDB1_VERSION
+                  && !(rev = (tdb->header.version==TDB1_BYTEREV(TDB1_VERSION)))) {
+               /* wrong version */
+               errno = EIO;
+               goto fail;
+       }
+       vp = (unsigned char *)&tdb->header.version;
+       vertest = (((uint32_t)vp[0]) << 24) | (((uint32_t)vp[1]) << 16) |
+                 (((uint32_t)vp[2]) << 8) | (uint32_t)vp[3];
+       tdb->flags |= (vertest==TDB1_VERSION) ? TDB1_BIGENDIAN : 0;
+       if (!rev)
+               tdb->flags &= ~TDB1_CONVERT;
+       else {
+               tdb->flags |= TDB1_CONVERT;
+               tdb1_convert(&tdb->header, sizeof(tdb->header));
+       }
+       if (fstat(tdb->fd, &st) == -1)
+               goto fail;
+
+       if (tdb->header.rwlocks != 0 &&
+           tdb->header.rwlocks != TDB1_HASH_RWLOCK_MAGIC) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: spinlocks no longer supported\n"));
+               goto fail;
+       }
+
+       if ((tdb->header.magic1_hash == 0) && (tdb->header.magic2_hash == 0)) {
+               /* older TDB without magic hash references */
+               tdb->hash_fn = tdb1_old_hash;
+       } else if (!check_header_hash(tdb, !hash_fn, &magic1, &magic2)) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_open_ex: "
+                        "%s was not created with %s hash function we are using\n"
+                        "magic1_hash[0x%08X %s 0x%08X] "
+                        "magic2_hash[0x%08X %s 0x%08X]\n",
+                        name, hash_alg,
+                        tdb->header.magic1_hash,
+                        (tdb->header.magic1_hash == magic1) ? "==" : "!=",
+                        magic1,
+                        tdb->header.magic2_hash,
+                        (tdb->header.magic2_hash == magic2) ? "==" : "!=",
+                        magic2));
+               errno = EINVAL;
+               goto fail;
+       }
+
+       /* Is it already in the open list?  If so, fail. */
+       if (tdb1_already_open(st.st_dev, st.st_ino)) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: "
+                        "%s (%d,%d) is already open in this process\n",
+                        name, (int)st.st_dev, (int)st.st_ino));
+               errno = EBUSY;
+               goto fail;
+       }
+
+       tdb->map_size = st.st_size;
+       tdb->device = st.st_dev;
+       tdb->inode = st.st_ino;
+       tdb1_mmap(tdb);
+       if (locked) {
+               if (tdb1_nest_unlock(tdb, TDB1_ACTIVE_LOCK, F_WRLCK, false) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: "
+                                "failed to release ACTIVE_LOCK on %s: %s\n",
+                                name, strerror(errno)));
+                       goto fail;
+               }
+
+       }
+
+       /* We always need to do this if the CLEAR_IF_FIRST flag is set, even if
+          we didn't get the initial exclusive lock as we need to let all other
+          users know we're using it. */
+
+       if (tdb1_flags & TDB1_CLEAR_IF_FIRST) {
+               /* leave this lock in place to indicate it's in use */
+               if (tdb1_nest_lock(tdb, TDB1_ACTIVE_LOCK, F_RDLCK, TDB1_LOCK_WAIT) == -1) {
+                       goto fail;
+               }
+       }
+
+       /* if needed, run recovery */
+       if (tdb1_transaction_recover(tdb) == -1) {
+               goto fail;
+       }
+
+ internal:
+       /* Internal (memory-only) databases skip all the code above to
+        * do with disk files, and resume here by releasing their
+        * open lock and hooking into the active list. */
+       if (tdb1_nest_unlock(tdb, TDB1_OPEN_LOCK, F_WRLCK, false) == -1) {
+               goto fail;
+       }
+       tdb->next = tdb1s;
+       tdb1s = tdb;
+       return tdb;
+
+ fail:
+       { int save_errno = errno;
+
+       if (!tdb)
+               return NULL;
+
+       if (tdb->map_ptr) {
+               if (tdb->flags & TDB1_INTERNAL)
+                       SAFE_FREE(tdb->map_ptr);
+               else
+                       tdb1_munmap(tdb);
+       }
+       if (tdb->fd != -1)
+               if (close(tdb->fd) != 0)
+                       TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_open_ex: failed to close tdb->fd on error!\n"));
+       SAFE_FREE(tdb->lockrecs);
+       SAFE_FREE(tdb->name);
+       SAFE_FREE(tdb);
+       errno = save_errno;
+       return NULL;
+       }
+}
+
+/*
+ * Set the maximum number of dead records per hash chain
+ */
+
+_PUBLIC_ void tdb1_set_max_dead(struct tdb1_context *tdb, int max_dead)
+{
+       tdb->max_dead_records = max_dead;
+}
+
+/**
+ * Close a database.
+ *
+ * @returns -1 for error; 0 for success.
+ **/
+_PUBLIC_ int tdb1_close(struct tdb1_context *tdb)
+{
+       struct tdb1_context **i;
+       int ret = 0;
+
+       if (tdb->transaction) {
+               tdb1_transaction_cancel(tdb);
+       }
+
+       if (tdb->map_ptr) {
+               if (tdb->flags & TDB1_INTERNAL)
+                       SAFE_FREE(tdb->map_ptr);
+               else
+                       tdb1_munmap(tdb);
+       }
+       SAFE_FREE(tdb->name);
+       if (tdb->fd != -1) {
+               ret = close(tdb->fd);
+               tdb->fd = -1;
+       }
+       SAFE_FREE(tdb->lockrecs);
+
+       /* Remove from contexts list */
+       for (i = &tdb1s; *i; i = &(*i)->next) {
+               if (*i == tdb) {
+                       *i = tdb->next;
+                       break;
+               }
+       }
+
+       memset(tdb, 0, sizeof(*tdb));
+       SAFE_FREE(tdb);
+
+       return ret;
+}
+
+/* register a loging function */
+_PUBLIC_ void tdb1_set_logging_function(struct tdb1_context *tdb,
+                                       const struct tdb1_logging_context *log_ctx)
+{
+        tdb->log = *log_ctx;
+}
+
+_PUBLIC_ void *tdb1_get_logging_private(struct tdb1_context *tdb)
+{
+       return tdb->log.log_private;
+}
+
+static int tdb1_reopen_internal(struct tdb1_context *tdb, bool active_lock)
+{
+#if !defined(LIBREPLACE_PREAD_NOT_REPLACED) || \
+       !defined(LIBREPLACE_PWRITE_NOT_REPLACED)
+       struct stat st;
+#endif
+
+       if (tdb->flags & TDB1_INTERNAL) {
+               return 0; /* Nothing to do. */
+       }
+
+       if (tdb1_have_extra_locks(tdb)) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_reopen: reopen not allowed with locks held\n"));
+               goto fail;
+       }
+
+       if (tdb->transaction != 0) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_reopen: reopen not allowed inside a transaction\n"));
+               goto fail;
+       }
+
+/* If we have real pread & pwrite, we can skip reopen. */
+#if !defined(LIBREPLACE_PREAD_NOT_REPLACED) || \
+       !defined(LIBREPLACE_PWRITE_NOT_REPLACED)
+       if (tdb1_munmap(tdb) != 0) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_reopen: munmap failed (%s)\n", strerror(errno)));
+               goto fail;
+       }
+       if (close(tdb->fd) != 0)
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_reopen: WARNING closing tdb->fd failed!\n"));
+       tdb->fd = open(tdb->name, tdb->open_flags & ~(O_CREAT|O_TRUNC), 0);
+       if (tdb->fd == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_reopen: open failed (%s)\n", strerror(errno)));
+               goto fail;
+       }
+       if (fstat(tdb->fd, &st) != 0) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_reopen: fstat failed (%s)\n", strerror(errno)));
+               goto fail;
+       }
+       if (st.st_ino != tdb->inode || st.st_dev != tdb->device) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_reopen: file dev/inode has changed!\n"));
+               goto fail;
+       }
+       tdb1_mmap(tdb);
+#endif /* fake pread or pwrite */
+
+       /* We may still think we hold the active lock. */
+       tdb->num_lockrecs = 0;
+       SAFE_FREE(tdb->lockrecs);
+
+       if (active_lock && tdb1_nest_lock(tdb, TDB1_ACTIVE_LOCK, F_RDLCK, TDB1_LOCK_WAIT) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_reopen: failed to obtain active lock\n"));
+               goto fail;
+       }
+
+       return 0;
+
+fail:
+       tdb1_close(tdb);
+       return -1;
+}
+
+/* reopen a tdb - this can be used after a fork to ensure that we have an independent
+   seek pointer from our parent and to re-establish locks */
+_PUBLIC_ int tdb1_reopen(struct tdb1_context *tdb)
+{
+       return tdb1_reopen_internal(tdb, tdb->flags & TDB1_CLEAR_IF_FIRST);
+}
+
+/* reopen all tdb's */
+_PUBLIC_ int tdb1_reopen_all(int parent_longlived)
+{
+       struct tdb1_context *tdb;
+
+       for (tdb=tdb1s; tdb; tdb = tdb->next) {
+               bool active_lock = (tdb->flags & TDB1_CLEAR_IF_FIRST);
+
+               /*
+                * If the parent is longlived (ie. a
+                * parent daemon architecture), we know
+                * it will keep it's active lock on a
+                * tdb opened with CLEAR_IF_FIRST. Thus
+                * for child processes we don't have to
+                * add an active lock. This is essential
+                * to improve performance on systems that
+                * keep POSIX locks as a non-scalable data
+                * structure in the kernel.
+                */
+               if (parent_longlived) {
+                       /* Ensure no clear-if-first. */
+                       active_lock = false;
+               }
+
+               if (tdb1_reopen_internal(tdb, active_lock) != 0)
+                       return -1;
+       }
+
+       return 0;
+}
diff --git a/ccan/tdb2/tdb1_private.h b/ccan/tdb2/tdb1_private.h
new file mode 100644 (file)
index 0000000..569ec71
--- /dev/null
@@ -0,0 +1,294 @@
+#ifndef CCAN_TDB2_TDB1_PRIVATE_H
+#define CCAN_TDB2_TDB1_PRIVATE_H
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library - private includes
+
+   Copyright (C) Andrew Tridgell              2005
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef _SAMBA_BUILD_
+#include "config.h"
+/* This keeps us consistent with TDB2 code. */
+#if HAVE_FILE_OFFSET_BITS
+#define _FILE_OFFSET_BITS 64
+#endif
+#include <stdint.h>
+#include <stdbool.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+#include <sys/time.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <stdio.h>
+#include <utime.h>
+
+#ifndef _PUBLIC_
+#define _PUBLIC_
+#endif
+
+#else
+#include "replace.h"
+#include "system/filesys.h"
+#include "system/time.h"
+#include "system/shmem.h"
+#include "system/select.h"
+#include "system/wait.h"
+#endif
+
+#include "tdb1.h"
+
+/* #define TDB_TRACE 1 */
+#ifndef HAVE_GETPAGESIZE
+#define getpagesize() 0x2000
+#endif
+
+#ifndef __STRING
+#define __STRING(x)    #x
+#endif
+
+#ifndef __STRINGSTRING
+#define __STRINGSTRING(x) __STRING(x)
+#endif
+
+#ifndef __location__
+#define __location__ __FILE__ ":" __STRINGSTRING(__LINE__)
+#endif
+
+typedef uint32_t tdb1_len_t;
+typedef uint32_t tdb1_off_t;
+
+#ifndef offsetof
+#define offsetof(t,f) ((unsigned int)&((t *)0)->f)
+#endif
+
+#define TDB1_MAGIC_FOOD "TDB file\n"
+#define TDB1_VERSION (0x26011967 + 6)
+#define TDB1_MAGIC (0x26011999U)
+#define TDB1_FREE_MAGIC (~TDB1_MAGIC)
+#define TDB1_DEAD_MAGIC (0xFEE1DEAD)
+#define TDB1_RECOVERY_MAGIC (0xf53bc0e7U)
+#define TDB1_RECOVERY_INVALID_MAGIC (0x0)
+#define TDB1_HASH_RWLOCK_MAGIC (0xbad1a51U)
+#define TDB1_ALIGNMENT 4
+#define TDB1_DEFAULT_HASH_SIZE 131
+#define TDB1_FREELIST_TOP (sizeof(struct tdb1_header))
+#define TDB1_ALIGN(x,a) (((x) + (a)-1) & ~((a)-1))
+#define TDB1_BYTEREV(x) (((((x)&0xff)<<24)|((x)&0xFF00)<<8)|(((x)>>8)&0xFF00)|((x)>>24))
+#define TDB1_DEAD(r) ((r)->magic == TDB1_DEAD_MAGIC)
+#define TDB1_BAD_MAGIC(r) ((r)->magic != TDB1_MAGIC && !TDB1_DEAD(r))
+#define TDB1_HASH_TOP(hash) (TDB1_FREELIST_TOP + (TDB1_BUCKET(hash)+1)*sizeof(tdb1_off_t))
+#define TDB1_HASHTABLE_SIZE(tdb) ((tdb->header.hash_size+1)*sizeof(tdb1_off_t))
+#define TDB1_DATA_START(hash_size) (TDB1_HASH_TOP(hash_size-1) + sizeof(tdb1_off_t))
+#define TDB1_RECOVERY_HEAD offsetof(struct tdb1_header, recovery_start)
+#define TDB1_SEQNUM_OFS    offsetof(struct tdb1_header, sequence_number)
+#define TDB1_PAD_BYTE 0x42
+#define TDB1_PAD_U32  0x42424242
+
+/* NB assumes there is a local variable called "tdb" that is the
+ * current context, also takes doubly-parenthesized print-style
+ * argument. */
+#define TDB1_LOG(x) tdb->log.log_fn x
+
+/* lock offsets */
+#define TDB1_OPEN_LOCK        0
+#define TDB1_ACTIVE_LOCK      4
+#define TDB1_TRANSACTION_LOCK 8
+
+/* free memory if the pointer is valid and zero the pointer */
+#ifndef SAFE_FREE
+#define SAFE_FREE(x) do { if ((x) != NULL) {free(x); (x)=NULL;} } while(0)
+#endif
+
+#define TDB1_BUCKET(hash) ((hash) % tdb->header.hash_size)
+
+#define TDB1_DOCONV() (tdb->flags & TDB1_CONVERT)
+#define TDB1_CONV(x) (TDB1_DOCONV() ? tdb1_convert(&x, sizeof(x)) : &x)
+
+/* the body of the database is made of one tdb1_record for the free space
+   plus a separate data list for each hash value */
+struct tdb1_record {
+       tdb1_off_t next; /* offset of the next record in the list */
+       tdb1_len_t rec_len; /* total byte length of record */
+       tdb1_len_t key_len; /* byte length of key */
+       tdb1_len_t data_len; /* byte length of data */
+       uint32_t full_hash; /* the full 32 bit hash of the key */
+       uint32_t magic;   /* try to catch errors */
+       /* the following union is implied:
+               union {
+                       char record[rec_len];
+                       struct {
+                               char key[key_len];
+                               char data[data_len];
+                       }
+                       uint32_t totalsize; (tailer)
+               }
+       */
+};
+
+
+/* this is stored at the front of every database */
+struct tdb1_header {
+       char magic_food[32]; /* for /etc/magic */
+       uint32_t version; /* version of the code */
+       uint32_t hash_size; /* number of hash entries */
+       tdb1_off_t rwlocks; /* obsolete - kept to detect old formats */
+       tdb1_off_t recovery_start; /* offset of transaction recovery region */
+       tdb1_off_t sequence_number; /* used when TDB1_SEQNUM is set */
+       uint32_t magic1_hash; /* hash of TDB1_MAGIC_FOOD. */
+       uint32_t magic2_hash; /* hash of TDB1_MAGIC. */
+       tdb1_off_t reserved[27];
+};
+
+struct tdb1_lock_type {
+       uint32_t off;
+       uint32_t count;
+       uint32_t ltype;
+};
+
+struct tdb1_traverse_lock {
+       struct tdb1_traverse_lock *next;
+       uint32_t off;
+       uint32_t hash;
+       int lock_rw;
+};
+
+enum tdb1_lock_flags {
+       /* WAIT == F_SETLKW, NOWAIT == F_SETLK */
+       TDB1_LOCK_NOWAIT = 0,
+       TDB1_LOCK_WAIT = 1,
+       /* If set, don't log an error on failure. */
+       TDB1_LOCK_PROBE = 2,
+       /* If set, don't actually lock at all. */
+       TDB1_LOCK_MARK_ONLY = 4,
+};
+
+struct tdb1_context;
+
+struct tdb1_methods {
+       int (*tdb1_read)(struct tdb1_context *, tdb1_off_t , void *, tdb1_len_t , int );
+       int (*tdb1_write)(struct tdb1_context *, tdb1_off_t, const void *, tdb1_len_t);
+       void (*next_hash_chain)(struct tdb1_context *, uint32_t *);
+       int (*tdb1_oob)(struct tdb1_context *, tdb1_off_t , int );
+       int (*tdb1_expand_file)(struct tdb1_context *, tdb1_off_t , tdb1_off_t );
+};
+
+struct tdb1_context {
+       char *name; /* the name of the database */
+       void *map_ptr; /* where it is currently mapped */
+       int fd; /* open file descriptor for the database */
+       tdb1_len_t map_size; /* how much space has been mapped */
+       int read_only; /* opened read-only */
+       int traverse_read; /* read-only traversal */
+       int traverse_write; /* read-write traversal */
+       struct tdb1_lock_type allrecord_lock; /* .offset == upgradable */
+       int num_lockrecs;
+       struct tdb1_lock_type *lockrecs; /* only real locks, all with count>0 */
+       enum TDB1_ERROR ecode; /* error code for last tdb error */
+       struct tdb1_header header; /* a cached copy of the header */
+       uint32_t flags; /* the flags passed to tdb1_open */
+       struct tdb1_traverse_lock travlocks; /* current traversal locks */
+       struct tdb1_context *next; /* all tdbs to avoid multiple opens */
+       dev_t device;   /* uniquely identifies this tdb */
+       ino_t inode;    /* uniquely identifies this tdb */
+       struct tdb1_logging_context log;
+       unsigned int (*hash_fn)(TDB1_DATA *key);
+       int open_flags; /* flags used in the open - needed by reopen */
+       const struct tdb1_methods *methods;
+       struct tdb1_transaction *transaction;
+       int page_size;
+       int max_dead_records;
+#ifdef TDB1_TRACE
+       int tracefd;
+#endif
+       volatile sig_atomic_t *interrupt_sig_ptr;
+};
+
+
+/*
+  internal prototypes
+*/
+int tdb1_munmap(struct tdb1_context *tdb);
+void tdb1_mmap(struct tdb1_context *tdb);
+int tdb1_lock(struct tdb1_context *tdb, int list, int ltype);
+int tdb1_lock_nonblock(struct tdb1_context *tdb, int list, int ltype);
+int tdb1_nest_lock(struct tdb1_context *tdb, uint32_t offset, int ltype,
+                 enum tdb1_lock_flags flags);
+int tdb1_nest_unlock(struct tdb1_context *tdb, uint32_t offset, int ltype,
+                   bool mark_lock);
+int tdb1_unlock(struct tdb1_context *tdb, int list, int ltype);
+int tdb1_brlock(struct tdb1_context *tdb,
+              int rw_type, tdb1_off_t offset, size_t len,
+              enum tdb1_lock_flags flags);
+int tdb1_brunlock(struct tdb1_context *tdb,
+                int rw_type, tdb1_off_t offset, size_t len);
+bool tdb1_have_extra_locks(struct tdb1_context *tdb);
+void tdb1_release_transaction_locks(struct tdb1_context *tdb);
+int tdb1_transaction_lock(struct tdb1_context *tdb, int ltype,
+                        enum tdb1_lock_flags lockflags);
+int tdb1_transaction_unlock(struct tdb1_context *tdb, int ltype);
+int tdb1_recovery_area(struct tdb1_context *tdb,
+                     const struct tdb1_methods *methods,
+                     tdb1_off_t *recovery_offset,
+                     struct tdb1_record *rec);
+int tdb1_allrecord_lock(struct tdb1_context *tdb, int ltype,
+                      enum tdb1_lock_flags flags, bool upgradable);
+int tdb1_allrecord_unlock(struct tdb1_context *tdb, int ltype, bool mark_lock);
+int tdb1_allrecord_upgrade(struct tdb1_context *tdb);
+int tdb1_write_lock_record(struct tdb1_context *tdb, tdb1_off_t off);
+int tdb1_write_unlock_record(struct tdb1_context *tdb, tdb1_off_t off);
+int tdb1_ofs_read(struct tdb1_context *tdb, tdb1_off_t offset, tdb1_off_t *d);
+int tdb1_ofs_write(struct tdb1_context *tdb, tdb1_off_t offset, tdb1_off_t *d);
+void *tdb1_convert(void *buf, uint32_t size);
+int tdb1_free(struct tdb1_context *tdb, tdb1_off_t offset, struct tdb1_record *rec);
+tdb1_off_t tdb1_allocate(struct tdb1_context *tdb, tdb1_len_t length, struct tdb1_record *rec);
+int tdb1_ofs_read(struct tdb1_context *tdb, tdb1_off_t offset, tdb1_off_t *d);
+int tdb1_ofs_write(struct tdb1_context *tdb, tdb1_off_t offset, tdb1_off_t *d);
+int tdb1_lock_record(struct tdb1_context *tdb, tdb1_off_t off);
+int tdb1_unlock_record(struct tdb1_context *tdb, tdb1_off_t off);
+bool tdb1_needs_recovery(struct tdb1_context *tdb);
+int tdb1_rec_read(struct tdb1_context *tdb, tdb1_off_t offset, struct tdb1_record *rec);
+int tdb1_rec_write(struct tdb1_context *tdb, tdb1_off_t offset, struct tdb1_record *rec);
+int tdb1_do_delete(struct tdb1_context *tdb, tdb1_off_t rec_ptr, struct tdb1_record *rec);
+unsigned char *tdb1_alloc_read(struct tdb1_context *tdb, tdb1_off_t offset, tdb1_len_t len);
+int tdb1_parse_data(struct tdb1_context *tdb, TDB1_DATA key,
+                  tdb1_off_t offset, tdb1_len_t len,
+                  int (*parser)(TDB1_DATA key, TDB1_DATA data,
+                                void *private_data),
+                  void *private_data);
+tdb1_off_t tdb1_find_lock_hash(struct tdb1_context *tdb, TDB1_DATA key, uint32_t hash, int locktype,
+                          struct tdb1_record *rec);
+void tdb1_io_init(struct tdb1_context *tdb);
+int tdb1_expand(struct tdb1_context *tdb, tdb1_off_t size);
+int tdb1_rec_free_read(struct tdb1_context *tdb, tdb1_off_t off,
+                     struct tdb1_record *rec);
+bool tdb1_write_all(int fd, const void *buf, size_t count);
+int tdb1_transaction_recover(struct tdb1_context *tdb);
+void tdb1_header_hash(struct tdb1_context *tdb,
+                    uint32_t *magic1_hash, uint32_t *magic2_hash);
+unsigned int tdb1_old_hash(TDB1_DATA *key);
+size_t tdb1_dead_space(struct tdb1_context *tdb, tdb1_off_t off);
+#endif /* CCAN_TDB2_TDB1_PRIVATE_H */
diff --git a/ccan/tdb2/tdb1_summary.c b/ccan/tdb2/tdb1_summary.c
new file mode 100644 (file)
index 0000000..61e1853
--- /dev/null
@@ -0,0 +1,201 @@
+ /*
+   Trivial Database: human-readable summary code
+   Copyright (C) Rusty Russell 2010
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+#include "tdb1_private.h"
+
+#define SUMMARY_FORMAT1 \
+       "Size of file/data: %u/%zu\n" \
+       "Number of records: %zu\n" \
+       "Smallest/average/largest keys: %zu/%zu/%zu\n" \
+       "Smallest/average/largest data: %zu/%zu/%zu\n" \
+       "Smallest/average/largest padding: %zu/%zu/%zu\n" \
+       "Number of dead records: %zu\n" \
+       "Smallest/average/largest dead records: %zu/%zu/%zu\n" \
+       "Number of free records: %zu\n" \
+       "Smallest/average/largest free records: %zu/%zu/%zu\n" \
+       "Number of hash chains: %zu\n" \
+       "Smallest/average/largest hash chains: %zu/%zu/%zu\n" \
+       "Number of uncoalesced records: %zu\n" \
+       "Smallest/average/largest uncoalesced runs: %zu/%zu/%zu\n" \
+       "Percentage keys/data/padding/free/dead/rechdrs&tailers/hashes: %.0f/%.0f/%.0f/%.0f/%.0f/%.0f/%.0f\n"
+
+/* We don't use tally module, to keep upstream happy. */
+struct tally {
+       size_t min, max, total;
+       size_t num;
+};
+
+static void tally1_init(struct tally *tally)
+{
+       tally->total = 0;
+       tally->num = 0;
+       tally->min = tally->max = 0;
+}
+
+static void tally1_add(struct tally *tally, size_t len)
+{
+       if (tally->num == 0)
+               tally->max = tally->min = len;
+       else if (len > tally->max)
+               tally->max = len;
+       else if (len < tally->min)
+               tally->min = len;
+       tally->num++;
+       tally->total += len;
+}
+
+static size_t tally1_mean(const struct tally *tally)
+{
+       if (!tally->num)
+               return 0;
+       return tally->total / tally->num;
+}
+
+static size_t get_hash_length(struct tdb1_context *tdb, unsigned int i)
+{
+       tdb1_off_t rec_ptr;
+       size_t count = 0;
+
+       if (tdb1_ofs_read(tdb, TDB1_HASH_TOP(i), &rec_ptr) == -1)
+               return 0;
+
+       /* keep looking until we find the right record */
+       while (rec_ptr) {
+               struct tdb1_record r;
+               ++count;
+               if (tdb1_rec_read(tdb, rec_ptr, &r) == -1)
+                       return 0;
+               rec_ptr = r.next;
+       }
+       return count;
+}
+
+_PUBLIC_ char *tdb1_summary(struct tdb1_context *tdb)
+{
+       tdb1_off_t off, rec_off;
+       struct tally freet, keys, data, dead, extra, hash, uncoal;
+       struct tdb1_record rec;
+       char *ret = NULL;
+       bool locked;
+       size_t len, unc = 0;
+       struct tdb1_record recovery;
+
+       /* Read-only databases use no locking at all: it's best-effort.
+        * We may have a write lock already, so skip that case too. */
+       if (tdb->read_only || tdb->allrecord_lock.count != 0) {
+               locked = false;
+       } else {
+               if (tdb1_lockall_read(tdb) == -1)
+                       return NULL;
+               locked = true;
+       }
+
+       if (tdb1_recovery_area(tdb, tdb->methods, &rec_off, &recovery) != 0) {
+               goto unlock;
+       }
+
+       tally1_init(&freet);
+       tally1_init(&keys);
+       tally1_init(&data);
+       tally1_init(&dead);
+       tally1_init(&extra);
+       tally1_init(&hash);
+       tally1_init(&uncoal);
+
+       for (off = TDB1_DATA_START(tdb->header.hash_size);
+            off < tdb->map_size - 1;
+            off += sizeof(rec) + rec.rec_len) {
+               if (tdb->methods->tdb1_read(tdb, off, &rec, sizeof(rec),
+                                          TDB1_DOCONV()) == -1)
+                       goto unlock;
+               switch (rec.magic) {
+               case TDB1_MAGIC:
+                       tally1_add(&keys, rec.key_len);
+                       tally1_add(&data, rec.data_len);
+                       tally1_add(&extra, rec.rec_len - (rec.key_len
+                                                        + rec.data_len));
+                       if (unc > 1)
+                               tally1_add(&uncoal, unc - 1);
+                       unc = 0;
+                       break;
+               case TDB1_FREE_MAGIC:
+                       tally1_add(&freet, rec.rec_len);
+                       unc++;
+                       break;
+               /* If we crash after ftruncate, we can get zeroes or fill. */
+               case TDB1_RECOVERY_INVALID_MAGIC:
+               case 0x42424242:
+                       unc++;
+                       /* If it's a valid recovery, we can trust rec_len. */
+                       if (off != rec_off) {
+                               rec.rec_len = tdb1_dead_space(tdb, off)
+                                       - sizeof(rec);
+                       }
+                       /* Fall through */
+               case TDB1_DEAD_MAGIC:
+                       tally1_add(&dead, rec.rec_len);
+                       break;
+               default:
+                       TDB1_LOG((tdb, TDB1_DEBUG_ERROR,
+                                "Unexpected record magic 0x%x at offset %d\n",
+                                rec.magic, off));
+                       goto unlock;
+               }
+       }
+       if (unc > 1)
+               tally1_add(&uncoal, unc - 1);
+
+       for (off = 0; off < tdb->header.hash_size; off++)
+               tally1_add(&hash, get_hash_length(tdb, off));
+
+       /* 20 is max length of a %zu. */
+       len = strlen(SUMMARY_FORMAT1) + 35*20 + 1;
+       ret = (char *)malloc(len);
+       if (!ret)
+               goto unlock;
+
+       snprintf(ret, len, SUMMARY_FORMAT1,
+                tdb->map_size, keys.total+data.total,
+                keys.num,
+                keys.min, tally1_mean(&keys), keys.max,
+                data.min, tally1_mean(&data), data.max,
+                extra.min, tally1_mean(&extra), extra.max,
+                dead.num,
+                dead.min, tally1_mean(&dead), dead.max,
+                freet.num,
+                freet.min, tally1_mean(&freet), freet.max,
+                hash.num,
+                hash.min, tally1_mean(&hash), hash.max,
+                uncoal.total,
+                uncoal.min, tally1_mean(&uncoal), uncoal.max,
+                keys.total * 100.0 / tdb->map_size,
+                data.total * 100.0 / tdb->map_size,
+                extra.total * 100.0 / tdb->map_size,
+                freet.total * 100.0 / tdb->map_size,
+                dead.total * 100.0 / tdb->map_size,
+                (keys.num + freet.num + dead.num)
+                * (sizeof(struct tdb1_record) + sizeof(uint32_t))
+                * 100.0 / tdb->map_size,
+                tdb->header.hash_size * sizeof(tdb1_off_t)
+                * 100.0 / tdb->map_size);
+
+unlock:
+       if (locked) {
+               tdb1_unlockall_read(tdb);
+       }
+       return ret;
+}
diff --git a/ccan/tdb2/tdb1_tdb.c b/ccan/tdb2/tdb1_tdb.c
new file mode 100644 (file)
index 0000000..1ada443
--- /dev/null
@@ -0,0 +1,993 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb1_private.h"
+
+_PUBLIC_ TDB1_DATA tdb1_null;
+
+/*
+  non-blocking increment of the tdb sequence number if the tdb has been opened using
+  the TDB1_SEQNUM flag
+*/
+_PUBLIC_ void tdb1_increment_seqnum_nonblock(struct tdb1_context *tdb)
+{
+       tdb1_off_t seqnum=0;
+
+       if (!(tdb->flags & TDB1_SEQNUM)) {
+               return;
+       }
+
+       /* we ignore errors from this, as we have no sane way of
+          dealing with them.
+       */
+       tdb1_ofs_read(tdb, TDB1_SEQNUM_OFS, &seqnum);
+       seqnum++;
+       tdb1_ofs_write(tdb, TDB1_SEQNUM_OFS, &seqnum);
+}
+
+/*
+  increment the tdb sequence number if the tdb has been opened using
+  the TDB1_SEQNUM flag
+*/
+static void tdb1_increment_seqnum(struct tdb1_context *tdb)
+{
+       if (!(tdb->flags & TDB1_SEQNUM)) {
+               return;
+       }
+
+       if (tdb1_nest_lock(tdb, TDB1_SEQNUM_OFS, F_WRLCK,
+                         TDB1_LOCK_WAIT|TDB1_LOCK_PROBE) != 0) {
+               return;
+       }
+
+       tdb1_increment_seqnum_nonblock(tdb);
+
+       tdb1_nest_unlock(tdb, TDB1_SEQNUM_OFS, F_WRLCK, false);
+}
+
+static int tdb1_key_compare(TDB1_DATA key, TDB1_DATA data, void *private_data)
+{
+       return memcmp(data.dptr, key.dptr, data.dsize);
+}
+
+/* Returns 0 on fail.  On success, return offset of record, and fills
+   in rec */
+static tdb1_off_t tdb1_find(struct tdb1_context *tdb, TDB1_DATA key, uint32_t hash,
+                       struct tdb1_record *r)
+{
+       tdb1_off_t rec_ptr;
+
+       /* read in the hash top */
+       if (tdb1_ofs_read(tdb, TDB1_HASH_TOP(hash), &rec_ptr) == -1)
+               return 0;
+
+       /* keep looking until we find the right record */
+       while (rec_ptr) {
+               if (tdb1_rec_read(tdb, rec_ptr, r) == -1)
+                       return 0;
+
+               if (!TDB1_DEAD(r) && hash==r->full_hash
+                   && key.dsize==r->key_len
+                   && tdb1_parse_data(tdb, key, rec_ptr + sizeof(*r),
+                                     r->key_len, tdb1_key_compare,
+                                     NULL) == 0) {
+                       return rec_ptr;
+               }
+               /* detect tight infinite loop */
+               if (rec_ptr == r->next) {
+                       tdb->ecode = TDB1_ERR_CORRUPT;
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_find: loop detected.\n"));
+                       return 0;
+               }
+               rec_ptr = r->next;
+       }
+       tdb->ecode = TDB1_ERR_NOEXIST;
+       return 0;
+}
+
+/* As tdb1_find, but if you succeed, keep the lock */
+tdb1_off_t tdb1_find_lock_hash(struct tdb1_context *tdb, TDB1_DATA key, uint32_t hash, int locktype,
+                          struct tdb1_record *rec)
+{
+       uint32_t rec_ptr;
+
+       if (tdb1_lock(tdb, TDB1_BUCKET(hash), locktype) == -1)
+               return 0;
+       if (!(rec_ptr = tdb1_find(tdb, key, hash, rec)))
+               tdb1_unlock(tdb, TDB1_BUCKET(hash), locktype);
+       return rec_ptr;
+}
+
+static TDB1_DATA _tdb1_fetch(struct tdb1_context *tdb, TDB1_DATA key);
+
+/* update an entry in place - this only works if the new data size
+   is <= the old data size and the key exists.
+   on failure return -1.
+*/
+static int tdb1_update_hash(struct tdb1_context *tdb, TDB1_DATA key, uint32_t hash, TDB1_DATA dbuf)
+{
+       struct tdb1_record rec;
+       tdb1_off_t rec_ptr;
+
+       /* find entry */
+       if (!(rec_ptr = tdb1_find(tdb, key, hash, &rec)))
+               return -1;
+
+       /* it could be an exact duplicate of what is there - this is
+        * surprisingly common (eg. with a ldb re-index). */
+       if (rec.key_len == key.dsize &&
+           rec.data_len == dbuf.dsize &&
+           rec.full_hash == hash) {
+               TDB1_DATA data = _tdb1_fetch(tdb, key);
+               if (data.dsize == dbuf.dsize &&
+                   memcmp(data.dptr, dbuf.dptr, data.dsize) == 0) {
+                       if (data.dptr) {
+                               free(data.dptr);
+                       }
+                       return 0;
+               }
+               if (data.dptr) {
+                       free(data.dptr);
+               }
+       }
+
+       /* must be long enough key, data and tailer */
+       if (rec.rec_len < key.dsize + dbuf.dsize + sizeof(tdb1_off_t)) {
+               tdb->ecode = TDB1_SUCCESS; /* Not really an error */
+               return -1;
+       }
+
+       if (tdb->methods->tdb1_write(tdb, rec_ptr + sizeof(rec) + rec.key_len,
+                     dbuf.dptr, dbuf.dsize) == -1)
+               return -1;
+
+       if (dbuf.dsize != rec.data_len) {
+               /* update size */
+               rec.data_len = dbuf.dsize;
+               return tdb1_rec_write(tdb, rec_ptr, &rec);
+       }
+
+       return 0;
+}
+
+/* find an entry in the database given a key */
+/* If an entry doesn't exist tdb1_err will be set to
+ * TDB1_ERR_NOEXIST. If a key has no data attached
+ * then the TDB1_DATA will have zero length but
+ * a non-zero pointer
+ */
+static TDB1_DATA _tdb1_fetch(struct tdb1_context *tdb, TDB1_DATA key)
+{
+       tdb1_off_t rec_ptr;
+       struct tdb1_record rec;
+       TDB1_DATA ret;
+       uint32_t hash;
+
+       /* find which hash bucket it is in */
+       hash = tdb->hash_fn(&key);
+       if (!(rec_ptr = tdb1_find_lock_hash(tdb,key,hash,F_RDLCK,&rec)))
+               return tdb1_null;
+
+       ret.dptr = tdb1_alloc_read(tdb, rec_ptr + sizeof(rec) + rec.key_len,
+                                 rec.data_len);
+       ret.dsize = rec.data_len;
+       tdb1_unlock(tdb, TDB1_BUCKET(rec.full_hash), F_RDLCK);
+       return ret;
+}
+
+_PUBLIC_ TDB1_DATA tdb1_fetch(struct tdb1_context *tdb, TDB1_DATA key)
+{
+       TDB1_DATA ret = _tdb1_fetch(tdb, key);
+
+       return ret;
+}
+
+/*
+ * Find an entry in the database and hand the record's data to a parsing
+ * function. The parsing function is executed under the chain read lock, so it
+ * should be fast and should not block on other syscalls.
+ *
+ * DON'T CALL OTHER TDB CALLS FROM THE PARSER, THIS MIGHT LEAD TO SEGFAULTS.
+ *
+ * For mmapped tdb's that do not have a transaction open it points the parsing
+ * function directly at the mmap area, it avoids the malloc/memcpy in this
+ * case. If a transaction is open or no mmap is available, it has to do
+ * malloc/read/parse/free.
+ *
+ * This is interesting for all readers of potentially large data structures in
+ * the tdb records, ldb indexes being one example.
+ *
+ * Return -1 if the record was not found.
+ */
+
+_PUBLIC_ int tdb1_parse_record(struct tdb1_context *tdb, TDB1_DATA key,
+                    int (*parser)(TDB1_DATA key, TDB1_DATA data,
+                                  void *private_data),
+                    void *private_data)
+{
+       tdb1_off_t rec_ptr;
+       struct tdb1_record rec;
+       int ret;
+       uint32_t hash;
+
+       /* find which hash bucket it is in */
+       hash = tdb->hash_fn(&key);
+
+       if (!(rec_ptr = tdb1_find_lock_hash(tdb,key,hash,F_RDLCK,&rec))) {
+               /* record not found */
+               tdb->ecode = TDB1_ERR_NOEXIST;
+               return -1;
+       }
+
+       ret = tdb1_parse_data(tdb, key, rec_ptr + sizeof(rec) + rec.key_len,
+                            rec.data_len, parser, private_data);
+
+       tdb1_unlock(tdb, TDB1_BUCKET(rec.full_hash), F_RDLCK);
+
+       return ret;
+}
+
+/* check if an entry in the database exists
+
+   note that 1 is returned if the key is found and 0 is returned if not found
+   this doesn't match the conventions in the rest of this module, but is
+   compatible with gdbm
+*/
+static int tdb1_exists_hash(struct tdb1_context *tdb, TDB1_DATA key, uint32_t hash)
+{
+       struct tdb1_record rec;
+
+       if (tdb1_find_lock_hash(tdb, key, hash, F_RDLCK, &rec) == 0)
+               return 0;
+       tdb1_unlock(tdb, TDB1_BUCKET(rec.full_hash), F_RDLCK);
+       return 1;
+}
+
+_PUBLIC_ int tdb1_exists(struct tdb1_context *tdb, TDB1_DATA key)
+{
+       uint32_t hash = tdb->hash_fn(&key);
+       int ret;
+
+       ret = tdb1_exists_hash(tdb, key, hash);
+       return ret;
+}
+
+/* actually delete an entry in the database given the offset */
+int tdb1_do_delete(struct tdb1_context *tdb, tdb1_off_t rec_ptr, struct tdb1_record *rec)
+{
+       tdb1_off_t last_ptr, i;
+       struct tdb1_record lastrec;
+
+       if (tdb->read_only || tdb->traverse_read) return -1;
+
+       if (((tdb->traverse_write != 0) && (!TDB1_DEAD(rec))) ||
+           tdb1_write_lock_record(tdb, rec_ptr) == -1) {
+               /* Someone traversing here: mark it as dead */
+               rec->magic = TDB1_DEAD_MAGIC;
+               return tdb1_rec_write(tdb, rec_ptr, rec);
+       }
+       if (tdb1_write_unlock_record(tdb, rec_ptr) != 0)
+               return -1;
+
+       /* find previous record in hash chain */
+       if (tdb1_ofs_read(tdb, TDB1_HASH_TOP(rec->full_hash), &i) == -1)
+               return -1;
+       for (last_ptr = 0; i != rec_ptr; last_ptr = i, i = lastrec.next)
+               if (tdb1_rec_read(tdb, i, &lastrec) == -1)
+                       return -1;
+
+       /* unlink it: next ptr is at start of record. */
+       if (last_ptr == 0)
+               last_ptr = TDB1_HASH_TOP(rec->full_hash);
+       if (tdb1_ofs_write(tdb, last_ptr, &rec->next) == -1)
+               return -1;
+
+       /* recover the space */
+       if (tdb1_free(tdb, rec_ptr, rec) == -1)
+               return -1;
+       return 0;
+}
+
+static int tdb1_count_dead(struct tdb1_context *tdb, uint32_t hash)
+{
+       int res = 0;
+       tdb1_off_t rec_ptr;
+       struct tdb1_record rec;
+
+       /* read in the hash top */
+       if (tdb1_ofs_read(tdb, TDB1_HASH_TOP(hash), &rec_ptr) == -1)
+               return 0;
+
+       while (rec_ptr) {
+               if (tdb1_rec_read(tdb, rec_ptr, &rec) == -1)
+                       return 0;
+
+               if (rec.magic == TDB1_DEAD_MAGIC) {
+                       res += 1;
+               }
+               rec_ptr = rec.next;
+       }
+       return res;
+}
+
+/*
+ * Purge all DEAD records from a hash chain
+ */
+static int tdb1_purge_dead(struct tdb1_context *tdb, uint32_t hash)
+{
+       int res = -1;
+       struct tdb1_record rec;
+       tdb1_off_t rec_ptr;
+
+       if (tdb1_lock(tdb, -1, F_WRLCK) == -1) {
+               return -1;
+       }
+
+       /* read in the hash top */
+       if (tdb1_ofs_read(tdb, TDB1_HASH_TOP(hash), &rec_ptr) == -1)
+               goto fail;
+
+       while (rec_ptr) {
+               tdb1_off_t next;
+
+               if (tdb1_rec_read(tdb, rec_ptr, &rec) == -1) {
+                       goto fail;
+               }
+
+               next = rec.next;
+
+               if (rec.magic == TDB1_DEAD_MAGIC
+                   && tdb1_do_delete(tdb, rec_ptr, &rec) == -1) {
+                       goto fail;
+               }
+               rec_ptr = next;
+       }
+       res = 0;
+ fail:
+       tdb1_unlock(tdb, -1, F_WRLCK);
+       return res;
+}
+
+/* delete an entry in the database given a key */
+static int tdb1_delete_hash(struct tdb1_context *tdb, TDB1_DATA key, uint32_t hash)
+{
+       tdb1_off_t rec_ptr;
+       struct tdb1_record rec;
+       int ret;
+
+       if (tdb->max_dead_records != 0) {
+
+               /*
+                * Allow for some dead records per hash chain, mainly for
+                * tdb's with a very high create/delete rate like locking.tdb.
+                */
+
+               if (tdb1_lock(tdb, TDB1_BUCKET(hash), F_WRLCK) == -1)
+                       return -1;
+
+               if (tdb1_count_dead(tdb, hash) >= tdb->max_dead_records) {
+                       /*
+                        * Don't let the per-chain freelist grow too large,
+                        * delete all existing dead records
+                        */
+                       tdb1_purge_dead(tdb, hash);
+               }
+
+               if (!(rec_ptr = tdb1_find(tdb, key, hash, &rec))) {
+                       tdb1_unlock(tdb, TDB1_BUCKET(hash), F_WRLCK);
+                       return -1;
+               }
+
+               /*
+                * Just mark the record as dead.
+                */
+               rec.magic = TDB1_DEAD_MAGIC;
+               ret = tdb1_rec_write(tdb, rec_ptr, &rec);
+       }
+       else {
+               if (!(rec_ptr = tdb1_find_lock_hash(tdb, key, hash, F_WRLCK,
+                                                  &rec)))
+                       return -1;
+
+               ret = tdb1_do_delete(tdb, rec_ptr, &rec);
+       }
+
+       if (ret == 0) {
+               tdb1_increment_seqnum(tdb);
+       }
+
+       if (tdb1_unlock(tdb, TDB1_BUCKET(rec.full_hash), F_WRLCK) != 0)
+               TDB1_LOG((tdb, TDB1_DEBUG_WARNING, "tdb1_delete: WARNING tdb1_unlock failed!\n"));
+       return ret;
+}
+
+_PUBLIC_ int tdb1_delete(struct tdb1_context *tdb, TDB1_DATA key)
+{
+       uint32_t hash = tdb->hash_fn(&key);
+       int ret;
+
+       ret = tdb1_delete_hash(tdb, key, hash);
+       return ret;
+}
+
+/*
+ * See if we have a dead record around with enough space
+ */
+static tdb1_off_t tdb1_find_dead(struct tdb1_context *tdb, uint32_t hash,
+                              struct tdb1_record *r, tdb1_len_t length)
+{
+       tdb1_off_t rec_ptr;
+
+       /* read in the hash top */
+       if (tdb1_ofs_read(tdb, TDB1_HASH_TOP(hash), &rec_ptr) == -1)
+               return 0;
+
+       /* keep looking until we find the right record */
+       while (rec_ptr) {
+               if (tdb1_rec_read(tdb, rec_ptr, r) == -1)
+                       return 0;
+
+               if (TDB1_DEAD(r) && r->rec_len >= length) {
+                       /*
+                        * First fit for simple coding, TODO: change to best
+                        * fit
+                        */
+                       return rec_ptr;
+               }
+               rec_ptr = r->next;
+       }
+       return 0;
+}
+
+static int _tdb1_store(struct tdb1_context *tdb, TDB1_DATA key,
+                      TDB1_DATA dbuf, int flag, uint32_t hash)
+{
+       struct tdb1_record rec;
+       tdb1_off_t rec_ptr;
+       char *p = NULL;
+       int ret = -1;
+
+       /* check for it existing, on insert. */
+       if (flag == TDB1_INSERT) {
+               if (tdb1_exists_hash(tdb, key, hash)) {
+                       tdb->ecode = TDB1_ERR_EXISTS;
+                       goto fail;
+               }
+       } else {
+               /* first try in-place update, on modify or replace. */
+               if (tdb1_update_hash(tdb, key, hash, dbuf) == 0) {
+                       goto done;
+               }
+               if (tdb->ecode == TDB1_ERR_NOEXIST &&
+                   flag == TDB1_MODIFY) {
+                       /* if the record doesn't exist and we are in TDB1_MODIFY mode then
+                        we should fail the store */
+                       goto fail;
+               }
+       }
+       /* reset the error code potentially set by the tdb1_update() */
+       tdb->ecode = TDB1_SUCCESS;
+
+       /* delete any existing record - if it doesn't exist we don't
+           care.  Doing this first reduces fragmentation, and avoids
+           coalescing with `allocated' block before it's updated. */
+       if (flag != TDB1_INSERT)
+               tdb1_delete_hash(tdb, key, hash);
+
+       /* Copy key+value *before* allocating free space in case malloc
+          fails and we are left with a dead spot in the tdb. */
+
+       if (!(p = (char *)malloc(key.dsize + dbuf.dsize))) {
+               tdb->ecode = TDB1_ERR_OOM;
+               goto fail;
+       }
+
+       memcpy(p, key.dptr, key.dsize);
+       if (dbuf.dsize)
+               memcpy(p+key.dsize, dbuf.dptr, dbuf.dsize);
+
+       if (tdb->max_dead_records != 0) {
+               /*
+                * Allow for some dead records per hash chain, look if we can
+                * find one that can hold the new record. We need enough space
+                * for key, data and tailer. If we find one, we don't have to
+                * consult the central freelist.
+                */
+               rec_ptr = tdb1_find_dead(
+                       tdb, hash, &rec,
+                       key.dsize + dbuf.dsize + sizeof(tdb1_off_t));
+
+               if (rec_ptr != 0) {
+                       rec.key_len = key.dsize;
+                       rec.data_len = dbuf.dsize;
+                       rec.full_hash = hash;
+                       rec.magic = TDB1_MAGIC;
+                       if (tdb1_rec_write(tdb, rec_ptr, &rec) == -1
+                           || tdb->methods->tdb1_write(
+                                   tdb, rec_ptr + sizeof(rec),
+                                   p, key.dsize + dbuf.dsize) == -1) {
+                               goto fail;
+                       }
+                       goto done;
+               }
+       }
+
+       /*
+        * We have to allocate some space from the freelist, so this means we
+        * have to lock it. Use the chance to purge all the DEAD records from
+        * the hash chain under the freelist lock.
+        */
+
+       if (tdb1_lock(tdb, -1, F_WRLCK) == -1) {
+               goto fail;
+       }
+
+       if ((tdb->max_dead_records != 0)
+           && (tdb1_purge_dead(tdb, hash) == -1)) {
+               tdb1_unlock(tdb, -1, F_WRLCK);
+               goto fail;
+       }
+
+       /* we have to allocate some space */
+       rec_ptr = tdb1_allocate(tdb, key.dsize + dbuf.dsize, &rec);
+
+       tdb1_unlock(tdb, -1, F_WRLCK);
+
+       if (rec_ptr == 0) {
+               goto fail;
+       }
+
+       /* Read hash top into next ptr */
+       if (tdb1_ofs_read(tdb, TDB1_HASH_TOP(hash), &rec.next) == -1)
+               goto fail;
+
+       rec.key_len = key.dsize;
+       rec.data_len = dbuf.dsize;
+       rec.full_hash = hash;
+       rec.magic = TDB1_MAGIC;
+
+       /* write out and point the top of the hash chain at it */
+       if (tdb1_rec_write(tdb, rec_ptr, &rec) == -1
+           || tdb->methods->tdb1_write(tdb, rec_ptr+sizeof(rec), p, key.dsize+dbuf.dsize)==-1
+           || tdb1_ofs_write(tdb, TDB1_HASH_TOP(hash), &rec_ptr) == -1) {
+               /* Need to tdb1_unallocate() here */
+               goto fail;
+       }
+
+ done:
+       ret = 0;
+ fail:
+       if (ret == 0) {
+               tdb1_increment_seqnum(tdb);
+       }
+
+       SAFE_FREE(p);
+       return ret;
+}
+
+/* store an element in the database, replacing any existing element
+   with the same key
+
+   return 0 on success, -1 on failure
+*/
+_PUBLIC_ int tdb1_store(struct tdb1_context *tdb, TDB1_DATA key, TDB1_DATA dbuf, int flag)
+{
+       uint32_t hash;
+       int ret;
+
+       if (tdb->read_only || tdb->traverse_read) {
+               tdb->ecode = TDB1_ERR_RDONLY;
+               return -1;
+       }
+
+       /* find which hash bucket it is in */
+       hash = tdb->hash_fn(&key);
+       if (tdb1_lock(tdb, TDB1_BUCKET(hash), F_WRLCK) == -1)
+               return -1;
+
+       ret = _tdb1_store(tdb, key, dbuf, flag, hash);
+       tdb1_unlock(tdb, TDB1_BUCKET(hash), F_WRLCK);
+       return ret;
+}
+
+/* Append to an entry. Create if not exist. */
+_PUBLIC_ int tdb1_append(struct tdb1_context *tdb, TDB1_DATA key, TDB1_DATA new_dbuf)
+{
+       uint32_t hash;
+       TDB1_DATA dbuf;
+       int ret = -1;
+
+       /* find which hash bucket it is in */
+       hash = tdb->hash_fn(&key);
+       if (tdb1_lock(tdb, TDB1_BUCKET(hash), F_WRLCK) == -1)
+               return -1;
+
+       dbuf = _tdb1_fetch(tdb, key);
+
+       if (dbuf.dptr == NULL) {
+               dbuf.dptr = (unsigned char *)malloc(new_dbuf.dsize);
+       } else {
+               unsigned int new_len = dbuf.dsize + new_dbuf.dsize;
+               unsigned char *new_dptr;
+
+               /* realloc '0' is special: don't do that. */
+               if (new_len == 0)
+                       new_len = 1;
+               new_dptr = (unsigned char *)realloc(dbuf.dptr, new_len);
+               if (new_dptr == NULL) {
+                       free(dbuf.dptr);
+               }
+               dbuf.dptr = new_dptr;
+       }
+
+       if (dbuf.dptr == NULL) {
+               tdb->ecode = TDB1_ERR_OOM;
+               goto failed;
+       }
+
+       memcpy(dbuf.dptr + dbuf.dsize, new_dbuf.dptr, new_dbuf.dsize);
+       dbuf.dsize += new_dbuf.dsize;
+
+       ret = _tdb1_store(tdb, key, dbuf, 0, hash);
+
+failed:
+       tdb1_unlock(tdb, TDB1_BUCKET(hash), F_WRLCK);
+       SAFE_FREE(dbuf.dptr);
+       return ret;
+}
+
+
+/*
+  return the name of the current tdb file
+  useful for external logging functions
+*/
+_PUBLIC_ const char *tdb1_name(struct tdb1_context *tdb)
+{
+       return tdb->name;
+}
+
+/*
+  return the underlying file descriptor being used by tdb, or -1
+  useful for external routines that want to check the device/inode
+  of the fd
+*/
+_PUBLIC_ int tdb1_fd(struct tdb1_context *tdb)
+{
+       return tdb->fd;
+}
+
+/*
+  return the current logging function
+  useful for external tdb routines that wish to log tdb errors
+*/
+_PUBLIC_ tdb1_log_func tdb1_log_fn(struct tdb1_context *tdb)
+{
+       return tdb->log.log_fn;
+}
+
+
+/*
+  get the tdb sequence number. Only makes sense if the writers opened
+  with TDB1_SEQNUM set. Note that this sequence number will wrap quite
+  quickly, so it should only be used for a 'has something changed'
+  test, not for code that relies on the count of the number of changes
+  made. If you want a counter then use a tdb record.
+
+  The aim of this sequence number is to allow for a very lightweight
+  test of a possible tdb change.
+*/
+_PUBLIC_ int tdb1_get_seqnum(struct tdb1_context *tdb)
+{
+       tdb1_off_t seqnum=0;
+
+       tdb1_ofs_read(tdb, TDB1_SEQNUM_OFS, &seqnum);
+       return seqnum;
+}
+
+_PUBLIC_ int tdb1_hash_size(struct tdb1_context *tdb)
+{
+       return tdb->header.hash_size;
+}
+
+_PUBLIC_ size_t tdb1_map_size(struct tdb1_context *tdb)
+{
+       return tdb->map_size;
+}
+
+_PUBLIC_ int tdb1_get_flags(struct tdb1_context *tdb)
+{
+       return tdb->flags;
+}
+
+_PUBLIC_ void tdb1_add_flags(struct tdb1_context *tdb, unsigned flags)
+{
+       if ((flags & TDB1_ALLOW_NESTING) &&
+           (flags & TDB1_DISALLOW_NESTING)) {
+               tdb->ecode = TDB1_ERR_NESTING;
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_add_flags: "
+                       "allow_nesting and disallow_nesting are not allowed together!"));
+               return;
+       }
+
+       if (flags & TDB1_ALLOW_NESTING) {
+               tdb->flags &= ~TDB1_DISALLOW_NESTING;
+       }
+       if (flags & TDB1_DISALLOW_NESTING) {
+               tdb->flags &= ~TDB1_ALLOW_NESTING;
+       }
+
+       tdb->flags |= flags;
+}
+
+_PUBLIC_ void tdb1_remove_flags(struct tdb1_context *tdb, unsigned flags)
+{
+       if ((flags & TDB1_ALLOW_NESTING) &&
+           (flags & TDB1_DISALLOW_NESTING)) {
+               tdb->ecode = TDB1_ERR_NESTING;
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_remove_flags: "
+                       "allow_nesting and disallow_nesting are not allowed together!"));
+               return;
+       }
+
+       if (flags & TDB1_ALLOW_NESTING) {
+               tdb->flags |= TDB1_DISALLOW_NESTING;
+       }
+       if (flags & TDB1_DISALLOW_NESTING) {
+               tdb->flags |= TDB1_ALLOW_NESTING;
+       }
+
+       tdb->flags &= ~flags;
+}
+
+
+/*
+  enable sequence number handling on an open tdb
+*/
+_PUBLIC_ void tdb1_enable_seqnum(struct tdb1_context *tdb)
+{
+       tdb->flags |= TDB1_SEQNUM;
+}
+
+
+/*
+  add a region of the file to the freelist. Length is the size of the region in bytes,
+  which includes the free list header that needs to be added
+ */
+static int tdb1_free_region(struct tdb1_context *tdb, tdb1_off_t offset, ssize_t length)
+{
+       struct tdb1_record rec;
+       if (length <= sizeof(rec)) {
+               /* the region is not worth adding */
+               return 0;
+       }
+       if (length + offset > tdb->map_size) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL,"tdb1_free_region: adding region beyond end of file\n"));
+               return -1;
+       }
+       memset(&rec,'\0',sizeof(rec));
+       rec.rec_len = length - sizeof(rec);
+       if (tdb1_free(tdb, offset, &rec) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL,"tdb1_free_region: failed to add free record\n"));
+               return -1;
+       }
+       return 0;
+}
+
+/*
+  wipe the entire database, deleting all records. This can be done
+  very fast by using a allrecord lock. The entire data portion of the
+  file becomes a single entry in the freelist.
+
+  This code carefully steps around the recovery area, leaving it alone
+ */
+_PUBLIC_ int tdb1_wipe_all(struct tdb1_context *tdb)
+{
+       int i;
+       tdb1_off_t offset = 0;
+       ssize_t data_len;
+       tdb1_off_t recovery_head;
+       tdb1_len_t recovery_size = 0;
+
+       if (tdb1_lockall(tdb) != 0) {
+               return -1;
+       }
+
+
+       /* see if the tdb has a recovery area, and remember its size
+          if so. We don't want to lose this as otherwise each
+          tdb1_wipe_all() in a transaction will increase the size of
+          the tdb by the size of the recovery area */
+       if (tdb1_ofs_read(tdb, TDB1_RECOVERY_HEAD, &recovery_head) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_wipe_all: failed to read recovery head\n"));
+               goto failed;
+       }
+
+       if (recovery_head != 0) {
+               struct tdb1_record rec;
+               if (tdb->methods->tdb1_read(tdb, recovery_head, &rec, sizeof(rec), TDB1_DOCONV()) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_wipe_all: failed to read recovery record\n"));
+                       return -1;
+               }
+               recovery_size = rec.rec_len + sizeof(rec);
+       }
+
+       /* wipe the hashes */
+       for (i=0;i<tdb->header.hash_size;i++) {
+               if (tdb1_ofs_write(tdb, TDB1_HASH_TOP(i), &offset) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL,"tdb1_wipe_all: failed to write hash %d\n", i));
+                       goto failed;
+               }
+       }
+
+       /* wipe the freelist */
+       if (tdb1_ofs_write(tdb, TDB1_FREELIST_TOP, &offset) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL,"tdb1_wipe_all: failed to write freelist\n"));
+               goto failed;
+       }
+
+       /* add all the rest of the file to the freelist, possibly leaving a gap
+          for the recovery area */
+       if (recovery_size == 0) {
+               /* the simple case - the whole file can be used as a freelist */
+               data_len = (tdb->map_size - TDB1_DATA_START(tdb->header.hash_size));
+               if (tdb1_free_region(tdb, TDB1_DATA_START(tdb->header.hash_size), data_len) != 0) {
+                       goto failed;
+               }
+       } else {
+               /* we need to add two freelist entries - one on either
+                  side of the recovery area
+
+                  Note that we cannot shift the recovery area during
+                  this operation. Only the transaction.c code may
+                  move the recovery area or we risk subtle data
+                  corruption
+               */
+               data_len = (recovery_head - TDB1_DATA_START(tdb->header.hash_size));
+               if (tdb1_free_region(tdb, TDB1_DATA_START(tdb->header.hash_size), data_len) != 0) {
+                       goto failed;
+               }
+               /* and the 2nd free list entry after the recovery area - if any */
+               data_len = tdb->map_size - (recovery_head+recovery_size);
+               if (tdb1_free_region(tdb, recovery_head+recovery_size, data_len) != 0) {
+                       goto failed;
+               }
+       }
+
+       if (tdb1_unlockall(tdb) != 0) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL,"tdb1_wipe_all: failed to unlock\n"));
+               goto failed;
+       }
+
+       return 0;
+
+failed:
+       tdb1_unlockall(tdb);
+       return -1;
+}
+
+struct traverse_state {
+       bool error;
+       struct tdb1_context *dest_db;
+};
+
+/*
+  traverse function for repacking
+ */
+static int repack_traverse(struct tdb1_context *tdb, TDB1_DATA key, TDB1_DATA data, void *private_data)
+{
+       struct traverse_state *state = (struct traverse_state *)private_data;
+       if (tdb1_store(state->dest_db, key, data, TDB1_INSERT) != 0) {
+               state->error = true;
+               return -1;
+       }
+       return 0;
+}
+
+/*
+  repack a tdb
+ */
+_PUBLIC_ int tdb1_repack(struct tdb1_context *tdb)
+{
+       struct tdb1_context *tmp_db;
+       struct traverse_state state;
+
+       if (tdb1_transaction_start(tdb) != 0) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, __location__ " Failed to start transaction\n"));
+               return -1;
+       }
+
+       tmp_db = tdb1_open("tmpdb", tdb1_hash_size(tdb), TDB1_INTERNAL, O_RDWR|O_CREAT, 0);
+       if (tmp_db == NULL) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, __location__ " Failed to create tmp_db\n"));
+               tdb1_transaction_cancel(tdb);
+               return -1;
+       }
+
+       state.error = false;
+       state.dest_db = tmp_db;
+
+       if (tdb1_traverse_read(tdb, repack_traverse, &state) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, __location__ " Failed to traverse copying out\n"));
+               tdb1_transaction_cancel(tdb);
+               tdb1_close(tmp_db);
+               return -1;
+       }
+
+       if (state.error) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, __location__ " Error during traversal\n"));
+               tdb1_transaction_cancel(tdb);
+               tdb1_close(tmp_db);
+               return -1;
+       }
+
+       if (tdb1_wipe_all(tdb) != 0) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, __location__ " Failed to wipe database\n"));
+               tdb1_transaction_cancel(tdb);
+               tdb1_close(tmp_db);
+               return -1;
+       }
+
+       state.error = false;
+       state.dest_db = tdb;
+
+       if (tdb1_traverse_read(tmp_db, repack_traverse, &state) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, __location__ " Failed to traverse copying back\n"));
+               tdb1_transaction_cancel(tdb);
+               tdb1_close(tmp_db);
+               return -1;
+       }
+
+       if (state.error) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, __location__ " Error during second traversal\n"));
+               tdb1_transaction_cancel(tdb);
+               tdb1_close(tmp_db);
+               return -1;
+       }
+
+       tdb1_close(tmp_db);
+
+       if (tdb1_transaction_commit(tdb) != 0) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, __location__ " Failed to commit\n"));
+               return -1;
+       }
+
+       return 0;
+}
+
+/* Even on files, we can get partial writes due to signals. */
+bool tdb1_write_all(int fd, const void *buf, size_t count)
+{
+       while (count) {
+               ssize_t ret;
+               ret = write(fd, buf, count);
+               if (ret < 0)
+                       return false;
+               buf = (const char *)buf + ret;
+               count -= ret;
+       }
+       return true;
+}
diff --git a/ccan/tdb2/tdb1_transaction.c b/ccan/tdb2/tdb1_transaction.c
new file mode 100644 (file)
index 0000000..6c4c6f7
--- /dev/null
@@ -0,0 +1,1271 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              2005
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb1_private.h"
+
+/*
+  transaction design:
+
+  - only allow a single transaction at a time per database. This makes
+    using the transaction API simpler, as otherwise the caller would
+    have to cope with temporary failures in transactions that conflict
+    with other current transactions
+
+  - keep the transaction recovery information in the same file as the
+    database, using a special 'transaction recovery' record pointed at
+    by the header. This removes the need for extra journal files as
+    used by some other databases
+
+  - dynamically allocated the transaction recover record, re-using it
+    for subsequent transactions. If a larger record is needed then
+    tdb1_free() the old record to place it on the normal tdb freelist
+    before allocating the new record
+
+  - during transactions, keep a linked list of writes all that have
+    been performed by intercepting all tdb1_write() calls. The hooked
+    transaction versions of tdb1_read() and tdb1_write() check this
+    linked list and try to use the elements of the list in preference
+    to the real database.
+
+  - don't allow any locks to be held when a transaction starts,
+    otherwise we can end up with deadlock (plus lack of lock nesting
+    in posix locks would mean the lock is lost)
+
+  - if the caller gains a lock during the transaction but doesn't
+    release it then fail the commit
+
+  - allow for nested calls to tdb1_transaction_start(), re-using the
+    existing transaction record. If the inner transaction is cancelled
+    then a subsequent commit will fail
+
+  - keep a mirrored copy of the tdb hash chain heads to allow for the
+    fast hash heads scan on traverse, updating the mirrored copy in
+    the transaction version of tdb1_write
+
+  - allow callers to mix transaction and non-transaction use of tdb,
+    although once a transaction is started then an exclusive lock is
+    gained until the transaction is committed or cancelled
+
+  - the commit stategy involves first saving away all modified data
+    into a linearised buffer in the transaction recovery area, then
+    marking the transaction recovery area with a magic value to
+    indicate a valid recovery record. In total 4 fsync/msync calls are
+    needed per commit to prevent race conditions. It might be possible
+    to reduce this to 3 or even 2 with some more work.
+
+  - check for a valid recovery record on open of the tdb, while the
+    open lock is held. Automatically recover from the transaction
+    recovery area if needed, then continue with the open as
+    usual. This allows for smooth crash recovery with no administrator
+    intervention.
+
+  - if TDB1_NOSYNC is passed to flags in tdb1_open then transactions are
+    still available, but no transaction recovery area is used and no
+    fsync/msync calls are made.
+
+  - if TDB1_ALLOW_NESTING is passed to flags in tdb open, or added using
+    tdb1_add_flags() transaction nesting is enabled.
+    It resets the TDB1_DISALLOW_NESTING flag, as both cannot be used together.
+    The default is that transaction nesting is allowed.
+    Note: this default may change in future versions of tdb.
+
+    Beware. when transactions are nested a transaction successfully
+    completed with tdb1_transaction_commit() can be silently unrolled later.
+
+  - if TDB1_DISALLOW_NESTING is passed to flags in tdb open, or added using
+    tdb1_add_flags() transaction nesting is disabled.
+    It resets the TDB1_ALLOW_NESTING flag, as both cannot be used together.
+    An attempt create a nested transaction will fail with TDB1_ERR_NESTING.
+    The default is that transaction nesting is allowed.
+    Note: this default may change in future versions of tdb.
+*/
+
+
+/*
+  hold the context of any current transaction
+*/
+struct tdb1_transaction {
+       /* we keep a mirrored copy of the tdb hash heads here so
+          tdb1_next_hash_chain() can operate efficiently */
+       uint32_t *hash_heads;
+
+       /* the original io methods - used to do IOs to the real db */
+       const struct tdb1_methods *io_methods;
+
+       /* the list of transaction blocks. When a block is first
+          written to, it gets created in this list */
+       uint8_t **blocks;
+       uint32_t num_blocks;
+       uint32_t block_size;      /* bytes in each block */
+       uint32_t last_block_size; /* number of valid bytes in the last block */
+
+       /* non-zero when an internal transaction error has
+          occurred. All write operations will then fail until the
+          transaction is ended */
+       int transaction_error;
+
+       /* when inside a transaction we need to keep track of any
+          nested tdb1_transaction_start() calls, as these are allowed,
+          but don't create a new transaction */
+       int nesting;
+
+       /* set when a prepare has already occurred */
+       bool prepared;
+       tdb1_off_t magic_offset;
+
+       /* old file size before transaction */
+       tdb1_len_t old_map_size;
+
+       /* did we expand in this transaction */
+       bool expanded;
+};
+
+
+/*
+  read while in a transaction. We need to check first if the data is in our list
+  of transaction elements, then if not do a real read
+*/
+static int transaction1_read(struct tdb1_context *tdb, tdb1_off_t off, void *buf,
+                            tdb1_len_t len, int cv)
+{
+       uint32_t blk;
+
+       /* break it down into block sized ops */
+       while (len + (off % tdb->transaction->block_size) > tdb->transaction->block_size) {
+               tdb1_len_t len2 = tdb->transaction->block_size - (off % tdb->transaction->block_size);
+               if (transaction1_read(tdb, off, buf, len2, cv) != 0) {
+                       return -1;
+               }
+               len -= len2;
+               off += len2;
+               buf = (void *)(len2 + (char *)buf);
+       }
+
+       if (len == 0) {
+               return 0;
+       }
+
+       blk = off / tdb->transaction->block_size;
+
+       /* see if we have it in the block list */
+       if (tdb->transaction->num_blocks <= blk ||
+           tdb->transaction->blocks[blk] == NULL) {
+               /* nope, do a real read */
+               if (tdb->transaction->io_methods->tdb1_read(tdb, off, buf, len, cv) != 0) {
+                       goto fail;
+               }
+               return 0;
+       }
+
+       /* it is in the block list. Now check for the last block */
+       if (blk == tdb->transaction->num_blocks-1) {
+               if (len > tdb->transaction->last_block_size) {
+                       goto fail;
+               }
+       }
+
+       /* now copy it out of this block */
+       memcpy(buf, tdb->transaction->blocks[blk] + (off % tdb->transaction->block_size), len);
+       if (cv) {
+               tdb1_convert(buf, len);
+       }
+       return 0;
+
+fail:
+       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "transaction_read: failed at off=%d len=%d\n", off, len));
+       tdb->ecode = TDB1_ERR_IO;
+       tdb->transaction->transaction_error = 1;
+       return -1;
+}
+
+
+/*
+  write while in a transaction
+*/
+static int transaction1_write(struct tdb1_context *tdb, tdb1_off_t off,
+                            const void *buf, tdb1_len_t len)
+{
+       uint32_t blk;
+
+       /* Only a commit is allowed on a prepared transaction */
+       if (tdb->transaction->prepared) {
+               tdb->ecode = TDB1_ERR_EINVAL;
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "transaction_write: transaction already prepared, write not allowed\n"));
+               tdb->transaction->transaction_error = 1;
+               return -1;
+       }
+
+       /* if the write is to a hash head, then update the transaction
+          hash heads */
+       if (len == sizeof(tdb1_off_t) && off >= TDB1_FREELIST_TOP &&
+           off < TDB1_FREELIST_TOP+TDB1_HASHTABLE_SIZE(tdb)) {
+               uint32_t chain = (off-TDB1_FREELIST_TOP) / sizeof(tdb1_off_t);
+               memcpy(&tdb->transaction->hash_heads[chain], buf, len);
+       }
+
+       /* break it up into block sized chunks */
+       while (len + (off % tdb->transaction->block_size) > tdb->transaction->block_size) {
+               tdb1_len_t len2 = tdb->transaction->block_size - (off % tdb->transaction->block_size);
+               if (transaction1_write(tdb, off, buf, len2) != 0) {
+                       return -1;
+               }
+               len -= len2;
+               off += len2;
+               if (buf != NULL) {
+                       buf = (const void *)(len2 + (const char *)buf);
+               }
+       }
+
+       if (len == 0) {
+               return 0;
+       }
+
+       blk = off / tdb->transaction->block_size;
+       off = off % tdb->transaction->block_size;
+
+       if (tdb->transaction->num_blocks <= blk) {
+               uint8_t **new_blocks;
+               /* expand the blocks array */
+               if (tdb->transaction->blocks == NULL) {
+                       new_blocks = (uint8_t **)malloc(
+                               (blk+1)*sizeof(uint8_t *));
+               } else {
+                       new_blocks = (uint8_t **)realloc(
+                               tdb->transaction->blocks,
+                               (blk+1)*sizeof(uint8_t *));
+               }
+               if (new_blocks == NULL) {
+                       tdb->ecode = TDB1_ERR_OOM;
+                       goto fail;
+               }
+               memset(&new_blocks[tdb->transaction->num_blocks], 0,
+                      (1+(blk - tdb->transaction->num_blocks))*sizeof(uint8_t *));
+               tdb->transaction->blocks = new_blocks;
+               tdb->transaction->num_blocks = blk+1;
+               tdb->transaction->last_block_size = 0;
+       }
+
+       /* allocate and fill a block? */
+       if (tdb->transaction->blocks[blk] == NULL) {
+               tdb->transaction->blocks[blk] = (uint8_t *)calloc(tdb->transaction->block_size, 1);
+               if (tdb->transaction->blocks[blk] == NULL) {
+                       tdb->ecode = TDB1_ERR_OOM;
+                       tdb->transaction->transaction_error = 1;
+                       return -1;
+               }
+               if (tdb->transaction->old_map_size > blk * tdb->transaction->block_size) {
+                       tdb1_len_t len2 = tdb->transaction->block_size;
+                       if (len2 + (blk * tdb->transaction->block_size) > tdb->transaction->old_map_size) {
+                               len2 = tdb->transaction->old_map_size - (blk * tdb->transaction->block_size);
+                       }
+                       if (tdb->transaction->io_methods->tdb1_read(tdb, blk * tdb->transaction->block_size,
+                                                                  tdb->transaction->blocks[blk],
+                                                                  len2, 0) != 0) {
+                               SAFE_FREE(tdb->transaction->blocks[blk]);
+                               tdb->ecode = TDB1_ERR_IO;
+                               goto fail;
+                       }
+                       if (blk == tdb->transaction->num_blocks-1) {
+                               tdb->transaction->last_block_size = len2;
+                       }
+               }
+       }
+
+       /* overwrite part of an existing block */
+       if (buf == NULL) {
+               memset(tdb->transaction->blocks[blk] + off, 0, len);
+       } else {
+               memcpy(tdb->transaction->blocks[blk] + off, buf, len);
+       }
+       if (blk == tdb->transaction->num_blocks-1) {
+               if (len + off > tdb->transaction->last_block_size) {
+                       tdb->transaction->last_block_size = len + off;
+               }
+       }
+
+       return 0;
+
+fail:
+       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "transaction_write: failed at off=%d len=%d\n",
+                (blk*tdb->transaction->block_size) + off, len));
+       tdb->transaction->transaction_error = 1;
+       return -1;
+}
+
+
+/*
+  write while in a transaction - this varient never expands the transaction blocks, it only
+  updates existing blocks. This means it cannot change the recovery size
+*/
+static int transaction1_write_existing(struct tdb1_context *tdb, tdb1_off_t off,
+                                     const void *buf, tdb1_len_t len)
+{
+       uint32_t blk;
+
+       /* break it up into block sized chunks */
+       while (len + (off % tdb->transaction->block_size) > tdb->transaction->block_size) {
+               tdb1_len_t len2 = tdb->transaction->block_size - (off % tdb->transaction->block_size);
+               if (transaction1_write_existing(tdb, off, buf, len2) != 0) {
+                       return -1;
+               }
+               len -= len2;
+               off += len2;
+               if (buf != NULL) {
+                       buf = (const void *)(len2 + (const char *)buf);
+               }
+       }
+
+       if (len == 0) {
+               return 0;
+       }
+
+       blk = off / tdb->transaction->block_size;
+       off = off % tdb->transaction->block_size;
+
+       if (tdb->transaction->num_blocks <= blk ||
+           tdb->transaction->blocks[blk] == NULL) {
+               return 0;
+       }
+
+       if (blk == tdb->transaction->num_blocks-1 &&
+           off + len > tdb->transaction->last_block_size) {
+               if (off >= tdb->transaction->last_block_size) {
+                       return 0;
+               }
+               len = tdb->transaction->last_block_size - off;
+       }
+
+       /* overwrite part of an existing block */
+       memcpy(tdb->transaction->blocks[blk] + off, buf, len);
+
+       return 0;
+}
+
+
+/*
+  accelerated hash chain head search, using the cached hash heads
+*/
+static void transaction1_next_hash_chain(struct tdb1_context *tdb, uint32_t *chain)
+{
+       uint32_t h = *chain;
+       for (;h < tdb->header.hash_size;h++) {
+               /* the +1 takes account of the freelist */
+               if (0 != tdb->transaction->hash_heads[h+1]) {
+                       break;
+               }
+       }
+       (*chain) = h;
+}
+
+/*
+  out of bounds check during a transaction
+*/
+static int transaction1_oob(struct tdb1_context *tdb, tdb1_off_t len, int probe)
+{
+       if (len <= tdb->map_size) {
+               return 0;
+       }
+       tdb->ecode = TDB1_ERR_IO;
+       return -1;
+}
+
+/*
+  transaction version of tdb1_expand().
+*/
+static int transaction1_expand_file(struct tdb1_context *tdb, tdb1_off_t size,
+                                   tdb1_off_t addition)
+{
+       /* add a write to the transaction elements, so subsequent
+          reads see the zero data */
+       if (transaction1_write(tdb, size, NULL, addition) != 0) {
+               return -1;
+       }
+
+       tdb->transaction->expanded = true;
+
+       return 0;
+}
+
+static const struct tdb1_methods transaction1_methods = {
+       transaction1_read,
+       transaction1_write,
+       transaction1_next_hash_chain,
+       transaction1_oob,
+       transaction1_expand_file,
+};
+
+
+/*
+  start a tdb transaction. No token is returned, as only a single
+  transaction is allowed to be pending per tdb1_context
+*/
+static int _tdb1_transaction_start(struct tdb1_context *tdb,
+                                 enum tdb1_lock_flags lockflags)
+{
+       /* some sanity checks */
+       if (tdb->read_only || (tdb->flags & TDB1_INTERNAL) || tdb->traverse_read) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_start: cannot start a transaction on a read-only or internal db\n"));
+               tdb->ecode = TDB1_ERR_EINVAL;
+               return -1;
+       }
+
+       /* cope with nested tdb1_transaction_start() calls */
+       if (tdb->transaction != NULL) {
+               if (!(tdb->flags & TDB1_ALLOW_NESTING)) {
+                       tdb->ecode = TDB1_ERR_NESTING;
+                       return -1;
+               }
+               tdb->transaction->nesting++;
+               TDB1_LOG((tdb, TDB1_DEBUG_TRACE, "tdb1_transaction_start: nesting %d\n",
+                        tdb->transaction->nesting));
+               return 0;
+       }
+
+       if (tdb1_have_extra_locks(tdb)) {
+               /* the caller must not have any locks when starting a
+                  transaction as otherwise we'll be screwed by lack
+                  of nested locks in posix */
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_start: cannot start a transaction with locks held\n"));
+               tdb->ecode = TDB1_ERR_LOCK;
+               return -1;
+       }
+
+       if (tdb->travlocks.next != NULL) {
+               /* you cannot use transactions inside a traverse (although you can use
+                  traverse inside a transaction) as otherwise you can end up with
+                  deadlock */
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_start: cannot start a transaction within a traverse\n"));
+               tdb->ecode = TDB1_ERR_LOCK;
+               return -1;
+       }
+
+       tdb->transaction = (struct tdb1_transaction *)
+               calloc(sizeof(struct tdb1_transaction), 1);
+       if (tdb->transaction == NULL) {
+               tdb->ecode = TDB1_ERR_OOM;
+               return -1;
+       }
+
+       /* a page at a time seems like a reasonable compromise between compactness and efficiency */
+       tdb->transaction->block_size = tdb->page_size;
+
+       /* get the transaction write lock. This is a blocking lock. As
+          discussed with Volker, there are a number of ways we could
+          make this async, which we will probably do in the future */
+       if (tdb1_transaction_lock(tdb, F_WRLCK, lockflags) == -1) {
+               SAFE_FREE(tdb->transaction->blocks);
+               SAFE_FREE(tdb->transaction);
+               if ((lockflags & TDB1_LOCK_WAIT) == 0) {
+                       tdb->ecode = TDB1_ERR_NOLOCK;
+               }
+               return -1;
+       }
+
+       /* get a read lock from the freelist to the end of file. This
+          is upgraded to a write lock during the commit */
+       if (tdb1_allrecord_lock(tdb, F_RDLCK, TDB1_LOCK_WAIT, true) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_start: failed to get hash locks\n"));
+               goto fail_allrecord_lock;
+       }
+
+       /* setup a copy of the hash table heads so the hash scan in
+          traverse can be fast */
+       tdb->transaction->hash_heads = (uint32_t *)
+               calloc(tdb->header.hash_size+1, sizeof(uint32_t));
+       if (tdb->transaction->hash_heads == NULL) {
+               tdb->ecode = TDB1_ERR_OOM;
+               goto fail;
+       }
+       if (tdb->methods->tdb1_read(tdb, TDB1_FREELIST_TOP, tdb->transaction->hash_heads,
+                                  TDB1_HASHTABLE_SIZE(tdb), 0) != 0) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_start: failed to read hash heads\n"));
+               tdb->ecode = TDB1_ERR_IO;
+               goto fail;
+       }
+
+       /* make sure we know about any file expansions already done by
+          anyone else */
+       tdb->methods->tdb1_oob(tdb, tdb->map_size + 1, 1);
+       tdb->transaction->old_map_size = tdb->map_size;
+
+       /* finally hook the io methods, replacing them with
+          transaction specific methods */
+       tdb->transaction->io_methods = tdb->methods;
+       tdb->methods = &transaction1_methods;
+
+       return 0;
+
+fail:
+       tdb1_allrecord_unlock(tdb, F_RDLCK, false);
+fail_allrecord_lock:
+       tdb1_transaction_unlock(tdb, F_WRLCK);
+       SAFE_FREE(tdb->transaction->blocks);
+       SAFE_FREE(tdb->transaction->hash_heads);
+       SAFE_FREE(tdb->transaction);
+       return -1;
+}
+
+_PUBLIC_ int tdb1_transaction_start(struct tdb1_context *tdb)
+{
+       return _tdb1_transaction_start(tdb, TDB1_LOCK_WAIT);
+}
+
+_PUBLIC_ int tdb1_transaction_start_nonblock(struct tdb1_context *tdb)
+{
+       return _tdb1_transaction_start(tdb, TDB1_LOCK_NOWAIT|TDB1_LOCK_PROBE);
+}
+
+/*
+  sync to disk
+*/
+static int transaction1_sync(struct tdb1_context *tdb, tdb1_off_t offset, tdb1_len_t length)
+{
+       if (tdb->flags & TDB1_NOSYNC) {
+               return 0;
+       }
+
+#if HAVE_FDATASYNC
+       if (fdatasync(tdb->fd) != 0) {
+#else
+       if (fsync(tdb->fd) != 0) {
+#endif
+               tdb->ecode = TDB1_ERR_IO;
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction: fsync failed\n"));
+               return -1;
+       }
+#if HAVE_MMAP
+       if (tdb->map_ptr) {
+               tdb1_off_t moffset = offset & ~(tdb->page_size-1);
+               if (msync(moffset + (char *)tdb->map_ptr,
+                         length + (offset - moffset), MS_SYNC) != 0) {
+                       tdb->ecode = TDB1_ERR_IO;
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction: msync failed - %s\n",
+                                strerror(errno)));
+                       return -1;
+               }
+       }
+#endif
+       return 0;
+}
+
+
+static int _tdb1_transaction_cancel(struct tdb1_context *tdb)
+{
+       int i, ret = 0;
+
+       if (tdb->transaction == NULL) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_cancel: no transaction\n"));
+               return -1;
+       }
+
+       if (tdb->transaction->nesting != 0) {
+               tdb->transaction->transaction_error = 1;
+               tdb->transaction->nesting--;
+               return 0;
+       }
+
+       tdb->map_size = tdb->transaction->old_map_size;
+
+       /* free all the transaction blocks */
+       for (i=0;i<tdb->transaction->num_blocks;i++) {
+               if (tdb->transaction->blocks[i] != NULL) {
+                       free(tdb->transaction->blocks[i]);
+               }
+       }
+       SAFE_FREE(tdb->transaction->blocks);
+
+       if (tdb->transaction->magic_offset) {
+               const struct tdb1_methods *methods = tdb->transaction->io_methods;
+               const uint32_t invalid = TDB1_RECOVERY_INVALID_MAGIC;
+
+               /* remove the recovery marker */
+               if (methods->tdb1_write(tdb, tdb->transaction->magic_offset, &invalid, 4) == -1 ||
+               transaction1_sync(tdb, tdb->transaction->magic_offset, 4) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_cancel: failed to remove recovery magic\n"));
+                       ret = -1;
+               }
+       }
+
+       /* This also removes the OPEN_LOCK, if we have it. */
+       tdb1_release_transaction_locks(tdb);
+
+       /* restore the normal io methods */
+       tdb->methods = tdb->transaction->io_methods;
+
+       SAFE_FREE(tdb->transaction->hash_heads);
+       SAFE_FREE(tdb->transaction);
+
+       return ret;
+}
+
+/*
+  cancel the current transaction
+*/
+_PUBLIC_ int tdb1_transaction_cancel(struct tdb1_context *tdb)
+{
+       return _tdb1_transaction_cancel(tdb);
+}
+
+/*
+  work out how much space the linearised recovery data will consume
+*/
+static tdb1_len_t tdb1_recovery_size(struct tdb1_context *tdb)
+{
+       tdb1_len_t recovery_size = 0;
+       int i;
+
+       recovery_size = sizeof(uint32_t);
+       for (i=0;i<tdb->transaction->num_blocks;i++) {
+               if (i * tdb->transaction->block_size >= tdb->transaction->old_map_size) {
+                       break;
+               }
+               if (tdb->transaction->blocks[i] == NULL) {
+                       continue;
+               }
+               recovery_size += 2*sizeof(tdb1_off_t);
+               if (i == tdb->transaction->num_blocks-1) {
+                       recovery_size += tdb->transaction->last_block_size;
+               } else {
+                       recovery_size += tdb->transaction->block_size;
+               }
+       }
+
+       return recovery_size;
+}
+
+int tdb1_recovery_area(struct tdb1_context *tdb,
+                     const struct tdb1_methods *methods,
+                     tdb1_off_t *recovery_offset,
+                     struct tdb1_record *rec)
+{
+       if (tdb1_ofs_read(tdb, TDB1_RECOVERY_HEAD, recovery_offset) == -1) {
+               return -1;
+       }
+
+       if (*recovery_offset == 0) {
+               rec->rec_len = 0;
+               return 0;
+       }
+
+       if (methods->tdb1_read(tdb, *recovery_offset, rec, sizeof(*rec),
+                             TDB1_DOCONV()) == -1) {
+               return -1;
+       }
+
+       /* ignore invalid recovery regions: can happen in crash */
+       if (rec->magic != TDB1_RECOVERY_MAGIC &&
+           rec->magic != TDB1_RECOVERY_INVALID_MAGIC) {
+               *recovery_offset = 0;
+               rec->rec_len = 0;
+       }
+       return 0;
+}
+
+/*
+  allocate the recovery area, or use an existing recovery area if it is
+  large enough
+*/
+static int tdb1_recovery_allocate(struct tdb1_context *tdb,
+                                tdb1_len_t *recovery_size,
+                                tdb1_off_t *recovery_offset,
+                                tdb1_len_t *recovery_max_size)
+{
+       struct tdb1_record rec;
+       const struct tdb1_methods *methods = tdb->transaction->io_methods;
+       tdb1_off_t recovery_head;
+
+       if (tdb1_recovery_area(tdb, methods, &recovery_head, &rec) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_recovery_allocate: failed to read recovery head\n"));
+               return -1;
+       }
+
+       *recovery_size = tdb1_recovery_size(tdb);
+
+       if (recovery_head != 0 && *recovery_size <= rec.rec_len) {
+               /* it fits in the existing area */
+               *recovery_max_size = rec.rec_len;
+               *recovery_offset = recovery_head;
+               return 0;
+       }
+
+       /* we need to free up the old recovery area, then allocate a
+          new one at the end of the file. Note that we cannot use
+          tdb1_allocate() to allocate the new one as that might return
+          us an area that is being currently used (as of the start of
+          the transaction) */
+       if (recovery_head != 0) {
+               if (tdb1_free(tdb, recovery_head, &rec) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_recovery_allocate: failed to free previous recovery area\n"));
+                       return -1;
+               }
+       }
+
+       /* the tdb1_free() call might have increased the recovery size */
+       *recovery_size = tdb1_recovery_size(tdb);
+
+       /* round up to a multiple of page size */
+       *recovery_max_size = TDB1_ALIGN(sizeof(rec) + *recovery_size, tdb->page_size) - sizeof(rec);
+       *recovery_offset = tdb->map_size;
+       recovery_head = *recovery_offset;
+
+       if (methods->tdb1_expand_file(tdb, tdb->transaction->old_map_size,
+                                    (tdb->map_size - tdb->transaction->old_map_size) +
+                                    sizeof(rec) + *recovery_max_size) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_recovery_allocate: failed to create recovery area\n"));
+               return -1;
+       }
+
+       /* remap the file (if using mmap) */
+       methods->tdb1_oob(tdb, tdb->map_size + 1, 1);
+
+       /* we have to reset the old map size so that we don't try to expand the file
+          again in the transaction commit, which would destroy the recovery area */
+       tdb->transaction->old_map_size = tdb->map_size;
+
+       /* write the recovery header offset and sync - we can sync without a race here
+          as the magic ptr in the recovery record has not been set */
+       TDB1_CONV(recovery_head);
+       if (methods->tdb1_write(tdb, TDB1_RECOVERY_HEAD,
+                              &recovery_head, sizeof(tdb1_off_t)) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_recovery_allocate: failed to write recovery head\n"));
+               return -1;
+       }
+       if (transaction1_write_existing(tdb, TDB1_RECOVERY_HEAD, &recovery_head, sizeof(tdb1_off_t)) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_recovery_allocate: failed to write recovery head\n"));
+               return -1;
+       }
+
+       return 0;
+}
+
+
+/*
+  setup the recovery data that will be used on a crash during commit
+*/
+static int transaction1_setup_recovery(struct tdb1_context *tdb,
+                                      tdb1_off_t *magic_offset)
+{
+       tdb1_len_t recovery_size;
+       unsigned char *data, *p;
+       const struct tdb1_methods *methods = tdb->transaction->io_methods;
+       struct tdb1_record *rec;
+       tdb1_off_t recovery_offset, recovery_max_size;
+       tdb1_off_t old_map_size = tdb->transaction->old_map_size;
+       uint32_t magic, tailer;
+       int i;
+
+       /*
+         check that the recovery area has enough space
+       */
+       if (tdb1_recovery_allocate(tdb, &recovery_size,
+                                 &recovery_offset, &recovery_max_size) == -1) {
+               return -1;
+       }
+
+       data = (unsigned char *)malloc(recovery_size + sizeof(*rec));
+       if (data == NULL) {
+               tdb->ecode = TDB1_ERR_OOM;
+               return -1;
+       }
+
+       rec = (struct tdb1_record *)data;
+       memset(rec, 0, sizeof(*rec));
+
+       rec->magic    = TDB1_RECOVERY_INVALID_MAGIC;
+       rec->data_len = recovery_size;
+       rec->rec_len  = recovery_max_size;
+       rec->key_len  = old_map_size;
+       TDB1_CONV(*rec);
+
+       /* build the recovery data into a single blob to allow us to do a single
+          large write, which should be more efficient */
+       p = data + sizeof(*rec);
+       for (i=0;i<tdb->transaction->num_blocks;i++) {
+               tdb1_off_t offset;
+               tdb1_len_t length;
+
+               if (tdb->transaction->blocks[i] == NULL) {
+                       continue;
+               }
+
+               offset = i * tdb->transaction->block_size;
+               length = tdb->transaction->block_size;
+               if (i == tdb->transaction->num_blocks-1) {
+                       length = tdb->transaction->last_block_size;
+               }
+
+               if (offset >= old_map_size) {
+                       continue;
+               }
+               if (offset + length > tdb->transaction->old_map_size) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_setup_recovery: transaction data over new region boundary\n"));
+                       free(data);
+                       tdb->ecode = TDB1_ERR_CORRUPT;
+                       return -1;
+               }
+               memcpy(p, &offset, 4);
+               memcpy(p+4, &length, 4);
+               if (TDB1_DOCONV()) {
+                       tdb1_convert(p, 8);
+               }
+               /* the recovery area contains the old data, not the
+                  new data, so we have to call the original tdb1_read
+                  method to get it */
+               if (methods->tdb1_read(tdb, offset, p + 8, length, 0) != 0) {
+                       free(data);
+                       tdb->ecode = TDB1_ERR_IO;
+                       return -1;
+               }
+               p += 8 + length;
+       }
+
+       /* and the tailer */
+       tailer = sizeof(*rec) + recovery_max_size;
+       memcpy(p, &tailer, 4);
+       if (TDB1_DOCONV()) {
+               tdb1_convert(p, 4);
+       }
+
+       /* write the recovery data to the recovery area */
+       if (methods->tdb1_write(tdb, recovery_offset, data, sizeof(*rec) + recovery_size) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_setup_recovery: failed to write recovery data\n"));
+               free(data);
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+       if (transaction1_write_existing(tdb, recovery_offset, data, sizeof(*rec) + recovery_size) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_setup_recovery: failed to write secondary recovery data\n"));
+               free(data);
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+
+       /* as we don't have ordered writes, we have to sync the recovery
+          data before we update the magic to indicate that the recovery
+          data is present */
+       if (transaction1_sync(tdb, recovery_offset, sizeof(*rec) + recovery_size) == -1) {
+               free(data);
+               return -1;
+       }
+
+       free(data);
+
+       magic = TDB1_RECOVERY_MAGIC;
+       TDB1_CONV(magic);
+
+       *magic_offset = recovery_offset + offsetof(struct tdb1_record, magic);
+
+       if (methods->tdb1_write(tdb, *magic_offset, &magic, sizeof(magic)) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_setup_recovery: failed to write recovery magic\n"));
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+       if (transaction1_write_existing(tdb, *magic_offset, &magic, sizeof(magic)) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_setup_recovery: failed to write secondary recovery magic\n"));
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+
+       /* ensure the recovery magic marker is on disk */
+       if (transaction1_sync(tdb, *magic_offset, sizeof(magic)) == -1) {
+               return -1;
+       }
+
+       return 0;
+}
+
+static int _tdb1_transaction_prepare_commit(struct tdb1_context *tdb)
+{
+       const struct tdb1_methods *methods;
+
+       if (tdb->transaction == NULL) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_prepare_commit: no transaction\n"));
+               return -1;
+       }
+
+       if (tdb->transaction->prepared) {
+               tdb->ecode = TDB1_ERR_EINVAL;
+               _tdb1_transaction_cancel(tdb);
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_prepare_commit: transaction already prepared\n"));
+               return -1;
+       }
+
+       if (tdb->transaction->transaction_error) {
+               tdb->ecode = TDB1_ERR_IO;
+               _tdb1_transaction_cancel(tdb);
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_prepare_commit: transaction error pending\n"));
+               return -1;
+       }
+
+
+       if (tdb->transaction->nesting != 0) {
+               return 0;
+       }
+
+       /* check for a null transaction */
+       if (tdb->transaction->blocks == NULL) {
+               return 0;
+       }
+
+       methods = tdb->transaction->io_methods;
+
+       /* if there are any locks pending then the caller has not
+          nested their locks properly, so fail the transaction */
+       if (tdb1_have_extra_locks(tdb)) {
+               tdb->ecode = TDB1_ERR_LOCK;
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_prepare_commit: locks pending on commit\n"));
+               _tdb1_transaction_cancel(tdb);
+               return -1;
+       }
+
+       /* upgrade the main transaction lock region to a write lock */
+       if (tdb1_allrecord_upgrade(tdb) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_prepare_commit: failed to upgrade hash locks\n"));
+               _tdb1_transaction_cancel(tdb);
+               return -1;
+       }
+
+       /* get the open lock - this prevents new users attaching to the database
+          during the commit */
+       if (tdb1_nest_lock(tdb, TDB1_OPEN_LOCK, F_WRLCK, TDB1_LOCK_WAIT) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_prepare_commit: failed to get open lock\n"));
+               _tdb1_transaction_cancel(tdb);
+               return -1;
+       }
+
+       if (!(tdb->flags & TDB1_NOSYNC)) {
+               /* write the recovery data to the end of the file */
+               if (transaction1_setup_recovery(tdb, &tdb->transaction->magic_offset) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_prepare_commit: failed to setup recovery data\n"));
+                       _tdb1_transaction_cancel(tdb);
+                       return -1;
+               }
+       }
+
+       tdb->transaction->prepared = true;
+
+       /* expand the file to the new size if needed */
+       if (tdb->map_size != tdb->transaction->old_map_size) {
+               if (methods->tdb1_expand_file(tdb, tdb->transaction->old_map_size,
+                                            tdb->map_size -
+                                            tdb->transaction->old_map_size) == -1) {
+                       tdb->ecode = TDB1_ERR_IO;
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_prepare_commit: expansion failed\n"));
+                       _tdb1_transaction_cancel(tdb);
+                       return -1;
+               }
+               tdb->map_size = tdb->transaction->old_map_size;
+               methods->tdb1_oob(tdb, tdb->map_size + 1, 1);
+       }
+
+       /* Keep the open lock until the actual commit */
+
+       return 0;
+}
+
+/*
+   prepare to commit the current transaction
+*/
+_PUBLIC_ int tdb1_transaction_prepare_commit(struct tdb1_context *tdb)
+{
+       return _tdb1_transaction_prepare_commit(tdb);
+}
+
+/* A repack is worthwhile if the largest is less than half total free. */
+static bool repack_worthwhile(struct tdb1_context *tdb)
+{
+       tdb1_off_t ptr;
+       struct tdb1_record rec;
+       tdb1_len_t total = 0, largest = 0;
+
+       if (tdb1_ofs_read(tdb, TDB1_FREELIST_TOP, &ptr) == -1) {
+               return false;
+       }
+
+       while (ptr != 0 && tdb1_rec_free_read(tdb, ptr, &rec) == 0) {
+               total += rec.rec_len;
+               if (rec.rec_len > largest) {
+                       largest = rec.rec_len;
+               }
+               ptr = rec.next;
+       }
+
+       return total > largest * 2;
+}
+
+/*
+  commit the current transaction
+*/
+_PUBLIC_ int tdb1_transaction_commit(struct tdb1_context *tdb)
+{
+       const struct tdb1_methods *methods;
+       int i;
+       bool need_repack = false;
+
+       if (tdb->transaction == NULL) {
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_commit: no transaction\n"));
+               return -1;
+       }
+
+       if (tdb->transaction->transaction_error) {
+               tdb->ecode = TDB1_ERR_IO;
+               _tdb1_transaction_cancel(tdb);
+               TDB1_LOG((tdb, TDB1_DEBUG_ERROR, "tdb1_transaction_commit: transaction error pending\n"));
+               return -1;
+       }
+
+
+       if (tdb->transaction->nesting != 0) {
+               tdb->transaction->nesting--;
+               return 0;
+       }
+
+       /* check for a null transaction */
+       if (tdb->transaction->blocks == NULL) {
+               _tdb1_transaction_cancel(tdb);
+               return 0;
+       }
+
+       if (!tdb->transaction->prepared) {
+               int ret = _tdb1_transaction_prepare_commit(tdb);
+               if (ret)
+                       return ret;
+       }
+
+       methods = tdb->transaction->io_methods;
+
+       /* perform all the writes */
+       for (i=0;i<tdb->transaction->num_blocks;i++) {
+               tdb1_off_t offset;
+               tdb1_len_t length;
+
+               if (tdb->transaction->blocks[i] == NULL) {
+                       continue;
+               }
+
+               offset = i * tdb->transaction->block_size;
+               length = tdb->transaction->block_size;
+               if (i == tdb->transaction->num_blocks-1) {
+                       length = tdb->transaction->last_block_size;
+               }
+
+               if (methods->tdb1_write(tdb, offset, tdb->transaction->blocks[i], length) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_commit: write failed during commit\n"));
+
+                       /* we've overwritten part of the data and
+                          possibly expanded the file, so we need to
+                          run the crash recovery code */
+                       tdb->methods = methods;
+                       tdb1_transaction_recover(tdb);
+
+                       _tdb1_transaction_cancel(tdb);
+
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_commit: write failed\n"));
+                       return -1;
+               }
+               SAFE_FREE(tdb->transaction->blocks[i]);
+       }
+
+       /* Do this before we drop lock or blocks. */
+       if (tdb->transaction->expanded) {
+               need_repack = repack_worthwhile(tdb);
+       }
+
+       SAFE_FREE(tdb->transaction->blocks);
+       tdb->transaction->num_blocks = 0;
+
+       /* ensure the new data is on disk */
+       if (transaction1_sync(tdb, 0, tdb->map_size) == -1) {
+               return -1;
+       }
+
+       /*
+         TODO: maybe write to some dummy hdr field, or write to magic
+         offset without mmap, before the last sync, instead of the
+         utime() call
+       */
+
+       /* on some systems (like Linux 2.6.x) changes via mmap/msync
+          don't change the mtime of the file, this means the file may
+          not be backed up (as tdb rounding to block sizes means that
+          file size changes are quite rare too). The following forces
+          mtime changes when a transaction completes */
+#if HAVE_UTIME
+       utime(tdb->name, NULL);
+#endif
+
+       /* use a transaction cancel to free memory and remove the
+          transaction locks */
+       _tdb1_transaction_cancel(tdb);
+
+       if (need_repack) {
+               return tdb1_repack(tdb);
+       }
+
+       return 0;
+}
+
+
+/*
+  recover from an aborted transaction. Must be called with exclusive
+  database write access already established (including the open
+  lock to prevent new processes attaching)
+*/
+int tdb1_transaction_recover(struct tdb1_context *tdb)
+{
+       tdb1_off_t recovery_head, recovery_eof;
+       unsigned char *data, *p;
+       uint32_t zero = 0;
+       struct tdb1_record rec;
+
+       /* find the recovery area */
+       if (tdb1_ofs_read(tdb, TDB1_RECOVERY_HEAD, &recovery_head) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_recover: failed to read recovery head\n"));
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+
+       if (recovery_head == 0) {
+               /* we have never allocated a recovery record */
+               return 0;
+       }
+
+       /* read the recovery record */
+       if (tdb->methods->tdb1_read(tdb, recovery_head, &rec,
+                                  sizeof(rec), TDB1_DOCONV()) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_recover: failed to read recovery record\n"));
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+
+       if (rec.magic != TDB1_RECOVERY_MAGIC) {
+               /* there is no valid recovery data */
+               return 0;
+       }
+
+       if (tdb->read_only) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_recover: attempt to recover read only database\n"));
+               tdb->ecode = TDB1_ERR_CORRUPT;
+               return -1;
+       }
+
+       recovery_eof = rec.key_len;
+
+       data = (unsigned char *)malloc(rec.data_len);
+       if (data == NULL) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_recover: failed to allocate recovery data\n"));
+               tdb->ecode = TDB1_ERR_OOM;
+               return -1;
+       }
+
+       /* read the full recovery data */
+       if (tdb->methods->tdb1_read(tdb, recovery_head + sizeof(rec), data,
+                                  rec.data_len, 0) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_recover: failed to read recovery data\n"));
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+
+       /* recover the file data */
+       p = data;
+       while (p+8 < data + rec.data_len) {
+               uint32_t ofs, len;
+               if (TDB1_DOCONV()) {
+                       tdb1_convert(p, 8);
+               }
+               memcpy(&ofs, p, 4);
+               memcpy(&len, p+4, 4);
+
+               if (tdb->methods->tdb1_write(tdb, ofs, p+8, len) == -1) {
+                       free(data);
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_recover: failed to recover %d bytes at offset %d\n", len, ofs));
+                       tdb->ecode = TDB1_ERR_IO;
+                       return -1;
+               }
+               p += 8 + len;
+       }
+
+       free(data);
+
+       if (transaction1_sync(tdb, 0, tdb->map_size) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_recover: failed to sync recovery\n"));
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+
+       /* if the recovery area is after the recovered eof then remove it */
+       if (recovery_eof <= recovery_head) {
+               if (tdb1_ofs_write(tdb, TDB1_RECOVERY_HEAD, &zero) == -1) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_recover: failed to remove recovery head\n"));
+                       tdb->ecode = TDB1_ERR_IO;
+                       return -1;
+               }
+       }
+
+       /* remove the recovery magic */
+       if (tdb1_ofs_write(tdb, recovery_head + offsetof(struct tdb1_record, magic),
+                         &zero) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_recover: failed to remove recovery magic\n"));
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+
+       if (transaction1_sync(tdb, 0, recovery_eof) == -1) {
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_transaction_recover: failed to sync2 recovery\n"));
+               tdb->ecode = TDB1_ERR_IO;
+               return -1;
+       }
+
+       TDB1_LOG((tdb, TDB1_DEBUG_TRACE, "tdb1_transaction_recover: recovered %d byte database\n",
+                recovery_eof));
+
+       /* all done */
+       return 0;
+}
+
+/* Any I/O failures we say "needs recovery". */
+bool tdb1_needs_recovery(struct tdb1_context *tdb)
+{
+       tdb1_off_t recovery_head;
+       struct tdb1_record rec;
+
+       /* find the recovery area */
+       if (tdb1_ofs_read(tdb, TDB1_RECOVERY_HEAD, &recovery_head) == -1) {
+               return true;
+       }
+
+       if (recovery_head == 0) {
+               /* we have never allocated a recovery record */
+               return false;
+       }
+
+       /* read the recovery record */
+       if (tdb->methods->tdb1_read(tdb, recovery_head, &rec,
+                                  sizeof(rec), TDB1_DOCONV()) == -1) {
+               return true;
+       }
+
+       return (rec.magic == TDB1_RECOVERY_MAGIC);
+}
diff --git a/ccan/tdb2/tdb1_traverse.c b/ccan/tdb2/tdb1_traverse.c
new file mode 100644 (file)
index 0000000..515beb1
--- /dev/null
@@ -0,0 +1,352 @@
+ /*
+   Unix SMB/CIFS implementation.
+
+   trivial database library
+
+   Copyright (C) Andrew Tridgell              1999-2005
+   Copyright (C) Paul `Rusty' Russell             2000
+   Copyright (C) Jeremy Allison                           2000-2003
+
+     ** NOTE! The following LGPL license applies to the tdb
+     ** library. This does NOT imply that all of Samba is released
+     ** under the LGPL
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 3 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with this library; if not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "tdb1_private.h"
+
+#define TDB1_NEXT_LOCK_ERR ((tdb1_off_t)-1)
+
+/* Uses traverse lock: 0 = finish, TDB1_NEXT_LOCK_ERR = error,
+   other = record offset */
+static tdb1_off_t tdb1_next_lock(struct tdb1_context *tdb, struct tdb1_traverse_lock *tlock,
+                        struct tdb1_record *rec)
+{
+       int want_next = (tlock->off != 0);
+
+       /* Lock each chain from the start one. */
+       for (; tlock->hash < tdb->header.hash_size; tlock->hash++) {
+               if (!tlock->off && tlock->hash != 0) {
+                       /* this is an optimisation for the common case where
+                          the hash chain is empty, which is particularly
+                          common for the use of tdb with ldb, where large
+                          hashes are used. In that case we spend most of our
+                          time in tdb1_brlock(), locking empty hash chains.
+
+                          To avoid this, we do an unlocked pre-check to see
+                          if the hash chain is empty before starting to look
+                          inside it. If it is empty then we can avoid that
+                          hash chain. If it isn't empty then we can't believe
+                          the value we get back, as we read it without a
+                          lock, so instead we get the lock and re-fetch the
+                          value below.
+
+                          Notice that not doing this optimisation on the
+                          first hash chain is critical. We must guarantee
+                          that we have done at least one fcntl lock at the
+                          start of a search to guarantee that memory is
+                          coherent on SMP systems. If records are added by
+                          others during the search then thats OK, and we
+                          could possibly miss those with this trick, but we
+                          could miss them anyway without this trick, so the
+                          semantics don't change.
+
+                          With a non-indexed ldb search this trick gains us a
+                          factor of around 80 in speed on a linux 2.6.x
+                          system (testing using ldbtest).
+                       */
+                       tdb->methods->next_hash_chain(tdb, &tlock->hash);
+                       if (tlock->hash == tdb->header.hash_size) {
+                               continue;
+                       }
+               }
+
+               if (tdb1_lock(tdb, tlock->hash, tlock->lock_rw) == -1)
+                       return TDB1_NEXT_LOCK_ERR;
+
+               /* No previous record?  Start at top of chain. */
+               if (!tlock->off) {
+                       if (tdb1_ofs_read(tdb, TDB1_HASH_TOP(tlock->hash),
+                                    &tlock->off) == -1)
+                               goto fail;
+               } else {
+                       /* Otherwise unlock the previous record. */
+                       if (tdb1_unlock_record(tdb, tlock->off) != 0)
+                               goto fail;
+               }
+
+               if (want_next) {
+                       /* We have offset of old record: grab next */
+                       if (tdb1_rec_read(tdb, tlock->off, rec) == -1)
+                               goto fail;
+                       tlock->off = rec->next;
+               }
+
+               /* Iterate through chain */
+               while( tlock->off) {
+                       tdb1_off_t current;
+                       if (tdb1_rec_read(tdb, tlock->off, rec) == -1)
+                               goto fail;
+
+                       /* Detect infinite loops. From "Shlomi Yaakobovich" <Shlomi@exanet.com>. */
+                       if (tlock->off == rec->next) {
+                               tdb->ecode = TDB1_ERR_CORRUPT;
+                               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_next_lock: loop detected.\n"));
+                               goto fail;
+                       }
+
+                       if (!TDB1_DEAD(rec)) {
+                               /* Woohoo: we found one! */
+                               if (tdb1_lock_record(tdb, tlock->off) != 0)
+                                       goto fail;
+                               return tlock->off;
+                       }
+
+                       /* Try to clean dead ones from old traverses */
+                       current = tlock->off;
+                       tlock->off = rec->next;
+                       if (!(tdb->read_only || tdb->traverse_read) &&
+                           tdb1_do_delete(tdb, current, rec) != 0)
+                               goto fail;
+               }
+               tdb1_unlock(tdb, tlock->hash, tlock->lock_rw);
+               want_next = 0;
+       }
+       /* We finished iteration without finding anything */
+       tdb->ecode = TDB1_SUCCESS;
+       return 0;
+
+ fail:
+       tlock->off = 0;
+       if (tdb1_unlock(tdb, tlock->hash, tlock->lock_rw) != 0)
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_next_lock: On error unlock failed!\n"));
+       return TDB1_NEXT_LOCK_ERR;
+}
+
+/* traverse the entire database - calling fn(tdb, key, data) on each element.
+   return -1 on error or the record count traversed
+   if fn is NULL then it is not called
+   a non-zero return value from fn() indicates that the traversal should stop
+  */
+static int tdb1_traverse_internal(struct tdb1_context *tdb,
+                                tdb1_traverse_func fn, void *private_data,
+                                struct tdb1_traverse_lock *tl)
+{
+       TDB1_DATA key, dbuf;
+       struct tdb1_record rec;
+       int ret = 0, count = 0;
+       tdb1_off_t off;
+
+       /* This was in the initializaton, above, but the IRIX compiler
+        * did not like it.  crh
+        */
+       tl->next = tdb->travlocks.next;
+
+       /* fcntl locks don't stack: beware traverse inside traverse */
+       tdb->travlocks.next = tl;
+
+       /* tdb1_next_lock places locks on the record returned, and its chain */
+       while ((off = tdb1_next_lock(tdb, tl, &rec)) != 0) {
+               if (off == TDB1_NEXT_LOCK_ERR) {
+                       ret = -1;
+                       goto out;
+               }
+               count++;
+               /* now read the full record */
+               key.dptr = tdb1_alloc_read(tdb, tl->off + sizeof(rec),
+                                         rec.key_len + rec.data_len);
+               if (!key.dptr) {
+                       ret = -1;
+                       if (tdb1_unlock(tdb, tl->hash, tl->lock_rw) != 0)
+                               goto out;
+                       if (tdb1_unlock_record(tdb, tl->off) != 0)
+                               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_traverse: key.dptr == NULL and unlock_record failed!\n"));
+                       goto out;
+               }
+               key.dsize = rec.key_len;
+               dbuf.dptr = key.dptr + rec.key_len;
+               dbuf.dsize = rec.data_len;
+
+               /* Drop chain lock, call out */
+               if (tdb1_unlock(tdb, tl->hash, tl->lock_rw) != 0) {
+                       ret = -1;
+                       SAFE_FREE(key.dptr);
+                       goto out;
+               }
+               if (fn && fn(tdb, key, dbuf, private_data)) {
+                       /* They want us to terminate traversal */
+                       if (tdb1_unlock_record(tdb, tl->off) != 0) {
+                               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_traverse: unlock_record failed!\n"));;
+                               ret = -1;
+                       }
+                       SAFE_FREE(key.dptr);
+                       goto out;
+               }
+               SAFE_FREE(key.dptr);
+       }
+out:
+       tdb->travlocks.next = tl->next;
+       if (ret < 0)
+               return -1;
+       else
+               return count;
+}
+
+
+/*
+  a write style traverse - temporarily marks the db read only
+*/
+_PUBLIC_ int tdb1_traverse_read(struct tdb1_context *tdb,
+                     tdb1_traverse_func fn, void *private_data)
+{
+       struct tdb1_traverse_lock tl = { NULL, 0, 0, F_RDLCK };
+       int ret;
+
+       /* we need to get a read lock on the transaction lock here to
+          cope with the lock ordering semantics of solaris10 */
+       if (tdb1_transaction_lock(tdb, F_RDLCK, TDB1_LOCK_WAIT)) {
+               return -1;
+       }
+
+       tdb->traverse_read++;
+       ret = tdb1_traverse_internal(tdb, fn, private_data, &tl);
+       tdb->traverse_read--;
+
+       tdb1_transaction_unlock(tdb, F_RDLCK);
+
+       return ret;
+}
+
+/*
+  a write style traverse - needs to get the transaction lock to
+  prevent deadlocks
+
+  WARNING: The data buffer given to the callback fn does NOT meet the
+  alignment restrictions malloc gives you.
+*/
+_PUBLIC_ int tdb1_traverse(struct tdb1_context *tdb,
+                tdb1_traverse_func fn, void *private_data)
+{
+       struct tdb1_traverse_lock tl = { NULL, 0, 0, F_WRLCK };
+       int ret;
+
+       if (tdb->read_only || tdb->traverse_read) {
+               return tdb1_traverse_read(tdb, fn, private_data);
+       }
+
+       if (tdb1_transaction_lock(tdb, F_WRLCK, TDB1_LOCK_WAIT)) {
+               return -1;
+       }
+
+       tdb->traverse_write++;
+       ret = tdb1_traverse_internal(tdb, fn, private_data, &tl);
+       tdb->traverse_write--;
+
+       tdb1_transaction_unlock(tdb, F_WRLCK);
+
+       return ret;
+}
+
+
+/* find the first entry in the database and return its key */
+_PUBLIC_ TDB1_DATA tdb1_firstkey(struct tdb1_context *tdb)
+{
+       TDB1_DATA key;
+       struct tdb1_record rec;
+       tdb1_off_t off;
+
+       /* release any old lock */
+       if (tdb1_unlock_record(tdb, tdb->travlocks.off) != 0)
+               return tdb1_null;
+       tdb->travlocks.off = tdb->travlocks.hash = 0;
+       tdb->travlocks.lock_rw = F_RDLCK;
+
+       /* Grab first record: locks chain and returned record. */
+       off = tdb1_next_lock(tdb, &tdb->travlocks, &rec);
+       if (off == 0 || off == TDB1_NEXT_LOCK_ERR) {
+               return tdb1_null;
+       }
+       /* now read the key */
+       key.dsize = rec.key_len;
+       key.dptr =tdb1_alloc_read(tdb,tdb->travlocks.off+sizeof(rec),key.dsize);
+
+       /* Unlock the hash chain of the record we just read. */
+       if (tdb1_unlock(tdb, tdb->travlocks.hash, tdb->travlocks.lock_rw) != 0)
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_firstkey: error occurred while tdb1_unlocking!\n"));
+       return key;
+}
+
+/* find the next entry in the database, returning its key */
+_PUBLIC_ TDB1_DATA tdb1_nextkey(struct tdb1_context *tdb, TDB1_DATA oldkey)
+{
+       uint32_t oldhash;
+       TDB1_DATA key = tdb1_null;
+       struct tdb1_record rec;
+       unsigned char *k = NULL;
+       tdb1_off_t off;
+
+       /* Is locked key the old key?  If so, traverse will be reliable. */
+       if (tdb->travlocks.off) {
+               if (tdb1_lock(tdb,tdb->travlocks.hash,tdb->travlocks.lock_rw))
+                       return tdb1_null;
+               if (tdb1_rec_read(tdb, tdb->travlocks.off, &rec) == -1
+                   || !(k = tdb1_alloc_read(tdb,tdb->travlocks.off+sizeof(rec),
+                                           rec.key_len))
+                   || memcmp(k, oldkey.dptr, oldkey.dsize) != 0) {
+                       /* No, it wasn't: unlock it and start from scratch */
+                       if (tdb1_unlock_record(tdb, tdb->travlocks.off) != 0) {
+                               SAFE_FREE(k);
+                               return tdb1_null;
+                       }
+                       if (tdb1_unlock(tdb, tdb->travlocks.hash, tdb->travlocks.lock_rw) != 0) {
+                               SAFE_FREE(k);
+                               return tdb1_null;
+                       }
+                       tdb->travlocks.off = 0;
+               }
+
+               SAFE_FREE(k);
+       }
+
+       if (!tdb->travlocks.off) {
+               /* No previous element: do normal find, and lock record */
+               tdb->travlocks.off = tdb1_find_lock_hash(tdb, oldkey, tdb->hash_fn(&oldkey), tdb->travlocks.lock_rw, &rec);
+               if (!tdb->travlocks.off) {
+                       return tdb1_null;
+               }
+               tdb->travlocks.hash = TDB1_BUCKET(rec.full_hash);
+               if (tdb1_lock_record(tdb, tdb->travlocks.off) != 0) {
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_nextkey: lock_record failed (%s)!\n", strerror(errno)));
+                       return tdb1_null;
+               }
+       }
+       oldhash = tdb->travlocks.hash;
+
+       /* Grab next record: locks chain and returned record,
+          unlocks old record */
+       off = tdb1_next_lock(tdb, &tdb->travlocks, &rec);
+       if (off != TDB1_NEXT_LOCK_ERR && off != 0) {
+               key.dsize = rec.key_len;
+               key.dptr = tdb1_alloc_read(tdb, tdb->travlocks.off+sizeof(rec),
+                                         key.dsize);
+               /* Unlock the chain of this new record */
+               if (tdb1_unlock(tdb, tdb->travlocks.hash, tdb->travlocks.lock_rw) != 0)
+                       TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_nextkey: WARNING tdb1_unlock failed!\n"));
+       }
+       /* Unlock the chain of old record */
+       if (tdb1_unlock(tdb, TDB1_BUCKET(oldhash), tdb->travlocks.lock_rw) != 0)
+               TDB1_LOG((tdb, TDB1_DEBUG_FATAL, "tdb1_nextkey: WARNING tdb1_unlock failed!\n"));
+       return key;
+}