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