dsdb: Always store and return the userParameters as a array of LE 16-bit values
[Samba.git] / source3 / locking / brlock.c
blobbe90b2b519162aa1ac8a55a074461e02f501c994
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 = %.0f, size = %.0f, fnum = %llu, %s %s\n",
68 (double)pls->start,
69 (double)pls->size,
70 (unsigned long long)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 *lck1, const struct lock_struct *lck2)
232 if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
233 return False;
235 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK)
236 return False;
238 /* POSIX flavour locks never conflict here - this is only called
239 in the read/write path. */
241 if (lck1->lock_flav == POSIX_LOCK && lck2->lock_flav == POSIX_LOCK)
242 return False;
245 * Incoming WRITE locks conflict with existing READ locks even
246 * if the context is the same. JRA. See LOCKTEST7 in smbtorture.
249 if (!(lck2->lock_type == WRITE_LOCK && lck1->lock_type == READ_LOCK)) {
250 if (brl_same_context(&lck1->context, &lck2->context) &&
251 lck1->fnum == lck2->fnum)
252 return False;
255 return brl_overlap(lck1, lck2);
258 /****************************************************************************
259 Check if an unlock overlaps a pending lock.
260 ****************************************************************************/
262 static bool brl_pending_overlap(const struct lock_struct *lock, const struct lock_struct *pend_lock)
264 if ((lock->start <= pend_lock->start) && (lock->start + lock->size > pend_lock->start))
265 return True;
266 if ((lock->start >= pend_lock->start) && (lock->start < pend_lock->start + pend_lock->size))
267 return True;
268 return False;
271 /****************************************************************************
272 Amazingly enough, w2k3 "remembers" whether the last lock failure on a fnum
273 is the same as this one and changes its error code. I wonder if any
274 app depends on this ?
275 ****************************************************************************/
277 static NTSTATUS brl_lock_failed(files_struct *fsp,
278 const struct lock_struct *lock,
279 bool blocking_lock)
281 if (lock->start >= 0xEF000000 && (lock->start >> 63) == 0) {
282 /* amazing the little things you learn with a test
283 suite. Locks beyond this offset (as a 64 bit
284 number!) always generate the conflict error code,
285 unless the top bit is set */
286 if (!blocking_lock) {
287 fsp->last_lock_failure = *lock;
289 return NT_STATUS_FILE_LOCK_CONFLICT;
292 if (serverid_equal(&lock->context.pid, &fsp->last_lock_failure.context.pid) &&
293 lock->context.tid == fsp->last_lock_failure.context.tid &&
294 lock->fnum == fsp->last_lock_failure.fnum &&
295 lock->start == fsp->last_lock_failure.start) {
296 return NT_STATUS_FILE_LOCK_CONFLICT;
299 if (!blocking_lock) {
300 fsp->last_lock_failure = *lock;
302 return NT_STATUS_LOCK_NOT_GRANTED;
305 /****************************************************************************
306 Open up the brlock.tdb database.
307 ****************************************************************************/
309 void brl_init(bool read_only)
311 int tdb_flags;
313 if (brlock_db) {
314 return;
317 tdb_flags = TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH;
319 if (!lp_clustering()) {
321 * We can't use the SEQNUM trick to cache brlock
322 * entries in the clustering case because ctdb seqnum
323 * propagation has a delay.
325 tdb_flags |= TDB_SEQNUM;
328 brlock_db = db_open(NULL, lock_path("brlock.tdb"),
329 SMB_OPEN_DATABASE_TDB_HASH_SIZE, tdb_flags,
330 read_only?O_RDONLY:(O_RDWR|O_CREAT), 0644,
331 DBWRAP_LOCK_ORDER_2, DBWRAP_FLAG_NONE);
332 if (!brlock_db) {
333 DEBUG(0,("Failed to open byte range locking database %s\n",
334 lock_path("brlock.tdb")));
335 return;
339 /****************************************************************************
340 Close down the brlock.tdb database.
341 ****************************************************************************/
343 void brl_shutdown(void)
345 TALLOC_FREE(brlock_db);
348 #if ZERO_ZERO
349 /****************************************************************************
350 Compare two locks for sorting.
351 ****************************************************************************/
353 static int lock_compare(const struct lock_struct *lck1,
354 const struct lock_struct *lck2)
356 if (lck1->start != lck2->start) {
357 return (lck1->start - lck2->start);
359 if (lck2->size != lck1->size) {
360 return ((int)lck1->size - (int)lck2->size);
362 return 0;
364 #endif
366 /****************************************************************************
367 Lock a range of bytes - Windows lock semantics.
368 ****************************************************************************/
370 NTSTATUS brl_lock_windows_default(struct byte_range_lock *br_lck,
371 struct lock_struct *plock, bool blocking_lock)
373 unsigned int i;
374 files_struct *fsp = br_lck->fsp;
375 struct lock_struct *locks = br_lck->lock_data;
376 NTSTATUS status;
378 SMB_ASSERT(plock->lock_type != UNLOCK_LOCK);
380 if ((plock->start + plock->size - 1 < plock->start) &&
381 plock->size != 0) {
382 return NT_STATUS_INVALID_LOCK_RANGE;
385 for (i=0; i < br_lck->num_locks; i++) {
386 /* Do any Windows or POSIX locks conflict ? */
387 if (brl_conflict(&locks[i], plock)) {
388 /* Remember who blocked us. */
389 plock->context.smblctx = locks[i].context.smblctx;
390 return brl_lock_failed(fsp,plock,blocking_lock);
392 #if ZERO_ZERO
393 if (plock->start == 0 && plock->size == 0 &&
394 locks[i].size == 0) {
395 break;
397 #endif
400 if (!IS_PENDING_LOCK(plock->lock_type)) {
401 contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
404 /* We can get the Windows lock, now see if it needs to
405 be mapped into a lower level POSIX one, and if so can
406 we get it ? */
408 if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(fsp->conn->params)) {
409 int errno_ret;
410 if (!set_posix_lock_windows_flavour(fsp,
411 plock->start,
412 plock->size,
413 plock->lock_type,
414 &plock->context,
415 locks,
416 br_lck->num_locks,
417 &errno_ret)) {
419 /* We don't know who blocked us. */
420 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
422 if (errno_ret == EACCES || errno_ret == EAGAIN) {
423 status = NT_STATUS_FILE_LOCK_CONFLICT;
424 goto fail;
425 } else {
426 status = map_nt_error_from_unix(errno);
427 goto fail;
432 /* no conflicts - add it to the list of locks */
433 locks = talloc_realloc(br_lck, locks, struct lock_struct,
434 (br_lck->num_locks + 1));
435 if (!locks) {
436 status = NT_STATUS_NO_MEMORY;
437 goto fail;
440 memcpy(&locks[br_lck->num_locks], plock, sizeof(struct lock_struct));
441 br_lck->num_locks += 1;
442 br_lck->lock_data = locks;
443 br_lck->modified = True;
445 return NT_STATUS_OK;
446 fail:
447 if (!IS_PENDING_LOCK(plock->lock_type)) {
448 contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
450 return status;
453 /****************************************************************************
454 Cope with POSIX range splits and merges.
455 ****************************************************************************/
457 static unsigned int brlock_posix_split_merge(struct lock_struct *lck_arr, /* Output array. */
458 struct lock_struct *ex, /* existing lock. */
459 struct lock_struct *plock) /* proposed lock. */
461 bool lock_types_differ = (ex->lock_type != plock->lock_type);
463 /* We can't merge non-conflicting locks on different context - ignore fnum. */
465 if (!brl_same_context(&ex->context, &plock->context)) {
466 /* Just copy. */
467 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
468 return 1;
471 /* We now know we have the same context. */
473 /* Did we overlap ? */
475 /*********************************************
476 +---------+
477 | ex |
478 +---------+
479 +-------+
480 | plock |
481 +-------+
482 OR....
483 +---------+
484 | ex |
485 +---------+
486 **********************************************/
488 if ( (ex->start > (plock->start + plock->size)) ||
489 (plock->start > (ex->start + ex->size))) {
491 /* No overlap with this lock - copy existing. */
493 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
494 return 1;
497 /*********************************************
498 +---------------------------+
499 | ex |
500 +---------------------------+
501 +---------------------------+
502 | plock | -> replace with plock.
503 +---------------------------+
505 +---------------+
506 | ex |
507 +---------------+
508 +---------------------------+
509 | plock | -> replace with plock.
510 +---------------------------+
512 **********************************************/
514 if ( (ex->start >= plock->start) &&
515 (ex->start + ex->size <= plock->start + plock->size) ) {
517 /* Replace - discard existing lock. */
519 return 0;
522 /*********************************************
523 Adjacent after.
524 +-------+
525 | ex |
526 +-------+
527 +---------------+
528 | plock |
529 +---------------+
531 BECOMES....
532 +---------------+-------+
533 | plock | ex | - different lock types.
534 +---------------+-------+
535 OR.... (merge)
536 +-----------------------+
537 | plock | - same lock type.
538 +-----------------------+
539 **********************************************/
541 if (plock->start + plock->size == ex->start) {
543 /* If the lock types are the same, we merge, if different, we
544 add the remainder of the old lock. */
546 if (lock_types_differ) {
547 /* Add existing. */
548 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
549 return 1;
550 } else {
551 /* Merge - adjust incoming lock as we may have more
552 * merging to come. */
553 plock->size += ex->size;
554 return 0;
558 /*********************************************
559 Adjacent before.
560 +-------+
561 | ex |
562 +-------+
563 +---------------+
564 | plock |
565 +---------------+
566 BECOMES....
567 +-------+---------------+
568 | ex | plock | - different lock types
569 +-------+---------------+
571 OR.... (merge)
572 +-----------------------+
573 | plock | - same lock type.
574 +-----------------------+
576 **********************************************/
578 if (ex->start + ex->size == plock->start) {
580 /* If the lock types are the same, we merge, if different, we
581 add the existing lock. */
583 if (lock_types_differ) {
584 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
585 return 1;
586 } else {
587 /* Merge - adjust incoming lock as we may have more
588 * merging to come. */
589 plock->start = ex->start;
590 plock->size += ex->size;
591 return 0;
595 /*********************************************
596 Overlap after.
597 +-----------------------+
598 | ex |
599 +-----------------------+
600 +---------------+
601 | plock |
602 +---------------+
604 +----------------+
605 | ex |
606 +----------------+
607 +---------------+
608 | plock |
609 +---------------+
611 BECOMES....
612 +---------------+-------+
613 | plock | ex | - different lock types.
614 +---------------+-------+
615 OR.... (merge)
616 +-----------------------+
617 | plock | - same lock type.
618 +-----------------------+
619 **********************************************/
621 if ( (ex->start >= plock->start) &&
622 (ex->start <= plock->start + plock->size) &&
623 (ex->start + ex->size > plock->start + plock->size) ) {
625 /* If the lock types are the same, we merge, if different, we
626 add the remainder of the old lock. */
628 if (lock_types_differ) {
629 /* Add remaining existing. */
630 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
631 /* Adjust existing start and size. */
632 lck_arr[0].start = plock->start + plock->size;
633 lck_arr[0].size = (ex->start + ex->size) - (plock->start + plock->size);
634 return 1;
635 } else {
636 /* Merge - adjust incoming lock as we may have more
637 * merging to come. */
638 plock->size += (ex->start + ex->size) - (plock->start + plock->size);
639 return 0;
643 /*********************************************
644 Overlap before.
645 +-----------------------+
646 | ex |
647 +-----------------------+
648 +---------------+
649 | plock |
650 +---------------+
652 +-------------+
653 | ex |
654 +-------------+
655 +---------------+
656 | plock |
657 +---------------+
659 BECOMES....
660 +-------+---------------+
661 | ex | plock | - different lock types
662 +-------+---------------+
664 OR.... (merge)
665 +-----------------------+
666 | plock | - same lock type.
667 +-----------------------+
669 **********************************************/
671 if ( (ex->start < plock->start) &&
672 (ex->start + ex->size >= plock->start) &&
673 (ex->start + ex->size <= plock->start + plock->size) ) {
675 /* If the lock types are the same, we merge, if different, we
676 add the truncated old lock. */
678 if (lock_types_differ) {
679 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
680 /* Adjust existing size. */
681 lck_arr[0].size = plock->start - ex->start;
682 return 1;
683 } else {
684 /* Merge - adjust incoming lock as we may have more
685 * merging to come. MUST ADJUST plock SIZE FIRST ! */
686 plock->size += (plock->start - ex->start);
687 plock->start = ex->start;
688 return 0;
692 /*********************************************
693 Complete overlap.
694 +---------------------------+
695 | ex |
696 +---------------------------+
697 +---------+
698 | plock |
699 +---------+
700 BECOMES.....
701 +-------+---------+---------+
702 | ex | plock | ex | - different lock types.
703 +-------+---------+---------+
705 +---------------------------+
706 | plock | - same lock type.
707 +---------------------------+
708 **********************************************/
710 if ( (ex->start < plock->start) && (ex->start + ex->size > plock->start + plock->size) ) {
712 if (lock_types_differ) {
714 /* We have to split ex into two locks here. */
716 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
717 memcpy(&lck_arr[1], ex, sizeof(struct lock_struct));
719 /* Adjust first existing size. */
720 lck_arr[0].size = plock->start - ex->start;
722 /* Adjust second existing start and size. */
723 lck_arr[1].start = plock->start + plock->size;
724 lck_arr[1].size = (ex->start + ex->size) - (plock->start + plock->size);
725 return 2;
726 } else {
727 /* Just eat the existing locks, merge them into plock. */
728 plock->start = ex->start;
729 plock->size = ex->size;
730 return 0;
734 /* Never get here. */
735 smb_panic("brlock_posix_split_merge");
736 /* Notreached. */
738 /* Keep some compilers happy. */
739 return 0;
742 /****************************************************************************
743 Lock a range of bytes - POSIX lock semantics.
744 We must cope with range splits and merges.
745 ****************************************************************************/
747 static NTSTATUS brl_lock_posix(struct messaging_context *msg_ctx,
748 struct byte_range_lock *br_lck,
749 struct lock_struct *plock)
751 unsigned int i, count, posix_count;
752 struct lock_struct *locks = br_lck->lock_data;
753 struct lock_struct *tp;
754 bool signal_pending_read = False;
755 bool break_oplocks = false;
756 NTSTATUS status;
758 /* No zero-zero locks for POSIX. */
759 if (plock->start == 0 && plock->size == 0) {
760 return NT_STATUS_INVALID_PARAMETER;
763 /* Don't allow 64-bit lock wrap. */
764 if (plock->start + plock->size - 1 < plock->start) {
765 return NT_STATUS_INVALID_PARAMETER;
768 /* The worst case scenario here is we have to split an
769 existing POSIX lock range into two, and add our lock,
770 so we need at most 2 more entries. */
772 tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 2);
773 if (!tp) {
774 return NT_STATUS_NO_MEMORY;
777 count = posix_count = 0;
779 for (i=0; i < br_lck->num_locks; i++) {
780 struct lock_struct *curr_lock = &locks[i];
782 /* If we have a pending read lock, a lock downgrade should
783 trigger a lock re-evaluation. */
784 if (curr_lock->lock_type == PENDING_READ_LOCK &&
785 brl_pending_overlap(plock, curr_lock)) {
786 signal_pending_read = True;
789 if (curr_lock->lock_flav == WINDOWS_LOCK) {
790 /* Do any Windows flavour locks conflict ? */
791 if (brl_conflict(curr_lock, plock)) {
792 /* No games with error messages. */
793 TALLOC_FREE(tp);
794 /* Remember who blocked us. */
795 plock->context.smblctx = curr_lock->context.smblctx;
796 return NT_STATUS_FILE_LOCK_CONFLICT;
798 /* Just copy the Windows lock into the new array. */
799 memcpy(&tp[count], curr_lock, sizeof(struct lock_struct));
800 count++;
801 } else {
802 unsigned int tmp_count = 0;
804 /* POSIX conflict semantics are different. */
805 if (brl_conflict_posix(curr_lock, plock)) {
806 /* Can't block ourselves with POSIX locks. */
807 /* No games with error messages. */
808 TALLOC_FREE(tp);
809 /* Remember who blocked us. */
810 plock->context.smblctx = curr_lock->context.smblctx;
811 return NT_STATUS_FILE_LOCK_CONFLICT;
814 /* Work out overlaps. */
815 tmp_count += brlock_posix_split_merge(&tp[count], curr_lock, plock);
816 posix_count += tmp_count;
817 count += tmp_count;
822 * Break oplocks while we hold a brl. Since lock() and unlock() calls
823 * are not symetric with POSIX semantics, we cannot guarantee our
824 * contend_level2_oplocks_begin/end calls will be acquired and
825 * released one-for-one as with Windows semantics. Therefore we only
826 * call contend_level2_oplocks_begin if this is the first POSIX brl on
827 * the file.
829 break_oplocks = (!IS_PENDING_LOCK(plock->lock_type) &&
830 posix_count == 0);
831 if (break_oplocks) {
832 contend_level2_oplocks_begin(br_lck->fsp,
833 LEVEL2_CONTEND_POSIX_BRL);
836 /* Try and add the lock in order, sorted by lock start. */
837 for (i=0; i < count; i++) {
838 struct lock_struct *curr_lock = &tp[i];
840 if (curr_lock->start <= plock->start) {
841 continue;
845 if (i < count) {
846 memmove(&tp[i+1], &tp[i],
847 (count - i)*sizeof(struct lock_struct));
849 memcpy(&tp[i], plock, sizeof(struct lock_struct));
850 count++;
852 /* We can get the POSIX lock, now see if it needs to
853 be mapped into a lower level POSIX one, and if so can
854 we get it ? */
856 if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(br_lck->fsp->conn->params)) {
857 int errno_ret;
859 /* The lower layer just needs to attempt to
860 get the system POSIX lock. We've weeded out
861 any conflicts above. */
863 if (!set_posix_lock_posix_flavour(br_lck->fsp,
864 plock->start,
865 plock->size,
866 plock->lock_type,
867 &errno_ret)) {
869 /* We don't know who blocked us. */
870 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
872 if (errno_ret == EACCES || errno_ret == EAGAIN) {
873 TALLOC_FREE(tp);
874 status = NT_STATUS_FILE_LOCK_CONFLICT;
875 goto fail;
876 } else {
877 TALLOC_FREE(tp);
878 status = map_nt_error_from_unix(errno);
879 goto fail;
884 /* If we didn't use all the allocated size,
885 * Realloc so we don't leak entries per lock call. */
886 if (count < br_lck->num_locks + 2) {
887 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
888 if (!tp) {
889 status = NT_STATUS_NO_MEMORY;
890 goto fail;
894 br_lck->num_locks = count;
895 TALLOC_FREE(br_lck->lock_data);
896 br_lck->lock_data = tp;
897 locks = tp;
898 br_lck->modified = True;
900 /* A successful downgrade from write to read lock can trigger a lock
901 re-evalutation where waiting readers can now proceed. */
903 if (signal_pending_read) {
904 /* Send unlock messages to any pending read waiters that overlap. */
905 for (i=0; i < br_lck->num_locks; i++) {
906 struct lock_struct *pend_lock = &locks[i];
908 /* Ignore non-pending locks. */
909 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
910 continue;
913 if (pend_lock->lock_type == PENDING_READ_LOCK &&
914 brl_pending_overlap(plock, pend_lock)) {
915 DEBUG(10,("brl_lock_posix: sending unlock message to pid %s\n",
916 procid_str_static(&pend_lock->context.pid )));
918 messaging_send(msg_ctx, pend_lock->context.pid,
919 MSG_SMB_UNLOCK, &data_blob_null);
924 return NT_STATUS_OK;
925 fail:
926 if (break_oplocks) {
927 contend_level2_oplocks_end(br_lck->fsp,
928 LEVEL2_CONTEND_POSIX_BRL);
930 return status;
933 NTSTATUS smb_vfs_call_brl_lock_windows(struct vfs_handle_struct *handle,
934 struct byte_range_lock *br_lck,
935 struct lock_struct *plock,
936 bool blocking_lock)
938 VFS_FIND(brl_lock_windows);
939 return handle->fns->brl_lock_windows_fn(handle, br_lck, plock,
940 blocking_lock);
943 /****************************************************************************
944 Lock a range of bytes.
945 ****************************************************************************/
947 NTSTATUS brl_lock(struct messaging_context *msg_ctx,
948 struct byte_range_lock *br_lck,
949 uint64_t smblctx,
950 struct server_id pid,
951 br_off start,
952 br_off size,
953 enum brl_type lock_type,
954 enum brl_flavour lock_flav,
955 bool blocking_lock,
956 uint64_t *psmblctx)
958 NTSTATUS ret;
959 struct lock_struct lock;
961 #if !ZERO_ZERO
962 if (start == 0 && size == 0) {
963 DEBUG(0,("client sent 0/0 lock - please report this\n"));
965 #endif
967 #ifdef DEVELOPER
968 /* Quieten valgrind on test. */
969 ZERO_STRUCT(lock);
970 #endif
972 lock.context.smblctx = smblctx;
973 lock.context.pid = pid;
974 lock.context.tid = br_lck->fsp->conn->cnum;
975 lock.start = start;
976 lock.size = size;
977 lock.fnum = br_lck->fsp->fnum;
978 lock.lock_type = lock_type;
979 lock.lock_flav = lock_flav;
981 if (lock_flav == WINDOWS_LOCK) {
982 ret = SMB_VFS_BRL_LOCK_WINDOWS(br_lck->fsp->conn, br_lck,
983 &lock, blocking_lock);
984 } else {
985 ret = brl_lock_posix(msg_ctx, br_lck, &lock);
988 #if ZERO_ZERO
989 /* sort the lock list */
990 TYPESAFE_QSORT(br_lck->lock_data, (size_t)br_lck->num_locks, lock_compare);
991 #endif
993 /* If we're returning an error, return who blocked us. */
994 if (!NT_STATUS_IS_OK(ret) && psmblctx) {
995 *psmblctx = lock.context.smblctx;
997 return ret;
1000 static void brl_delete_lock_struct(struct lock_struct *locks,
1001 unsigned num_locks,
1002 unsigned del_idx)
1004 if (del_idx >= num_locks) {
1005 return;
1007 memmove(&locks[del_idx], &locks[del_idx+1],
1008 sizeof(*locks) * (num_locks - del_idx - 1));
1011 /****************************************************************************
1012 Unlock a range of bytes - Windows semantics.
1013 ****************************************************************************/
1015 bool brl_unlock_windows_default(struct messaging_context *msg_ctx,
1016 struct byte_range_lock *br_lck,
1017 const struct lock_struct *plock)
1019 unsigned int i, j;
1020 struct lock_struct *locks = br_lck->lock_data;
1021 enum brl_type deleted_lock_type = READ_LOCK; /* shut the compiler up.... */
1023 SMB_ASSERT(plock->lock_type == UNLOCK_LOCK);
1025 #if ZERO_ZERO
1026 /* Delete write locks by preference... The lock list
1027 is sorted in the zero zero case. */
1029 for (i = 0; i < br_lck->num_locks; i++) {
1030 struct lock_struct *lock = &locks[i];
1032 if (lock->lock_type == WRITE_LOCK &&
1033 brl_same_context(&lock->context, &plock->context) &&
1034 lock->fnum == plock->fnum &&
1035 lock->lock_flav == WINDOWS_LOCK &&
1036 lock->start == plock->start &&
1037 lock->size == plock->size) {
1039 /* found it - delete it */
1040 deleted_lock_type = lock->lock_type;
1041 break;
1045 if (i != br_lck->num_locks) {
1046 /* We found it - don't search again. */
1047 goto unlock_continue;
1049 #endif
1051 for (i = 0; i < br_lck->num_locks; i++) {
1052 struct lock_struct *lock = &locks[i];
1054 if (IS_PENDING_LOCK(lock->lock_type)) {
1055 continue;
1058 /* Only remove our own locks that match in start, size, and flavour. */
1059 if (brl_same_context(&lock->context, &plock->context) &&
1060 lock->fnum == plock->fnum &&
1061 lock->lock_flav == WINDOWS_LOCK &&
1062 lock->start == plock->start &&
1063 lock->size == plock->size ) {
1064 deleted_lock_type = lock->lock_type;
1065 break;
1069 if (i == br_lck->num_locks) {
1070 /* we didn't find it */
1071 return False;
1074 #if ZERO_ZERO
1075 unlock_continue:
1076 #endif
1078 brl_delete_lock_struct(locks, br_lck->num_locks, i);
1079 br_lck->num_locks -= 1;
1080 br_lck->modified = True;
1082 /* Unlock the underlying POSIX regions. */
1083 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1084 release_posix_lock_windows_flavour(br_lck->fsp,
1085 plock->start,
1086 plock->size,
1087 deleted_lock_type,
1088 &plock->context,
1089 locks,
1090 br_lck->num_locks);
1093 /* Send unlock messages to any pending waiters that overlap. */
1094 for (j=0; j < br_lck->num_locks; j++) {
1095 struct lock_struct *pend_lock = &locks[j];
1097 /* Ignore non-pending locks. */
1098 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1099 continue;
1102 /* We could send specific lock info here... */
1103 if (brl_pending_overlap(plock, pend_lock)) {
1104 DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
1105 procid_str_static(&pend_lock->context.pid )));
1107 messaging_send(msg_ctx, pend_lock->context.pid,
1108 MSG_SMB_UNLOCK, &data_blob_null);
1112 contend_level2_oplocks_end(br_lck->fsp, LEVEL2_CONTEND_WINDOWS_BRL);
1113 return True;
1116 /****************************************************************************
1117 Unlock a range of bytes - POSIX semantics.
1118 ****************************************************************************/
1120 static bool brl_unlock_posix(struct messaging_context *msg_ctx,
1121 struct byte_range_lock *br_lck,
1122 struct lock_struct *plock)
1124 unsigned int i, j, count;
1125 struct lock_struct *tp;
1126 struct lock_struct *locks = br_lck->lock_data;
1127 bool overlap_found = False;
1129 /* No zero-zero locks for POSIX. */
1130 if (plock->start == 0 && plock->size == 0) {
1131 return False;
1134 /* Don't allow 64-bit lock wrap. */
1135 if (plock->start + plock->size < plock->start ||
1136 plock->start + plock->size < plock->size) {
1137 DEBUG(10,("brl_unlock_posix: lock wrap\n"));
1138 return False;
1141 /* The worst case scenario here is we have to split an
1142 existing POSIX lock range into two, so we need at most
1143 1 more entry. */
1145 tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 1);
1146 if (!tp) {
1147 DEBUG(10,("brl_unlock_posix: malloc fail\n"));
1148 return False;
1151 count = 0;
1152 for (i = 0; i < br_lck->num_locks; i++) {
1153 struct lock_struct *lock = &locks[i];
1154 unsigned int tmp_count;
1156 /* Only remove our own locks - ignore fnum. */
1157 if (IS_PENDING_LOCK(lock->lock_type) ||
1158 !brl_same_context(&lock->context, &plock->context)) {
1159 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1160 count++;
1161 continue;
1164 if (lock->lock_flav == WINDOWS_LOCK) {
1165 /* Do any Windows flavour locks conflict ? */
1166 if (brl_conflict(lock, plock)) {
1167 TALLOC_FREE(tp);
1168 return false;
1170 /* Just copy the Windows lock into the new array. */
1171 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1172 count++;
1173 continue;
1176 /* Work out overlaps. */
1177 tmp_count = brlock_posix_split_merge(&tp[count], lock, plock);
1179 if (tmp_count == 0) {
1180 /* plock overlapped the existing lock completely,
1181 or replaced it. Don't copy the existing lock. */
1182 overlap_found = true;
1183 } else if (tmp_count == 1) {
1184 /* Either no overlap, (simple copy of existing lock) or
1185 * an overlap of an existing lock. */
1186 /* If the lock changed size, we had an overlap. */
1187 if (tp[count].size != lock->size) {
1188 overlap_found = true;
1190 count += tmp_count;
1191 } else if (tmp_count == 2) {
1192 /* We split a lock range in two. */
1193 overlap_found = true;
1194 count += tmp_count;
1196 /* Optimisation... */
1197 /* We know we're finished here as we can't overlap any
1198 more POSIX locks. Copy the rest of the lock array. */
1200 if (i < br_lck->num_locks - 1) {
1201 memcpy(&tp[count], &locks[i+1],
1202 sizeof(*locks)*((br_lck->num_locks-1) - i));
1203 count += ((br_lck->num_locks-1) - i);
1205 break;
1210 if (!overlap_found) {
1211 /* Just ignore - no change. */
1212 TALLOC_FREE(tp);
1213 DEBUG(10,("brl_unlock_posix: No overlap - unlocked.\n"));
1214 return True;
1217 /* Unlock any POSIX regions. */
1218 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1219 release_posix_lock_posix_flavour(br_lck->fsp,
1220 plock->start,
1221 plock->size,
1222 &plock->context,
1224 count);
1227 /* Realloc so we don't leak entries per unlock call. */
1228 if (count) {
1229 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
1230 if (!tp) {
1231 DEBUG(10,("brl_unlock_posix: realloc fail\n"));
1232 return False;
1234 } else {
1235 /* We deleted the last lock. */
1236 TALLOC_FREE(tp);
1237 tp = NULL;
1240 contend_level2_oplocks_end(br_lck->fsp,
1241 LEVEL2_CONTEND_POSIX_BRL);
1243 br_lck->num_locks = count;
1244 TALLOC_FREE(br_lck->lock_data);
1245 locks = tp;
1246 br_lck->lock_data = tp;
1247 br_lck->modified = True;
1249 /* Send unlock messages to any pending waiters that overlap. */
1251 for (j=0; j < br_lck->num_locks; j++) {
1252 struct lock_struct *pend_lock = &locks[j];
1254 /* Ignore non-pending locks. */
1255 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1256 continue;
1259 /* We could send specific lock info here... */
1260 if (brl_pending_overlap(plock, pend_lock)) {
1261 DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
1262 procid_str_static(&pend_lock->context.pid )));
1264 messaging_send(msg_ctx, pend_lock->context.pid,
1265 MSG_SMB_UNLOCK, &data_blob_null);
1269 return True;
1272 bool smb_vfs_call_brl_unlock_windows(struct vfs_handle_struct *handle,
1273 struct messaging_context *msg_ctx,
1274 struct byte_range_lock *br_lck,
1275 const struct lock_struct *plock)
1277 VFS_FIND(brl_unlock_windows);
1278 return handle->fns->brl_unlock_windows_fn(handle, msg_ctx, br_lck,
1279 plock);
1282 /****************************************************************************
1283 Unlock a range of bytes.
1284 ****************************************************************************/
1286 bool brl_unlock(struct messaging_context *msg_ctx,
1287 struct byte_range_lock *br_lck,
1288 uint64_t smblctx,
1289 struct server_id pid,
1290 br_off start,
1291 br_off size,
1292 enum brl_flavour lock_flav)
1294 struct lock_struct lock;
1296 lock.context.smblctx = smblctx;
1297 lock.context.pid = pid;
1298 lock.context.tid = br_lck->fsp->conn->cnum;
1299 lock.start = start;
1300 lock.size = size;
1301 lock.fnum = br_lck->fsp->fnum;
1302 lock.lock_type = UNLOCK_LOCK;
1303 lock.lock_flav = lock_flav;
1305 if (lock_flav == WINDOWS_LOCK) {
1306 return SMB_VFS_BRL_UNLOCK_WINDOWS(br_lck->fsp->conn, msg_ctx,
1307 br_lck, &lock);
1308 } else {
1309 return brl_unlock_posix(msg_ctx, br_lck, &lock);
1313 /****************************************************************************
1314 Test if we could add a lock if we wanted to.
1315 Returns True if the region required is currently unlocked, False if locked.
1316 ****************************************************************************/
1318 bool brl_locktest(struct byte_range_lock *br_lck,
1319 uint64_t smblctx,
1320 struct server_id pid,
1321 br_off start,
1322 br_off size,
1323 enum brl_type lock_type,
1324 enum brl_flavour lock_flav)
1326 bool ret = True;
1327 unsigned int i;
1328 struct lock_struct lock;
1329 const struct lock_struct *locks = br_lck->lock_data;
1330 files_struct *fsp = br_lck->fsp;
1332 lock.context.smblctx = smblctx;
1333 lock.context.pid = pid;
1334 lock.context.tid = br_lck->fsp->conn->cnum;
1335 lock.start = start;
1336 lock.size = size;
1337 lock.fnum = fsp->fnum;
1338 lock.lock_type = lock_type;
1339 lock.lock_flav = lock_flav;
1341 /* Make sure existing locks don't conflict */
1342 for (i=0; i < br_lck->num_locks; i++) {
1344 * Our own locks don't conflict.
1346 if (brl_conflict_other(&locks[i], &lock)) {
1347 return False;
1352 * There is no lock held by an SMB daemon, check to
1353 * see if there is a POSIX lock from a UNIX or NFS process.
1354 * This only conflicts with Windows locks, not POSIX locks.
1357 if(lp_posix_locking(fsp->conn->params) && (lock_flav == WINDOWS_LOCK)) {
1358 ret = is_posix_locked(fsp, &start, &size, &lock_type, WINDOWS_LOCK);
1360 DEBUG(10,("brl_locktest: posix start=%.0f len=%.0f %s for %s file %s\n",
1361 (double)start, (double)size, ret ? "locked" : "unlocked",
1362 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1364 /* We need to return the inverse of is_posix_locked. */
1365 ret = !ret;
1368 /* no conflicts - we could have added it */
1369 return ret;
1372 /****************************************************************************
1373 Query for existing locks.
1374 ****************************************************************************/
1376 NTSTATUS brl_lockquery(struct byte_range_lock *br_lck,
1377 uint64_t *psmblctx,
1378 struct server_id pid,
1379 br_off *pstart,
1380 br_off *psize,
1381 enum brl_type *plock_type,
1382 enum brl_flavour lock_flav)
1384 unsigned int i;
1385 struct lock_struct lock;
1386 const struct lock_struct *locks = br_lck->lock_data;
1387 files_struct *fsp = br_lck->fsp;
1389 lock.context.smblctx = *psmblctx;
1390 lock.context.pid = pid;
1391 lock.context.tid = br_lck->fsp->conn->cnum;
1392 lock.start = *pstart;
1393 lock.size = *psize;
1394 lock.fnum = fsp->fnum;
1395 lock.lock_type = *plock_type;
1396 lock.lock_flav = lock_flav;
1398 /* Make sure existing locks don't conflict */
1399 for (i=0; i < br_lck->num_locks; i++) {
1400 const struct lock_struct *exlock = &locks[i];
1401 bool conflict = False;
1403 if (exlock->lock_flav == WINDOWS_LOCK) {
1404 conflict = brl_conflict(exlock, &lock);
1405 } else {
1406 conflict = brl_conflict_posix(exlock, &lock);
1409 if (conflict) {
1410 *psmblctx = exlock->context.smblctx;
1411 *pstart = exlock->start;
1412 *psize = exlock->size;
1413 *plock_type = exlock->lock_type;
1414 return NT_STATUS_LOCK_NOT_GRANTED;
1419 * There is no lock held by an SMB daemon, check to
1420 * see if there is a POSIX lock from a UNIX or NFS process.
1423 if(lp_posix_locking(fsp->conn->params)) {
1424 bool ret = is_posix_locked(fsp, pstart, psize, plock_type, POSIX_LOCK);
1426 DEBUG(10,("brl_lockquery: posix start=%.0f len=%.0f %s for %s file %s\n",
1427 (double)*pstart, (double)*psize, ret ? "locked" : "unlocked",
1428 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1430 if (ret) {
1431 /* Hmmm. No clue what to set smblctx to - use -1. */
1432 *psmblctx = 0xFFFFFFFFFFFFFFFFLL;
1433 return NT_STATUS_LOCK_NOT_GRANTED;
1437 return NT_STATUS_OK;
1441 bool smb_vfs_call_brl_cancel_windows(struct vfs_handle_struct *handle,
1442 struct byte_range_lock *br_lck,
1443 struct lock_struct *plock)
1445 VFS_FIND(brl_cancel_windows);
1446 return handle->fns->brl_cancel_windows_fn(handle, br_lck, plock);
1449 /****************************************************************************
1450 Remove a particular pending lock.
1451 ****************************************************************************/
1452 bool brl_lock_cancel(struct byte_range_lock *br_lck,
1453 uint64_t smblctx,
1454 struct server_id pid,
1455 br_off start,
1456 br_off size,
1457 enum brl_flavour lock_flav)
1459 bool ret;
1460 struct lock_struct lock;
1462 lock.context.smblctx = smblctx;
1463 lock.context.pid = pid;
1464 lock.context.tid = br_lck->fsp->conn->cnum;
1465 lock.start = start;
1466 lock.size = size;
1467 lock.fnum = br_lck->fsp->fnum;
1468 lock.lock_flav = lock_flav;
1469 /* lock.lock_type doesn't matter */
1471 if (lock_flav == WINDOWS_LOCK) {
1472 ret = SMB_VFS_BRL_CANCEL_WINDOWS(br_lck->fsp->conn, br_lck,
1473 &lock);
1474 } else {
1475 ret = brl_lock_cancel_default(br_lck, &lock);
1478 return ret;
1481 bool brl_lock_cancel_default(struct byte_range_lock *br_lck,
1482 struct lock_struct *plock)
1484 unsigned int i;
1485 struct lock_struct *locks = br_lck->lock_data;
1487 SMB_ASSERT(plock);
1489 for (i = 0; i < br_lck->num_locks; i++) {
1490 struct lock_struct *lock = &locks[i];
1492 /* For pending locks we *always* care about the fnum. */
1493 if (brl_same_context(&lock->context, &plock->context) &&
1494 lock->fnum == plock->fnum &&
1495 IS_PENDING_LOCK(lock->lock_type) &&
1496 lock->lock_flav == plock->lock_flav &&
1497 lock->start == plock->start &&
1498 lock->size == plock->size) {
1499 break;
1503 if (i == br_lck->num_locks) {
1504 /* Didn't find it. */
1505 return False;
1508 brl_delete_lock_struct(locks, br_lck->num_locks, i);
1509 br_lck->num_locks -= 1;
1510 br_lck->modified = True;
1511 return True;
1514 /****************************************************************************
1515 Remove any locks associated with a open file.
1516 We return True if this process owns any other Windows locks on this
1517 fd and so we should not immediately close the fd.
1518 ****************************************************************************/
1520 void brl_close_fnum(struct messaging_context *msg_ctx,
1521 struct byte_range_lock *br_lck)
1523 files_struct *fsp = br_lck->fsp;
1524 uint32_t tid = fsp->conn->cnum;
1525 uint64_t fnum = fsp->fnum;
1526 unsigned int i;
1527 struct lock_struct *locks = br_lck->lock_data;
1528 struct server_id pid = messaging_server_id(fsp->conn->sconn->msg_ctx);
1529 struct lock_struct *locks_copy;
1530 unsigned int num_locks_copy;
1532 /* Copy the current lock array. */
1533 if (br_lck->num_locks) {
1534 locks_copy = (struct lock_struct *)talloc_memdup(br_lck, locks, br_lck->num_locks * sizeof(struct lock_struct));
1535 if (!locks_copy) {
1536 smb_panic("brl_close_fnum: talloc failed");
1538 } else {
1539 locks_copy = NULL;
1542 num_locks_copy = br_lck->num_locks;
1544 for (i=0; i < num_locks_copy; i++) {
1545 struct lock_struct *lock = &locks_copy[i];
1547 if (lock->context.tid == tid && serverid_equal(&lock->context.pid, &pid) &&
1548 (lock->fnum == fnum)) {
1549 brl_unlock(msg_ctx,
1550 br_lck,
1551 lock->context.smblctx,
1552 pid,
1553 lock->start,
1554 lock->size,
1555 lock->lock_flav);
1560 bool brl_mark_disconnected(struct files_struct *fsp)
1562 uint32_t tid = fsp->conn->cnum;
1563 uint64_t smblctx;
1564 uint64_t fnum = fsp->fnum;
1565 unsigned int i;
1566 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1567 struct byte_range_lock *br_lck = NULL;
1569 if (fsp->op == NULL) {
1570 return false;
1573 smblctx = fsp->op->global->open_persistent_id;
1575 if (!fsp->op->global->durable) {
1576 return false;
1579 if (fsp->current_lock_count == 0) {
1580 return true;
1583 br_lck = brl_get_locks(talloc_tos(), fsp);
1584 if (br_lck == NULL) {
1585 return false;
1588 for (i=0; i < br_lck->num_locks; i++) {
1589 struct lock_struct *lock = &br_lck->lock_data[i];
1592 * as this is a durable handle, we only expect locks
1593 * of the current file handle!
1596 if (lock->context.smblctx != smblctx) {
1597 TALLOC_FREE(br_lck);
1598 return false;
1601 if (lock->context.tid != tid) {
1602 TALLOC_FREE(br_lck);
1603 return false;
1606 if (!serverid_equal(&lock->context.pid, &self)) {
1607 TALLOC_FREE(br_lck);
1608 return false;
1611 if (lock->fnum != fnum) {
1612 TALLOC_FREE(br_lck);
1613 return false;
1616 server_id_set_disconnected(&lock->context.pid);
1617 lock->context.tid = TID_FIELD_INVALID;
1618 lock->fnum = FNUM_FIELD_INVALID;
1621 br_lck->modified = true;
1622 TALLOC_FREE(br_lck);
1623 return true;
1626 bool brl_reconnect_disconnected(struct files_struct *fsp)
1628 uint32_t tid = fsp->conn->cnum;
1629 uint64_t smblctx;
1630 uint64_t fnum = fsp->fnum;
1631 unsigned int i;
1632 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1633 struct byte_range_lock *br_lck = NULL;
1635 if (fsp->op == NULL) {
1636 return false;
1639 smblctx = fsp->op->global->open_persistent_id;
1641 if (!fsp->op->global->durable) {
1642 return false;
1646 * When reconnecting, we do not want to validate the brlock entries
1647 * and thereby remove our own (disconnected) entries but reactivate
1648 * them instead.
1650 fsp->lockdb_clean = true;
1652 br_lck = brl_get_locks(talloc_tos(), fsp);
1653 if (br_lck == NULL) {
1654 return false;
1657 if (br_lck->num_locks == 0) {
1658 TALLOC_FREE(br_lck);
1659 return true;
1662 for (i=0; i < br_lck->num_locks; i++) {
1663 struct lock_struct *lock = &br_lck->lock_data[i];
1666 * as this is a durable handle we only expect locks
1667 * of the current file handle!
1670 if (lock->context.smblctx != smblctx) {
1671 TALLOC_FREE(br_lck);
1672 return false;
1675 if (lock->context.tid != TID_FIELD_INVALID) {
1676 TALLOC_FREE(br_lck);
1677 return false;
1680 if (!server_id_is_disconnected(&lock->context.pid)) {
1681 TALLOC_FREE(br_lck);
1682 return false;
1685 if (lock->fnum != FNUM_FIELD_INVALID) {
1686 TALLOC_FREE(br_lck);
1687 return false;
1690 lock->context.pid = self;
1691 lock->context.tid = tid;
1692 lock->fnum = fnum;
1695 fsp->current_lock_count = br_lck->num_locks;
1696 br_lck->modified = true;
1697 TALLOC_FREE(br_lck);
1698 return true;
1701 /****************************************************************************
1702 Ensure this set of lock entries is valid.
1703 ****************************************************************************/
1704 static bool validate_lock_entries(unsigned int *pnum_entries, struct lock_struct **pplocks,
1705 bool keep_disconnected)
1707 unsigned int i;
1708 struct lock_struct *locks = *pplocks;
1709 unsigned int num_entries = *pnum_entries;
1710 TALLOC_CTX *frame;
1711 struct server_id *ids;
1712 bool *exists;
1714 if (num_entries == 0) {
1715 return true;
1718 frame = talloc_stackframe();
1720 ids = talloc_array(frame, struct server_id, num_entries);
1721 if (ids == NULL) {
1722 DEBUG(0, ("validate_lock_entries: "
1723 "talloc_array(struct server_id, %u) failed\n",
1724 num_entries));
1725 talloc_free(frame);
1726 return false;
1729 exists = talloc_array(frame, bool, num_entries);
1730 if (exists == NULL) {
1731 DEBUG(0, ("validate_lock_entries: "
1732 "talloc_array(bool, %u) failed\n",
1733 num_entries));
1734 talloc_free(frame);
1735 return false;
1738 for (i = 0; i < num_entries; i++) {
1739 ids[i] = locks[i].context.pid;
1742 if (!serverids_exist(ids, num_entries, exists)) {
1743 DEBUG(3, ("validate_lock_entries: serverids_exists failed\n"));
1744 talloc_free(frame);
1745 return false;
1748 i = 0;
1750 while (i < num_entries) {
1751 if (exists[i]) {
1752 i++;
1753 continue;
1756 if (keep_disconnected &&
1757 server_id_is_disconnected(&ids[i]))
1759 i++;
1760 continue;
1763 /* This process no longer exists */
1765 brl_delete_lock_struct(locks, num_entries, i);
1766 num_entries -= 1;
1768 TALLOC_FREE(frame);
1770 *pnum_entries = num_entries;
1772 return True;
1775 struct brl_forall_cb {
1776 void (*fn)(struct file_id id, struct server_id pid,
1777 enum brl_type lock_type,
1778 enum brl_flavour lock_flav,
1779 br_off start, br_off size,
1780 void *private_data);
1781 void *private_data;
1784 /****************************************************************************
1785 Traverse the whole database with this function, calling traverse_callback
1786 on each lock.
1787 ****************************************************************************/
1789 static int brl_traverse_fn(struct db_record *rec, void *state)
1791 struct brl_forall_cb *cb = (struct brl_forall_cb *)state;
1792 struct lock_struct *locks;
1793 struct file_id *key;
1794 unsigned int i;
1795 unsigned int num_locks = 0;
1796 unsigned int orig_num_locks = 0;
1797 TDB_DATA dbkey;
1798 TDB_DATA value;
1800 dbkey = dbwrap_record_get_key(rec);
1801 value = dbwrap_record_get_value(rec);
1803 /* In a traverse function we must make a copy of
1804 dbuf before modifying it. */
1806 locks = (struct lock_struct *)talloc_memdup(
1807 talloc_tos(), value.dptr, value.dsize);
1808 if (!locks) {
1809 return -1; /* Terminate traversal. */
1812 key = (struct file_id *)dbkey.dptr;
1813 orig_num_locks = num_locks = value.dsize/sizeof(*locks);
1815 /* Ensure the lock db is clean of entries from invalid processes. */
1817 if (!validate_lock_entries(&num_locks, &locks, true)) {
1818 TALLOC_FREE(locks);
1819 return -1; /* Terminate traversal */
1822 if (orig_num_locks != num_locks) {
1823 if (num_locks) {
1824 TDB_DATA data;
1825 data.dptr = (uint8_t *)locks;
1826 data.dsize = num_locks*sizeof(struct lock_struct);
1827 dbwrap_record_store(rec, data, TDB_REPLACE);
1828 } else {
1829 dbwrap_record_delete(rec);
1833 if (cb->fn) {
1834 for ( i=0; i<num_locks; i++) {
1835 cb->fn(*key,
1836 locks[i].context.pid,
1837 locks[i].lock_type,
1838 locks[i].lock_flav,
1839 locks[i].start,
1840 locks[i].size,
1841 cb->private_data);
1845 TALLOC_FREE(locks);
1846 return 0;
1849 /*******************************************************************
1850 Call the specified function on each lock in the database.
1851 ********************************************************************/
1853 int brl_forall(void (*fn)(struct file_id id, struct server_id pid,
1854 enum brl_type lock_type,
1855 enum brl_flavour lock_flav,
1856 br_off start, br_off size,
1857 void *private_data),
1858 void *private_data)
1860 struct brl_forall_cb cb;
1861 NTSTATUS status;
1862 int count = 0;
1864 if (!brlock_db) {
1865 return 0;
1867 cb.fn = fn;
1868 cb.private_data = private_data;
1869 status = dbwrap_traverse(brlock_db, brl_traverse_fn, &cb, &count);
1871 if (!NT_STATUS_IS_OK(status)) {
1872 return -1;
1873 } else {
1874 return count;
1878 /*******************************************************************
1879 Store a potentially modified set of byte range lock data back into
1880 the database.
1881 Unlock the record.
1882 ********************************************************************/
1884 static void byte_range_lock_flush(struct byte_range_lock *br_lck)
1886 size_t data_len;
1887 if (!br_lck->modified) {
1888 DEBUG(10, ("br_lck not modified\n"));
1889 goto done;
1892 data_len = br_lck->num_locks * sizeof(struct lock_struct);
1894 if (br_lck->have_read_oplocks) {
1895 data_len += 1;
1898 DEBUG(10, ("data_len=%d\n", (int)data_len));
1900 if (data_len == 0) {
1901 /* No locks - delete this entry. */
1902 NTSTATUS status = dbwrap_record_delete(br_lck->record);
1903 if (!NT_STATUS_IS_OK(status)) {
1904 DEBUG(0, ("delete_rec returned %s\n",
1905 nt_errstr(status)));
1906 smb_panic("Could not delete byte range lock entry");
1908 } else {
1909 TDB_DATA data;
1910 NTSTATUS status;
1912 data.dsize = data_len;
1913 data.dptr = talloc_array(talloc_tos(), uint8_t, data_len);
1914 SMB_ASSERT(data.dptr != NULL);
1916 memcpy(data.dptr, br_lck->lock_data,
1917 br_lck->num_locks * sizeof(struct lock_struct));
1919 if (br_lck->have_read_oplocks) {
1920 data.dptr[data_len-1] = 1;
1923 status = dbwrap_record_store(br_lck->record, data, TDB_REPLACE);
1924 TALLOC_FREE(data.dptr);
1925 if (!NT_STATUS_IS_OK(status)) {
1926 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
1927 smb_panic("Could not store byte range mode entry");
1931 DEBUG(10, ("seqnum=%d\n", dbwrap_get_seqnum(brlock_db)));
1933 done:
1934 br_lck->modified = false;
1935 TALLOC_FREE(br_lck->record);
1938 static int byte_range_lock_destructor(struct byte_range_lock *br_lck)
1940 byte_range_lock_flush(br_lck);
1941 return 0;
1944 /*******************************************************************
1945 Fetch a set of byte range lock data from the database.
1946 Leave the record locked.
1947 TALLOC_FREE(brl) will release the lock in the destructor.
1948 ********************************************************************/
1950 struct byte_range_lock *brl_get_locks(TALLOC_CTX *mem_ctx, files_struct *fsp)
1952 TDB_DATA key, data;
1953 struct byte_range_lock *br_lck = talloc(mem_ctx, struct byte_range_lock);
1955 if (br_lck == NULL) {
1956 return NULL;
1959 br_lck->fsp = fsp;
1960 br_lck->num_locks = 0;
1961 br_lck->have_read_oplocks = false;
1962 br_lck->modified = False;
1964 key.dptr = (uint8 *)&fsp->file_id;
1965 key.dsize = sizeof(struct file_id);
1967 br_lck->record = dbwrap_fetch_locked(brlock_db, br_lck, key);
1969 if (br_lck->record == NULL) {
1970 DEBUG(3, ("Could not lock byte range lock entry\n"));
1971 TALLOC_FREE(br_lck);
1972 return NULL;
1975 data = dbwrap_record_get_value(br_lck->record);
1977 br_lck->lock_data = NULL;
1979 talloc_set_destructor(br_lck, byte_range_lock_destructor);
1981 br_lck->num_locks = data.dsize / sizeof(struct lock_struct);
1983 if (br_lck->num_locks != 0) {
1984 br_lck->lock_data = talloc_array(
1985 br_lck, struct lock_struct, br_lck->num_locks);
1986 if (br_lck->lock_data == NULL) {
1987 DEBUG(0, ("malloc failed\n"));
1988 TALLOC_FREE(br_lck);
1989 return NULL;
1992 memcpy(br_lck->lock_data, data.dptr,
1993 talloc_get_size(br_lck->lock_data));
1996 DEBUG(10, ("data.dsize=%d\n", (int)data.dsize));
1998 if ((data.dsize % sizeof(struct lock_struct)) == 1) {
1999 br_lck->have_read_oplocks = (data.dptr[data.dsize-1] == 1);
2002 if (!fsp->lockdb_clean) {
2003 int orig_num_locks = br_lck->num_locks;
2006 * This is the first time we access the byte range lock
2007 * record with this fsp. Go through and ensure all entries
2008 * are valid - remove any that don't.
2009 * This makes the lockdb self cleaning at low cost.
2011 * Note: Disconnected entries belong to disconnected
2012 * durable handles. So at this point, we have a new
2013 * handle on the file and the disconnected durable has
2014 * already been closed (we are not a durable reconnect).
2015 * So we need to clean the disconnected brl entry.
2018 if (!validate_lock_entries(&br_lck->num_locks,
2019 &br_lck->lock_data, false)) {
2020 TALLOC_FREE(br_lck);
2021 return NULL;
2024 /* Ensure invalid locks are cleaned up in the destructor. */
2025 if (orig_num_locks != br_lck->num_locks) {
2026 br_lck->modified = True;
2029 /* Mark the lockdb as "clean" as seen from this open file. */
2030 fsp->lockdb_clean = True;
2033 if (DEBUGLEVEL >= 10) {
2034 unsigned int i;
2035 struct lock_struct *locks = br_lck->lock_data;
2036 DEBUG(10,("brl_get_locks_internal: %u current locks on file_id %s\n",
2037 br_lck->num_locks,
2038 file_id_string_tos(&fsp->file_id)));
2039 for( i = 0; i < br_lck->num_locks; i++) {
2040 print_lock_struct(i, &locks[i]);
2044 return br_lck;
2047 struct brl_get_locks_readonly_state {
2048 TALLOC_CTX *mem_ctx;
2049 struct byte_range_lock **br_lock;
2052 static void brl_get_locks_readonly_parser(TDB_DATA key, TDB_DATA data,
2053 void *private_data)
2055 struct brl_get_locks_readonly_state *state =
2056 (struct brl_get_locks_readonly_state *)private_data;
2057 struct byte_range_lock *br_lock;
2059 br_lock = talloc_pooled_object(
2060 state->mem_ctx, struct byte_range_lock, 1, data.dsize);
2061 if (br_lock == NULL) {
2062 *state->br_lock = NULL;
2063 return;
2065 br_lock->lock_data = (struct lock_struct *)talloc_memdup(
2066 br_lock, data.dptr, data.dsize);
2067 br_lock->num_locks = data.dsize / sizeof(struct lock_struct);
2069 if ((data.dsize % sizeof(struct lock_struct)) == 1) {
2070 br_lock->have_read_oplocks = (data.dptr[data.dsize-1] == 1);
2071 } else {
2072 br_lock->have_read_oplocks = false;
2075 DEBUG(10, ("Got %d bytes, have_read_oplocks: %s\n", (int)data.dsize,
2076 br_lock->have_read_oplocks ? "true" : "false"));
2078 *state->br_lock = br_lock;
2081 struct byte_range_lock *brl_get_locks_readonly(files_struct *fsp)
2083 struct byte_range_lock *br_lock = NULL;
2084 struct byte_range_lock *rw = NULL;
2086 DEBUG(10, ("seqnum=%d, fsp->brlock_seqnum=%d\n",
2087 dbwrap_get_seqnum(brlock_db), fsp->brlock_seqnum));
2089 if ((fsp->brlock_rec != NULL)
2090 && (dbwrap_get_seqnum(brlock_db) == fsp->brlock_seqnum)) {
2092 * We have cached the brlock_rec and the database did not
2093 * change.
2095 return fsp->brlock_rec;
2098 if (!fsp->lockdb_clean) {
2100 * Fetch the record in R/W mode to give validate_lock_entries
2101 * a chance to kick in once.
2103 rw = brl_get_locks(talloc_tos(), fsp);
2104 if (rw == NULL) {
2105 return NULL;
2107 fsp->lockdb_clean = true;
2110 if (rw != NULL) {
2111 size_t lock_data_size;
2114 * Make a copy of the already retrieved and sanitized rw record
2116 lock_data_size = rw->num_locks * sizeof(struct lock_struct);
2117 br_lock = talloc_pooled_object(
2118 fsp, struct byte_range_lock, 1, lock_data_size);
2119 if (br_lock == NULL) {
2120 goto fail;
2122 br_lock->have_read_oplocks = rw->have_read_oplocks;
2123 br_lock->num_locks = rw->num_locks;
2124 br_lock->lock_data = (struct lock_struct *)talloc_memdup(
2125 br_lock, rw->lock_data, lock_data_size);
2126 } else {
2127 struct brl_get_locks_readonly_state state;
2128 NTSTATUS status;
2131 * Parse the record fresh from the database
2134 state.mem_ctx = fsp;
2135 state.br_lock = &br_lock;
2137 status = dbwrap_parse_record(
2138 brlock_db,
2139 make_tdb_data((uint8_t *)&fsp->file_id,
2140 sizeof(fsp->file_id)),
2141 brl_get_locks_readonly_parser, &state);
2143 if (NT_STATUS_EQUAL(status,NT_STATUS_NOT_FOUND)) {
2145 * No locks on this file. Return an empty br_lock.
2147 br_lock = talloc(fsp, struct byte_range_lock);
2148 if (br_lock == NULL) {
2149 goto fail;
2152 br_lock->have_read_oplocks = false;
2153 br_lock->num_locks = 0;
2154 br_lock->lock_data = NULL;
2156 } else if (!NT_STATUS_IS_OK(status)) {
2157 DEBUG(3, ("Could not parse byte range lock record: "
2158 "%s\n", nt_errstr(status)));
2159 goto fail;
2161 if (br_lock == NULL) {
2162 goto fail;
2166 br_lock->fsp = fsp;
2167 br_lock->modified = false;
2168 br_lock->record = NULL;
2170 if (lp_clustering()) {
2172 * In the cluster case we can't cache the brlock struct
2173 * because dbwrap_get_seqnum does not work reliably over
2174 * ctdb. Thus we have to throw away the brlock struct soon.
2176 talloc_steal(talloc_tos(), br_lock);
2177 } else {
2179 * Cache the brlock struct, invalidated when the dbwrap_seqnum
2180 * changes. See beginning of this routine.
2182 TALLOC_FREE(fsp->brlock_rec);
2183 fsp->brlock_rec = br_lock;
2184 fsp->brlock_seqnum = dbwrap_get_seqnum(brlock_db);
2187 fail:
2188 TALLOC_FREE(rw);
2189 return br_lock;
2192 struct brl_revalidate_state {
2193 ssize_t array_size;
2194 uint32 num_pids;
2195 struct server_id *pids;
2199 * Collect PIDs of all processes with pending entries
2202 static void brl_revalidate_collect(struct file_id id, struct server_id pid,
2203 enum brl_type lock_type,
2204 enum brl_flavour lock_flav,
2205 br_off start, br_off size,
2206 void *private_data)
2208 struct brl_revalidate_state *state =
2209 (struct brl_revalidate_state *)private_data;
2211 if (!IS_PENDING_LOCK(lock_type)) {
2212 return;
2215 add_to_large_array(state, sizeof(pid), (void *)&pid,
2216 &state->pids, &state->num_pids,
2217 &state->array_size);
2221 * qsort callback to sort the processes
2224 static int compare_procids(const void *p1, const void *p2)
2226 const struct server_id *i1 = (const struct server_id *)p1;
2227 const struct server_id *i2 = (const struct server_id *)p2;
2229 if (i1->pid < i2->pid) return -1;
2230 if (i1->pid > i2->pid) return 1;
2231 return 0;
2235 * Send a MSG_SMB_UNLOCK message to all processes with pending byte range
2236 * locks so that they retry. Mainly used in the cluster code after a node has
2237 * died.
2239 * Done in two steps to avoid double-sends: First we collect all entries in an
2240 * array, then qsort that array and only send to non-dupes.
2243 void brl_revalidate(struct messaging_context *msg_ctx,
2244 void *private_data,
2245 uint32_t msg_type,
2246 struct server_id server_id,
2247 DATA_BLOB *data)
2249 struct brl_revalidate_state *state;
2250 uint32 i;
2251 struct server_id last_pid;
2253 if (!(state = talloc_zero(NULL, struct brl_revalidate_state))) {
2254 DEBUG(0, ("talloc failed\n"));
2255 return;
2258 brl_forall(brl_revalidate_collect, state);
2260 if (state->array_size == -1) {
2261 DEBUG(0, ("talloc failed\n"));
2262 goto done;
2265 if (state->num_pids == 0) {
2266 goto done;
2269 TYPESAFE_QSORT(state->pids, state->num_pids, compare_procids);
2271 ZERO_STRUCT(last_pid);
2273 for (i=0; i<state->num_pids; i++) {
2274 if (serverid_equal(&last_pid, &state->pids[i])) {
2276 * We've seen that one already
2278 continue;
2281 messaging_send(msg_ctx, state->pids[i], MSG_SMB_UNLOCK,
2282 &data_blob_null);
2283 last_pid = state->pids[i];
2286 done:
2287 TALLOC_FREE(state);
2288 return;
2291 bool brl_cleanup_disconnected(struct file_id fid, uint64_t open_persistent_id)
2293 bool ret = false;
2294 TALLOC_CTX *frame = talloc_stackframe();
2295 TDB_DATA key, val;
2296 struct db_record *rec;
2297 struct lock_struct *lock;
2298 unsigned n, num;
2299 NTSTATUS status;
2301 key = make_tdb_data((void*)&fid, sizeof(fid));
2303 rec = dbwrap_fetch_locked(brlock_db, frame, key);
2304 if (rec == NULL) {
2305 DEBUG(5, ("brl_cleanup_disconnected: failed to fetch record "
2306 "for file %s\n", file_id_string(frame, &fid)));
2307 goto done;
2310 val = dbwrap_record_get_value(rec);
2311 lock = (struct lock_struct*)val.dptr;
2312 num = val.dsize / sizeof(struct lock_struct);
2313 if (lock == NULL) {
2314 DEBUG(10, ("brl_cleanup_disconnected: no byte range locks for "
2315 "file %s\n", file_id_string(frame, &fid)));
2316 ret = true;
2317 goto done;
2320 for (n=0; n<num; n++) {
2321 struct lock_context *ctx = &lock[n].context;
2323 if (!server_id_is_disconnected(&ctx->pid)) {
2324 DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2325 "%s used by server %s, do not cleanup\n",
2326 file_id_string(frame, &fid),
2327 server_id_str(frame, &ctx->pid)));
2328 goto done;
2331 if (ctx->smblctx != open_persistent_id) {
2332 DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2333 "%s expected smblctx %llu but found %llu"
2334 ", do not cleanup\n",
2335 file_id_string(frame, &fid),
2336 (unsigned long long)open_persistent_id,
2337 (unsigned long long)ctx->smblctx));
2338 goto done;
2342 status = dbwrap_record_delete(rec);
2343 if (!NT_STATUS_IS_OK(status)) {
2344 DEBUG(5, ("brl_cleanup_disconnected: failed to delete record "
2345 "for file %s from %s, open %llu: %s\n",
2346 file_id_string(frame, &fid), dbwrap_name(brlock_db),
2347 (unsigned long long)open_persistent_id,
2348 nt_errstr(status)));
2349 goto done;
2352 DEBUG(10, ("brl_cleanup_disconnected: "
2353 "file %s cleaned up %u entries from open %llu\n",
2354 file_id_string(frame, &fid), num,
2355 (unsigned long long)open_persistent_id));
2357 ret = true;
2358 done:
2359 talloc_free(frame);
2360 return ret;