gp: Move GNOME admx templates
[Samba.git] / source3 / locking / brlock.c
blobd2e4abf48d73e8612a703a3a801eaa233d133865
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 "lib/util/server_id.h"
30 #include "locking/proto.h"
31 #include "smbd/globals.h"
32 #include "dbwrap/dbwrap.h"
33 #include "dbwrap/dbwrap_open.h"
34 #include "serverid.h"
35 #include "messages.h"
36 #include "util_tdb.h"
38 #undef DBGC_CLASS
39 #define DBGC_CLASS DBGC_LOCKING
41 #define ZERO_ZERO 0
43 /* The open brlock.tdb database. */
45 static struct db_context *brlock_db;
47 struct byte_range_lock {
48 struct files_struct *fsp;
49 TALLOC_CTX *req_mem_ctx;
50 const struct GUID *req_guid;
51 unsigned int num_locks;
52 bool modified;
53 struct lock_struct *lock_data;
54 struct db_record *record;
57 /****************************************************************************
58 Debug info at level 10 for lock struct.
59 ****************************************************************************/
61 static void print_lock_struct(unsigned int i, const struct lock_struct *pls)
63 struct server_id_buf tmp;
65 DBG_DEBUG("[%u]: smblctx = %"PRIu64", tid = %"PRIu32", pid = %s, "
66 "start = %"PRIu64", size = %"PRIu64", fnum = %"PRIu64", "
67 "%s %s\n",
69 pls->context.smblctx,
70 pls->context.tid,
71 server_id_str_buf(pls->context.pid, &tmp),
72 pls->start,
73 pls->size,
74 pls->fnum,
75 lock_type_name(pls->lock_type),
76 lock_flav_name(pls->lock_flav));
79 unsigned int brl_num_locks(const struct byte_range_lock *brl)
81 return brl->num_locks;
84 struct files_struct *brl_fsp(struct byte_range_lock *brl)
86 return brl->fsp;
89 TALLOC_CTX *brl_req_mem_ctx(const struct byte_range_lock *brl)
91 if (brl->req_mem_ctx == NULL) {
92 return talloc_get_type_abort(brl, struct byte_range_lock);
95 return brl->req_mem_ctx;
98 const struct GUID *brl_req_guid(const struct byte_range_lock *brl)
100 if (brl->req_guid == NULL) {
101 static const struct GUID brl_zero_req_guid;
102 return &brl_zero_req_guid;
105 return brl->req_guid;
108 /****************************************************************************
109 See if two locking contexts are equal.
110 ****************************************************************************/
112 static bool brl_same_context(const struct lock_context *ctx1,
113 const struct lock_context *ctx2)
115 return (server_id_equal(&ctx1->pid, &ctx2->pid) &&
116 (ctx1->smblctx == ctx2->smblctx) &&
117 (ctx1->tid == ctx2->tid));
120 bool byte_range_valid(uint64_t ofs, uint64_t len)
122 uint64_t max_len = UINT64_MAX - ofs;
123 uint64_t effective_len;
126 * [MS-FSA] specifies this:
128 * If (((FileOffset + Length - 1) < FileOffset) && Length != 0) {
129 * return STATUS_INVALID_LOCK_RANGE
132 * We avoid integer wrapping and calculate
133 * max and effective len instead.
136 if (len == 0) {
137 return true;
140 effective_len = len - 1;
141 if (effective_len <= max_len) {
142 return true;
145 return false;
148 bool byte_range_overlap(uint64_t ofs1,
149 uint64_t len1,
150 uint64_t ofs2,
151 uint64_t len2)
153 uint64_t last1;
154 uint64_t last2;
155 bool valid;
158 * This is based on [MS-FSA] 2.1.4.10
159 * Algorithm for Determining If a Range Access
160 * Conflicts with Byte-Range Locks
164 * The {0, 0} range doesn't conflict with any byte-range lock
166 if (ofs1 == 0 && len1 == 0) {
167 return false;
169 if (ofs2 == 0 && len2 == 0) {
170 return false;
174 * The caller should have checked that the ranges are
175 * valid. But currently we gracefully handle
176 * the overflow of a read/write check.
178 valid = byte_range_valid(ofs1, len1);
179 if (valid) {
180 last1 = ofs1 + len1 - 1;
181 } else {
182 last1 = UINT64_MAX;
184 valid = byte_range_valid(ofs2, len2);
185 if (valid) {
186 last2 = ofs2 + len2 - 1;
187 } else {
188 last2 = UINT64_MAX;
192 * If one range starts after the last
193 * byte of the other range there's
194 * no conflict.
196 if (ofs1 > last2) {
197 return false;
199 if (ofs2 > last1) {
200 return false;
203 return true;
206 /****************************************************************************
207 See if lck1 and lck2 overlap.
208 ****************************************************************************/
210 static bool brl_overlap(const struct lock_struct *lck1,
211 const struct lock_struct *lck2)
213 return byte_range_overlap(lck1->start,
214 lck1->size,
215 lck2->start,
216 lck2->size);
219 /****************************************************************************
220 See if lock2 can be added when lock1 is in place.
221 ****************************************************************************/
223 static bool brl_conflict(const struct lock_struct *lck1,
224 const struct lock_struct *lck2)
226 /* Read locks never conflict. */
227 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
228 return False;
231 /* A READ lock can stack on top of a WRITE lock if they have the same
232 * context & fnum. */
233 if (lck1->lock_type == WRITE_LOCK && lck2->lock_type == READ_LOCK &&
234 brl_same_context(&lck1->context, &lck2->context) &&
235 lck1->fnum == lck2->fnum) {
236 return False;
239 return brl_overlap(lck1, lck2);
242 /****************************************************************************
243 See if lock2 can be added when lock1 is in place - when both locks are POSIX
244 flavour. POSIX locks ignore fnum - they only care about dev/ino which we
245 know already match.
246 ****************************************************************************/
248 static bool brl_conflict_posix(const struct lock_struct *lck1,
249 const struct lock_struct *lck2)
251 #if defined(DEVELOPER)
252 SMB_ASSERT(lck1->lock_flav == POSIX_LOCK);
253 SMB_ASSERT(lck2->lock_flav == POSIX_LOCK);
254 #endif
256 /* Read locks never conflict. */
257 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
258 return False;
261 /* Locks on the same context don't conflict. Ignore fnum. */
262 if (brl_same_context(&lck1->context, &lck2->context)) {
263 return False;
266 /* One is read, the other write, or the context is different,
267 do they overlap ? */
268 return brl_overlap(lck1, lck2);
271 #if ZERO_ZERO
272 static bool brl_conflict1(const struct lock_struct *lck1,
273 const struct lock_struct *lck2)
275 if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
276 return False;
279 if (brl_same_context(&lck1->context, &lck2->context) &&
280 lck2->lock_type == READ_LOCK && lck1->fnum == lck2->fnum) {
281 return False;
284 if (lck2->start == 0 && lck2->size == 0 && lck1->size != 0) {
285 return True;
288 if (lck1->start >= (lck2->start + lck2->size) ||
289 lck2->start >= (lck1->start + lck1->size)) {
290 return False;
293 return True;
295 #endif
297 /****************************************************************************
298 Check to see if this lock conflicts, but ignore our own locks on the
299 same fnum only. This is the read/write lock check code path.
300 This is never used in the POSIX lock case.
301 ****************************************************************************/
303 static bool brl_conflict_other(const struct lock_struct *lock,
304 const struct lock_struct *rw_probe)
306 if (lock->lock_type == READ_LOCK && rw_probe->lock_type == READ_LOCK) {
307 return False;
310 if (lock->lock_flav == POSIX_LOCK &&
311 rw_probe->lock_flav == POSIX_LOCK) {
313 * POSIX flavour locks never conflict here - this is only called
314 * in the read/write path.
316 return False;
319 if (!brl_overlap(lock, rw_probe)) {
321 * I/O can only conflict when overlapping a lock, thus let it
322 * pass
324 return false;
327 if (!brl_same_context(&lock->context, &rw_probe->context)) {
329 * Different process, conflict
331 return true;
334 if (lock->fnum != rw_probe->fnum) {
336 * Different file handle, conflict
338 return true;
341 if ((lock->lock_type == READ_LOCK) &&
342 (rw_probe->lock_type == WRITE_LOCK)) {
344 * Incoming WRITE locks conflict with existing READ locks even
345 * if the context is the same. JRA. See LOCKTEST7 in
346 * smbtorture.
348 return true;
352 * I/O request compatible with existing lock, let it pass without
353 * conflict
356 return false;
359 /****************************************************************************
360 Open up the brlock.tdb database.
361 ****************************************************************************/
363 void brl_init(bool read_only)
365 int tdb_flags;
366 char *db_path;
368 if (brlock_db) {
369 return;
372 tdb_flags =
373 TDB_DEFAULT|
374 TDB_VOLATILE|
375 TDB_CLEAR_IF_FIRST|
376 TDB_INCOMPATIBLE_HASH|
377 TDB_SEQNUM;
379 db_path = lock_path(talloc_tos(), "brlock.tdb");
380 if (db_path == NULL) {
381 DEBUG(0, ("out of memory!\n"));
382 return;
385 brlock_db = db_open(NULL, db_path,
386 SMB_OPEN_DATABASE_TDB_HASH_SIZE, tdb_flags,
387 read_only?O_RDONLY:(O_RDWR|O_CREAT), 0644,
388 DBWRAP_LOCK_ORDER_2, DBWRAP_FLAG_NONE);
389 if (!brlock_db) {
390 DEBUG(0,("Failed to open byte range locking database %s\n",
391 db_path));
392 TALLOC_FREE(db_path);
393 return;
395 TALLOC_FREE(db_path);
398 /****************************************************************************
399 Close down the brlock.tdb database.
400 ****************************************************************************/
402 void brl_shutdown(void)
404 TALLOC_FREE(brlock_db);
407 #if ZERO_ZERO
408 /****************************************************************************
409 Compare two locks for sorting.
410 ****************************************************************************/
412 static int lock_compare(const struct lock_struct *lck1,
413 const struct lock_struct *lck2)
415 if (lck1->start != lck2->start) {
416 return (lck1->start - lck2->start);
418 if (lck2->size != lck1->size) {
419 return ((int)lck1->size - (int)lck2->size);
421 return 0;
423 #endif
425 /****************************************************************************
426 Lock a range of bytes - Windows lock semantics.
427 ****************************************************************************/
429 NTSTATUS brl_lock_windows_default(struct byte_range_lock *br_lck,
430 struct lock_struct *plock)
432 unsigned int i;
433 files_struct *fsp = br_lck->fsp;
434 struct lock_struct *locks = br_lck->lock_data;
435 NTSTATUS status;
436 bool valid;
438 SMB_ASSERT(plock->lock_type != UNLOCK_LOCK);
440 valid = byte_range_valid(plock->start, plock->size);
441 if (!valid) {
442 return NT_STATUS_INVALID_LOCK_RANGE;
445 for (i=0; i < br_lck->num_locks; i++) {
446 /* Do any Windows or POSIX locks conflict ? */
447 if (brl_conflict(&locks[i], plock)) {
448 if (!serverid_exists(&locks[i].context.pid)) {
449 locks[i].context.pid.pid = 0;
450 br_lck->modified = true;
451 continue;
453 /* Remember who blocked us. */
454 plock->context.smblctx = locks[i].context.smblctx;
455 return NT_STATUS_LOCK_NOT_GRANTED;
457 #if ZERO_ZERO
458 if (plock->start == 0 && plock->size == 0 &&
459 locks[i].size == 0) {
460 break;
462 #endif
465 contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
467 /* We can get the Windows lock, now see if it needs to
468 be mapped into a lower level POSIX one, and if so can
469 we get it ? */
471 if (lp_posix_locking(fsp->conn->params)) {
472 int errno_ret;
473 if (!set_posix_lock_windows_flavour(fsp,
474 plock->start,
475 plock->size,
476 plock->lock_type,
477 &plock->context,
478 locks,
479 br_lck->num_locks,
480 &errno_ret)) {
482 /* We don't know who blocked us. */
483 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
485 if (errno_ret == EACCES || errno_ret == EAGAIN) {
486 status = NT_STATUS_LOCK_NOT_GRANTED;
487 goto fail;
488 } else {
489 status = map_nt_error_from_unix(errno);
490 goto fail;
495 /* no conflicts - add it to the list of locks */
496 locks = talloc_realloc(br_lck, locks, struct lock_struct,
497 (br_lck->num_locks + 1));
498 if (!locks) {
499 status = NT_STATUS_NO_MEMORY;
500 goto fail;
503 memcpy(&locks[br_lck->num_locks], plock, sizeof(struct lock_struct));
504 br_lck->num_locks += 1;
505 br_lck->lock_data = locks;
506 br_lck->modified = True;
508 return NT_STATUS_OK;
509 fail:
510 contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
511 return status;
514 /****************************************************************************
515 Cope with POSIX range splits and merges.
516 ****************************************************************************/
518 static unsigned int brlock_posix_split_merge(struct lock_struct *lck_arr, /* Output array. */
519 struct lock_struct *ex, /* existing lock. */
520 struct lock_struct *plock) /* proposed lock. */
522 bool lock_types_differ = (ex->lock_type != plock->lock_type);
524 /* We can't merge non-conflicting locks on different context - ignore fnum. */
526 if (!brl_same_context(&ex->context, &plock->context)) {
527 /* Just copy. */
528 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
529 return 1;
532 /* We now know we have the same context. */
534 /* Did we overlap ? */
536 /*********************************************
537 +---------+
538 | ex |
539 +---------+
540 +-------+
541 | plock |
542 +-------+
543 OR....
544 +---------+
545 | ex |
546 +---------+
547 **********************************************/
549 if ( (ex->start > (plock->start + plock->size)) ||
550 (plock->start > (ex->start + ex->size))) {
552 /* No overlap with this lock - copy existing. */
554 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
555 return 1;
558 /*********************************************
559 +---------------------------+
560 | ex |
561 +---------------------------+
562 +---------------------------+
563 | plock | -> replace with plock.
564 +---------------------------+
566 +---------------+
567 | ex |
568 +---------------+
569 +---------------------------+
570 | plock | -> replace with plock.
571 +---------------------------+
573 **********************************************/
575 if ( (ex->start >= plock->start) &&
576 (ex->start + ex->size <= plock->start + plock->size) ) {
578 /* Replace - discard existing lock. */
580 return 0;
583 /*********************************************
584 Adjacent after.
585 +-------+
586 | ex |
587 +-------+
588 +---------------+
589 | plock |
590 +---------------+
592 BECOMES....
593 +---------------+-------+
594 | plock | ex | - different lock types.
595 +---------------+-------+
596 OR.... (merge)
597 +-----------------------+
598 | plock | - same lock type.
599 +-----------------------+
600 **********************************************/
602 if (plock->start + plock->size == ex->start) {
604 /* If the lock types are the same, we merge, if different, we
605 add the remainder of the old lock. */
607 if (lock_types_differ) {
608 /* Add existing. */
609 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
610 return 1;
611 } else {
612 /* Merge - adjust incoming lock as we may have more
613 * merging to come. */
614 plock->size += ex->size;
615 return 0;
619 /*********************************************
620 Adjacent before.
621 +-------+
622 | ex |
623 +-------+
624 +---------------+
625 | plock |
626 +---------------+
627 BECOMES....
628 +-------+---------------+
629 | ex | plock | - different lock types
630 +-------+---------------+
632 OR.... (merge)
633 +-----------------------+
634 | plock | - same lock type.
635 +-----------------------+
637 **********************************************/
639 if (ex->start + ex->size == plock->start) {
641 /* If the lock types are the same, we merge, if different, we
642 add the existing lock. */
644 if (lock_types_differ) {
645 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
646 return 1;
647 } else {
648 /* Merge - adjust incoming lock as we may have more
649 * merging to come. */
650 plock->start = ex->start;
651 plock->size += ex->size;
652 return 0;
656 /*********************************************
657 Overlap after.
658 +-----------------------+
659 | ex |
660 +-----------------------+
661 +---------------+
662 | plock |
663 +---------------+
665 +----------------+
666 | ex |
667 +----------------+
668 +---------------+
669 | plock |
670 +---------------+
672 BECOMES....
673 +---------------+-------+
674 | plock | ex | - different lock types.
675 +---------------+-------+
676 OR.... (merge)
677 +-----------------------+
678 | plock | - same lock type.
679 +-----------------------+
680 **********************************************/
682 if ( (ex->start >= plock->start) &&
683 (ex->start <= plock->start + plock->size) &&
684 (ex->start + ex->size > plock->start + plock->size) ) {
686 /* If the lock types are the same, we merge, if different, we
687 add the remainder of the old lock. */
689 if (lock_types_differ) {
690 /* Add remaining existing. */
691 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
692 /* Adjust existing start and size. */
693 lck_arr[0].start = plock->start + plock->size;
694 lck_arr[0].size = (ex->start + ex->size) - (plock->start + plock->size);
695 return 1;
696 } else {
697 /* Merge - adjust incoming lock as we may have more
698 * merging to come. */
699 plock->size += (ex->start + ex->size) - (plock->start + plock->size);
700 return 0;
704 /*********************************************
705 Overlap before.
706 +-----------------------+
707 | ex |
708 +-----------------------+
709 +---------------+
710 | plock |
711 +---------------+
713 +-------------+
714 | ex |
715 +-------------+
716 +---------------+
717 | plock |
718 +---------------+
720 BECOMES....
721 +-------+---------------+
722 | ex | plock | - different lock types
723 +-------+---------------+
725 OR.... (merge)
726 +-----------------------+
727 | plock | - same lock type.
728 +-----------------------+
730 **********************************************/
732 if ( (ex->start < plock->start) &&
733 (ex->start + ex->size >= plock->start) &&
734 (ex->start + ex->size <= plock->start + plock->size) ) {
736 /* If the lock types are the same, we merge, if different, we
737 add the truncated old lock. */
739 if (lock_types_differ) {
740 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
741 /* Adjust existing size. */
742 lck_arr[0].size = plock->start - ex->start;
743 return 1;
744 } else {
745 /* Merge - adjust incoming lock as we may have more
746 * merging to come. MUST ADJUST plock SIZE FIRST ! */
747 plock->size += (plock->start - ex->start);
748 plock->start = ex->start;
749 return 0;
753 /*********************************************
754 Complete overlap.
755 +---------------------------+
756 | ex |
757 +---------------------------+
758 +---------+
759 | plock |
760 +---------+
761 BECOMES.....
762 +-------+---------+---------+
763 | ex | plock | ex | - different lock types.
764 +-------+---------+---------+
766 +---------------------------+
767 | plock | - same lock type.
768 +---------------------------+
769 **********************************************/
771 if ( (ex->start < plock->start) && (ex->start + ex->size > plock->start + plock->size) ) {
773 if (lock_types_differ) {
775 /* We have to split ex into two locks here. */
777 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
778 memcpy(&lck_arr[1], ex, sizeof(struct lock_struct));
780 /* Adjust first existing size. */
781 lck_arr[0].size = plock->start - ex->start;
783 /* Adjust second existing start and size. */
784 lck_arr[1].start = plock->start + plock->size;
785 lck_arr[1].size = (ex->start + ex->size) - (plock->start + plock->size);
786 return 2;
787 } else {
788 /* Just eat the existing locks, merge them into plock. */
789 plock->start = ex->start;
790 plock->size = ex->size;
791 return 0;
795 /* Never get here. */
796 smb_panic("brlock_posix_split_merge");
797 /* Notreached. */
799 /* Keep some compilers happy. */
800 return 0;
803 /****************************************************************************
804 Lock a range of bytes - POSIX lock semantics.
805 We must cope with range splits and merges.
806 ****************************************************************************/
808 static NTSTATUS brl_lock_posix(struct byte_range_lock *br_lck,
809 struct lock_struct *plock)
811 unsigned int i, count, posix_count;
812 struct lock_struct *locks = br_lck->lock_data;
813 struct lock_struct *tp;
814 bool break_oplocks = false;
815 NTSTATUS status;
817 /* No zero-zero locks for POSIX. */
818 if (plock->start == 0 && plock->size == 0) {
819 return NT_STATUS_INVALID_PARAMETER;
822 /* Don't allow 64-bit lock wrap. */
823 if (plock->start + plock->size - 1 < plock->start) {
824 return NT_STATUS_INVALID_PARAMETER;
827 /* The worst case scenario here is we have to split an
828 existing POSIX lock range into two, and add our lock,
829 so we need at most 2 more entries. */
831 tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 2);
832 if (!tp) {
833 return NT_STATUS_NO_MEMORY;
836 count = posix_count = 0;
838 for (i=0; i < br_lck->num_locks; i++) {
839 struct lock_struct *curr_lock = &locks[i];
841 if (curr_lock->lock_flav == WINDOWS_LOCK) {
842 /* Do any Windows flavour locks conflict ? */
843 if (brl_conflict(curr_lock, plock)) {
844 if (!serverid_exists(&curr_lock->context.pid)) {
845 curr_lock->context.pid.pid = 0;
846 br_lck->modified = true;
847 continue;
849 /* No games with error messages. */
850 TALLOC_FREE(tp);
851 /* Remember who blocked us. */
852 plock->context.smblctx = curr_lock->context.smblctx;
853 return NT_STATUS_LOCK_NOT_GRANTED;
855 /* Just copy the Windows lock into the new array. */
856 memcpy(&tp[count], curr_lock, sizeof(struct lock_struct));
857 count++;
858 } else {
859 unsigned int tmp_count = 0;
861 /* POSIX conflict semantics are different. */
862 if (brl_conflict_posix(curr_lock, plock)) {
863 if (!serverid_exists(&curr_lock->context.pid)) {
864 curr_lock->context.pid.pid = 0;
865 br_lck->modified = true;
866 continue;
868 /* Can't block ourselves with POSIX locks. */
869 /* No games with error messages. */
870 TALLOC_FREE(tp);
871 /* Remember who blocked us. */
872 plock->context.smblctx = curr_lock->context.smblctx;
873 return NT_STATUS_LOCK_NOT_GRANTED;
876 /* Work out overlaps. */
877 tmp_count += brlock_posix_split_merge(&tp[count], curr_lock, plock);
878 posix_count += tmp_count;
879 count += tmp_count;
884 * Break oplocks while we hold a brl. Since lock() and unlock() calls
885 * are not symetric with POSIX semantics, we cannot guarantee our
886 * contend_level2_oplocks_begin/end calls will be acquired and
887 * released one-for-one as with Windows semantics. Therefore we only
888 * call contend_level2_oplocks_begin if this is the first POSIX brl on
889 * the file.
891 break_oplocks = (posix_count == 0);
892 if (break_oplocks) {
893 contend_level2_oplocks_begin(br_lck->fsp,
894 LEVEL2_CONTEND_POSIX_BRL);
897 /* Try and add the lock in order, sorted by lock start. */
898 for (i=0; i < count; i++) {
899 struct lock_struct *curr_lock = &tp[i];
901 if (curr_lock->start <= plock->start) {
902 continue;
906 if (i < count) {
907 memmove(&tp[i+1], &tp[i],
908 (count - i)*sizeof(struct lock_struct));
910 memcpy(&tp[i], plock, sizeof(struct lock_struct));
911 count++;
913 /* We can get the POSIX lock, now see if it needs to
914 be mapped into a lower level POSIX one, and if so can
915 we get it ? */
917 if (lp_posix_locking(br_lck->fsp->conn->params)) {
918 int errno_ret;
920 /* The lower layer just needs to attempt to
921 get the system POSIX lock. We've weeded out
922 any conflicts above. */
924 if (!set_posix_lock_posix_flavour(br_lck->fsp,
925 plock->start,
926 plock->size,
927 plock->lock_type,
928 &plock->context,
929 &errno_ret)) {
931 /* We don't know who blocked us. */
932 plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
934 if (errno_ret == EACCES || errno_ret == EAGAIN) {
935 TALLOC_FREE(tp);
936 status = NT_STATUS_LOCK_NOT_GRANTED;
937 goto fail;
938 } else {
939 TALLOC_FREE(tp);
940 status = map_nt_error_from_unix(errno);
941 goto fail;
946 /* If we didn't use all the allocated size,
947 * Realloc so we don't leak entries per lock call. */
948 if (count < br_lck->num_locks + 2) {
949 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
950 if (!tp) {
951 status = NT_STATUS_NO_MEMORY;
952 goto fail;
956 br_lck->num_locks = count;
957 TALLOC_FREE(br_lck->lock_data);
958 br_lck->lock_data = tp;
959 locks = tp;
960 br_lck->modified = True;
962 /* A successful downgrade from write to read lock can trigger a lock
963 re-evalutation where waiting readers can now proceed. */
965 return NT_STATUS_OK;
966 fail:
967 if (break_oplocks) {
968 contend_level2_oplocks_end(br_lck->fsp,
969 LEVEL2_CONTEND_POSIX_BRL);
971 return status;
974 /****************************************************************************
975 Lock a range of bytes.
976 ****************************************************************************/
978 NTSTATUS brl_lock(
979 struct byte_range_lock *br_lck,
980 uint64_t smblctx,
981 struct server_id pid,
982 br_off start,
983 br_off size,
984 enum brl_type lock_type,
985 enum brl_flavour lock_flav,
986 struct server_id *blocker_pid,
987 uint64_t *psmblctx)
989 NTSTATUS ret;
990 struct lock_struct lock;
992 ZERO_STRUCT(lock);
994 #if !ZERO_ZERO
995 if (start == 0 && size == 0) {
996 DEBUG(0,("client sent 0/0 lock - please report this\n"));
998 #endif
1000 lock = (struct lock_struct) {
1001 .context.smblctx = smblctx,
1002 .context.pid = pid,
1003 .context.tid = br_lck->fsp->conn->cnum,
1004 .start = start,
1005 .size = size,
1006 .fnum = br_lck->fsp->fnum,
1007 .lock_type = lock_type,
1008 .lock_flav = lock_flav
1011 if (lock_flav == WINDOWS_LOCK) {
1012 ret = SMB_VFS_BRL_LOCK_WINDOWS(
1013 br_lck->fsp->conn, br_lck, &lock);
1014 } else {
1015 ret = brl_lock_posix(br_lck, &lock);
1018 #if ZERO_ZERO
1019 /* sort the lock list */
1020 TYPESAFE_QSORT(br_lck->lock_data, (size_t)br_lck->num_locks, lock_compare);
1021 #endif
1022 /* If we're returning an error, return who blocked us. */
1023 if (!NT_STATUS_IS_OK(ret) && psmblctx) {
1024 *blocker_pid = lock.context.pid;
1025 *psmblctx = lock.context.smblctx;
1027 return ret;
1030 /****************************************************************************
1031 Unlock a range of bytes - Windows semantics.
1032 ****************************************************************************/
1034 bool brl_unlock_windows_default(struct byte_range_lock *br_lck,
1035 const struct lock_struct *plock)
1037 unsigned int i;
1038 struct lock_struct *locks = br_lck->lock_data;
1039 enum brl_type deleted_lock_type = READ_LOCK; /* shut the compiler up.... */
1041 SMB_ASSERT(plock->lock_type == UNLOCK_LOCK);
1043 #if ZERO_ZERO
1044 /* Delete write locks by preference... The lock list
1045 is sorted in the zero zero case. */
1047 for (i = 0; i < br_lck->num_locks; i++) {
1048 struct lock_struct *lock = &locks[i];
1050 if (lock->lock_type == WRITE_LOCK &&
1051 brl_same_context(&lock->context, &plock->context) &&
1052 lock->fnum == plock->fnum &&
1053 lock->lock_flav == WINDOWS_LOCK &&
1054 lock->start == plock->start &&
1055 lock->size == plock->size) {
1057 /* found it - delete it */
1058 deleted_lock_type = lock->lock_type;
1059 break;
1063 if (i != br_lck->num_locks) {
1064 /* We found it - don't search again. */
1065 goto unlock_continue;
1067 #endif
1069 for (i = 0; i < br_lck->num_locks; i++) {
1070 struct lock_struct *lock = &locks[i];
1072 /* Only remove our own locks that match in start, size, and flavour. */
1073 if (brl_same_context(&lock->context, &plock->context) &&
1074 lock->fnum == plock->fnum &&
1075 lock->lock_flav == WINDOWS_LOCK &&
1076 lock->start == plock->start &&
1077 lock->size == plock->size ) {
1078 deleted_lock_type = lock->lock_type;
1079 break;
1083 if (i == br_lck->num_locks) {
1084 /* we didn't find it */
1085 return False;
1088 #if ZERO_ZERO
1089 unlock_continue:
1090 #endif
1092 ARRAY_DEL_ELEMENT(locks, i, br_lck->num_locks);
1093 br_lck->num_locks -= 1;
1094 br_lck->modified = True;
1096 /* Unlock the underlying POSIX regions. */
1097 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1098 release_posix_lock_windows_flavour(br_lck->fsp,
1099 plock->start,
1100 plock->size,
1101 deleted_lock_type,
1102 &plock->context,
1103 locks,
1104 br_lck->num_locks);
1107 contend_level2_oplocks_end(br_lck->fsp, LEVEL2_CONTEND_WINDOWS_BRL);
1108 return True;
1111 /****************************************************************************
1112 Unlock a range of bytes - POSIX semantics.
1113 ****************************************************************************/
1115 static bool brl_unlock_posix(struct byte_range_lock *br_lck,
1116 struct lock_struct *plock)
1118 unsigned int i, count;
1119 struct lock_struct *tp;
1120 struct lock_struct *locks = br_lck->lock_data;
1121 bool overlap_found = False;
1123 /* No zero-zero locks for POSIX. */
1124 if (plock->start == 0 && plock->size == 0) {
1125 return False;
1128 /* Don't allow 64-bit lock wrap. */
1129 if (plock->start + plock->size < plock->start ||
1130 plock->start + plock->size < plock->size) {
1131 DEBUG(10,("brl_unlock_posix: lock wrap\n"));
1132 return False;
1135 /* The worst case scenario here is we have to split an
1136 existing POSIX lock range into two, so we need at most
1137 1 more entry. */
1139 tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 1);
1140 if (!tp) {
1141 DEBUG(10,("brl_unlock_posix: malloc fail\n"));
1142 return False;
1145 count = 0;
1146 for (i = 0; i < br_lck->num_locks; i++) {
1147 struct lock_struct *lock = &locks[i];
1148 unsigned int tmp_count;
1150 /* Only remove our own locks - ignore fnum. */
1151 if (!brl_same_context(&lock->context, &plock->context)) {
1152 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1153 count++;
1154 continue;
1157 if (lock->lock_flav == WINDOWS_LOCK) {
1158 /* Do any Windows flavour locks conflict ? */
1159 if (brl_conflict(lock, plock)) {
1160 TALLOC_FREE(tp);
1161 return false;
1163 /* Just copy the Windows lock into the new array. */
1164 memcpy(&tp[count], lock, sizeof(struct lock_struct));
1165 count++;
1166 continue;
1169 /* Work out overlaps. */
1170 tmp_count = brlock_posix_split_merge(&tp[count], lock, plock);
1172 if (tmp_count == 0) {
1173 /* plock overlapped the existing lock completely,
1174 or replaced it. Don't copy the existing lock. */
1175 overlap_found = true;
1176 } else if (tmp_count == 1) {
1177 /* Either no overlap, (simple copy of existing lock) or
1178 * an overlap of an existing lock. */
1179 /* If the lock changed size, we had an overlap. */
1180 if (tp[count].size != lock->size) {
1181 overlap_found = true;
1183 count += tmp_count;
1184 } else if (tmp_count == 2) {
1185 /* We split a lock range in two. */
1186 overlap_found = true;
1187 count += tmp_count;
1189 /* Optimisation... */
1190 /* We know we're finished here as we can't overlap any
1191 more POSIX locks. Copy the rest of the lock array. */
1193 if (i < br_lck->num_locks - 1) {
1194 memcpy(&tp[count], &locks[i+1],
1195 sizeof(*locks)*((br_lck->num_locks-1) - i));
1196 count += ((br_lck->num_locks-1) - i);
1198 break;
1203 if (!overlap_found) {
1204 /* Just ignore - no change. */
1205 TALLOC_FREE(tp);
1206 DEBUG(10,("brl_unlock_posix: No overlap - unlocked.\n"));
1207 return True;
1210 /* Unlock any POSIX regions. */
1211 if(lp_posix_locking(br_lck->fsp->conn->params)) {
1212 release_posix_lock_posix_flavour(br_lck->fsp,
1213 plock->start,
1214 plock->size,
1215 &plock->context,
1217 count);
1220 /* Realloc so we don't leak entries per unlock call. */
1221 if (count) {
1222 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
1223 if (!tp) {
1224 DEBUG(10,("brl_unlock_posix: realloc fail\n"));
1225 return False;
1227 } else {
1228 /* We deleted the last lock. */
1229 TALLOC_FREE(tp);
1230 tp = NULL;
1233 contend_level2_oplocks_end(br_lck->fsp,
1234 LEVEL2_CONTEND_POSIX_BRL);
1236 br_lck->num_locks = count;
1237 TALLOC_FREE(br_lck->lock_data);
1238 locks = tp;
1239 br_lck->lock_data = tp;
1240 br_lck->modified = True;
1242 return True;
1245 /****************************************************************************
1246 Unlock a range of bytes.
1247 ****************************************************************************/
1249 bool brl_unlock(struct byte_range_lock *br_lck,
1250 uint64_t smblctx,
1251 struct server_id pid,
1252 br_off start,
1253 br_off size,
1254 enum brl_flavour lock_flav)
1256 struct lock_struct lock;
1258 lock.context.smblctx = smblctx;
1259 lock.context.pid = pid;
1260 lock.context.tid = br_lck->fsp->conn->cnum;
1261 lock.start = start;
1262 lock.size = size;
1263 lock.fnum = br_lck->fsp->fnum;
1264 lock.lock_type = UNLOCK_LOCK;
1265 lock.lock_flav = lock_flav;
1267 if (lock_flav == WINDOWS_LOCK) {
1268 return SMB_VFS_BRL_UNLOCK_WINDOWS(
1269 br_lck->fsp->conn, br_lck, &lock);
1270 } else {
1271 return brl_unlock_posix(br_lck, &lock);
1275 /****************************************************************************
1276 Test if we could add a lock if we wanted to.
1277 Returns True if the region required is currently unlocked, False if locked.
1278 ****************************************************************************/
1280 bool brl_locktest(struct byte_range_lock *br_lck,
1281 const struct lock_struct *rw_probe)
1283 bool ret = True;
1284 unsigned int i;
1285 struct lock_struct *locks = br_lck->lock_data;
1286 files_struct *fsp = br_lck->fsp;
1288 /* Make sure existing locks don't conflict */
1289 for (i=0; i < br_lck->num_locks; i++) {
1291 * Our own locks don't conflict.
1293 if (brl_conflict_other(&locks[i], rw_probe)) {
1294 if (br_lck->record == NULL) {
1295 /* readonly */
1296 return false;
1299 if (!serverid_exists(&locks[i].context.pid)) {
1300 locks[i].context.pid.pid = 0;
1301 br_lck->modified = true;
1302 continue;
1305 return False;
1310 * There is no lock held by an SMB daemon, check to
1311 * see if there is a POSIX lock from a UNIX or NFS process.
1312 * This only conflicts with Windows locks, not POSIX locks.
1315 if(lp_posix_locking(fsp->conn->params) &&
1316 (rw_probe->lock_flav == WINDOWS_LOCK)) {
1318 * Make copies -- is_posix_locked might modify the values
1321 br_off start = rw_probe->start;
1322 br_off size = rw_probe->size;
1323 enum brl_type lock_type = rw_probe->lock_type;
1325 ret = is_posix_locked(fsp, &start, &size, &lock_type, WINDOWS_LOCK);
1327 DEBUG(10, ("brl_locktest: posix start=%ju len=%ju %s for %s "
1328 "file %s\n", (uintmax_t)start, (uintmax_t)size,
1329 ret ? "locked" : "unlocked",
1330 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1332 /* We need to return the inverse of is_posix_locked. */
1333 ret = !ret;
1336 /* no conflicts - we could have added it */
1337 return ret;
1340 /****************************************************************************
1341 Query for existing locks.
1342 ****************************************************************************/
1344 NTSTATUS brl_lockquery(struct byte_range_lock *br_lck,
1345 uint64_t *psmblctx,
1346 struct server_id pid,
1347 br_off *pstart,
1348 br_off *psize,
1349 enum brl_type *plock_type,
1350 enum brl_flavour lock_flav)
1352 unsigned int i;
1353 struct lock_struct lock;
1354 const struct lock_struct *locks = br_lck->lock_data;
1355 files_struct *fsp = br_lck->fsp;
1357 lock.context.smblctx = *psmblctx;
1358 lock.context.pid = pid;
1359 lock.context.tid = br_lck->fsp->conn->cnum;
1360 lock.start = *pstart;
1361 lock.size = *psize;
1362 lock.fnum = fsp->fnum;
1363 lock.lock_type = *plock_type;
1364 lock.lock_flav = lock_flav;
1366 /* Make sure existing locks don't conflict */
1367 for (i=0; i < br_lck->num_locks; i++) {
1368 const struct lock_struct *exlock = &locks[i];
1369 bool conflict = False;
1371 if (exlock->lock_flav == WINDOWS_LOCK) {
1372 conflict = brl_conflict(exlock, &lock);
1373 } else {
1374 conflict = brl_conflict_posix(exlock, &lock);
1377 if (conflict) {
1378 *psmblctx = exlock->context.smblctx;
1379 *pstart = exlock->start;
1380 *psize = exlock->size;
1381 *plock_type = exlock->lock_type;
1382 return NT_STATUS_LOCK_NOT_GRANTED;
1387 * There is no lock held by an SMB daemon, check to
1388 * see if there is a POSIX lock from a UNIX or NFS process.
1391 if(lp_posix_locking(fsp->conn->params)) {
1392 bool ret = is_posix_locked(fsp, pstart, psize, plock_type, POSIX_LOCK);
1394 DEBUG(10, ("brl_lockquery: posix start=%ju len=%ju %s for %s "
1395 "file %s\n", (uintmax_t)*pstart,
1396 (uintmax_t)*psize, ret ? "locked" : "unlocked",
1397 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1399 if (ret) {
1400 /* Hmmm. No clue what to set smblctx to - use -1. */
1401 *psmblctx = 0xFFFFFFFFFFFFFFFFLL;
1402 return NT_STATUS_LOCK_NOT_GRANTED;
1406 return NT_STATUS_OK;
1410 /****************************************************************************
1411 Remove any locks associated with a open file.
1412 We return True if this process owns any other Windows locks on this
1413 fd and so we should not immediately close the fd.
1414 ****************************************************************************/
1416 void brl_close_fnum(struct byte_range_lock *br_lck)
1418 files_struct *fsp = br_lck->fsp;
1419 uint32_t tid = fsp->conn->cnum;
1420 uint64_t fnum = fsp->fnum;
1421 unsigned int i;
1422 struct lock_struct *locks = br_lck->lock_data;
1423 struct server_id pid = messaging_server_id(fsp->conn->sconn->msg_ctx);
1424 struct lock_struct *locks_copy;
1425 unsigned int num_locks_copy;
1427 /* Copy the current lock array. */
1428 if (br_lck->num_locks) {
1429 locks_copy = (struct lock_struct *)talloc_memdup(br_lck, locks, br_lck->num_locks * sizeof(struct lock_struct));
1430 if (!locks_copy) {
1431 smb_panic("brl_close_fnum: talloc failed");
1433 } else {
1434 locks_copy = NULL;
1437 num_locks_copy = br_lck->num_locks;
1439 for (i=0; i < num_locks_copy; i++) {
1440 struct lock_struct *lock = &locks_copy[i];
1442 if (lock->context.tid == tid &&
1443 server_id_equal(&lock->context.pid, &pid) &&
1444 (lock->fnum == fnum)) {
1445 brl_unlock(
1446 br_lck,
1447 lock->context.smblctx,
1448 pid,
1449 lock->start,
1450 lock->size,
1451 lock->lock_flav);
1456 bool brl_mark_disconnected(struct files_struct *fsp)
1458 uint32_t tid = fsp->conn->cnum;
1459 uint64_t smblctx;
1460 uint64_t fnum = fsp->fnum;
1461 unsigned int i;
1462 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1463 struct byte_range_lock *br_lck = NULL;
1465 if (fsp->op == NULL) {
1466 return false;
1469 smblctx = fsp->op->global->open_persistent_id;
1471 if (!fsp->op->global->durable) {
1472 return false;
1475 if (fsp->current_lock_count == 0) {
1476 return true;
1479 br_lck = brl_get_locks(talloc_tos(), fsp);
1480 if (br_lck == NULL) {
1481 return false;
1484 for (i=0; i < br_lck->num_locks; i++) {
1485 struct lock_struct *lock = &br_lck->lock_data[i];
1488 * as this is a durable handle, we only expect locks
1489 * of the current file handle!
1492 if (lock->context.smblctx != smblctx) {
1493 TALLOC_FREE(br_lck);
1494 return false;
1497 if (lock->context.tid != tid) {
1498 TALLOC_FREE(br_lck);
1499 return false;
1502 if (!server_id_equal(&lock->context.pid, &self)) {
1503 TALLOC_FREE(br_lck);
1504 return false;
1507 if (lock->fnum != fnum) {
1508 TALLOC_FREE(br_lck);
1509 return false;
1512 server_id_set_disconnected(&lock->context.pid);
1513 lock->context.tid = TID_FIELD_INVALID;
1514 lock->fnum = FNUM_FIELD_INVALID;
1517 br_lck->modified = true;
1518 TALLOC_FREE(br_lck);
1519 return true;
1522 bool brl_reconnect_disconnected(struct files_struct *fsp)
1524 uint32_t tid = fsp->conn->cnum;
1525 uint64_t smblctx;
1526 uint64_t fnum = fsp->fnum;
1527 unsigned int i;
1528 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1529 struct byte_range_lock *br_lck = NULL;
1531 if (fsp->op == NULL) {
1532 return false;
1535 smblctx = fsp->op->global->open_persistent_id;
1537 if (!fsp->op->global->durable) {
1538 return false;
1542 * When reconnecting, we do not want to validate the brlock entries
1543 * and thereby remove our own (disconnected) entries but reactivate
1544 * them instead.
1547 br_lck = brl_get_locks(talloc_tos(), fsp);
1548 if (br_lck == NULL) {
1549 return false;
1552 if (br_lck->num_locks == 0) {
1553 TALLOC_FREE(br_lck);
1554 return true;
1557 for (i=0; i < br_lck->num_locks; i++) {
1558 struct lock_struct *lock = &br_lck->lock_data[i];
1561 * as this is a durable handle we only expect locks
1562 * of the current file handle!
1565 if (lock->context.smblctx != smblctx) {
1566 TALLOC_FREE(br_lck);
1567 return false;
1570 if (lock->context.tid != TID_FIELD_INVALID) {
1571 TALLOC_FREE(br_lck);
1572 return false;
1575 if (!server_id_is_disconnected(&lock->context.pid)) {
1576 TALLOC_FREE(br_lck);
1577 return false;
1580 if (lock->fnum != FNUM_FIELD_INVALID) {
1581 TALLOC_FREE(br_lck);
1582 return false;
1585 lock->context.pid = self;
1586 lock->context.tid = tid;
1587 lock->fnum = fnum;
1590 fsp->current_lock_count = br_lck->num_locks;
1591 br_lck->modified = true;
1592 TALLOC_FREE(br_lck);
1593 return true;
1596 struct brl_forall_cb {
1597 void (*fn)(struct file_id id, struct server_id pid,
1598 enum brl_type lock_type,
1599 enum brl_flavour lock_flav,
1600 br_off start, br_off size,
1601 void *private_data);
1602 void *private_data;
1605 /****************************************************************************
1606 Traverse the whole database with this function, calling traverse_callback
1607 on each lock.
1608 ****************************************************************************/
1610 static int brl_traverse_fn(struct db_record *rec, void *state)
1612 struct brl_forall_cb *cb = (struct brl_forall_cb *)state;
1613 struct lock_struct *locks;
1614 struct file_id *key;
1615 unsigned int i;
1616 unsigned int num_locks = 0;
1617 TDB_DATA dbkey;
1618 TDB_DATA value;
1620 dbkey = dbwrap_record_get_key(rec);
1621 value = dbwrap_record_get_value(rec);
1623 /* In a traverse function we must make a copy of
1624 dbuf before modifying it. */
1626 locks = (struct lock_struct *)talloc_memdup(
1627 talloc_tos(), value.dptr, value.dsize);
1628 if (!locks) {
1629 return -1; /* Terminate traversal. */
1632 key = (struct file_id *)dbkey.dptr;
1633 num_locks = value.dsize/sizeof(*locks);
1635 if (cb->fn) {
1636 for ( i=0; i<num_locks; i++) {
1637 cb->fn(*key,
1638 locks[i].context.pid,
1639 locks[i].lock_type,
1640 locks[i].lock_flav,
1641 locks[i].start,
1642 locks[i].size,
1643 cb->private_data);
1647 TALLOC_FREE(locks);
1648 return 0;
1651 /*******************************************************************
1652 Call the specified function on each lock in the database.
1653 ********************************************************************/
1655 int brl_forall(void (*fn)(struct file_id id, struct server_id pid,
1656 enum brl_type lock_type,
1657 enum brl_flavour lock_flav,
1658 br_off start, br_off size,
1659 void *private_data),
1660 void *private_data)
1662 struct brl_forall_cb cb;
1663 NTSTATUS status;
1664 int count = 0;
1666 if (!brlock_db) {
1667 return 0;
1669 cb.fn = fn;
1670 cb.private_data = private_data;
1671 status = dbwrap_traverse(brlock_db, brl_traverse_fn, &cb, &count);
1673 if (!NT_STATUS_IS_OK(status)) {
1674 return -1;
1675 } else {
1676 return count;
1680 /*******************************************************************
1681 Store a potentially modified set of byte range lock data back into
1682 the database.
1683 Unlock the record.
1684 ********************************************************************/
1686 static void byte_range_lock_flush(struct byte_range_lock *br_lck)
1688 unsigned i;
1689 struct lock_struct *locks = br_lck->lock_data;
1691 if (!br_lck->modified) {
1692 DEBUG(10, ("br_lck not modified\n"));
1693 goto done;
1696 i = 0;
1698 while (i < br_lck->num_locks) {
1699 if (locks[i].context.pid.pid == 0) {
1701 * Autocleanup, the process conflicted and does not
1702 * exist anymore.
1704 locks[i] = locks[br_lck->num_locks-1];
1705 br_lck->num_locks -= 1;
1706 } else {
1707 i += 1;
1711 if (br_lck->num_locks == 0) {
1712 /* No locks - delete this entry. */
1713 NTSTATUS status = dbwrap_record_delete(br_lck->record);
1714 if (!NT_STATUS_IS_OK(status)) {
1715 DEBUG(0, ("delete_rec returned %s\n",
1716 nt_errstr(status)));
1717 smb_panic("Could not delete byte range lock entry");
1719 } else {
1720 TDB_DATA data = {
1721 .dsize = br_lck->num_locks * sizeof(struct lock_struct),
1722 .dptr = (uint8_t *)br_lck->lock_data,
1724 NTSTATUS status;
1726 status = dbwrap_record_store(br_lck->record, data, TDB_REPLACE);
1727 if (!NT_STATUS_IS_OK(status)) {
1728 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
1729 smb_panic("Could not store byte range mode entry");
1733 DEBUG(10, ("seqnum=%d\n", dbwrap_get_seqnum(brlock_db)));
1735 done:
1736 br_lck->modified = false;
1737 TALLOC_FREE(br_lck->record);
1740 static int byte_range_lock_destructor(struct byte_range_lock *br_lck)
1742 byte_range_lock_flush(br_lck);
1743 return 0;
1746 static bool brl_parse_data(struct byte_range_lock *br_lck, TDB_DATA data)
1748 size_t data_len;
1750 if (data.dsize == 0) {
1751 return true;
1753 if (data.dsize % sizeof(struct lock_struct) != 0) {
1754 DEBUG(1, ("Invalid data size: %u\n", (unsigned)data.dsize));
1755 return false;
1758 br_lck->num_locks = data.dsize / sizeof(struct lock_struct);
1759 data_len = br_lck->num_locks * sizeof(struct lock_struct);
1761 br_lck->lock_data = talloc_memdup(br_lck, data.dptr, data_len);
1762 if (br_lck->lock_data == NULL) {
1763 DEBUG(1, ("talloc_memdup failed\n"));
1764 return false;
1766 return true;
1769 /*******************************************************************
1770 Fetch a set of byte range lock data from the database.
1771 Leave the record locked.
1772 TALLOC_FREE(brl) will release the lock in the destructor.
1773 ********************************************************************/
1775 struct byte_range_lock *brl_get_locks(TALLOC_CTX *mem_ctx, files_struct *fsp)
1777 TDB_DATA key, data;
1778 struct byte_range_lock *br_lck;
1780 br_lck = talloc_zero(mem_ctx, struct byte_range_lock);
1781 if (br_lck == NULL) {
1782 return NULL;
1785 br_lck->fsp = fsp;
1787 key.dptr = (uint8_t *)&fsp->file_id;
1788 key.dsize = sizeof(struct file_id);
1790 br_lck->record = dbwrap_fetch_locked(brlock_db, br_lck, key);
1792 if (br_lck->record == NULL) {
1793 DEBUG(3, ("Could not lock byte range lock entry\n"));
1794 TALLOC_FREE(br_lck);
1795 return NULL;
1798 data = dbwrap_record_get_value(br_lck->record);
1800 if (!brl_parse_data(br_lck, data)) {
1801 TALLOC_FREE(br_lck);
1802 return NULL;
1805 talloc_set_destructor(br_lck, byte_range_lock_destructor);
1807 if (DEBUGLEVEL >= 10) {
1808 unsigned int i;
1809 struct file_id_buf buf;
1810 struct lock_struct *locks = br_lck->lock_data;
1811 DBG_DEBUG("%u current locks on file_id %s\n",
1812 br_lck->num_locks,
1813 file_id_str_buf(fsp->file_id, &buf));
1814 for( i = 0; i < br_lck->num_locks; i++) {
1815 print_lock_struct(i, &locks[i]);
1819 return br_lck;
1822 struct byte_range_lock *brl_get_locks_for_locking(TALLOC_CTX *mem_ctx,
1823 files_struct *fsp,
1824 TALLOC_CTX *req_mem_ctx,
1825 const struct GUID *req_guid)
1827 struct byte_range_lock *br_lck = NULL;
1829 br_lck = brl_get_locks(mem_ctx, fsp);
1830 if (br_lck == NULL) {
1831 return NULL;
1833 SMB_ASSERT(req_mem_ctx != NULL);
1834 br_lck->req_mem_ctx = req_mem_ctx;
1835 SMB_ASSERT(req_guid != NULL);
1836 br_lck->req_guid = req_guid;
1838 return br_lck;
1841 struct brl_get_locks_readonly_state {
1842 TALLOC_CTX *mem_ctx;
1843 struct byte_range_lock **br_lock;
1846 static void brl_get_locks_readonly_parser(TDB_DATA key, TDB_DATA data,
1847 void *private_data)
1849 struct brl_get_locks_readonly_state *state =
1850 (struct brl_get_locks_readonly_state *)private_data;
1851 struct byte_range_lock *br_lck;
1853 br_lck = talloc_pooled_object(
1854 state->mem_ctx, struct byte_range_lock, 1, data.dsize);
1855 if (br_lck == NULL) {
1856 *state->br_lock = NULL;
1857 return;
1859 *br_lck = (struct byte_range_lock) { 0 };
1860 if (!brl_parse_data(br_lck, data)) {
1861 *state->br_lock = NULL;
1862 return;
1864 *state->br_lock = br_lck;
1867 struct byte_range_lock *brl_get_locks_readonly(files_struct *fsp)
1869 struct byte_range_lock *br_lock = NULL;
1870 struct brl_get_locks_readonly_state state;
1871 NTSTATUS status;
1873 DEBUG(10, ("seqnum=%d, fsp->brlock_seqnum=%d\n",
1874 dbwrap_get_seqnum(brlock_db), fsp->brlock_seqnum));
1876 if ((fsp->brlock_rec != NULL)
1877 && (dbwrap_get_seqnum(brlock_db) == fsp->brlock_seqnum)) {
1879 * We have cached the brlock_rec and the database did not
1880 * change.
1882 return fsp->brlock_rec;
1886 * Parse the record fresh from the database
1889 state.mem_ctx = fsp;
1890 state.br_lock = &br_lock;
1892 status = dbwrap_parse_record(
1893 brlock_db,
1894 make_tdb_data((uint8_t *)&fsp->file_id,
1895 sizeof(fsp->file_id)),
1896 brl_get_locks_readonly_parser, &state);
1898 if (NT_STATUS_EQUAL(status,NT_STATUS_NOT_FOUND)) {
1900 * No locks on this file. Return an empty br_lock.
1902 br_lock = talloc_zero(fsp, struct byte_range_lock);
1903 if (br_lock == NULL) {
1904 return NULL;
1907 } else if (!NT_STATUS_IS_OK(status)) {
1908 DEBUG(3, ("Could not parse byte range lock record: "
1909 "%s\n", nt_errstr(status)));
1910 return NULL;
1912 if (br_lock == NULL) {
1913 return NULL;
1916 br_lock->fsp = fsp;
1917 br_lock->modified = false;
1918 br_lock->record = NULL;
1921 * Cache the brlock struct, invalidated when the dbwrap_seqnum
1922 * changes. See beginning of this routine.
1924 TALLOC_FREE(fsp->brlock_rec);
1925 fsp->brlock_rec = br_lock;
1926 fsp->brlock_seqnum = dbwrap_get_seqnum(brlock_db);
1928 return br_lock;
1931 bool brl_cleanup_disconnected(struct file_id fid, uint64_t open_persistent_id)
1933 bool ret = false;
1934 TALLOC_CTX *frame = talloc_stackframe();
1935 TDB_DATA key, val;
1936 struct db_record *rec;
1937 struct lock_struct *lock;
1938 unsigned n, num;
1939 struct file_id_buf buf;
1940 NTSTATUS status;
1942 key = make_tdb_data((void*)&fid, sizeof(fid));
1944 rec = dbwrap_fetch_locked(brlock_db, frame, key);
1945 if (rec == NULL) {
1946 DBG_INFO("failed to fetch record for file %s\n",
1947 file_id_str_buf(fid, &buf));
1948 goto done;
1951 val = dbwrap_record_get_value(rec);
1952 lock = (struct lock_struct*)val.dptr;
1953 num = val.dsize / sizeof(struct lock_struct);
1954 if (lock == NULL) {
1955 DBG_DEBUG("no byte range locks for file %s\n",
1956 file_id_str_buf(fid, &buf));
1957 ret = true;
1958 goto done;
1961 for (n=0; n<num; n++) {
1962 struct lock_context *ctx = &lock[n].context;
1964 if (!server_id_is_disconnected(&ctx->pid)) {
1965 struct server_id_buf tmp;
1966 DBG_INFO("byte range lock "
1967 "%s used by server %s, do not cleanup\n",
1968 file_id_str_buf(fid, &buf),
1969 server_id_str_buf(ctx->pid, &tmp));
1970 goto done;
1973 if (ctx->smblctx != open_persistent_id) {
1974 DBG_INFO("byte range lock %s expected smblctx %"PRIu64" "
1975 "but found %"PRIu64", do not cleanup\n",
1976 file_id_str_buf(fid, &buf),
1977 open_persistent_id,
1978 ctx->smblctx);
1979 goto done;
1983 status = dbwrap_record_delete(rec);
1984 if (!NT_STATUS_IS_OK(status)) {
1985 DBG_INFO("failed to delete record "
1986 "for file %s from %s, open %"PRIu64": %s\n",
1987 file_id_str_buf(fid, &buf),
1988 dbwrap_name(brlock_db),
1989 open_persistent_id,
1990 nt_errstr(status));
1991 goto done;
1994 DBG_DEBUG("file %s cleaned up %u entries from open %"PRIu64"\n",
1995 file_id_str_buf(fid, &buf),
1996 num,
1997 open_persistent_id);
1999 ret = true;
2000 done:
2001 talloc_free(frame);
2002 return ret;