tevent: Fix Coverity ID 989236 Operands don't affect result
[Samba/bjacke.git] / source3 / locking / brlock.c
blob865aaca1b4fa7ea0b2cfc9516d5eb06fbda73d6f
1 /*
2 Unix SMB/CIFS implementation.
3 byte range locking code
4 Updated to handle range splits/merges.
6 Copyright (C) Andrew Tridgell 1992-2000
7 Copyright (C) Jeremy Allison 1992-2000
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 /* This module implements a tdb based byte range locking service,
24 replacing the fcntl() based byte range locking previously
25 used. This allows us to provide the same semantics as NT */
27 #include "includes.h"
28 #include "system/filesys.h"
29 #include "locking/proto.h"
30 #include "smbd/globals.h"
31 #include "dbwrap/dbwrap.h"
32 #include "dbwrap/dbwrap_open.h"
33 #include "serverid.h"
34 #include "messages.h"
35 #include "util_tdb.h"
37 #undef DBGC_CLASS
38 #define DBGC_CLASS DBGC_LOCKING
40 #define ZERO_ZERO 0
42 /* The open brlock.tdb database. */
44 static struct db_context *brlock_db;
46 /****************************************************************************
47 Debug info at level 10 for lock struct.
48 ****************************************************************************/
50 static void print_lock_struct(unsigned int i, const struct lock_struct *pls)
52 DEBUG(10,("[%u]: smblctx = %llu, tid = %u, pid = %s, ",
54 (unsigned long long)pls->context.smblctx,
55 (unsigned int)pls->context.tid,
56 server_id_str(talloc_tos(), &pls->context.pid) ));
58 DEBUG(10,("start = %.0f, size = %.0f, fnum = %llu, %s %s\n",
59 (double)pls->start,
60 (double)pls->size,
61 (unsigned long long)pls->fnum,
62 lock_type_name(pls->lock_type),
63 lock_flav_name(pls->lock_flav) ));
66 /****************************************************************************
67 See if two locking contexts are equal.
68 ****************************************************************************/
70 bool brl_same_context(const struct lock_context *ctx1,
71 const struct lock_context *ctx2)
73 return (serverid_equal(&ctx1->pid, &ctx2->pid) &&
74 (ctx1->smblctx == ctx2->smblctx) &&
75 (ctx1->tid == ctx2->tid));
78 /****************************************************************************
79 See if lck1 and lck2 overlap.
80 ****************************************************************************/
82 static bool brl_overlap(const struct lock_struct *lck1,
83 const struct lock_struct *lck2)
85 /* XXX Remove for Win7 compatibility. */
86 /* this extra check is not redundant - it copes with locks
87 that go beyond the end of 64 bit file space */
88 if (lck1->size != 0 &&
89 lck1->start == lck2->start &&
90 lck1->size == lck2->size) {
91 return True;
94 if (lck1->start >= (lck2->start+lck2->size) ||
95 lck2->start >= (lck1->start+lck1->size)) {
96 return False;
98 return True;
101 /****************************************************************************
102 See if lock2 can be added when lock1 is in place.
103 ****************************************************************************/
105 static bool brl_conflict(const struct lock_struct *lck1,
106 const struct lock_struct *lck2)
108 /* Ignore PENDING locks. */
109 if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
110 return False;
112 /* Read locks never conflict. */
113 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
114 return False;
117 /* A READ lock can stack on top of a WRITE lock if they have the same
118 * context & fnum. */
119 if (lck1->lock_type == WRITE_LOCK && lck2->lock_type == READ_LOCK &&
120 brl_same_context(&lck1->context, &lck2->context) &&
121 lck1->fnum == lck2->fnum) {
122 return False;
125 return brl_overlap(lck1, lck2);
128 /****************************************************************************
129 See if lock2 can be added when lock1 is in place - when both locks are POSIX
130 flavour. POSIX locks ignore fnum - they only care about dev/ino which we
131 know already match.
132 ****************************************************************************/
134 static bool brl_conflict_posix(const struct lock_struct *lck1,
135 const struct lock_struct *lck2)
137 #if defined(DEVELOPER)
138 SMB_ASSERT(lck1->lock_flav == POSIX_LOCK);
139 SMB_ASSERT(lck2->lock_flav == POSIX_LOCK);
140 #endif
142 /* Ignore PENDING locks. */
143 if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
144 return False;
146 /* Read locks never conflict. */
147 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
148 return False;
151 /* Locks on the same context con't conflict. Ignore fnum. */
152 if (brl_same_context(&lck1->context, &lck2->context)) {
153 return False;
156 /* One is read, the other write, or the context is different,
157 do they overlap ? */
158 return brl_overlap(lck1, lck2);
161 #if ZERO_ZERO
162 static bool brl_conflict1(const struct lock_struct *lck1,
163 const struct lock_struct *lck2)
165 if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
166 return False;
168 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
169 return False;
172 if (brl_same_context(&lck1->context, &lck2->context) &&
173 lck2->lock_type == READ_LOCK && lck1->fnum == lck2->fnum) {
174 return False;
177 if (lck2->start == 0 && lck2->size == 0 && lck1->size != 0) {
178 return True;
181 if (lck1->start >= (lck2->start + lck2->size) ||
182 lck2->start >= (lck1->start + lck1->size)) {
183 return False;
186 return True;
188 #endif
190 /****************************************************************************
191 Check to see if this lock conflicts, but ignore our own locks on the
192 same fnum only. This is the read/write lock check code path.
193 This is never used in the POSIX lock case.
194 ****************************************************************************/
196 static bool brl_conflict_other(const struct lock_struct *lck1, const struct lock_struct *lck2)
198 if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
199 return False;
201 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK)
202 return False;
204 /* POSIX flavour locks never conflict here - this is only called
205 in the read/write path. */
207 if (lck1->lock_flav == POSIX_LOCK && lck2->lock_flav == POSIX_LOCK)
208 return False;
211 * Incoming WRITE locks conflict with existing READ locks even
212 * if the context is the same. JRA. See LOCKTEST7 in smbtorture.
215 if (!(lck2->lock_type == WRITE_LOCK && lck1->lock_type == READ_LOCK)) {
216 if (brl_same_context(&lck1->context, &lck2->context) &&
217 lck1->fnum == lck2->fnum)
218 return False;
221 return brl_overlap(lck1, lck2);
224 /****************************************************************************
225 Check if an unlock overlaps a pending lock.
226 ****************************************************************************/
228 static bool brl_pending_overlap(const struct lock_struct *lock, const struct lock_struct *pend_lock)
230 if ((lock->start <= pend_lock->start) && (lock->start + lock->size > pend_lock->start))
231 return True;
232 if ((lock->start >= pend_lock->start) && (lock->start <= pend_lock->start + pend_lock->size))
233 return True;
234 return False;
237 /****************************************************************************
238 Amazingly enough, w2k3 "remembers" whether the last lock failure on a fnum
239 is the same as this one and changes its error code. I wonder if any
240 app depends on this ?
241 ****************************************************************************/
243 NTSTATUS brl_lock_failed(files_struct *fsp, const struct lock_struct *lock, bool blocking_lock)
245 if (lock->start >= 0xEF000000 && (lock->start >> 63) == 0) {
246 /* amazing the little things you learn with a test
247 suite. Locks beyond this offset (as a 64 bit
248 number!) always generate the conflict error code,
249 unless the top bit is set */
250 if (!blocking_lock) {
251 fsp->last_lock_failure = *lock;
253 return NT_STATUS_FILE_LOCK_CONFLICT;
256 if (serverid_equal(&lock->context.pid, &fsp->last_lock_failure.context.pid) &&
257 lock->context.tid == fsp->last_lock_failure.context.tid &&
258 lock->fnum == fsp->last_lock_failure.fnum &&
259 lock->start == fsp->last_lock_failure.start) {
260 return NT_STATUS_FILE_LOCK_CONFLICT;
263 if (!blocking_lock) {
264 fsp->last_lock_failure = *lock;
266 return NT_STATUS_LOCK_NOT_GRANTED;
269 /****************************************************************************
270 Open up the brlock.tdb database.
271 ****************************************************************************/
273 void brl_init(bool read_only)
275 int tdb_flags;
277 if (brlock_db) {
278 return;
281 tdb_flags = TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH;
283 if (!lp_clustering()) {
285 * We can't use the SEQNUM trick to cache brlock
286 * entries in the clustering case because ctdb seqnum
287 * propagation has a delay.
289 tdb_flags |= TDB_SEQNUM;
292 brlock_db = db_open(NULL, lock_path("brlock.tdb"),
293 lp_open_files_db_hash_size(), tdb_flags,
294 read_only?O_RDONLY:(O_RDWR|O_CREAT), 0644,
295 DBWRAP_LOCK_ORDER_2);
296 if (!brlock_db) {
297 DEBUG(0,("Failed to open byte range locking database %s\n",
298 lock_path("brlock.tdb")));
299 return;
303 /****************************************************************************
304 Close down the brlock.tdb database.
305 ****************************************************************************/
307 void brl_shutdown(void)
309 TALLOC_FREE(brlock_db);
312 #if ZERO_ZERO
313 /****************************************************************************
314 Compare two locks for sorting.
315 ****************************************************************************/
317 static int lock_compare(const struct lock_struct *lck1,
318 const struct lock_struct *lck2)
320 if (lck1->start != lck2->start) {
321 return (lck1->start - lck2->start);
323 if (lck2->size != lck1->size) {
324 return ((int)lck1->size - (int)lck2->size);
326 return 0;
328 #endif
330 /****************************************************************************
331 Lock a range of bytes - Windows lock semantics.
332 ****************************************************************************/
334 NTSTATUS brl_lock_windows_default(struct byte_range_lock *br_lck,
335 struct lock_struct *plock, bool blocking_lock)
337 unsigned int i;
338 files_struct *fsp = br_lck->fsp;
339 struct lock_struct *locks = br_lck->lock_data;
340 NTSTATUS status;
342 SMB_ASSERT(plock->lock_type != UNLOCK_LOCK);
344 if ((plock->start + plock->size - 1 < plock->start) &&
345 plock->size != 0) {
346 return NT_STATUS_INVALID_LOCK_RANGE;
349 for (i=0; i < br_lck->num_locks; i++) {
350 /* Do any Windows or POSIX locks conflict ? */
351 if (brl_conflict(&locks[i], plock)) {
352 /* Remember who blocked us. */
353 plock->context.smblctx = locks[i].context.smblctx;
354 return brl_lock_failed(fsp,plock,blocking_lock);
356 #if ZERO_ZERO
357 if (plock->start == 0 && plock->size == 0 &&
358 locks[i].size == 0) {
359 break;
361 #endif
364 if (!IS_PENDING_LOCK(plock->lock_type)) {
365 contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
368 /* We can get the Windows lock, now see if it needs to
369 be mapped into a lower level POSIX one, and if so can
370 we get it ? */
372 if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(fsp->conn->params)) {
373 int errno_ret;
374 if (!set_posix_lock_windows_flavour(fsp,
375 plock->start,
376 plock->size,
377 plock->lock_type,
378 &plock->context,
379 locks,
380 br_lck->num_locks,
381 &errno_ret)) {
383 /* We don't know who blocked us. */
384 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
386 if (errno_ret == EACCES || errno_ret == EAGAIN) {
387 status = NT_STATUS_FILE_LOCK_CONFLICT;
388 goto fail;
389 } else {
390 status = map_nt_error_from_unix(errno);
391 goto fail;
396 /* no conflicts - add it to the list of locks */
397 locks = (struct lock_struct *)SMB_REALLOC(locks, (br_lck->num_locks + 1) * sizeof(*locks));
398 if (!locks) {
399 status = NT_STATUS_NO_MEMORY;
400 goto fail;
403 memcpy(&locks[br_lck->num_locks], plock, sizeof(struct lock_struct));
404 br_lck->num_locks += 1;
405 br_lck->lock_data = locks;
406 br_lck->modified = True;
408 return NT_STATUS_OK;
409 fail:
410 if (!IS_PENDING_LOCK(plock->lock_type)) {
411 contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
413 return status;
416 /****************************************************************************
417 Cope with POSIX range splits and merges.
418 ****************************************************************************/
420 static unsigned int brlock_posix_split_merge(struct lock_struct *lck_arr, /* Output array. */
421 struct lock_struct *ex, /* existing lock. */
422 struct lock_struct *plock) /* proposed lock. */
424 bool lock_types_differ = (ex->lock_type != plock->lock_type);
426 /* We can't merge non-conflicting locks on different context - ignore fnum. */
428 if (!brl_same_context(&ex->context, &plock->context)) {
429 /* Just copy. */
430 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
431 return 1;
434 /* We now know we have the same context. */
436 /* Did we overlap ? */
438 /*********************************************
439 +---------+
440 | ex |
441 +---------+
442 +-------+
443 | plock |
444 +-------+
445 OR....
446 +---------+
447 | ex |
448 +---------+
449 **********************************************/
451 if ( (ex->start > (plock->start + plock->size)) ||
452 (plock->start > (ex->start + ex->size))) {
454 /* No overlap with this lock - copy existing. */
456 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
457 return 1;
460 /*********************************************
461 +---------------------------+
462 | ex |
463 +---------------------------+
464 +---------------------------+
465 | plock | -> replace with plock.
466 +---------------------------+
468 +---------------+
469 | ex |
470 +---------------+
471 +---------------------------+
472 | plock | -> replace with plock.
473 +---------------------------+
475 **********************************************/
477 if ( (ex->start >= plock->start) &&
478 (ex->start + ex->size <= plock->start + plock->size) ) {
480 /* Replace - discard existing lock. */
482 return 0;
485 /*********************************************
486 Adjacent after.
487 +-------+
488 | ex |
489 +-------+
490 +---------------+
491 | plock |
492 +---------------+
494 BECOMES....
495 +---------------+-------+
496 | plock | ex | - different lock types.
497 +---------------+-------+
498 OR.... (merge)
499 +-----------------------+
500 | plock | - same lock type.
501 +-----------------------+
502 **********************************************/
504 if (plock->start + plock->size == ex->start) {
506 /* If the lock types are the same, we merge, if different, we
507 add the remainder of the old lock. */
509 if (lock_types_differ) {
510 /* Add existing. */
511 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
512 return 1;
513 } else {
514 /* Merge - adjust incoming lock as we may have more
515 * merging to come. */
516 plock->size += ex->size;
517 return 0;
521 /*********************************************
522 Adjacent before.
523 +-------+
524 | ex |
525 +-------+
526 +---------------+
527 | plock |
528 +---------------+
529 BECOMES....
530 +-------+---------------+
531 | ex | plock | - different lock types
532 +-------+---------------+
534 OR.... (merge)
535 +-----------------------+
536 | plock | - same lock type.
537 +-----------------------+
539 **********************************************/
541 if (ex->start + ex->size == plock->start) {
543 /* If the lock types are the same, we merge, if different, we
544 add the existing lock. */
546 if (lock_types_differ) {
547 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
548 return 1;
549 } else {
550 /* Merge - adjust incoming lock as we may have more
551 * merging to come. */
552 plock->start = ex->start;
553 plock->size += ex->size;
554 return 0;
558 /*********************************************
559 Overlap after.
560 +-----------------------+
561 | ex |
562 +-----------------------+
563 +---------------+
564 | plock |
565 +---------------+
567 +----------------+
568 | ex |
569 +----------------+
570 +---------------+
571 | plock |
572 +---------------+
574 BECOMES....
575 +---------------+-------+
576 | plock | ex | - different lock types.
577 +---------------+-------+
578 OR.... (merge)
579 +-----------------------+
580 | plock | - same lock type.
581 +-----------------------+
582 **********************************************/
584 if ( (ex->start >= plock->start) &&
585 (ex->start <= plock->start + plock->size) &&
586 (ex->start + ex->size > plock->start + plock->size) ) {
588 /* If the lock types are the same, we merge, if different, we
589 add the remainder of the old lock. */
591 if (lock_types_differ) {
592 /* Add remaining existing. */
593 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
594 /* Adjust existing start and size. */
595 lck_arr[0].start = plock->start + plock->size;
596 lck_arr[0].size = (ex->start + ex->size) - (plock->start + plock->size);
597 return 1;
598 } else {
599 /* Merge - adjust incoming lock as we may have more
600 * merging to come. */
601 plock->size += (ex->start + ex->size) - (plock->start + plock->size);
602 return 0;
606 /*********************************************
607 Overlap before.
608 +-----------------------+
609 | ex |
610 +-----------------------+
611 +---------------+
612 | plock |
613 +---------------+
615 +-------------+
616 | ex |
617 +-------------+
618 +---------------+
619 | plock |
620 +---------------+
622 BECOMES....
623 +-------+---------------+
624 | ex | plock | - different lock types
625 +-------+---------------+
627 OR.... (merge)
628 +-----------------------+
629 | plock | - same lock type.
630 +-----------------------+
632 **********************************************/
634 if ( (ex->start < plock->start) &&
635 (ex->start + ex->size >= plock->start) &&
636 (ex->start + ex->size <= plock->start + plock->size) ) {
638 /* If the lock types are the same, we merge, if different, we
639 add the truncated old lock. */
641 if (lock_types_differ) {
642 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
643 /* Adjust existing size. */
644 lck_arr[0].size = plock->start - ex->start;
645 return 1;
646 } else {
647 /* Merge - adjust incoming lock as we may have more
648 * merging to come. MUST ADJUST plock SIZE FIRST ! */
649 plock->size += (plock->start - ex->start);
650 plock->start = ex->start;
651 return 0;
655 /*********************************************
656 Complete overlap.
657 +---------------------------+
658 | ex |
659 +---------------------------+
660 +---------+
661 | plock |
662 +---------+
663 BECOMES.....
664 +-------+---------+---------+
665 | ex | plock | ex | - different lock types.
666 +-------+---------+---------+
668 +---------------------------+
669 | plock | - same lock type.
670 +---------------------------+
671 **********************************************/
673 if ( (ex->start < plock->start) && (ex->start + ex->size > plock->start + plock->size) ) {
675 if (lock_types_differ) {
677 /* We have to split ex into two locks here. */
679 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
680 memcpy(&lck_arr[1], ex, sizeof(struct lock_struct));
682 /* Adjust first existing size. */
683 lck_arr[0].size = plock->start - ex->start;
685 /* Adjust second existing start and size. */
686 lck_arr[1].start = plock->start + plock->size;
687 lck_arr[1].size = (ex->start + ex->size) - (plock->start + plock->size);
688 return 2;
689 } else {
690 /* Just eat the existing locks, merge them into plock. */
691 plock->start = ex->start;
692 plock->size = ex->size;
693 return 0;
697 /* Never get here. */
698 smb_panic("brlock_posix_split_merge");
699 /* Notreached. */
701 /* Keep some compilers happy. */
702 return 0;
705 /****************************************************************************
706 Lock a range of bytes - POSIX lock semantics.
707 We must cope with range splits and merges.
708 ****************************************************************************/
710 static NTSTATUS brl_lock_posix(struct messaging_context *msg_ctx,
711 struct byte_range_lock *br_lck,
712 struct lock_struct *plock)
714 unsigned int i, count, posix_count;
715 struct lock_struct *locks = br_lck->lock_data;
716 struct lock_struct *tp;
717 bool signal_pending_read = False;
718 bool break_oplocks = false;
719 NTSTATUS status;
721 /* No zero-zero locks for POSIX. */
722 if (plock->start == 0 && plock->size == 0) {
723 return NT_STATUS_INVALID_PARAMETER;
726 /* Don't allow 64-bit lock wrap. */
727 if (plock->start + plock->size - 1 < plock->start) {
728 return NT_STATUS_INVALID_PARAMETER;
731 /* The worst case scenario here is we have to split an
732 existing POSIX lock range into two, and add our lock,
733 so we need at most 2 more entries. */
735 tp = SMB_MALLOC_ARRAY(struct lock_struct, (br_lck->num_locks + 2));
736 if (!tp) {
737 return NT_STATUS_NO_MEMORY;
740 count = posix_count = 0;
742 for (i=0; i < br_lck->num_locks; i++) {
743 struct lock_struct *curr_lock = &locks[i];
745 /* If we have a pending read lock, a lock downgrade should
746 trigger a lock re-evaluation. */
747 if (curr_lock->lock_type == PENDING_READ_LOCK &&
748 brl_pending_overlap(plock, curr_lock)) {
749 signal_pending_read = True;
752 if (curr_lock->lock_flav == WINDOWS_LOCK) {
753 /* Do any Windows flavour locks conflict ? */
754 if (brl_conflict(curr_lock, plock)) {
755 /* No games with error messages. */
756 SAFE_FREE(tp);
757 /* Remember who blocked us. */
758 plock->context.smblctx = curr_lock->context.smblctx;
759 return NT_STATUS_FILE_LOCK_CONFLICT;
761 /* Just copy the Windows lock into the new array. */
762 memcpy(&tp[count], curr_lock, sizeof(struct lock_struct));
763 count++;
764 } else {
765 unsigned int tmp_count = 0;
767 /* POSIX conflict semantics are different. */
768 if (brl_conflict_posix(curr_lock, plock)) {
769 /* Can't block ourselves with POSIX locks. */
770 /* No games with error messages. */
771 SAFE_FREE(tp);
772 /* Remember who blocked us. */
773 plock->context.smblctx = curr_lock->context.smblctx;
774 return NT_STATUS_FILE_LOCK_CONFLICT;
777 /* Work out overlaps. */
778 tmp_count += brlock_posix_split_merge(&tp[count], curr_lock, plock);
779 posix_count += tmp_count;
780 count += tmp_count;
785 * Break oplocks while we hold a brl. Since lock() and unlock() calls
786 * are not symetric with POSIX semantics, we cannot guarantee our
787 * contend_level2_oplocks_begin/end calls will be acquired and
788 * released one-for-one as with Windows semantics. Therefore we only
789 * call contend_level2_oplocks_begin if this is the first POSIX brl on
790 * the file.
792 break_oplocks = (!IS_PENDING_LOCK(plock->lock_type) &&
793 posix_count == 0);
794 if (break_oplocks) {
795 contend_level2_oplocks_begin(br_lck->fsp,
796 LEVEL2_CONTEND_POSIX_BRL);
799 /* Try and add the lock in order, sorted by lock start. */
800 for (i=0; i < count; i++) {
801 struct lock_struct *curr_lock = &tp[i];
803 if (curr_lock->start <= plock->start) {
804 continue;
808 if (i < count) {
809 memmove(&tp[i+1], &tp[i],
810 (count - i)*sizeof(struct lock_struct));
812 memcpy(&tp[i], plock, sizeof(struct lock_struct));
813 count++;
815 /* We can get the POSIX lock, now see if it needs to
816 be mapped into a lower level POSIX one, and if so can
817 we get it ? */
819 if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(br_lck->fsp->conn->params)) {
820 int errno_ret;
822 /* The lower layer just needs to attempt to
823 get the system POSIX lock. We've weeded out
824 any conflicts above. */
826 if (!set_posix_lock_posix_flavour(br_lck->fsp,
827 plock->start,
828 plock->size,
829 plock->lock_type,
830 &errno_ret)) {
832 /* We don't know who blocked us. */
833 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
835 if (errno_ret == EACCES || errno_ret == EAGAIN) {
836 SAFE_FREE(tp);
837 status = NT_STATUS_FILE_LOCK_CONFLICT;
838 goto fail;
839 } else {
840 SAFE_FREE(tp);
841 status = map_nt_error_from_unix(errno);
842 goto fail;
847 /* If we didn't use all the allocated size,
848 * Realloc so we don't leak entries per lock call. */
849 if (count < br_lck->num_locks + 2) {
850 tp = (struct lock_struct *)SMB_REALLOC(tp, count * sizeof(*locks));
851 if (!tp) {
852 status = NT_STATUS_NO_MEMORY;
853 goto fail;
857 br_lck->num_locks = count;
858 SAFE_FREE(br_lck->lock_data);
859 br_lck->lock_data = tp;
860 locks = tp;
861 br_lck->modified = True;
863 /* A successful downgrade from write to read lock can trigger a lock
864 re-evalutation where waiting readers can now proceed. */
866 if (signal_pending_read) {
867 /* Send unlock messages to any pending read waiters that overlap. */
868 for (i=0; i < br_lck->num_locks; i++) {
869 struct lock_struct *pend_lock = &locks[i];
871 /* Ignore non-pending locks. */
872 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
873 continue;
876 if (pend_lock->lock_type == PENDING_READ_LOCK &&
877 brl_pending_overlap(plock, pend_lock)) {
878 DEBUG(10,("brl_lock_posix: sending unlock message to pid %s\n",
879 procid_str_static(&pend_lock->context.pid )));
881 messaging_send(msg_ctx, pend_lock->context.pid,
882 MSG_SMB_UNLOCK, &data_blob_null);
887 return NT_STATUS_OK;
888 fail:
889 if (break_oplocks) {
890 contend_level2_oplocks_end(br_lck->fsp,
891 LEVEL2_CONTEND_POSIX_BRL);
893 return status;
896 NTSTATUS smb_vfs_call_brl_lock_windows(struct vfs_handle_struct *handle,
897 struct byte_range_lock *br_lck,
898 struct lock_struct *plock,
899 bool blocking_lock,
900 struct blocking_lock_record *blr)
902 VFS_FIND(brl_lock_windows);
903 return handle->fns->brl_lock_windows_fn(handle, br_lck, plock,
904 blocking_lock, blr);
907 /****************************************************************************
908 Lock a range of bytes.
909 ****************************************************************************/
911 NTSTATUS brl_lock(struct messaging_context *msg_ctx,
912 struct byte_range_lock *br_lck,
913 uint64_t smblctx,
914 struct server_id pid,
915 br_off start,
916 br_off size,
917 enum brl_type lock_type,
918 enum brl_flavour lock_flav,
919 bool blocking_lock,
920 uint64_t *psmblctx,
921 struct blocking_lock_record *blr)
923 NTSTATUS ret;
924 struct lock_struct lock;
926 #if !ZERO_ZERO
927 if (start == 0 && size == 0) {
928 DEBUG(0,("client sent 0/0 lock - please report this\n"));
930 #endif
932 #ifdef DEVELOPER
933 /* Quieten valgrind on test. */
934 memset(&lock, '\0', sizeof(lock));
935 #endif
937 lock.context.smblctx = smblctx;
938 lock.context.pid = pid;
939 lock.context.tid = br_lck->fsp->conn->cnum;
940 lock.start = start;
941 lock.size = size;
942 lock.fnum = br_lck->fsp->fnum;
943 lock.lock_type = lock_type;
944 lock.lock_flav = lock_flav;
946 if (lock_flav == WINDOWS_LOCK) {
947 ret = SMB_VFS_BRL_LOCK_WINDOWS(br_lck->fsp->conn, br_lck,
948 &lock, blocking_lock, blr);
949 } else {
950 ret = brl_lock_posix(msg_ctx, br_lck, &lock);
953 #if ZERO_ZERO
954 /* sort the lock list */
955 TYPESAFE_QSORT(br_lck->lock_data, (size_t)br_lck->num_locks, lock_compare);
956 #endif
958 /* If we're returning an error, return who blocked us. */
959 if (!NT_STATUS_IS_OK(ret) && psmblctx) {
960 *psmblctx = lock.context.smblctx;
962 return ret;
965 /****************************************************************************
966 Unlock a range of bytes - Windows semantics.
967 ****************************************************************************/
969 bool brl_unlock_windows_default(struct messaging_context *msg_ctx,
970 struct byte_range_lock *br_lck,
971 const struct lock_struct *plock)
973 unsigned int i, j;
974 struct lock_struct *locks = br_lck->lock_data;
975 enum brl_type deleted_lock_type = READ_LOCK; /* shut the compiler up.... */
977 SMB_ASSERT(plock->lock_type == UNLOCK_LOCK);
979 #if ZERO_ZERO
980 /* Delete write locks by preference... The lock list
981 is sorted in the zero zero case. */
983 for (i = 0; i < br_lck->num_locks; i++) {
984 struct lock_struct *lock = &locks[i];
986 if (lock->lock_type == WRITE_LOCK &&
987 brl_same_context(&lock->context, &plock->context) &&
988 lock->fnum == plock->fnum &&
989 lock->lock_flav == WINDOWS_LOCK &&
990 lock->start == plock->start &&
991 lock->size == plock->size) {
993 /* found it - delete it */
994 deleted_lock_type = lock->lock_type;
995 break;
999 if (i != br_lck->num_locks) {
1000 /* We found it - don't search again. */
1001 goto unlock_continue;
1003 #endif
1005 for (i = 0; i < br_lck->num_locks; i++) {
1006 struct lock_struct *lock = &locks[i];
1008 if (IS_PENDING_LOCK(lock->lock_type)) {
1009 continue;
1012 /* Only remove our own locks that match in start, size, and flavour. */
1013 if (brl_same_context(&lock->context, &plock->context) &&
1014 lock->fnum == plock->fnum &&
1015 lock->lock_flav == WINDOWS_LOCK &&
1016 lock->start == plock->start &&
1017 lock->size == plock->size ) {
1018 deleted_lock_type = lock->lock_type;
1019 break;
1023 if (i == br_lck->num_locks) {
1024 /* we didn't find it */
1025 return False;
1028 #if ZERO_ZERO
1029 unlock_continue:
1030 #endif
1032 /* Actually delete the lock. */
1033 if (i < br_lck->num_locks - 1) {
1034 memmove(&locks[i], &locks[i+1],
1035 sizeof(*locks)*((br_lck->num_locks-1) - i));
1038 br_lck->num_locks -= 1;
1039 br_lck->modified = True;
1041 /* Unlock the underlying POSIX regions. */
1042 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1043 release_posix_lock_windows_flavour(br_lck->fsp,
1044 plock->start,
1045 plock->size,
1046 deleted_lock_type,
1047 &plock->context,
1048 locks,
1049 br_lck->num_locks);
1052 /* Send unlock messages to any pending waiters that overlap. */
1053 for (j=0; j < br_lck->num_locks; j++) {
1054 struct lock_struct *pend_lock = &locks[j];
1056 /* Ignore non-pending locks. */
1057 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1058 continue;
1061 /* We could send specific lock info here... */
1062 if (brl_pending_overlap(plock, pend_lock)) {
1063 DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
1064 procid_str_static(&pend_lock->context.pid )));
1066 messaging_send(msg_ctx, pend_lock->context.pid,
1067 MSG_SMB_UNLOCK, &data_blob_null);
1071 contend_level2_oplocks_end(br_lck->fsp, LEVEL2_CONTEND_WINDOWS_BRL);
1072 return True;
1075 /****************************************************************************
1076 Unlock a range of bytes - POSIX semantics.
1077 ****************************************************************************/
1079 static bool brl_unlock_posix(struct messaging_context *msg_ctx,
1080 struct byte_range_lock *br_lck,
1081 struct lock_struct *plock)
1083 unsigned int i, j, count;
1084 struct lock_struct *tp;
1085 struct lock_struct *locks = br_lck->lock_data;
1086 bool overlap_found = False;
1088 /* No zero-zero locks for POSIX. */
1089 if (plock->start == 0 && plock->size == 0) {
1090 return False;
1093 /* Don't allow 64-bit lock wrap. */
1094 if (plock->start + plock->size < plock->start ||
1095 plock->start + plock->size < plock->size) {
1096 DEBUG(10,("brl_unlock_posix: lock wrap\n"));
1097 return False;
1100 /* The worst case scenario here is we have to split an
1101 existing POSIX lock range into two, so we need at most
1102 1 more entry. */
1104 tp = SMB_MALLOC_ARRAY(struct lock_struct, (br_lck->num_locks + 1));
1105 if (!tp) {
1106 DEBUG(10,("brl_unlock_posix: malloc fail\n"));
1107 return False;
1110 count = 0;
1111 for (i = 0; i < br_lck->num_locks; i++) {
1112 struct lock_struct *lock = &locks[i];
1113 unsigned int tmp_count;
1115 /* Only remove our own locks - ignore fnum. */
1116 if (IS_PENDING_LOCK(lock->lock_type) ||
1117 !brl_same_context(&lock->context, &plock->context)) {
1118 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1119 count++;
1120 continue;
1123 if (lock->lock_flav == WINDOWS_LOCK) {
1124 /* Do any Windows flavour locks conflict ? */
1125 if (brl_conflict(lock, plock)) {
1126 SAFE_FREE(tp);
1127 return false;
1129 /* Just copy the Windows lock into the new array. */
1130 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1131 count++;
1132 continue;
1135 /* Work out overlaps. */
1136 tmp_count = brlock_posix_split_merge(&tp[count], lock, plock);
1138 if (tmp_count == 0) {
1139 /* plock overlapped the existing lock completely,
1140 or replaced it. Don't copy the existing lock. */
1141 overlap_found = true;
1142 } else if (tmp_count == 1) {
1143 /* Either no overlap, (simple copy of existing lock) or
1144 * an overlap of an existing lock. */
1145 /* If the lock changed size, we had an overlap. */
1146 if (tp[count].size != lock->size) {
1147 overlap_found = true;
1149 count += tmp_count;
1150 } else if (tmp_count == 2) {
1151 /* We split a lock range in two. */
1152 overlap_found = true;
1153 count += tmp_count;
1155 /* Optimisation... */
1156 /* We know we're finished here as we can't overlap any
1157 more POSIX locks. Copy the rest of the lock array. */
1159 if (i < br_lck->num_locks - 1) {
1160 memcpy(&tp[count], &locks[i+1],
1161 sizeof(*locks)*((br_lck->num_locks-1) - i));
1162 count += ((br_lck->num_locks-1) - i);
1164 break;
1169 if (!overlap_found) {
1170 /* Just ignore - no change. */
1171 SAFE_FREE(tp);
1172 DEBUG(10,("brl_unlock_posix: No overlap - unlocked.\n"));
1173 return True;
1176 /* Unlock any POSIX regions. */
1177 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1178 release_posix_lock_posix_flavour(br_lck->fsp,
1179 plock->start,
1180 plock->size,
1181 &plock->context,
1183 count);
1186 /* Realloc so we don't leak entries per unlock call. */
1187 if (count) {
1188 tp = (struct lock_struct *)SMB_REALLOC(tp, count * sizeof(*locks));
1189 if (!tp) {
1190 DEBUG(10,("brl_unlock_posix: realloc fail\n"));
1191 return False;
1193 } else {
1194 /* We deleted the last lock. */
1195 SAFE_FREE(tp);
1196 tp = NULL;
1199 contend_level2_oplocks_end(br_lck->fsp,
1200 LEVEL2_CONTEND_POSIX_BRL);
1202 br_lck->num_locks = count;
1203 SAFE_FREE(br_lck->lock_data);
1204 locks = tp;
1205 br_lck->lock_data = tp;
1206 br_lck->modified = True;
1208 /* Send unlock messages to any pending waiters that overlap. */
1210 for (j=0; j < br_lck->num_locks; j++) {
1211 struct lock_struct *pend_lock = &locks[j];
1213 /* Ignore non-pending locks. */
1214 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1215 continue;
1218 /* We could send specific lock info here... */
1219 if (brl_pending_overlap(plock, pend_lock)) {
1220 DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
1221 procid_str_static(&pend_lock->context.pid )));
1223 messaging_send(msg_ctx, pend_lock->context.pid,
1224 MSG_SMB_UNLOCK, &data_blob_null);
1228 return True;
1231 bool smb_vfs_call_brl_unlock_windows(struct vfs_handle_struct *handle,
1232 struct messaging_context *msg_ctx,
1233 struct byte_range_lock *br_lck,
1234 const struct lock_struct *plock)
1236 VFS_FIND(brl_unlock_windows);
1237 return handle->fns->brl_unlock_windows_fn(handle, msg_ctx, br_lck,
1238 plock);
1241 /****************************************************************************
1242 Unlock a range of bytes.
1243 ****************************************************************************/
1245 bool brl_unlock(struct messaging_context *msg_ctx,
1246 struct byte_range_lock *br_lck,
1247 uint64_t smblctx,
1248 struct server_id pid,
1249 br_off start,
1250 br_off size,
1251 enum brl_flavour lock_flav)
1253 struct lock_struct lock;
1255 lock.context.smblctx = smblctx;
1256 lock.context.pid = pid;
1257 lock.context.tid = br_lck->fsp->conn->cnum;
1258 lock.start = start;
1259 lock.size = size;
1260 lock.fnum = br_lck->fsp->fnum;
1261 lock.lock_type = UNLOCK_LOCK;
1262 lock.lock_flav = lock_flav;
1264 if (lock_flav == WINDOWS_LOCK) {
1265 return SMB_VFS_BRL_UNLOCK_WINDOWS(br_lck->fsp->conn, msg_ctx,
1266 br_lck, &lock);
1267 } else {
1268 return brl_unlock_posix(msg_ctx, br_lck, &lock);
1272 /****************************************************************************
1273 Test if we could add a lock if we wanted to.
1274 Returns True if the region required is currently unlocked, False if locked.
1275 ****************************************************************************/
1277 bool brl_locktest(struct byte_range_lock *br_lck,
1278 uint64_t smblctx,
1279 struct server_id pid,
1280 br_off start,
1281 br_off size,
1282 enum brl_type lock_type,
1283 enum brl_flavour lock_flav)
1285 bool ret = True;
1286 unsigned int i;
1287 struct lock_struct lock;
1288 const struct lock_struct *locks = br_lck->lock_data;
1289 files_struct *fsp = br_lck->fsp;
1291 lock.context.smblctx = smblctx;
1292 lock.context.pid = pid;
1293 lock.context.tid = br_lck->fsp->conn->cnum;
1294 lock.start = start;
1295 lock.size = size;
1296 lock.fnum = fsp->fnum;
1297 lock.lock_type = lock_type;
1298 lock.lock_flav = lock_flav;
1300 /* Make sure existing locks don't conflict */
1301 for (i=0; i < br_lck->num_locks; i++) {
1303 * Our own locks don't conflict.
1305 if (brl_conflict_other(&locks[i], &lock)) {
1306 return False;
1311 * There is no lock held by an SMB daemon, check to
1312 * see if there is a POSIX lock from a UNIX or NFS process.
1313 * This only conflicts with Windows locks, not POSIX locks.
1316 if(lp_posix_locking(fsp->conn->params) && (lock_flav == WINDOWS_LOCK)) {
1317 ret = is_posix_locked(fsp, &start, &size, &lock_type, WINDOWS_LOCK);
1319 DEBUG(10,("brl_locktest: posix start=%.0f len=%.0f %s for %s file %s\n",
1320 (double)start, (double)size, ret ? "locked" : "unlocked",
1321 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1323 /* We need to return the inverse of is_posix_locked. */
1324 ret = !ret;
1327 /* no conflicts - we could have added it */
1328 return ret;
1331 /****************************************************************************
1332 Query for existing locks.
1333 ****************************************************************************/
1335 NTSTATUS brl_lockquery(struct byte_range_lock *br_lck,
1336 uint64_t *psmblctx,
1337 struct server_id pid,
1338 br_off *pstart,
1339 br_off *psize,
1340 enum brl_type *plock_type,
1341 enum brl_flavour lock_flav)
1343 unsigned int i;
1344 struct lock_struct lock;
1345 const struct lock_struct *locks = br_lck->lock_data;
1346 files_struct *fsp = br_lck->fsp;
1348 lock.context.smblctx = *psmblctx;
1349 lock.context.pid = pid;
1350 lock.context.tid = br_lck->fsp->conn->cnum;
1351 lock.start = *pstart;
1352 lock.size = *psize;
1353 lock.fnum = fsp->fnum;
1354 lock.lock_type = *plock_type;
1355 lock.lock_flav = lock_flav;
1357 /* Make sure existing locks don't conflict */
1358 for (i=0; i < br_lck->num_locks; i++) {
1359 const struct lock_struct *exlock = &locks[i];
1360 bool conflict = False;
1362 if (exlock->lock_flav == WINDOWS_LOCK) {
1363 conflict = brl_conflict(exlock, &lock);
1364 } else {
1365 conflict = brl_conflict_posix(exlock, &lock);
1368 if (conflict) {
1369 *psmblctx = exlock->context.smblctx;
1370 *pstart = exlock->start;
1371 *psize = exlock->size;
1372 *plock_type = exlock->lock_type;
1373 return NT_STATUS_LOCK_NOT_GRANTED;
1378 * There is no lock held by an SMB daemon, check to
1379 * see if there is a POSIX lock from a UNIX or NFS process.
1382 if(lp_posix_locking(fsp->conn->params)) {
1383 bool ret = is_posix_locked(fsp, pstart, psize, plock_type, POSIX_LOCK);
1385 DEBUG(10,("brl_lockquery: posix start=%.0f len=%.0f %s for %s file %s\n",
1386 (double)*pstart, (double)*psize, ret ? "locked" : "unlocked",
1387 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1389 if (ret) {
1390 /* Hmmm. No clue what to set smblctx to - use -1. */
1391 *psmblctx = 0xFFFFFFFFFFFFFFFFLL;
1392 return NT_STATUS_LOCK_NOT_GRANTED;
1396 return NT_STATUS_OK;
1400 bool smb_vfs_call_brl_cancel_windows(struct vfs_handle_struct *handle,
1401 struct byte_range_lock *br_lck,
1402 struct lock_struct *plock,
1403 struct blocking_lock_record *blr)
1405 VFS_FIND(brl_cancel_windows);
1406 return handle->fns->brl_cancel_windows_fn(handle, br_lck, plock, blr);
1409 /****************************************************************************
1410 Remove a particular pending lock.
1411 ****************************************************************************/
1412 bool brl_lock_cancel(struct byte_range_lock *br_lck,
1413 uint64_t smblctx,
1414 struct server_id pid,
1415 br_off start,
1416 br_off size,
1417 enum brl_flavour lock_flav,
1418 struct blocking_lock_record *blr)
1420 bool ret;
1421 struct lock_struct lock;
1423 lock.context.smblctx = smblctx;
1424 lock.context.pid = pid;
1425 lock.context.tid = br_lck->fsp->conn->cnum;
1426 lock.start = start;
1427 lock.size = size;
1428 lock.fnum = br_lck->fsp->fnum;
1429 lock.lock_flav = lock_flav;
1430 /* lock.lock_type doesn't matter */
1432 if (lock_flav == WINDOWS_LOCK) {
1433 ret = SMB_VFS_BRL_CANCEL_WINDOWS(br_lck->fsp->conn, br_lck,
1434 &lock, blr);
1435 } else {
1436 ret = brl_lock_cancel_default(br_lck, &lock);
1439 return ret;
1442 bool brl_lock_cancel_default(struct byte_range_lock *br_lck,
1443 struct lock_struct *plock)
1445 unsigned int i;
1446 struct lock_struct *locks = br_lck->lock_data;
1448 SMB_ASSERT(plock);
1450 for (i = 0; i < br_lck->num_locks; i++) {
1451 struct lock_struct *lock = &locks[i];
1453 /* For pending locks we *always* care about the fnum. */
1454 if (brl_same_context(&lock->context, &plock->context) &&
1455 lock->fnum == plock->fnum &&
1456 IS_PENDING_LOCK(lock->lock_type) &&
1457 lock->lock_flav == plock->lock_flav &&
1458 lock->start == plock->start &&
1459 lock->size == plock->size) {
1460 break;
1464 if (i == br_lck->num_locks) {
1465 /* Didn't find it. */
1466 return False;
1469 if (i < br_lck->num_locks - 1) {
1470 /* Found this particular pending lock - delete it */
1471 memmove(&locks[i], &locks[i+1],
1472 sizeof(*locks)*((br_lck->num_locks-1) - i));
1475 br_lck->num_locks -= 1;
1476 br_lck->modified = True;
1477 return True;
1480 /****************************************************************************
1481 Remove any locks associated with a open file.
1482 We return True if this process owns any other Windows locks on this
1483 fd and so we should not immediately close the fd.
1484 ****************************************************************************/
1486 void brl_close_fnum(struct messaging_context *msg_ctx,
1487 struct byte_range_lock *br_lck)
1489 files_struct *fsp = br_lck->fsp;
1490 uint32_t tid = fsp->conn->cnum;
1491 uint64_t fnum = fsp->fnum;
1492 unsigned int i;
1493 struct lock_struct *locks = br_lck->lock_data;
1494 struct server_id pid = messaging_server_id(fsp->conn->sconn->msg_ctx);
1495 struct lock_struct *locks_copy;
1496 unsigned int num_locks_copy;
1498 /* Copy the current lock array. */
1499 if (br_lck->num_locks) {
1500 locks_copy = (struct lock_struct *)talloc_memdup(br_lck, locks, br_lck->num_locks * sizeof(struct lock_struct));
1501 if (!locks_copy) {
1502 smb_panic("brl_close_fnum: talloc failed");
1504 } else {
1505 locks_copy = NULL;
1508 num_locks_copy = br_lck->num_locks;
1510 for (i=0; i < num_locks_copy; i++) {
1511 struct lock_struct *lock = &locks_copy[i];
1513 if (lock->context.tid == tid && serverid_equal(&lock->context.pid, &pid) &&
1514 (lock->fnum == fnum)) {
1515 brl_unlock(msg_ctx,
1516 br_lck,
1517 lock->context.smblctx,
1518 pid,
1519 lock->start,
1520 lock->size,
1521 lock->lock_flav);
1526 bool brl_mark_disconnected(struct files_struct *fsp)
1528 uint32_t tid = fsp->conn->cnum;
1529 uint64_t smblctx = fsp->op->global->open_persistent_id;
1530 uint64_t fnum = fsp->fnum;
1531 unsigned int i;
1532 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1533 struct byte_range_lock *br_lck = NULL;
1535 if (!fsp->op->global->durable) {
1536 return false;
1539 if (fsp->current_lock_count == 0) {
1540 return true;
1543 br_lck = brl_get_locks(talloc_tos(), fsp);
1544 if (br_lck == NULL) {
1545 return false;
1548 for (i=0; i < br_lck->num_locks; i++) {
1549 struct lock_struct *lock = &br_lck->lock_data[i];
1552 * as this is a durable handle, we only expect locks
1553 * of the current file handle!
1556 if (lock->context.smblctx != smblctx) {
1557 TALLOC_FREE(br_lck);
1558 return false;
1561 if (lock->context.tid != tid) {
1562 TALLOC_FREE(br_lck);
1563 return false;
1566 if (!serverid_equal(&lock->context.pid, &self)) {
1567 TALLOC_FREE(br_lck);
1568 return false;
1571 if (lock->fnum != fnum) {
1572 TALLOC_FREE(br_lck);
1573 return false;
1576 server_id_set_disconnected(&lock->context.pid);
1577 lock->context.tid = TID_FIELD_INVALID;
1578 lock->fnum = FNUM_FIELD_INVALID;
1581 br_lck->modified = true;
1582 TALLOC_FREE(br_lck);
1583 return true;
1586 bool brl_reconnect_disconnected(struct files_struct *fsp)
1588 uint32_t tid = fsp->conn->cnum;
1589 uint64_t smblctx = fsp->op->global->open_persistent_id;
1590 uint64_t fnum = fsp->fnum;
1591 unsigned int i;
1592 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1593 struct byte_range_lock *br_lck = NULL;
1595 if (!fsp->op->global->durable) {
1596 return false;
1600 * When reconnecting, we do not want to validate the brlock entries
1601 * and thereby remove our own (disconnected) entries but reactivate
1602 * them instead.
1604 fsp->lockdb_clean = true;
1606 br_lck = brl_get_locks(talloc_tos(), fsp);
1607 if (br_lck == NULL) {
1608 return false;
1611 if (br_lck->num_locks == 0) {
1612 TALLOC_FREE(br_lck);
1613 return true;
1616 for (i=0; i < br_lck->num_locks; i++) {
1617 struct lock_struct *lock = &br_lck->lock_data[i];
1620 * as this is a durable handle we only expect locks
1621 * of the current file handle!
1624 if (lock->context.smblctx != smblctx) {
1625 TALLOC_FREE(br_lck);
1626 return false;
1629 if (lock->context.tid != TID_FIELD_INVALID) {
1630 TALLOC_FREE(br_lck);
1631 return false;
1634 if (!server_id_is_disconnected(&lock->context.pid)) {
1635 TALLOC_FREE(br_lck);
1636 return false;
1639 if (lock->fnum != FNUM_FIELD_INVALID) {
1640 TALLOC_FREE(br_lck);
1641 return false;
1644 lock->context.pid = self;
1645 lock->context.tid = tid;
1646 lock->fnum = fnum;
1649 fsp->current_lock_count = br_lck->num_locks;
1650 br_lck->modified = true;
1651 TALLOC_FREE(br_lck);
1652 return true;
1655 /****************************************************************************
1656 Ensure this set of lock entries is valid.
1657 ****************************************************************************/
1658 static bool validate_lock_entries(unsigned int *pnum_entries, struct lock_struct **pplocks,
1659 bool keep_disconnected)
1661 unsigned int i;
1662 unsigned int num_valid_entries = 0;
1663 struct lock_struct *locks = *pplocks;
1664 TALLOC_CTX *frame = talloc_stackframe();
1665 struct server_id *ids;
1666 bool *exists;
1668 ids = talloc_array(frame, struct server_id, *pnum_entries);
1669 if (ids == NULL) {
1670 DEBUG(0, ("validate_lock_entries: "
1671 "talloc_array(struct server_id, %u) failed\n",
1672 *pnum_entries));
1673 talloc_free(frame);
1674 return false;
1677 exists = talloc_array(frame, bool, *pnum_entries);
1678 if (exists == NULL) {
1679 DEBUG(0, ("validate_lock_entries: "
1680 "talloc_array(bool, %u) failed\n",
1681 *pnum_entries));
1682 talloc_free(frame);
1683 return false;
1686 for (i = 0; i < *pnum_entries; i++) {
1687 ids[i] = locks[i].context.pid;
1690 if (!serverids_exist(ids, *pnum_entries, exists)) {
1691 DEBUG(3, ("validate_lock_entries: serverids_exists failed\n"));
1692 talloc_free(frame);
1693 return false;
1696 for (i = 0; i < *pnum_entries; i++) {
1697 if (exists[i]) {
1698 num_valid_entries++;
1699 continue;
1702 if (keep_disconnected &&
1703 server_id_is_disconnected(&ids[i]))
1705 num_valid_entries++;
1706 continue;
1709 /* This process no longer exists - mark this
1710 entry as invalid by zeroing it. */
1711 ZERO_STRUCTP(&locks[i]);
1713 TALLOC_FREE(frame);
1715 if (num_valid_entries != *pnum_entries) {
1716 struct lock_struct *new_lock_data = NULL;
1718 if (num_valid_entries) {
1719 new_lock_data = SMB_MALLOC_ARRAY(struct lock_struct, num_valid_entries);
1720 if (!new_lock_data) {
1721 DEBUG(3, ("malloc fail\n"));
1722 return False;
1725 num_valid_entries = 0;
1726 for (i = 0; i < *pnum_entries; i++) {
1727 struct lock_struct *lock_data = &locks[i];
1728 if (lock_data->context.smblctx &&
1729 lock_data->context.tid) {
1730 /* Valid (nonzero) entry - copy it. */
1731 memcpy(&new_lock_data[num_valid_entries],
1732 lock_data, sizeof(struct lock_struct));
1733 num_valid_entries++;
1738 SAFE_FREE(*pplocks);
1739 *pplocks = new_lock_data;
1740 *pnum_entries = num_valid_entries;
1743 return True;
1746 struct brl_forall_cb {
1747 void (*fn)(struct file_id id, struct server_id pid,
1748 enum brl_type lock_type,
1749 enum brl_flavour lock_flav,
1750 br_off start, br_off size,
1751 void *private_data);
1752 void *private_data;
1755 /****************************************************************************
1756 Traverse the whole database with this function, calling traverse_callback
1757 on each lock.
1758 ****************************************************************************/
1760 static int brl_traverse_fn(struct db_record *rec, void *state)
1762 struct brl_forall_cb *cb = (struct brl_forall_cb *)state;
1763 struct lock_struct *locks;
1764 struct file_id *key;
1765 unsigned int i;
1766 unsigned int num_locks = 0;
1767 unsigned int orig_num_locks = 0;
1768 TDB_DATA dbkey;
1769 TDB_DATA value;
1771 dbkey = dbwrap_record_get_key(rec);
1772 value = dbwrap_record_get_value(rec);
1774 /* In a traverse function we must make a copy of
1775 dbuf before modifying it. */
1777 locks = (struct lock_struct *)memdup(value.dptr, value.dsize);
1778 if (!locks) {
1779 return -1; /* Terminate traversal. */
1782 key = (struct file_id *)dbkey.dptr;
1783 orig_num_locks = num_locks = value.dsize/sizeof(*locks);
1785 /* Ensure the lock db is clean of entries from invalid processes. */
1787 if (!validate_lock_entries(&num_locks, &locks, true)) {
1788 SAFE_FREE(locks);
1789 return -1; /* Terminate traversal */
1792 if (orig_num_locks != num_locks) {
1793 if (num_locks) {
1794 TDB_DATA data;
1795 data.dptr = (uint8_t *)locks;
1796 data.dsize = num_locks*sizeof(struct lock_struct);
1797 dbwrap_record_store(rec, data, TDB_REPLACE);
1798 } else {
1799 dbwrap_record_delete(rec);
1803 if (cb->fn) {
1804 for ( i=0; i<num_locks; i++) {
1805 cb->fn(*key,
1806 locks[i].context.pid,
1807 locks[i].lock_type,
1808 locks[i].lock_flav,
1809 locks[i].start,
1810 locks[i].size,
1811 cb->private_data);
1815 SAFE_FREE(locks);
1816 return 0;
1819 /*******************************************************************
1820 Call the specified function on each lock in the database.
1821 ********************************************************************/
1823 int brl_forall(void (*fn)(struct file_id id, struct server_id pid,
1824 enum brl_type lock_type,
1825 enum brl_flavour lock_flav,
1826 br_off start, br_off size,
1827 void *private_data),
1828 void *private_data)
1830 struct brl_forall_cb cb;
1831 NTSTATUS status;
1832 int count = 0;
1834 if (!brlock_db) {
1835 return 0;
1837 cb.fn = fn;
1838 cb.private_data = private_data;
1839 status = dbwrap_traverse(brlock_db, brl_traverse_fn, &cb, &count);
1841 if (!NT_STATUS_IS_OK(status)) {
1842 return -1;
1843 } else {
1844 return count;
1848 /*******************************************************************
1849 Store a potentially modified set of byte range lock data back into
1850 the database.
1851 Unlock the record.
1852 ********************************************************************/
1854 static void byte_range_lock_flush(struct byte_range_lock *br_lck)
1856 if (br_lck->read_only) {
1857 SMB_ASSERT(!br_lck->modified);
1860 if (!br_lck->modified) {
1861 goto done;
1864 if (br_lck->num_locks == 0) {
1865 /* No locks - delete this entry. */
1866 NTSTATUS status = dbwrap_record_delete(br_lck->record);
1867 if (!NT_STATUS_IS_OK(status)) {
1868 DEBUG(0, ("delete_rec returned %s\n",
1869 nt_errstr(status)));
1870 smb_panic("Could not delete byte range lock entry");
1872 } else {
1873 TDB_DATA data;
1874 NTSTATUS status;
1876 data.dptr = (uint8 *)br_lck->lock_data;
1877 data.dsize = br_lck->num_locks * sizeof(struct lock_struct);
1879 status = dbwrap_record_store(br_lck->record, data, TDB_REPLACE);
1880 if (!NT_STATUS_IS_OK(status)) {
1881 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
1882 smb_panic("Could not store byte range mode entry");
1886 done:
1888 br_lck->read_only = true;
1889 br_lck->modified = false;
1891 TALLOC_FREE(br_lck->record);
1894 static int byte_range_lock_destructor(struct byte_range_lock *br_lck)
1896 byte_range_lock_flush(br_lck);
1897 SAFE_FREE(br_lck->lock_data);
1898 return 0;
1901 /*******************************************************************
1902 Fetch a set of byte range lock data from the database.
1903 Leave the record locked.
1904 TALLOC_FREE(brl) will release the lock in the destructor.
1905 ********************************************************************/
1907 static struct byte_range_lock *brl_get_locks_internal(TALLOC_CTX *mem_ctx,
1908 files_struct *fsp, bool read_only)
1910 TDB_DATA key, data;
1911 struct byte_range_lock *br_lck = talloc(mem_ctx, struct byte_range_lock);
1912 bool do_read_only = read_only;
1914 if (br_lck == NULL) {
1915 return NULL;
1918 br_lck->fsp = fsp;
1919 br_lck->num_locks = 0;
1920 br_lck->modified = False;
1921 br_lck->key = fsp->file_id;
1923 key.dptr = (uint8 *)&br_lck->key;
1924 key.dsize = sizeof(struct file_id);
1926 if (!fsp->lockdb_clean) {
1927 /* We must be read/write to clean
1928 the dead entries. */
1929 do_read_only = false;
1932 if (do_read_only) {
1933 NTSTATUS status;
1934 status = dbwrap_fetch(brlock_db, br_lck, key, &data);
1935 if (!NT_STATUS_IS_OK(status)) {
1936 DEBUG(3, ("Could not fetch byte range lock record\n"));
1937 TALLOC_FREE(br_lck);
1938 return NULL;
1940 br_lck->record = NULL;
1941 } else {
1942 br_lck->record = dbwrap_fetch_locked(brlock_db, br_lck, key);
1944 if (br_lck->record == NULL) {
1945 DEBUG(3, ("Could not lock byte range lock entry\n"));
1946 TALLOC_FREE(br_lck);
1947 return NULL;
1950 data = dbwrap_record_get_value(br_lck->record);
1953 br_lck->read_only = do_read_only;
1954 br_lck->lock_data = NULL;
1956 talloc_set_destructor(br_lck, byte_range_lock_destructor);
1958 br_lck->num_locks = data.dsize / sizeof(struct lock_struct);
1960 if (br_lck->num_locks != 0) {
1961 br_lck->lock_data = SMB_MALLOC_ARRAY(struct lock_struct,
1962 br_lck->num_locks);
1963 if (br_lck->lock_data == NULL) {
1964 DEBUG(0, ("malloc failed\n"));
1965 TALLOC_FREE(br_lck);
1966 return NULL;
1969 memcpy(br_lck->lock_data, data.dptr, data.dsize);
1972 if (!fsp->lockdb_clean) {
1973 int orig_num_locks = br_lck->num_locks;
1976 * This is the first time we access the byte range lock
1977 * record with this fsp. Go through and ensure all entries
1978 * are valid - remove any that don't.
1979 * This makes the lockdb self cleaning at low cost.
1981 * Note: Disconnected entries belong to disconnected
1982 * durable handles. So at this point, we have a new
1983 * handle on the file and the disconnected durable has
1984 * already been closed (we are not a durable reconnect).
1985 * So we need to clean the disconnected brl entry.
1988 if (!validate_lock_entries(&br_lck->num_locks,
1989 &br_lck->lock_data, false)) {
1990 SAFE_FREE(br_lck->lock_data);
1991 TALLOC_FREE(br_lck);
1992 return NULL;
1995 /* Ensure invalid locks are cleaned up in the destructor. */
1996 if (orig_num_locks != br_lck->num_locks) {
1997 br_lck->modified = True;
2000 /* Mark the lockdb as "clean" as seen from this open file. */
2001 fsp->lockdb_clean = True;
2004 if (DEBUGLEVEL >= 10) {
2005 unsigned int i;
2006 struct lock_struct *locks = br_lck->lock_data;
2007 DEBUG(10,("brl_get_locks_internal: %u current locks on file_id %s\n",
2008 br_lck->num_locks,
2009 file_id_string_tos(&fsp->file_id)));
2010 for( i = 0; i < br_lck->num_locks; i++) {
2011 print_lock_struct(i, &locks[i]);
2015 if (do_read_only != read_only) {
2017 * this stores the record and gets rid of
2018 * the write lock that is needed for a cleanup
2020 byte_range_lock_flush(br_lck);
2023 return br_lck;
2026 struct byte_range_lock *brl_get_locks(TALLOC_CTX *mem_ctx,
2027 files_struct *fsp)
2029 return brl_get_locks_internal(mem_ctx, fsp, False);
2032 struct byte_range_lock *brl_get_locks_readonly(files_struct *fsp)
2034 struct byte_range_lock *br_lock;
2036 if (lp_clustering()) {
2037 return brl_get_locks_internal(talloc_tos(), fsp, true);
2040 if ((fsp->brlock_rec != NULL)
2041 && (dbwrap_get_seqnum(brlock_db) == fsp->brlock_seqnum)) {
2042 return fsp->brlock_rec;
2045 TALLOC_FREE(fsp->brlock_rec);
2047 br_lock = brl_get_locks_internal(talloc_tos(), fsp, true);
2048 if (br_lock == NULL) {
2049 return NULL;
2051 fsp->brlock_seqnum = dbwrap_get_seqnum(brlock_db);
2053 fsp->brlock_rec = talloc_move(fsp, &br_lock);
2055 return fsp->brlock_rec;
2058 struct brl_revalidate_state {
2059 ssize_t array_size;
2060 uint32 num_pids;
2061 struct server_id *pids;
2065 * Collect PIDs of all processes with pending entries
2068 static void brl_revalidate_collect(struct file_id id, struct server_id pid,
2069 enum brl_type lock_type,
2070 enum brl_flavour lock_flav,
2071 br_off start, br_off size,
2072 void *private_data)
2074 struct brl_revalidate_state *state =
2075 (struct brl_revalidate_state *)private_data;
2077 if (!IS_PENDING_LOCK(lock_type)) {
2078 return;
2081 add_to_large_array(state, sizeof(pid), (void *)&pid,
2082 &state->pids, &state->num_pids,
2083 &state->array_size);
2087 * qsort callback to sort the processes
2090 static int compare_procids(const void *p1, const void *p2)
2092 const struct server_id *i1 = (const struct server_id *)p1;
2093 const struct server_id *i2 = (const struct server_id *)p2;
2095 if (i1->pid < i2->pid) return -1;
2096 if (i2->pid > i2->pid) return 1;
2097 return 0;
2101 * Send a MSG_SMB_UNLOCK message to all processes with pending byte range
2102 * locks so that they retry. Mainly used in the cluster code after a node has
2103 * died.
2105 * Done in two steps to avoid double-sends: First we collect all entries in an
2106 * array, then qsort that array and only send to non-dupes.
2109 void brl_revalidate(struct messaging_context *msg_ctx,
2110 void *private_data,
2111 uint32_t msg_type,
2112 struct server_id server_id,
2113 DATA_BLOB *data)
2115 struct brl_revalidate_state *state;
2116 uint32 i;
2117 struct server_id last_pid;
2119 if (!(state = talloc_zero(NULL, struct brl_revalidate_state))) {
2120 DEBUG(0, ("talloc failed\n"));
2121 return;
2124 brl_forall(brl_revalidate_collect, state);
2126 if (state->array_size == -1) {
2127 DEBUG(0, ("talloc failed\n"));
2128 goto done;
2131 if (state->num_pids == 0) {
2132 goto done;
2135 TYPESAFE_QSORT(state->pids, state->num_pids, compare_procids);
2137 ZERO_STRUCT(last_pid);
2139 for (i=0; i<state->num_pids; i++) {
2140 if (serverid_equal(&last_pid, &state->pids[i])) {
2142 * We've seen that one already
2144 continue;
2147 messaging_send(msg_ctx, state->pids[i], MSG_SMB_UNLOCK,
2148 &data_blob_null);
2149 last_pid = state->pids[i];
2152 done:
2153 TALLOC_FREE(state);
2154 return;
2157 bool brl_cleanup_disconnected(struct file_id fid, uint64_t open_persistent_id)
2159 bool ret = false;
2160 TALLOC_CTX *frame = talloc_stackframe();
2161 TDB_DATA key, val;
2162 struct db_record *rec;
2163 struct lock_struct *lock;
2164 unsigned n, num;
2165 NTSTATUS status;
2167 key = make_tdb_data((void*)&fid, sizeof(fid));
2169 rec = dbwrap_fetch_locked(brlock_db, frame, key);
2170 if (rec == NULL) {
2171 DEBUG(5, ("brl_cleanup_disconnected: failed to fetch record "
2172 "for file %s\n", file_id_string(frame, &fid)));
2173 goto done;
2176 val = dbwrap_record_get_value(rec);
2177 lock = (struct lock_struct*)val.dptr;
2178 num = val.dsize / sizeof(struct lock_struct);
2179 if (lock == NULL) {
2180 DEBUG(10, ("brl_cleanup_disconnected: no byte range locks for "
2181 "file %s\n", file_id_string(frame, &fid)));
2182 ret = true;
2183 goto done;
2186 for (n=0; n<num; n++) {
2187 struct lock_context *ctx = &lock[n].context;
2189 if (!server_id_is_disconnected(&ctx->pid)) {
2190 DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2191 "%s used by server %s, do not cleanup\n",
2192 file_id_string(frame, &fid),
2193 server_id_str(frame, &ctx->pid)));
2194 goto done;
2197 if (ctx->smblctx != open_persistent_id) {
2198 DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2199 "%s expected smblctx %llu but found %llu"
2200 ", do not cleanup\n",
2201 file_id_string(frame, &fid),
2202 (unsigned long long)open_persistent_id,
2203 (unsigned long long)ctx->smblctx));
2204 goto done;
2208 status = dbwrap_record_delete(rec);
2209 if (!NT_STATUS_IS_OK(status)) {
2210 DEBUG(5, ("brl_cleanup_disconnected: failed to delete record "
2211 "for file %s from %s, open %llu: %s\n",
2212 file_id_string(frame, &fid), dbwrap_name(brlock_db),
2213 (unsigned long long)open_persistent_id,
2214 nt_errstr(status)));
2215 goto done;
2218 DEBUG(10, ("brl_cleanup_disconnected: "
2219 "file %s cleaned up %u entries from open %llu\n",
2220 file_id_string(frame, &fid), num,
2221 (unsigned long long)open_persistent_id));
2223 ret = true;
2224 done:
2225 talloc_free(frame);
2226 return ret;