kcc: Add corresponding methods for repsTo
[Samba.git] / source3 / locking / brlock.c
blob70096d627f02ccb308c1ad3c8ac344dab24a3be9
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 uint32_t num_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 struct server_id_buf tmp;
63 DEBUG(10,("[%u]: smblctx = %llu, tid = %u, pid = %s, ",
65 (unsigned long long)pls->context.smblctx,
66 (unsigned int)pls->context.tid,
67 server_id_str_buf(pls->context.pid, &tmp) ));
69 DEBUG(10, ("start = %ju, size = %ju, fnum = %ju, %s %s\n",
70 (uintmax_t)pls->start,
71 (uintmax_t)pls->size,
72 (uintmax_t)pls->fnum,
73 lock_type_name(pls->lock_type),
74 lock_flav_name(pls->lock_flav)));
77 unsigned int brl_num_locks(const struct byte_range_lock *brl)
79 return brl->num_locks;
82 struct files_struct *brl_fsp(struct byte_range_lock *brl)
84 return brl->fsp;
87 uint32_t brl_num_read_oplocks(const struct byte_range_lock *brl)
89 return brl->num_read_oplocks;
92 void brl_set_num_read_oplocks(struct byte_range_lock *brl,
93 uint32_t num_read_oplocks)
95 DEBUG(10, ("Setting num_read_oplocks to %"PRIu32"\n",
96 num_read_oplocks));
97 SMB_ASSERT(brl->record != NULL); /* otherwise we're readonly */
98 brl->num_read_oplocks = num_read_oplocks;
99 brl->modified = true;
102 /****************************************************************************
103 See if two locking contexts are equal.
104 ****************************************************************************/
106 static bool brl_same_context(const struct lock_context *ctx1,
107 const struct lock_context *ctx2)
109 return (serverid_equal(&ctx1->pid, &ctx2->pid) &&
110 (ctx1->smblctx == ctx2->smblctx) &&
111 (ctx1->tid == ctx2->tid));
114 /****************************************************************************
115 See if lck1 and lck2 overlap.
116 ****************************************************************************/
118 static bool brl_overlap(const struct lock_struct *lck1,
119 const struct lock_struct *lck2)
121 /* XXX Remove for Win7 compatibility. */
122 /* this extra check is not redundant - it copes with locks
123 that go beyond the end of 64 bit file space */
124 if (lck1->size != 0 &&
125 lck1->start == lck2->start &&
126 lck1->size == lck2->size) {
127 return True;
130 if (lck1->start >= (lck2->start+lck2->size) ||
131 lck2->start >= (lck1->start+lck1->size)) {
132 return False;
134 return True;
137 /****************************************************************************
138 See if lock2 can be added when lock1 is in place.
139 ****************************************************************************/
141 static bool brl_conflict(const struct lock_struct *lck1,
142 const struct lock_struct *lck2)
144 /* Ignore PENDING locks. */
145 if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
146 return False;
148 /* Read locks never conflict. */
149 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
150 return False;
153 /* A READ lock can stack on top of a WRITE lock if they have the same
154 * context & fnum. */
155 if (lck1->lock_type == WRITE_LOCK && lck2->lock_type == READ_LOCK &&
156 brl_same_context(&lck1->context, &lck2->context) &&
157 lck1->fnum == lck2->fnum) {
158 return False;
161 return brl_overlap(lck1, lck2);
164 /****************************************************************************
165 See if lock2 can be added when lock1 is in place - when both locks are POSIX
166 flavour. POSIX locks ignore fnum - they only care about dev/ino which we
167 know already match.
168 ****************************************************************************/
170 static bool brl_conflict_posix(const struct lock_struct *lck1,
171 const struct lock_struct *lck2)
173 #if defined(DEVELOPER)
174 SMB_ASSERT(lck1->lock_flav == POSIX_LOCK);
175 SMB_ASSERT(lck2->lock_flav == POSIX_LOCK);
176 #endif
178 /* Ignore PENDING locks. */
179 if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
180 return False;
182 /* Read locks never conflict. */
183 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
184 return False;
187 /* Locks on the same context don't conflict. Ignore fnum. */
188 if (brl_same_context(&lck1->context, &lck2->context)) {
189 return False;
192 /* One is read, the other write, or the context is different,
193 do they overlap ? */
194 return brl_overlap(lck1, lck2);
197 #if ZERO_ZERO
198 static bool brl_conflict1(const struct lock_struct *lck1,
199 const struct lock_struct *lck2)
201 if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
202 return False;
204 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
205 return False;
208 if (brl_same_context(&lck1->context, &lck2->context) &&
209 lck2->lock_type == READ_LOCK && lck1->fnum == lck2->fnum) {
210 return False;
213 if (lck2->start == 0 && lck2->size == 0 && lck1->size != 0) {
214 return True;
217 if (lck1->start >= (lck2->start + lck2->size) ||
218 lck2->start >= (lck1->start + lck1->size)) {
219 return False;
222 return True;
224 #endif
226 /****************************************************************************
227 Check to see if this lock conflicts, but ignore our own locks on the
228 same fnum only. This is the read/write lock check code path.
229 This is never used in the POSIX lock case.
230 ****************************************************************************/
232 static bool brl_conflict_other(const struct lock_struct *lock,
233 const struct lock_struct *rw_probe)
235 if (IS_PENDING_LOCK(lock->lock_type) ||
236 IS_PENDING_LOCK(rw_probe->lock_type)) {
237 return False;
240 if (lock->lock_type == READ_LOCK && rw_probe->lock_type == READ_LOCK) {
241 return False;
244 if (lock->lock_flav == POSIX_LOCK &&
245 rw_probe->lock_flav == POSIX_LOCK) {
247 * POSIX flavour locks never conflict here - this is only called
248 * in the read/write path.
250 return False;
253 if (!brl_overlap(lock, rw_probe)) {
255 * I/O can only conflict when overlapping a lock, thus let it
256 * pass
258 return false;
261 if (!brl_same_context(&lock->context, &rw_probe->context)) {
263 * Different process, conflict
265 return true;
268 if (lock->fnum != rw_probe->fnum) {
270 * Different file handle, conflict
272 return true;
275 if ((lock->lock_type == READ_LOCK) &&
276 (rw_probe->lock_type == WRITE_LOCK)) {
278 * Incoming WRITE locks conflict with existing READ locks even
279 * if the context is the same. JRA. See LOCKTEST7 in
280 * smbtorture.
282 return true;
286 * I/O request compatible with existing lock, let it pass without
287 * conflict
290 return false;
293 /****************************************************************************
294 Check if an unlock overlaps a pending lock.
295 ****************************************************************************/
297 static bool brl_pending_overlap(const struct lock_struct *lock, const struct lock_struct *pend_lock)
299 if ((lock->start <= pend_lock->start) && (lock->start + lock->size > pend_lock->start))
300 return True;
301 if ((lock->start >= pend_lock->start) && (lock->start < pend_lock->start + pend_lock->size))
302 return True;
303 return False;
306 /****************************************************************************
307 Amazingly enough, w2k3 "remembers" whether the last lock failure on a fnum
308 is the same as this one and changes its error code. I wonder if any
309 app depends on this ?
310 ****************************************************************************/
312 static NTSTATUS brl_lock_failed(files_struct *fsp,
313 const struct lock_struct *lock,
314 bool blocking_lock)
316 if (lock->start >= 0xEF000000 && (lock->start >> 63) == 0) {
317 /* amazing the little things you learn with a test
318 suite. Locks beyond this offset (as a 64 bit
319 number!) always generate the conflict error code,
320 unless the top bit is set */
321 if (!blocking_lock) {
322 fsp->last_lock_failure = *lock;
324 return NT_STATUS_FILE_LOCK_CONFLICT;
327 if (serverid_equal(&lock->context.pid, &fsp->last_lock_failure.context.pid) &&
328 lock->context.tid == fsp->last_lock_failure.context.tid &&
329 lock->fnum == fsp->last_lock_failure.fnum &&
330 lock->start == fsp->last_lock_failure.start) {
331 return NT_STATUS_FILE_LOCK_CONFLICT;
334 if (!blocking_lock) {
335 fsp->last_lock_failure = *lock;
337 return NT_STATUS_LOCK_NOT_GRANTED;
340 /****************************************************************************
341 Open up the brlock.tdb database.
342 ****************************************************************************/
344 void brl_init(bool read_only)
346 int tdb_flags;
347 char *db_path;
349 if (brlock_db) {
350 return;
353 tdb_flags = TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH;
355 if (!lp_clustering()) {
357 * We can't use the SEQNUM trick to cache brlock
358 * entries in the clustering case because ctdb seqnum
359 * propagation has a delay.
361 tdb_flags |= TDB_SEQNUM;
364 db_path = lock_path("brlock.tdb");
365 if (db_path == NULL) {
366 DEBUG(0, ("out of memory!\n"));
367 return;
370 brlock_db = db_open(NULL, db_path,
371 SMB_OPEN_DATABASE_TDB_HASH_SIZE, tdb_flags,
372 read_only?O_RDONLY:(O_RDWR|O_CREAT), 0644,
373 DBWRAP_LOCK_ORDER_2, DBWRAP_FLAG_NONE);
374 if (!brlock_db) {
375 DEBUG(0,("Failed to open byte range locking database %s\n",
376 db_path));
377 TALLOC_FREE(db_path);
378 return;
380 TALLOC_FREE(db_path);
383 /****************************************************************************
384 Close down the brlock.tdb database.
385 ****************************************************************************/
387 void brl_shutdown(void)
389 TALLOC_FREE(brlock_db);
392 #if ZERO_ZERO
393 /****************************************************************************
394 Compare two locks for sorting.
395 ****************************************************************************/
397 static int lock_compare(const struct lock_struct *lck1,
398 const struct lock_struct *lck2)
400 if (lck1->start != lck2->start) {
401 return (lck1->start - lck2->start);
403 if (lck2->size != lck1->size) {
404 return ((int)lck1->size - (int)lck2->size);
406 return 0;
408 #endif
410 /****************************************************************************
411 Lock a range of bytes - Windows lock semantics.
412 ****************************************************************************/
414 NTSTATUS brl_lock_windows_default(struct byte_range_lock *br_lck,
415 struct lock_struct *plock, bool blocking_lock)
417 unsigned int i;
418 files_struct *fsp = br_lck->fsp;
419 struct lock_struct *locks = br_lck->lock_data;
420 NTSTATUS status;
422 SMB_ASSERT(plock->lock_type != UNLOCK_LOCK);
424 if ((plock->start + plock->size - 1 < plock->start) &&
425 plock->size != 0) {
426 return NT_STATUS_INVALID_LOCK_RANGE;
429 for (i=0; i < br_lck->num_locks; i++) {
430 /* Do any Windows or POSIX locks conflict ? */
431 if (brl_conflict(&locks[i], plock)) {
432 if (!serverid_exists(&locks[i].context.pid)) {
433 locks[i].context.pid.pid = 0;
434 br_lck->modified = true;
435 continue;
437 /* Remember who blocked us. */
438 plock->context.smblctx = locks[i].context.smblctx;
439 return brl_lock_failed(fsp,plock,blocking_lock);
441 #if ZERO_ZERO
442 if (plock->start == 0 && plock->size == 0 &&
443 locks[i].size == 0) {
444 break;
446 #endif
449 if (!IS_PENDING_LOCK(plock->lock_type)) {
450 contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
453 /* We can get the Windows lock, now see if it needs to
454 be mapped into a lower level POSIX one, and if so can
455 we get it ? */
457 if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(fsp->conn->params)) {
458 int errno_ret;
459 if (!set_posix_lock_windows_flavour(fsp,
460 plock->start,
461 plock->size,
462 plock->lock_type,
463 &plock->context,
464 locks,
465 br_lck->num_locks,
466 &errno_ret)) {
468 /* We don't know who blocked us. */
469 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
471 if (errno_ret == EACCES || errno_ret == EAGAIN) {
472 status = NT_STATUS_FILE_LOCK_CONFLICT;
473 goto fail;
474 } else {
475 status = map_nt_error_from_unix(errno);
476 goto fail;
481 /* no conflicts - add it to the list of locks */
482 locks = talloc_realloc(br_lck, locks, struct lock_struct,
483 (br_lck->num_locks + 1));
484 if (!locks) {
485 status = NT_STATUS_NO_MEMORY;
486 goto fail;
489 memcpy(&locks[br_lck->num_locks], plock, sizeof(struct lock_struct));
490 br_lck->num_locks += 1;
491 br_lck->lock_data = locks;
492 br_lck->modified = True;
494 return NT_STATUS_OK;
495 fail:
496 if (!IS_PENDING_LOCK(plock->lock_type)) {
497 contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
499 return status;
502 /****************************************************************************
503 Cope with POSIX range splits and merges.
504 ****************************************************************************/
506 static unsigned int brlock_posix_split_merge(struct lock_struct *lck_arr, /* Output array. */
507 struct lock_struct *ex, /* existing lock. */
508 struct lock_struct *plock) /* proposed lock. */
510 bool lock_types_differ = (ex->lock_type != plock->lock_type);
512 /* We can't merge non-conflicting locks on different context - ignore fnum. */
514 if (!brl_same_context(&ex->context, &plock->context)) {
515 /* Just copy. */
516 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
517 return 1;
520 /* We now know we have the same context. */
522 /* Did we overlap ? */
524 /*********************************************
525 +---------+
526 | ex |
527 +---------+
528 +-------+
529 | plock |
530 +-------+
531 OR....
532 +---------+
533 | ex |
534 +---------+
535 **********************************************/
537 if ( (ex->start > (plock->start + plock->size)) ||
538 (plock->start > (ex->start + ex->size))) {
540 /* No overlap with this lock - copy existing. */
542 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
543 return 1;
546 /*********************************************
547 +---------------------------+
548 | ex |
549 +---------------------------+
550 +---------------------------+
551 | plock | -> replace with plock.
552 +---------------------------+
554 +---------------+
555 | ex |
556 +---------------+
557 +---------------------------+
558 | plock | -> replace with plock.
559 +---------------------------+
561 **********************************************/
563 if ( (ex->start >= plock->start) &&
564 (ex->start + ex->size <= plock->start + plock->size) ) {
566 /* Replace - discard existing lock. */
568 return 0;
571 /*********************************************
572 Adjacent after.
573 +-------+
574 | ex |
575 +-------+
576 +---------------+
577 | plock |
578 +---------------+
580 BECOMES....
581 +---------------+-------+
582 | plock | ex | - different lock types.
583 +---------------+-------+
584 OR.... (merge)
585 +-----------------------+
586 | plock | - same lock type.
587 +-----------------------+
588 **********************************************/
590 if (plock->start + plock->size == ex->start) {
592 /* If the lock types are the same, we merge, if different, we
593 add the remainder of the old lock. */
595 if (lock_types_differ) {
596 /* Add existing. */
597 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
598 return 1;
599 } else {
600 /* Merge - adjust incoming lock as we may have more
601 * merging to come. */
602 plock->size += ex->size;
603 return 0;
607 /*********************************************
608 Adjacent before.
609 +-------+
610 | ex |
611 +-------+
612 +---------------+
613 | plock |
614 +---------------+
615 BECOMES....
616 +-------+---------------+
617 | ex | plock | - different lock types
618 +-------+---------------+
620 OR.... (merge)
621 +-----------------------+
622 | plock | - same lock type.
623 +-----------------------+
625 **********************************************/
627 if (ex->start + ex->size == plock->start) {
629 /* If the lock types are the same, we merge, if different, we
630 add the existing lock. */
632 if (lock_types_differ) {
633 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
634 return 1;
635 } else {
636 /* Merge - adjust incoming lock as we may have more
637 * merging to come. */
638 plock->start = ex->start;
639 plock->size += ex->size;
640 return 0;
644 /*********************************************
645 Overlap after.
646 +-----------------------+
647 | ex |
648 +-----------------------+
649 +---------------+
650 | plock |
651 +---------------+
653 +----------------+
654 | ex |
655 +----------------+
656 +---------------+
657 | plock |
658 +---------------+
660 BECOMES....
661 +---------------+-------+
662 | plock | ex | - different lock types.
663 +---------------+-------+
664 OR.... (merge)
665 +-----------------------+
666 | plock | - same lock type.
667 +-----------------------+
668 **********************************************/
670 if ( (ex->start >= plock->start) &&
671 (ex->start <= plock->start + plock->size) &&
672 (ex->start + ex->size > plock->start + plock->size) ) {
674 /* If the lock types are the same, we merge, if different, we
675 add the remainder of the old lock. */
677 if (lock_types_differ) {
678 /* Add remaining existing. */
679 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
680 /* Adjust existing start and size. */
681 lck_arr[0].start = plock->start + plock->size;
682 lck_arr[0].size = (ex->start + ex->size) - (plock->start + plock->size);
683 return 1;
684 } else {
685 /* Merge - adjust incoming lock as we may have more
686 * merging to come. */
687 plock->size += (ex->start + ex->size) - (plock->start + plock->size);
688 return 0;
692 /*********************************************
693 Overlap before.
694 +-----------------------+
695 | ex |
696 +-----------------------+
697 +---------------+
698 | plock |
699 +---------------+
701 +-------------+
702 | ex |
703 +-------------+
704 +---------------+
705 | plock |
706 +---------------+
708 BECOMES....
709 +-------+---------------+
710 | ex | plock | - different lock types
711 +-------+---------------+
713 OR.... (merge)
714 +-----------------------+
715 | plock | - same lock type.
716 +-----------------------+
718 **********************************************/
720 if ( (ex->start < plock->start) &&
721 (ex->start + ex->size >= plock->start) &&
722 (ex->start + ex->size <= plock->start + plock->size) ) {
724 /* If the lock types are the same, we merge, if different, we
725 add the truncated old lock. */
727 if (lock_types_differ) {
728 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
729 /* Adjust existing size. */
730 lck_arr[0].size = plock->start - ex->start;
731 return 1;
732 } else {
733 /* Merge - adjust incoming lock as we may have more
734 * merging to come. MUST ADJUST plock SIZE FIRST ! */
735 plock->size += (plock->start - ex->start);
736 plock->start = ex->start;
737 return 0;
741 /*********************************************
742 Complete overlap.
743 +---------------------------+
744 | ex |
745 +---------------------------+
746 +---------+
747 | plock |
748 +---------+
749 BECOMES.....
750 +-------+---------+---------+
751 | ex | plock | ex | - different lock types.
752 +-------+---------+---------+
754 +---------------------------+
755 | plock | - same lock type.
756 +---------------------------+
757 **********************************************/
759 if ( (ex->start < plock->start) && (ex->start + ex->size > plock->start + plock->size) ) {
761 if (lock_types_differ) {
763 /* We have to split ex into two locks here. */
765 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
766 memcpy(&lck_arr[1], ex, sizeof(struct lock_struct));
768 /* Adjust first existing size. */
769 lck_arr[0].size = plock->start - ex->start;
771 /* Adjust second existing start and size. */
772 lck_arr[1].start = plock->start + plock->size;
773 lck_arr[1].size = (ex->start + ex->size) - (plock->start + plock->size);
774 return 2;
775 } else {
776 /* Just eat the existing locks, merge them into plock. */
777 plock->start = ex->start;
778 plock->size = ex->size;
779 return 0;
783 /* Never get here. */
784 smb_panic("brlock_posix_split_merge");
785 /* Notreached. */
787 /* Keep some compilers happy. */
788 return 0;
791 /****************************************************************************
792 Lock a range of bytes - POSIX lock semantics.
793 We must cope with range splits and merges.
794 ****************************************************************************/
796 static NTSTATUS brl_lock_posix(struct messaging_context *msg_ctx,
797 struct byte_range_lock *br_lck,
798 struct lock_struct *plock)
800 unsigned int i, count, posix_count;
801 struct lock_struct *locks = br_lck->lock_data;
802 struct lock_struct *tp;
803 bool signal_pending_read = False;
804 bool break_oplocks = false;
805 NTSTATUS status;
807 /* No zero-zero locks for POSIX. */
808 if (plock->start == 0 && plock->size == 0) {
809 return NT_STATUS_INVALID_PARAMETER;
812 /* Don't allow 64-bit lock wrap. */
813 if (plock->start + plock->size - 1 < plock->start) {
814 return NT_STATUS_INVALID_PARAMETER;
817 /* The worst case scenario here is we have to split an
818 existing POSIX lock range into two, and add our lock,
819 so we need at most 2 more entries. */
821 tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 2);
822 if (!tp) {
823 return NT_STATUS_NO_MEMORY;
826 count = posix_count = 0;
828 for (i=0; i < br_lck->num_locks; i++) {
829 struct lock_struct *curr_lock = &locks[i];
831 /* If we have a pending read lock, a lock downgrade should
832 trigger a lock re-evaluation. */
833 if (curr_lock->lock_type == PENDING_READ_LOCK &&
834 brl_pending_overlap(plock, curr_lock)) {
835 signal_pending_read = True;
838 if (curr_lock->lock_flav == WINDOWS_LOCK) {
839 /* Do any Windows flavour locks conflict ? */
840 if (brl_conflict(curr_lock, plock)) {
841 if (!serverid_exists(&curr_lock->context.pid)) {
842 curr_lock->context.pid.pid = 0;
843 br_lck->modified = true;
844 continue;
846 /* No games with error messages. */
847 TALLOC_FREE(tp);
848 /* Remember who blocked us. */
849 plock->context.smblctx = curr_lock->context.smblctx;
850 return NT_STATUS_FILE_LOCK_CONFLICT;
852 /* Just copy the Windows lock into the new array. */
853 memcpy(&tp[count], curr_lock, sizeof(struct lock_struct));
854 count++;
855 } else {
856 unsigned int tmp_count = 0;
858 /* POSIX conflict semantics are different. */
859 if (brl_conflict_posix(curr_lock, plock)) {
860 if (!serverid_exists(&curr_lock->context.pid)) {
861 curr_lock->context.pid.pid = 0;
862 br_lck->modified = true;
863 continue;
865 /* Can't block ourselves with POSIX locks. */
866 /* No games with error messages. */
867 TALLOC_FREE(tp);
868 /* Remember who blocked us. */
869 plock->context.smblctx = curr_lock->context.smblctx;
870 return NT_STATUS_FILE_LOCK_CONFLICT;
873 /* Work out overlaps. */
874 tmp_count += brlock_posix_split_merge(&tp[count], curr_lock, plock);
875 posix_count += tmp_count;
876 count += tmp_count;
881 * Break oplocks while we hold a brl. Since lock() and unlock() calls
882 * are not symetric with POSIX semantics, we cannot guarantee our
883 * contend_level2_oplocks_begin/end calls will be acquired and
884 * released one-for-one as with Windows semantics. Therefore we only
885 * call contend_level2_oplocks_begin if this is the first POSIX brl on
886 * the file.
888 break_oplocks = (!IS_PENDING_LOCK(plock->lock_type) &&
889 posix_count == 0);
890 if (break_oplocks) {
891 contend_level2_oplocks_begin(br_lck->fsp,
892 LEVEL2_CONTEND_POSIX_BRL);
895 /* Try and add the lock in order, sorted by lock start. */
896 for (i=0; i < count; i++) {
897 struct lock_struct *curr_lock = &tp[i];
899 if (curr_lock->start <= plock->start) {
900 continue;
904 if (i < count) {
905 memmove(&tp[i+1], &tp[i],
906 (count - i)*sizeof(struct lock_struct));
908 memcpy(&tp[i], plock, sizeof(struct lock_struct));
909 count++;
911 /* We can get the POSIX lock, now see if it needs to
912 be mapped into a lower level POSIX one, and if so can
913 we get it ? */
915 if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(br_lck->fsp->conn->params)) {
916 int errno_ret;
918 /* The lower layer just needs to attempt to
919 get the system POSIX lock. We've weeded out
920 any conflicts above. */
922 if (!set_posix_lock_posix_flavour(br_lck->fsp,
923 plock->start,
924 plock->size,
925 plock->lock_type,
926 &plock->context,
927 &errno_ret)) {
929 /* We don't know who blocked us. */
930 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
932 if (errno_ret == EACCES || errno_ret == EAGAIN) {
933 TALLOC_FREE(tp);
934 status = NT_STATUS_FILE_LOCK_CONFLICT;
935 goto fail;
936 } else {
937 TALLOC_FREE(tp);
938 status = map_nt_error_from_unix(errno);
939 goto fail;
944 /* If we didn't use all the allocated size,
945 * Realloc so we don't leak entries per lock call. */
946 if (count < br_lck->num_locks + 2) {
947 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
948 if (!tp) {
949 status = NT_STATUS_NO_MEMORY;
950 goto fail;
954 br_lck->num_locks = count;
955 TALLOC_FREE(br_lck->lock_data);
956 br_lck->lock_data = tp;
957 locks = tp;
958 br_lck->modified = True;
960 /* A successful downgrade from write to read lock can trigger a lock
961 re-evalutation where waiting readers can now proceed. */
963 if (signal_pending_read) {
964 /* Send unlock messages to any pending read waiters that overlap. */
965 for (i=0; i < br_lck->num_locks; i++) {
966 struct lock_struct *pend_lock = &locks[i];
968 /* Ignore non-pending locks. */
969 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
970 continue;
973 if (pend_lock->lock_type == PENDING_READ_LOCK &&
974 brl_pending_overlap(plock, pend_lock)) {
975 struct server_id_buf tmp;
977 DEBUG(10, ("brl_lock_posix: sending unlock "
978 "message to pid %s\n",
979 server_id_str_buf(pend_lock->context.pid,
980 &tmp)));
982 messaging_send(msg_ctx, pend_lock->context.pid,
983 MSG_SMB_UNLOCK, &data_blob_null);
988 return NT_STATUS_OK;
989 fail:
990 if (break_oplocks) {
991 contend_level2_oplocks_end(br_lck->fsp,
992 LEVEL2_CONTEND_POSIX_BRL);
994 return status;
997 NTSTATUS smb_vfs_call_brl_lock_windows(struct vfs_handle_struct *handle,
998 struct byte_range_lock *br_lck,
999 struct lock_struct *plock,
1000 bool blocking_lock)
1002 VFS_FIND(brl_lock_windows);
1003 return handle->fns->brl_lock_windows_fn(handle, br_lck, plock,
1004 blocking_lock);
1007 /****************************************************************************
1008 Lock a range of bytes.
1009 ****************************************************************************/
1011 NTSTATUS brl_lock(struct messaging_context *msg_ctx,
1012 struct byte_range_lock *br_lck,
1013 uint64_t smblctx,
1014 struct server_id pid,
1015 br_off start,
1016 br_off size,
1017 enum brl_type lock_type,
1018 enum brl_flavour lock_flav,
1019 bool blocking_lock,
1020 uint64_t *psmblctx)
1022 NTSTATUS ret;
1023 struct lock_struct lock;
1025 ZERO_STRUCT(lock);
1027 #if !ZERO_ZERO
1028 if (start == 0 && size == 0) {
1029 DEBUG(0,("client sent 0/0 lock - please report this\n"));
1031 #endif
1033 lock = (struct lock_struct) {
1034 .context.smblctx = smblctx,
1035 .context.pid = pid,
1036 .context.tid = br_lck->fsp->conn->cnum,
1037 .start = start,
1038 .size = size,
1039 .fnum = br_lck->fsp->fnum,
1040 .lock_type = lock_type,
1041 .lock_flav = lock_flav
1044 if (lock_flav == WINDOWS_LOCK) {
1045 ret = SMB_VFS_BRL_LOCK_WINDOWS(br_lck->fsp->conn, br_lck,
1046 &lock, blocking_lock);
1047 } else {
1048 ret = brl_lock_posix(msg_ctx, br_lck, &lock);
1051 #if ZERO_ZERO
1052 /* sort the lock list */
1053 TYPESAFE_QSORT(br_lck->lock_data, (size_t)br_lck->num_locks, lock_compare);
1054 #endif
1056 /* If we're returning an error, return who blocked us. */
1057 if (!NT_STATUS_IS_OK(ret) && psmblctx) {
1058 *psmblctx = lock.context.smblctx;
1060 return ret;
1063 static void brl_delete_lock_struct(struct lock_struct *locks,
1064 unsigned num_locks,
1065 unsigned del_idx)
1067 if (del_idx >= num_locks) {
1068 return;
1070 memmove(&locks[del_idx], &locks[del_idx+1],
1071 sizeof(*locks) * (num_locks - del_idx - 1));
1074 /****************************************************************************
1075 Unlock a range of bytes - Windows semantics.
1076 ****************************************************************************/
1078 bool brl_unlock_windows_default(struct messaging_context *msg_ctx,
1079 struct byte_range_lock *br_lck,
1080 const struct lock_struct *plock)
1082 unsigned int i, j;
1083 struct lock_struct *locks = br_lck->lock_data;
1084 enum brl_type deleted_lock_type = READ_LOCK; /* shut the compiler up.... */
1086 SMB_ASSERT(plock->lock_type == UNLOCK_LOCK);
1088 #if ZERO_ZERO
1089 /* Delete write locks by preference... The lock list
1090 is sorted in the zero zero case. */
1092 for (i = 0; i < br_lck->num_locks; i++) {
1093 struct lock_struct *lock = &locks[i];
1095 if (lock->lock_type == WRITE_LOCK &&
1096 brl_same_context(&lock->context, &plock->context) &&
1097 lock->fnum == plock->fnum &&
1098 lock->lock_flav == WINDOWS_LOCK &&
1099 lock->start == plock->start &&
1100 lock->size == plock->size) {
1102 /* found it - delete it */
1103 deleted_lock_type = lock->lock_type;
1104 break;
1108 if (i != br_lck->num_locks) {
1109 /* We found it - don't search again. */
1110 goto unlock_continue;
1112 #endif
1114 for (i = 0; i < br_lck->num_locks; i++) {
1115 struct lock_struct *lock = &locks[i];
1117 if (IS_PENDING_LOCK(lock->lock_type)) {
1118 continue;
1121 /* Only remove our own locks that match in start, size, and flavour. */
1122 if (brl_same_context(&lock->context, &plock->context) &&
1123 lock->fnum == plock->fnum &&
1124 lock->lock_flav == WINDOWS_LOCK &&
1125 lock->start == plock->start &&
1126 lock->size == plock->size ) {
1127 deleted_lock_type = lock->lock_type;
1128 break;
1132 if (i == br_lck->num_locks) {
1133 /* we didn't find it */
1134 return False;
1137 #if ZERO_ZERO
1138 unlock_continue:
1139 #endif
1141 brl_delete_lock_struct(locks, br_lck->num_locks, i);
1142 br_lck->num_locks -= 1;
1143 br_lck->modified = True;
1145 /* Unlock the underlying POSIX regions. */
1146 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1147 release_posix_lock_windows_flavour(br_lck->fsp,
1148 plock->start,
1149 plock->size,
1150 deleted_lock_type,
1151 &plock->context,
1152 locks,
1153 br_lck->num_locks);
1156 /* Send unlock messages to any pending waiters that overlap. */
1157 for (j=0; j < br_lck->num_locks; j++) {
1158 struct lock_struct *pend_lock = &locks[j];
1160 /* Ignore non-pending locks. */
1161 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1162 continue;
1165 /* We could send specific lock info here... */
1166 if (brl_pending_overlap(plock, pend_lock)) {
1167 struct server_id_buf tmp;
1169 DEBUG(10, ("brl_unlock: sending unlock message to "
1170 "pid %s\n",
1171 server_id_str_buf(pend_lock->context.pid,
1172 &tmp)));
1174 messaging_send(msg_ctx, pend_lock->context.pid,
1175 MSG_SMB_UNLOCK, &data_blob_null);
1179 contend_level2_oplocks_end(br_lck->fsp, LEVEL2_CONTEND_WINDOWS_BRL);
1180 return True;
1183 /****************************************************************************
1184 Unlock a range of bytes - POSIX semantics.
1185 ****************************************************************************/
1187 static bool brl_unlock_posix(struct messaging_context *msg_ctx,
1188 struct byte_range_lock *br_lck,
1189 struct lock_struct *plock)
1191 unsigned int i, j, count;
1192 struct lock_struct *tp;
1193 struct lock_struct *locks = br_lck->lock_data;
1194 bool overlap_found = False;
1196 /* No zero-zero locks for POSIX. */
1197 if (plock->start == 0 && plock->size == 0) {
1198 return False;
1201 /* Don't allow 64-bit lock wrap. */
1202 if (plock->start + plock->size < plock->start ||
1203 plock->start + plock->size < plock->size) {
1204 DEBUG(10,("brl_unlock_posix: lock wrap\n"));
1205 return False;
1208 /* The worst case scenario here is we have to split an
1209 existing POSIX lock range into two, so we need at most
1210 1 more entry. */
1212 tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 1);
1213 if (!tp) {
1214 DEBUG(10,("brl_unlock_posix: malloc fail\n"));
1215 return False;
1218 count = 0;
1219 for (i = 0; i < br_lck->num_locks; i++) {
1220 struct lock_struct *lock = &locks[i];
1221 unsigned int tmp_count;
1223 /* Only remove our own locks - ignore fnum. */
1224 if (IS_PENDING_LOCK(lock->lock_type) ||
1225 !brl_same_context(&lock->context, &plock->context)) {
1226 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1227 count++;
1228 continue;
1231 if (lock->lock_flav == WINDOWS_LOCK) {
1232 /* Do any Windows flavour locks conflict ? */
1233 if (brl_conflict(lock, plock)) {
1234 TALLOC_FREE(tp);
1235 return false;
1237 /* Just copy the Windows lock into the new array. */
1238 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1239 count++;
1240 continue;
1243 /* Work out overlaps. */
1244 tmp_count = brlock_posix_split_merge(&tp[count], lock, plock);
1246 if (tmp_count == 0) {
1247 /* plock overlapped the existing lock completely,
1248 or replaced it. Don't copy the existing lock. */
1249 overlap_found = true;
1250 } else if (tmp_count == 1) {
1251 /* Either no overlap, (simple copy of existing lock) or
1252 * an overlap of an existing lock. */
1253 /* If the lock changed size, we had an overlap. */
1254 if (tp[count].size != lock->size) {
1255 overlap_found = true;
1257 count += tmp_count;
1258 } else if (tmp_count == 2) {
1259 /* We split a lock range in two. */
1260 overlap_found = true;
1261 count += tmp_count;
1263 /* Optimisation... */
1264 /* We know we're finished here as we can't overlap any
1265 more POSIX locks. Copy the rest of the lock array. */
1267 if (i < br_lck->num_locks - 1) {
1268 memcpy(&tp[count], &locks[i+1],
1269 sizeof(*locks)*((br_lck->num_locks-1) - i));
1270 count += ((br_lck->num_locks-1) - i);
1272 break;
1277 if (!overlap_found) {
1278 /* Just ignore - no change. */
1279 TALLOC_FREE(tp);
1280 DEBUG(10,("brl_unlock_posix: No overlap - unlocked.\n"));
1281 return True;
1284 /* Unlock any POSIX regions. */
1285 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1286 release_posix_lock_posix_flavour(br_lck->fsp,
1287 plock->start,
1288 plock->size,
1289 &plock->context,
1291 count);
1294 /* Realloc so we don't leak entries per unlock call. */
1295 if (count) {
1296 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
1297 if (!tp) {
1298 DEBUG(10,("brl_unlock_posix: realloc fail\n"));
1299 return False;
1301 } else {
1302 /* We deleted the last lock. */
1303 TALLOC_FREE(tp);
1304 tp = NULL;
1307 contend_level2_oplocks_end(br_lck->fsp,
1308 LEVEL2_CONTEND_POSIX_BRL);
1310 br_lck->num_locks = count;
1311 TALLOC_FREE(br_lck->lock_data);
1312 locks = tp;
1313 br_lck->lock_data = tp;
1314 br_lck->modified = True;
1316 /* Send unlock messages to any pending waiters that overlap. */
1318 for (j=0; j < br_lck->num_locks; j++) {
1319 struct lock_struct *pend_lock = &locks[j];
1321 /* Ignore non-pending locks. */
1322 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1323 continue;
1326 /* We could send specific lock info here... */
1327 if (brl_pending_overlap(plock, pend_lock)) {
1328 struct server_id_buf tmp;
1330 DEBUG(10, ("brl_unlock: sending unlock message to "
1331 "pid %s\n",
1332 server_id_str_buf(pend_lock->context.pid,
1333 &tmp)));
1335 messaging_send(msg_ctx, pend_lock->context.pid,
1336 MSG_SMB_UNLOCK, &data_blob_null);
1340 return True;
1343 bool smb_vfs_call_brl_unlock_windows(struct vfs_handle_struct *handle,
1344 struct messaging_context *msg_ctx,
1345 struct byte_range_lock *br_lck,
1346 const struct lock_struct *plock)
1348 VFS_FIND(brl_unlock_windows);
1349 return handle->fns->brl_unlock_windows_fn(handle, msg_ctx, br_lck,
1350 plock);
1353 /****************************************************************************
1354 Unlock a range of bytes.
1355 ****************************************************************************/
1357 bool brl_unlock(struct messaging_context *msg_ctx,
1358 struct byte_range_lock *br_lck,
1359 uint64_t smblctx,
1360 struct server_id pid,
1361 br_off start,
1362 br_off size,
1363 enum brl_flavour lock_flav)
1365 struct lock_struct lock;
1367 lock.context.smblctx = smblctx;
1368 lock.context.pid = pid;
1369 lock.context.tid = br_lck->fsp->conn->cnum;
1370 lock.start = start;
1371 lock.size = size;
1372 lock.fnum = br_lck->fsp->fnum;
1373 lock.lock_type = UNLOCK_LOCK;
1374 lock.lock_flav = lock_flav;
1376 if (lock_flav == WINDOWS_LOCK) {
1377 return SMB_VFS_BRL_UNLOCK_WINDOWS(br_lck->fsp->conn, msg_ctx,
1378 br_lck, &lock);
1379 } else {
1380 return brl_unlock_posix(msg_ctx, br_lck, &lock);
1384 /****************************************************************************
1385 Test if we could add a lock if we wanted to.
1386 Returns True if the region required is currently unlocked, False if locked.
1387 ****************************************************************************/
1389 bool brl_locktest(struct byte_range_lock *br_lck,
1390 const struct lock_struct *rw_probe)
1392 bool ret = True;
1393 unsigned int i;
1394 struct lock_struct *locks = br_lck->lock_data;
1395 files_struct *fsp = br_lck->fsp;
1397 /* Make sure existing locks don't conflict */
1398 for (i=0; i < br_lck->num_locks; i++) {
1400 * Our own locks don't conflict.
1402 if (brl_conflict_other(&locks[i], rw_probe)) {
1403 if (br_lck->record == NULL) {
1404 /* readonly */
1405 return false;
1408 if (!serverid_exists(&locks[i].context.pid)) {
1409 locks[i].context.pid.pid = 0;
1410 br_lck->modified = true;
1411 continue;
1414 return False;
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.
1421 * This only conflicts with Windows locks, not POSIX locks.
1424 if(lp_posix_locking(fsp->conn->params) &&
1425 (rw_probe->lock_flav == WINDOWS_LOCK)) {
1427 * Make copies -- is_posix_locked might modify the values
1430 br_off start = rw_probe->start;
1431 br_off size = rw_probe->size;
1432 enum brl_type lock_type = rw_probe->lock_type;
1434 ret = is_posix_locked(fsp, &start, &size, &lock_type, WINDOWS_LOCK);
1436 DEBUG(10, ("brl_locktest: posix start=%ju len=%ju %s for %s "
1437 "file %s\n", (uintmax_t)start, (uintmax_t)size,
1438 ret ? "locked" : "unlocked",
1439 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1441 /* We need to return the inverse of is_posix_locked. */
1442 ret = !ret;
1445 /* no conflicts - we could have added it */
1446 return ret;
1449 /****************************************************************************
1450 Query for existing locks.
1451 ****************************************************************************/
1453 NTSTATUS brl_lockquery(struct byte_range_lock *br_lck,
1454 uint64_t *psmblctx,
1455 struct server_id pid,
1456 br_off *pstart,
1457 br_off *psize,
1458 enum brl_type *plock_type,
1459 enum brl_flavour lock_flav)
1461 unsigned int i;
1462 struct lock_struct lock;
1463 const struct lock_struct *locks = br_lck->lock_data;
1464 files_struct *fsp = br_lck->fsp;
1466 lock.context.smblctx = *psmblctx;
1467 lock.context.pid = pid;
1468 lock.context.tid = br_lck->fsp->conn->cnum;
1469 lock.start = *pstart;
1470 lock.size = *psize;
1471 lock.fnum = fsp->fnum;
1472 lock.lock_type = *plock_type;
1473 lock.lock_flav = lock_flav;
1475 /* Make sure existing locks don't conflict */
1476 for (i=0; i < br_lck->num_locks; i++) {
1477 const struct lock_struct *exlock = &locks[i];
1478 bool conflict = False;
1480 if (exlock->lock_flav == WINDOWS_LOCK) {
1481 conflict = brl_conflict(exlock, &lock);
1482 } else {
1483 conflict = brl_conflict_posix(exlock, &lock);
1486 if (conflict) {
1487 *psmblctx = exlock->context.smblctx;
1488 *pstart = exlock->start;
1489 *psize = exlock->size;
1490 *plock_type = exlock->lock_type;
1491 return NT_STATUS_LOCK_NOT_GRANTED;
1496 * There is no lock held by an SMB daemon, check to
1497 * see if there is a POSIX lock from a UNIX or NFS process.
1500 if(lp_posix_locking(fsp->conn->params)) {
1501 bool ret = is_posix_locked(fsp, pstart, psize, plock_type, POSIX_LOCK);
1503 DEBUG(10, ("brl_lockquery: posix start=%ju len=%ju %s for %s "
1504 "file %s\n", (uintmax_t)*pstart,
1505 (uintmax_t)*psize, ret ? "locked" : "unlocked",
1506 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1508 if (ret) {
1509 /* Hmmm. No clue what to set smblctx to - use -1. */
1510 *psmblctx = 0xFFFFFFFFFFFFFFFFLL;
1511 return NT_STATUS_LOCK_NOT_GRANTED;
1515 return NT_STATUS_OK;
1519 bool smb_vfs_call_brl_cancel_windows(struct vfs_handle_struct *handle,
1520 struct byte_range_lock *br_lck,
1521 struct lock_struct *plock)
1523 VFS_FIND(brl_cancel_windows);
1524 return handle->fns->brl_cancel_windows_fn(handle, br_lck, plock);
1527 /****************************************************************************
1528 Remove a particular pending lock.
1529 ****************************************************************************/
1530 bool brl_lock_cancel(struct byte_range_lock *br_lck,
1531 uint64_t smblctx,
1532 struct server_id pid,
1533 br_off start,
1534 br_off size,
1535 enum brl_flavour lock_flav)
1537 bool ret;
1538 struct lock_struct lock;
1540 lock.context.smblctx = smblctx;
1541 lock.context.pid = pid;
1542 lock.context.tid = br_lck->fsp->conn->cnum;
1543 lock.start = start;
1544 lock.size = size;
1545 lock.fnum = br_lck->fsp->fnum;
1546 lock.lock_flav = lock_flav;
1547 /* lock.lock_type doesn't matter */
1549 if (lock_flav == WINDOWS_LOCK) {
1550 ret = SMB_VFS_BRL_CANCEL_WINDOWS(br_lck->fsp->conn, br_lck,
1551 &lock);
1552 } else {
1553 ret = brl_lock_cancel_default(br_lck, &lock);
1556 return ret;
1559 bool brl_lock_cancel_default(struct byte_range_lock *br_lck,
1560 struct lock_struct *plock)
1562 unsigned int i;
1563 struct lock_struct *locks = br_lck->lock_data;
1565 SMB_ASSERT(plock);
1567 for (i = 0; i < br_lck->num_locks; i++) {
1568 struct lock_struct *lock = &locks[i];
1570 /* For pending locks we *always* care about the fnum. */
1571 if (brl_same_context(&lock->context, &plock->context) &&
1572 lock->fnum == plock->fnum &&
1573 IS_PENDING_LOCK(lock->lock_type) &&
1574 lock->lock_flav == plock->lock_flav &&
1575 lock->start == plock->start &&
1576 lock->size == plock->size) {
1577 break;
1581 if (i == br_lck->num_locks) {
1582 /* Didn't find it. */
1583 return False;
1586 brl_delete_lock_struct(locks, br_lck->num_locks, i);
1587 br_lck->num_locks -= 1;
1588 br_lck->modified = True;
1589 return True;
1592 /****************************************************************************
1593 Remove any locks associated with a open file.
1594 We return True if this process owns any other Windows locks on this
1595 fd and so we should not immediately close the fd.
1596 ****************************************************************************/
1598 void brl_close_fnum(struct messaging_context *msg_ctx,
1599 struct byte_range_lock *br_lck)
1601 files_struct *fsp = br_lck->fsp;
1602 uint32_t tid = fsp->conn->cnum;
1603 uint64_t fnum = fsp->fnum;
1604 unsigned int i;
1605 struct lock_struct *locks = br_lck->lock_data;
1606 struct server_id pid = messaging_server_id(fsp->conn->sconn->msg_ctx);
1607 struct lock_struct *locks_copy;
1608 unsigned int num_locks_copy;
1610 /* Copy the current lock array. */
1611 if (br_lck->num_locks) {
1612 locks_copy = (struct lock_struct *)talloc_memdup(br_lck, locks, br_lck->num_locks * sizeof(struct lock_struct));
1613 if (!locks_copy) {
1614 smb_panic("brl_close_fnum: talloc failed");
1616 } else {
1617 locks_copy = NULL;
1620 num_locks_copy = br_lck->num_locks;
1622 for (i=0; i < num_locks_copy; i++) {
1623 struct lock_struct *lock = &locks_copy[i];
1625 if (lock->context.tid == tid && serverid_equal(&lock->context.pid, &pid) &&
1626 (lock->fnum == fnum)) {
1627 brl_unlock(msg_ctx,
1628 br_lck,
1629 lock->context.smblctx,
1630 pid,
1631 lock->start,
1632 lock->size,
1633 lock->lock_flav);
1638 bool brl_mark_disconnected(struct files_struct *fsp)
1640 uint32_t tid = fsp->conn->cnum;
1641 uint64_t smblctx;
1642 uint64_t fnum = fsp->fnum;
1643 unsigned int i;
1644 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1645 struct byte_range_lock *br_lck = NULL;
1647 if (fsp->op == NULL) {
1648 return false;
1651 smblctx = fsp->op->global->open_persistent_id;
1653 if (!fsp->op->global->durable) {
1654 return false;
1657 if (fsp->current_lock_count == 0) {
1658 return true;
1661 br_lck = brl_get_locks(talloc_tos(), fsp);
1662 if (br_lck == NULL) {
1663 return false;
1666 for (i=0; i < br_lck->num_locks; i++) {
1667 struct lock_struct *lock = &br_lck->lock_data[i];
1670 * as this is a durable handle, we only expect locks
1671 * of the current file handle!
1674 if (lock->context.smblctx != smblctx) {
1675 TALLOC_FREE(br_lck);
1676 return false;
1679 if (lock->context.tid != tid) {
1680 TALLOC_FREE(br_lck);
1681 return false;
1684 if (!serverid_equal(&lock->context.pid, &self)) {
1685 TALLOC_FREE(br_lck);
1686 return false;
1689 if (lock->fnum != fnum) {
1690 TALLOC_FREE(br_lck);
1691 return false;
1694 server_id_set_disconnected(&lock->context.pid);
1695 lock->context.tid = TID_FIELD_INVALID;
1696 lock->fnum = FNUM_FIELD_INVALID;
1699 br_lck->modified = true;
1700 TALLOC_FREE(br_lck);
1701 return true;
1704 bool brl_reconnect_disconnected(struct files_struct *fsp)
1706 uint32_t tid = fsp->conn->cnum;
1707 uint64_t smblctx;
1708 uint64_t fnum = fsp->fnum;
1709 unsigned int i;
1710 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1711 struct byte_range_lock *br_lck = NULL;
1713 if (fsp->op == NULL) {
1714 return false;
1717 smblctx = fsp->op->global->open_persistent_id;
1719 if (!fsp->op->global->durable) {
1720 return false;
1724 * When reconnecting, we do not want to validate the brlock entries
1725 * and thereby remove our own (disconnected) entries but reactivate
1726 * them instead.
1729 br_lck = brl_get_locks(talloc_tos(), fsp);
1730 if (br_lck == NULL) {
1731 return false;
1734 if (br_lck->num_locks == 0) {
1735 TALLOC_FREE(br_lck);
1736 return true;
1739 for (i=0; i < br_lck->num_locks; i++) {
1740 struct lock_struct *lock = &br_lck->lock_data[i];
1743 * as this is a durable handle we only expect locks
1744 * of the current file handle!
1747 if (lock->context.smblctx != smblctx) {
1748 TALLOC_FREE(br_lck);
1749 return false;
1752 if (lock->context.tid != TID_FIELD_INVALID) {
1753 TALLOC_FREE(br_lck);
1754 return false;
1757 if (!server_id_is_disconnected(&lock->context.pid)) {
1758 TALLOC_FREE(br_lck);
1759 return false;
1762 if (lock->fnum != FNUM_FIELD_INVALID) {
1763 TALLOC_FREE(br_lck);
1764 return false;
1767 lock->context.pid = self;
1768 lock->context.tid = tid;
1769 lock->fnum = fnum;
1772 fsp->current_lock_count = br_lck->num_locks;
1773 br_lck->modified = true;
1774 TALLOC_FREE(br_lck);
1775 return true;
1778 struct brl_forall_cb {
1779 void (*fn)(struct file_id id, struct server_id pid,
1780 enum brl_type lock_type,
1781 enum brl_flavour lock_flav,
1782 br_off start, br_off size,
1783 void *private_data);
1784 void *private_data;
1787 /****************************************************************************
1788 Traverse the whole database with this function, calling traverse_callback
1789 on each lock.
1790 ****************************************************************************/
1792 static int brl_traverse_fn(struct db_record *rec, void *state)
1794 struct brl_forall_cb *cb = (struct brl_forall_cb *)state;
1795 struct lock_struct *locks;
1796 struct file_id *key;
1797 unsigned int i;
1798 unsigned int num_locks = 0;
1799 TDB_DATA dbkey;
1800 TDB_DATA value;
1802 dbkey = dbwrap_record_get_key(rec);
1803 value = dbwrap_record_get_value(rec);
1805 /* In a traverse function we must make a copy of
1806 dbuf before modifying it. */
1808 locks = (struct lock_struct *)talloc_memdup(
1809 talloc_tos(), value.dptr, value.dsize);
1810 if (!locks) {
1811 return -1; /* Terminate traversal. */
1814 key = (struct file_id *)dbkey.dptr;
1815 num_locks = value.dsize/sizeof(*locks);
1817 if (cb->fn) {
1818 for ( i=0; i<num_locks; i++) {
1819 cb->fn(*key,
1820 locks[i].context.pid,
1821 locks[i].lock_type,
1822 locks[i].lock_flav,
1823 locks[i].start,
1824 locks[i].size,
1825 cb->private_data);
1829 TALLOC_FREE(locks);
1830 return 0;
1833 /*******************************************************************
1834 Call the specified function on each lock in the database.
1835 ********************************************************************/
1837 int brl_forall(void (*fn)(struct file_id id, struct server_id pid,
1838 enum brl_type lock_type,
1839 enum brl_flavour lock_flav,
1840 br_off start, br_off size,
1841 void *private_data),
1842 void *private_data)
1844 struct brl_forall_cb cb;
1845 NTSTATUS status;
1846 int count = 0;
1848 if (!brlock_db) {
1849 return 0;
1851 cb.fn = fn;
1852 cb.private_data = private_data;
1853 status = dbwrap_traverse(brlock_db, brl_traverse_fn, &cb, &count);
1855 if (!NT_STATUS_IS_OK(status)) {
1856 return -1;
1857 } else {
1858 return count;
1862 /*******************************************************************
1863 Store a potentially modified set of byte range lock data back into
1864 the database.
1865 Unlock the record.
1866 ********************************************************************/
1868 static void byte_range_lock_flush(struct byte_range_lock *br_lck)
1870 unsigned i;
1871 struct lock_struct *locks = br_lck->lock_data;
1873 if (!br_lck->modified) {
1874 DEBUG(10, ("br_lck not modified\n"));
1875 goto done;
1878 i = 0;
1880 while (i < br_lck->num_locks) {
1881 if (locks[i].context.pid.pid == 0) {
1883 * Autocleanup, the process conflicted and does not
1884 * exist anymore.
1886 locks[i] = locks[br_lck->num_locks-1];
1887 br_lck->num_locks -= 1;
1888 } else {
1889 i += 1;
1893 if ((br_lck->num_locks == 0) && (br_lck->num_read_oplocks == 0)) {
1894 /* No locks - delete this entry. */
1895 NTSTATUS status = dbwrap_record_delete(br_lck->record);
1896 if (!NT_STATUS_IS_OK(status)) {
1897 DEBUG(0, ("delete_rec returned %s\n",
1898 nt_errstr(status)));
1899 smb_panic("Could not delete byte range lock entry");
1901 } else {
1902 size_t lock_len, data_len;
1903 TDB_DATA data;
1904 NTSTATUS status;
1906 lock_len = br_lck->num_locks * sizeof(struct lock_struct);
1907 data_len = lock_len + sizeof(br_lck->num_read_oplocks);
1909 data.dsize = data_len;
1910 data.dptr = talloc_array(talloc_tos(), uint8_t, data_len);
1911 SMB_ASSERT(data.dptr != NULL);
1913 memcpy(data.dptr, br_lck->lock_data, lock_len);
1914 memcpy(data.dptr + lock_len, &br_lck->num_read_oplocks,
1915 sizeof(br_lck->num_read_oplocks));
1917 status = dbwrap_record_store(br_lck->record, data, TDB_REPLACE);
1918 TALLOC_FREE(data.dptr);
1919 if (!NT_STATUS_IS_OK(status)) {
1920 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
1921 smb_panic("Could not store byte range mode entry");
1925 DEBUG(10, ("seqnum=%d\n", dbwrap_get_seqnum(brlock_db)));
1927 done:
1928 br_lck->modified = false;
1929 TALLOC_FREE(br_lck->record);
1932 static int byte_range_lock_destructor(struct byte_range_lock *br_lck)
1934 byte_range_lock_flush(br_lck);
1935 return 0;
1938 static bool brl_parse_data(struct byte_range_lock *br_lck, TDB_DATA data)
1940 size_t data_len;
1942 if (data.dsize == 0) {
1943 return true;
1945 if (data.dsize % sizeof(struct lock_struct) !=
1946 sizeof(br_lck->num_read_oplocks)) {
1947 DEBUG(1, ("Invalid data size: %u\n", (unsigned)data.dsize));
1948 return false;
1951 br_lck->num_locks = data.dsize / sizeof(struct lock_struct);
1952 data_len = br_lck->num_locks * sizeof(struct lock_struct);
1954 br_lck->lock_data = talloc_memdup(br_lck, data.dptr, data_len);
1955 if (br_lck->lock_data == NULL) {
1956 DEBUG(1, ("talloc_memdup failed\n"));
1957 return false;
1959 memcpy(&br_lck->num_read_oplocks, data.dptr + data_len,
1960 sizeof(br_lck->num_read_oplocks));
1961 return true;
1964 /*******************************************************************
1965 Fetch a set of byte range lock data from the database.
1966 Leave the record locked.
1967 TALLOC_FREE(brl) will release the lock in the destructor.
1968 ********************************************************************/
1970 struct byte_range_lock *brl_get_locks(TALLOC_CTX *mem_ctx, files_struct *fsp)
1972 TDB_DATA key, data;
1973 struct byte_range_lock *br_lck;
1975 br_lck = talloc_zero(mem_ctx, struct byte_range_lock);
1976 if (br_lck == NULL) {
1977 return NULL;
1980 br_lck->fsp = fsp;
1982 key.dptr = (uint8_t *)&fsp->file_id;
1983 key.dsize = sizeof(struct file_id);
1985 br_lck->record = dbwrap_fetch_locked(brlock_db, br_lck, key);
1987 if (br_lck->record == NULL) {
1988 DEBUG(3, ("Could not lock byte range lock entry\n"));
1989 TALLOC_FREE(br_lck);
1990 return NULL;
1993 data = dbwrap_record_get_value(br_lck->record);
1995 if (!brl_parse_data(br_lck, data)) {
1996 TALLOC_FREE(br_lck);
1997 return NULL;
2000 talloc_set_destructor(br_lck, byte_range_lock_destructor);
2002 if (DEBUGLEVEL >= 10) {
2003 unsigned int i;
2004 struct lock_struct *locks = br_lck->lock_data;
2005 DEBUG(10,("brl_get_locks_internal: %u current locks on file_id %s\n",
2006 br_lck->num_locks,
2007 file_id_string_tos(&fsp->file_id)));
2008 for( i = 0; i < br_lck->num_locks; i++) {
2009 print_lock_struct(i, &locks[i]);
2013 return br_lck;
2016 struct brl_get_locks_readonly_state {
2017 TALLOC_CTX *mem_ctx;
2018 struct byte_range_lock **br_lock;
2021 static void brl_get_locks_readonly_parser(TDB_DATA key, TDB_DATA data,
2022 void *private_data)
2024 struct brl_get_locks_readonly_state *state =
2025 (struct brl_get_locks_readonly_state *)private_data;
2026 struct byte_range_lock *br_lck;
2028 br_lck = talloc_pooled_object(
2029 state->mem_ctx, struct byte_range_lock, 1, data.dsize);
2030 if (br_lck == NULL) {
2031 *state->br_lock = NULL;
2032 return;
2034 *br_lck = (struct byte_range_lock) { 0 };
2035 if (!brl_parse_data(br_lck, data)) {
2036 *state->br_lock = NULL;
2037 return;
2039 *state->br_lock = br_lck;
2042 struct byte_range_lock *brl_get_locks_readonly(files_struct *fsp)
2044 struct byte_range_lock *br_lock = NULL;
2045 struct brl_get_locks_readonly_state state;
2046 NTSTATUS status;
2048 DEBUG(10, ("seqnum=%d, fsp->brlock_seqnum=%d\n",
2049 dbwrap_get_seqnum(brlock_db), fsp->brlock_seqnum));
2051 if ((fsp->brlock_rec != NULL)
2052 && (dbwrap_get_seqnum(brlock_db) == fsp->brlock_seqnum)) {
2054 * We have cached the brlock_rec and the database did not
2055 * change.
2057 return fsp->brlock_rec;
2061 * Parse the record fresh from the database
2064 state.mem_ctx = fsp;
2065 state.br_lock = &br_lock;
2067 status = dbwrap_parse_record(
2068 brlock_db,
2069 make_tdb_data((uint8_t *)&fsp->file_id,
2070 sizeof(fsp->file_id)),
2071 brl_get_locks_readonly_parser, &state);
2073 if (NT_STATUS_EQUAL(status,NT_STATUS_NOT_FOUND)) {
2075 * No locks on this file. Return an empty br_lock.
2077 br_lock = talloc(fsp, struct byte_range_lock);
2078 if (br_lock == NULL) {
2079 return NULL;
2082 br_lock->num_read_oplocks = 0;
2083 br_lock->num_locks = 0;
2084 br_lock->lock_data = NULL;
2086 } else if (!NT_STATUS_IS_OK(status)) {
2087 DEBUG(3, ("Could not parse byte range lock record: "
2088 "%s\n", nt_errstr(status)));
2089 return NULL;
2091 if (br_lock == NULL) {
2092 return NULL;
2095 br_lock->fsp = fsp;
2096 br_lock->modified = false;
2097 br_lock->record = NULL;
2099 if (lp_clustering()) {
2101 * In the cluster case we can't cache the brlock struct
2102 * because dbwrap_get_seqnum does not work reliably over
2103 * ctdb. Thus we have to throw away the brlock struct soon.
2105 talloc_steal(talloc_tos(), br_lock);
2106 } else {
2108 * Cache the brlock struct, invalidated when the dbwrap_seqnum
2109 * changes. See beginning of this routine.
2111 TALLOC_FREE(fsp->brlock_rec);
2112 fsp->brlock_rec = br_lock;
2113 fsp->brlock_seqnum = dbwrap_get_seqnum(brlock_db);
2116 return br_lock;
2119 struct brl_revalidate_state {
2120 ssize_t array_size;
2121 uint32_t num_pids;
2122 struct server_id *pids;
2126 * Collect PIDs of all processes with pending entries
2129 static void brl_revalidate_collect(struct file_id id, struct server_id pid,
2130 enum brl_type lock_type,
2131 enum brl_flavour lock_flav,
2132 br_off start, br_off size,
2133 void *private_data)
2135 struct brl_revalidate_state *state =
2136 (struct brl_revalidate_state *)private_data;
2138 if (!IS_PENDING_LOCK(lock_type)) {
2139 return;
2142 add_to_large_array(state, sizeof(pid), (void *)&pid,
2143 &state->pids, &state->num_pids,
2144 &state->array_size);
2148 * qsort callback to sort the processes
2151 static int compare_procids(const void *p1, const void *p2)
2153 const struct server_id *i1 = (const struct server_id *)p1;
2154 const struct server_id *i2 = (const struct server_id *)p2;
2156 if (i1->pid < i2->pid) return -1;
2157 if (i1->pid > i2->pid) return 1;
2158 return 0;
2162 * Send a MSG_SMB_UNLOCK message to all processes with pending byte range
2163 * locks so that they retry. Mainly used in the cluster code after a node has
2164 * died.
2166 * Done in two steps to avoid double-sends: First we collect all entries in an
2167 * array, then qsort that array and only send to non-dupes.
2170 void brl_revalidate(struct messaging_context *msg_ctx,
2171 void *private_data,
2172 uint32_t msg_type,
2173 struct server_id server_id,
2174 DATA_BLOB *data)
2176 struct brl_revalidate_state *state;
2177 uint32_t i;
2178 struct server_id last_pid;
2180 if (!(state = talloc_zero(NULL, struct brl_revalidate_state))) {
2181 DEBUG(0, ("talloc failed\n"));
2182 return;
2185 brl_forall(brl_revalidate_collect, state);
2187 if (state->array_size == -1) {
2188 DEBUG(0, ("talloc failed\n"));
2189 goto done;
2192 if (state->num_pids == 0) {
2193 goto done;
2196 TYPESAFE_QSORT(state->pids, state->num_pids, compare_procids);
2198 ZERO_STRUCT(last_pid);
2200 for (i=0; i<state->num_pids; i++) {
2201 if (serverid_equal(&last_pid, &state->pids[i])) {
2203 * We've seen that one already
2205 continue;
2208 messaging_send(msg_ctx, state->pids[i], MSG_SMB_UNLOCK,
2209 &data_blob_null);
2210 last_pid = state->pids[i];
2213 done:
2214 TALLOC_FREE(state);
2215 return;
2218 bool brl_cleanup_disconnected(struct file_id fid, uint64_t open_persistent_id)
2220 bool ret = false;
2221 TALLOC_CTX *frame = talloc_stackframe();
2222 TDB_DATA key, val;
2223 struct db_record *rec;
2224 struct lock_struct *lock;
2225 unsigned n, num;
2226 NTSTATUS status;
2228 key = make_tdb_data((void*)&fid, sizeof(fid));
2230 rec = dbwrap_fetch_locked(brlock_db, frame, key);
2231 if (rec == NULL) {
2232 DEBUG(5, ("brl_cleanup_disconnected: failed to fetch record "
2233 "for file %s\n", file_id_string(frame, &fid)));
2234 goto done;
2237 val = dbwrap_record_get_value(rec);
2238 lock = (struct lock_struct*)val.dptr;
2239 num = val.dsize / sizeof(struct lock_struct);
2240 if (lock == NULL) {
2241 DEBUG(10, ("brl_cleanup_disconnected: no byte range locks for "
2242 "file %s\n", file_id_string(frame, &fid)));
2243 ret = true;
2244 goto done;
2247 for (n=0; n<num; n++) {
2248 struct lock_context *ctx = &lock[n].context;
2250 if (!server_id_is_disconnected(&ctx->pid)) {
2251 struct server_id_buf tmp;
2252 DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2253 "%s used by server %s, do not cleanup\n",
2254 file_id_string(frame, &fid),
2255 server_id_str_buf(ctx->pid, &tmp)));
2256 goto done;
2259 if (ctx->smblctx != open_persistent_id) {
2260 DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2261 "%s expected smblctx %llu but found %llu"
2262 ", do not cleanup\n",
2263 file_id_string(frame, &fid),
2264 (unsigned long long)open_persistent_id,
2265 (unsigned long long)ctx->smblctx));
2266 goto done;
2270 status = dbwrap_record_delete(rec);
2271 if (!NT_STATUS_IS_OK(status)) {
2272 DEBUG(5, ("brl_cleanup_disconnected: failed to delete record "
2273 "for file %s from %s, open %llu: %s\n",
2274 file_id_string(frame, &fid), dbwrap_name(brlock_db),
2275 (unsigned long long)open_persistent_id,
2276 nt_errstr(status)));
2277 goto done;
2280 DEBUG(10, ("brl_cleanup_disconnected: "
2281 "file %s cleaned up %u entries from open %llu\n",
2282 file_id_string(frame, &fid), num,
2283 (unsigned long long)open_persistent_id));
2285 ret = true;
2286 done:
2287 talloc_free(frame);
2288 return ret;