s3:locking: fix uninitialiazed variable in brl_get_locks_readonly_parser()
[obnox/samba/samba-obnox.git] / source3 / locking / brlock.c
1 /*
2    Unix SMB/CIFS implementation.
3    byte range locking code
4    Updated to handle range splits/merges.
5
6    Copyright (C) Andrew Tridgell 1992-2000
7    Copyright (C) Jeremy Allison 1992-2000
8
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.
13
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.
18
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/>.
21 */
22
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 */
26
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"
36
37 #undef DBGC_CLASS
38 #define DBGC_CLASS DBGC_LOCKING
39
40 #define ZERO_ZERO 0
41
42 /* The open brlock.tdb database. */
43
44 static struct db_context *brlock_db;
45
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;
53 };
54
55 /****************************************************************************
56  Debug info at level 10 for lock struct.
57 ****************************************************************************/
58
59 static void print_lock_struct(unsigned int i, const struct lock_struct *pls)
60 {
61         DEBUG(10,("[%u]: smblctx = %llu, tid = %u, pid = %s, ",
62                         i,
63                         (unsigned long long)pls->context.smblctx,
64                         (unsigned int)pls->context.tid,
65                         server_id_str(talloc_tos(), &pls->context.pid) ));
66
67         DEBUG(10, ("start = %ju, size = %ju, fnum = %ju, %s %s\n",
68                    (uintmax_t)pls->start,
69                    (uintmax_t)pls->size,
70                    (uintmax_t)pls->fnum,
71                    lock_type_name(pls->lock_type),
72                    lock_flav_name(pls->lock_flav)));
73 }
74
75 unsigned int brl_num_locks(const struct byte_range_lock *brl)
76 {
77         return brl->num_locks;
78 }
79
80 struct files_struct *brl_fsp(struct byte_range_lock *brl)
81 {
82         return brl->fsp;
83 }
84
85 uint32_t brl_num_read_oplocks(const struct byte_range_lock *brl)
86 {
87         return brl->num_read_oplocks;
88 }
89
90 void brl_set_num_read_oplocks(struct byte_range_lock *brl,
91                               uint32_t num_read_oplocks)
92 {
93         DEBUG(10, ("Setting num_read_oplocks to %"PRIu32"\n",
94                    num_read_oplocks));
95         SMB_ASSERT(brl->record != NULL); /* otherwise we're readonly */
96         brl->num_read_oplocks = num_read_oplocks;
97         brl->modified = true;
98 }
99
100 /****************************************************************************
101  See if two locking contexts are equal.
102 ****************************************************************************/
103
104 static bool brl_same_context(const struct lock_context *ctx1,
105                              const struct lock_context *ctx2)
106 {
107         return (serverid_equal(&ctx1->pid, &ctx2->pid) &&
108                 (ctx1->smblctx == ctx2->smblctx) &&
109                 (ctx1->tid == ctx2->tid));
110 }
111
112 /****************************************************************************
113  See if lck1 and lck2 overlap.
114 ****************************************************************************/
115
116 static bool brl_overlap(const struct lock_struct *lck1,
117                         const struct lock_struct *lck2)
118 {
119         /* XXX Remove for Win7 compatibility. */
120         /* this extra check is not redundant - it copes with locks
121            that go beyond the end of 64 bit file space */
122         if (lck1->size != 0 &&
123             lck1->start == lck2->start &&
124             lck1->size == lck2->size) {
125                 return True;
126         }
127
128         if (lck1->start >= (lck2->start+lck2->size) ||
129             lck2->start >= (lck1->start+lck1->size)) {
130                 return False;
131         }
132         return True;
133 }
134
135 /****************************************************************************
136  See if lock2 can be added when lock1 is in place.
137 ****************************************************************************/
138
139 static bool brl_conflict(const struct lock_struct *lck1,
140                          const struct lock_struct *lck2)
141 {
142         /* Ignore PENDING locks. */
143         if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
144                 return False;
145
146         /* Read locks never conflict. */
147         if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
148                 return False;
149         }
150
151         /* A READ lock can stack on top of a WRITE lock if they have the same
152          * context & fnum. */
153         if (lck1->lock_type == WRITE_LOCK && lck2->lock_type == READ_LOCK &&
154             brl_same_context(&lck1->context, &lck2->context) &&
155             lck1->fnum == lck2->fnum) {
156                 return False;
157         }
158
159         return brl_overlap(lck1, lck2);
160 }
161
162 /****************************************************************************
163  See if lock2 can be added when lock1 is in place - when both locks are POSIX
164  flavour. POSIX locks ignore fnum - they only care about dev/ino which we
165  know already match.
166 ****************************************************************************/
167
168 static bool brl_conflict_posix(const struct lock_struct *lck1,
169                                 const struct lock_struct *lck2)
170 {
171 #if defined(DEVELOPER)
172         SMB_ASSERT(lck1->lock_flav == POSIX_LOCK);
173         SMB_ASSERT(lck2->lock_flav == POSIX_LOCK);
174 #endif
175
176         /* Ignore PENDING locks. */
177         if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
178                 return False;
179
180         /* Read locks never conflict. */
181         if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
182                 return False;
183         }
184
185         /* Locks on the same context don't conflict. Ignore fnum. */
186         if (brl_same_context(&lck1->context, &lck2->context)) {
187                 return False;
188         }
189
190         /* One is read, the other write, or the context is different,
191            do they overlap ? */
192         return brl_overlap(lck1, lck2);
193 }
194
195 #if ZERO_ZERO
196 static bool brl_conflict1(const struct lock_struct *lck1,
197                          const struct lock_struct *lck2)
198 {
199         if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
200                 return False;
201
202         if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
203                 return False;
204         }
205
206         if (brl_same_context(&lck1->context, &lck2->context) &&
207             lck2->lock_type == READ_LOCK && lck1->fnum == lck2->fnum) {
208                 return False;
209         }
210
211         if (lck2->start == 0 && lck2->size == 0 && lck1->size != 0) {
212                 return True;
213         }
214
215         if (lck1->start >= (lck2->start + lck2->size) ||
216             lck2->start >= (lck1->start + lck1->size)) {
217                 return False;
218         }
219
220         return True;
221 }
222 #endif
223
224 /****************************************************************************
225  Check to see if this lock conflicts, but ignore our own locks on the
226  same fnum only. This is the read/write lock check code path.
227  This is never used in the POSIX lock case.
228 ****************************************************************************/
229
230 static bool brl_conflict_other(const struct lock_struct *lock,
231                                const struct lock_struct *rw_probe)
232 {
233         if (IS_PENDING_LOCK(lock->lock_type) ||
234             IS_PENDING_LOCK(rw_probe->lock_type)) {
235                 return False;
236         }
237
238         if (lock->lock_type == READ_LOCK && rw_probe->lock_type == READ_LOCK) {
239                 return False;
240         }
241
242         if (lock->lock_flav == POSIX_LOCK &&
243             rw_probe->lock_flav == POSIX_LOCK) {
244                 /*
245                  * POSIX flavour locks never conflict here - this is only called
246                  * in the read/write path.
247                  */
248                 return False;
249         }
250
251         if (!brl_overlap(lock, rw_probe)) {
252                 /*
253                  * I/O can only conflict when overlapping a lock, thus let it
254                  * pass
255                  */
256                 return false;
257         }
258
259         if (!brl_same_context(&lock->context, &rw_probe->context)) {
260                 /*
261                  * Different process, conflict
262                  */
263                 return true;
264         }
265
266         if (lock->fnum != rw_probe->fnum) {
267                 /*
268                  * Different file handle, conflict
269                  */
270                 return true;
271         }
272
273         if ((lock->lock_type == READ_LOCK) &&
274             (rw_probe->lock_type == WRITE_LOCK)) {
275                 /*
276                  * Incoming WRITE locks conflict with existing READ locks even
277                  * if the context is the same. JRA. See LOCKTEST7 in
278                  * smbtorture.
279                  */
280                 return true;
281         }
282
283         /*
284          * I/O request compatible with existing lock, let it pass without
285          * conflict
286          */
287
288         return false;
289 }
290
291 /****************************************************************************
292  Check if an unlock overlaps a pending lock.
293 ****************************************************************************/
294
295 static bool brl_pending_overlap(const struct lock_struct *lock, const struct lock_struct *pend_lock)
296 {
297         if ((lock->start <= pend_lock->start) && (lock->start + lock->size > pend_lock->start))
298                 return True;
299         if ((lock->start >= pend_lock->start) && (lock->start < pend_lock->start + pend_lock->size))
300                 return True;
301         return False;
302 }
303
304 /****************************************************************************
305  Amazingly enough, w2k3 "remembers" whether the last lock failure on a fnum
306  is the same as this one and changes its error code. I wonder if any
307  app depends on this ?
308 ****************************************************************************/
309
310 static NTSTATUS brl_lock_failed(files_struct *fsp,
311                                 const struct lock_struct *lock,
312                                 bool blocking_lock)
313 {
314         if (lock->start >= 0xEF000000 && (lock->start >> 63) == 0) {
315                 /* amazing the little things you learn with a test
316                    suite. Locks beyond this offset (as a 64 bit
317                    number!) always generate the conflict error code,
318                    unless the top bit is set */
319                 if (!blocking_lock) {
320                         fsp->last_lock_failure = *lock;
321                 }
322                 return NT_STATUS_FILE_LOCK_CONFLICT;
323         }
324
325         if (serverid_equal(&lock->context.pid, &fsp->last_lock_failure.context.pid) &&
326                         lock->context.tid == fsp->last_lock_failure.context.tid &&
327                         lock->fnum == fsp->last_lock_failure.fnum &&
328                         lock->start == fsp->last_lock_failure.start) {
329                 return NT_STATUS_FILE_LOCK_CONFLICT;
330         }
331
332         if (!blocking_lock) {
333                 fsp->last_lock_failure = *lock;
334         }
335         return NT_STATUS_LOCK_NOT_GRANTED;
336 }
337
338 /****************************************************************************
339  Open up the brlock.tdb database.
340 ****************************************************************************/
341
342 void brl_init(bool read_only)
343 {
344         int tdb_flags;
345         char *db_path;
346
347         if (brlock_db) {
348                 return;
349         }
350
351         tdb_flags = TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST|TDB_INCOMPATIBLE_HASH;
352
353         if (!lp_clustering()) {
354                 /*
355                  * We can't use the SEQNUM trick to cache brlock
356                  * entries in the clustering case because ctdb seqnum
357                  * propagation has a delay.
358                  */
359                 tdb_flags |= TDB_SEQNUM;
360         }
361
362         db_path = lock_path("brlock.tdb");
363         if (db_path == NULL) {
364                 DEBUG(0, ("out of memory!\n"));
365                 return;
366         }
367
368         brlock_db = db_open(NULL, db_path,
369                             SMB_OPEN_DATABASE_TDB_HASH_SIZE, tdb_flags,
370                             read_only?O_RDONLY:(O_RDWR|O_CREAT), 0644,
371                             DBWRAP_LOCK_ORDER_2, DBWRAP_FLAG_NONE);
372         if (!brlock_db) {
373                 DEBUG(0,("Failed to open byte range locking database %s\n",
374                          db_path));
375                 TALLOC_FREE(db_path);
376                 return;
377         }
378         TALLOC_FREE(db_path);
379 }
380
381 /****************************************************************************
382  Close down the brlock.tdb database.
383 ****************************************************************************/
384
385 void brl_shutdown(void)
386 {
387         TALLOC_FREE(brlock_db);
388 }
389
390 #if ZERO_ZERO
391 /****************************************************************************
392  Compare two locks for sorting.
393 ****************************************************************************/
394
395 static int lock_compare(const struct lock_struct *lck1,
396                          const struct lock_struct *lck2)
397 {
398         if (lck1->start != lck2->start) {
399                 return (lck1->start - lck2->start);
400         }
401         if (lck2->size != lck1->size) {
402                 return ((int)lck1->size - (int)lck2->size);
403         }
404         return 0;
405 }
406 #endif
407
408 /****************************************************************************
409  Lock a range of bytes - Windows lock semantics.
410 ****************************************************************************/
411
412 NTSTATUS brl_lock_windows_default(struct byte_range_lock *br_lck,
413     struct lock_struct *plock, bool blocking_lock)
414 {
415         unsigned int i;
416         files_struct *fsp = br_lck->fsp;
417         struct lock_struct *locks = br_lck->lock_data;
418         NTSTATUS status;
419
420         SMB_ASSERT(plock->lock_type != UNLOCK_LOCK);
421
422         if ((plock->start + plock->size - 1 < plock->start) &&
423                         plock->size != 0) {
424                 return NT_STATUS_INVALID_LOCK_RANGE;
425         }
426
427         for (i=0; i < br_lck->num_locks; i++) {
428                 /* Do any Windows or POSIX locks conflict ? */
429                 if (brl_conflict(&locks[i], plock)) {
430                         if (!serverid_exists(&locks[i].context.pid)) {
431                                 locks[i].context.pid.pid = 0;
432                                 br_lck->modified = true;
433                                 continue;
434                         }
435                         /* Remember who blocked us. */
436                         plock->context.smblctx = locks[i].context.smblctx;
437                         return brl_lock_failed(fsp,plock,blocking_lock);
438                 }
439 #if ZERO_ZERO
440                 if (plock->start == 0 && plock->size == 0 &&
441                                 locks[i].size == 0) {
442                         break;
443                 }
444 #endif
445         }
446
447         if (!IS_PENDING_LOCK(plock->lock_type)) {
448                 contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
449         }
450
451         /* We can get the Windows lock, now see if it needs to
452            be mapped into a lower level POSIX one, and if so can
453            we get it ? */
454
455         if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(fsp->conn->params)) {
456                 int errno_ret;
457                 if (!set_posix_lock_windows_flavour(fsp,
458                                 plock->start,
459                                 plock->size,
460                                 plock->lock_type,
461                                 &plock->context,
462                                 locks,
463                                 br_lck->num_locks,
464                                 &errno_ret)) {
465
466                         /* We don't know who blocked us. */
467                         plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
468
469                         if (errno_ret == EACCES || errno_ret == EAGAIN) {
470                                 status = NT_STATUS_FILE_LOCK_CONFLICT;
471                                 goto fail;
472                         } else {
473                                 status = map_nt_error_from_unix(errno);
474                                 goto fail;
475                         }
476                 }
477         }
478
479         /* no conflicts - add it to the list of locks */
480         locks = talloc_realloc(br_lck, locks, struct lock_struct,
481                                (br_lck->num_locks + 1));
482         if (!locks) {
483                 status = NT_STATUS_NO_MEMORY;
484                 goto fail;
485         }
486
487         memcpy(&locks[br_lck->num_locks], plock, sizeof(struct lock_struct));
488         br_lck->num_locks += 1;
489         br_lck->lock_data = locks;
490         br_lck->modified = True;
491
492         return NT_STATUS_OK;
493  fail:
494         if (!IS_PENDING_LOCK(plock->lock_type)) {
495                 contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WINDOWS_BRL);
496         }
497         return status;
498 }
499
500 /****************************************************************************
501  Cope with POSIX range splits and merges.
502 ****************************************************************************/
503
504 static unsigned int brlock_posix_split_merge(struct lock_struct *lck_arr,       /* Output array. */
505                                                 struct lock_struct *ex,         /* existing lock. */
506                                                 struct lock_struct *plock)      /* proposed lock. */
507 {
508         bool lock_types_differ = (ex->lock_type != plock->lock_type);
509
510         /* We can't merge non-conflicting locks on different context - ignore fnum. */
511
512         if (!brl_same_context(&ex->context, &plock->context)) {
513                 /* Just copy. */
514                 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
515                 return 1;
516         }
517
518         /* We now know we have the same context. */
519
520         /* Did we overlap ? */
521
522 /*********************************************
523                                         +---------+
524                                         | ex      |
525                                         +---------+
526                          +-------+
527                          | plock |
528                          +-------+
529 OR....
530         +---------+
531         |  ex     |
532         +---------+
533 **********************************************/
534
535         if ( (ex->start > (plock->start + plock->size)) ||
536                 (plock->start > (ex->start + ex->size))) {
537
538                 /* No overlap with this lock - copy existing. */
539
540                 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
541                 return 1;
542         }
543
544 /*********************************************
545         +---------------------------+
546         |          ex               |
547         +---------------------------+
548         +---------------------------+
549         |       plock               | -> replace with plock.
550         +---------------------------+
551 OR
552              +---------------+
553              |       ex      |
554              +---------------+
555         +---------------------------+
556         |       plock               | -> replace with plock.
557         +---------------------------+
558
559 **********************************************/
560
561         if ( (ex->start >= plock->start) &&
562                 (ex->start + ex->size <= plock->start + plock->size) ) {
563
564                 /* Replace - discard existing lock. */
565
566                 return 0;
567         }
568
569 /*********************************************
570 Adjacent after.
571                         +-------+
572                         |  ex   |
573                         +-------+
574         +---------------+
575         |   plock       |
576         +---------------+
577
578 BECOMES....
579         +---------------+-------+
580         |   plock       | ex    | - different lock types.
581         +---------------+-------+
582 OR.... (merge)
583         +-----------------------+
584         |   plock               | - same lock type.
585         +-----------------------+
586 **********************************************/
587
588         if (plock->start + plock->size == ex->start) {
589
590                 /* If the lock types are the same, we merge, if different, we
591                    add the remainder of the old lock. */
592
593                 if (lock_types_differ) {
594                         /* Add existing. */
595                         memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
596                         return 1;
597                 } else {
598                         /* Merge - adjust incoming lock as we may have more
599                          * merging to come. */
600                         plock->size += ex->size;
601                         return 0;
602                 }
603         }
604
605 /*********************************************
606 Adjacent before.
607         +-------+
608         |  ex   |
609         +-------+
610                 +---------------+
611                 |   plock       |
612                 +---------------+
613 BECOMES....
614         +-------+---------------+
615         | ex    |   plock       | - different lock types
616         +-------+---------------+
617
618 OR.... (merge)
619         +-----------------------+
620         |      plock            | - same lock type.
621         +-----------------------+
622
623 **********************************************/
624
625         if (ex->start + ex->size == plock->start) {
626
627                 /* If the lock types are the same, we merge, if different, we
628                    add the existing lock. */
629
630                 if (lock_types_differ) {
631                         memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
632                         return 1;
633                 } else {
634                         /* Merge - adjust incoming lock as we may have more
635                          * merging to come. */
636                         plock->start = ex->start;
637                         plock->size += ex->size;
638                         return 0;
639                 }
640         }
641
642 /*********************************************
643 Overlap after.
644         +-----------------------+
645         |          ex           |
646         +-----------------------+
647         +---------------+
648         |   plock       |
649         +---------------+
650 OR
651                +----------------+
652                |       ex       |
653                +----------------+
654         +---------------+
655         |   plock       |
656         +---------------+
657
658 BECOMES....
659         +---------------+-------+
660         |   plock       | ex    | - different lock types.
661         +---------------+-------+
662 OR.... (merge)
663         +-----------------------+
664         |   plock               | - same lock type.
665         +-----------------------+
666 **********************************************/
667
668         if ( (ex->start >= plock->start) &&
669                 (ex->start <= plock->start + plock->size) &&
670                 (ex->start + ex->size > plock->start + plock->size) ) {
671
672                 /* If the lock types are the same, we merge, if different, we
673                    add the remainder of the old lock. */
674
675                 if (lock_types_differ) {
676                         /* Add remaining existing. */
677                         memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
678                         /* Adjust existing start and size. */
679                         lck_arr[0].start = plock->start + plock->size;
680                         lck_arr[0].size = (ex->start + ex->size) - (plock->start + plock->size);
681                         return 1;
682                 } else {
683                         /* Merge - adjust incoming lock as we may have more
684                          * merging to come. */
685                         plock->size += (ex->start + ex->size) - (plock->start + plock->size);
686                         return 0;
687                 }
688         }
689
690 /*********************************************
691 Overlap before.
692         +-----------------------+
693         |  ex                   |
694         +-----------------------+
695                 +---------------+
696                 |   plock       |
697                 +---------------+
698 OR
699         +-------------+
700         |  ex         |
701         +-------------+
702                 +---------------+
703                 |   plock       |
704                 +---------------+
705
706 BECOMES....
707         +-------+---------------+
708         | ex    |   plock       | - different lock types
709         +-------+---------------+
710
711 OR.... (merge)
712         +-----------------------+
713         |      plock            | - same lock type.
714         +-----------------------+
715
716 **********************************************/
717
718         if ( (ex->start < plock->start) &&
719                         (ex->start + ex->size >= plock->start) &&
720                         (ex->start + ex->size <= plock->start + plock->size) ) {
721
722                 /* If the lock types are the same, we merge, if different, we
723                    add the truncated old lock. */
724
725                 if (lock_types_differ) {
726                         memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
727                         /* Adjust existing size. */
728                         lck_arr[0].size = plock->start - ex->start;
729                         return 1;
730                 } else {
731                         /* Merge - adjust incoming lock as we may have more
732                          * merging to come. MUST ADJUST plock SIZE FIRST ! */
733                         plock->size += (plock->start - ex->start);
734                         plock->start = ex->start;
735                         return 0;
736                 }
737         }
738
739 /*********************************************
740 Complete overlap.
741         +---------------------------+
742         |        ex                 |
743         +---------------------------+
744                 +---------+
745                 |  plock  |
746                 +---------+
747 BECOMES.....
748         +-------+---------+---------+
749         | ex    |  plock  | ex      | - different lock types.
750         +-------+---------+---------+
751 OR
752         +---------------------------+
753         |        plock              | - same lock type.
754         +---------------------------+
755 **********************************************/
756
757         if ( (ex->start < plock->start) && (ex->start + ex->size > plock->start + plock->size) ) {
758
759                 if (lock_types_differ) {
760
761                         /* We have to split ex into two locks here. */
762
763                         memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
764                         memcpy(&lck_arr[1], ex, sizeof(struct lock_struct));
765
766                         /* Adjust first existing size. */
767                         lck_arr[0].size = plock->start - ex->start;
768
769                         /* Adjust second existing start and size. */
770                         lck_arr[1].start = plock->start + plock->size;
771                         lck_arr[1].size = (ex->start + ex->size) - (plock->start + plock->size);
772                         return 2;
773                 } else {
774                         /* Just eat the existing locks, merge them into plock. */
775                         plock->start = ex->start;
776                         plock->size = ex->size;
777                         return 0;
778                 }
779         }
780
781         /* Never get here. */
782         smb_panic("brlock_posix_split_merge");
783         /* Notreached. */
784
785         /* Keep some compilers happy. */
786         return 0;
787 }
788
789 /****************************************************************************
790  Lock a range of bytes - POSIX lock semantics.
791  We must cope with range splits and merges.
792 ****************************************************************************/
793
794 static NTSTATUS brl_lock_posix(struct messaging_context *msg_ctx,
795                                struct byte_range_lock *br_lck,
796                                struct lock_struct *plock)
797 {
798         unsigned int i, count, posix_count;
799         struct lock_struct *locks = br_lck->lock_data;
800         struct lock_struct *tp;
801         bool signal_pending_read = False;
802         bool break_oplocks = false;
803         NTSTATUS status;
804
805         /* No zero-zero locks for POSIX. */
806         if (plock->start == 0 && plock->size == 0) {
807                 return NT_STATUS_INVALID_PARAMETER;
808         }
809
810         /* Don't allow 64-bit lock wrap. */
811         if (plock->start + plock->size - 1 < plock->start) {
812                 return NT_STATUS_INVALID_PARAMETER;
813         }
814
815         /* The worst case scenario here is we have to split an
816            existing POSIX lock range into two, and add our lock,
817            so we need at most 2 more entries. */
818
819         tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 2);
820         if (!tp) {
821                 return NT_STATUS_NO_MEMORY;
822         }
823
824         count = posix_count = 0;
825
826         for (i=0; i < br_lck->num_locks; i++) {
827                 struct lock_struct *curr_lock = &locks[i];
828
829                 /* If we have a pending read lock, a lock downgrade should
830                    trigger a lock re-evaluation. */
831                 if (curr_lock->lock_type == PENDING_READ_LOCK &&
832                                 brl_pending_overlap(plock, curr_lock)) {
833                         signal_pending_read = True;
834                 }
835
836                 if (curr_lock->lock_flav == WINDOWS_LOCK) {
837                         /* Do any Windows flavour locks conflict ? */
838                         if (brl_conflict(curr_lock, plock)) {
839                                 if (!serverid_exists(&curr_lock->context.pid)) {
840                                         curr_lock->context.pid.pid = 0;
841                                         br_lck->modified = true;
842                                         continue;
843                                 }
844                                 /* No games with error messages. */
845                                 TALLOC_FREE(tp);
846                                 /* Remember who blocked us. */
847                                 plock->context.smblctx = curr_lock->context.smblctx;
848                                 return NT_STATUS_FILE_LOCK_CONFLICT;
849                         }
850                         /* Just copy the Windows lock into the new array. */
851                         memcpy(&tp[count], curr_lock, sizeof(struct lock_struct));
852                         count++;
853                 } else {
854                         unsigned int tmp_count = 0;
855
856                         /* POSIX conflict semantics are different. */
857                         if (brl_conflict_posix(curr_lock, plock)) {
858                                 if (!serverid_exists(&curr_lock->context.pid)) {
859                                         curr_lock->context.pid.pid = 0;
860                                         br_lck->modified = true;
861                                         continue;
862                                 }
863                                 /* Can't block ourselves with POSIX locks. */
864                                 /* No games with error messages. */
865                                 TALLOC_FREE(tp);
866                                 /* Remember who blocked us. */
867                                 plock->context.smblctx = curr_lock->context.smblctx;
868                                 return NT_STATUS_FILE_LOCK_CONFLICT;
869                         }
870
871                         /* Work out overlaps. */
872                         tmp_count += brlock_posix_split_merge(&tp[count], curr_lock, plock);
873                         posix_count += tmp_count;
874                         count += tmp_count;
875                 }
876         }
877
878         /*
879          * Break oplocks while we hold a brl. Since lock() and unlock() calls
880          * are not symetric with POSIX semantics, we cannot guarantee our
881          * contend_level2_oplocks_begin/end calls will be acquired and
882          * released one-for-one as with Windows semantics. Therefore we only
883          * call contend_level2_oplocks_begin if this is the first POSIX brl on
884          * the file.
885          */
886         break_oplocks = (!IS_PENDING_LOCK(plock->lock_type) &&
887                          posix_count == 0);
888         if (break_oplocks) {
889                 contend_level2_oplocks_begin(br_lck->fsp,
890                                              LEVEL2_CONTEND_POSIX_BRL);
891         }
892
893         /* Try and add the lock in order, sorted by lock start. */
894         for (i=0; i < count; i++) {
895                 struct lock_struct *curr_lock = &tp[i];
896
897                 if (curr_lock->start <= plock->start) {
898                         continue;
899                 }
900         }
901
902         if (i < count) {
903                 memmove(&tp[i+1], &tp[i],
904                         (count - i)*sizeof(struct lock_struct));
905         }
906         memcpy(&tp[i], plock, sizeof(struct lock_struct));
907         count++;
908
909         /* We can get the POSIX lock, now see if it needs to
910            be mapped into a lower level POSIX one, and if so can
911            we get it ? */
912
913         if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(br_lck->fsp->conn->params)) {
914                 int errno_ret;
915
916                 /* The lower layer just needs to attempt to
917                    get the system POSIX lock. We've weeded out
918                    any conflicts above. */
919
920                 if (!set_posix_lock_posix_flavour(br_lck->fsp,
921                                 plock->start,
922                                 plock->size,
923                                 plock->lock_type,
924                                 &errno_ret)) {
925
926                         /* We don't know who blocked us. */
927                         plock->context.smblctx = 0xFFFFFFFFFFFFFFFFLL;
928
929                         if (errno_ret == EACCES || errno_ret == EAGAIN) {
930                                 TALLOC_FREE(tp);
931                                 status = NT_STATUS_FILE_LOCK_CONFLICT;
932                                 goto fail;
933                         } else {
934                                 TALLOC_FREE(tp);
935                                 status = map_nt_error_from_unix(errno);
936                                 goto fail;
937                         }
938                 }
939         }
940
941         /* If we didn't use all the allocated size,
942          * Realloc so we don't leak entries per lock call. */
943         if (count < br_lck->num_locks + 2) {
944                 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
945                 if (!tp) {
946                         status = NT_STATUS_NO_MEMORY;
947                         goto fail;
948                 }
949         }
950
951         br_lck->num_locks = count;
952         TALLOC_FREE(br_lck->lock_data);
953         br_lck->lock_data = tp;
954         locks = tp;
955         br_lck->modified = True;
956
957         /* A successful downgrade from write to read lock can trigger a lock
958            re-evalutation where waiting readers can now proceed. */
959
960         if (signal_pending_read) {
961                 /* Send unlock messages to any pending read waiters that overlap. */
962                 for (i=0; i < br_lck->num_locks; i++) {
963                         struct lock_struct *pend_lock = &locks[i];
964
965                         /* Ignore non-pending locks. */
966                         if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
967                                 continue;
968                         }
969
970                         if (pend_lock->lock_type == PENDING_READ_LOCK &&
971                                         brl_pending_overlap(plock, pend_lock)) {
972                                 DEBUG(10,("brl_lock_posix: sending unlock message to pid %s\n",
973                                         procid_str_static(&pend_lock->context.pid )));
974
975                                 messaging_send(msg_ctx, pend_lock->context.pid,
976                                                MSG_SMB_UNLOCK, &data_blob_null);
977                         }
978                 }
979         }
980
981         return NT_STATUS_OK;
982  fail:
983         if (break_oplocks) {
984                 contend_level2_oplocks_end(br_lck->fsp,
985                                            LEVEL2_CONTEND_POSIX_BRL);
986         }
987         return status;
988 }
989
990 NTSTATUS smb_vfs_call_brl_lock_windows(struct vfs_handle_struct *handle,
991                                        struct byte_range_lock *br_lck,
992                                        struct lock_struct *plock,
993                                        bool blocking_lock)
994 {
995         VFS_FIND(brl_lock_windows);
996         return handle->fns->brl_lock_windows_fn(handle, br_lck, plock,
997                                                 blocking_lock);
998 }
999
1000 /****************************************************************************
1001  Lock a range of bytes.
1002 ****************************************************************************/
1003
1004 NTSTATUS brl_lock(struct messaging_context *msg_ctx,
1005                 struct byte_range_lock *br_lck,
1006                 uint64_t smblctx,
1007                 struct server_id pid,
1008                 br_off start,
1009                 br_off size,
1010                 enum brl_type lock_type,
1011                 enum brl_flavour lock_flav,
1012                 bool blocking_lock,
1013                 uint64_t *psmblctx)
1014 {
1015         NTSTATUS ret;
1016         struct lock_struct lock;
1017
1018 #if !ZERO_ZERO
1019         if (start == 0 && size == 0) {
1020                 DEBUG(0,("client sent 0/0 lock - please report this\n"));
1021         }
1022 #endif
1023
1024         lock = (struct lock_struct) {
1025                 .context.smblctx = smblctx,
1026                 .context.pid = pid,
1027                 .context.tid = br_lck->fsp->conn->cnum,
1028                 .start = start,
1029                 .size = size,
1030                 .fnum = br_lck->fsp->fnum,
1031                 .lock_type = lock_type,
1032                 .lock_flav = lock_flav
1033         };
1034
1035         if (lock_flav == WINDOWS_LOCK) {
1036                 ret = SMB_VFS_BRL_LOCK_WINDOWS(br_lck->fsp->conn, br_lck,
1037                                                &lock, blocking_lock);
1038         } else {
1039                 ret = brl_lock_posix(msg_ctx, br_lck, &lock);
1040         }
1041
1042 #if ZERO_ZERO
1043         /* sort the lock list */
1044         TYPESAFE_QSORT(br_lck->lock_data, (size_t)br_lck->num_locks, lock_compare);
1045 #endif
1046
1047         /* If we're returning an error, return who blocked us. */
1048         if (!NT_STATUS_IS_OK(ret) && psmblctx) {
1049                 *psmblctx = lock.context.smblctx;
1050         }
1051         return ret;
1052 }
1053
1054 static void brl_delete_lock_struct(struct lock_struct *locks,
1055                                    unsigned num_locks,
1056                                    unsigned del_idx)
1057 {
1058         if (del_idx >= num_locks) {
1059                 return;
1060         }
1061         memmove(&locks[del_idx], &locks[del_idx+1],
1062                 sizeof(*locks) * (num_locks - del_idx - 1));
1063 }
1064
1065 /****************************************************************************
1066  Unlock a range of bytes - Windows semantics.
1067 ****************************************************************************/
1068
1069 bool brl_unlock_windows_default(struct messaging_context *msg_ctx,
1070                                struct byte_range_lock *br_lck,
1071                                const struct lock_struct *plock)
1072 {
1073         unsigned int i, j;
1074         struct lock_struct *locks = br_lck->lock_data;
1075         enum brl_type deleted_lock_type = READ_LOCK; /* shut the compiler up.... */
1076
1077         SMB_ASSERT(plock->lock_type == UNLOCK_LOCK);
1078
1079 #if ZERO_ZERO
1080         /* Delete write locks by preference... The lock list
1081            is sorted in the zero zero case. */
1082
1083         for (i = 0; i < br_lck->num_locks; i++) {
1084                 struct lock_struct *lock = &locks[i];
1085
1086                 if (lock->lock_type == WRITE_LOCK &&
1087                     brl_same_context(&lock->context, &plock->context) &&
1088                     lock->fnum == plock->fnum &&
1089                     lock->lock_flav == WINDOWS_LOCK &&
1090                     lock->start == plock->start &&
1091                     lock->size == plock->size) {
1092
1093                         /* found it - delete it */
1094                         deleted_lock_type = lock->lock_type;
1095                         break;
1096                 }
1097         }
1098
1099         if (i != br_lck->num_locks) {
1100                 /* We found it - don't search again. */
1101                 goto unlock_continue;
1102         }
1103 #endif
1104
1105         for (i = 0; i < br_lck->num_locks; i++) {
1106                 struct lock_struct *lock = &locks[i];
1107
1108                 if (IS_PENDING_LOCK(lock->lock_type)) {
1109                         continue;
1110                 }
1111
1112                 /* Only remove our own locks that match in start, size, and flavour. */
1113                 if (brl_same_context(&lock->context, &plock->context) &&
1114                                         lock->fnum == plock->fnum &&
1115                                         lock->lock_flav == WINDOWS_LOCK &&
1116                                         lock->start == plock->start &&
1117                                         lock->size == plock->size ) {
1118                         deleted_lock_type = lock->lock_type;
1119                         break;
1120                 }
1121         }
1122
1123         if (i == br_lck->num_locks) {
1124                 /* we didn't find it */
1125                 return False;
1126         }
1127
1128 #if ZERO_ZERO
1129   unlock_continue:
1130 #endif
1131
1132         brl_delete_lock_struct(locks, br_lck->num_locks, i);
1133         br_lck->num_locks -= 1;
1134         br_lck->modified = True;
1135
1136         /* Unlock the underlying POSIX regions. */
1137         if(lp_posix_locking(br_lck->fsp->conn->params)) {
1138                 release_posix_lock_windows_flavour(br_lck->fsp,
1139                                 plock->start,
1140                                 plock->size,
1141                                 deleted_lock_type,
1142                                 &plock->context,
1143                                 locks,
1144                                 br_lck->num_locks);
1145         }
1146
1147         /* Send unlock messages to any pending waiters that overlap. */
1148         for (j=0; j < br_lck->num_locks; j++) {
1149                 struct lock_struct *pend_lock = &locks[j];
1150
1151                 /* Ignore non-pending locks. */
1152                 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1153                         continue;
1154                 }
1155
1156                 /* We could send specific lock info here... */
1157                 if (brl_pending_overlap(plock, pend_lock)) {
1158                         DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
1159                                 procid_str_static(&pend_lock->context.pid )));
1160
1161                         messaging_send(msg_ctx, pend_lock->context.pid,
1162                                        MSG_SMB_UNLOCK, &data_blob_null);
1163                 }
1164         }
1165
1166         contend_level2_oplocks_end(br_lck->fsp, LEVEL2_CONTEND_WINDOWS_BRL);
1167         return True;
1168 }
1169
1170 /****************************************************************************
1171  Unlock a range of bytes - POSIX semantics.
1172 ****************************************************************************/
1173
1174 static bool brl_unlock_posix(struct messaging_context *msg_ctx,
1175                              struct byte_range_lock *br_lck,
1176                              struct lock_struct *plock)
1177 {
1178         unsigned int i, j, count;
1179         struct lock_struct *tp;
1180         struct lock_struct *locks = br_lck->lock_data;
1181         bool overlap_found = False;
1182
1183         /* No zero-zero locks for POSIX. */
1184         if (plock->start == 0 && plock->size == 0) {
1185                 return False;
1186         }
1187
1188         /* Don't allow 64-bit lock wrap. */
1189         if (plock->start + plock->size < plock->start ||
1190                         plock->start + plock->size < plock->size) {
1191                 DEBUG(10,("brl_unlock_posix: lock wrap\n"));
1192                 return False;
1193         }
1194
1195         /* The worst case scenario here is we have to split an
1196            existing POSIX lock range into two, so we need at most
1197            1 more entry. */
1198
1199         tp = talloc_array(br_lck, struct lock_struct, br_lck->num_locks + 1);
1200         if (!tp) {
1201                 DEBUG(10,("brl_unlock_posix: malloc fail\n"));
1202                 return False;
1203         }
1204
1205         count = 0;
1206         for (i = 0; i < br_lck->num_locks; i++) {
1207                 struct lock_struct *lock = &locks[i];
1208                 unsigned int tmp_count;
1209
1210                 /* Only remove our own locks - ignore fnum. */
1211                 if (IS_PENDING_LOCK(lock->lock_type) ||
1212                                 !brl_same_context(&lock->context, &plock->context)) {
1213                         memcpy(&tp[count], lock, sizeof(struct lock_struct));
1214                         count++;
1215                         continue;
1216                 }
1217
1218                 if (lock->lock_flav == WINDOWS_LOCK) {
1219                         /* Do any Windows flavour locks conflict ? */
1220                         if (brl_conflict(lock, plock)) {
1221                                 TALLOC_FREE(tp);
1222                                 return false;
1223                         }
1224                         /* Just copy the Windows lock into the new array. */
1225                         memcpy(&tp[count], lock, sizeof(struct lock_struct));
1226                         count++;
1227                         continue;
1228                 }
1229
1230                 /* Work out overlaps. */
1231                 tmp_count = brlock_posix_split_merge(&tp[count], lock, plock);
1232
1233                 if (tmp_count == 0) {
1234                         /* plock overlapped the existing lock completely,
1235                            or replaced it. Don't copy the existing lock. */
1236                         overlap_found = true;
1237                 } else if (tmp_count == 1) {
1238                         /* Either no overlap, (simple copy of existing lock) or
1239                          * an overlap of an existing lock. */
1240                         /* If the lock changed size, we had an overlap. */
1241                         if (tp[count].size != lock->size) {
1242                                 overlap_found = true;
1243                         }
1244                         count += tmp_count;
1245                 } else if (tmp_count == 2) {
1246                         /* We split a lock range in two. */
1247                         overlap_found = true;
1248                         count += tmp_count;
1249
1250                         /* Optimisation... */
1251                         /* We know we're finished here as we can't overlap any
1252                            more POSIX locks. Copy the rest of the lock array. */
1253
1254                         if (i < br_lck->num_locks - 1) {
1255                                 memcpy(&tp[count], &locks[i+1],
1256                                         sizeof(*locks)*((br_lck->num_locks-1) - i));
1257                                 count += ((br_lck->num_locks-1) - i);
1258                         }
1259                         break;
1260                 }
1261
1262         }
1263
1264         if (!overlap_found) {
1265                 /* Just ignore - no change. */
1266                 TALLOC_FREE(tp);
1267                 DEBUG(10,("brl_unlock_posix: No overlap - unlocked.\n"));
1268                 return True;
1269         }
1270
1271         /* Unlock any POSIX regions. */
1272         if(lp_posix_locking(br_lck->fsp->conn->params)) {
1273                 release_posix_lock_posix_flavour(br_lck->fsp,
1274                                                 plock->start,
1275                                                 plock->size,
1276                                                 &plock->context,
1277                                                 tp,
1278                                                 count);
1279         }
1280
1281         /* Realloc so we don't leak entries per unlock call. */
1282         if (count) {
1283                 tp = talloc_realloc(br_lck, tp, struct lock_struct, count);
1284                 if (!tp) {
1285                         DEBUG(10,("brl_unlock_posix: realloc fail\n"));
1286                         return False;
1287                 }
1288         } else {
1289                 /* We deleted the last lock. */
1290                 TALLOC_FREE(tp);
1291                 tp = NULL;
1292         }
1293
1294         contend_level2_oplocks_end(br_lck->fsp,
1295                                    LEVEL2_CONTEND_POSIX_BRL);
1296
1297         br_lck->num_locks = count;
1298         TALLOC_FREE(br_lck->lock_data);
1299         locks = tp;
1300         br_lck->lock_data = tp;
1301         br_lck->modified = True;
1302
1303         /* Send unlock messages to any pending waiters that overlap. */
1304
1305         for (j=0; j < br_lck->num_locks; j++) {
1306                 struct lock_struct *pend_lock = &locks[j];
1307
1308                 /* Ignore non-pending locks. */
1309                 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1310                         continue;
1311                 }
1312
1313                 /* We could send specific lock info here... */
1314                 if (brl_pending_overlap(plock, pend_lock)) {
1315                         DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
1316                                 procid_str_static(&pend_lock->context.pid )));
1317
1318                         messaging_send(msg_ctx, pend_lock->context.pid,
1319                                        MSG_SMB_UNLOCK, &data_blob_null);
1320                 }
1321         }
1322
1323         return True;
1324 }
1325
1326 bool smb_vfs_call_brl_unlock_windows(struct vfs_handle_struct *handle,
1327                                      struct messaging_context *msg_ctx,
1328                                      struct byte_range_lock *br_lck,
1329                                      const struct lock_struct *plock)
1330 {
1331         VFS_FIND(brl_unlock_windows);
1332         return handle->fns->brl_unlock_windows_fn(handle, msg_ctx, br_lck,
1333                                                   plock);
1334 }
1335
1336 /****************************************************************************
1337  Unlock a range of bytes.
1338 ****************************************************************************/
1339
1340 bool brl_unlock(struct messaging_context *msg_ctx,
1341                 struct byte_range_lock *br_lck,
1342                 uint64_t smblctx,
1343                 struct server_id pid,
1344                 br_off start,
1345                 br_off size,
1346                 enum brl_flavour lock_flav)
1347 {
1348         struct lock_struct lock;
1349
1350         lock.context.smblctx = smblctx;
1351         lock.context.pid = pid;
1352         lock.context.tid = br_lck->fsp->conn->cnum;
1353         lock.start = start;
1354         lock.size = size;
1355         lock.fnum = br_lck->fsp->fnum;
1356         lock.lock_type = UNLOCK_LOCK;
1357         lock.lock_flav = lock_flav;
1358
1359         if (lock_flav == WINDOWS_LOCK) {
1360                 return SMB_VFS_BRL_UNLOCK_WINDOWS(br_lck->fsp->conn, msg_ctx,
1361                     br_lck, &lock);
1362         } else {
1363                 return brl_unlock_posix(msg_ctx, br_lck, &lock);
1364         }
1365 }
1366
1367 /****************************************************************************
1368  Test if we could add a lock if we wanted to.
1369  Returns True if the region required is currently unlocked, False if locked.
1370 ****************************************************************************/
1371
1372 bool brl_locktest(struct byte_range_lock *br_lck,
1373                   const struct lock_struct *rw_probe)
1374 {
1375         bool ret = True;
1376         unsigned int i;
1377         struct lock_struct *locks = br_lck->lock_data;
1378         files_struct *fsp = br_lck->fsp;
1379
1380         /* Make sure existing locks don't conflict */
1381         for (i=0; i < br_lck->num_locks; i++) {
1382                 /*
1383                  * Our own locks don't conflict.
1384                  */
1385                 if (brl_conflict_other(&locks[i], rw_probe)) {
1386                         if (br_lck->record == NULL) {
1387                                 /* readonly */
1388                                 return false;
1389                         }
1390
1391                         if (!serverid_exists(&locks[i].context.pid)) {
1392                                 locks[i].context.pid.pid = 0;
1393                                 br_lck->modified = true;
1394                                 continue;
1395                         }
1396
1397                         return False;
1398                 }
1399         }
1400
1401         /*
1402          * There is no lock held by an SMB daemon, check to
1403          * see if there is a POSIX lock from a UNIX or NFS process.
1404          * This only conflicts with Windows locks, not POSIX locks.
1405          */
1406
1407         if(lp_posix_locking(fsp->conn->params) &&
1408            (rw_probe->lock_flav == WINDOWS_LOCK)) {
1409                 /*
1410                  * Make copies -- is_posix_locked might modify the values
1411                  */
1412
1413                 br_off start = rw_probe->start;
1414                 br_off size = rw_probe->size;
1415                 enum brl_type lock_type = rw_probe->lock_type;
1416
1417                 ret = is_posix_locked(fsp, &start, &size, &lock_type, WINDOWS_LOCK);
1418
1419                 DEBUG(10, ("brl_locktest: posix start=%ju len=%ju %s for %s "
1420                            "file %s\n", (uintmax_t)start, (uintmax_t)size,
1421                            ret ? "locked" : "unlocked",
1422                            fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1423
1424                 /* We need to return the inverse of is_posix_locked. */
1425                 ret = !ret;
1426         }
1427
1428         /* no conflicts - we could have added it */
1429         return ret;
1430 }
1431
1432 /****************************************************************************
1433  Query for existing locks.
1434 ****************************************************************************/
1435
1436 NTSTATUS brl_lockquery(struct byte_range_lock *br_lck,
1437                 uint64_t *psmblctx,
1438                 struct server_id pid,
1439                 br_off *pstart,
1440                 br_off *psize,
1441                 enum brl_type *plock_type,
1442                 enum brl_flavour lock_flav)
1443 {
1444         unsigned int i;
1445         struct lock_struct lock;
1446         const struct lock_struct *locks = br_lck->lock_data;
1447         files_struct *fsp = br_lck->fsp;
1448
1449         lock.context.smblctx = *psmblctx;
1450         lock.context.pid = pid;
1451         lock.context.tid = br_lck->fsp->conn->cnum;
1452         lock.start = *pstart;
1453         lock.size = *psize;
1454         lock.fnum = fsp->fnum;
1455         lock.lock_type = *plock_type;
1456         lock.lock_flav = lock_flav;
1457
1458         /* Make sure existing locks don't conflict */
1459         for (i=0; i < br_lck->num_locks; i++) {
1460                 const struct lock_struct *exlock = &locks[i];
1461                 bool conflict = False;
1462
1463                 if (exlock->lock_flav == WINDOWS_LOCK) {
1464                         conflict = brl_conflict(exlock, &lock);
1465                 } else {
1466                         conflict = brl_conflict_posix(exlock, &lock);
1467                 }
1468
1469                 if (conflict) {
1470                         *psmblctx = exlock->context.smblctx;
1471                         *pstart = exlock->start;
1472                         *psize = exlock->size;
1473                         *plock_type = exlock->lock_type;
1474                         return NT_STATUS_LOCK_NOT_GRANTED;
1475                 }
1476         }
1477
1478         /*
1479          * There is no lock held by an SMB daemon, check to
1480          * see if there is a POSIX lock from a UNIX or NFS process.
1481          */
1482
1483         if(lp_posix_locking(fsp->conn->params)) {
1484                 bool ret = is_posix_locked(fsp, pstart, psize, plock_type, POSIX_LOCK);
1485
1486                 DEBUG(10, ("brl_lockquery: posix start=%ju len=%ju %s for %s "
1487                            "file %s\n", (uintmax_t)*pstart,
1488                            (uintmax_t)*psize, ret ? "locked" : "unlocked",
1489                            fsp_fnum_dbg(fsp), fsp_str_dbg(fsp)));
1490
1491                 if (ret) {
1492                         /* Hmmm. No clue what to set smblctx to - use -1. */
1493                         *psmblctx = 0xFFFFFFFFFFFFFFFFLL;
1494                         return NT_STATUS_LOCK_NOT_GRANTED;
1495                 }
1496         }
1497
1498         return NT_STATUS_OK;
1499 }
1500
1501
1502 bool smb_vfs_call_brl_cancel_windows(struct vfs_handle_struct *handle,
1503                                      struct byte_range_lock *br_lck,
1504                                      struct lock_struct *plock)
1505 {
1506         VFS_FIND(brl_cancel_windows);
1507         return handle->fns->brl_cancel_windows_fn(handle, br_lck, plock);
1508 }
1509
1510 /****************************************************************************
1511  Remove a particular pending lock.
1512 ****************************************************************************/
1513 bool brl_lock_cancel(struct byte_range_lock *br_lck,
1514                 uint64_t smblctx,
1515                 struct server_id pid,
1516                 br_off start,
1517                 br_off size,
1518                 enum brl_flavour lock_flav)
1519 {
1520         bool ret;
1521         struct lock_struct lock;
1522
1523         lock.context.smblctx = smblctx;
1524         lock.context.pid = pid;
1525         lock.context.tid = br_lck->fsp->conn->cnum;
1526         lock.start = start;
1527         lock.size = size;
1528         lock.fnum = br_lck->fsp->fnum;
1529         lock.lock_flav = lock_flav;
1530         /* lock.lock_type doesn't matter */
1531
1532         if (lock_flav == WINDOWS_LOCK) {
1533                 ret = SMB_VFS_BRL_CANCEL_WINDOWS(br_lck->fsp->conn, br_lck,
1534                                                  &lock);
1535         } else {
1536                 ret = brl_lock_cancel_default(br_lck, &lock);
1537         }
1538
1539         return ret;
1540 }
1541
1542 bool brl_lock_cancel_default(struct byte_range_lock *br_lck,
1543                 struct lock_struct *plock)
1544 {
1545         unsigned int i;
1546         struct lock_struct *locks = br_lck->lock_data;
1547
1548         SMB_ASSERT(plock);
1549
1550         for (i = 0; i < br_lck->num_locks; i++) {
1551                 struct lock_struct *lock = &locks[i];
1552
1553                 /* For pending locks we *always* care about the fnum. */
1554                 if (brl_same_context(&lock->context, &plock->context) &&
1555                                 lock->fnum == plock->fnum &&
1556                                 IS_PENDING_LOCK(lock->lock_type) &&
1557                                 lock->lock_flav == plock->lock_flav &&
1558                                 lock->start == plock->start &&
1559                                 lock->size == plock->size) {
1560                         break;
1561                 }
1562         }
1563
1564         if (i == br_lck->num_locks) {
1565                 /* Didn't find it. */
1566                 return False;
1567         }
1568
1569         brl_delete_lock_struct(locks, br_lck->num_locks, i);
1570         br_lck->num_locks -= 1;
1571         br_lck->modified = True;
1572         return True;
1573 }
1574
1575 /****************************************************************************
1576  Remove any locks associated with a open file.
1577  We return True if this process owns any other Windows locks on this
1578  fd and so we should not immediately close the fd.
1579 ****************************************************************************/
1580
1581 void brl_close_fnum(struct messaging_context *msg_ctx,
1582                     struct byte_range_lock *br_lck)
1583 {
1584         files_struct *fsp = br_lck->fsp;
1585         uint32_t tid = fsp->conn->cnum;
1586         uint64_t fnum = fsp->fnum;
1587         unsigned int i;
1588         struct lock_struct *locks = br_lck->lock_data;
1589         struct server_id pid = messaging_server_id(fsp->conn->sconn->msg_ctx);
1590         struct lock_struct *locks_copy;
1591         unsigned int num_locks_copy;
1592
1593         /* Copy the current lock array. */
1594         if (br_lck->num_locks) {
1595                 locks_copy = (struct lock_struct *)talloc_memdup(br_lck, locks, br_lck->num_locks * sizeof(struct lock_struct));
1596                 if (!locks_copy) {
1597                         smb_panic("brl_close_fnum: talloc failed");
1598                         }
1599         } else {
1600                 locks_copy = NULL;
1601         }
1602
1603         num_locks_copy = br_lck->num_locks;
1604
1605         for (i=0; i < num_locks_copy; i++) {
1606                 struct lock_struct *lock = &locks_copy[i];
1607
1608                 if (lock->context.tid == tid && serverid_equal(&lock->context.pid, &pid) &&
1609                                 (lock->fnum == fnum)) {
1610                         brl_unlock(msg_ctx,
1611                                 br_lck,
1612                                 lock->context.smblctx,
1613                                 pid,
1614                                 lock->start,
1615                                 lock->size,
1616                                 lock->lock_flav);
1617                 }
1618         }
1619 }
1620
1621 bool brl_mark_disconnected(struct files_struct *fsp)
1622 {
1623         uint32_t tid = fsp->conn->cnum;
1624         uint64_t smblctx;
1625         uint64_t fnum = fsp->fnum;
1626         unsigned int i;
1627         struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1628         struct byte_range_lock *br_lck = NULL;
1629
1630         if (fsp->op == NULL) {
1631                 return false;
1632         }
1633
1634         smblctx = fsp->op->global->open_persistent_id;
1635
1636         if (!fsp->op->global->durable) {
1637                 return false;
1638         }
1639
1640         if (fsp->current_lock_count == 0) {
1641                 return true;
1642         }
1643
1644         br_lck = brl_get_locks(talloc_tos(), fsp);
1645         if (br_lck == NULL) {
1646                 return false;
1647         }
1648
1649         for (i=0; i < br_lck->num_locks; i++) {
1650                 struct lock_struct *lock = &br_lck->lock_data[i];
1651
1652                 /*
1653                  * as this is a durable handle, we only expect locks
1654                  * of the current file handle!
1655                  */
1656
1657                 if (lock->context.smblctx != smblctx) {
1658                         TALLOC_FREE(br_lck);
1659                         return false;
1660                 }
1661
1662                 if (lock->context.tid != tid) {
1663                         TALLOC_FREE(br_lck);
1664                         return false;
1665                 }
1666
1667                 if (!serverid_equal(&lock->context.pid, &self)) {
1668                         TALLOC_FREE(br_lck);
1669                         return false;
1670                 }
1671
1672                 if (lock->fnum != fnum) {
1673                         TALLOC_FREE(br_lck);
1674                         return false;
1675                 }
1676
1677                 server_id_set_disconnected(&lock->context.pid);
1678                 lock->context.tid = TID_FIELD_INVALID;
1679                 lock->fnum = FNUM_FIELD_INVALID;
1680         }
1681
1682         br_lck->modified = true;
1683         TALLOC_FREE(br_lck);
1684         return true;
1685 }
1686
1687 bool brl_reconnect_disconnected(struct files_struct *fsp)
1688 {
1689         uint32_t tid = fsp->conn->cnum;
1690         uint64_t smblctx;
1691         uint64_t fnum = fsp->fnum;
1692         unsigned int i;
1693         struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1694         struct byte_range_lock *br_lck = NULL;
1695
1696         if (fsp->op == NULL) {
1697                 return false;
1698         }
1699
1700         smblctx = fsp->op->global->open_persistent_id;
1701
1702         if (!fsp->op->global->durable) {
1703                 return false;
1704         }
1705
1706         /*
1707          * When reconnecting, we do not want to validate the brlock entries
1708          * and thereby remove our own (disconnected) entries but reactivate
1709          * them instead.
1710          */
1711
1712         br_lck = brl_get_locks(talloc_tos(), fsp);
1713         if (br_lck == NULL) {
1714                 return false;
1715         }
1716
1717         if (br_lck->num_locks == 0) {
1718                 TALLOC_FREE(br_lck);
1719                 return true;
1720         }
1721
1722         for (i=0; i < br_lck->num_locks; i++) {
1723                 struct lock_struct *lock = &br_lck->lock_data[i];
1724
1725                 /*
1726                  * as this is a durable handle we only expect locks
1727                  * of the current file handle!
1728                  */
1729
1730                 if (lock->context.smblctx != smblctx) {
1731                         TALLOC_FREE(br_lck);
1732                         return false;
1733                 }
1734
1735                 if (lock->context.tid != TID_FIELD_INVALID) {
1736                         TALLOC_FREE(br_lck);
1737                         return false;
1738                 }
1739
1740                 if (!server_id_is_disconnected(&lock->context.pid)) {
1741                         TALLOC_FREE(br_lck);
1742                         return false;
1743                 }
1744
1745                 if (lock->fnum != FNUM_FIELD_INVALID) {
1746                         TALLOC_FREE(br_lck);
1747                         return false;
1748                 }
1749
1750                 lock->context.pid = self;
1751                 lock->context.tid = tid;
1752                 lock->fnum = fnum;
1753         }
1754
1755         fsp->current_lock_count = br_lck->num_locks;
1756         br_lck->modified = true;
1757         TALLOC_FREE(br_lck);
1758         return true;
1759 }
1760
1761 struct brl_forall_cb {
1762         void (*fn)(struct file_id id, struct server_id pid,
1763                    enum brl_type lock_type,
1764                    enum brl_flavour lock_flav,
1765                    br_off start, br_off size,
1766                    void *private_data);
1767         void *private_data;
1768 };
1769
1770 /****************************************************************************
1771  Traverse the whole database with this function, calling traverse_callback
1772  on each lock.
1773 ****************************************************************************/
1774
1775 static int brl_traverse_fn(struct db_record *rec, void *state)
1776 {
1777         struct brl_forall_cb *cb = (struct brl_forall_cb *)state;
1778         struct lock_struct *locks;
1779         struct file_id *key;
1780         unsigned int i;
1781         unsigned int num_locks = 0;
1782         TDB_DATA dbkey;
1783         TDB_DATA value;
1784
1785         dbkey = dbwrap_record_get_key(rec);
1786         value = dbwrap_record_get_value(rec);
1787
1788         /* In a traverse function we must make a copy of
1789            dbuf before modifying it. */
1790
1791         locks = (struct lock_struct *)talloc_memdup(
1792                 talloc_tos(), value.dptr, value.dsize);
1793         if (!locks) {
1794                 return -1; /* Terminate traversal. */
1795         }
1796
1797         key = (struct file_id *)dbkey.dptr;
1798         num_locks = value.dsize/sizeof(*locks);
1799
1800         if (cb->fn) {
1801                 for ( i=0; i<num_locks; i++) {
1802                         cb->fn(*key,
1803                                 locks[i].context.pid,
1804                                 locks[i].lock_type,
1805                                 locks[i].lock_flav,
1806                                 locks[i].start,
1807                                 locks[i].size,
1808                                 cb->private_data);
1809                 }
1810         }
1811
1812         TALLOC_FREE(locks);
1813         return 0;
1814 }
1815
1816 /*******************************************************************
1817  Call the specified function on each lock in the database.
1818 ********************************************************************/
1819
1820 int brl_forall(void (*fn)(struct file_id id, struct server_id pid,
1821                           enum brl_type lock_type,
1822                           enum brl_flavour lock_flav,
1823                           br_off start, br_off size,
1824                           void *private_data),
1825                void *private_data)
1826 {
1827         struct brl_forall_cb cb;
1828         NTSTATUS status;
1829         int count = 0;
1830
1831         if (!brlock_db) {
1832                 return 0;
1833         }
1834         cb.fn = fn;
1835         cb.private_data = private_data;
1836         status = dbwrap_traverse(brlock_db, brl_traverse_fn, &cb, &count);
1837
1838         if (!NT_STATUS_IS_OK(status)) {
1839                 return -1;
1840         } else {
1841                 return count;
1842         }
1843 }
1844
1845 /*******************************************************************
1846  Store a potentially modified set of byte range lock data back into
1847  the database.
1848  Unlock the record.
1849 ********************************************************************/
1850
1851 static void byte_range_lock_flush(struct byte_range_lock *br_lck)
1852 {
1853         unsigned i;
1854         struct lock_struct *locks = br_lck->lock_data;
1855
1856         if (!br_lck->modified) {
1857                 DEBUG(10, ("br_lck not modified\n"));
1858                 goto done;
1859         }
1860
1861         i = 0;
1862
1863         while (i < br_lck->num_locks) {
1864                 if (locks[i].context.pid.pid == 0) {
1865                         /*
1866                          * Autocleanup, the process conflicted and does not
1867                          * exist anymore.
1868                          */
1869                         locks[i] = locks[br_lck->num_locks-1];
1870                         br_lck->num_locks -= 1;
1871                 } else {
1872                         i += 1;
1873                 }
1874         }
1875
1876         if ((br_lck->num_locks == 0) && (br_lck->num_read_oplocks == 0)) {
1877                 /* No locks - delete this entry. */
1878                 NTSTATUS status = dbwrap_record_delete(br_lck->record);
1879                 if (!NT_STATUS_IS_OK(status)) {
1880                         DEBUG(0, ("delete_rec returned %s\n",
1881                                   nt_errstr(status)));
1882                         smb_panic("Could not delete byte range lock entry");
1883                 }
1884         } else {
1885                 size_t lock_len, data_len;
1886                 TDB_DATA data;
1887                 NTSTATUS status;
1888
1889                 lock_len = br_lck->num_locks * sizeof(struct lock_struct);
1890                 data_len = lock_len + sizeof(br_lck->num_read_oplocks);
1891
1892                 data.dsize = data_len;
1893                 data.dptr = talloc_array(talloc_tos(), uint8_t, data_len);
1894                 SMB_ASSERT(data.dptr != NULL);
1895
1896                 memcpy(data.dptr, br_lck->lock_data, lock_len);
1897                 memcpy(data.dptr + lock_len, &br_lck->num_read_oplocks,
1898                        sizeof(br_lck->num_read_oplocks));
1899
1900                 status = dbwrap_record_store(br_lck->record, data, TDB_REPLACE);
1901                 TALLOC_FREE(data.dptr);
1902                 if (!NT_STATUS_IS_OK(status)) {
1903                         DEBUG(0, ("store returned %s\n", nt_errstr(status)));
1904                         smb_panic("Could not store byte range mode entry");
1905                 }
1906         }
1907
1908         DEBUG(10, ("seqnum=%d\n", dbwrap_get_seqnum(brlock_db)));
1909
1910  done:
1911         br_lck->modified = false;
1912         TALLOC_FREE(br_lck->record);
1913 }
1914
1915 static int byte_range_lock_destructor(struct byte_range_lock *br_lck)
1916 {
1917         byte_range_lock_flush(br_lck);
1918         return 0;
1919 }
1920
1921 static bool brl_parse_data(struct byte_range_lock *br_lck, TDB_DATA data)
1922 {
1923         size_t data_len;
1924
1925         if (data.dsize == 0) {
1926                 return true;
1927         }
1928         if (data.dsize % sizeof(struct lock_struct) !=
1929             sizeof(br_lck->num_read_oplocks)) {
1930                 DEBUG(1, ("Invalid data size: %u\n", (unsigned)data.dsize));
1931                 return false;
1932         }
1933
1934         br_lck->num_locks = data.dsize / sizeof(struct lock_struct);
1935         data_len = br_lck->num_locks * sizeof(struct lock_struct);
1936
1937         br_lck->lock_data = talloc_memdup(br_lck, data.dptr, data_len);
1938         if (br_lck->lock_data == NULL) {
1939                 DEBUG(1, ("talloc_memdup failed\n"));
1940                 return false;
1941         }
1942         memcpy(&br_lck->num_read_oplocks, data.dptr + data_len,
1943                sizeof(br_lck->num_read_oplocks));
1944         return true;
1945 }
1946
1947 /*******************************************************************
1948  Fetch a set of byte range lock data from the database.
1949  Leave the record locked.
1950  TALLOC_FREE(brl) will release the lock in the destructor.
1951 ********************************************************************/
1952
1953 struct byte_range_lock *brl_get_locks(TALLOC_CTX *mem_ctx, files_struct *fsp)
1954 {
1955         TDB_DATA key, data;
1956         struct byte_range_lock *br_lck;
1957
1958         br_lck = talloc_zero(mem_ctx, struct byte_range_lock);
1959         if (br_lck == NULL) {
1960                 return NULL;
1961         }
1962
1963         br_lck->fsp = fsp;
1964
1965         key.dptr = (uint8 *)&fsp->file_id;
1966         key.dsize = sizeof(struct file_id);
1967
1968         br_lck->record = dbwrap_fetch_locked(brlock_db, br_lck, key);
1969
1970         if (br_lck->record == NULL) {
1971                 DEBUG(3, ("Could not lock byte range lock entry\n"));
1972                 TALLOC_FREE(br_lck);
1973                 return NULL;
1974         }
1975
1976         data = dbwrap_record_get_value(br_lck->record);
1977
1978         if (!brl_parse_data(br_lck, data)) {
1979                 TALLOC_FREE(br_lck);
1980                 return NULL;
1981         }
1982
1983         talloc_set_destructor(br_lck, byte_range_lock_destructor);
1984
1985         if (DEBUGLEVEL >= 10) {
1986                 unsigned int i;
1987                 struct lock_struct *locks = br_lck->lock_data;
1988                 DEBUG(10,("brl_get_locks_internal: %u current locks on file_id %s\n",
1989                         br_lck->num_locks,
1990                           file_id_string_tos(&fsp->file_id)));
1991                 for( i = 0; i < br_lck->num_locks; i++) {
1992                         print_lock_struct(i, &locks[i]);
1993                 }
1994         }
1995
1996         return br_lck;
1997 }
1998
1999 struct brl_get_locks_readonly_state {
2000         TALLOC_CTX *mem_ctx;
2001         struct byte_range_lock **br_lock;
2002 };
2003
2004 static void brl_get_locks_readonly_parser(TDB_DATA key, TDB_DATA data,
2005                                           void *private_data)
2006 {
2007         struct brl_get_locks_readonly_state *state =
2008                 (struct brl_get_locks_readonly_state *)private_data;
2009         struct byte_range_lock *br_lck;
2010
2011         br_lck = talloc_pooled_object(
2012                 state->mem_ctx, struct byte_range_lock, 1, data.dsize);
2013         if (br_lck == NULL) {
2014                 *state->br_lock = NULL;
2015                 return;
2016         }
2017         *br_lck = (struct byte_range_lock) {};
2018         if (!brl_parse_data(br_lck, data)) {
2019                 *state->br_lock = NULL;
2020                 return;
2021         }
2022         *state->br_lock = br_lck;
2023 }
2024
2025 struct byte_range_lock *brl_get_locks_readonly(files_struct *fsp)
2026 {
2027         struct byte_range_lock *br_lock = NULL;
2028         struct brl_get_locks_readonly_state state;
2029         NTSTATUS status;
2030
2031         DEBUG(10, ("seqnum=%d, fsp->brlock_seqnum=%d\n",
2032                    dbwrap_get_seqnum(brlock_db), fsp->brlock_seqnum));
2033
2034         if ((fsp->brlock_rec != NULL)
2035             && (dbwrap_get_seqnum(brlock_db) == fsp->brlock_seqnum)) {
2036                 /*
2037                  * We have cached the brlock_rec and the database did not
2038                  * change.
2039                  */
2040                 return fsp->brlock_rec;
2041         }
2042
2043         /*
2044          * Parse the record fresh from the database
2045          */
2046
2047         state.mem_ctx = fsp;
2048         state.br_lock = &br_lock;
2049
2050         status = dbwrap_parse_record(
2051                 brlock_db,
2052                 make_tdb_data((uint8_t *)&fsp->file_id,
2053                               sizeof(fsp->file_id)),
2054                 brl_get_locks_readonly_parser, &state);
2055
2056         if (NT_STATUS_EQUAL(status,NT_STATUS_NOT_FOUND)) {
2057                 /*
2058                  * No locks on this file. Return an empty br_lock.
2059                  */
2060                 br_lock = talloc(fsp, struct byte_range_lock);
2061                 if (br_lock == NULL) {
2062                         return NULL;
2063                 }
2064
2065                 br_lock->num_read_oplocks = 0;
2066                 br_lock->num_locks = 0;
2067                 br_lock->lock_data = NULL;
2068
2069         } else if (!NT_STATUS_IS_OK(status)) {
2070                 DEBUG(3, ("Could not parse byte range lock record: "
2071                           "%s\n", nt_errstr(status)));
2072                 return NULL;
2073         }
2074         if (br_lock == NULL) {
2075                 return NULL;
2076         }
2077
2078         br_lock->fsp = fsp;
2079         br_lock->modified = false;
2080         br_lock->record = NULL;
2081
2082         if (lp_clustering()) {
2083                 /*
2084                  * In the cluster case we can't cache the brlock struct
2085                  * because dbwrap_get_seqnum does not work reliably over
2086                  * ctdb. Thus we have to throw away the brlock struct soon.
2087                  */
2088                 talloc_steal(talloc_tos(), br_lock);
2089         } else {
2090                 /*
2091                  * Cache the brlock struct, invalidated when the dbwrap_seqnum
2092                  * changes. See beginning of this routine.
2093                  */
2094                 TALLOC_FREE(fsp->brlock_rec);
2095                 fsp->brlock_rec = br_lock;
2096                 fsp->brlock_seqnum = dbwrap_get_seqnum(brlock_db);
2097         }
2098
2099         return br_lock;
2100 }
2101
2102 struct brl_revalidate_state {
2103         ssize_t array_size;
2104         uint32 num_pids;
2105         struct server_id *pids;
2106 };
2107
2108 /*
2109  * Collect PIDs of all processes with pending entries
2110  */
2111
2112 static void brl_revalidate_collect(struct file_id id, struct server_id pid,
2113                                    enum brl_type lock_type,
2114                                    enum brl_flavour lock_flav,
2115                                    br_off start, br_off size,
2116                                    void *private_data)
2117 {
2118         struct brl_revalidate_state *state =
2119                 (struct brl_revalidate_state *)private_data;
2120
2121         if (!IS_PENDING_LOCK(lock_type)) {
2122                 return;
2123         }
2124
2125         add_to_large_array(state, sizeof(pid), (void *)&pid,
2126                            &state->pids, &state->num_pids,
2127                            &state->array_size);
2128 }
2129
2130 /*
2131  * qsort callback to sort the processes
2132  */
2133
2134 static int compare_procids(const void *p1, const void *p2)
2135 {
2136         const struct server_id *i1 = (const struct server_id *)p1;
2137         const struct server_id *i2 = (const struct server_id *)p2;
2138
2139         if (i1->pid < i2->pid) return -1;
2140         if (i1->pid > i2->pid) return 1;
2141         return 0;
2142 }
2143
2144 /*
2145  * Send a MSG_SMB_UNLOCK message to all processes with pending byte range
2146  * locks so that they retry. Mainly used in the cluster code after a node has
2147  * died.
2148  *
2149  * Done in two steps to avoid double-sends: First we collect all entries in an
2150  * array, then qsort that array and only send to non-dupes.
2151  */
2152
2153 void brl_revalidate(struct messaging_context *msg_ctx,
2154                     void *private_data,
2155                     uint32_t msg_type,
2156                     struct server_id server_id,
2157                     DATA_BLOB *data)
2158 {
2159         struct brl_revalidate_state *state;
2160         uint32 i;
2161         struct server_id last_pid;
2162
2163         if (!(state = talloc_zero(NULL, struct brl_revalidate_state))) {
2164                 DEBUG(0, ("talloc failed\n"));
2165                 return;
2166         }
2167
2168         brl_forall(brl_revalidate_collect, state);
2169
2170         if (state->array_size == -1) {
2171                 DEBUG(0, ("talloc failed\n"));
2172                 goto done;
2173         }
2174
2175         if (state->num_pids == 0) {
2176                 goto done;
2177         }
2178
2179         TYPESAFE_QSORT(state->pids, state->num_pids, compare_procids);
2180
2181         ZERO_STRUCT(last_pid);
2182
2183         for (i=0; i<state->num_pids; i++) {
2184                 if (serverid_equal(&last_pid, &state->pids[i])) {
2185                         /*
2186                          * We've seen that one already
2187                          */
2188                         continue;
2189                 }
2190
2191                 messaging_send(msg_ctx, state->pids[i], MSG_SMB_UNLOCK,
2192                                &data_blob_null);
2193                 last_pid = state->pids[i];
2194         }
2195
2196  done:
2197         TALLOC_FREE(state);
2198         return;
2199 }
2200
2201 bool brl_cleanup_disconnected(struct file_id fid, uint64_t open_persistent_id)
2202 {
2203         bool ret = false;
2204         TALLOC_CTX *frame = talloc_stackframe();
2205         TDB_DATA key, val;
2206         struct db_record *rec;
2207         struct lock_struct *lock;
2208         unsigned n, num;
2209         NTSTATUS status;
2210
2211         key = make_tdb_data((void*)&fid, sizeof(fid));
2212
2213         rec = dbwrap_fetch_locked(brlock_db, frame, key);
2214         if (rec == NULL) {
2215                 DEBUG(5, ("brl_cleanup_disconnected: failed to fetch record "
2216                           "for file %s\n", file_id_string(frame, &fid)));
2217                 goto done;
2218         }
2219
2220         val = dbwrap_record_get_value(rec);
2221         lock = (struct lock_struct*)val.dptr;
2222         num = val.dsize / sizeof(struct lock_struct);
2223         if (lock == NULL) {
2224                 DEBUG(10, ("brl_cleanup_disconnected: no byte range locks for "
2225                            "file %s\n", file_id_string(frame, &fid)));
2226                 ret = true;
2227                 goto done;
2228         }
2229
2230         for (n=0; n<num; n++) {
2231                 struct lock_context *ctx = &lock[n].context;
2232
2233                 if (!server_id_is_disconnected(&ctx->pid)) {
2234                         DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2235                                   "%s used by server %s, do not cleanup\n",
2236                                   file_id_string(frame, &fid),
2237                                   server_id_str(frame, &ctx->pid)));
2238                         goto done;
2239                 }
2240
2241                 if (ctx->smblctx != open_persistent_id) {
2242                         DEBUG(5, ("brl_cleanup_disconnected: byte range lock "
2243                                   "%s expected smblctx %llu but found %llu"
2244                                   ", do not cleanup\n",
2245                                   file_id_string(frame, &fid),
2246                                   (unsigned long long)open_persistent_id,
2247                                   (unsigned long long)ctx->smblctx));
2248                         goto done;
2249                 }
2250         }
2251
2252         status = dbwrap_record_delete(rec);
2253         if (!NT_STATUS_IS_OK(status)) {
2254                 DEBUG(5, ("brl_cleanup_disconnected: failed to delete record "
2255                           "for file %s from %s, open %llu: %s\n",
2256                           file_id_string(frame, &fid), dbwrap_name(brlock_db),
2257                           (unsigned long long)open_persistent_id,
2258                           nt_errstr(status)));
2259                 goto done;
2260         }
2261
2262         DEBUG(10, ("brl_cleanup_disconnected: "
2263                    "file %s cleaned up %u entries from open %llu\n",
2264                    file_id_string(frame, &fid), num,
2265                    (unsigned long long)open_persistent_id));
2266
2267         ret = true;
2268 done:
2269         talloc_free(frame);
2270         return ret;
2271 }