]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/lock.c
tdb2: update documentation.
[ccan] / ccan / tdb2 / lock.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 "private.h"
29 #include <assert.h>
30 #include <ccan/build_assert/build_assert.h>
31
32 static int fcntl_lock(struct tdb_context *tdb,
33                       int rw, off_t off, off_t len, bool waitflag)
34 {
35         struct flock fl;
36
37         fl.l_type = rw;
38         fl.l_whence = SEEK_SET;
39         fl.l_start = off;
40         fl.l_len = len;
41         fl.l_pid = 0;
42
43         if (waitflag)
44                 return fcntl(tdb->fd, F_SETLKW, &fl);
45         else
46                 return fcntl(tdb->fd, F_SETLK, &fl);
47 }
48
49 static int fcntl_unlock(struct tdb_context *tdb, int rw, off_t off, off_t len)
50 {
51         struct flock fl;
52 #if 0 /* Check they matched up locks and unlocks correctly. */
53         char line[80];
54         FILE *locks;
55         bool found = false;
56
57         locks = fopen("/proc/locks", "r");
58
59         while (fgets(line, 80, locks)) {
60                 char *p;
61                 int type, start, l;
62
63                 /* eg. 1: FLOCK  ADVISORY  WRITE 2440 08:01:2180826 0 EOF */
64                 p = strchr(line, ':') + 1;
65                 if (strncmp(p, " POSIX  ADVISORY  ", strlen(" POSIX  ADVISORY  ")))
66                         continue;
67                 p += strlen(" FLOCK  ADVISORY  ");
68                 if (strncmp(p, "READ  ", strlen("READ  ")) == 0)
69                         type = F_RDLCK;
70                 else if (strncmp(p, "WRITE ", strlen("WRITE ")) == 0)
71                         type = F_WRLCK;
72                 else
73                         abort();
74                 p += 6;
75                 if (atoi(p) != getpid())
76                         continue;
77                 p = strchr(strchr(p, ' ') + 1, ' ') + 1;
78                 start = atoi(p);
79                 p = strchr(p, ' ') + 1;
80                 if (strncmp(p, "EOF", 3) == 0)
81                         l = 0;
82                 else
83                         l = atoi(p) - start + 1;
84
85                 if (off == start) {
86                         if (len != l) {
87                                 fprintf(stderr, "Len %u should be %u: %s",
88                                         (int)len, l, line);
89                                 abort();
90                         }
91                         if (type != rw) {
92                                 fprintf(stderr, "Type %s wrong: %s",
93                                         rw == F_RDLCK ? "READ" : "WRITE", line);
94                                 abort();
95                         }
96                         found = true;
97                         break;
98                 }
99         }
100
101         if (!found) {
102                 fprintf(stderr, "Unlock on %u@%u not found!\n",
103                         (int)off, (int)len);
104                 abort();
105         }
106
107         fclose(locks);
108 #endif
109
110         fl.l_type = F_UNLCK;
111         fl.l_whence = SEEK_SET;
112         fl.l_start = off;
113         fl.l_len = len;
114         fl.l_pid = 0;
115
116         return fcntl(tdb->fd, F_SETLKW, &fl);
117 }
118
119 /* a byte range locking function - return 0 on success
120    this functions locks/unlocks 1 byte at the specified offset.
121
122    note that a len of zero means lock to end of file
123 */
124 static int tdb_brlock(struct tdb_context *tdb,
125                       int rw_type, tdb_off_t offset, tdb_off_t len,
126                       enum tdb_lock_flags flags)
127 {
128         int ret;
129
130         if (tdb->flags & TDB_NOLOCK) {
131                 return 0;
132         }
133
134         if (rw_type == F_WRLCK && tdb->read_only) {
135                 tdb->ecode = TDB_ERR_RDONLY;
136                 return -1;
137         }
138
139         /* A 32 bit system cannot open a 64-bit file, but it could have
140          * expanded since then: check here. */
141         if ((size_t)(offset + len) != offset + len) {
142                 tdb->ecode = TDB_ERR_IO;
143                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
144                          "tdb_brlock: lock on giant offset %llu\n",
145                          (long long)(offset + len));
146                 return -1;
147         }
148
149         do {
150                 ret = fcntl_lock(tdb, rw_type, offset, len,
151                                  flags & TDB_LOCK_WAIT);
152         } while (ret == -1 && errno == EINTR);
153
154         if (ret == -1) {
155                 tdb->ecode = TDB_ERR_LOCK;
156                 /* Generic lock error. errno set by fcntl.
157                  * EAGAIN is an expected return from non-blocking
158                  * locks. */
159                 if (!(flags & TDB_LOCK_PROBE) && errno != EAGAIN) {
160                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
161                                  "tdb_brlock failed (fd=%d) at"
162                                  " offset %llu rw_type=%d flags=%d len=%llu\n",
163                                  tdb->fd, (long long)offset, rw_type,
164                                  flags, (long long)len);
165                 }
166                 return -1;
167         }
168         return 0;
169 }
170
171 static int tdb_brunlock(struct tdb_context *tdb,
172                         int rw_type, tdb_off_t offset, size_t len)
173 {
174         int ret;
175
176         if (tdb->flags & TDB_NOLOCK) {
177                 return 0;
178         }
179
180         do {
181                 ret = fcntl_unlock(tdb, rw_type, offset, len);
182         } while (ret == -1 && errno == EINTR);
183
184         if (ret == -1) {
185                 tdb->log(tdb, TDB_DEBUG_TRACE, tdb->log_priv,
186                          "tdb_brunlock failed (fd=%d) at offset %llu"
187                          " rw_type=%d len=%llu\n",
188                          tdb->fd, (long long)offset, rw_type, (long long)len);
189         }
190         return ret;
191 }
192
193 #if 0
194 /*
195   upgrade a read lock to a write lock. This needs to be handled in a
196   special way as some OSes (such as solaris) have too conservative
197   deadlock detection and claim a deadlock when progress can be
198   made. For those OSes we may loop for a while.  
199 */
200 int tdb_allrecord_upgrade(struct tdb_context *tdb)
201 {
202         int count = 1000;
203
204         if (tdb->allrecord_lock.count != 1) {
205                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
206                          "tdb_allrecord_upgrade failed: count %u too high\n",
207                          tdb->allrecord_lock.count);
208                 return -1;
209         }
210
211         if (tdb->allrecord_lock.off != 1) {
212                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
213                          "tdb_allrecord_upgrade failed: already upgraded?\n");
214                 return -1;
215         }
216
217         while (count--) {
218                 struct timeval tv;
219                 if (tdb_brlock(tdb, F_WRLCK,
220                                TDB_HASH_LOCK_START
221                                + (1ULL << tdb->header.v.hash_bits), 0,
222                                TDB_LOCK_WAIT|TDB_LOCK_PROBE) == 0) {
223                         tdb->allrecord_lock.ltype = F_WRLCK;
224                         tdb->allrecord_lock.off = 0;
225                         return 0;
226                 }
227                 if (errno != EDEADLK) {
228                         break;
229                 }
230                 /* sleep for as short a time as we can - more portable than usleep() */
231                 tv.tv_sec = 0;
232                 tv.tv_usec = 1;
233                 select(0, NULL, NULL, NULL, &tv);
234         }
235         tdb->log(tdb, TDB_DEBUG_WARNING, tdb->log_priv,
236                  "tdb_allrecord_upgrade failed\n");
237         return -1;
238 }
239 #endif
240
241 static struct tdb_lock_type *find_nestlock(struct tdb_context *tdb,
242                                            tdb_off_t offset)
243 {
244         unsigned int i;
245
246         for (i=0; i<tdb->num_lockrecs; i++) {
247                 if (tdb->lockrecs[i].off == offset) {
248                         return &tdb->lockrecs[i];
249                 }
250         }
251         return NULL;
252 }
253
254 /* lock an offset in the database. */
255 static int tdb_nest_lock(struct tdb_context *tdb, tdb_off_t offset, int ltype,
256                          enum tdb_lock_flags flags)
257 {
258         struct tdb_lock_type *new_lck;
259
260         if (offset >= TDB_HASH_LOCK_START + (1 << 30) + tdb->map_size / 8) {
261                 tdb->ecode = TDB_ERR_LOCK;
262                 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
263                          "tdb_lock: invalid offset %llu ltype=%d\n",
264                          (long long)offset, ltype);
265                 return -1;
266         }
267
268         if (tdb->flags & TDB_NOLOCK)
269                 return 0;
270
271         new_lck = find_nestlock(tdb, offset);
272         if (new_lck) {
273                 /*
274                  * Just increment the in-memory struct, posix locks
275                  * don't stack.
276                  */
277                 new_lck->count++;
278                 return 0;
279         }
280
281         new_lck = (struct tdb_lock_type *)realloc(
282                 tdb->lockrecs,
283                 sizeof(*tdb->lockrecs) * (tdb->num_lockrecs+1));
284         if (new_lck == NULL) {
285                 tdb->ecode = TDB_ERR_OOM;
286                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
287                          "tdb_lock: unable to allocate %llu lock structure",
288                          (long long)(tdb->num_lockrecs + 1));
289                 errno = ENOMEM;
290                 return -1;
291         }
292         tdb->lockrecs = new_lck;
293
294         /* Since fcntl locks don't nest, we do a lock for the first one,
295            and simply bump the count for future ones */
296         if (tdb_brlock(tdb, ltype, offset, 1, flags)) {
297                 return -1;
298         }
299
300         tdb->lockrecs[tdb->num_lockrecs].off = offset;
301         tdb->lockrecs[tdb->num_lockrecs].count = 1;
302         tdb->lockrecs[tdb->num_lockrecs].ltype = ltype;
303         tdb->num_lockrecs++;
304
305         return 0;
306 }
307
308 static int tdb_lock_and_recover(struct tdb_context *tdb)
309 {
310 #if 0 /* FIXME */
311
312         int ret;
313
314         /* We need to match locking order in transaction commit. */
315         if (tdb_brlock(tdb, F_WRLCK, FREELIST_TOP, 0, TDB_LOCK_WAIT)) {
316                 return -1;
317         }
318
319         if (tdb_brlock(tdb, F_WRLCK, OPEN_LOCK, 1, TDB_LOCK_WAIT)) {
320                 tdb_brunlock(tdb, F_WRLCK, FREELIST_TOP, 0);
321                 return -1;
322         }
323
324         ret = tdb_transaction_recover(tdb);
325
326         tdb_brunlock(tdb, F_WRLCK, OPEN_LOCK, 1);
327         tdb_brunlock(tdb, F_WRLCK, FREELIST_TOP, 0);
328
329         return ret;
330 #else
331         abort();
332         return -1;
333 #endif
334 }
335
336 static bool tdb_needs_recovery(struct tdb_context *tdb)
337 {
338         /* FIXME */
339         return false;
340 }
341
342 static int tdb_nest_unlock(struct tdb_context *tdb, tdb_off_t off, int ltype)
343 {
344         int ret = -1;
345         struct tdb_lock_type *lck;
346
347         if (tdb->flags & TDB_NOLOCK)
348                 return 0;
349
350         lck = find_nestlock(tdb, off);
351         if ((lck == NULL) || (lck->count == 0)) {
352                 tdb->ecode = TDB_ERR_LOCK;
353                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
354                          "tdb_unlock: no lock for %llu\n", (long long)off);
355                 return -1;
356         }
357
358         if (lck->count > 1) {
359                 lck->count--;
360                 return 0;
361         }
362
363         /*
364          * This lock has count==1 left, so we need to unlock it in the
365          * kernel. We don't bother with decrementing the in-memory array
366          * element, we're about to overwrite it with the last array element
367          * anyway.
368          */
369         ret = tdb_brunlock(tdb, ltype, off, 1);
370
371         /*
372          * Shrink the array by overwriting the element just unlocked with the
373          * last array element.
374          */
375         *lck = tdb->lockrecs[--tdb->num_lockrecs];
376
377         if (tdb->num_lockrecs == 0) {
378                 /* If we're not holding any locks, header can change. */
379                 tdb->header_uptodate = false;
380         }
381
382         return ret;
383 }
384
385 #if 0
386 /*
387   get the transaction lock
388  */
389 int tdb_transaction_lock(struct tdb_context *tdb, int ltype,
390                          enum tdb_lock_flags lockflags)
391 {
392         return tdb_nest_lock(tdb, TRANSACTION_LOCK, ltype, lockflags);
393 }
394
395 /*
396   release the transaction lock
397  */
398 int tdb_transaction_unlock(struct tdb_context *tdb, int ltype)
399 {
400         return tdb_nest_unlock(tdb, TRANSACTION_LOCK, ltype, false);
401 }
402 #endif
403
404 /* We only need to lock individual bytes, but Linux merges consecutive locks
405  * so we lock in contiguous ranges. */
406 static int tdb_lock_gradual(struct tdb_context *tdb,
407                             int ltype, enum tdb_lock_flags flags,
408                             tdb_off_t off, tdb_off_t len)
409 {
410         int ret;
411         enum tdb_lock_flags nb_flags = (flags & ~TDB_LOCK_WAIT);
412
413         if (len <= 4) {
414                 /* Single record.  Just do blocking lock. */
415                 return tdb_brlock(tdb, ltype, off, len, flags);
416         }
417
418         /* First we try non-blocking. */
419         ret = tdb_brlock(tdb, ltype, off, len, nb_flags);
420         if (ret == 0) {
421                 return 0;
422         }
423
424         /* Try locking first half, then second. */
425         ret = tdb_lock_gradual(tdb, ltype, flags, off, len / 2);
426         if (ret == -1)
427                 return -1;
428
429         ret = tdb_lock_gradual(tdb, ltype, flags,
430                                     off + len / 2, len - len / 2);
431         if (ret == -1) {
432                 tdb_brunlock(tdb, ltype, off, len / 2);
433                 return -1;
434         }
435         return 0;
436 }
437
438 /* lock/unlock entire database.  It can only be upgradable if you have some
439  * other way of guaranteeing exclusivity (ie. transaction write lock).
440  * Note that we don't lock the free chains: noone can get those locks
441  * without a hash chain lock first.
442  * The header *will be* up to date once this returns success. */
443 int tdb_allrecord_lock(struct tdb_context *tdb, int ltype,
444                        enum tdb_lock_flags flags, bool upgradable)
445 {
446         tdb_off_t hash_size;
447
448         /* FIXME: There are no locks on read-only dbs */
449         if (tdb->read_only) {
450                 tdb->ecode = TDB_ERR_LOCK;
451                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
452                          "tdb_allrecord_lock: read-only\n");
453                 return -1;
454         }
455
456         if (tdb->allrecord_lock.count && tdb->allrecord_lock.ltype == ltype) {
457                 tdb->allrecord_lock.count++;
458                 return 0;
459         }
460
461         if (tdb->allrecord_lock.count) {
462                 /* a global lock of a different type exists */
463                 tdb->ecode = TDB_ERR_LOCK;
464                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
465                          "tdb_allrecord_lock: already have %s lock\n",
466                          tdb->allrecord_lock.ltype == F_RDLCK
467                          ? "read" : "write");
468                 return -1;
469         }
470
471         if (tdb_has_locks(tdb)) {
472                 /* can't combine global and chain locks */
473                 tdb->ecode = TDB_ERR_LOCK;
474                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
475                          "tdb_allrecord_lock: already have chain lock\n");
476                 return -1;
477         }
478
479         if (upgradable && ltype != F_RDLCK) {
480                 /* tdb error: you can't upgrade a write lock! */
481                 tdb->ecode = TDB_ERR_LOCK;
482                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
483                          "tdb_allrecord_lock: can't upgrade a write lock\n");
484                 return -1;
485         }
486
487         /* Lock all the hash buckets. */
488 again:
489         hash_size = (1ULL << tdb->header.v.hash_bits);
490         if (tdb_lock_gradual(tdb, ltype, flags, TDB_HASH_LOCK_START,
491                              hash_size)) {
492                 if (!(flags & TDB_LOCK_PROBE)) {
493                         tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
494                                  "tdb_lockall hashes failed (%s)\n",
495                                  strerror(errno));
496                 }
497                 return -1;
498         }
499
500         tdb->allrecord_lock.count = 1;
501         /* If it's upgradable, it's actually exclusive so we can treat
502          * it as a write lock. */
503         tdb->allrecord_lock.ltype = upgradable ? F_WRLCK : ltype;
504         tdb->allrecord_lock.off = upgradable;
505
506         /* Now we re-check header, holding lock. */
507         if (unlikely(header_changed(tdb))) {
508                 tdb_allrecord_unlock(tdb, ltype);
509                 goto again;
510         }
511
512         /* Now check for needing recovery. */
513         if (unlikely(tdb_needs_recovery(tdb))) {
514                 tdb_allrecord_unlock(tdb, ltype);
515                 if (tdb_lock_and_recover(tdb) == -1) {
516                         return -1;
517                 }               
518                 goto again;
519         }
520
521         return 0;
522 }
523
524 int tdb_lock_open(struct tdb_context *tdb)
525 {
526         return tdb_nest_lock(tdb, TDB_OPEN_LOCK, F_WRLCK, TDB_LOCK_WAIT);
527 }
528
529 void tdb_unlock_open(struct tdb_context *tdb)
530 {
531         tdb_nest_unlock(tdb, TDB_OPEN_LOCK, F_WRLCK);
532 }
533
534 int tdb_lock_expand(struct tdb_context *tdb, int ltype)
535 {
536         return tdb_nest_lock(tdb, TDB_EXPANSION_LOCK, ltype, TDB_LOCK_WAIT);
537 }
538
539 void tdb_unlock_expand(struct tdb_context *tdb, int ltype)
540 {
541         tdb_nest_unlock(tdb, TDB_EXPANSION_LOCK, ltype);
542 }
543
544 /* unlock entire db */
545 int tdb_allrecord_unlock(struct tdb_context *tdb, int ltype)
546 {
547         tdb_off_t hash_size;
548
549         /* FIXME: There are no locks on read-only dbs */
550         if (tdb->read_only) {
551                 tdb->ecode = TDB_ERR_LOCK;
552                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
553                          "tdb_allrecord_unlock: read-only\n");
554                 return -1;
555         }
556
557         if (tdb->allrecord_lock.count == 0) {
558                 tdb->ecode = TDB_ERR_LOCK;
559                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
560                          "tdb_allrecord_unlock: not locked!\n");
561                 return -1;
562         }
563
564         /* Upgradable locks are marked as write locks. */
565         if (tdb->allrecord_lock.ltype != ltype
566             && (!tdb->allrecord_lock.off || ltype != F_RDLCK)) {
567                 tdb->ecode = TDB_ERR_LOCK;
568                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
569                          "tdb_allrecord_unlock: have %s lock\n",
570                          tdb->allrecord_lock.ltype == F_RDLCK
571                          ? "read" : "write");
572                 return -1;
573         }
574
575         if (tdb->allrecord_lock.count > 1) {
576                 tdb->allrecord_lock.count--;
577                 return 0;
578         }
579
580         tdb->allrecord_lock.count = 0;
581         tdb->allrecord_lock.ltype = 0;
582         tdb->header_uptodate = false;
583
584         hash_size = (1ULL << tdb->header.v.hash_bits);
585
586         return tdb_brunlock(tdb, ltype, TDB_HASH_LOCK_START, hash_size);
587 }
588
589 bool tdb_has_locks(struct tdb_context *tdb)
590 {
591         return tdb->allrecord_lock.count || tdb->num_lockrecs;
592 }
593
594 #if 0
595 /* lock entire database with write lock */
596 int tdb_lockall(struct tdb_context *tdb)
597 {
598         tdb_trace(tdb, "tdb_lockall");
599         return tdb_allrecord_lock(tdb, F_WRLCK, TDB_LOCK_WAIT, false);
600 }
601
602 /* lock entire database with write lock - nonblocking varient */
603 int tdb_lockall_nonblock(struct tdb_context *tdb)
604 {
605         int ret = tdb_allrecord_lock(tdb, F_WRLCK, TDB_LOCK_NOWAIT, false);
606         tdb_trace_ret(tdb, "tdb_lockall_nonblock", ret);
607         return ret;
608 }
609
610 /* unlock entire database with write lock */
611 int tdb_unlockall(struct tdb_context *tdb)
612 {
613         tdb_trace(tdb, "tdb_unlockall");
614         return tdb_allrecord_unlock(tdb, F_WRLCK);
615 }
616
617 /* lock entire database with read lock */
618 int tdb_lockall_read(struct tdb_context *tdb)
619 {
620         tdb_trace(tdb, "tdb_lockall_read");
621         return tdb_allrecord_lock(tdb, F_RDLCK, TDB_LOCK_WAIT, false);
622 }
623
624 /* lock entire database with read lock - nonblock varient */
625 int tdb_lockall_read_nonblock(struct tdb_context *tdb)
626 {
627         int ret = tdb_allrecord_lock(tdb, F_RDLCK, TDB_LOCK_NOWAIT, false);
628         tdb_trace_ret(tdb, "tdb_lockall_read_nonblock", ret);
629         return ret;
630 }
631
632 /* unlock entire database with read lock */
633 int tdb_unlockall_read(struct tdb_context *tdb)
634 {
635         tdb_trace(tdb, "tdb_unlockall_read");
636         return tdb_allrecord_unlock(tdb, F_RDLCK);
637 }
638 #endif
639
640 /* Returns the list we actually locked. */
641 tdb_off_t tdb_lock_list(struct tdb_context *tdb, uint64_t hash,
642                         int ltype, enum tdb_lock_flags waitflag)
643 {
644         tdb_off_t list = hash & ((1ULL << tdb->header.v.hash_bits) - 1);
645         /* Header can change ONLY if we had no locks before. */
646         bool can_change = tdb->num_lockrecs == 0;
647
648         /* a allrecord lock allows us to avoid per chain locks */
649         if (tdb->allrecord_lock.count &&
650             (ltype == tdb->allrecord_lock.ltype || ltype == F_RDLCK)) {
651                 return list;
652         }
653
654         if (tdb->allrecord_lock.count) {
655                 tdb->ecode = TDB_ERR_LOCK;
656                 tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
657                          "tdb_lock_list: have %s allrecordlock\n",
658                          tdb->allrecord_lock.ltype == F_RDLCK
659                          ? "read" : "write");
660                 return TDB_OFF_ERR;
661         }
662
663 again:
664         if (tdb_nest_lock(tdb, TDB_HASH_LOCK_START + list, ltype, waitflag))
665                 return TDB_OFF_ERR;
666
667         if (can_change && unlikely(header_changed(tdb))) {
668                 tdb_off_t new = hash & ((1ULL << tdb->header.v.hash_bits) - 1);
669                 if (new != list) {
670                         tdb_nest_unlock(tdb, TDB_HASH_LOCK_START+list, ltype);
671                         list = new;
672                         goto again;
673                 }
674         }
675         return list;
676 }
677
678 int tdb_unlock_list(struct tdb_context *tdb, tdb_off_t list, int ltype)
679 {
680         list &= ((1ULL << tdb->header.v.hash_bits) - 1);
681
682         /* a allrecord lock allows us to avoid per chain locks */
683         if (tdb->allrecord_lock.count) {
684                 if (tdb->allrecord_lock.ltype == F_RDLCK
685                     && ltype == F_WRLCK) {
686                         tdb->ecode = TDB_ERR_LOCK;
687                         tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
688                                  "tdb_unlock_list RO allrecord!\n");
689                         return -1;
690                 }
691                 return 0;
692         } else {
693                 return tdb_nest_unlock(tdb, TDB_HASH_LOCK_START + list, ltype);
694         }
695 }
696
697 /* Hash locks use TDB_HASH_LOCK_START + the next 30 bits.
698  * Then we begin; bucket offsets are sizeof(tdb_len_t) apart, so we divide.
699  * The result is that on 32 bit systems we don't use lock values > 2^31 on
700  * files that are less than 4GB.
701  */
702 static tdb_off_t free_lock_off(tdb_off_t b_off)
703 {
704         return TDB_HASH_LOCK_START + (1 << 30) + b_off / sizeof(tdb_off_t);
705 }
706
707 int tdb_lock_free_bucket(struct tdb_context *tdb, tdb_off_t b_off,
708                          enum tdb_lock_flags waitflag)
709 {
710         assert(b_off >= sizeof(struct tdb_header));
711
712         /* You're supposed to have a hash lock first! */
713         if (!(tdb->flags & TDB_NOLOCK) && !tdb_has_locks(tdb)) {
714                 tdb->ecode = TDB_ERR_LOCK;
715                 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
716                          "tdb_lock_free_list without lock!\n");
717                 return -1;
718         }
719
720         /* a allrecord lock allows us to avoid per chain locks */
721         if (tdb->allrecord_lock.count) {
722                 if (tdb->allrecord_lock.ltype == F_WRLCK)
723                         return 0;
724                 tdb->ecode = TDB_ERR_LOCK;
725                 tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
726                          "tdb_lock_free_list with RO allrecordlock!\n");
727                 return -1;
728         }
729
730         return tdb_nest_lock(tdb, free_lock_off(b_off), F_WRLCK, waitflag);
731 }
732
733 void tdb_unlock_free_bucket(struct tdb_context *tdb, tdb_off_t b_off)
734 {
735         if (tdb->allrecord_lock.count)
736                 return;
737
738         tdb_nest_unlock(tdb, free_lock_off(b_off), F_WRLCK);
739 }
740
741 /* Even if the entry isn't in this hash bucket, you'd have to lock this
742  * bucket to find it. */
743 static int chainlock(struct tdb_context *tdb, const TDB_DATA *key,
744                      int ltype, enum tdb_lock_flags waitflag,
745                      const char *func)
746 {
747         int ret;
748         uint64_t h = tdb_hash(tdb, key->dptr, key->dsize);
749
750         ret = tdb_lock_list(tdb, h, ltype, waitflag) == TDB_OFF_ERR ? -1 : 0;
751         tdb_trace_1rec(tdb, func, *key);
752         return ret;
753 }
754
755 /* lock/unlock one hash chain. This is meant to be used to reduce
756    contention - it cannot guarantee how many records will be locked */
757 int tdb_chainlock(struct tdb_context *tdb, TDB_DATA key)
758 {
759         return chainlock(tdb, &key, F_WRLCK, TDB_LOCK_WAIT, "tdb_chainlock");
760 }
761
762 int tdb_chainunlock(struct tdb_context *tdb, TDB_DATA key)
763 {
764         uint64_t h = tdb_hash(tdb, key.dptr, key.dsize);
765         tdb_trace_1rec(tdb, "tdb_chainunlock", key);
766         return tdb_unlock_list(tdb, h, F_WRLCK);
767 }
768
769 #if 0
770 /* lock/unlock one hash chain, non-blocking. This is meant to be used
771    to reduce contention - it cannot guarantee how many records will be
772    locked */
773 int tdb_chainlock_nonblock(struct tdb_context *tdb, TDB_DATA key)
774 {
775         return chainlock(tdb, &key, F_WRLCK, TDB_LOCK_NOWAIT,
776                          "tdb_chainlock_nonblock");
777 }
778
779 int tdb_chainlock_read(struct tdb_context *tdb, TDB_DATA key)
780 {
781         return chainlock(tdb, &key, F_RDLCK, TDB_LOCK_WAIT,
782                          "tdb_chainlock_read");
783 }
784
785 int tdb_chainunlock_read(struct tdb_context *tdb, TDB_DATA key)
786 {
787         uint64_t h = tdb_hash(tdb, key.dptr, key.dsize);
788         tdb_trace_1rec(tdb, "tdb_chainunlock_read", key);
789         return tdb_unlock_list(tdb, h & ((1ULL << tdb->header.v.hash_bits)-1),
790                                F_RDLCK);
791 }
792
793 /* record lock stops delete underneath */
794 int tdb_lock_record(struct tdb_context *tdb, tdb_off_t off)
795 {
796         if (tdb->allrecord_lock.count) {
797                 return 0;
798         }
799         return off ? tdb_brlock(tdb, F_RDLCK, off, 1, TDB_LOCK_WAIT) : 0;
800 }
801
802 /*
803   Write locks override our own fcntl readlocks, so check it here.
804   Note this is meant to be F_SETLK, *not* F_SETLKW, as it's not
805   an error to fail to get the lock here.
806 */
807 int tdb_write_lock_record(struct tdb_context *tdb, tdb_off_t off)
808 {
809         struct tdb_traverse_lock *i;
810         for (i = &tdb->travlocks; i; i = i->next)
811                 if (i->off == off)
812                         return -1;
813         if (tdb->allrecord_lock.count) {
814                 if (tdb->allrecord_lock.ltype == F_WRLCK) {
815                         return 0;
816                 }
817                 return -1;
818         }
819         return tdb_brlock(tdb, F_WRLCK, off, 1, TDB_LOCK_NOWAIT|TDB_LOCK_PROBE);
820 }
821
822 int tdb_write_unlock_record(struct tdb_context *tdb, tdb_off_t off)
823 {
824         if (tdb->allrecord_lock.count) {
825                 return 0;
826         }
827         return tdb_brunlock(tdb, F_WRLCK, off, 1);
828 }
829
830 /* fcntl locks don't stack: avoid unlocking someone else's */
831 int tdb_unlock_record(struct tdb_context *tdb, tdb_off_t off)
832 {
833         struct tdb_traverse_lock *i;
834         uint32_t count = 0;
835
836         if (tdb->allrecord_lock.count) {
837                 return 0;
838         }
839
840         if (off == 0)
841                 return 0;
842         for (i = &tdb->travlocks; i; i = i->next)
843                 if (i->off == off)
844                         count++;
845         return (count == 1 ? tdb_brunlock(tdb, F_RDLCK, off, 1) : 0);
846 }
847
848 /* The transaction code uses this to remove all locks. */
849 void tdb_release_transaction_locks(struct tdb_context *tdb)
850 {
851         unsigned int i;
852
853         if (tdb->allrecord_lock.count != 0) {
854                 tdb_off_t hash_size, free_size;
855
856                 hash_size = (1ULL << tdb->header.v.hash_bits)
857                         * sizeof(tdb_off_t);
858                 free_size = tdb->header.v.free_zones 
859                         * (tdb->header.v.free_buckets + 1) * sizeof(tdb_off_t);
860
861                 tdb_brunlock(tdb, tdb->allrecord_lock.ltype,
862                              tdb->header.v.hash_off, hash_size);
863                 tdb_brunlock(tdb, tdb->allrecord_lock.ltype,
864                              tdb->header.v.free_off, free_size);
865                 tdb->allrecord_lock.count = 0;
866                 tdb->allrecord_lock.ltype = 0;
867         }
868
869         for (i = 0; i<tdb->num_lockrecs; i++) {
870                 struct tdb_lock_type *lck = &tdb->lockrecs[i];
871
872                 tdb_brunlock(tdb, lck->ltype, lck->off, 1);
873         }
874         tdb->num_lockrecs = 0;
875         SAFE_FREE(tdb->lockrecs);
876         tdb->header_uptodate = false;
877 }
878 #endif
879
880 void tdb_lock_init(struct tdb_context *tdb)
881 {
882         tdb->num_lockrecs = 0;
883         tdb->lockrecs = NULL;
884         tdb->allrecord_lock.count = 0;
885 }