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