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