First cut of replay_trace for tdb.
[ccan] / ccan / tdb / traverse.c
1  /* 
2    Unix SMB/CIFS implementation.
3
4    trivial database library
5
6    Copyright (C) Andrew Tridgell              1999-2005
7    Copyright (C) Paul `Rusty' Russell              2000
8    Copyright (C) Jeremy Allison                    2000-2003
9    
10      ** NOTE! The following LGPL license applies to the tdb
11      ** library. This does NOT imply that all of Samba is released
12      ** under the LGPL
13    
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.
18
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.
23
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/>.
26 */
27
28 #include "tdb_private.h"
29
30 /* Uses traverse lock: 0 = finish, -1 = error, other = record offset */
31 static int tdb_next_lock(struct tdb_context *tdb, struct tdb_traverse_lock *tlock,
32                          struct list_struct *rec)
33 {
34         int want_next = (tlock->off != 0);
35
36         /* Lock each chain from the start one. */
37         for (; tlock->hash < tdb->header.hash_size; tlock->hash++) {
38                 if (!tlock->off && tlock->hash != 0) {
39                         /* this is an optimisation for the common case where
40                            the hash chain is empty, which is particularly
41                            common for the use of tdb with ldb, where large
42                            hashes are used. In that case we spend most of our
43                            time in tdb_brlock(), locking empty hash chains.
44                            
45                            To avoid this, we do an unlocked pre-check to see
46                            if the hash chain is empty before starting to look
47                            inside it. If it is empty then we can avoid that
48                            hash chain. If it isn't empty then we can't believe
49                            the value we get back, as we read it without a
50                            lock, so instead we get the lock and re-fetch the
51                            value below.
52                            
53                            Notice that not doing this optimisation on the
54                            first hash chain is critical. We must guarantee
55                            that we have done at least one fcntl lock at the
56                            start of a search to guarantee that memory is
57                            coherent on SMP systems. If records are added by
58                            others during the search then thats OK, and we
59                            could possibly miss those with this trick, but we
60                            could miss them anyway without this trick, so the
61                            semantics don't change.
62                            
63                            With a non-indexed ldb search this trick gains us a
64                            factor of around 80 in speed on a linux 2.6.x
65                            system (testing using ldbtest).
66                         */
67                         tdb->methods->next_hash_chain(tdb, &tlock->hash);
68                         if (tlock->hash == tdb->header.hash_size) {
69                                 continue;
70                         }
71                 }
72
73                 if (tdb_lock(tdb, tlock->hash, tlock->lock_rw) == -1)
74                         return -1;
75
76                 /* No previous record?  Start at top of chain. */
77                 if (!tlock->off) {
78                         if (tdb_ofs_read(tdb, TDB_HASH_TOP(tlock->hash),
79                                      &tlock->off) == -1)
80                                 goto fail;
81                 } else {
82                         /* Otherwise unlock the previous record. */
83                         if (tdb_unlock_record(tdb, tlock->off) != 0)
84                                 goto fail;
85                 }
86
87                 if (want_next) {
88                         /* We have offset of old record: grab next */
89                         if (tdb_rec_read(tdb, tlock->off, rec) == -1)
90                                 goto fail;
91                         tlock->off = rec->next;
92                 }
93
94                 /* Iterate through chain */
95                 while( tlock->off) {
96                         tdb_off_t current;
97                         if (tdb_rec_read(tdb, tlock->off, rec) == -1)
98                                 goto fail;
99
100                         /* Detect infinite loops. From "Shlomi Yaakobovich" <Shlomi@exanet.com>. */
101                         if (tlock->off == rec->next) {
102                                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_next_lock: loop detected.\n"));
103                                 goto fail;
104                         }
105
106                         if (!TDB_DEAD(rec)) {
107                                 /* Woohoo: we found one! */
108                                 if (tdb_lock_record(tdb, tlock->off) != 0)
109                                         goto fail;
110                                 return tlock->off;
111                         }
112
113                         /* Try to clean dead ones from old traverses */
114                         current = tlock->off;
115                         tlock->off = rec->next;
116                         if (!(tdb->read_only || tdb->traverse_read) && 
117                             tdb_do_delete(tdb, current, rec) != 0)
118                                 goto fail;
119                 }
120                 tdb_unlock(tdb, tlock->hash, tlock->lock_rw);
121                 want_next = 0;
122         }
123         /* We finished iteration without finding anything */
124         return TDB_ERRCODE(TDB_SUCCESS, 0);
125
126  fail:
127         tlock->off = 0;
128         if (tdb_unlock(tdb, tlock->hash, tlock->lock_rw) != 0)
129                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_next_lock: On error unlock failed!\n"));
130         return -1;
131 }
132
133 /* traverse the entire database - calling fn(tdb, key, data) on each element.
134    return -1 on error or the record count traversed
135    if fn is NULL then it is not called
136    a non-zero return value from fn() indicates that the traversal should stop
137   */
138 static int tdb_traverse_internal(struct tdb_context *tdb, 
139                                  tdb_traverse_func fn, void *private_data,
140                                  struct tdb_traverse_lock *tl)
141 {
142         TDB_DATA key, dbuf;
143         struct list_struct rec;
144         int ret, count = 0;
145
146         /* This was in the initializaton, above, but the IRIX compiler
147          * did not like it.  crh
148          */
149         tl->next = tdb->travlocks.next;
150
151         /* fcntl locks don't stack: beware traverse inside traverse */
152         tdb->travlocks.next = tl;
153
154         /* tdb_next_lock places locks on the record returned, and its chain */
155         while ((ret = tdb_next_lock(tdb, tl, &rec)) > 0) {
156                 count++;
157                 /* now read the full record */
158                 key.dptr = tdb_alloc_read(tdb, tl->off + sizeof(rec), 
159                                           rec.key_len + rec.data_len);
160                 if (!key.dptr) {
161                         ret = -1;
162                         if (tdb_unlock(tdb, tl->hash, tl->lock_rw) != 0)
163                                 goto out;
164                         if (tdb_unlock_record(tdb, tl->off) != 0)
165                                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_traverse: key.dptr == NULL and unlock_record failed!\n"));
166                         goto out;
167                 }
168                 key.dsize = rec.key_len;
169                 dbuf.dptr = key.dptr + rec.key_len;
170                 dbuf.dsize = rec.data_len;
171
172                 tdb_trace(tdb, "traverse ");
173                 tdb_trace_record(tdb, key);
174                 tdb_trace_record(tdb, dbuf);
175                 tdb_trace(tdb, "\n");
176
177                 /* Drop chain lock, call out */
178                 if (tdb_unlock(tdb, tl->hash, tl->lock_rw) != 0) {
179                         ret = -1;
180                         SAFE_FREE(key.dptr);
181                         goto out;
182                 }
183                 if (fn && fn(tdb, key, dbuf, private_data)) {
184                         /* They want us to terminate traversal */
185                         ret = count;
186                         if (tdb_unlock_record(tdb, tl->off) != 0) {
187                                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_traverse: unlock_record failed!\n"));;
188                                 ret = -1;
189                         }
190                         SAFE_FREE(key.dptr);
191                         goto out;
192                 }
193                 SAFE_FREE(key.dptr);
194         }
195 out:
196         tdb->travlocks.next = tl->next;
197         if (ret < 0)
198                 return -1;
199         else
200                 return count;
201 }
202
203
204 /*
205   a write style traverse - temporarily marks the db read only
206 */
207 int tdb_traverse_read(struct tdb_context *tdb, 
208                       tdb_traverse_func fn, void *private_data)
209 {
210         struct tdb_traverse_lock tl = { NULL, 0, 0, F_RDLCK };
211         int ret;
212
213         /* we need to get a read lock on the transaction lock here to
214            cope with the lock ordering semantics of solaris10 */
215         if (tdb_transaction_lock(tdb, F_RDLCK)) {
216                 return -1;
217         }
218
219         tdb->traverse_read++;
220         tdb_trace(tdb, "tdb_traverse_read_start\n");
221         ret = tdb_traverse_internal(tdb, fn, private_data, &tl);
222         tdb_trace(tdb, "tdb_traverse_end = %i\n", ret);
223         tdb->traverse_read--;
224
225         tdb_transaction_unlock(tdb);
226
227         return ret;
228 }
229
230 /*
231   a write style traverse - needs to get the transaction lock to
232   prevent deadlocks
233
234   WARNING: The data buffer given to the callback fn does NOT meet the
235   alignment restrictions malloc gives you.
236 */
237 int tdb_traverse(struct tdb_context *tdb, 
238                  tdb_traverse_func fn, void *private_data)
239 {
240         struct tdb_traverse_lock tl = { NULL, 0, 0, F_WRLCK };
241         int ret;
242
243         if (tdb->read_only || tdb->traverse_read) {
244                 return tdb_traverse_read(tdb, fn, private_data);
245         }
246         
247         if (tdb_transaction_lock(tdb, F_WRLCK)) {
248                 return -1;
249         }
250
251         tdb->traverse_write++;
252         tdb_trace(tdb, "tdb_traverse_start\n");
253         ret = tdb_traverse_internal(tdb, fn, private_data, &tl);
254         tdb_trace(tdb, "tdb_traverse_end = %i\n", ret);
255         tdb->traverse_write--;
256
257         tdb_transaction_unlock(tdb);
258
259         return ret;
260 }
261
262
263 /* find the first entry in the database and return its key */
264 TDB_DATA tdb_firstkey(struct tdb_context *tdb)
265 {
266         TDB_DATA key;
267         struct list_struct rec;
268
269         /* release any old lock */
270         if (tdb_unlock_record(tdb, tdb->travlocks.off) != 0)
271                 return tdb_null;
272         tdb->travlocks.off = tdb->travlocks.hash = 0;
273         tdb->travlocks.lock_rw = F_RDLCK;
274
275         /* Grab first record: locks chain and returned record. */
276         if (tdb_next_lock(tdb, &tdb->travlocks, &rec) <= 0) {
277                 tdb_trace(tdb, "tdb_firstkey = ENOENT\n");
278                 return tdb_null;
279         }
280         /* now read the key */
281         key.dsize = rec.key_len;
282         key.dptr =tdb_alloc_read(tdb,tdb->travlocks.off+sizeof(rec),key.dsize);
283
284         tdb_trace(tdb, "tdb_firstkey = ");
285         tdb_trace_record(tdb, key);
286         tdb_trace(tdb, "\n");
287
288         /* Unlock the hash chain of the record we just read. */
289         if (tdb_unlock(tdb, tdb->travlocks.hash, tdb->travlocks.lock_rw) != 0)
290                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_firstkey: error occurred while tdb_unlocking!\n"));
291         return key;
292 }
293
294 /* find the next entry in the database, returning its key */
295 TDB_DATA tdb_nextkey(struct tdb_context *tdb, TDB_DATA oldkey)
296 {
297         uint32_t oldhash;
298         TDB_DATA key = tdb_null;
299         struct list_struct rec;
300         unsigned char *k = NULL;
301
302         /* Is locked key the old key?  If so, traverse will be reliable. */
303         if (tdb->travlocks.off) {
304                 if (tdb_lock(tdb,tdb->travlocks.hash,tdb->travlocks.lock_rw))
305                         return tdb_null;
306                 if (tdb_rec_read(tdb, tdb->travlocks.off, &rec) == -1
307                     || !(k = tdb_alloc_read(tdb,tdb->travlocks.off+sizeof(rec),
308                                             rec.key_len))
309                     || memcmp(k, oldkey.dptr, oldkey.dsize) != 0) {
310                         /* No, it wasn't: unlock it and start from scratch */
311                         if (tdb_unlock_record(tdb, tdb->travlocks.off) != 0) {
312                                 tdb_trace(tdb, "tdb_nextkey ");
313                                 tdb_trace_record(tdb, oldkey);
314                                 tdb_trace(tdb, "= ENOENT\n");
315                                 SAFE_FREE(k);
316                                 return tdb_null;
317                         }
318                         if (tdb_unlock(tdb, tdb->travlocks.hash, tdb->travlocks.lock_rw) != 0) {
319                                 SAFE_FREE(k);
320                                 return tdb_null;
321                         }
322                         tdb->travlocks.off = 0;
323                 }
324
325                 SAFE_FREE(k);
326         }
327
328         if (!tdb->travlocks.off) {
329                 /* No previous element: do normal find, and lock record */
330                 tdb->travlocks.off = tdb_find_lock_hash(tdb, oldkey, tdb->hash_fn(&oldkey), tdb->travlocks.lock_rw, &rec);
331                 if (!tdb->travlocks.off) {
332                         tdb_trace(tdb, "tdb_nextkey ");
333                         tdb_trace_record(tdb, oldkey);
334                         tdb_trace(tdb, "= ENOENT\n");
335                         return tdb_null;
336                 }
337                 tdb->travlocks.hash = BUCKET(rec.full_hash);
338                 if (tdb_lock_record(tdb, tdb->travlocks.off) != 0) {
339                         TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_nextkey: lock_record failed (%s)!\n", strerror(errno)));
340                         return tdb_null;
341                 }
342         }
343         oldhash = tdb->travlocks.hash;
344
345         /* Grab next record: locks chain and returned record,
346            unlocks old record */
347         if (tdb_next_lock(tdb, &tdb->travlocks, &rec) > 0) {
348                 key.dsize = rec.key_len;
349                 key.dptr = tdb_alloc_read(tdb, tdb->travlocks.off+sizeof(rec),
350                                           key.dsize);
351                 /* Unlock the chain of this new record */
352                 if (tdb_unlock(tdb, tdb->travlocks.hash, tdb->travlocks.lock_rw) != 0)
353                         TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_nextkey: WARNING tdb_unlock failed!\n"));
354         }
355         /* Unlock the chain of old record */
356         if (tdb_unlock(tdb, BUCKET(oldhash), tdb->travlocks.lock_rw) != 0)
357                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_nextkey: WARNING tdb_unlock failed!\n"));
358         tdb_trace(tdb, "tdb_nextkey ");
359         tdb_trace_record(tdb, oldkey);
360         tdb_trace(tdb, "= ");
361         tdb_trace_record(tdb, key);
362         tdb_trace(tdb, "\n");
363         return key;
364 }
365