2 Unix SMB/CIFS implementation.
4 trivial database library
6 Copyright (C) Andrew Tridgell 1999-2005
7 Copyright (C) Paul `Rusty' Russell 2000
8 Copyright (C) Jeremy Allison 2000-2003
10 ** NOTE! The following LGPL license applies to the tdb
11 ** library. This does NOT imply that all of Samba is released
14 This library is free software; you can redistribute it and/or
15 modify it under the terms of the GNU Lesser General Public
16 License as published by the Free Software Foundation; either
17 version 3 of the License, or (at your option) any later version.
19 This library is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 Lesser General Public License for more details.
24 You should have received a copy of the GNU Lesser General Public
25 License along with this library; if not, see <http://www.gnu.org/licenses/>.
28 #include "tdb_private.h"
33 non-blocking increment of the tdb sequence number if the tdb has been opened using
36 void tdb_increment_seqnum_nonblock(struct tdb_context *tdb)
40 if (!(tdb->flags & TDB_SEQNUM)) {
44 /* we ignore errors from this, as we have no sane way of
47 tdb_ofs_read(tdb, TDB_SEQNUM_OFS, &seqnum);
49 tdb_ofs_write(tdb, TDB_SEQNUM_OFS, &seqnum);
53 increment the tdb sequence number if the tdb has been opened using
56 static void tdb_increment_seqnum(struct tdb_context *tdb)
58 if (!(tdb->flags & TDB_SEQNUM)) {
62 if (tdb_brlock(tdb, TDB_SEQNUM_OFS, F_WRLCK, F_SETLKW, 1, 1) != 0) {
66 tdb_increment_seqnum_nonblock(tdb);
68 tdb_brlock(tdb, TDB_SEQNUM_OFS, F_UNLCK, F_SETLKW, 1, 1);
71 static int tdb_key_compare(TDB_DATA key, TDB_DATA data, void *private_data)
73 return memcmp(data.dptr, key.dptr, data.dsize);
76 /* Returns 0 on fail. On success, return offset of record, and fills
78 static tdb_off_t tdb_find(struct tdb_context *tdb, TDB_DATA key, uint32_t hash,
79 struct list_struct *r)
83 /* read in the hash top */
84 if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1)
87 /* keep looking until we find the right record */
89 if (tdb_rec_read(tdb, rec_ptr, r) == -1)
92 if (!TDB_DEAD(r) && hash==r->full_hash
93 && key.dsize==r->key_len
94 && tdb_parse_data(tdb, key, rec_ptr + sizeof(*r),
95 r->key_len, tdb_key_compare,
99 /* detect tight infinite loop */
100 if (rec_ptr == r->next) {
101 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_find: loop detected.\n"));
102 return TDB_ERRCODE(TDB_ERR_CORRUPT, 0);
106 return TDB_ERRCODE(TDB_ERR_NOEXIST, 0);
109 /* As tdb_find, but if you succeed, keep the lock */
110 tdb_off_t tdb_find_lock_hash(struct tdb_context *tdb, TDB_DATA key, uint32_t hash, int locktype,
111 struct list_struct *rec)
115 if (tdb_lock(tdb, BUCKET(hash), locktype) == -1)
117 if (!(rec_ptr = tdb_find(tdb, key, hash, rec)))
118 tdb_unlock(tdb, BUCKET(hash), locktype);
123 /* update an entry in place - this only works if the new data size
124 is <= the old data size and the key exists.
125 on failure return -1.
127 static int tdb_update_hash(struct tdb_context *tdb, TDB_DATA key, uint32_t hash, TDB_DATA dbuf)
129 struct list_struct rec;
133 if (!(rec_ptr = tdb_find(tdb, key, hash, &rec)))
136 /* must be long enough key, data and tailer */
137 if (rec.rec_len < key.dsize + dbuf.dsize + sizeof(tdb_off_t)) {
138 tdb->ecode = TDB_SUCCESS; /* Not really an error */
142 if (tdb->methods->tdb_write(tdb, rec_ptr + sizeof(rec) + rec.key_len,
143 dbuf.dptr, dbuf.dsize) == -1)
146 if (dbuf.dsize != rec.data_len) {
148 rec.data_len = dbuf.dsize;
149 return tdb_rec_write(tdb, rec_ptr, &rec);
155 /* find an entry in the database given a key */
156 /* If an entry doesn't exist tdb_err will be set to
157 * TDB_ERR_NOEXIST. If a key has no data attached
158 * then the TDB_DATA will have zero length but
161 TDB_DATA tdb_fetch(struct tdb_context *tdb, TDB_DATA key)
164 struct list_struct rec;
168 /* find which hash bucket it is in */
169 hash = tdb->hash_fn(&key);
170 if (!(rec_ptr = tdb_find_lock_hash(tdb,key,hash,F_RDLCK,&rec)))
173 ret.dptr = tdb_alloc_read(tdb, rec_ptr + sizeof(rec) + rec.key_len,
175 ret.dsize = rec.data_len;
176 tdb_unlock(tdb, BUCKET(rec.full_hash), F_RDLCK);
181 * Find an entry in the database and hand the record's data to a parsing
182 * function. The parsing function is executed under the chain read lock, so it
183 * should be fast and should not block on other syscalls.
185 * DONT CALL OTHER TDB CALLS FROM THE PARSER, THIS MIGHT LEAD TO SEGFAULTS.
187 * For mmapped tdb's that do not have a transaction open it points the parsing
188 * function directly at the mmap area, it avoids the malloc/memcpy in this
189 * case. If a transaction is open or no mmap is available, it has to do
190 * malloc/read/parse/free.
192 * This is interesting for all readers of potentially large data structures in
193 * the tdb records, ldb indexes being one example.
196 int tdb_parse_record(struct tdb_context *tdb, TDB_DATA key,
197 int (*parser)(TDB_DATA key, TDB_DATA data,
202 struct list_struct rec;
206 /* find which hash bucket it is in */
207 hash = tdb->hash_fn(&key);
209 if (!(rec_ptr = tdb_find_lock_hash(tdb,key,hash,F_RDLCK,&rec))) {
210 return TDB_ERRCODE(TDB_ERR_NOEXIST, 0);
213 ret = tdb_parse_data(tdb, key, rec_ptr + sizeof(rec) + rec.key_len,
214 rec.data_len, parser, private_data);
216 tdb_unlock(tdb, BUCKET(rec.full_hash), F_RDLCK);
221 /* check if an entry in the database exists
223 note that 1 is returned if the key is found and 0 is returned if not found
224 this doesn't match the conventions in the rest of this module, but is
227 static int tdb_exists_hash(struct tdb_context *tdb, TDB_DATA key, uint32_t hash)
229 struct list_struct rec;
231 if (tdb_find_lock_hash(tdb, key, hash, F_RDLCK, &rec) == 0)
233 tdb_unlock(tdb, BUCKET(rec.full_hash), F_RDLCK);
237 int tdb_exists(struct tdb_context *tdb, TDB_DATA key)
239 uint32_t hash = tdb->hash_fn(&key);
240 return tdb_exists_hash(tdb, key, hash);
243 /* actually delete an entry in the database given the offset */
244 int tdb_do_delete(struct tdb_context *tdb, tdb_off_t rec_ptr, struct list_struct *rec)
246 tdb_off_t last_ptr, i;
247 struct list_struct lastrec;
249 if (tdb->read_only || tdb->traverse_read) return -1;
251 if (((tdb->traverse_write != 0) && (!TDB_DEAD(rec))) ||
252 tdb_write_lock_record(tdb, rec_ptr) == -1) {
253 /* Someone traversing here: mark it as dead */
254 rec->magic = TDB_DEAD_MAGIC;
255 return tdb_rec_write(tdb, rec_ptr, rec);
257 if (tdb_write_unlock_record(tdb, rec_ptr) != 0)
260 /* find previous record in hash chain */
261 if (tdb_ofs_read(tdb, TDB_HASH_TOP(rec->full_hash), &i) == -1)
263 for (last_ptr = 0; i != rec_ptr; last_ptr = i, i = lastrec.next)
264 if (tdb_rec_read(tdb, i, &lastrec) == -1)
267 /* unlink it: next ptr is at start of record. */
269 last_ptr = TDB_HASH_TOP(rec->full_hash);
270 if (tdb_ofs_write(tdb, last_ptr, &rec->next) == -1)
273 /* recover the space */
274 if (tdb_free(tdb, rec_ptr, rec) == -1)
279 static int tdb_count_dead(struct tdb_context *tdb, uint32_t hash)
283 struct list_struct rec;
285 /* read in the hash top */
286 if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1)
290 if (tdb_rec_read(tdb, rec_ptr, &rec) == -1)
293 if (rec.magic == TDB_DEAD_MAGIC) {
302 * Purge all DEAD records from a hash chain
304 static int tdb_purge_dead(struct tdb_context *tdb, uint32_t hash)
307 struct list_struct rec;
310 if (tdb_lock(tdb, -1, F_WRLCK) == -1) {
314 /* read in the hash top */
315 if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1)
321 if (tdb_rec_read(tdb, rec_ptr, &rec) == -1) {
327 if (rec.magic == TDB_DEAD_MAGIC
328 && tdb_do_delete(tdb, rec_ptr, &rec) == -1) {
335 tdb_unlock(tdb, -1, F_WRLCK);
339 /* delete an entry in the database given a key */
340 static int tdb_delete_hash(struct tdb_context *tdb, TDB_DATA key, uint32_t hash)
343 struct list_struct rec;
346 if (tdb->max_dead_records != 0) {
349 * Allow for some dead records per hash chain, mainly for
350 * tdb's with a very high create/delete rate like locking.tdb.
353 if (tdb_lock(tdb, BUCKET(hash), F_WRLCK) == -1)
356 if (tdb_count_dead(tdb, hash) >= tdb->max_dead_records) {
358 * Don't let the per-chain freelist grow too large,
359 * delete all existing dead records
361 tdb_purge_dead(tdb, hash);
364 if (!(rec_ptr = tdb_find(tdb, key, hash, &rec))) {
365 tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
370 * Just mark the record as dead.
372 rec.magic = TDB_DEAD_MAGIC;
373 ret = tdb_rec_write(tdb, rec_ptr, &rec);
376 if (!(rec_ptr = tdb_find_lock_hash(tdb, key, hash, F_WRLCK,
380 ret = tdb_do_delete(tdb, rec_ptr, &rec);
384 tdb_increment_seqnum(tdb);
387 if (tdb_unlock(tdb, BUCKET(rec.full_hash), F_WRLCK) != 0)
388 TDB_LOG((tdb, TDB_DEBUG_WARNING, "tdb_delete: WARNING tdb_unlock failed!\n"));
392 int tdb_delete(struct tdb_context *tdb, TDB_DATA key)
394 uint32_t hash = tdb->hash_fn(&key);
395 return tdb_delete_hash(tdb, key, hash);
399 * See if we have a dead record around with enough space
401 static tdb_off_t tdb_find_dead(struct tdb_context *tdb, uint32_t hash,
402 struct list_struct *r, tdb_len_t length)
406 /* read in the hash top */
407 if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1)
410 /* keep looking until we find the right record */
412 if (tdb_rec_read(tdb, rec_ptr, r) == -1)
415 if (TDB_DEAD(r) && r->rec_len >= length) {
417 * First fit for simple coding, TODO: change to best
427 /* store an element in the database, replacing any existing element
430 return 0 on success, -1 on failure
432 int tdb_store(struct tdb_context *tdb, TDB_DATA key, TDB_DATA dbuf, int flag)
434 struct list_struct rec;
440 if (tdb->read_only || tdb->traverse_read) {
441 tdb->ecode = TDB_ERR_RDONLY;
445 /* find which hash bucket it is in */
446 hash = tdb->hash_fn(&key);
447 if (tdb_lock(tdb, BUCKET(hash), F_WRLCK) == -1)
450 /* check for it existing, on insert. */
451 if (flag == TDB_INSERT) {
452 if (tdb_exists_hash(tdb, key, hash)) {
453 tdb->ecode = TDB_ERR_EXISTS;
457 /* first try in-place update, on modify or replace. */
458 if (tdb_update_hash(tdb, key, hash, dbuf) == 0) {
461 if (tdb->ecode == TDB_ERR_NOEXIST &&
462 flag == TDB_MODIFY) {
463 /* if the record doesn't exist and we are in TDB_MODIFY mode then
464 we should fail the store */
468 /* reset the error code potentially set by the tdb_update() */
469 tdb->ecode = TDB_SUCCESS;
471 /* delete any existing record - if it doesn't exist we don't
472 care. Doing this first reduces fragmentation, and avoids
473 coalescing with `allocated' block before it's updated. */
474 if (flag != TDB_INSERT)
475 tdb_delete_hash(tdb, key, hash);
477 /* Copy key+value *before* allocating free space in case malloc
478 fails and we are left with a dead spot in the tdb. */
480 if (!(p = (char *)malloc(key.dsize + dbuf.dsize))) {
481 tdb->ecode = TDB_ERR_OOM;
485 memcpy(p, key.dptr, key.dsize);
487 memcpy(p+key.dsize, dbuf.dptr, dbuf.dsize);
489 if (tdb->max_dead_records != 0) {
491 * Allow for some dead records per hash chain, look if we can
492 * find one that can hold the new record. We need enough space
493 * for key, data and tailer. If we find one, we don't have to
494 * consult the central freelist.
496 rec_ptr = tdb_find_dead(
498 key.dsize + dbuf.dsize + sizeof(tdb_off_t));
501 rec.key_len = key.dsize;
502 rec.data_len = dbuf.dsize;
503 rec.full_hash = hash;
504 rec.magic = TDB_MAGIC;
505 if (tdb_rec_write(tdb, rec_ptr, &rec) == -1
506 || tdb->methods->tdb_write(
507 tdb, rec_ptr + sizeof(rec),
508 p, key.dsize + dbuf.dsize) == -1) {
516 * We have to allocate some space from the freelist, so this means we
517 * have to lock it. Use the chance to purge all the DEAD records from
518 * the hash chain under the freelist lock.
521 if (tdb_lock(tdb, -1, F_WRLCK) == -1) {
525 if ((tdb->max_dead_records != 0)
526 && (tdb_purge_dead(tdb, hash) == -1)) {
527 tdb_unlock(tdb, -1, F_WRLCK);
531 /* we have to allocate some space */
532 rec_ptr = tdb_allocate(tdb, key.dsize + dbuf.dsize, &rec);
534 tdb_unlock(tdb, -1, F_WRLCK);
540 /* Read hash top into next ptr */
541 if (tdb_ofs_read(tdb, TDB_HASH_TOP(hash), &rec.next) == -1)
544 rec.key_len = key.dsize;
545 rec.data_len = dbuf.dsize;
546 rec.full_hash = hash;
547 rec.magic = TDB_MAGIC;
549 /* write out and point the top of the hash chain at it */
550 if (tdb_rec_write(tdb, rec_ptr, &rec) == -1
551 || tdb->methods->tdb_write(tdb, rec_ptr+sizeof(rec), p, key.dsize+dbuf.dsize)==-1
552 || tdb_ofs_write(tdb, TDB_HASH_TOP(hash), &rec_ptr) == -1) {
553 /* Need to tdb_unallocate() here */
561 tdb_increment_seqnum(tdb);
565 tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
570 /* Append to an entry. Create if not exist. */
571 int tdb_append(struct tdb_context *tdb, TDB_DATA key, TDB_DATA new_dbuf)
577 /* find which hash bucket it is in */
578 hash = tdb->hash_fn(&key);
579 if (tdb_lock(tdb, BUCKET(hash), F_WRLCK) == -1)
582 dbuf = tdb_fetch(tdb, key);
584 if (dbuf.dptr == NULL) {
585 dbuf.dptr = (unsigned char *)malloc(new_dbuf.dsize);
587 unsigned char *new_dptr = (unsigned char *)realloc(dbuf.dptr,
588 dbuf.dsize + new_dbuf.dsize);
589 if (new_dptr == NULL) {
592 dbuf.dptr = new_dptr;
595 if (dbuf.dptr == NULL) {
596 tdb->ecode = TDB_ERR_OOM;
600 memcpy(dbuf.dptr + dbuf.dsize, new_dbuf.dptr, new_dbuf.dsize);
601 dbuf.dsize += new_dbuf.dsize;
603 ret = tdb_store(tdb, key, dbuf, 0);
606 tdb_unlock(tdb, BUCKET(hash), F_WRLCK);
607 SAFE_FREE(dbuf.dptr);
613 return the name of the current tdb file
614 useful for external logging functions
616 const char *tdb_name(struct tdb_context *tdb)
622 return the underlying file descriptor being used by tdb, or -1
623 useful for external routines that want to check the device/inode
626 int tdb_fd(struct tdb_context *tdb)
632 return the current logging function
633 useful for external tdb routines that wish to log tdb errors
635 tdb_log_func tdb_log_fn(struct tdb_context *tdb)
637 return tdb->log.log_fn;
642 get the tdb sequence number. Only makes sense if the writers opened
643 with TDB_SEQNUM set. Note that this sequence number will wrap quite
644 quickly, so it should only be used for a 'has something changed'
645 test, not for code that relies on the count of the number of changes
646 made. If you want a counter then use a tdb record.
648 The aim of this sequence number is to allow for a very lightweight
649 test of a possible tdb change.
651 int tdb_get_seqnum(struct tdb_context *tdb)
655 tdb_ofs_read(tdb, TDB_SEQNUM_OFS, &seqnum);
659 int tdb_hash_size(struct tdb_context *tdb)
661 return tdb->header.hash_size;
664 size_t tdb_map_size(struct tdb_context *tdb)
666 return tdb->map_size;
669 int tdb_get_flags(struct tdb_context *tdb)
674 void tdb_add_flags(struct tdb_context *tdb, unsigned flags)
679 void tdb_remove_flags(struct tdb_context *tdb, unsigned flags)
681 tdb->flags &= ~flags;
686 enable sequence number handling on an open tdb
688 void tdb_enable_seqnum(struct tdb_context *tdb)
690 tdb->flags |= TDB_SEQNUM;
695 add a region of the file to the freelist. Length is the size of the region in bytes,
696 which includes the free list header that needs to be added
698 static int tdb_free_region(struct tdb_context *tdb, tdb_off_t offset, ssize_t length)
700 struct list_struct rec;
701 if (length <= sizeof(rec)) {
702 /* the region is not worth adding */
705 if (length + offset > tdb->map_size) {
706 TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_free_region: adding region beyond end of file\n"));
709 memset(&rec,'\0',sizeof(rec));
710 rec.rec_len = length - sizeof(rec);
711 if (tdb_free(tdb, offset, &rec) == -1) {
712 TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_free_region: failed to add free record\n"));
719 wipe the entire database, deleting all records. This can be done
720 very fast by using a global lock. The entire data portion of the
721 file becomes a single entry in the freelist.
723 This code carefully steps around the recovery area, leaving it alone
725 int tdb_wipe_all(struct tdb_context *tdb)
728 tdb_off_t offset = 0;
730 tdb_off_t recovery_head;
731 tdb_len_t recovery_size = 0;
733 if (tdb_lockall(tdb) != 0) {
737 /* see if the tdb has a recovery area, and remember its size
738 if so. We don't want to lose this as otherwise each
739 tdb_wipe_all() in a transaction will increase the size of
740 the tdb by the size of the recovery area */
741 if (tdb_ofs_read(tdb, TDB_RECOVERY_HEAD, &recovery_head) == -1) {
742 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_wipe_all: failed to read recovery head\n"));
746 if (recovery_head != 0) {
747 struct list_struct rec;
748 if (tdb->methods->tdb_read(tdb, recovery_head, &rec, sizeof(rec), DOCONV()) == -1) {
749 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_wipe_all: failed to read recovery record\n"));
752 recovery_size = rec.rec_len + sizeof(rec);
755 /* wipe the hashes */
756 for (i=0;i<tdb->header.hash_size;i++) {
757 if (tdb_ofs_write(tdb, TDB_HASH_TOP(i), &offset) == -1) {
758 TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_wipe_all: failed to write hash %d\n", i));
763 /* wipe the freelist */
764 if (tdb_ofs_write(tdb, FREELIST_TOP, &offset) == -1) {
765 TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_wipe_all: failed to write freelist\n"));
769 /* add all the rest of the file to the freelist, possibly leaving a gap
770 for the recovery area */
771 if (recovery_size == 0) {
772 /* the simple case - the whole file can be used as a freelist */
773 data_len = (tdb->map_size - TDB_DATA_START(tdb->header.hash_size));
774 if (tdb_free_region(tdb, TDB_DATA_START(tdb->header.hash_size), data_len) != 0) {
778 /* we need to add two freelist entries - one on either
779 side of the recovery area
781 Note that we cannot shift the recovery area during
782 this operation. Only the transaction.c code may
783 move the recovery area or we risk subtle data
786 data_len = (recovery_head - TDB_DATA_START(tdb->header.hash_size));
787 if (tdb_free_region(tdb, TDB_DATA_START(tdb->header.hash_size), data_len) != 0) {
790 /* and the 2nd free list entry after the recovery area - if any */
791 data_len = tdb->map_size - (recovery_head+recovery_size);
792 if (tdb_free_region(tdb, recovery_head+recovery_size, data_len) != 0) {
797 if (tdb_unlockall(tdb) != 0) {
798 TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_wipe_all: failed to unlock\n"));
809 struct traverse_state {
811 struct tdb_context *dest_db;
815 traverse function for repacking
817 static int repack_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
819 struct traverse_state *state = (struct traverse_state *)private;
820 if (tdb_store(state->dest_db, key, data, TDB_INSERT) != 0) {
830 int tdb_repack(struct tdb_context *tdb)
832 struct tdb_context *tmp_db;
833 struct traverse_state state;
835 if (tdb_transaction_start(tdb) != 0) {
836 TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to start transaction\n"));
840 tmp_db = tdb_open("tmpdb", tdb_hash_size(tdb), TDB_INTERNAL, O_RDWR|O_CREAT, 0);
841 if (tmp_db == NULL) {
842 TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to create tmp_db\n"));
843 tdb_transaction_cancel(tdb);
848 state.dest_db = tmp_db;
850 if (tdb_traverse_read(tdb, repack_traverse, &state) == -1) {
851 TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to traverse copying out\n"));
852 tdb_transaction_cancel(tdb);
858 TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Error during traversal\n"));
859 tdb_transaction_cancel(tdb);
864 if (tdb_wipe_all(tdb) != 0) {
865 TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to wipe database\n"));
866 tdb_transaction_cancel(tdb);
874 if (tdb_traverse_read(tmp_db, repack_traverse, &state) == -1) {
875 TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to traverse copying back\n"));
876 tdb_transaction_cancel(tdb);
882 TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Error during second traversal\n"));
883 tdb_transaction_cancel(tdb);
890 if (tdb_transaction_commit(tdb) != 0) {
891 TDB_LOG((tdb, TDB_DEBUG_FATAL, __location__ " Failed to commit\n"));