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