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