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