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