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