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