- merged ctdb_store test from ronnie
[sahlberg/ctdb.git] / lib / tdb / common / 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 2 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, write to the Free Software
26    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27 */
28
29 #include "tdb_private.h"
30
31 #define TDB_MARK_LOCK 0x80000000
32
33 /* a byte range locking function - return 0 on success
34    this functions locks/unlocks 1 byte at the specified offset.
35
36    On error, errno is also set so that errors are passed back properly
37    through tdb_open(). 
38
39    note that a len of zero means lock to end of file
40 */
41 int tdb_brlock(struct tdb_context *tdb, tdb_off_t offset, 
42                int rw_type, int lck_type, int probe, size_t len)
43 {
44         struct flock fl;
45         int ret;
46
47         if (tdb->flags & TDB_NOLOCK) {
48                 return 0;
49         }
50
51         if ((rw_type == F_WRLCK) && (tdb->read_only || tdb->traverse_read)) {
52                 tdb->ecode = TDB_ERR_RDONLY;
53                 return -1;
54         }
55
56         fl.l_type = rw_type;
57         fl.l_whence = SEEK_SET;
58         fl.l_start = offset;
59         fl.l_len = len;
60         fl.l_pid = 0;
61
62         do {
63                 ret = fcntl(tdb->fd,lck_type,&fl);
64         } while (ret == -1 && errno == EINTR);
65
66         if (ret == -1) {
67                 /* Generic lock error. errno set by fcntl.
68                  * EAGAIN is an expected return from non-blocking
69                  * locks. */
70                 if (!probe && lck_type != F_SETLK) {
71                         /* Ensure error code is set for log fun to examine. */
72                         tdb->ecode = TDB_ERR_LOCK;
73                         TDB_LOG((tdb, TDB_DEBUG_TRACE,"tdb_brlock failed (fd=%d) at offset %d rw_type=%d lck_type=%d len=%d\n", 
74                                  tdb->fd, offset, rw_type, lck_type, (int)len));
75                 }
76                 return TDB_ERRCODE(TDB_ERR_LOCK, -1);
77         }
78         return 0;
79 }
80
81
82 /*
83   upgrade a read lock to a write lock. This needs to be handled in a
84   special way as some OSes (such as solaris) have too conservative
85   deadlock detection and claim a deadlock when progress can be
86   made. For those OSes we may loop for a while.  
87 */
88 int tdb_brlock_upgrade(struct tdb_context *tdb, tdb_off_t offset, size_t len)
89 {
90         int count = 1000;
91         while (count--) {
92                 struct timeval tv;
93                 if (tdb_brlock(tdb, offset, F_WRLCK, F_SETLKW, 1, len) == 0) {
94                         return 0;
95                 }
96                 if (errno != EDEADLK) {
97                         break;
98                 }
99                 /* sleep for as short a time as we can - more portable than usleep() */
100                 tv.tv_sec = 0;
101                 tv.tv_usec = 1;
102                 select(0, NULL, NULL, NULL, &tv);
103         }
104         TDB_LOG((tdb, TDB_DEBUG_TRACE,"tdb_brlock_upgrade failed at offset %d\n", offset));
105         return -1;
106 }
107
108
109 /* lock a list in the database. list -1 is the alloc list */
110 static int _tdb_lock(struct tdb_context *tdb, int list, int ltype, int op)
111 {
112         struct tdb_lock_type *new_lck;
113         int i;
114         bool mark_lock = ((ltype & TDB_MARK_LOCK) == TDB_MARK_LOCK);
115
116         ltype &= ~TDB_MARK_LOCK;
117
118         /* a global lock allows us to avoid per chain locks */
119         if (tdb->global_lock.count && 
120             (ltype == tdb->global_lock.ltype || ltype == F_RDLCK)) {
121                 return 0;
122         }
123
124         if (tdb->global_lock.count) {
125                 return TDB_ERRCODE(TDB_ERR_LOCK, -1);
126         }
127
128         if (list < -1 || list >= (int)tdb->header.hash_size) {
129                 TDB_LOG((tdb, TDB_DEBUG_ERROR,"tdb_lock: invalid list %d for ltype=%d\n", 
130                            list, ltype));
131                 return -1;
132         }
133         if (tdb->flags & TDB_NOLOCK)
134                 return 0;
135
136         for (i=0; i<tdb->num_lockrecs; i++) {
137                 if (tdb->lockrecs[i].list == list) {
138                         if (tdb->lockrecs[i].count == 0) {
139                                 /*
140                                  * Can't happen, see tdb_unlock(). It should
141                                  * be an assert.
142                                  */
143                                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_lock: "
144                                          "lck->count == 0 for list %d", list));
145                         }
146                         /*
147                          * Just increment the in-memory struct, posix locks
148                          * don't stack.
149                          */
150                         tdb->lockrecs[i].count++;
151                         return 0;
152                 }
153         }
154
155         new_lck = (struct tdb_lock_type *)realloc(
156                 tdb->lockrecs,
157                 sizeof(*tdb->lockrecs) * (tdb->num_lockrecs+1));
158         if (new_lck == NULL) {
159                 errno = ENOMEM;
160                 return -1;
161         }
162         tdb->lockrecs = new_lck;
163
164         /* Since fcntl locks don't nest, we do a lock for the first one,
165            and simply bump the count for future ones */
166         if (!mark_lock &&
167             tdb->methods->tdb_brlock(tdb,FREELIST_TOP+4*list, ltype, op,
168                                      0, 1)) {
169                 return -1;
170         }
171
172         tdb->num_locks++;
173
174         tdb->lockrecs[tdb->num_lockrecs].list = list;
175         tdb->lockrecs[tdb->num_lockrecs].count = 1;
176         tdb->lockrecs[tdb->num_lockrecs].ltype = ltype;
177         tdb->num_lockrecs += 1;
178
179         return 0;
180 }
181
182 /* lock a list in the database. list -1 is the alloc list */
183 int tdb_lock(struct tdb_context *tdb, int list, int ltype)
184 {
185         int ret;
186         ret = _tdb_lock(tdb, list, ltype, F_SETLKW);
187         if (ret) {
188                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_lock failed on list %d "
189                          "ltype=%d (%s)\n",  list, ltype, strerror(errno)));
190         }
191         return ret;
192 }
193
194 /* lock a list in the database. list -1 is the alloc list. non-blocking lock */
195 int tdb_lock_nonblock(struct tdb_context *tdb, int list, int ltype)
196 {
197         return _tdb_lock(tdb, list, ltype, F_SETLK);
198 }
199
200
201 /* unlock the database: returns void because it's too late for errors. */
202         /* changed to return int it may be interesting to know there
203            has been an error  --simo */
204 int tdb_unlock(struct tdb_context *tdb, int list, int ltype)
205 {
206         int ret = -1;
207         int i;
208         struct tdb_lock_type *lck = NULL;
209         bool mark_lock = ((ltype & TDB_MARK_LOCK) == TDB_MARK_LOCK);
210
211         ltype &= ~TDB_MARK_LOCK;
212
213         /* a global lock allows us to avoid per chain locks */
214         if (tdb->global_lock.count && 
215             (ltype == tdb->global_lock.ltype || ltype == F_RDLCK)) {
216                 return 0;
217         }
218
219         if (tdb->global_lock.count) {
220                 return TDB_ERRCODE(TDB_ERR_LOCK, -1);
221         }
222
223         if (tdb->flags & TDB_NOLOCK)
224                 return 0;
225
226         /* Sanity checks */
227         if (list < -1 || list >= (int)tdb->header.hash_size) {
228                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlock: list %d invalid (%d)\n", list, tdb->header.hash_size));
229                 return ret;
230         }
231
232         for (i=0; i<tdb->num_lockrecs; i++) {
233                 if (tdb->lockrecs[i].list == list) {
234                         lck = &tdb->lockrecs[i];
235                         break;
236                 }
237         }
238
239         if ((lck == NULL) || (lck->count == 0)) {
240                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlock: count is 0\n"));
241                 return -1;
242         }
243
244         if (lck->count > 1) {
245                 lck->count--;
246                 return 0;
247         }
248
249         /*
250          * This lock has count==1 left, so we need to unlock it in the
251          * kernel. We don't bother with decrementing the in-memory array
252          * element, we're about to overwrite it with the last array element
253          * anyway.
254          */
255
256         if (mark_lock) {
257                 ret = 0;
258         } else {
259                 ret = tdb->methods->tdb_brlock(tdb, FREELIST_TOP+4*list, F_UNLCK,
260                                                F_SETLKW, 0, 1);
261         }
262         tdb->num_locks--;
263
264         /*
265          * Shrink the array by overwriting the element just unlocked with the
266          * last array element.
267          */
268
269         if (tdb->num_lockrecs > 1) {
270                 *lck = tdb->lockrecs[tdb->num_lockrecs-1];
271         }
272         tdb->num_lockrecs -= 1;
273
274         /*
275          * We don't bother with realloc when the array shrinks, but if we have
276          * a completely idle tdb we should get rid of the locked array.
277          */
278
279         if (tdb->num_lockrecs == 0) {
280                 SAFE_FREE(tdb->lockrecs);
281         }
282
283         if (ret)
284                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlock: An error occurred unlocking!\n")); 
285         return ret;
286 }
287
288 /*
289   get the transaction lock
290  */
291 int tdb_transaction_lock(struct tdb_context *tdb, int ltype)
292 {
293         if (tdb->have_transaction_lock || tdb->global_lock.count) {
294                 return 0;
295         }
296         if (tdb->methods->tdb_brlock(tdb, TRANSACTION_LOCK, ltype, 
297                                      F_SETLKW, 0, 1) == -1) {
298                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_transaction_lock: failed to get transaction lock\n"));
299                 tdb->ecode = TDB_ERR_LOCK;
300                 return -1;
301         }
302         tdb->have_transaction_lock = 1;
303         return 0;
304 }
305
306 /*
307   release the transaction lock
308  */
309 int tdb_transaction_unlock(struct tdb_context *tdb)
310 {
311         int ret;
312         if (!tdb->have_transaction_lock) {
313                 return 0;
314         }
315         ret = tdb->methods->tdb_brlock(tdb, TRANSACTION_LOCK, F_UNLCK, F_SETLKW, 0, 1);
316         if (ret == 0) {
317                 tdb->have_transaction_lock = 0;
318         }
319         return ret;
320 }
321
322
323
324
325 /* lock/unlock entire database */
326 static int _tdb_lockall(struct tdb_context *tdb, int ltype, int op)
327 {
328         bool mark_lock = ((ltype & TDB_MARK_LOCK) == TDB_MARK_LOCK);
329
330         ltype &= ~TDB_MARK_LOCK;
331
332         /* There are no locks on read-only dbs */
333         if (tdb->read_only || tdb->traverse_read)
334                 return TDB_ERRCODE(TDB_ERR_LOCK, -1);
335
336         if (tdb->global_lock.count && tdb->global_lock.ltype == ltype) {
337                 tdb->global_lock.count++;
338                 return 0;
339         }
340
341         if (tdb->global_lock.count) {
342                 /* a global lock of a different type exists */
343                 return TDB_ERRCODE(TDB_ERR_LOCK, -1);
344         }
345         
346         if (tdb->num_locks != 0) {
347                 /* can't combine global and chain locks */
348                 return TDB_ERRCODE(TDB_ERR_LOCK, -1);
349         }
350
351         if (!mark_lock &&
352             tdb->methods->tdb_brlock(tdb, FREELIST_TOP, ltype, op,
353                                      0, 4*tdb->header.hash_size)) {
354                 if (op == F_SETLKW) {
355                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_lockall failed (%s)\n", strerror(errno)));
356                 }
357                 return -1;
358         }
359
360         tdb->global_lock.count = 1;
361         tdb->global_lock.ltype = ltype;
362
363         return 0;
364 }
365
366
367
368 /* unlock entire db */
369 static int _tdb_unlockall(struct tdb_context *tdb, int ltype)
370 {
371         bool mark_lock = ((ltype & TDB_MARK_LOCK) == TDB_MARK_LOCK);
372
373         ltype &= ~TDB_MARK_LOCK;
374
375         /* There are no locks on read-only dbs */
376         if (tdb->read_only || tdb->traverse_read) {
377                 return TDB_ERRCODE(TDB_ERR_LOCK, -1);
378         }
379
380         if (tdb->global_lock.ltype != ltype || tdb->global_lock.count == 0) {
381                 return TDB_ERRCODE(TDB_ERR_LOCK, -1);
382         }
383
384         if (tdb->global_lock.count > 1) {
385                 tdb->global_lock.count--;
386                 return 0;
387         }
388
389         if (!mark_lock &&
390             tdb->methods->tdb_brlock(tdb, FREELIST_TOP, F_UNLCK, F_SETLKW, 
391                                      0, 4*tdb->header.hash_size)) {
392                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_unlockall failed (%s)\n", strerror(errno)));
393                 return -1;
394         }
395
396         tdb->global_lock.count = 0;
397         tdb->global_lock.ltype = 0;
398
399         return 0;
400 }
401
402 /* lock entire database with write lock */
403 int tdb_lockall(struct tdb_context *tdb)
404 {
405         return _tdb_lockall(tdb, F_WRLCK, F_SETLKW);
406 }
407
408 /* lock entire database with write lock - mark only */
409 int tdb_lockall_mark(struct tdb_context *tdb)
410 {
411         return _tdb_lockall(tdb, F_WRLCK | TDB_MARK_LOCK, F_SETLKW);
412 }
413
414 /* unlock entire database with write lock - unmark only */
415 int tdb_lockall_unmark(struct tdb_context *tdb)
416 {
417         return _tdb_unlockall(tdb, F_WRLCK | TDB_MARK_LOCK);
418 }
419
420 /* lock entire database with write lock - nonblocking varient */
421 int tdb_lockall_nonblock(struct tdb_context *tdb)
422 {
423         return _tdb_lockall(tdb, F_WRLCK, F_SETLK);
424 }
425
426 /* unlock entire database with write lock */
427 int tdb_unlockall(struct tdb_context *tdb)
428 {
429         return _tdb_unlockall(tdb, F_WRLCK);
430 }
431
432 /* lock entire database with read lock */
433 int tdb_lockall_read(struct tdb_context *tdb)
434 {
435         return _tdb_lockall(tdb, F_RDLCK, F_SETLKW);
436 }
437
438 /* lock entire database with read lock - nonblock varient */
439 int tdb_lockall_read_nonblock(struct tdb_context *tdb)
440 {
441         return _tdb_lockall(tdb, F_RDLCK, F_SETLK);
442 }
443
444 /* unlock entire database with read lock */
445 int tdb_unlockall_read(struct tdb_context *tdb)
446 {
447         return _tdb_unlockall(tdb, F_RDLCK);
448 }
449
450 /* lock/unlock one hash chain. This is meant to be used to reduce
451    contention - it cannot guarantee how many records will be locked */
452 int tdb_chainlock(struct tdb_context *tdb, TDB_DATA key)
453 {
454         return tdb_lock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK);
455 }
456
457 /* lock/unlock one hash chain, non-blocking. This is meant to be used
458    to reduce contention - it cannot guarantee how many records will be
459    locked */
460 int tdb_chainlock_nonblock(struct tdb_context *tdb, TDB_DATA key)
461 {
462         return tdb_lock_nonblock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK);
463 }
464
465 /* mark a chain as locked without actually locking it. Warning! use with great caution! */
466 int tdb_chainlock_mark(struct tdb_context *tdb, TDB_DATA key)
467 {
468         return tdb_lock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK | TDB_MARK_LOCK);
469 }
470
471 /* unmark a chain as locked without actually locking it. Warning! use with great caution! */
472 int tdb_chainlock_unmark(struct tdb_context *tdb, TDB_DATA key)
473 {
474         return tdb_unlock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK | TDB_MARK_LOCK);
475 }
476
477 int tdb_chainunlock(struct tdb_context *tdb, TDB_DATA key)
478 {
479         return tdb_unlock(tdb, BUCKET(tdb->hash_fn(&key)), F_WRLCK);
480 }
481
482 int tdb_chainlock_read(struct tdb_context *tdb, TDB_DATA key)
483 {
484         return tdb_lock(tdb, BUCKET(tdb->hash_fn(&key)), F_RDLCK);
485 }
486
487 int tdb_chainunlock_read(struct tdb_context *tdb, TDB_DATA key)
488 {
489         return tdb_unlock(tdb, BUCKET(tdb->hash_fn(&key)), F_RDLCK);
490 }
491
492
493
494 /* record lock stops delete underneath */
495 int tdb_lock_record(struct tdb_context *tdb, tdb_off_t off)
496 {
497         if (tdb->global_lock.count) {
498                 return 0;
499         }
500         return off ? tdb->methods->tdb_brlock(tdb, off, F_RDLCK, F_SETLKW, 0, 1) : 0;
501 }
502
503 /*
504   Write locks override our own fcntl readlocks, so check it here.
505   Note this is meant to be F_SETLK, *not* F_SETLKW, as it's not
506   an error to fail to get the lock here.
507 */
508 int tdb_write_lock_record(struct tdb_context *tdb, tdb_off_t off)
509 {
510         struct tdb_traverse_lock *i;
511         for (i = &tdb->travlocks; i; i = i->next)
512                 if (i->off == off)
513                         return -1;
514         return tdb->methods->tdb_brlock(tdb, off, F_WRLCK, F_SETLK, 1, 1);
515 }
516
517 /*
518   Note this is meant to be F_SETLK, *not* F_SETLKW, as it's not
519   an error to fail to get the lock here.
520 */
521 int tdb_write_unlock_record(struct tdb_context *tdb, tdb_off_t off)
522 {
523         return tdb->methods->tdb_brlock(tdb, off, F_UNLCK, F_SETLK, 0, 1);
524 }
525
526 /* fcntl locks don't stack: avoid unlocking someone else's */
527 int tdb_unlock_record(struct tdb_context *tdb, tdb_off_t off)
528 {
529         struct tdb_traverse_lock *i;
530         u32 count = 0;
531
532         if (tdb->global_lock.count) {
533                 return 0;
534         }
535
536         if (off == 0)
537                 return 0;
538         for (i = &tdb->travlocks; i; i = i->next)
539                 if (i->off == off)
540                         count++;
541         return (count == 1 ? tdb->methods->tdb_brlock(tdb, off, F_UNLCK, F_SETLKW, 0, 1) : 0);
542 }