2 Trivial Database 2: traverse function.
3 Copyright (C) Rusty Russell 2010
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 3 of the License, or (at your option) any later version.
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 #include <ccan/likely/likely.h>
21 static int64_t traverse(struct tdb_context *tdb, int ltype,
22 tdb_traverse_func fn, void *p)
24 uint64_t i, num, count = 0;
25 tdb_off_t off, prev_bucket;
26 struct tdb_used_record rec;
30 /* FIXME: Do we need to start at 0? */
31 prev_bucket = tdb_lock_list(tdb, 0, ltype, TDB_LOCK_WAIT);
35 num = (1ULL << tdb->header.v.hash_bits);
37 for (i = tdb_find_nonzero_off(tdb, hash_off(tdb, 0), num);
39 i += tdb_find_nonzero_off(tdb, hash_off(tdb, i), num - i)) {
40 if (tdb_lock_list(tdb, i, ltype, TDB_LOCK_WAIT) != i)
43 off = tdb_read_off(tdb, hash_off(tdb, i));
44 if (off == TDB_OFF_ERR) {
45 tdb_unlock_list(tdb, i, ltype);
49 /* This race can happen, but look again. */
51 tdb_unlock_list(tdb, i, ltype);
55 /* Drop previous lock. */
56 tdb_unlock_list(tdb, prev_bucket, ltype);
59 if (tdb_read_convert(tdb, off, &rec, sizeof(rec)) != 0)
62 k.dsize = rec_key_length(&rec);
63 d.dsize = rec_data_length(&rec);
64 if (ltype == F_RDLCK) {
65 /* Read traverses can keep the lock. */
66 k.dptr = (void *)tdb_access_read(tdb,
71 k.dptr = tdb_alloc_read(tdb, off + sizeof(rec),
76 d.dptr = k.dptr + k.dsize;
79 if (ltype == F_WRLCK) {
80 /* Drop lock before calling out. */
81 tdb_unlock_list(tdb, i, ltype);
84 if (fn && fn(tdb, k, d, p))
87 if (ltype == F_WRLCK) {
89 /* Regain lock. FIXME: Is this necessary? */
90 if (tdb_lock_list(tdb, i, ltype, TDB_LOCK_WAIT) != i)
93 /* This makes deleting under ourselves a bit nicer. */
94 if (tdb_read_off(tdb, hash_off(tdb, i)) == off)
97 tdb_access_release(tdb, k.dptr);
102 /* Drop final lock. */
103 tdb_unlock_list(tdb, prev_bucket, ltype);
107 tdb_unlock_list(tdb, prev_bucket, ltype);
111 int64_t tdb_traverse(struct tdb_context *tdb, tdb_traverse_func fn, void *p)
113 return traverse(tdb, F_WRLCK, fn, p);
116 int64_t tdb_traverse_read(struct tdb_context *tdb,
117 tdb_traverse_func fn, void *p)
120 bool was_ro = tdb->read_only;
121 tdb->read_only = true;
122 ret = traverse(tdb, F_RDLCK, fn, p);
123 tdb->read_only = was_ro;