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