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