]> git.ozlabs.org Git - ccan/blob - ccan/tdb/lock.c
e6b900e419ea00a5b2610ec0ee939157ba665431
[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 wait)
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 (wait)
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 /* a byte range locking function - return 0 on success
123    this functions locks/unlocks 1 byte at the specified offset.
124
125    On error, errno is also set so that errors are passed back properly
126    through tdb_open(). 
127
128    note that a len of zero means lock to end of file
129 */
130 int tdb_brlock(struct tdb_context *tdb,
131                int rw_type, tdb_off_t offset, size_t len,
132                enum tdb_lock_flags flags)
133 {
134         int ret;
135
136         if (tdb->flags & TDB_NOLOCK) {
137                 return 0;
138         }
139
140         if (flags & TDB_LOCK_MARK_ONLY) {
141                 return 0;
142         }
143
144         if ((rw_type == F_WRLCK) && (tdb->read_only || tdb->traverse_read)) {
145                 tdb->ecode = TDB_ERR_RDONLY;
146                 return -1;
147         }
148
149         do {
150                 ret = fcntl_lock(tdb, rw_type, offset, len,
151                                  flags & TDB_LOCK_WAIT);
152                 /* Check for a sigalarm break. */
153                 if (ret == -1 && errno == EINTR &&
154                                 tdb->interrupt_sig_ptr &&
155                                 *tdb->interrupt_sig_ptr) {
156                         break;
157                 }
158         } while (ret == -1 && errno == EINTR);
159
160         if (ret == -1) {
161                 /* Generic lock error. errno set by fcntl.
162                  * EAGAIN is an expected return from non-blocking
163                  * locks. */
164                 if (!(flags & TDB_LOCK_PROBE) && errno != EAGAIN) {
165                         /* Ensure error code is set for log fun to examine. */
166                         tdb->ecode = TDB_ERR_LOCK;
167                         TDB_LOG((tdb, TDB_DEBUG_TRACE,"tdb_brlock failed (fd=%d) at offset %d rw_type=%d flags=%d len=%d\n", 
168                                  tdb->fd, offset, rw_type, flags, (int)len));
169                 }
170                 return -1;
171         }
172         return 0;
173 }
174
175 int tdb_brunlock(struct tdb_context *tdb,
176                  int rw_type, tdb_off_t offset, size_t len)
177 {
178         int ret;
179
180         if (tdb->flags & TDB_NOLOCK) {
181                 return 0;
182         }
183
184         do {
185                 ret = fcntl_unlock(tdb, rw_type, offset, len);
186         } while (ret == -1 && errno == EINTR);
187
188         if (ret == -1) {
189                 TDB_LOG((tdb, TDB_DEBUG_TRACE,"tdb_brunlock failed (fd=%d) at offset %d rw_type=%d len=%d\n", 
190                          tdb->fd, offset, rw_type, (int)len));
191         }
192         return ret;
193 }
194
195 /*
196   upgrade a read lock to a write lock. This needs to be handled in a
197   special way as some OSes (such as solaris) have too conservative
198   deadlock detection and claim a deadlock when progress can be
199   made. For those OSes we may loop for a while.  
200 */
201 int tdb_brlock_upgrade(struct tdb_context *tdb, tdb_off_t offset, size_t len)
202 {
203         int count = 1000;
204         while (count--) {
205                 struct timeval tv;
206                 if (tdb_brlock(tdb, F_WRLCK, offset, len,
207                                TDB_LOCK_WAIT|TDB_LOCK_PROBE) == 0) {
208                         return 0;
209                 }
210                 if (errno != EDEADLK) {
211                         break;
212                 }
213                 /* sleep for as short a time as we can - more portable than usleep() */
214                 tv.tv_sec = 0;
215                 tv.tv_usec = 1;
216                 select(0, NULL, NULL, NULL, &tv);
217         }
218         TDB_LOG((tdb, TDB_DEBUG_TRACE,"tdb_brlock_upgrade failed at offset %d\n", offset));
219         return -1;
220 }
221
222
223 /* lock a list in the database. list -1 is the alloc list */
224 static int _tdb_lock(struct tdb_context *tdb, int list, int ltype,
225                      enum tdb_lock_flags flags)
226 {
227         struct tdb_lock_type *new_lck;
228         int i;
229
230         /* a global lock allows us to avoid per chain locks */
231         if (tdb->global_lock.count && 
232             (ltype == tdb->global_lock.ltype || ltype == F_RDLCK)) {
233                 return 0;
234         }
235
236         if (tdb->global_lock.count) {
237                 tdb->ecode = TDB_ERR_LOCK;
238                 return -1;
239         }
240
241         if (list < -1 || list >= (int)tdb->header.hash_size) {
242                 tdb->ecode = TDB_ERR_LOCK;
243                 TDB_LOG((tdb, TDB_DEBUG_ERROR,"tdb_lock: invalid list %d for ltype=%d\n", 
244                            list, ltype));
245                 return -1;
246         }
247         if (tdb->flags & TDB_NOLOCK)
248                 return 0;
249
250         for (i=0; i<tdb->num_lockrecs; i++) {
251                 if (tdb->lockrecs[i].list == list) {
252                         if (tdb->lockrecs[i].count == 0) {
253                                 /*
254                                  * Can't happen, see tdb_unlock(). It should
255                                  * be an assert.
256                                  */
257                                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_lock: "
258                                          "lck->count == 0 for list %d", list));
259                         }
260                         /*
261                          * Just increment the in-memory struct, posix locks
262                          * don't stack.
263                          */
264                         tdb->lockrecs[i].count++;
265                         return 0;
266                 }
267         }
268
269         new_lck = (struct tdb_lock_type *)realloc(
270                 tdb->lockrecs,
271                 sizeof(*tdb->lockrecs) * (tdb->num_lockrecs+1));
272         if (new_lck == NULL) {
273                 errno = ENOMEM;
274                 return -1;
275         }
276         tdb->lockrecs = new_lck;
277
278         /* Since fcntl locks don't nest, we do a lock for the first one,
279            and simply bump the count for future ones */
280         if (tdb->methods->brlock(tdb, ltype, FREELIST_TOP+4*list, 1, flags)) {
281                 return -1;
282         }
283
284         tdb->num_locks++;
285
286         tdb->lockrecs[tdb->num_lockrecs].list = list;
287         tdb->lockrecs[tdb->num_lockrecs].count = 1;
288         tdb->lockrecs[tdb->num_lockrecs].ltype = ltype;
289         tdb->num_lockrecs += 1;
290
291         return 0;
292 }
293
294 /* lock a list in the database. list -1 is the alloc list */
295 int tdb_lock(struct tdb_context *tdb, int list, int ltype)
296 {
297         int ret;
298
299         ret = _tdb_lock(tdb, list, ltype, TDB_LOCK_WAIT);
300         if (ret) {
301                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_lock failed on list %d "
302                          "ltype=%d (%s)\n",  list, ltype, strerror(errno)));
303         }
304         return ret;
305 }
306
307 /* lock a list in the database. list -1 is the alloc list. non-blocking lock */
308 int tdb_lock_nonblock(struct tdb_context *tdb, int list, int ltype)
309 {
310         return _tdb_lock(tdb, list, ltype, TDB_LOCK_NOWAIT);
311 }
312
313
314 static int _tdb_unlock(struct tdb_context *tdb, int list, int ltype,
315                        bool mark_lock)
316 {
317         int ret = -1;
318         int i;
319         struct tdb_lock_type *lck = NULL;
320
321         /* a global lock allows us to avoid per chain locks */
322         if (tdb->global_lock.count && 
323             (ltype == tdb->global_lock.ltype || ltype == F_RDLCK)) {
324                 return 0;
325         }
326
327         if (tdb->global_lock.count) {
328                 tdb->ecode = TDB_ERR_LOCK;
329                 return -1;
330         }
331
332         if (tdb->flags & TDB_NOLOCK)
333                 return 0;
334
335         /* Sanity checks */
336         if (list < -1 || list >= (int)tdb->header.hash_size) {
337                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlock: list %d invalid (%d)\n", list, tdb->header.hash_size));
338                 return ret;
339         }
340
341         for (i=0; i<tdb->num_lockrecs; i++) {
342                 if (tdb->lockrecs[i].list == list) {
343                         lck = &tdb->lockrecs[i];
344                         break;
345                 }
346         }
347
348         if ((lck == NULL) || (lck->count == 0)) {
349                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlock: count is 0\n"));
350                 return -1;
351         }
352
353         if (lck->count > 1) {
354                 lck->count--;
355                 return 0;
356         }
357
358         /*
359          * This lock has count==1 left, so we need to unlock it in the
360          * kernel. We don't bother with decrementing the in-memory array
361          * element, we're about to overwrite it with the last array element
362          * anyway.
363          */
364
365         if (mark_lock) {
366                 ret = 0;
367         } else {
368                 ret = tdb->methods->brunlock(tdb, ltype,
369                                              FREELIST_TOP+4*list, 1);
370         }
371         tdb->num_locks--;
372
373         /*
374          * Shrink the array by overwriting the element just unlocked with the
375          * last array element.
376          */
377
378         if (tdb->num_lockrecs > 1) {
379                 *lck = tdb->lockrecs[tdb->num_lockrecs-1];
380         }
381         tdb->num_lockrecs -= 1;
382
383         /*
384          * We don't bother with realloc when the array shrinks, but if we have
385          * a completely idle tdb we should get rid of the locked array.
386          */
387
388         if (tdb->num_lockrecs == 0) {
389                 SAFE_FREE(tdb->lockrecs);
390         }
391
392         if (ret)
393                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlock: An error occurred unlocking!\n")); 
394         return ret;
395 }
396
397 int tdb_unlock(struct tdb_context *tdb, int list, int ltype)
398 {
399         return _tdb_unlock(tdb, list, ltype, false);
400 }
401
402 /*
403   get the transaction lock
404  */
405 int tdb_transaction_lock(struct tdb_context *tdb, int ltype)
406 {
407         if (tdb->global_lock.count) {
408                 return 0;
409         }
410         if (tdb->transaction_lock_count > 0) {
411                 tdb->transaction_lock_count++;
412                 return 0;
413         }
414
415         if (tdb->methods->brlock(tdb, ltype, TRANSACTION_LOCK, 1, TDB_LOCK_WAIT) == -1) {
416                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_lock: failed to get transaction lock\n"));
417                 tdb->ecode = TDB_ERR_LOCK;
418                 return -1;
419         }
420         tdb->transaction_lock_count++;
421         return 0;
422 }
423
424 /*
425   release the transaction lock
426  */
427 int tdb_transaction_unlock(struct tdb_context *tdb, int ltype)
428 {
429         int ret;
430         if (tdb->global_lock.count) {
431                 return 0;
432         }
433         if (tdb->transaction_lock_count > 1) {
434                 tdb->transaction_lock_count--;
435                 return 0;
436         }
437         ret = tdb->methods->brunlock(tdb, ltype, TRANSACTION_LOCK, 1);
438         if (ret == 0) {
439                 tdb->transaction_lock_count = 0;
440         }
441         return ret;
442 }
443
444
445
446
447 /* lock/unlock entire database */
448 static int _tdb_lockall(struct tdb_context *tdb, int ltype,
449                         enum tdb_lock_flags flags)
450 {
451         /* There are no locks on read-only dbs */
452         if (tdb->read_only || tdb->traverse_read) {
453                 tdb->ecode = TDB_ERR_LOCK;
454                 return -1;
455         }
456
457         if (tdb->global_lock.count && tdb->global_lock.ltype == ltype) {
458                 tdb->global_lock.count++;
459                 return 0;
460         }
461
462         if (tdb->global_lock.count) {
463                 /* a global lock of a different type exists */
464                 tdb->ecode = TDB_ERR_LOCK;
465                 return -1;
466         }
467         
468         if (tdb->num_locks != 0) {
469                 /* can't combine global and chain locks */
470                 tdb->ecode = TDB_ERR_LOCK;
471                 return -1;
472         }
473
474         if (tdb->methods->brlock(tdb, ltype,
475                                  FREELIST_TOP, 4*tdb->header.hash_size,
476                                  flags)) {
477                 if (flags & TDB_LOCK_WAIT) {
478                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_lockall failed (%s)\n", strerror(errno)));
479                 }
480                 return -1;
481         }
482
483         tdb->global_lock.count = 1;
484         tdb->global_lock.ltype = ltype;
485
486         return 0;
487 }
488
489
490
491 /* unlock entire db */
492 static int _tdb_unlockall(struct tdb_context *tdb, int ltype, bool mark_lock)
493 {
494         /* There are no locks on read-only dbs */
495         if (tdb->read_only || tdb->traverse_read) {
496                 tdb->ecode = TDB_ERR_LOCK;
497                 return -1;
498         }
499
500         if (tdb->global_lock.ltype != ltype || tdb->global_lock.count == 0) {
501                 tdb->ecode = TDB_ERR_LOCK;
502                 return -1;
503         }
504
505         if (tdb->global_lock.count > 1) {
506                 tdb->global_lock.count--;
507                 return 0;
508         }
509
510         if (!mark_lock &&
511             tdb->methods->brunlock(tdb, F_WRLCK,
512                                    FREELIST_TOP, 4*tdb->header.hash_size)) {
513                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlockall failed (%s)\n", strerror(errno)));
514                 return -1;
515         }
516
517         tdb->global_lock.count = 0;
518         tdb->global_lock.ltype = 0;
519
520         return 0;
521 }
522
523 /* lock entire database with write lock */
524 int tdb_lockall(struct tdb_context *tdb)
525 {
526         tdb_trace(tdb, "tdb_lockall");
527         return _tdb_lockall(tdb, F_WRLCK, TDB_LOCK_WAIT);
528 }
529
530 /* lock entire database with write lock - mark only */
531 int tdb_lockall_mark(struct tdb_context *tdb)
532 {
533         tdb_trace(tdb, "tdb_lockall_mark");
534         return _tdb_lockall(tdb, F_WRLCK, TDB_LOCK_MARK_ONLY);
535 }
536
537 /* unlock entire database with write lock - unmark only */
538 int tdb_lockall_unmark(struct tdb_context *tdb)
539 {
540         tdb_trace(tdb, "tdb_lockall_unmark");
541         return _tdb_unlockall(tdb, F_WRLCK, true);
542 }
543
544 /* lock entire database with write lock - nonblocking varient */
545 int tdb_lockall_nonblock(struct tdb_context *tdb)
546 {
547         int ret = _tdb_lockall(tdb, F_WRLCK, TDB_LOCK_NOWAIT);
548         tdb_trace_ret(tdb, "tdb_lockall_nonblock", ret);
549         return ret;
550 }
551
552 /* unlock entire database with write lock */
553 int tdb_unlockall(struct tdb_context *tdb)
554 {
555         tdb_trace(tdb, "tdb_unlockall");
556         return _tdb_unlockall(tdb, F_WRLCK, false);
557 }
558
559 /* lock entire database with read lock */
560 int tdb_lockall_read(struct tdb_context *tdb)
561 {
562         tdb_trace(tdb, "tdb_lockall_read");
563         return _tdb_lockall(tdb, F_RDLCK, TDB_LOCK_WAIT);
564 }
565
566 /* lock entire database with read lock - nonblock varient */
567 int tdb_lockall_read_nonblock(struct tdb_context *tdb)
568 {
569         int ret = _tdb_lockall(tdb, F_RDLCK, TDB_LOCK_NOWAIT);
570         tdb_trace_ret(tdb, "tdb_lockall_read_nonblock", ret);
571         return ret;
572 }
573
574 /* unlock entire database with read lock */
575 int tdb_unlockall_read(struct tdb_context *tdb)
576 {
577         tdb_trace(tdb, "tdb_unlockall_read");
578         return _tdb_unlockall(tdb, F_RDLCK, false);
579 }
580
581 /* lock/unlock one hash chain. This is meant to be used to reduce
582    contention - it cannot guarantee how many records will be locked */
583 int tdb_chainlock(struct tdb_context *tdb, TDB_DATA key)
584 {
585         int ret = tdb_lock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK);
586         tdb_trace_1rec(tdb, "tdb_chainlock", key);
587         return ret;
588 }
589
590 /* lock/unlock one hash chain, non-blocking. This is meant to be used
591    to reduce contention - it cannot guarantee how many records will be
592    locked */
593 int tdb_chainlock_nonblock(struct tdb_context *tdb, TDB_DATA key)
594 {
595         int ret = tdb_lock_nonblock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK);
596         tdb_trace_1rec_ret(tdb, "tdb_chainlock_nonblock", key, ret);
597         return ret;
598 }
599
600 /* mark a chain as locked without actually locking it. Warning! use with great caution! */
601 int tdb_chainlock_mark(struct tdb_context *tdb, TDB_DATA key)
602 {
603         int ret = _tdb_lock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK,
604                             TDB_LOCK_MARK_ONLY);
605         tdb_trace_1rec(tdb, "tdb_chainlock_mark", key);
606         return ret;
607 }
608
609 /* unmark a chain as locked without actually locking it. Warning! use with great caution! */
610 int tdb_chainlock_unmark(struct tdb_context *tdb, TDB_DATA key)
611 {
612         tdb_trace_1rec(tdb, "tdb_chainlock_unmark", key);
613         return _tdb_unlock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK, true);
614 }
615
616 int tdb_chainunlock(struct tdb_context *tdb, TDB_DATA key)
617 {
618         tdb_trace_1rec(tdb, "tdb_chainunlock", key);
619         return tdb_unlock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK);
620 }
621
622 int tdb_chainlock_read(struct tdb_context *tdb, TDB_DATA key)
623 {
624         int ret;
625         ret = tdb_lock(tdb, BUCKET(tdb->hash_fn(&key)), F_RDLCK);
626         tdb_trace_1rec(tdb, "tdb_chainlock_read", key);
627         return ret;
628 }
629
630 int tdb_chainunlock_read(struct tdb_context *tdb, TDB_DATA key)
631 {
632         tdb_trace_1rec(tdb, "tdb_chainunlock_read", key);
633         return tdb_unlock(tdb, BUCKET(tdb->hash_fn(&key)), F_RDLCK);
634 }
635
636 /* record lock stops delete underneath */
637 int tdb_lock_record(struct tdb_context *tdb, tdb_off_t off)
638 {
639         if (tdb->global_lock.count) {
640                 return 0;
641         }
642         return off ? tdb->methods->brlock(tdb, F_RDLCK, off, 1, TDB_LOCK_WAIT) : 0;
643 }
644
645 /*
646   Write locks override our own fcntl readlocks, so check it here.
647   Note this is meant to be F_SETLK, *not* F_SETLKW, as it's not
648   an error to fail to get the lock here.
649 */
650 int tdb_write_lock_record(struct tdb_context *tdb, tdb_off_t off)
651 {
652         struct tdb_traverse_lock *i;
653         for (i = &tdb->travlocks; i; i = i->next)
654                 if (i->off == off)
655                         return -1;
656         return tdb->methods->brlock(tdb, F_WRLCK, off, 1, TDB_LOCK_NOWAIT|TDB_LOCK_PROBE);
657 }
658
659 int tdb_write_unlock_record(struct tdb_context *tdb, tdb_off_t off)
660 {
661         return tdb->methods->brunlock(tdb, F_WRLCK, off, 1);
662 }
663
664 /* fcntl locks don't stack: avoid unlocking someone else's */
665 int tdb_unlock_record(struct tdb_context *tdb, tdb_off_t off)
666 {
667         struct tdb_traverse_lock *i;
668         uint32_t count = 0;
669
670         if (tdb->global_lock.count) {
671                 return 0;
672         }
673
674         if (off == 0)
675                 return 0;
676         for (i = &tdb->travlocks; i; i = i->next)
677                 if (i->off == off)
678                         count++;
679         return (count == 1 ? tdb->methods->brunlock(tdb, F_RDLCK, off, 1) : 0);
680 }