smbd: Fix indentation, {} and line length in brl_conflict_other
[Samba.git] / source3 / locking / brlock.c
blobe881b8fd78d7fad640bfb2965bc748040fa9be23
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 /* POSIX flavour locks never conflict here - this is only called
243 in the read/write path. */
245 if (lock->lock_flav == POSIX_LOCK &&
246 rw_probe->lock_flav == POSIX_LOCK) {
247 return False;
251 * Incoming WRITE locks conflict with existing READ locks even
252 * if the context is the same. JRA. See LOCKTEST7 in smbtorture.
255 if (!(rw_probe->lock_type == WRITE_LOCK &&
256 lock->lock_type == READ_LOCK)) {
257 if (brl_same_context(&lock->context, &rw_probe->context) &&
258 lock->fnum == rw_probe->fnum) {
259 return False;
263 return brl_overlap(lock, rw_probe);
266 /****************************************************************************
267 Check if an unlock overlaps a pending lock.
268 ****************************************************************************/
270 static bool brl_pending_overlap(const struct lock_struct *lock, const struct lock_struct *pend_lock)
272 if ((lock->start <= pend_lock->start) && (lock->start + lock->size > pend_lock->start))
273 return True;
274 if ((lock->start >= pend_lock->start) && (lock->start < pend_lock->start + pend_lock->size))
275 return True;
276 return False;
279 /****************************************************************************
280 Amazingly enough, w2k3 "remembers" whether the last lock failure on a fnum
281 is the same as this one and changes its error code. I wonder if any
282 app depends on this ?
283 ****************************************************************************/
285 static NTSTATUS brl_lock_failed(files_struct *fsp,
286 const struct lock_struct *lock,
287 bool blocking_lock)
289 if (lock->start >= 0xEF000000 && (lock->start >> 63) == 0) {
290 /* amazing the little things you learn with a test
291 suite. Locks beyond this offset (as a 64 bit
292 number!) always generate the conflict error code,
293 unless the top bit is set */
294 if (!blocking_lock) {
295 fsp->last_lock_failure = *lock;
297 return NT_STATUS_FILE_LOCK_CONFLICT;
300 if (serverid_equal(&lock->context.pid, &fsp->last_lock_failure.context.pid) &&
301 lock->context.tid == fsp->last_lock_failure.context.tid &&
302 lock->fnum == fsp->last_lock_failure.fnum &&
303 lock->start == fsp->last_lock_failure.start) {
304 return NT_STATUS_FILE_LOCK_CONFLICT;
307 if (!blocking_lock) {
308 fsp->last_lock_failure = *lock;
310 return NT_STATUS_LOCK_NOT_GRANTED;
313 /****************************************************************************
314 Open up the brlock.tdb database.
315 ****************************************************************************/
317 void brl_init(bool read_only)
319 int tdb_flags;
321 if (brlock_db) {
322 return;
325 tdb_flags = TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH;
327 if (!lp_clustering()) {
329 * We can't use the SEQNUM trick to cache brlock
330 * entries in the clustering case because ctdb seqnum
331 * propagation has a delay.
333 tdb_flags |= TDB_SEQNUM;
336 brlock_db = db_open(NULL, lock_path("brlock.tdb"),
337 SMB_OPEN_DATABASE_TDB_HASH_SIZE, tdb_flags,
338 read_only?O_RDONLY:(O_RDWR|O_CREAT), 0644,
339 DBWRAP_LOCK_ORDER_2, DBWRAP_FLAG_NONE);
340 if (!brlock_db) {
341 DEBUG(0,("Failed to open byte range locking database %s\n",
342 lock_path("brlock.tdb")));
343 return;
347 /****************************************************************************
348 Close down the brlock.tdb database.
349 ****************************************************************************/
351 void brl_shutdown(void)
353 TALLOC_FREE(brlock_db);
356 #if ZERO_ZERO
357 /****************************************************************************
358 Compare two locks for sorting.
359 ****************************************************************************/
361 static int lock_compare(const struct lock_struct *lck1,
362 const struct lock_struct *lck2)
364 if (lck1->start != lck2->start) {
365 return (lck1->start - lck2->start);
367 if (lck2->size != lck1->size) {
368 return ((int)lck1->size - (int)lck2->size);
370 return 0;
372 #endif
374 /****************************************************************************
375 Lock a range of bytes - Windows lock semantics.
376 ****************************************************************************/
378 NTSTATUS brl_lock_windows_default(struct byte_range_lock *br_lck,
379 struct lock_struct *plock, bool blocking_lock)
381 unsigned int i;
382 files_struct *fsp = br_lck->fsp;
383 struct lock_struct *locks = br_lck->lock_data;
384 NTSTATUS status;
386 SMB_ASSERT(plock->lock_type != UNLOCK_LOCK);
388 if ((plock->start + plock->size - 1 < plock->start) &&
389 plock->size != 0) {
390 return NT_STATUS_INVALID_LOCK_RANGE;
393 for (i=0; i < br_lck->num_locks; i++) {
394 /* Do any Windows or POSIX locks conflict ? */
395 if (brl_conflict(&locks[i], plock)) {
396 /* Remember who blocked us. */
397 plock->context.smblctx = locks[i].context.smblctx;
398 return brl_lock_failed(fsp,plock,blocking_lock);
400 #if ZERO_ZERO
401 if (plock->start == 0 && plock->size == 0 &&
402 locks[i].size == 0) {
403 break;
405 #endif
408 if (!IS_PENDING_LOCK(plock->lock_type)) {
409 contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
412 /* We can get the Windows lock, now see if it needs to
413 be mapped into a lower level POSIX one, and if so can
414 we get it ? */
416 if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(fsp->conn->params)) {
417 int errno_ret;
418 if (!set_posix_lock_windows_flavour(fsp,
419 plock->start,
420 plock->size,
421 plock->lock_type,
422 &plock->context,
423 locks,
424 br_lck->num_locks,
425 &errno_ret)) {
427 /* We don't know who blocked us. */
428 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
430 if (errno_ret == EACCES || errno_ret == EAGAIN) {
431 status = NT_STATUS_FILE_LOCK_CONFLICT;
432 goto fail;
433 } else {
434 status = map_nt_error_from_unix(errno);
435 goto fail;
440 /* no conflicts - add it to the list of locks */
441 locks = talloc_realloc(br_lck, locks, struct lock_struct,
442 (br_lck->num_locks + 1));
443 if (!locks) {
444 status = NT_STATUS_NO_MEMORY;
445 goto fail;
448 memcpy(&locks[br_lck->num_locks], plock, sizeof(struct lock_struct));
449 br_lck->num_locks += 1;
450 br_lck->lock_data = locks;
451 br_lck->modified = True;
453 return NT_STATUS_OK;
454 fail:
455 if (!IS_PENDING_LOCK(plock->lock_type)) {
456 contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
458 return status;
461 /****************************************************************************
462 Cope with POSIX range splits and merges.
463 ****************************************************************************/
465 static unsigned int brlock_posix_split_merge(struct lock_struct *lck_arr, /* Output array. */
466 struct lock_struct *ex, /* existing lock. */
467 struct lock_struct *plock) /* proposed lock. */
469 bool lock_types_differ = (ex->lock_type != plock->lock_type);
471 /* We can't merge non-conflicting locks on different context - ignore fnum. */
473 if (!brl_same_context(&ex->context, &plock->context)) {
474 /* Just copy. */
475 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
476 return 1;
479 /* We now know we have the same context. */
481 /* Did we overlap ? */
483 /*********************************************
484 +---------+
485 | ex |
486 +---------+
487 +-------+
488 | plock |
489 +-------+
490 OR....
491 +---------+
492 | ex |
493 +---------+
494 **********************************************/
496 if ( (ex->start > (plock->start + plock->size)) ||
497 (plock->start > (ex->start + ex->size))) {
499 /* No overlap with this lock - copy existing. */
501 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
502 return 1;
505 /*********************************************
506 +---------------------------+
507 | ex |
508 +---------------------------+
509 +---------------------------+
510 | plock | -> replace with plock.
511 +---------------------------+
513 +---------------+
514 | ex |
515 +---------------+
516 +---------------------------+
517 | plock | -> replace with plock.
518 +---------------------------+
520 **********************************************/
522 if ( (ex->start >= plock->start) &&
523 (ex->start + ex->size <= plock->start + plock->size) ) {
525 /* Replace - discard existing lock. */
527 return 0;
530 /*********************************************
531 Adjacent after.
532 +-------+
533 | ex |
534 +-------+
535 +---------------+
536 | plock |
537 +---------------+
539 BECOMES....
540 +---------------+-------+
541 | plock | ex | - different lock types.
542 +---------------+-------+
543 OR.... (merge)
544 +-----------------------+
545 | plock | - same lock type.
546 +-----------------------+
547 **********************************************/
549 if (plock->start + plock->size == ex->start) {
551 /* If the lock types are the same, we merge, if different, we
552 add the remainder of the old lock. */
554 if (lock_types_differ) {
555 /* Add existing. */
556 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
557 return 1;
558 } else {
559 /* Merge - adjust incoming lock as we may have more
560 * merging to come. */
561 plock->size += ex->size;
562 return 0;
566 /*********************************************
567 Adjacent before.
568 +-------+
569 | ex |
570 +-------+
571 +---------------+
572 | plock |
573 +---------------+
574 BECOMES....
575 +-------+---------------+
576 | ex | plock | - different lock types
577 +-------+---------------+
579 OR.... (merge)
580 +-----------------------+
581 | plock | - same lock type.
582 +-----------------------+
584 **********************************************/
586 if (ex->start + ex->size == plock->start) {
588 /* If the lock types are the same, we merge, if different, we
589 add the existing lock. */
591 if (lock_types_differ) {
592 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
593 return 1;
594 } else {
595 /* Merge - adjust incoming lock as we may have more
596 * merging to come. */
597 plock->start = ex->start;
598 plock->size += ex->size;
599 return 0;
603 /*********************************************
604 Overlap after.
605 +-----------------------+
606 | ex |
607 +-----------------------+
608 +---------------+
609 | plock |
610 +---------------+
612 +----------------+
613 | ex |
614 +----------------+
615 +---------------+
616 | plock |
617 +---------------+
619 BECOMES....
620 +---------------+-------+
621 | plock | ex | - different lock types.
622 +---------------+-------+
623 OR.... (merge)
624 +-----------------------+
625 | plock | - same lock type.
626 +-----------------------+
627 **********************************************/
629 if ( (ex->start >= plock->start) &&
630 (ex->start <= plock->start + plock->size) &&
631 (ex->start + ex->size > plock->start + plock->size) ) {
633 /* If the lock types are the same, we merge, if different, we
634 add the remainder of the old lock. */
636 if (lock_types_differ) {
637 /* Add remaining existing. */
638 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
639 /* Adjust existing start and size. */
640 lck_arr[0].start = plock->start + plock->size;
641 lck_arr[0].size = (ex->start + ex->size) - (plock->start + plock->size);
642 return 1;
643 } else {
644 /* Merge - adjust incoming lock as we may have more
645 * merging to come. */
646 plock->size += (ex->start + ex->size) - (plock->start + plock->size);
647 return 0;
651 /*********************************************
652 Overlap before.
653 +-----------------------+
654 | ex |
655 +-----------------------+
656 +---------------+
657 | plock |
658 +---------------+
660 +-------------+
661 | ex |
662 +-------------+
663 +---------------+
664 | plock |
665 +---------------+
667 BECOMES....
668 +-------+---------------+
669 | ex | plock | - different lock types
670 +-------+---------------+
672 OR.... (merge)
673 +-----------------------+
674 | plock | - same lock type.
675 +-----------------------+
677 **********************************************/
679 if ( (ex->start < plock->start) &&
680 (ex->start + ex->size >= plock->start) &&
681 (ex->start + ex->size <= plock->start + plock->size) ) {
683 /* If the lock types are the same, we merge, if different, we
684 add the truncated old lock. */
686 if (lock_types_differ) {
687 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
688 /* Adjust existing size. */
689 lck_arr[0].size = plock->start - ex->start;
690 return 1;
691 } else {
692 /* Merge - adjust incoming lock as we may have more
693 * merging to come. MUST ADJUST plock SIZE FIRST ! */
694 plock->size += (plock->start - ex->start);
695 plock->start = ex->start;
696 return 0;
700 /*********************************************
701 Complete overlap.
702 +---------------------------+
703 | ex |
704 +---------------------------+
705 +---------+
706 | plock |
707 +---------+
708 BECOMES.....
709 +-------+---------+---------+
710 | ex | plock | ex | - different lock types.
711 +-------+---------+---------+
713 +---------------------------+
714 | plock | - same lock type.
715 +---------------------------+
716 **********************************************/
718 if ( (ex->start < plock->start) && (ex->start + ex->size > plock->start + plock->size) ) {
720 if (lock_types_differ) {
722 /* We have to split ex into two locks here. */
724 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
725 memcpy(&lck_arr[1], ex, sizeof(struct lock_struct));
727 /* Adjust first existing size. */
728 lck_arr[0].size = plock->start - ex->start;
730 /* Adjust second existing start and size. */
731 lck_arr[1].start = plock->start + plock->size;
732 lck_arr[1].size = (ex->start + ex->size) - (plock->start + plock->size);
733 return 2;
734 } else {
735 /* Just eat the existing locks, merge them into plock. */
736 plock->start = ex->start;
737 plock->size = ex->size;
738 return 0;
742 /* Never get here. */
743 smb_panic("brlock_posix_split_merge");
744 /* Notreached. */
746 /* Keep some compilers happy. */
747 return 0;
750 /****************************************************************************
751 Lock a range of bytes - POSIX lock semantics.
752 We must cope with range splits and merges.
753 ****************************************************************************/
755 static NTSTATUS brl_lock_posix(struct messaging_context *msg_ctx,
756 struct byte_range_lock *br_lck,
757 struct lock_struct *plock)
759 unsigned int i, count, posix_count;
760 struct lock_struct *locks = br_lck->lock_data;
761 struct lock_struct *tp;
762 bool signal_pending_read = False;
763 bool break_oplocks = false;
764 NTSTATUS status;
766 /* No zero-zero locks for POSIX. */
767 if (plock->start == 0 && plock->size == 0) {
768 return NT_STATUS_INVALID_PARAMETER;
771 /* Don't allow 64-bit lock wrap. */
772 if (plock->start + plock->size - 1 < plock->start) {
773 return NT_STATUS_INVALID_PARAMETER;
776 /* The worst case scenario here is we have to split an
777 existing POSIX lock range into two, and add our lock,
778 so we need at most 2 more entries. */
780 tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 2);
781 if (!tp) {
782 return NT_STATUS_NO_MEMORY;
785 count = posix_count = 0;
787 for (i=0; i < br_lck->num_locks; i++) {
788 struct lock_struct *curr_lock = &locks[i];
790 /* If we have a pending read lock, a lock downgrade should
791 trigger a lock re-evaluation. */
792 if (curr_lock->lock_type == PENDING_READ_LOCK &&
793 brl_pending_overlap(plock, curr_lock)) {
794 signal_pending_read = True;
797 if (curr_lock->lock_flav == WINDOWS_LOCK) {
798 /* Do any Windows flavour locks conflict ? */
799 if (brl_conflict(curr_lock, plock)) {
800 /* No games with error messages. */
801 TALLOC_FREE(tp);
802 /* Remember who blocked us. */
803 plock->context.smblctx = curr_lock->context.smblctx;
804 return NT_STATUS_FILE_LOCK_CONFLICT;
806 /* Just copy the Windows lock into the new array. */
807 memcpy(&tp[count], curr_lock, sizeof(struct lock_struct));
808 count++;
809 } else {
810 unsigned int tmp_count = 0;
812 /* POSIX conflict semantics are different. */
813 if (brl_conflict_posix(curr_lock, plock)) {
814 /* Can't block ourselves with POSIX locks. */
815 /* No games with error messages. */
816 TALLOC_FREE(tp);
817 /* Remember who blocked us. */
818 plock->context.smblctx = curr_lock->context.smblctx;
819 return NT_STATUS_FILE_LOCK_CONFLICT;
822 /* Work out overlaps. */
823 tmp_count += brlock_posix_split_merge(&tp[count], curr_lock, plock);
824 posix_count += tmp_count;
825 count += tmp_count;
830 * Break oplocks while we hold a brl. Since lock() and unlock() calls
831 * are not symetric with POSIX semantics, we cannot guarantee our
832 * contend_level2_oplocks_begin/end calls will be acquired and
833 * released one-for-one as with Windows semantics. Therefore we only
834 * call contend_level2_oplocks_begin if this is the first POSIX brl on
835 * the file.
837 break_oplocks = (!IS_PENDING_LOCK(plock->lock_type) &&
838 posix_count == 0);
839 if (break_oplocks) {
840 contend_level2_oplocks_begin(br_lck->fsp,
841 LEVEL2_CONTEND_POSIX_BRL);
844 /* Try and add the lock in order, sorted by lock start. */
845 for (i=0; i < count; i++) {
846 struct lock_struct *curr_lock = &tp[i];
848 if (curr_lock->start <= plock->start) {
849 continue;
853 if (i < count) {
854 memmove(&tp[i+1], &tp[i],
855 (count - i)*sizeof(struct lock_struct));
857 memcpy(&tp[i], plock, sizeof(struct lock_struct));
858 count++;
860 /* We can get the POSIX lock, now see if it needs to
861 be mapped into a lower level POSIX one, and if so can
862 we get it ? */
864 if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(br_lck->fsp->conn->params)) {
865 int errno_ret;
867 /* The lower layer just needs to attempt to
868 get the system POSIX lock. We've weeded out
869 any conflicts above. */
871 if (!set_posix_lock_posix_flavour(br_lck->fsp,
872 plock->start,
873 plock->size,
874 plock->lock_type,
875 &errno_ret)) {
877 /* We don't know who blocked us. */
878 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
880 if (errno_ret == EACCES || errno_ret == EAGAIN) {
881 TALLOC_FREE(tp);
882 status = NT_STATUS_FILE_LOCK_CONFLICT;
883 goto fail;
884 } else {
885 TALLOC_FREE(tp);
886 status = map_nt_error_from_unix(errno);
887 goto fail;
892 /* If we didn't use all the allocated size,
893 * Realloc so we don't leak entries per lock call. */
894 if (count < br_lck->num_locks + 2) {
895 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
896 if (!tp) {
897 status = NT_STATUS_NO_MEMORY;
898 goto fail;
902 br_lck->num_locks = count;
903 TALLOC_FREE(br_lck->lock_data);
904 br_lck->lock_data = tp;
905 locks = tp;
906 br_lck->modified = True;
908 /* A successful downgrade from write to read lock can trigger a lock
909 re-evalutation where waiting readers can now proceed. */
911 if (signal_pending_read) {
912 /* Send unlock messages to any pending read waiters that overlap. */
913 for (i=0; i < br_lck->num_locks; i++) {
914 struct lock_struct *pend_lock = &locks[i];
916 /* Ignore non-pending locks. */
917 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
918 continue;
921 if (pend_lock->lock_type == PENDING_READ_LOCK &&
922 brl_pending_overlap(plock, pend_lock)) {
923 DEBUG(10,("brl_lock_posix: sending unlock message to pid %s\n",
924 procid_str_static(&pend_lock->context.pid )));
926 messaging_send(msg_ctx, pend_lock->context.pid,
927 MSG_SMB_UNLOCK, &data_blob_null);
932 return NT_STATUS_OK;
933 fail:
934 if (break_oplocks) {
935 contend_level2_oplocks_end(br_lck->fsp,
936 LEVEL2_CONTEND_POSIX_BRL);
938 return status;
941 NTSTATUS smb_vfs_call_brl_lock_windows(struct vfs_handle_struct *handle,
942 struct byte_range_lock *br_lck,
943 struct lock_struct *plock,
944 bool blocking_lock)
946 VFS_FIND(brl_lock_windows);
947 return handle->fns->brl_lock_windows_fn(handle, br_lck, plock,
948 blocking_lock);
951 /****************************************************************************
952 Lock a range of bytes.
953 ****************************************************************************/
955 NTSTATUS brl_lock(struct messaging_context *msg_ctx,
956 struct byte_range_lock *br_lck,
957 uint64_t smblctx,
958 struct server_id pid,
959 br_off start,
960 br_off size,
961 enum brl_type lock_type,
962 enum brl_flavour lock_flav,
963 bool blocking_lock,
964 uint64_t *psmblctx)
966 NTSTATUS ret;
967 struct lock_struct lock;
969 #if !ZERO_ZERO
970 if (start == 0 && size == 0) {
971 DEBUG(0,("client sent 0/0 lock - please report this\n"));
973 #endif
975 lock = (struct lock_struct) {
976 .context.smblctx = smblctx,
977 .context.pid = pid,
978 .context.tid = br_lck->fsp->conn->cnum,
979 .start = start,
980 .size = size,
981 .fnum = br_lck->fsp->fnum,
982 .lock_type = lock_type,
983 .lock_flav = lock_flav
986 if (lock_flav == WINDOWS_LOCK) {
987 ret = SMB_VFS_BRL_LOCK_WINDOWS(br_lck->fsp->conn, br_lck,
988 &lock, blocking_lock);
989 } else {
990 ret = brl_lock_posix(msg_ctx, br_lck, &lock);
993 #if ZERO_ZERO
994 /* sort the lock list */
995 TYPESAFE_QSORT(br_lck->lock_data, (size_t)br_lck->num_locks, lock_compare);
996 #endif
998 /* If we're returning an error, return who blocked us. */
999 if (!NT_STATUS_IS_OK(ret) && psmblctx) {
1000 *psmblctx = lock.context.smblctx;
1002 return ret;
1005 static void brl_delete_lock_struct(struct lock_struct *locks,
1006 unsigned num_locks,
1007 unsigned del_idx)
1009 if (del_idx >= num_locks) {
1010 return;
1012 memmove(&locks[del_idx], &locks[del_idx+1],
1013 sizeof(*locks) * (num_locks - del_idx - 1));
1016 /****************************************************************************
1017 Unlock a range of bytes - Windows semantics.
1018 ****************************************************************************/
1020 bool brl_unlock_windows_default(struct messaging_context *msg_ctx,
1021 struct byte_range_lock *br_lck,
1022 const struct lock_struct *plock)
1024 unsigned int i, j;
1025 struct lock_struct *locks = br_lck->lock_data;
1026 enum brl_type deleted_lock_type = READ_LOCK; /* shut the compiler up.... */
1028 SMB_ASSERT(plock->lock_type == UNLOCK_LOCK);
1030 #if ZERO_ZERO
1031 /* Delete write locks by preference... The lock list
1032 is sorted in the zero zero case. */
1034 for (i = 0; i < br_lck->num_locks; i++) {
1035 struct lock_struct *lock = &locks[i];
1037 if (lock->lock_type == WRITE_LOCK &&
1038 brl_same_context(&lock->context, &plock->context) &&
1039 lock->fnum == plock->fnum &&
1040 lock->lock_flav == WINDOWS_LOCK &&
1041 lock->start == plock->start &&
1042 lock->size == plock->size) {
1044 /* found it - delete it */
1045 deleted_lock_type = lock->lock_type;
1046 break;
1050 if (i != br_lck->num_locks) {
1051 /* We found it - don't search again. */
1052 goto unlock_continue;
1054 #endif
1056 for (i = 0; i < br_lck->num_locks; i++) {
1057 struct lock_struct *lock = &locks[i];
1059 if (IS_PENDING_LOCK(lock->lock_type)) {
1060 continue;
1063 /* Only remove our own locks that match in start, size, and flavour. */
1064 if (brl_same_context(&lock->context, &plock->context) &&
1065 lock->fnum == plock->fnum &&
1066 lock->lock_flav == WINDOWS_LOCK &&
1067 lock->start == plock->start &&
1068 lock->size == plock->size ) {
1069 deleted_lock_type = lock->lock_type;
1070 break;
1074 if (i == br_lck->num_locks) {
1075 /* we didn't find it */
1076 return False;
1079 #if ZERO_ZERO
1080 unlock_continue:
1081 #endif
1083 brl_delete_lock_struct(locks, br_lck->num_locks, i);
1084 br_lck->num_locks -= 1;
1085 br_lck->modified = True;
1087 /* Unlock the underlying POSIX regions. */
1088 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1089 release_posix_lock_windows_flavour(br_lck->fsp,
1090 plock->start,
1091 plock->size,
1092 deleted_lock_type,
1093 &plock->context,
1094 locks,
1095 br_lck->num_locks);
1098 /* Send unlock messages to any pending waiters that overlap. */
1099 for (j=0; j < br_lck->num_locks; j++) {
1100 struct lock_struct *pend_lock = &locks[j];
1102 /* Ignore non-pending locks. */
1103 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1104 continue;
1107 /* We could send specific lock info here... */
1108 if (brl_pending_overlap(plock, pend_lock)) {
1109 DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
1110 procid_str_static(&pend_lock->context.pid )));
1112 messaging_send(msg_ctx, pend_lock->context.pid,
1113 MSG_SMB_UNLOCK, &data_blob_null);
1117 contend_level2_oplocks_end(br_lck->fsp, LEVEL2_CONTEND_WINDOWS_BRL);
1118 return True;
1121 /****************************************************************************
1122 Unlock a range of bytes - POSIX semantics.
1123 ****************************************************************************/
1125 static bool brl_unlock_posix(struct messaging_context *msg_ctx,
1126 struct byte_range_lock *br_lck,
1127 struct lock_struct *plock)
1129 unsigned int i, j, count;
1130 struct lock_struct *tp;
1131 struct lock_struct *locks = br_lck->lock_data;
1132 bool overlap_found = False;
1134 /* No zero-zero locks for POSIX. */
1135 if (plock->start == 0 && plock->size == 0) {
1136 return False;
1139 /* Don't allow 64-bit lock wrap. */
1140 if (plock->start + plock->size < plock->start ||
1141 plock->start + plock->size < plock->size) {
1142 DEBUG(10,("brl_unlock_posix: lock wrap\n"));
1143 return False;
1146 /* The worst case scenario here is we have to split an
1147 existing POSIX lock range into two, so we need at most
1148 1 more entry. */
1150 tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 1);
1151 if (!tp) {
1152 DEBUG(10,("brl_unlock_posix: malloc fail\n"));
1153 return False;
1156 count = 0;
1157 for (i = 0; i < br_lck->num_locks; i++) {
1158 struct lock_struct *lock = &locks[i];
1159 unsigned int tmp_count;
1161 /* Only remove our own locks - ignore fnum. */
1162 if (IS_PENDING_LOCK(lock->lock_type) ||
1163 !brl_same_context(&lock->context, &plock->context)) {
1164 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1165 count++;
1166 continue;
1169 if (lock->lock_flav == WINDOWS_LOCK) {
1170 /* Do any Windows flavour locks conflict ? */
1171 if (brl_conflict(lock, plock)) {
1172 TALLOC_FREE(tp);
1173 return false;
1175 /* Just copy the Windows lock into the new array. */
1176 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1177 count++;
1178 continue;
1181 /* Work out overlaps. */
1182 tmp_count = brlock_posix_split_merge(&tp[count], lock, plock);
1184 if (tmp_count == 0) {
1185 /* plock overlapped the existing lock completely,
1186 or replaced it. Don't copy the existing lock. */
1187 overlap_found = true;
1188 } else if (tmp_count == 1) {
1189 /* Either no overlap, (simple copy of existing lock) or
1190 * an overlap of an existing lock. */
1191 /* If the lock changed size, we had an overlap. */
1192 if (tp[count].size != lock->size) {
1193 overlap_found = true;
1195 count += tmp_count;
1196 } else if (tmp_count == 2) {
1197 /* We split a lock range in two. */
1198 overlap_found = true;
1199 count += tmp_count;
1201 /* Optimisation... */
1202 /* We know we're finished here as we can't overlap any
1203 more POSIX locks. Copy the rest of the lock array. */
1205 if (i < br_lck->num_locks - 1) {
1206 memcpy(&tp[count], &locks[i+1],
1207 sizeof(*locks)*((br_lck->num_locks-1) - i));
1208 count += ((br_lck->num_locks-1) - i);
1210 break;
1215 if (!overlap_found) {
1216 /* Just ignore - no change. */
1217 TALLOC_FREE(tp);
1218 DEBUG(10,("brl_unlock_posix: No overlap - unlocked.\n"));
1219 return True;
1222 /* Unlock any POSIX regions. */
1223 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1224 release_posix_lock_posix_flavour(br_lck->fsp,
1225 plock->start,
1226 plock->size,
1227 &plock->context,
1229 count);
1232 /* Realloc so we don't leak entries per unlock call. */
1233 if (count) {
1234 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
1235 if (!tp) {
1236 DEBUG(10,("brl_unlock_posix: realloc fail\n"));
1237 return False;
1239 } else {
1240 /* We deleted the last lock. */
1241 TALLOC_FREE(tp);
1242 tp = NULL;
1245 contend_level2_oplocks_end(br_lck->fsp,
1246 LEVEL2_CONTEND_POSIX_BRL);
1248 br_lck->num_locks = count;
1249 TALLOC_FREE(br_lck->lock_data);
1250 locks = tp;
1251 br_lck->lock_data = tp;
1252 br_lck->modified = True;
1254 /* Send unlock messages to any pending waiters that overlap. */
1256 for (j=0; j < br_lck->num_locks; j++) {
1257 struct lock_struct *pend_lock = &locks[j];
1259 /* Ignore non-pending locks. */
1260 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1261 continue;
1264 /* We could send specific lock info here... */
1265 if (brl_pending_overlap(plock, pend_lock)) {
1266 DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
1267 procid_str_static(&pend_lock->context.pid )));
1269 messaging_send(msg_ctx, pend_lock->context.pid,
1270 MSG_SMB_UNLOCK, &data_blob_null);
1274 return True;
1277 bool smb_vfs_call_brl_unlock_windows(struct vfs_handle_struct *handle,
1278 struct messaging_context *msg_ctx,
1279 struct byte_range_lock *br_lck,
1280 const struct lock_struct *plock)
1282 VFS_FIND(brl_unlock_windows);
1283 return handle->fns->brl_unlock_windows_fn(handle, msg_ctx, br_lck,
1284 plock);
1287 /****************************************************************************
1288 Unlock a range of bytes.
1289 ****************************************************************************/
1291 bool brl_unlock(struct messaging_context *msg_ctx,
1292 struct byte_range_lock *br_lck,
1293 uint64_t smblctx,
1294 struct server_id pid,
1295 br_off start,
1296 br_off size,
1297 enum brl_flavour lock_flav)
1299 struct lock_struct lock;
1301 lock.context.smblctx = smblctx;
1302 lock.context.pid = pid;
1303 lock.context.tid = br_lck->fsp->conn->cnum;
1304 lock.start = start;
1305 lock.size = size;
1306 lock.fnum = br_lck->fsp->fnum;
1307 lock.lock_type = UNLOCK_LOCK;
1308 lock.lock_flav = lock_flav;
1310 if (lock_flav == WINDOWS_LOCK) {
1311 return SMB_VFS_BRL_UNLOCK_WINDOWS(br_lck->fsp->conn, msg_ctx,
1312 br_lck, &lock);
1313 } else {
1314 return brl_unlock_posix(msg_ctx, br_lck, &lock);
1318 /****************************************************************************
1319 Test if we could add a lock if we wanted to.
1320 Returns True if the region required is currently unlocked, False if locked.
1321 ****************************************************************************/
1323 bool brl_locktest(struct byte_range_lock *br_lck,
1324 uint64_t smblctx,
1325 struct server_id pid,
1326 br_off start,
1327 br_off size,
1328 enum brl_type lock_type,
1329 enum brl_flavour lock_flav)
1331 bool ret = True;
1332 unsigned int i;
1333 struct lock_struct lock;
1334 const struct lock_struct *locks = br_lck->lock_data;
1335 files_struct *fsp = br_lck->fsp;
1337 lock.context.smblctx = smblctx;
1338 lock.context.pid = pid;
1339 lock.context.tid = br_lck->fsp->conn->cnum;
1340 lock.start = start;
1341 lock.size = size;
1342 lock.fnum = fsp->fnum;
1343 lock.lock_type = lock_type;
1344 lock.lock_flav = lock_flav;
1346 /* Make sure existing locks don't conflict */
1347 for (i=0; i < br_lck->num_locks; i++) {
1349 * Our own locks don't conflict.
1351 if (brl_conflict_other(&locks[i], &lock)) {
1352 return False;
1357 * There is no lock held by an SMB daemon, check to
1358 * see if there is a POSIX lock from a UNIX or NFS process.
1359 * This only conflicts with Windows locks, not POSIX locks.
1362 if(lp_posix_locking(fsp->conn->params) && (lock_flav == WINDOWS_LOCK)) {
1363 ret = is_posix_locked(fsp, &start, &size, &lock_type, WINDOWS_LOCK);
1365 DEBUG(10, ("brl_locktest: posix start=%ju len=%ju %s for %s "
1366 "file %s\n", (uintmax_t)start, (uintmax_t)size,
1367 ret ? "locked" : "unlocked",
1368 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1370 /* We need to return the inverse of is_posix_locked. */
1371 ret = !ret;
1374 /* no conflicts - we could have added it */
1375 return ret;
1378 /****************************************************************************
1379 Query for existing locks.
1380 ****************************************************************************/
1382 NTSTATUS brl_lockquery(struct byte_range_lock *br_lck,
1383 uint64_t *psmblctx,
1384 struct server_id pid,
1385 br_off *pstart,
1386 br_off *psize,
1387 enum brl_type *plock_type,
1388 enum brl_flavour lock_flav)
1390 unsigned int i;
1391 struct lock_struct lock;
1392 const struct lock_struct *locks = br_lck->lock_data;
1393 files_struct *fsp = br_lck->fsp;
1395 lock.context.smblctx = *psmblctx;
1396 lock.context.pid = pid;
1397 lock.context.tid = br_lck->fsp->conn->cnum;
1398 lock.start = *pstart;
1399 lock.size = *psize;
1400 lock.fnum = fsp->fnum;
1401 lock.lock_type = *plock_type;
1402 lock.lock_flav = lock_flav;
1404 /* Make sure existing locks don't conflict */
1405 for (i=0; i < br_lck->num_locks; i++) {
1406 const struct lock_struct *exlock = &locks[i];
1407 bool conflict = False;
1409 if (exlock->lock_flav == WINDOWS_LOCK) {
1410 conflict = brl_conflict(exlock, &lock);
1411 } else {
1412 conflict = brl_conflict_posix(exlock, &lock);
1415 if (conflict) {
1416 *psmblctx = exlock->context.smblctx;
1417 *pstart = exlock->start;
1418 *psize = exlock->size;
1419 *plock_type = exlock->lock_type;
1420 return NT_STATUS_LOCK_NOT_GRANTED;
1425 * There is no lock held by an SMB daemon, check to
1426 * see if there is a POSIX lock from a UNIX or NFS process.
1429 if(lp_posix_locking(fsp->conn->params)) {
1430 bool ret = is_posix_locked(fsp, pstart, psize, plock_type, POSIX_LOCK);
1432 DEBUG(10, ("brl_lockquery: posix start=%ju len=%ju %s for %s "
1433 "file %s\n", (uintmax_t)*pstart,
1434 (uintmax_t)*psize, ret ? "locked" : "unlocked",
1435 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1437 if (ret) {
1438 /* Hmmm. No clue what to set smblctx to - use -1. */
1439 *psmblctx = 0xFFFFFFFFFFFFFFFFLL;
1440 return NT_STATUS_LOCK_NOT_GRANTED;
1444 return NT_STATUS_OK;
1448 bool smb_vfs_call_brl_cancel_windows(struct vfs_handle_struct *handle,
1449 struct byte_range_lock *br_lck,
1450 struct lock_struct *plock)
1452 VFS_FIND(brl_cancel_windows);
1453 return handle->fns->brl_cancel_windows_fn(handle, br_lck, plock);
1456 /****************************************************************************
1457 Remove a particular pending lock.
1458 ****************************************************************************/
1459 bool brl_lock_cancel(struct byte_range_lock *br_lck,
1460 uint64_t smblctx,
1461 struct server_id pid,
1462 br_off start,
1463 br_off size,
1464 enum brl_flavour lock_flav)
1466 bool ret;
1467 struct lock_struct lock;
1469 lock.context.smblctx = smblctx;
1470 lock.context.pid = pid;
1471 lock.context.tid = br_lck->fsp->conn->cnum;
1472 lock.start = start;
1473 lock.size = size;
1474 lock.fnum = br_lck->fsp->fnum;
1475 lock.lock_flav = lock_flav;
1476 /* lock.lock_type doesn't matter */
1478 if (lock_flav == WINDOWS_LOCK) {
1479 ret = SMB_VFS_BRL_CANCEL_WINDOWS(br_lck->fsp->conn, br_lck,
1480 &lock);
1481 } else {
1482 ret = brl_lock_cancel_default(br_lck, &lock);
1485 return ret;
1488 bool brl_lock_cancel_default(struct byte_range_lock *br_lck,
1489 struct lock_struct *plock)
1491 unsigned int i;
1492 struct lock_struct *locks = br_lck->lock_data;
1494 SMB_ASSERT(plock);
1496 for (i = 0; i < br_lck->num_locks; i++) {
1497 struct lock_struct *lock = &locks[i];
1499 /* For pending locks we *always* care about the fnum. */
1500 if (brl_same_context(&lock->context, &plock->context) &&
1501 lock->fnum == plock->fnum &&
1502 IS_PENDING_LOCK(lock->lock_type) &&
1503 lock->lock_flav == plock->lock_flav &&
1504 lock->start == plock->start &&
1505 lock->size == plock->size) {
1506 break;
1510 if (i == br_lck->num_locks) {
1511 /* Didn't find it. */
1512 return False;
1515 brl_delete_lock_struct(locks, br_lck->num_locks, i);
1516 br_lck->num_locks -= 1;
1517 br_lck->modified = True;
1518 return True;
1521 /****************************************************************************
1522 Remove any locks associated with a open file.
1523 We return True if this process owns any other Windows locks on this
1524 fd and so we should not immediately close the fd.
1525 ****************************************************************************/
1527 void brl_close_fnum(struct messaging_context *msg_ctx,
1528 struct byte_range_lock *br_lck)
1530 files_struct *fsp = br_lck->fsp;
1531 uint32_t tid = fsp->conn->cnum;
1532 uint64_t fnum = fsp->fnum;
1533 unsigned int i;
1534 struct lock_struct *locks = br_lck->lock_data;
1535 struct server_id pid = messaging_server_id(fsp->conn->sconn->msg_ctx);
1536 struct lock_struct *locks_copy;
1537 unsigned int num_locks_copy;
1539 /* Copy the current lock array. */
1540 if (br_lck->num_locks) {
1541 locks_copy = (struct lock_struct *)talloc_memdup(br_lck, locks, br_lck->num_locks * sizeof(struct lock_struct));
1542 if (!locks_copy) {
1543 smb_panic("brl_close_fnum: talloc failed");
1545 } else {
1546 locks_copy = NULL;
1549 num_locks_copy = br_lck->num_locks;
1551 for (i=0; i < num_locks_copy; i++) {
1552 struct lock_struct *lock = &locks_copy[i];
1554 if (lock->context.tid == tid && serverid_equal(&lock->context.pid, &pid) &&
1555 (lock->fnum == fnum)) {
1556 brl_unlock(msg_ctx,
1557 br_lck,
1558 lock->context.smblctx,
1559 pid,
1560 lock->start,
1561 lock->size,
1562 lock->lock_flav);
1567 bool brl_mark_disconnected(struct files_struct *fsp)
1569 uint32_t tid = fsp->conn->cnum;
1570 uint64_t smblctx;
1571 uint64_t fnum = fsp->fnum;
1572 unsigned int i;
1573 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1574 struct byte_range_lock *br_lck = NULL;
1576 if (fsp->op == NULL) {
1577 return false;
1580 smblctx = fsp->op->global->open_persistent_id;
1582 if (!fsp->op->global->durable) {
1583 return false;
1586 if (fsp->current_lock_count == 0) {
1587 return true;
1590 br_lck = brl_get_locks(talloc_tos(), fsp);
1591 if (br_lck == NULL) {
1592 return false;
1595 for (i=0; i < br_lck->num_locks; i++) {
1596 struct lock_struct *lock = &br_lck->lock_data[i];
1599 * as this is a durable handle, we only expect locks
1600 * of the current file handle!
1603 if (lock->context.smblctx != smblctx) {
1604 TALLOC_FREE(br_lck);
1605 return false;
1608 if (lock->context.tid != tid) {
1609 TALLOC_FREE(br_lck);
1610 return false;
1613 if (!serverid_equal(&lock->context.pid, &self)) {
1614 TALLOC_FREE(br_lck);
1615 return false;
1618 if (lock->fnum != fnum) {
1619 TALLOC_FREE(br_lck);
1620 return false;
1623 server_id_set_disconnected(&lock->context.pid);
1624 lock->context.tid = TID_FIELD_INVALID;
1625 lock->fnum = FNUM_FIELD_INVALID;
1628 br_lck->modified = true;
1629 TALLOC_FREE(br_lck);
1630 return true;
1633 bool brl_reconnect_disconnected(struct files_struct *fsp)
1635 uint32_t tid = fsp->conn->cnum;
1636 uint64_t smblctx;
1637 uint64_t fnum = fsp->fnum;
1638 unsigned int i;
1639 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1640 struct byte_range_lock *br_lck = NULL;
1642 if (fsp->op == NULL) {
1643 return false;
1646 smblctx = fsp->op->global->open_persistent_id;
1648 if (!fsp->op->global->durable) {
1649 return false;
1653 * When reconnecting, we do not want to validate the brlock entries
1654 * and thereby remove our own (disconnected) entries but reactivate
1655 * them instead.
1657 fsp->lockdb_clean = true;
1659 br_lck = brl_get_locks(talloc_tos(), fsp);
1660 if (br_lck == NULL) {
1661 return false;
1664 if (br_lck->num_locks == 0) {
1665 TALLOC_FREE(br_lck);
1666 return true;
1669 for (i=0; i < br_lck->num_locks; i++) {
1670 struct lock_struct *lock = &br_lck->lock_data[i];
1673 * as this is a durable handle we only expect locks
1674 * of the current file handle!
1677 if (lock->context.smblctx != smblctx) {
1678 TALLOC_FREE(br_lck);
1679 return false;
1682 if (lock->context.tid != TID_FIELD_INVALID) {
1683 TALLOC_FREE(br_lck);
1684 return false;
1687 if (!server_id_is_disconnected(&lock->context.pid)) {
1688 TALLOC_FREE(br_lck);
1689 return false;
1692 if (lock->fnum != FNUM_FIELD_INVALID) {
1693 TALLOC_FREE(br_lck);
1694 return false;
1697 lock->context.pid = self;
1698 lock->context.tid = tid;
1699 lock->fnum = fnum;
1702 fsp->current_lock_count = br_lck->num_locks;
1703 br_lck->modified = true;
1704 TALLOC_FREE(br_lck);
1705 return true;
1708 /****************************************************************************
1709 Ensure this set of lock entries is valid.
1710 ****************************************************************************/
1711 static bool validate_lock_entries(unsigned int *pnum_entries, struct lock_struct **pplocks,
1712 bool keep_disconnected)
1714 unsigned int i;
1715 struct lock_struct *locks = *pplocks;
1716 unsigned int num_entries = *pnum_entries;
1717 TALLOC_CTX *frame;
1718 struct server_id *ids;
1719 bool *exists;
1721 if (num_entries == 0) {
1722 return true;
1725 frame = talloc_stackframe();
1727 ids = talloc_array(frame, struct server_id, num_entries);
1728 if (ids == NULL) {
1729 DEBUG(0, ("validate_lock_entries: "
1730 "talloc_array(struct server_id, %u) failed\n",
1731 num_entries));
1732 talloc_free(frame);
1733 return false;
1736 exists = talloc_array(frame, bool, num_entries);
1737 if (exists == NULL) {
1738 DEBUG(0, ("validate_lock_entries: "
1739 "talloc_array(bool, %u) failed\n",
1740 num_entries));
1741 talloc_free(frame);
1742 return false;
1745 for (i = 0; i < num_entries; i++) {
1746 ids[i] = locks[i].context.pid;
1749 if (!serverids_exist(ids, num_entries, exists)) {
1750 DEBUG(3, ("validate_lock_entries: serverids_exists failed\n"));
1751 talloc_free(frame);
1752 return false;
1755 i = 0;
1757 while (i < num_entries) {
1758 if (exists[i]) {
1759 i++;
1760 continue;
1763 if (keep_disconnected &&
1764 server_id_is_disconnected(&ids[i]))
1766 i++;
1767 continue;
1770 /* This process no longer exists */
1772 brl_delete_lock_struct(locks, num_entries, i);
1773 num_entries -= 1;
1775 TALLOC_FREE(frame);
1777 *pnum_entries = num_entries;
1779 return True;
1782 struct brl_forall_cb {
1783 void (*fn)(struct file_id id, struct server_id pid,
1784 enum brl_type lock_type,
1785 enum brl_flavour lock_flav,
1786 br_off start, br_off size,
1787 void *private_data);
1788 void *private_data;
1791 /****************************************************************************
1792 Traverse the whole database with this function, calling traverse_callback
1793 on each lock.
1794 ****************************************************************************/
1796 static int brl_traverse_fn(struct db_record *rec, void *state)
1798 struct brl_forall_cb *cb = (struct brl_forall_cb *)state;
1799 struct lock_struct *locks;
1800 struct file_id *key;
1801 unsigned int i;
1802 unsigned int num_locks = 0;
1803 unsigned int orig_num_locks = 0;
1804 TDB_DATA dbkey;
1805 TDB_DATA value;
1807 dbkey = dbwrap_record_get_key(rec);
1808 value = dbwrap_record_get_value(rec);
1810 /* In a traverse function we must make a copy of
1811 dbuf before modifying it. */
1813 locks = (struct lock_struct *)talloc_memdup(
1814 talloc_tos(), value.dptr, value.dsize);
1815 if (!locks) {
1816 return -1; /* Terminate traversal. */
1819 key = (struct file_id *)dbkey.dptr;
1820 orig_num_locks = num_locks = value.dsize/sizeof(*locks);
1822 /* Ensure the lock db is clean of entries from invalid processes. */
1824 if (!validate_lock_entries(&num_locks, &locks, true)) {
1825 TALLOC_FREE(locks);
1826 return -1; /* Terminate traversal */
1829 if (orig_num_locks != num_locks) {
1830 if (num_locks) {
1831 TDB_DATA data;
1832 data.dptr = (uint8_t *)locks;
1833 data.dsize = num_locks*sizeof(struct lock_struct);
1834 dbwrap_record_store(rec, data, TDB_REPLACE);
1835 } else {
1836 dbwrap_record_delete(rec);
1840 if (cb->fn) {
1841 for ( i=0; i<num_locks; i++) {
1842 cb->fn(*key,
1843 locks[i].context.pid,
1844 locks[i].lock_type,
1845 locks[i].lock_flav,
1846 locks[i].start,
1847 locks[i].size,
1848 cb->private_data);
1852 TALLOC_FREE(locks);
1853 return 0;
1856 /*******************************************************************
1857 Call the specified function on each lock in the database.
1858 ********************************************************************/
1860 int brl_forall(void (*fn)(struct file_id id, struct server_id pid,
1861 enum brl_type lock_type,
1862 enum brl_flavour lock_flav,
1863 br_off start, br_off size,
1864 void *private_data),
1865 void *private_data)
1867 struct brl_forall_cb cb;
1868 NTSTATUS status;
1869 int count = 0;
1871 if (!brlock_db) {
1872 return 0;
1874 cb.fn = fn;
1875 cb.private_data = private_data;
1876 status = dbwrap_traverse(brlock_db, brl_traverse_fn, &cb, &count);
1878 if (!NT_STATUS_IS_OK(status)) {
1879 return -1;
1880 } else {
1881 return count;
1885 /*******************************************************************
1886 Store a potentially modified set of byte range lock data back into
1887 the database.
1888 Unlock the record.
1889 ********************************************************************/
1891 static void byte_range_lock_flush(struct byte_range_lock *br_lck)
1893 size_t data_len;
1894 if (!br_lck->modified) {
1895 DEBUG(10, ("br_lck not modified\n"));
1896 goto done;
1899 data_len = br_lck->num_locks * sizeof(struct lock_struct);
1901 if (br_lck->have_read_oplocks) {
1902 data_len += 1;
1905 DEBUG(10, ("data_len=%d\n", (int)data_len));
1907 if (data_len == 0) {
1908 /* No locks - delete this entry. */
1909 NTSTATUS status = dbwrap_record_delete(br_lck->record);
1910 if (!NT_STATUS_IS_OK(status)) {
1911 DEBUG(0, ("delete_rec returned %s\n",
1912 nt_errstr(status)));
1913 smb_panic("Could not delete byte range lock entry");
1915 } else {
1916 TDB_DATA data;
1917 NTSTATUS status;
1919 data.dsize = data_len;
1920 data.dptr = talloc_array(talloc_tos(), uint8_t, data_len);
1921 SMB_ASSERT(data.dptr != NULL);
1923 memcpy(data.dptr, br_lck->lock_data,
1924 br_lck->num_locks * sizeof(struct lock_struct));
1926 if (br_lck->have_read_oplocks) {
1927 data.dptr[data_len-1] = 1;
1930 status = dbwrap_record_store(br_lck->record, data, TDB_REPLACE);
1931 TALLOC_FREE(data.dptr);
1932 if (!NT_STATUS_IS_OK(status)) {
1933 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
1934 smb_panic("Could not store byte range mode entry");
1938 DEBUG(10, ("seqnum=%d\n", dbwrap_get_seqnum(brlock_db)));
1940 done:
1941 br_lck->modified = false;
1942 TALLOC_FREE(br_lck->record);
1945 static int byte_range_lock_destructor(struct byte_range_lock *br_lck)
1947 byte_range_lock_flush(br_lck);
1948 return 0;
1951 /*******************************************************************
1952 Fetch a set of byte range lock data from the database.
1953 Leave the record locked.
1954 TALLOC_FREE(brl) will release the lock in the destructor.
1955 ********************************************************************/
1957 struct byte_range_lock *brl_get_locks(TALLOC_CTX *mem_ctx, files_struct *fsp)
1959 TDB_DATA key, data;
1960 struct byte_range_lock *br_lck = talloc(mem_ctx, struct byte_range_lock);
1962 if (br_lck == NULL) {
1963 return NULL;
1966 br_lck->fsp = fsp;
1967 br_lck->num_locks = 0;
1968 br_lck->have_read_oplocks = false;
1969 br_lck->modified = False;
1971 key.dptr = (uint8 *)&fsp->file_id;
1972 key.dsize = sizeof(struct file_id);
1974 br_lck->record = dbwrap_fetch_locked(brlock_db, br_lck, key);
1976 if (br_lck->record == NULL) {
1977 DEBUG(3, ("Could not lock byte range lock entry\n"));
1978 TALLOC_FREE(br_lck);
1979 return NULL;
1982 data = dbwrap_record_get_value(br_lck->record);
1984 br_lck->lock_data = NULL;
1986 talloc_set_destructor(br_lck, byte_range_lock_destructor);
1988 br_lck->num_locks = data.dsize / sizeof(struct lock_struct);
1990 if (br_lck->num_locks != 0) {
1991 br_lck->lock_data = talloc_array(
1992 br_lck, struct lock_struct, br_lck->num_locks);
1993 if (br_lck->lock_data == NULL) {
1994 DEBUG(0, ("malloc failed\n"));
1995 TALLOC_FREE(br_lck);
1996 return NULL;
1999 memcpy(br_lck->lock_data, data.dptr,
2000 talloc_get_size(br_lck->lock_data));
2003 DEBUG(10, ("data.dsize=%d\n", (int)data.dsize));
2005 if ((data.dsize % sizeof(struct lock_struct)) == 1) {
2006 br_lck->have_read_oplocks = (data.dptr[data.dsize-1] == 1);
2009 if (!fsp->lockdb_clean) {
2010 int orig_num_locks = br_lck->num_locks;
2013 * This is the first time we access the byte range lock
2014 * record with this fsp. Go through and ensure all entries
2015 * are valid - remove any that don't.
2016 * This makes the lockdb self cleaning at low cost.
2018 * Note: Disconnected entries belong to disconnected
2019 * durable handles. So at this point, we have a new
2020 * handle on the file and the disconnected durable has
2021 * already been closed (we are not a durable reconnect).
2022 * So we need to clean the disconnected brl entry.
2025 if (!validate_lock_entries(&br_lck->num_locks,
2026 &br_lck->lock_data, false)) {
2027 TALLOC_FREE(br_lck);
2028 return NULL;
2031 /* Ensure invalid locks are cleaned up in the destructor. */
2032 if (orig_num_locks != br_lck->num_locks) {
2033 br_lck->modified = True;
2036 /* Mark the lockdb as "clean" as seen from this open file. */
2037 fsp->lockdb_clean = True;
2040 if (DEBUGLEVEL >= 10) {
2041 unsigned int i;
2042 struct lock_struct *locks = br_lck->lock_data;
2043 DEBUG(10,("brl_get_locks_internal: %u current locks on file_id %s\n",
2044 br_lck->num_locks,
2045 file_id_string_tos(&fsp->file_id)));
2046 for( i = 0; i < br_lck->num_locks; i++) {
2047 print_lock_struct(i, &locks[i]);
2051 return br_lck;
2054 struct brl_get_locks_readonly_state {
2055 TALLOC_CTX *mem_ctx;
2056 struct byte_range_lock **br_lock;
2059 static void brl_get_locks_readonly_parser(TDB_DATA key, TDB_DATA data,
2060 void *private_data)
2062 struct brl_get_locks_readonly_state *state =
2063 (struct brl_get_locks_readonly_state *)private_data;
2064 struct byte_range_lock *br_lock;
2066 br_lock = talloc_pooled_object(
2067 state->mem_ctx, struct byte_range_lock, 1, data.dsize);
2068 if (br_lock == NULL) {
2069 *state->br_lock = NULL;
2070 return;
2072 br_lock->lock_data = (struct lock_struct *)talloc_memdup(
2073 br_lock, data.dptr, data.dsize);
2074 br_lock->num_locks = data.dsize / sizeof(struct lock_struct);
2076 if ((data.dsize % sizeof(struct lock_struct)) == 1) {
2077 br_lock->have_read_oplocks = (data.dptr[data.dsize-1] == 1);
2078 } else {
2079 br_lock->have_read_oplocks = false;
2082 DEBUG(10, ("Got %d bytes, have_read_oplocks: %s\n", (int)data.dsize,
2083 br_lock->have_read_oplocks ? "true" : "false"));
2085 *state->br_lock = br_lock;
2088 struct byte_range_lock *brl_get_locks_readonly(files_struct *fsp)
2090 struct byte_range_lock *br_lock = NULL;
2091 struct byte_range_lock *rw = NULL;
2093 DEBUG(10, ("seqnum=%d, fsp->brlock_seqnum=%d\n",
2094 dbwrap_get_seqnum(brlock_db), fsp->brlock_seqnum));
2096 if ((fsp->brlock_rec != NULL)
2097 && (dbwrap_get_seqnum(brlock_db) == fsp->brlock_seqnum)) {
2099 * We have cached the brlock_rec and the database did not
2100 * change.
2102 return fsp->brlock_rec;
2105 if (!fsp->lockdb_clean) {
2107 * Fetch the record in R/W mode to give validate_lock_entries
2108 * a chance to kick in once.
2110 rw = brl_get_locks(talloc_tos(), fsp);
2111 if (rw == NULL) {
2112 return NULL;
2114 fsp->lockdb_clean = true;
2117 if (rw != NULL) {
2118 size_t lock_data_size;
2121 * Make a copy of the already retrieved and sanitized rw record
2123 lock_data_size = rw->num_locks * sizeof(struct lock_struct);
2124 br_lock = talloc_pooled_object(
2125 fsp, struct byte_range_lock, 1, lock_data_size);
2126 if (br_lock == NULL) {
2127 goto fail;
2129 br_lock->have_read_oplocks = rw->have_read_oplocks;
2130 br_lock->num_locks = rw->num_locks;
2131 br_lock->lock_data = (struct lock_struct *)talloc_memdup(
2132 br_lock, rw->lock_data, lock_data_size);
2133 } else {
2134 struct brl_get_locks_readonly_state state;
2135 NTSTATUS status;
2138 * Parse the record fresh from the database
2141 state.mem_ctx = fsp;
2142 state.br_lock = &br_lock;
2144 status = dbwrap_parse_record(
2145 brlock_db,
2146 make_tdb_data((uint8_t *)&fsp->file_id,
2147 sizeof(fsp->file_id)),
2148 brl_get_locks_readonly_parser, &state);
2150 if (NT_STATUS_EQUAL(status,NT_STATUS_NOT_FOUND)) {
2152 * No locks on this file. Return an empty br_lock.
2154 br_lock = talloc(fsp, struct byte_range_lock);
2155 if (br_lock == NULL) {
2156 goto fail;
2159 br_lock->have_read_oplocks = false;
2160 br_lock->num_locks = 0;
2161 br_lock->lock_data = NULL;
2163 } else if (!NT_STATUS_IS_OK(status)) {
2164 DEBUG(3, ("Could not parse byte range lock record: "
2165 "%s\n", nt_errstr(status)));
2166 goto fail;
2168 if (br_lock == NULL) {
2169 goto fail;
2173 br_lock->fsp = fsp;
2174 br_lock->modified = false;
2175 br_lock->record = NULL;
2177 if (lp_clustering()) {
2179 * In the cluster case we can't cache the brlock struct
2180 * because dbwrap_get_seqnum does not work reliably over
2181 * ctdb. Thus we have to throw away the brlock struct soon.
2183 talloc_steal(talloc_tos(), br_lock);
2184 } else {
2186 * Cache the brlock struct, invalidated when the dbwrap_seqnum
2187 * changes. See beginning of this routine.
2189 TALLOC_FREE(fsp->brlock_rec);
2190 fsp->brlock_rec = br_lock;
2191 fsp->brlock_seqnum = dbwrap_get_seqnum(brlock_db);
2194 fail:
2195 TALLOC_FREE(rw);
2196 return br_lock;
2199 struct brl_revalidate_state {
2200 ssize_t array_size;
2201 uint32 num_pids;
2202 struct server_id *pids;
2206 * Collect PIDs of all processes with pending entries
2209 static void brl_revalidate_collect(struct file_id id, struct server_id pid,
2210 enum brl_type lock_type,
2211 enum brl_flavour lock_flav,
2212 br_off start, br_off size,
2213 void *private_data)
2215 struct brl_revalidate_state *state =
2216 (struct brl_revalidate_state *)private_data;
2218 if (!IS_PENDING_LOCK(lock_type)) {
2219 return;
2222 add_to_large_array(state, sizeof(pid), (void *)&pid,
2223 &state->pids, &state->num_pids,
2224 &state->array_size);
2228 * qsort callback to sort the processes
2231 static int compare_procids(const void *p1, const void *p2)
2233 const struct server_id *i1 = (const struct server_id *)p1;
2234 const struct server_id *i2 = (const struct server_id *)p2;
2236 if (i1->pid < i2->pid) return -1;
2237 if (i1->pid > i2->pid) return 1;
2238 return 0;
2242 * Send a MSG_SMB_UNLOCK message to all processes with pending byte range
2243 * locks so that they retry. Mainly used in the cluster code after a node has
2244 * died.
2246 * Done in two steps to avoid double-sends: First we collect all entries in an
2247 * array, then qsort that array and only send to non-dupes.
2250 void brl_revalidate(struct messaging_context *msg_ctx,
2251 void *private_data,
2252 uint32_t msg_type,
2253 struct server_id server_id,
2254 DATA_BLOB *data)
2256 struct brl_revalidate_state *state;
2257 uint32 i;
2258 struct server_id last_pid;
2260 if (!(state = talloc_zero(NULL, struct brl_revalidate_state))) {
2261 DEBUG(0, ("talloc failed\n"));
2262 return;
2265 brl_forall(brl_revalidate_collect, state);
2267 if (state->array_size == -1) {
2268 DEBUG(0, ("talloc failed\n"));
2269 goto done;
2272 if (state->num_pids == 0) {
2273 goto done;
2276 TYPESAFE_QSORT(state->pids, state->num_pids, compare_procids);
2278 ZERO_STRUCT(last_pid);
2280 for (i=0; i<state->num_pids; i++) {
2281 if (serverid_equal(&last_pid, &state->pids[i])) {
2283 * We've seen that one already
2285 continue;
2288 messaging_send(msg_ctx, state->pids[i], MSG_SMB_UNLOCK,
2289 &data_blob_null);
2290 last_pid = state->pids[i];
2293 done:
2294 TALLOC_FREE(state);
2295 return;
2298 bool brl_cleanup_disconnected(struct file_id fid, uint64_t open_persistent_id)
2300 bool ret = false;
2301 TALLOC_CTX *frame = talloc_stackframe();
2302 TDB_DATA key, val;
2303 struct db_record *rec;
2304 struct lock_struct *lock;
2305 unsigned n, num;
2306 NTSTATUS status;
2308 key = make_tdb_data((void*)&fid, sizeof(fid));
2310 rec = dbwrap_fetch_locked(brlock_db, frame, key);
2311 if (rec == NULL) {
2312 DEBUG(5, ("brl_cleanup_disconnected: failed to fetch record "
2313 "for file %s\n", file_id_string(frame, &fid)));
2314 goto done;
2317 val = dbwrap_record_get_value(rec);
2318 lock = (struct lock_struct*)val.dptr;
2319 num = val.dsize / sizeof(struct lock_struct);
2320 if (lock == NULL) {
2321 DEBUG(10, ("brl_cleanup_disconnected: no byte range locks for "
2322 "file %s\n", file_id_string(frame, &fid)));
2323 ret = true;
2324 goto done;
2327 for (n=0; n<num; n++) {
2328 struct lock_context *ctx = &lock[n].context;
2330 if (!server_id_is_disconnected(&ctx->pid)) {
2331 DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2332 "%s used by server %s, do not cleanup\n",
2333 file_id_string(frame, &fid),
2334 server_id_str(frame, &ctx->pid)));
2335 goto done;
2338 if (ctx->smblctx != open_persistent_id) {
2339 DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2340 "%s expected smblctx %llu but found %llu"
2341 ", do not cleanup\n",
2342 file_id_string(frame, &fid),
2343 (unsigned long long)open_persistent_id,
2344 (unsigned long long)ctx->smblctx));
2345 goto done;
2349 status = dbwrap_record_delete(rec);
2350 if (!NT_STATUS_IS_OK(status)) {
2351 DEBUG(5, ("brl_cleanup_disconnected: failed to delete record "
2352 "for file %s from %s, open %llu: %s\n",
2353 file_id_string(frame, &fid), dbwrap_name(brlock_db),
2354 (unsigned long long)open_persistent_id,
2355 nt_errstr(status)));
2356 goto done;
2359 DEBUG(10, ("brl_cleanup_disconnected: "
2360 "file %s cleaned up %u entries from open %llu\n",
2361 file_id_string(frame, &fid), num,
2362 (unsigned long long)open_persistent_id));
2364 ret = true;
2365 done:
2366 talloc_free(frame);
2367 return ret;