smbd: Restructure brl_conflict_other
[Samba.git] / source3 / locking / brlock.c
blobfe613056121d1012fc7aec51750a839ca65fcc72
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 struct byte_range_lock {
47 struct files_struct *fsp;
48 unsigned int num_locks;
49 bool modified;
50 bool have_read_oplocks;
51 struct lock_struct *lock_data;
52 struct db_record *record;
55 /****************************************************************************
56 Debug info at level 10 for lock struct.
57 ****************************************************************************/
59 static void print_lock_struct(unsigned int i, const struct lock_struct *pls)
61 DEBUG(10,("[%u]: smblctx = %llu, tid = %u, pid = %s, ",
63 (unsigned long long)pls->context.smblctx,
64 (unsigned int)pls->context.tid,
65 server_id_str(talloc_tos(), &pls->context.pid) ));
67 DEBUG(10, ("start = %ju, size = %ju, fnum = %ju, %s %s\n",
68 (uintmax_t)pls->start,
69 (uintmax_t)pls->size,
70 (uintmax_t)pls->fnum,
71 lock_type_name(pls->lock_type),
72 lock_flav_name(pls->lock_flav)));
75 unsigned int brl_num_locks(const struct byte_range_lock *brl)
77 return brl->num_locks;
80 struct files_struct *brl_fsp(struct byte_range_lock *brl)
82 return brl->fsp;
85 bool brl_have_read_oplocks(const struct byte_range_lock *brl)
87 return brl->have_read_oplocks;
90 void brl_set_have_read_oplocks(struct byte_range_lock *brl,
91 bool have_read_oplocks)
93 DEBUG(10, ("Setting have_read_oplocks to %s\n",
94 have_read_oplocks ? "true" : "false"));
95 SMB_ASSERT(brl->record != NULL); /* otherwise we're readonly */
96 brl->have_read_oplocks = have_read_oplocks;
97 brl->modified = true;
100 /****************************************************************************
101 See if two locking contexts are equal.
102 ****************************************************************************/
104 static bool brl_same_context(const struct lock_context *ctx1,
105 const struct lock_context *ctx2)
107 return (serverid_equal(&ctx1->pid, &ctx2->pid) &&
108 (ctx1->smblctx == ctx2->smblctx) &&
109 (ctx1->tid == ctx2->tid));
112 /****************************************************************************
113 See if lck1 and lck2 overlap.
114 ****************************************************************************/
116 static bool brl_overlap(const struct lock_struct *lck1,
117 const struct lock_struct *lck2)
119 /* XXX Remove for Win7 compatibility. */
120 /* this extra check is not redundant - it copes with locks
121 that go beyond the end of 64 bit file space */
122 if (lck1->size != 0 &&
123 lck1->start == lck2->start &&
124 lck1->size == lck2->size) {
125 return True;
128 if (lck1->start >= (lck2->start+lck2->size) ||
129 lck2->start >= (lck1->start+lck1->size)) {
130 return False;
132 return True;
135 /****************************************************************************
136 See if lock2 can be added when lock1 is in place.
137 ****************************************************************************/
139 static bool brl_conflict(const struct lock_struct *lck1,
140 const struct lock_struct *lck2)
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 /* A READ lock can stack on top of a WRITE lock if they have the same
152 * context & fnum. */
153 if (lck1->lock_type == WRITE_LOCK && lck2->lock_type == READ_LOCK &&
154 brl_same_context(&lck1->context, &lck2->context) &&
155 lck1->fnum == lck2->fnum) {
156 return False;
159 return brl_overlap(lck1, lck2);
162 /****************************************************************************
163 See if lock2 can be added when lock1 is in place - when both locks are POSIX
164 flavour. POSIX locks ignore fnum - they only care about dev/ino which we
165 know already match.
166 ****************************************************************************/
168 static bool brl_conflict_posix(const struct lock_struct *lck1,
169 const struct lock_struct *lck2)
171 #if defined(DEVELOPER)
172 SMB_ASSERT(lck1->lock_flav == POSIX_LOCK);
173 SMB_ASSERT(lck2->lock_flav == POSIX_LOCK);
174 #endif
176 /* Ignore PENDING locks. */
177 if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
178 return False;
180 /* Read locks never conflict. */
181 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
182 return False;
185 /* Locks on the same context don't conflict. Ignore fnum. */
186 if (brl_same_context(&lck1->context, &lck2->context)) {
187 return False;
190 /* One is read, the other write, or the context is different,
191 do they overlap ? */
192 return brl_overlap(lck1, lck2);
195 #if ZERO_ZERO
196 static bool brl_conflict1(const struct lock_struct *lck1,
197 const struct lock_struct *lck2)
199 if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
200 return False;
202 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
203 return False;
206 if (brl_same_context(&lck1->context, &lck2->context) &&
207 lck2->lock_type == READ_LOCK && lck1->fnum == lck2->fnum) {
208 return False;
211 if (lck2->start == 0 && lck2->size == 0 && lck1->size != 0) {
212 return True;
215 if (lck1->start >= (lck2->start + lck2->size) ||
216 lck2->start >= (lck1->start + lck1->size)) {
217 return False;
220 return True;
222 #endif
224 /****************************************************************************
225 Check to see if this lock conflicts, but ignore our own locks on the
226 same fnum only. This is the read/write lock check code path.
227 This is never used in the POSIX lock case.
228 ****************************************************************************/
230 static bool brl_conflict_other(const struct lock_struct *lock,
231 const struct lock_struct *rw_probe)
233 if (IS_PENDING_LOCK(lock->lock_type) ||
234 IS_PENDING_LOCK(rw_probe->lock_type)) {
235 return False;
238 if (lock->lock_type == READ_LOCK && rw_probe->lock_type == READ_LOCK) {
239 return False;
242 if (lock->lock_flav == POSIX_LOCK &&
243 rw_probe->lock_flav == POSIX_LOCK) {
245 * POSIX flavour locks never conflict here - this is only called
246 * in the read/write path.
248 return False;
251 if (!brl_overlap(lock, rw_probe)) {
253 * I/O can only conflict when overlapping a lock, thus let it
254 * pass
256 return false;
259 if (!brl_same_context(&lock->context, &rw_probe->context)) {
261 * Different process, conflict
263 return true;
266 if (lock->fnum != rw_probe->fnum) {
268 * Different file handle, conflict
270 return true;
273 if ((lock->lock_type == READ_LOCK) &&
274 (rw_probe->lock_type == WRITE_LOCK)) {
276 * Incoming WRITE locks conflict with existing READ locks even
277 * if the context is the same. JRA. See LOCKTEST7 in
278 * smbtorture.
280 return true;
284 * I/O request compatible with existing lock, let it pass without
285 * conflict
288 return false;
291 /****************************************************************************
292 Check if an unlock overlaps a pending lock.
293 ****************************************************************************/
295 static bool brl_pending_overlap(const struct lock_struct *lock, const struct lock_struct *pend_lock)
297 if ((lock->start <= pend_lock->start) && (lock->start + lock->size > pend_lock->start))
298 return True;
299 if ((lock->start >= pend_lock->start) && (lock->start < pend_lock->start + pend_lock->size))
300 return True;
301 return False;
304 /****************************************************************************
305 Amazingly enough, w2k3 "remembers" whether the last lock failure on a fnum
306 is the same as this one and changes its error code. I wonder if any
307 app depends on this ?
308 ****************************************************************************/
310 static NTSTATUS brl_lock_failed(files_struct *fsp,
311 const struct lock_struct *lock,
312 bool blocking_lock)
314 if (lock->start >= 0xEF000000 && (lock->start >> 63) == 0) {
315 /* amazing the little things you learn with a test
316 suite. Locks beyond this offset (as a 64 bit
317 number!) always generate the conflict error code,
318 unless the top bit is set */
319 if (!blocking_lock) {
320 fsp->last_lock_failure = *lock;
322 return NT_STATUS_FILE_LOCK_CONFLICT;
325 if (serverid_equal(&lock->context.pid, &fsp->last_lock_failure.context.pid) &&
326 lock->context.tid == fsp->last_lock_failure.context.tid &&
327 lock->fnum == fsp->last_lock_failure.fnum &&
328 lock->start == fsp->last_lock_failure.start) {
329 return NT_STATUS_FILE_LOCK_CONFLICT;
332 if (!blocking_lock) {
333 fsp->last_lock_failure = *lock;
335 return NT_STATUS_LOCK_NOT_GRANTED;
338 /****************************************************************************
339 Open up the brlock.tdb database.
340 ****************************************************************************/
342 void brl_init(bool read_only)
344 int tdb_flags;
346 if (brlock_db) {
347 return;
350 tdb_flags = TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH;
352 if (!lp_clustering()) {
354 * We can't use the SEQNUM trick to cache brlock
355 * entries in the clustering case because ctdb seqnum
356 * propagation has a delay.
358 tdb_flags |= TDB_SEQNUM;
361 brlock_db = db_open(NULL, lock_path("brlock.tdb"),
362 SMB_OPEN_DATABASE_TDB_HASH_SIZE, tdb_flags,
363 read_only?O_RDONLY:(O_RDWR|O_CREAT), 0644,
364 DBWRAP_LOCK_ORDER_2, DBWRAP_FLAG_NONE);
365 if (!brlock_db) {
366 DEBUG(0,("Failed to open byte range locking database %s\n",
367 lock_path("brlock.tdb")));
368 return;
372 /****************************************************************************
373 Close down the brlock.tdb database.
374 ****************************************************************************/
376 void brl_shutdown(void)
378 TALLOC_FREE(brlock_db);
381 #if ZERO_ZERO
382 /****************************************************************************
383 Compare two locks for sorting.
384 ****************************************************************************/
386 static int lock_compare(const struct lock_struct *lck1,
387 const struct lock_struct *lck2)
389 if (lck1->start != lck2->start) {
390 return (lck1->start - lck2->start);
392 if (lck2->size != lck1->size) {
393 return ((int)lck1->size - (int)lck2->size);
395 return 0;
397 #endif
399 /****************************************************************************
400 Lock a range of bytes - Windows lock semantics.
401 ****************************************************************************/
403 NTSTATUS brl_lock_windows_default(struct byte_range_lock *br_lck,
404 struct lock_struct *plock, bool blocking_lock)
406 unsigned int i;
407 files_struct *fsp = br_lck->fsp;
408 struct lock_struct *locks = br_lck->lock_data;
409 NTSTATUS status;
411 SMB_ASSERT(plock->lock_type != UNLOCK_LOCK);
413 if ((plock->start + plock->size - 1 < plock->start) &&
414 plock->size != 0) {
415 return NT_STATUS_INVALID_LOCK_RANGE;
418 for (i=0; i < br_lck->num_locks; i++) {
419 /* Do any Windows or POSIX locks conflict ? */
420 if (brl_conflict(&locks[i], plock)) {
421 /* Remember who blocked us. */
422 plock->context.smblctx = locks[i].context.smblctx;
423 return brl_lock_failed(fsp,plock,blocking_lock);
425 #if ZERO_ZERO
426 if (plock->start == 0 && plock->size == 0 &&
427 locks[i].size == 0) {
428 break;
430 #endif
433 if (!IS_PENDING_LOCK(plock->lock_type)) {
434 contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
437 /* We can get the Windows lock, now see if it needs to
438 be mapped into a lower level POSIX one, and if so can
439 we get it ? */
441 if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(fsp->conn->params)) {
442 int errno_ret;
443 if (!set_posix_lock_windows_flavour(fsp,
444 plock->start,
445 plock->size,
446 plock->lock_type,
447 &plock->context,
448 locks,
449 br_lck->num_locks,
450 &errno_ret)) {
452 /* We don't know who blocked us. */
453 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
455 if (errno_ret == EACCES || errno_ret == EAGAIN) {
456 status = NT_STATUS_FILE_LOCK_CONFLICT;
457 goto fail;
458 } else {
459 status = map_nt_error_from_unix(errno);
460 goto fail;
465 /* no conflicts - add it to the list of locks */
466 locks = talloc_realloc(br_lck, locks, struct lock_struct,
467 (br_lck->num_locks + 1));
468 if (!locks) {
469 status = NT_STATUS_NO_MEMORY;
470 goto fail;
473 memcpy(&locks[br_lck->num_locks], plock, sizeof(struct lock_struct));
474 br_lck->num_locks += 1;
475 br_lck->lock_data = locks;
476 br_lck->modified = True;
478 return NT_STATUS_OK;
479 fail:
480 if (!IS_PENDING_LOCK(plock->lock_type)) {
481 contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
483 return status;
486 /****************************************************************************
487 Cope with POSIX range splits and merges.
488 ****************************************************************************/
490 static unsigned int brlock_posix_split_merge(struct lock_struct *lck_arr, /* Output array. */
491 struct lock_struct *ex, /* existing lock. */
492 struct lock_struct *plock) /* proposed lock. */
494 bool lock_types_differ = (ex->lock_type != plock->lock_type);
496 /* We can't merge non-conflicting locks on different context - ignore fnum. */
498 if (!brl_same_context(&ex->context, &plock->context)) {
499 /* Just copy. */
500 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
501 return 1;
504 /* We now know we have the same context. */
506 /* Did we overlap ? */
508 /*********************************************
509 +---------+
510 | ex |
511 +---------+
512 +-------+
513 | plock |
514 +-------+
515 OR....
516 +---------+
517 | ex |
518 +---------+
519 **********************************************/
521 if ( (ex->start > (plock->start + plock->size)) ||
522 (plock->start > (ex->start + ex->size))) {
524 /* No overlap with this lock - copy existing. */
526 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
527 return 1;
530 /*********************************************
531 +---------------------------+
532 | ex |
533 +---------------------------+
534 +---------------------------+
535 | plock | -> replace with plock.
536 +---------------------------+
538 +---------------+
539 | ex |
540 +---------------+
541 +---------------------------+
542 | plock | -> replace with plock.
543 +---------------------------+
545 **********************************************/
547 if ( (ex->start >= plock->start) &&
548 (ex->start + ex->size <= plock->start + plock->size) ) {
550 /* Replace - discard existing lock. */
552 return 0;
555 /*********************************************
556 Adjacent after.
557 +-------+
558 | ex |
559 +-------+
560 +---------------+
561 | plock |
562 +---------------+
564 BECOMES....
565 +---------------+-------+
566 | plock | ex | - different lock types.
567 +---------------+-------+
568 OR.... (merge)
569 +-----------------------+
570 | plock | - same lock type.
571 +-----------------------+
572 **********************************************/
574 if (plock->start + plock->size == ex->start) {
576 /* If the lock types are the same, we merge, if different, we
577 add the remainder of the old lock. */
579 if (lock_types_differ) {
580 /* Add existing. */
581 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
582 return 1;
583 } else {
584 /* Merge - adjust incoming lock as we may have more
585 * merging to come. */
586 plock->size += ex->size;
587 return 0;
591 /*********************************************
592 Adjacent before.
593 +-------+
594 | ex |
595 +-------+
596 +---------------+
597 | plock |
598 +---------------+
599 BECOMES....
600 +-------+---------------+
601 | ex | plock | - different lock types
602 +-------+---------------+
604 OR.... (merge)
605 +-----------------------+
606 | plock | - same lock type.
607 +-----------------------+
609 **********************************************/
611 if (ex->start + ex->size == plock->start) {
613 /* If the lock types are the same, we merge, if different, we
614 add the existing lock. */
616 if (lock_types_differ) {
617 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
618 return 1;
619 } else {
620 /* Merge - adjust incoming lock as we may have more
621 * merging to come. */
622 plock->start = ex->start;
623 plock->size += ex->size;
624 return 0;
628 /*********************************************
629 Overlap after.
630 +-----------------------+
631 | ex |
632 +-----------------------+
633 +---------------+
634 | plock |
635 +---------------+
637 +----------------+
638 | ex |
639 +----------------+
640 +---------------+
641 | plock |
642 +---------------+
644 BECOMES....
645 +---------------+-------+
646 | plock | ex | - different lock types.
647 +---------------+-------+
648 OR.... (merge)
649 +-----------------------+
650 | plock | - same lock type.
651 +-----------------------+
652 **********************************************/
654 if ( (ex->start >= plock->start) &&
655 (ex->start <= plock->start + plock->size) &&
656 (ex->start + ex->size > plock->start + plock->size) ) {
658 /* If the lock types are the same, we merge, if different, we
659 add the remainder of the old lock. */
661 if (lock_types_differ) {
662 /* Add remaining existing. */
663 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
664 /* Adjust existing start and size. */
665 lck_arr[0].start = plock->start + plock->size;
666 lck_arr[0].size = (ex->start + ex->size) - (plock->start + plock->size);
667 return 1;
668 } else {
669 /* Merge - adjust incoming lock as we may have more
670 * merging to come. */
671 plock->size += (ex->start + ex->size) - (plock->start + plock->size);
672 return 0;
676 /*********************************************
677 Overlap before.
678 +-----------------------+
679 | ex |
680 +-----------------------+
681 +---------------+
682 | plock |
683 +---------------+
685 +-------------+
686 | ex |
687 +-------------+
688 +---------------+
689 | plock |
690 +---------------+
692 BECOMES....
693 +-------+---------------+
694 | ex | plock | - different lock types
695 +-------+---------------+
697 OR.... (merge)
698 +-----------------------+
699 | plock | - same lock type.
700 +-----------------------+
702 **********************************************/
704 if ( (ex->start < plock->start) &&
705 (ex->start + ex->size >= plock->start) &&
706 (ex->start + ex->size <= plock->start + plock->size) ) {
708 /* If the lock types are the same, we merge, if different, we
709 add the truncated old lock. */
711 if (lock_types_differ) {
712 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
713 /* Adjust existing size. */
714 lck_arr[0].size = plock->start - ex->start;
715 return 1;
716 } else {
717 /* Merge - adjust incoming lock as we may have more
718 * merging to come. MUST ADJUST plock SIZE FIRST ! */
719 plock->size += (plock->start - ex->start);
720 plock->start = ex->start;
721 return 0;
725 /*********************************************
726 Complete overlap.
727 +---------------------------+
728 | ex |
729 +---------------------------+
730 +---------+
731 | plock |
732 +---------+
733 BECOMES.....
734 +-------+---------+---------+
735 | ex | plock | ex | - different lock types.
736 +-------+---------+---------+
738 +---------------------------+
739 | plock | - same lock type.
740 +---------------------------+
741 **********************************************/
743 if ( (ex->start < plock->start) && (ex->start + ex->size > plock->start + plock->size) ) {
745 if (lock_types_differ) {
747 /* We have to split ex into two locks here. */
749 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
750 memcpy(&lck_arr[1], ex, sizeof(struct lock_struct));
752 /* Adjust first existing size. */
753 lck_arr[0].size = plock->start - ex->start;
755 /* Adjust second existing start and size. */
756 lck_arr[1].start = plock->start + plock->size;
757 lck_arr[1].size = (ex->start + ex->size) - (plock->start + plock->size);
758 return 2;
759 } else {
760 /* Just eat the existing locks, merge them into plock. */
761 plock->start = ex->start;
762 plock->size = ex->size;
763 return 0;
767 /* Never get here. */
768 smb_panic("brlock_posix_split_merge");
769 /* Notreached. */
771 /* Keep some compilers happy. */
772 return 0;
775 /****************************************************************************
776 Lock a range of bytes - POSIX lock semantics.
777 We must cope with range splits and merges.
778 ****************************************************************************/
780 static NTSTATUS brl_lock_posix(struct messaging_context *msg_ctx,
781 struct byte_range_lock *br_lck,
782 struct lock_struct *plock)
784 unsigned int i, count, posix_count;
785 struct lock_struct *locks = br_lck->lock_data;
786 struct lock_struct *tp;
787 bool signal_pending_read = False;
788 bool break_oplocks = false;
789 NTSTATUS status;
791 /* No zero-zero locks for POSIX. */
792 if (plock->start == 0 && plock->size == 0) {
793 return NT_STATUS_INVALID_PARAMETER;
796 /* Don't allow 64-bit lock wrap. */
797 if (plock->start + plock->size - 1 < plock->start) {
798 return NT_STATUS_INVALID_PARAMETER;
801 /* The worst case scenario here is we have to split an
802 existing POSIX lock range into two, and add our lock,
803 so we need at most 2 more entries. */
805 tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 2);
806 if (!tp) {
807 return NT_STATUS_NO_MEMORY;
810 count = posix_count = 0;
812 for (i=0; i < br_lck->num_locks; i++) {
813 struct lock_struct *curr_lock = &locks[i];
815 /* If we have a pending read lock, a lock downgrade should
816 trigger a lock re-evaluation. */
817 if (curr_lock->lock_type == PENDING_READ_LOCK &&
818 brl_pending_overlap(plock, curr_lock)) {
819 signal_pending_read = True;
822 if (curr_lock->lock_flav == WINDOWS_LOCK) {
823 /* Do any Windows flavour locks conflict ? */
824 if (brl_conflict(curr_lock, plock)) {
825 /* No games with error messages. */
826 TALLOC_FREE(tp);
827 /* Remember who blocked us. */
828 plock->context.smblctx = curr_lock->context.smblctx;
829 return NT_STATUS_FILE_LOCK_CONFLICT;
831 /* Just copy the Windows lock into the new array. */
832 memcpy(&tp[count], curr_lock, sizeof(struct lock_struct));
833 count++;
834 } else {
835 unsigned int tmp_count = 0;
837 /* POSIX conflict semantics are different. */
838 if (brl_conflict_posix(curr_lock, plock)) {
839 /* Can't block ourselves with POSIX locks. */
840 /* No games with error messages. */
841 TALLOC_FREE(tp);
842 /* Remember who blocked us. */
843 plock->context.smblctx = curr_lock->context.smblctx;
844 return NT_STATUS_FILE_LOCK_CONFLICT;
847 /* Work out overlaps. */
848 tmp_count += brlock_posix_split_merge(&tp[count], curr_lock, plock);
849 posix_count += tmp_count;
850 count += tmp_count;
855 * Break oplocks while we hold a brl. Since lock() and unlock() calls
856 * are not symetric with POSIX semantics, we cannot guarantee our
857 * contend_level2_oplocks_begin/end calls will be acquired and
858 * released one-for-one as with Windows semantics. Therefore we only
859 * call contend_level2_oplocks_begin if this is the first POSIX brl on
860 * the file.
862 break_oplocks = (!IS_PENDING_LOCK(plock->lock_type) &&
863 posix_count == 0);
864 if (break_oplocks) {
865 contend_level2_oplocks_begin(br_lck->fsp,
866 LEVEL2_CONTEND_POSIX_BRL);
869 /* Try and add the lock in order, sorted by lock start. */
870 for (i=0; i < count; i++) {
871 struct lock_struct *curr_lock = &tp[i];
873 if (curr_lock->start <= plock->start) {
874 continue;
878 if (i < count) {
879 memmove(&tp[i+1], &tp[i],
880 (count - i)*sizeof(struct lock_struct));
882 memcpy(&tp[i], plock, sizeof(struct lock_struct));
883 count++;
885 /* We can get the POSIX lock, now see if it needs to
886 be mapped into a lower level POSIX one, and if so can
887 we get it ? */
889 if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(br_lck->fsp->conn->params)) {
890 int errno_ret;
892 /* The lower layer just needs to attempt to
893 get the system POSIX lock. We've weeded out
894 any conflicts above. */
896 if (!set_posix_lock_posix_flavour(br_lck->fsp,
897 plock->start,
898 plock->size,
899 plock->lock_type,
900 &errno_ret)) {
902 /* We don't know who blocked us. */
903 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
905 if (errno_ret == EACCES || errno_ret == EAGAIN) {
906 TALLOC_FREE(tp);
907 status = NT_STATUS_FILE_LOCK_CONFLICT;
908 goto fail;
909 } else {
910 TALLOC_FREE(tp);
911 status = map_nt_error_from_unix(errno);
912 goto fail;
917 /* If we didn't use all the allocated size,
918 * Realloc so we don't leak entries per lock call. */
919 if (count < br_lck->num_locks + 2) {
920 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
921 if (!tp) {
922 status = NT_STATUS_NO_MEMORY;
923 goto fail;
927 br_lck->num_locks = count;
928 TALLOC_FREE(br_lck->lock_data);
929 br_lck->lock_data = tp;
930 locks = tp;
931 br_lck->modified = True;
933 /* A successful downgrade from write to read lock can trigger a lock
934 re-evalutation where waiting readers can now proceed. */
936 if (signal_pending_read) {
937 /* Send unlock messages to any pending read waiters that overlap. */
938 for (i=0; i < br_lck->num_locks; i++) {
939 struct lock_struct *pend_lock = &locks[i];
941 /* Ignore non-pending locks. */
942 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
943 continue;
946 if (pend_lock->lock_type == PENDING_READ_LOCK &&
947 brl_pending_overlap(plock, pend_lock)) {
948 DEBUG(10,("brl_lock_posix: sending unlock message to pid %s\n",
949 procid_str_static(&pend_lock->context.pid )));
951 messaging_send(msg_ctx, pend_lock->context.pid,
952 MSG_SMB_UNLOCK, &data_blob_null);
957 return NT_STATUS_OK;
958 fail:
959 if (break_oplocks) {
960 contend_level2_oplocks_end(br_lck->fsp,
961 LEVEL2_CONTEND_POSIX_BRL);
963 return status;
966 NTSTATUS smb_vfs_call_brl_lock_windows(struct vfs_handle_struct *handle,
967 struct byte_range_lock *br_lck,
968 struct lock_struct *plock,
969 bool blocking_lock)
971 VFS_FIND(brl_lock_windows);
972 return handle->fns->brl_lock_windows_fn(handle, br_lck, plock,
973 blocking_lock);
976 /****************************************************************************
977 Lock a range of bytes.
978 ****************************************************************************/
980 NTSTATUS brl_lock(struct messaging_context *msg_ctx,
981 struct byte_range_lock *br_lck,
982 uint64_t smblctx,
983 struct server_id pid,
984 br_off start,
985 br_off size,
986 enum brl_type lock_type,
987 enum brl_flavour lock_flav,
988 bool blocking_lock,
989 uint64_t *psmblctx)
991 NTSTATUS ret;
992 struct lock_struct lock;
994 #if !ZERO_ZERO
995 if (start == 0 && size == 0) {
996 DEBUG(0,("client sent 0/0 lock - please report this\n"));
998 #endif
1000 lock = (struct lock_struct) {
1001 .context.smblctx = smblctx,
1002 .context.pid = pid,
1003 .context.tid = br_lck->fsp->conn->cnum,
1004 .start = start,
1005 .size = size,
1006 .fnum = br_lck->fsp->fnum,
1007 .lock_type = lock_type,
1008 .lock_flav = lock_flav
1011 if (lock_flav == WINDOWS_LOCK) {
1012 ret = SMB_VFS_BRL_LOCK_WINDOWS(br_lck->fsp->conn, br_lck,
1013 &lock, blocking_lock);
1014 } else {
1015 ret = brl_lock_posix(msg_ctx, br_lck, &lock);
1018 #if ZERO_ZERO
1019 /* sort the lock list */
1020 TYPESAFE_QSORT(br_lck->lock_data, (size_t)br_lck->num_locks, lock_compare);
1021 #endif
1023 /* If we're returning an error, return who blocked us. */
1024 if (!NT_STATUS_IS_OK(ret) && psmblctx) {
1025 *psmblctx = lock.context.smblctx;
1027 return ret;
1030 static void brl_delete_lock_struct(struct lock_struct *locks,
1031 unsigned num_locks,
1032 unsigned del_idx)
1034 if (del_idx >= num_locks) {
1035 return;
1037 memmove(&locks[del_idx], &locks[del_idx+1],
1038 sizeof(*locks) * (num_locks - del_idx - 1));
1041 /****************************************************************************
1042 Unlock a range of bytes - Windows semantics.
1043 ****************************************************************************/
1045 bool brl_unlock_windows_default(struct messaging_context *msg_ctx,
1046 struct byte_range_lock *br_lck,
1047 const struct lock_struct *plock)
1049 unsigned int i, j;
1050 struct lock_struct *locks = br_lck->lock_data;
1051 enum brl_type deleted_lock_type = READ_LOCK; /* shut the compiler up.... */
1053 SMB_ASSERT(plock->lock_type == UNLOCK_LOCK);
1055 #if ZERO_ZERO
1056 /* Delete write locks by preference... The lock list
1057 is sorted in the zero zero case. */
1059 for (i = 0; i < br_lck->num_locks; i++) {
1060 struct lock_struct *lock = &locks[i];
1062 if (lock->lock_type == WRITE_LOCK &&
1063 brl_same_context(&lock->context, &plock->context) &&
1064 lock->fnum == plock->fnum &&
1065 lock->lock_flav == WINDOWS_LOCK &&
1066 lock->start == plock->start &&
1067 lock->size == plock->size) {
1069 /* found it - delete it */
1070 deleted_lock_type = lock->lock_type;
1071 break;
1075 if (i != br_lck->num_locks) {
1076 /* We found it - don't search again. */
1077 goto unlock_continue;
1079 #endif
1081 for (i = 0; i < br_lck->num_locks; i++) {
1082 struct lock_struct *lock = &locks[i];
1084 if (IS_PENDING_LOCK(lock->lock_type)) {
1085 continue;
1088 /* Only remove our own locks that match in start, size, and flavour. */
1089 if (brl_same_context(&lock->context, &plock->context) &&
1090 lock->fnum == plock->fnum &&
1091 lock->lock_flav == WINDOWS_LOCK &&
1092 lock->start == plock->start &&
1093 lock->size == plock->size ) {
1094 deleted_lock_type = lock->lock_type;
1095 break;
1099 if (i == br_lck->num_locks) {
1100 /* we didn't find it */
1101 return False;
1104 #if ZERO_ZERO
1105 unlock_continue:
1106 #endif
1108 brl_delete_lock_struct(locks, br_lck->num_locks, i);
1109 br_lck->num_locks -= 1;
1110 br_lck->modified = True;
1112 /* Unlock the underlying POSIX regions. */
1113 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1114 release_posix_lock_windows_flavour(br_lck->fsp,
1115 plock->start,
1116 plock->size,
1117 deleted_lock_type,
1118 &plock->context,
1119 locks,
1120 br_lck->num_locks);
1123 /* Send unlock messages to any pending waiters that overlap. */
1124 for (j=0; j < br_lck->num_locks; j++) {
1125 struct lock_struct *pend_lock = &locks[j];
1127 /* Ignore non-pending locks. */
1128 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1129 continue;
1132 /* We could send specific lock info here... */
1133 if (brl_pending_overlap(plock, pend_lock)) {
1134 DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
1135 procid_str_static(&pend_lock->context.pid )));
1137 messaging_send(msg_ctx, pend_lock->context.pid,
1138 MSG_SMB_UNLOCK, &data_blob_null);
1142 contend_level2_oplocks_end(br_lck->fsp, LEVEL2_CONTEND_WINDOWS_BRL);
1143 return True;
1146 /****************************************************************************
1147 Unlock a range of bytes - POSIX semantics.
1148 ****************************************************************************/
1150 static bool brl_unlock_posix(struct messaging_context *msg_ctx,
1151 struct byte_range_lock *br_lck,
1152 struct lock_struct *plock)
1154 unsigned int i, j, count;
1155 struct lock_struct *tp;
1156 struct lock_struct *locks = br_lck->lock_data;
1157 bool overlap_found = False;
1159 /* No zero-zero locks for POSIX. */
1160 if (plock->start == 0 && plock->size == 0) {
1161 return False;
1164 /* Don't allow 64-bit lock wrap. */
1165 if (plock->start + plock->size < plock->start ||
1166 plock->start + plock->size < plock->size) {
1167 DEBUG(10,("brl_unlock_posix: lock wrap\n"));
1168 return False;
1171 /* The worst case scenario here is we have to split an
1172 existing POSIX lock range into two, so we need at most
1173 1 more entry. */
1175 tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 1);
1176 if (!tp) {
1177 DEBUG(10,("brl_unlock_posix: malloc fail\n"));
1178 return False;
1181 count = 0;
1182 for (i = 0; i < br_lck->num_locks; i++) {
1183 struct lock_struct *lock = &locks[i];
1184 unsigned int tmp_count;
1186 /* Only remove our own locks - ignore fnum. */
1187 if (IS_PENDING_LOCK(lock->lock_type) ||
1188 !brl_same_context(&lock->context, &plock->context)) {
1189 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1190 count++;
1191 continue;
1194 if (lock->lock_flav == WINDOWS_LOCK) {
1195 /* Do any Windows flavour locks conflict ? */
1196 if (brl_conflict(lock, plock)) {
1197 TALLOC_FREE(tp);
1198 return false;
1200 /* Just copy the Windows lock into the new array. */
1201 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1202 count++;
1203 continue;
1206 /* Work out overlaps. */
1207 tmp_count = brlock_posix_split_merge(&tp[count], lock, plock);
1209 if (tmp_count == 0) {
1210 /* plock overlapped the existing lock completely,
1211 or replaced it. Don't copy the existing lock. */
1212 overlap_found = true;
1213 } else if (tmp_count == 1) {
1214 /* Either no overlap, (simple copy of existing lock) or
1215 * an overlap of an existing lock. */
1216 /* If the lock changed size, we had an overlap. */
1217 if (tp[count].size != lock->size) {
1218 overlap_found = true;
1220 count += tmp_count;
1221 } else if (tmp_count == 2) {
1222 /* We split a lock range in two. */
1223 overlap_found = true;
1224 count += tmp_count;
1226 /* Optimisation... */
1227 /* We know we're finished here as we can't overlap any
1228 more POSIX locks. Copy the rest of the lock array. */
1230 if (i < br_lck->num_locks - 1) {
1231 memcpy(&tp[count], &locks[i+1],
1232 sizeof(*locks)*((br_lck->num_locks-1) - i));
1233 count += ((br_lck->num_locks-1) - i);
1235 break;
1240 if (!overlap_found) {
1241 /* Just ignore - no change. */
1242 TALLOC_FREE(tp);
1243 DEBUG(10,("brl_unlock_posix: No overlap - unlocked.\n"));
1244 return True;
1247 /* Unlock any POSIX regions. */
1248 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1249 release_posix_lock_posix_flavour(br_lck->fsp,
1250 plock->start,
1251 plock->size,
1252 &plock->context,
1254 count);
1257 /* Realloc so we don't leak entries per unlock call. */
1258 if (count) {
1259 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
1260 if (!tp) {
1261 DEBUG(10,("brl_unlock_posix: realloc fail\n"));
1262 return False;
1264 } else {
1265 /* We deleted the last lock. */
1266 TALLOC_FREE(tp);
1267 tp = NULL;
1270 contend_level2_oplocks_end(br_lck->fsp,
1271 LEVEL2_CONTEND_POSIX_BRL);
1273 br_lck->num_locks = count;
1274 TALLOC_FREE(br_lck->lock_data);
1275 locks = tp;
1276 br_lck->lock_data = tp;
1277 br_lck->modified = True;
1279 /* Send unlock messages to any pending waiters that overlap. */
1281 for (j=0; j < br_lck->num_locks; j++) {
1282 struct lock_struct *pend_lock = &locks[j];
1284 /* Ignore non-pending locks. */
1285 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1286 continue;
1289 /* We could send specific lock info here... */
1290 if (brl_pending_overlap(plock, pend_lock)) {
1291 DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
1292 procid_str_static(&pend_lock->context.pid )));
1294 messaging_send(msg_ctx, pend_lock->context.pid,
1295 MSG_SMB_UNLOCK, &data_blob_null);
1299 return True;
1302 bool smb_vfs_call_brl_unlock_windows(struct vfs_handle_struct *handle,
1303 struct messaging_context *msg_ctx,
1304 struct byte_range_lock *br_lck,
1305 const struct lock_struct *plock)
1307 VFS_FIND(brl_unlock_windows);
1308 return handle->fns->brl_unlock_windows_fn(handle, msg_ctx, br_lck,
1309 plock);
1312 /****************************************************************************
1313 Unlock a range of bytes.
1314 ****************************************************************************/
1316 bool brl_unlock(struct messaging_context *msg_ctx,
1317 struct byte_range_lock *br_lck,
1318 uint64_t smblctx,
1319 struct server_id pid,
1320 br_off start,
1321 br_off size,
1322 enum brl_flavour lock_flav)
1324 struct lock_struct lock;
1326 lock.context.smblctx = smblctx;
1327 lock.context.pid = pid;
1328 lock.context.tid = br_lck->fsp->conn->cnum;
1329 lock.start = start;
1330 lock.size = size;
1331 lock.fnum = br_lck->fsp->fnum;
1332 lock.lock_type = UNLOCK_LOCK;
1333 lock.lock_flav = lock_flav;
1335 if (lock_flav == WINDOWS_LOCK) {
1336 return SMB_VFS_BRL_UNLOCK_WINDOWS(br_lck->fsp->conn, msg_ctx,
1337 br_lck, &lock);
1338 } else {
1339 return brl_unlock_posix(msg_ctx, br_lck, &lock);
1343 /****************************************************************************
1344 Test if we could add a lock if we wanted to.
1345 Returns True if the region required is currently unlocked, False if locked.
1346 ****************************************************************************/
1348 bool brl_locktest(struct byte_range_lock *br_lck,
1349 uint64_t smblctx,
1350 struct server_id pid,
1351 br_off start,
1352 br_off size,
1353 enum brl_type lock_type,
1354 enum brl_flavour lock_flav)
1356 bool ret = True;
1357 unsigned int i;
1358 struct lock_struct lock;
1359 const struct lock_struct *locks = br_lck->lock_data;
1360 files_struct *fsp = br_lck->fsp;
1362 lock.context.smblctx = smblctx;
1363 lock.context.pid = pid;
1364 lock.context.tid = br_lck->fsp->conn->cnum;
1365 lock.start = start;
1366 lock.size = size;
1367 lock.fnum = fsp->fnum;
1368 lock.lock_type = lock_type;
1369 lock.lock_flav = lock_flav;
1371 /* Make sure existing locks don't conflict */
1372 for (i=0; i < br_lck->num_locks; i++) {
1374 * Our own locks don't conflict.
1376 if (brl_conflict_other(&locks[i], &lock)) {
1377 return False;
1382 * There is no lock held by an SMB daemon, check to
1383 * see if there is a POSIX lock from a UNIX or NFS process.
1384 * This only conflicts with Windows locks, not POSIX locks.
1387 if(lp_posix_locking(fsp->conn->params) && (lock_flav == WINDOWS_LOCK)) {
1388 ret = is_posix_locked(fsp, &start, &size, &lock_type, WINDOWS_LOCK);
1390 DEBUG(10, ("brl_locktest: posix start=%ju len=%ju %s for %s "
1391 "file %s\n", (uintmax_t)start, (uintmax_t)size,
1392 ret ? "locked" : "unlocked",
1393 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1395 /* We need to return the inverse of is_posix_locked. */
1396 ret = !ret;
1399 /* no conflicts - we could have added it */
1400 return ret;
1403 /****************************************************************************
1404 Query for existing locks.
1405 ****************************************************************************/
1407 NTSTATUS brl_lockquery(struct byte_range_lock *br_lck,
1408 uint64_t *psmblctx,
1409 struct server_id pid,
1410 br_off *pstart,
1411 br_off *psize,
1412 enum brl_type *plock_type,
1413 enum brl_flavour lock_flav)
1415 unsigned int i;
1416 struct lock_struct lock;
1417 const struct lock_struct *locks = br_lck->lock_data;
1418 files_struct *fsp = br_lck->fsp;
1420 lock.context.smblctx = *psmblctx;
1421 lock.context.pid = pid;
1422 lock.context.tid = br_lck->fsp->conn->cnum;
1423 lock.start = *pstart;
1424 lock.size = *psize;
1425 lock.fnum = fsp->fnum;
1426 lock.lock_type = *plock_type;
1427 lock.lock_flav = lock_flav;
1429 /* Make sure existing locks don't conflict */
1430 for (i=0; i < br_lck->num_locks; i++) {
1431 const struct lock_struct *exlock = &locks[i];
1432 bool conflict = False;
1434 if (exlock->lock_flav == WINDOWS_LOCK) {
1435 conflict = brl_conflict(exlock, &lock);
1436 } else {
1437 conflict = brl_conflict_posix(exlock, &lock);
1440 if (conflict) {
1441 *psmblctx = exlock->context.smblctx;
1442 *pstart = exlock->start;
1443 *psize = exlock->size;
1444 *plock_type = exlock->lock_type;
1445 return NT_STATUS_LOCK_NOT_GRANTED;
1450 * There is no lock held by an SMB daemon, check to
1451 * see if there is a POSIX lock from a UNIX or NFS process.
1454 if(lp_posix_locking(fsp->conn->params)) {
1455 bool ret = is_posix_locked(fsp, pstart, psize, plock_type, POSIX_LOCK);
1457 DEBUG(10, ("brl_lockquery: posix start=%ju len=%ju %s for %s "
1458 "file %s\n", (uintmax_t)*pstart,
1459 (uintmax_t)*psize, ret ? "locked" : "unlocked",
1460 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1462 if (ret) {
1463 /* Hmmm. No clue what to set smblctx to - use -1. */
1464 *psmblctx = 0xFFFFFFFFFFFFFFFFLL;
1465 return NT_STATUS_LOCK_NOT_GRANTED;
1469 return NT_STATUS_OK;
1473 bool smb_vfs_call_brl_cancel_windows(struct vfs_handle_struct *handle,
1474 struct byte_range_lock *br_lck,
1475 struct lock_struct *plock)
1477 VFS_FIND(brl_cancel_windows);
1478 return handle->fns->brl_cancel_windows_fn(handle, br_lck, plock);
1481 /****************************************************************************
1482 Remove a particular pending lock.
1483 ****************************************************************************/
1484 bool brl_lock_cancel(struct byte_range_lock *br_lck,
1485 uint64_t smblctx,
1486 struct server_id pid,
1487 br_off start,
1488 br_off size,
1489 enum brl_flavour lock_flav)
1491 bool ret;
1492 struct lock_struct lock;
1494 lock.context.smblctx = smblctx;
1495 lock.context.pid = pid;
1496 lock.context.tid = br_lck->fsp->conn->cnum;
1497 lock.start = start;
1498 lock.size = size;
1499 lock.fnum = br_lck->fsp->fnum;
1500 lock.lock_flav = lock_flav;
1501 /* lock.lock_type doesn't matter */
1503 if (lock_flav == WINDOWS_LOCK) {
1504 ret = SMB_VFS_BRL_CANCEL_WINDOWS(br_lck->fsp->conn, br_lck,
1505 &lock);
1506 } else {
1507 ret = brl_lock_cancel_default(br_lck, &lock);
1510 return ret;
1513 bool brl_lock_cancel_default(struct byte_range_lock *br_lck,
1514 struct lock_struct *plock)
1516 unsigned int i;
1517 struct lock_struct *locks = br_lck->lock_data;
1519 SMB_ASSERT(plock);
1521 for (i = 0; i < br_lck->num_locks; i++) {
1522 struct lock_struct *lock = &locks[i];
1524 /* For pending locks we *always* care about the fnum. */
1525 if (brl_same_context(&lock->context, &plock->context) &&
1526 lock->fnum == plock->fnum &&
1527 IS_PENDING_LOCK(lock->lock_type) &&
1528 lock->lock_flav == plock->lock_flav &&
1529 lock->start == plock->start &&
1530 lock->size == plock->size) {
1531 break;
1535 if (i == br_lck->num_locks) {
1536 /* Didn't find it. */
1537 return False;
1540 brl_delete_lock_struct(locks, br_lck->num_locks, i);
1541 br_lck->num_locks -= 1;
1542 br_lck->modified = True;
1543 return True;
1546 /****************************************************************************
1547 Remove any locks associated with a open file.
1548 We return True if this process owns any other Windows locks on this
1549 fd and so we should not immediately close the fd.
1550 ****************************************************************************/
1552 void brl_close_fnum(struct messaging_context *msg_ctx,
1553 struct byte_range_lock *br_lck)
1555 files_struct *fsp = br_lck->fsp;
1556 uint32_t tid = fsp->conn->cnum;
1557 uint64_t fnum = fsp->fnum;
1558 unsigned int i;
1559 struct lock_struct *locks = br_lck->lock_data;
1560 struct server_id pid = messaging_server_id(fsp->conn->sconn->msg_ctx);
1561 struct lock_struct *locks_copy;
1562 unsigned int num_locks_copy;
1564 /* Copy the current lock array. */
1565 if (br_lck->num_locks) {
1566 locks_copy = (struct lock_struct *)talloc_memdup(br_lck, locks, br_lck->num_locks * sizeof(struct lock_struct));
1567 if (!locks_copy) {
1568 smb_panic("brl_close_fnum: talloc failed");
1570 } else {
1571 locks_copy = NULL;
1574 num_locks_copy = br_lck->num_locks;
1576 for (i=0; i < num_locks_copy; i++) {
1577 struct lock_struct *lock = &locks_copy[i];
1579 if (lock->context.tid == tid && serverid_equal(&lock->context.pid, &pid) &&
1580 (lock->fnum == fnum)) {
1581 brl_unlock(msg_ctx,
1582 br_lck,
1583 lock->context.smblctx,
1584 pid,
1585 lock->start,
1586 lock->size,
1587 lock->lock_flav);
1592 bool brl_mark_disconnected(struct files_struct *fsp)
1594 uint32_t tid = fsp->conn->cnum;
1595 uint64_t smblctx;
1596 uint64_t fnum = fsp->fnum;
1597 unsigned int i;
1598 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1599 struct byte_range_lock *br_lck = NULL;
1601 if (fsp->op == NULL) {
1602 return false;
1605 smblctx = fsp->op->global->open_persistent_id;
1607 if (!fsp->op->global->durable) {
1608 return false;
1611 if (fsp->current_lock_count == 0) {
1612 return true;
1615 br_lck = brl_get_locks(talloc_tos(), fsp);
1616 if (br_lck == NULL) {
1617 return false;
1620 for (i=0; i < br_lck->num_locks; i++) {
1621 struct lock_struct *lock = &br_lck->lock_data[i];
1624 * as this is a durable handle, we only expect locks
1625 * of the current file handle!
1628 if (lock->context.smblctx != smblctx) {
1629 TALLOC_FREE(br_lck);
1630 return false;
1633 if (lock->context.tid != tid) {
1634 TALLOC_FREE(br_lck);
1635 return false;
1638 if (!serverid_equal(&lock->context.pid, &self)) {
1639 TALLOC_FREE(br_lck);
1640 return false;
1643 if (lock->fnum != fnum) {
1644 TALLOC_FREE(br_lck);
1645 return false;
1648 server_id_set_disconnected(&lock->context.pid);
1649 lock->context.tid = TID_FIELD_INVALID;
1650 lock->fnum = FNUM_FIELD_INVALID;
1653 br_lck->modified = true;
1654 TALLOC_FREE(br_lck);
1655 return true;
1658 bool brl_reconnect_disconnected(struct files_struct *fsp)
1660 uint32_t tid = fsp->conn->cnum;
1661 uint64_t smblctx;
1662 uint64_t fnum = fsp->fnum;
1663 unsigned int i;
1664 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1665 struct byte_range_lock *br_lck = NULL;
1667 if (fsp->op == NULL) {
1668 return false;
1671 smblctx = fsp->op->global->open_persistent_id;
1673 if (!fsp->op->global->durable) {
1674 return false;
1678 * When reconnecting, we do not want to validate the brlock entries
1679 * and thereby remove our own (disconnected) entries but reactivate
1680 * them instead.
1682 fsp->lockdb_clean = true;
1684 br_lck = brl_get_locks(talloc_tos(), fsp);
1685 if (br_lck == NULL) {
1686 return false;
1689 if (br_lck->num_locks == 0) {
1690 TALLOC_FREE(br_lck);
1691 return true;
1694 for (i=0; i < br_lck->num_locks; i++) {
1695 struct lock_struct *lock = &br_lck->lock_data[i];
1698 * as this is a durable handle we only expect locks
1699 * of the current file handle!
1702 if (lock->context.smblctx != smblctx) {
1703 TALLOC_FREE(br_lck);
1704 return false;
1707 if (lock->context.tid != TID_FIELD_INVALID) {
1708 TALLOC_FREE(br_lck);
1709 return false;
1712 if (!server_id_is_disconnected(&lock->context.pid)) {
1713 TALLOC_FREE(br_lck);
1714 return false;
1717 if (lock->fnum != FNUM_FIELD_INVALID) {
1718 TALLOC_FREE(br_lck);
1719 return false;
1722 lock->context.pid = self;
1723 lock->context.tid = tid;
1724 lock->fnum = fnum;
1727 fsp->current_lock_count = br_lck->num_locks;
1728 br_lck->modified = true;
1729 TALLOC_FREE(br_lck);
1730 return true;
1733 /****************************************************************************
1734 Ensure this set of lock entries is valid.
1735 ****************************************************************************/
1736 static bool validate_lock_entries(unsigned int *pnum_entries, struct lock_struct **pplocks,
1737 bool keep_disconnected)
1739 unsigned int i;
1740 struct lock_struct *locks = *pplocks;
1741 unsigned int num_entries = *pnum_entries;
1742 TALLOC_CTX *frame;
1743 struct server_id *ids;
1744 bool *exists;
1746 if (num_entries == 0) {
1747 return true;
1750 frame = talloc_stackframe();
1752 ids = talloc_array(frame, struct server_id, num_entries);
1753 if (ids == NULL) {
1754 DEBUG(0, ("validate_lock_entries: "
1755 "talloc_array(struct server_id, %u) failed\n",
1756 num_entries));
1757 talloc_free(frame);
1758 return false;
1761 exists = talloc_array(frame, bool, num_entries);
1762 if (exists == NULL) {
1763 DEBUG(0, ("validate_lock_entries: "
1764 "talloc_array(bool, %u) failed\n",
1765 num_entries));
1766 talloc_free(frame);
1767 return false;
1770 for (i = 0; i < num_entries; i++) {
1771 ids[i] = locks[i].context.pid;
1774 if (!serverids_exist(ids, num_entries, exists)) {
1775 DEBUG(3, ("validate_lock_entries: serverids_exists failed\n"));
1776 talloc_free(frame);
1777 return false;
1780 i = 0;
1782 while (i < num_entries) {
1783 if (exists[i]) {
1784 i++;
1785 continue;
1788 if (keep_disconnected &&
1789 server_id_is_disconnected(&ids[i]))
1791 i++;
1792 continue;
1795 /* This process no longer exists */
1797 brl_delete_lock_struct(locks, num_entries, i);
1798 num_entries -= 1;
1800 TALLOC_FREE(frame);
1802 *pnum_entries = num_entries;
1804 return True;
1807 struct brl_forall_cb {
1808 void (*fn)(struct file_id id, struct server_id pid,
1809 enum brl_type lock_type,
1810 enum brl_flavour lock_flav,
1811 br_off start, br_off size,
1812 void *private_data);
1813 void *private_data;
1816 /****************************************************************************
1817 Traverse the whole database with this function, calling traverse_callback
1818 on each lock.
1819 ****************************************************************************/
1821 static int brl_traverse_fn(struct db_record *rec, void *state)
1823 struct brl_forall_cb *cb = (struct brl_forall_cb *)state;
1824 struct lock_struct *locks;
1825 struct file_id *key;
1826 unsigned int i;
1827 unsigned int num_locks = 0;
1828 unsigned int orig_num_locks = 0;
1829 TDB_DATA dbkey;
1830 TDB_DATA value;
1832 dbkey = dbwrap_record_get_key(rec);
1833 value = dbwrap_record_get_value(rec);
1835 /* In a traverse function we must make a copy of
1836 dbuf before modifying it. */
1838 locks = (struct lock_struct *)talloc_memdup(
1839 talloc_tos(), value.dptr, value.dsize);
1840 if (!locks) {
1841 return -1; /* Terminate traversal. */
1844 key = (struct file_id *)dbkey.dptr;
1845 orig_num_locks = num_locks = value.dsize/sizeof(*locks);
1847 /* Ensure the lock db is clean of entries from invalid processes. */
1849 if (!validate_lock_entries(&num_locks, &locks, true)) {
1850 TALLOC_FREE(locks);
1851 return -1; /* Terminate traversal */
1854 if (orig_num_locks != num_locks) {
1855 if (num_locks) {
1856 TDB_DATA data;
1857 data.dptr = (uint8_t *)locks;
1858 data.dsize = num_locks*sizeof(struct lock_struct);
1859 dbwrap_record_store(rec, data, TDB_REPLACE);
1860 } else {
1861 dbwrap_record_delete(rec);
1865 if (cb->fn) {
1866 for ( i=0; i<num_locks; i++) {
1867 cb->fn(*key,
1868 locks[i].context.pid,
1869 locks[i].lock_type,
1870 locks[i].lock_flav,
1871 locks[i].start,
1872 locks[i].size,
1873 cb->private_data);
1877 TALLOC_FREE(locks);
1878 return 0;
1881 /*******************************************************************
1882 Call the specified function on each lock in the database.
1883 ********************************************************************/
1885 int brl_forall(void (*fn)(struct file_id id, struct server_id pid,
1886 enum brl_type lock_type,
1887 enum brl_flavour lock_flav,
1888 br_off start, br_off size,
1889 void *private_data),
1890 void *private_data)
1892 struct brl_forall_cb cb;
1893 NTSTATUS status;
1894 int count = 0;
1896 if (!brlock_db) {
1897 return 0;
1899 cb.fn = fn;
1900 cb.private_data = private_data;
1901 status = dbwrap_traverse(brlock_db, brl_traverse_fn, &cb, &count);
1903 if (!NT_STATUS_IS_OK(status)) {
1904 return -1;
1905 } else {
1906 return count;
1910 /*******************************************************************
1911 Store a potentially modified set of byte range lock data back into
1912 the database.
1913 Unlock the record.
1914 ********************************************************************/
1916 static void byte_range_lock_flush(struct byte_range_lock *br_lck)
1918 size_t data_len;
1919 if (!br_lck->modified) {
1920 DEBUG(10, ("br_lck not modified\n"));
1921 goto done;
1924 data_len = br_lck->num_locks * sizeof(struct lock_struct);
1926 if (br_lck->have_read_oplocks) {
1927 data_len += 1;
1930 DEBUG(10, ("data_len=%d\n", (int)data_len));
1932 if (data_len == 0) {
1933 /* No locks - delete this entry. */
1934 NTSTATUS status = dbwrap_record_delete(br_lck->record);
1935 if (!NT_STATUS_IS_OK(status)) {
1936 DEBUG(0, ("delete_rec returned %s\n",
1937 nt_errstr(status)));
1938 smb_panic("Could not delete byte range lock entry");
1940 } else {
1941 TDB_DATA data;
1942 NTSTATUS status;
1944 data.dsize = data_len;
1945 data.dptr = talloc_array(talloc_tos(), uint8_t, data_len);
1946 SMB_ASSERT(data.dptr != NULL);
1948 memcpy(data.dptr, br_lck->lock_data,
1949 br_lck->num_locks * sizeof(struct lock_struct));
1951 if (br_lck->have_read_oplocks) {
1952 data.dptr[data_len-1] = 1;
1955 status = dbwrap_record_store(br_lck->record, data, TDB_REPLACE);
1956 TALLOC_FREE(data.dptr);
1957 if (!NT_STATUS_IS_OK(status)) {
1958 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
1959 smb_panic("Could not store byte range mode entry");
1963 DEBUG(10, ("seqnum=%d\n", dbwrap_get_seqnum(brlock_db)));
1965 done:
1966 br_lck->modified = false;
1967 TALLOC_FREE(br_lck->record);
1970 static int byte_range_lock_destructor(struct byte_range_lock *br_lck)
1972 byte_range_lock_flush(br_lck);
1973 return 0;
1976 /*******************************************************************
1977 Fetch a set of byte range lock data from the database.
1978 Leave the record locked.
1979 TALLOC_FREE(brl) will release the lock in the destructor.
1980 ********************************************************************/
1982 struct byte_range_lock *brl_get_locks(TALLOC_CTX *mem_ctx, files_struct *fsp)
1984 TDB_DATA key, data;
1985 struct byte_range_lock *br_lck = talloc(mem_ctx, struct byte_range_lock);
1987 if (br_lck == NULL) {
1988 return NULL;
1991 br_lck->fsp = fsp;
1992 br_lck->num_locks = 0;
1993 br_lck->have_read_oplocks = false;
1994 br_lck->modified = False;
1996 key.dptr = (uint8 *)&fsp->file_id;
1997 key.dsize = sizeof(struct file_id);
1999 br_lck->record = dbwrap_fetch_locked(brlock_db, br_lck, key);
2001 if (br_lck->record == NULL) {
2002 DEBUG(3, ("Could not lock byte range lock entry\n"));
2003 TALLOC_FREE(br_lck);
2004 return NULL;
2007 data = dbwrap_record_get_value(br_lck->record);
2009 br_lck->lock_data = NULL;
2011 talloc_set_destructor(br_lck, byte_range_lock_destructor);
2013 br_lck->num_locks = data.dsize / sizeof(struct lock_struct);
2015 if (br_lck->num_locks != 0) {
2016 br_lck->lock_data = talloc_array(
2017 br_lck, struct lock_struct, br_lck->num_locks);
2018 if (br_lck->lock_data == NULL) {
2019 DEBUG(0, ("malloc failed\n"));
2020 TALLOC_FREE(br_lck);
2021 return NULL;
2024 memcpy(br_lck->lock_data, data.dptr,
2025 talloc_get_size(br_lck->lock_data));
2028 DEBUG(10, ("data.dsize=%d\n", (int)data.dsize));
2030 if ((data.dsize % sizeof(struct lock_struct)) == 1) {
2031 br_lck->have_read_oplocks = (data.dptr[data.dsize-1] == 1);
2034 if (!fsp->lockdb_clean) {
2035 int orig_num_locks = br_lck->num_locks;
2038 * This is the first time we access the byte range lock
2039 * record with this fsp. Go through and ensure all entries
2040 * are valid - remove any that don't.
2041 * This makes the lockdb self cleaning at low cost.
2043 * Note: Disconnected entries belong to disconnected
2044 * durable handles. So at this point, we have a new
2045 * handle on the file and the disconnected durable has
2046 * already been closed (we are not a durable reconnect).
2047 * So we need to clean the disconnected brl entry.
2050 if (!validate_lock_entries(&br_lck->num_locks,
2051 &br_lck->lock_data, false)) {
2052 TALLOC_FREE(br_lck);
2053 return NULL;
2056 /* Ensure invalid locks are cleaned up in the destructor. */
2057 if (orig_num_locks != br_lck->num_locks) {
2058 br_lck->modified = True;
2061 /* Mark the lockdb as "clean" as seen from this open file. */
2062 fsp->lockdb_clean = True;
2065 if (DEBUGLEVEL >= 10) {
2066 unsigned int i;
2067 struct lock_struct *locks = br_lck->lock_data;
2068 DEBUG(10,("brl_get_locks_internal: %u current locks on file_id %s\n",
2069 br_lck->num_locks,
2070 file_id_string_tos(&fsp->file_id)));
2071 for( i = 0; i < br_lck->num_locks; i++) {
2072 print_lock_struct(i, &locks[i]);
2076 return br_lck;
2079 struct brl_get_locks_readonly_state {
2080 TALLOC_CTX *mem_ctx;
2081 struct byte_range_lock **br_lock;
2084 static void brl_get_locks_readonly_parser(TDB_DATA key, TDB_DATA data,
2085 void *private_data)
2087 struct brl_get_locks_readonly_state *state =
2088 (struct brl_get_locks_readonly_state *)private_data;
2089 struct byte_range_lock *br_lock;
2091 br_lock = talloc_pooled_object(
2092 state->mem_ctx, struct byte_range_lock, 1, data.dsize);
2093 if (br_lock == NULL) {
2094 *state->br_lock = NULL;
2095 return;
2097 br_lock->lock_data = (struct lock_struct *)talloc_memdup(
2098 br_lock, data.dptr, data.dsize);
2099 br_lock->num_locks = data.dsize / sizeof(struct lock_struct);
2101 if ((data.dsize % sizeof(struct lock_struct)) == 1) {
2102 br_lock->have_read_oplocks = (data.dptr[data.dsize-1] == 1);
2103 } else {
2104 br_lock->have_read_oplocks = false;
2107 DEBUG(10, ("Got %d bytes, have_read_oplocks: %s\n", (int)data.dsize,
2108 br_lock->have_read_oplocks ? "true" : "false"));
2110 *state->br_lock = br_lock;
2113 struct byte_range_lock *brl_get_locks_readonly(files_struct *fsp)
2115 struct byte_range_lock *br_lock = NULL;
2116 struct byte_range_lock *rw = NULL;
2118 DEBUG(10, ("seqnum=%d, fsp->brlock_seqnum=%d\n",
2119 dbwrap_get_seqnum(brlock_db), fsp->brlock_seqnum));
2121 if ((fsp->brlock_rec != NULL)
2122 && (dbwrap_get_seqnum(brlock_db) == fsp->brlock_seqnum)) {
2124 * We have cached the brlock_rec and the database did not
2125 * change.
2127 return fsp->brlock_rec;
2130 if (!fsp->lockdb_clean) {
2132 * Fetch the record in R/W mode to give validate_lock_entries
2133 * a chance to kick in once.
2135 rw = brl_get_locks(talloc_tos(), fsp);
2136 if (rw == NULL) {
2137 return NULL;
2139 fsp->lockdb_clean = true;
2142 if (rw != NULL) {
2143 size_t lock_data_size;
2146 * Make a copy of the already retrieved and sanitized rw record
2148 lock_data_size = rw->num_locks * sizeof(struct lock_struct);
2149 br_lock = talloc_pooled_object(
2150 fsp, struct byte_range_lock, 1, lock_data_size);
2151 if (br_lock == NULL) {
2152 goto fail;
2154 br_lock->have_read_oplocks = rw->have_read_oplocks;
2155 br_lock->num_locks = rw->num_locks;
2156 br_lock->lock_data = (struct lock_struct *)talloc_memdup(
2157 br_lock, rw->lock_data, lock_data_size);
2158 } else {
2159 struct brl_get_locks_readonly_state state;
2160 NTSTATUS status;
2163 * Parse the record fresh from the database
2166 state.mem_ctx = fsp;
2167 state.br_lock = &br_lock;
2169 status = dbwrap_parse_record(
2170 brlock_db,
2171 make_tdb_data((uint8_t *)&fsp->file_id,
2172 sizeof(fsp->file_id)),
2173 brl_get_locks_readonly_parser, &state);
2175 if (NT_STATUS_EQUAL(status,NT_STATUS_NOT_FOUND)) {
2177 * No locks on this file. Return an empty br_lock.
2179 br_lock = talloc(fsp, struct byte_range_lock);
2180 if (br_lock == NULL) {
2181 goto fail;
2184 br_lock->have_read_oplocks = false;
2185 br_lock->num_locks = 0;
2186 br_lock->lock_data = NULL;
2188 } else if (!NT_STATUS_IS_OK(status)) {
2189 DEBUG(3, ("Could not parse byte range lock record: "
2190 "%s\n", nt_errstr(status)));
2191 goto fail;
2193 if (br_lock == NULL) {
2194 goto fail;
2198 br_lock->fsp = fsp;
2199 br_lock->modified = false;
2200 br_lock->record = NULL;
2202 if (lp_clustering()) {
2204 * In the cluster case we can't cache the brlock struct
2205 * because dbwrap_get_seqnum does not work reliably over
2206 * ctdb. Thus we have to throw away the brlock struct soon.
2208 talloc_steal(talloc_tos(), br_lock);
2209 } else {
2211 * Cache the brlock struct, invalidated when the dbwrap_seqnum
2212 * changes. See beginning of this routine.
2214 TALLOC_FREE(fsp->brlock_rec);
2215 fsp->brlock_rec = br_lock;
2216 fsp->brlock_seqnum = dbwrap_get_seqnum(brlock_db);
2219 fail:
2220 TALLOC_FREE(rw);
2221 return br_lock;
2224 struct brl_revalidate_state {
2225 ssize_t array_size;
2226 uint32 num_pids;
2227 struct server_id *pids;
2231 * Collect PIDs of all processes with pending entries
2234 static void brl_revalidate_collect(struct file_id id, struct server_id pid,
2235 enum brl_type lock_type,
2236 enum brl_flavour lock_flav,
2237 br_off start, br_off size,
2238 void *private_data)
2240 struct brl_revalidate_state *state =
2241 (struct brl_revalidate_state *)private_data;
2243 if (!IS_PENDING_LOCK(lock_type)) {
2244 return;
2247 add_to_large_array(state, sizeof(pid), (void *)&pid,
2248 &state->pids, &state->num_pids,
2249 &state->array_size);
2253 * qsort callback to sort the processes
2256 static int compare_procids(const void *p1, const void *p2)
2258 const struct server_id *i1 = (const struct server_id *)p1;
2259 const struct server_id *i2 = (const struct server_id *)p2;
2261 if (i1->pid < i2->pid) return -1;
2262 if (i1->pid > i2->pid) return 1;
2263 return 0;
2267 * Send a MSG_SMB_UNLOCK message to all processes with pending byte range
2268 * locks so that they retry. Mainly used in the cluster code after a node has
2269 * died.
2271 * Done in two steps to avoid double-sends: First we collect all entries in an
2272 * array, then qsort that array and only send to non-dupes.
2275 void brl_revalidate(struct messaging_context *msg_ctx,
2276 void *private_data,
2277 uint32_t msg_type,
2278 struct server_id server_id,
2279 DATA_BLOB *data)
2281 struct brl_revalidate_state *state;
2282 uint32 i;
2283 struct server_id last_pid;
2285 if (!(state = talloc_zero(NULL, struct brl_revalidate_state))) {
2286 DEBUG(0, ("talloc failed\n"));
2287 return;
2290 brl_forall(brl_revalidate_collect, state);
2292 if (state->array_size == -1) {
2293 DEBUG(0, ("talloc failed\n"));
2294 goto done;
2297 if (state->num_pids == 0) {
2298 goto done;
2301 TYPESAFE_QSORT(state->pids, state->num_pids, compare_procids);
2303 ZERO_STRUCT(last_pid);
2305 for (i=0; i<state->num_pids; i++) {
2306 if (serverid_equal(&last_pid, &state->pids[i])) {
2308 * We've seen that one already
2310 continue;
2313 messaging_send(msg_ctx, state->pids[i], MSG_SMB_UNLOCK,
2314 &data_blob_null);
2315 last_pid = state->pids[i];
2318 done:
2319 TALLOC_FREE(state);
2320 return;
2323 bool brl_cleanup_disconnected(struct file_id fid, uint64_t open_persistent_id)
2325 bool ret = false;
2326 TALLOC_CTX *frame = talloc_stackframe();
2327 TDB_DATA key, val;
2328 struct db_record *rec;
2329 struct lock_struct *lock;
2330 unsigned n, num;
2331 NTSTATUS status;
2333 key = make_tdb_data((void*)&fid, sizeof(fid));
2335 rec = dbwrap_fetch_locked(brlock_db, frame, key);
2336 if (rec == NULL) {
2337 DEBUG(5, ("brl_cleanup_disconnected: failed to fetch record "
2338 "for file %s\n", file_id_string(frame, &fid)));
2339 goto done;
2342 val = dbwrap_record_get_value(rec);
2343 lock = (struct lock_struct*)val.dptr;
2344 num = val.dsize / sizeof(struct lock_struct);
2345 if (lock == NULL) {
2346 DEBUG(10, ("brl_cleanup_disconnected: no byte range locks for "
2347 "file %s\n", file_id_string(frame, &fid)));
2348 ret = true;
2349 goto done;
2352 for (n=0; n<num; n++) {
2353 struct lock_context *ctx = &lock[n].context;
2355 if (!server_id_is_disconnected(&ctx->pid)) {
2356 DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2357 "%s used by server %s, do not cleanup\n",
2358 file_id_string(frame, &fid),
2359 server_id_str(frame, &ctx->pid)));
2360 goto done;
2363 if (ctx->smblctx != open_persistent_id) {
2364 DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2365 "%s expected smblctx %llu but found %llu"
2366 ", do not cleanup\n",
2367 file_id_string(frame, &fid),
2368 (unsigned long long)open_persistent_id,
2369 (unsigned long long)ctx->smblctx));
2370 goto done;
2374 status = dbwrap_record_delete(rec);
2375 if (!NT_STATUS_IS_OK(status)) {
2376 DEBUG(5, ("brl_cleanup_disconnected: failed to delete record "
2377 "for file %s from %s, open %llu: %s\n",
2378 file_id_string(frame, &fid), dbwrap_name(brlock_db),
2379 (unsigned long long)open_persistent_id,
2380 nt_errstr(status)));
2381 goto done;
2384 DEBUG(10, ("brl_cleanup_disconnected: "
2385 "file %s cleaned up %u entries from open %llu\n",
2386 file_id_string(frame, &fid), num,
2387 (unsigned long long)open_persistent_id));
2389 ret = true;
2390 done:
2391 talloc_free(frame);
2392 return ret;