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