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