r22846: Chunk one to replace message_send_pid with messaging_send: Deep inside
[sfrench/samba-autobuild/.git] / source / 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 2 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, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 /* This module implements a tdb based byte range locking service,
25    replacing the fcntl() based byte range locking previously
26    used. This allows us to provide the same semantics as NT */
27
28 #include "includes.h"
29
30 #undef DBGC_CLASS
31 #define DBGC_CLASS DBGC_LOCKING
32
33 #define ZERO_ZERO 0
34
35 /* The open brlock.tdb database. */
36
37 static TDB_CONTEXT *tdb;
38
39 /****************************************************************************
40  Debug info at level 10 for lock struct.
41 ****************************************************************************/
42
43 static void print_lock_struct(unsigned int i, struct lock_struct *pls)
44 {
45         DEBUG(10,("[%u]: smbpid = %u, tid = %u, pid = %u, ",
46                         i,
47                         (unsigned int)pls->context.smbpid,
48                         (unsigned int)pls->context.tid,
49                         (unsigned int)procid_to_pid(&pls->context.pid) ));
50         
51         DEBUG(10,("start = %.0f, size = %.0f, fnum = %d, %s %s\n",
52                 (double)pls->start,
53                 (double)pls->size,
54                 pls->fnum,
55                 lock_type_name(pls->lock_type),
56                 lock_flav_name(pls->lock_flav) ));
57 }
58
59 /****************************************************************************
60  See if two locking contexts are equal.
61 ****************************************************************************/
62
63 BOOL brl_same_context(const struct lock_context *ctx1, 
64                              const struct lock_context *ctx2)
65 {
66         return (procid_equal(&ctx1->pid, &ctx2->pid) &&
67                 (ctx1->smbpid == ctx2->smbpid) &&
68                 (ctx1->tid == ctx2->tid));
69 }
70
71 /****************************************************************************
72  See if lck1 and lck2 overlap.
73 ****************************************************************************/
74
75 static BOOL brl_overlap(const struct lock_struct *lck1,
76                         const struct lock_struct *lck2)
77 {
78         /* this extra check is not redundent - it copes with locks
79            that go beyond the end of 64 bit file space */
80         if (lck1->size != 0 &&
81             lck1->start == lck2->start &&
82             lck1->size == lck2->size) {
83                 return True;
84         }
85
86         if (lck1->start >= (lck2->start+lck2->size) ||
87             lck2->start >= (lck1->start+lck1->size)) {
88                 return False;
89         }
90         return True;
91 }
92
93 /****************************************************************************
94  See if lock2 can be added when lock1 is in place.
95 ****************************************************************************/
96
97 static BOOL brl_conflict(const struct lock_struct *lck1, 
98                          const struct lock_struct *lck2)
99 {
100         /* Ignore PENDING locks. */
101         if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
102                 return False;
103
104         /* Read locks never conflict. */
105         if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
106                 return False;
107         }
108
109         if (brl_same_context(&lck1->context, &lck2->context) &&
110             lck2->lock_type == READ_LOCK && lck1->fnum == lck2->fnum) {
111                 return False;
112         }
113
114         return brl_overlap(lck1, lck2);
115
116
117 /****************************************************************************
118  See if lock2 can be added when lock1 is in place - when both locks are POSIX
119  flavour. POSIX locks ignore fnum - they only care about dev/ino which we
120  know already match.
121 ****************************************************************************/
122
123 static BOOL brl_conflict_posix(const struct lock_struct *lck1, 
124                                 const struct lock_struct *lck2)
125 {
126 #if defined(DEVELOPER)
127         SMB_ASSERT(lck1->lock_flav == POSIX_LOCK);
128         SMB_ASSERT(lck2->lock_flav == POSIX_LOCK);
129 #endif
130
131         /* Ignore PENDING locks. */
132         if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
133                 return False;
134
135         /* Read locks never conflict. */
136         if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
137                 return False;
138         }
139
140         /* Locks on the same context con't conflict. Ignore fnum. */
141         if (brl_same_context(&lck1->context, &lck2->context)) {
142                 return False;
143         }
144
145         /* One is read, the other write, or the context is different,
146            do they overlap ? */
147         return brl_overlap(lck1, lck2);
148
149
150 #if ZERO_ZERO
151 static BOOL brl_conflict1(const struct lock_struct *lck1, 
152                          const struct lock_struct *lck2)
153 {
154         if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
155                 return False;
156
157         if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) {
158                 return False;
159         }
160
161         if (brl_same_context(&lck1->context, &lck2->context) &&
162             lck2->lock_type == READ_LOCK && lck1->fnum == lck2->fnum) {
163                 return False;
164         }
165
166         if (lck2->start == 0 && lck2->size == 0 && lck1->size != 0) {
167                 return True;
168         }
169
170         if (lck1->start >= (lck2->start + lck2->size) ||
171             lck2->start >= (lck1->start + lck1->size)) {
172                 return False;
173         }
174             
175         return True;
176
177 #endif
178
179 /****************************************************************************
180  Check to see if this lock conflicts, but ignore our own locks on the
181  same fnum only. This is the read/write lock check code path.
182  This is never used in the POSIX lock case.
183 ****************************************************************************/
184
185 static BOOL brl_conflict_other(const struct lock_struct *lck1, const struct lock_struct *lck2)
186 {
187         if (IS_PENDING_LOCK(lck1->lock_type) || IS_PENDING_LOCK(lck2->lock_type))
188                 return False;
189
190         if (lck1->lock_type == READ_LOCK && lck2->lock_type == READ_LOCK) 
191                 return False;
192
193         /* POSIX flavour locks never conflict here - this is only called
194            in the read/write path. */
195
196         if (lck1->lock_flav == POSIX_LOCK && lck2->lock_flav == POSIX_LOCK)
197                 return False;
198
199         /*
200          * Incoming WRITE locks conflict with existing READ locks even
201          * if the context is the same. JRA. See LOCKTEST7 in smbtorture.
202          */
203
204         if (!(lck2->lock_type == WRITE_LOCK && lck1->lock_type == READ_LOCK)) {
205                 if (brl_same_context(&lck1->context, &lck2->context) &&
206                                         lck1->fnum == lck2->fnum)
207                         return False;
208         }
209
210         return brl_overlap(lck1, lck2);
211
212
213 /****************************************************************************
214  Check if an unlock overlaps a pending lock.
215 ****************************************************************************/
216
217 static BOOL brl_pending_overlap(const struct lock_struct *lock, const struct lock_struct *pend_lock)
218 {
219         if ((lock->start <= pend_lock->start) && (lock->start + lock->size > pend_lock->start))
220                 return True;
221         if ((lock->start >= pend_lock->start) && (lock->start <= pend_lock->start + pend_lock->size))
222                 return True;
223         return False;
224 }
225
226 /****************************************************************************
227  Amazingly enough, w2k3 "remembers" whether the last lock failure on a fnum
228  is the same as this one and changes its error code. I wonder if any
229  app depends on this ?
230 ****************************************************************************/
231
232 static NTSTATUS brl_lock_failed(files_struct *fsp, const struct lock_struct *lock, BOOL blocking_lock)
233 {
234         if (lock->start >= 0xEF000000 && (lock->start >> 63) == 0) {
235                 /* amazing the little things you learn with a test
236                    suite. Locks beyond this offset (as a 64 bit
237                    number!) always generate the conflict error code,
238                    unless the top bit is set */
239                 if (!blocking_lock) {
240                         fsp->last_lock_failure = *lock;
241                 }
242                 return NT_STATUS_FILE_LOCK_CONFLICT;
243         }
244
245         if (procid_equal(&lock->context.pid, &fsp->last_lock_failure.context.pid) &&
246                         lock->context.tid == fsp->last_lock_failure.context.tid &&
247                         lock->fnum == fsp->last_lock_failure.fnum &&
248                         lock->start == fsp->last_lock_failure.start) {
249                 return NT_STATUS_FILE_LOCK_CONFLICT;
250         }
251
252         if (!blocking_lock) {
253                 fsp->last_lock_failure = *lock;
254         }
255         return NT_STATUS_LOCK_NOT_GRANTED;
256 }
257
258 /****************************************************************************
259  Open up the brlock.tdb database.
260 ****************************************************************************/
261
262 void brl_init(int read_only)
263 {
264         if (tdb) {
265                 return;
266         }
267         tdb = tdb_open_log(lock_path("brlock.tdb"),
268                         lp_open_files_db_hash_size(),
269                         TDB_DEFAULT|(read_only?0x0:TDB_CLEAR_IF_FIRST),
270                         read_only?O_RDONLY:(O_RDWR|O_CREAT), 0644 );
271         if (!tdb) {
272                 DEBUG(0,("Failed to open byte range locking database %s\n",
273                         lock_path("brlock.tdb")));
274                 return;
275         }
276
277         /* Activate the per-hashchain freelist */
278         tdb_set_max_dead(tdb, 5);
279 }
280
281 /****************************************************************************
282  Close down the brlock.tdb database.
283 ****************************************************************************/
284
285 void brl_shutdown(int read_only)
286 {
287         if (!tdb) {
288                 return;
289         }
290         tdb_close(tdb);
291 }
292
293 #if ZERO_ZERO
294 /****************************************************************************
295  Compare two locks for sorting.
296 ****************************************************************************/
297
298 static int lock_compare(const struct lock_struct *lck1, 
299                          const struct lock_struct *lck2)
300 {
301         if (lck1->start != lck2->start) {
302                 return (lck1->start - lck2->start);
303         }
304         if (lck2->size != lck1->size) {
305                 return ((int)lck1->size - (int)lck2->size);
306         }
307         return 0;
308 }
309 #endif
310
311 /****************************************************************************
312  Lock a range of bytes - Windows lock semantics.
313 ****************************************************************************/
314
315 static NTSTATUS brl_lock_windows(struct byte_range_lock *br_lck,
316                         const struct lock_struct *plock, BOOL blocking_lock)
317 {
318         unsigned int i;
319         files_struct *fsp = br_lck->fsp;
320         struct lock_struct *locks = br_lck->lock_data;
321
322         for (i=0; i < br_lck->num_locks; i++) {
323                 /* Do any Windows or POSIX locks conflict ? */
324                 if (brl_conflict(&locks[i], plock)) {
325                         return brl_lock_failed(fsp,plock,blocking_lock);
326                 }
327 #if ZERO_ZERO
328                 if (plock->start == 0 && plock->size == 0 && 
329                                 locks[i].size == 0) {
330                         break;
331                 }
332 #endif
333         }
334
335         /* We can get the Windows lock, now see if it needs to
336            be mapped into a lower level POSIX one, and if so can
337            we get it ? */
338
339         if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(fsp->conn->params)) {
340                 int errno_ret;
341                 if (!set_posix_lock_windows_flavour(fsp,
342                                 plock->start,
343                                 plock->size,
344                                 plock->lock_type,
345                                 &plock->context,
346                                 locks,
347                                 br_lck->num_locks,
348                                 &errno_ret)) {
349                         if (errno_ret == EACCES || errno_ret == EAGAIN) {
350                                 return NT_STATUS_FILE_LOCK_CONFLICT;
351                         } else {
352                                 return map_nt_error_from_unix(errno);
353                         }
354                 }
355         }
356
357         /* no conflicts - add it to the list of locks */
358         locks = (struct lock_struct *)SMB_REALLOC(locks, (br_lck->num_locks + 1) * sizeof(*locks));
359         if (!locks) {
360                 return NT_STATUS_NO_MEMORY;
361         }
362
363         memcpy(&locks[br_lck->num_locks], plock, sizeof(struct lock_struct));
364         br_lck->num_locks += 1;
365         br_lck->lock_data = locks;
366         br_lck->modified = True;
367
368         return NT_STATUS_OK;
369 }
370
371 /****************************************************************************
372  Cope with POSIX range splits and merges.
373 ****************************************************************************/
374
375 static unsigned int brlock_posix_split_merge(struct lock_struct *lck_arr,               /* Output array. */
376                                                 const struct lock_struct *ex,           /* existing lock. */
377                                                 const struct lock_struct *plock,        /* proposed lock. */
378                                                 BOOL *lock_was_added)
379 {
380         BOOL lock_types_differ = (ex->lock_type != plock->lock_type);
381
382         /* We can't merge non-conflicting locks on different context - ignore fnum. */
383
384         if (!brl_same_context(&ex->context, &plock->context)) {
385                 /* Just copy. */
386                 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
387                 return 1;
388         }
389
390         /* We now know we have the same context. */
391
392         /* Did we overlap ? */
393
394 /*********************************************
395                                              +---------+
396                                              | ex      |
397                                              +---------+
398                               +-------+
399                               | plock |
400                               +-------+
401 OR....
402              +---------+
403              |  ex     |
404              +---------+
405 **********************************************/
406
407         if ( (ex->start > (plock->start + plock->size)) ||
408                         (plock->start > (ex->start + ex->size))) {
409                 /* No overlap with this lock - copy existing. */
410                 memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
411                 return 1;
412         }
413
414 /*********************************************
415         +---------------------------+
416         |          ex               |
417         +---------------------------+
418         +---------------------------+
419         |       plock               | -> replace with plock.
420         +---------------------------+
421 **********************************************/
422
423         if ( (ex->start >= plock->start) &&
424                         (ex->start + ex->size <= plock->start + plock->size) ) {
425                 memcpy(&lck_arr[0], plock, sizeof(struct lock_struct));
426                 *lock_was_added = True;
427                 return 1;
428         }
429
430 /*********************************************
431         +-----------------------+
432         |          ex           |
433         +-----------------------+
434         +---------------+
435         |   plock       |
436         +---------------+
437 OR....
438                         +-------+
439                         |  ex   |
440                         +-------+
441         +---------------+
442         |   plock       |
443         +---------------+
444
445 BECOMES....
446         +---------------+-------+
447         |   plock       | ex    | - different lock types.
448         +---------------+-------+
449 OR.... (merge)
450         +-----------------------+
451         |   ex                  | - same lock type.
452         +-----------------------+
453 **********************************************/
454
455         if ( (ex->start >= plock->start) &&
456                                 (ex->start <= plock->start + plock->size) &&
457                                 (ex->start + ex->size > plock->start + plock->size) ) {
458
459                 *lock_was_added = True;
460
461                 /* If the lock types are the same, we merge, if different, we
462                    add the new lock before the old. */
463
464                 if (lock_types_differ) {
465                         /* Add new. */
466                         memcpy(&lck_arr[0], plock, sizeof(struct lock_struct));
467                         memcpy(&lck_arr[1], ex, sizeof(struct lock_struct));
468                         /* Adjust existing start and size. */
469                         lck_arr[1].start = plock->start + plock->size;
470                         lck_arr[1].size = (ex->start + ex->size) - (plock->start + plock->size);
471                         return 2;
472                 } else {
473                         /* Merge. */
474                         memcpy(&lck_arr[0], plock, sizeof(struct lock_struct));
475                         /* Set new start and size. */
476                         lck_arr[0].start = plock->start;
477                         lck_arr[0].size = (ex->start + ex->size) - plock->start;
478                         return 1;
479                 }
480         }
481
482 /*********************************************
483    +-----------------------+
484    |  ex                   |
485    +-----------------------+
486            +---------------+
487            |   plock       |
488            +---------------+
489 OR....
490    +-------+        
491    |  ex   |
492    +-------+
493            +---------------+
494            |   plock       |
495            +---------------+
496 BECOMES....
497    +-------+---------------+
498    | ex    |   plock       | - different lock types
499    +-------+---------------+
500
501 OR.... (merge)
502    +-----------------------+
503    | ex                    | - same lock type.
504    +-----------------------+
505
506 **********************************************/
507
508         if ( (ex->start < plock->start) &&
509                         (ex->start + ex->size >= plock->start) &&
510                         (ex->start + ex->size <= plock->start + plock->size) ) {
511
512                 *lock_was_added = True;
513
514                 /* If the lock types are the same, we merge, if different, we
515                    add the new lock after the old. */
516
517                 if (lock_types_differ) {
518                         memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
519                         memcpy(&lck_arr[1], plock, sizeof(struct lock_struct));
520                         /* Adjust existing size. */
521                         lck_arr[0].size = plock->start - ex->start;
522                         return 2;
523                 } else {
524                         /* Merge. */
525                         memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
526                         /* Adjust existing size. */
527                         lck_arr[0].size = (plock->start + plock->size) - ex->start;
528                         return 1;
529                 }
530         }
531
532 /*********************************************
533         +---------------------------+
534         |        ex                 |
535         +---------------------------+
536                 +---------+
537                 |  plock  |
538                 +---------+
539 BECOMES.....
540         +-------+---------+---------+
541         | ex    |  plock  | ex      | - different lock types.
542         +-------+---------+---------+
543 OR
544         +---------------------------+
545         |        ex                 | - same lock type.
546         +---------------------------+
547 **********************************************/
548
549         if ( (ex->start < plock->start) && (ex->start + ex->size > plock->start + plock->size) ) {
550                 *lock_was_added = True;
551
552                 if (lock_types_differ) {
553
554                         /* We have to split ex into two locks here. */
555
556                         memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
557                         memcpy(&lck_arr[1], plock, sizeof(struct lock_struct));
558                         memcpy(&lck_arr[2], ex, sizeof(struct lock_struct));
559
560                         /* Adjust first existing size. */
561                         lck_arr[0].size = plock->start - ex->start;
562
563                         /* Adjust second existing start and size. */
564                         lck_arr[2].start = plock->start + plock->size;
565                         lck_arr[2].size = (ex->start + ex->size) - (plock->start + plock->size);
566                         return 3;
567                 } else {
568                         /* Just eat plock. */
569                         memcpy(&lck_arr[0], ex, sizeof(struct lock_struct));
570                         return 1;
571                 }
572         }
573
574         /* Never get here. */
575         smb_panic("brlock_posix_split_merge\n");
576         /* Notreached. */
577         abort();
578         /* Keep some compilers happy. */
579         return 0;
580 }
581
582 /****************************************************************************
583  Lock a range of bytes - POSIX lock semantics.
584  We must cope with range splits and merges.
585 ****************************************************************************/
586
587 static NTSTATUS brl_lock_posix(struct messaging_context *msg_ctx,
588                                struct byte_range_lock *br_lck,
589                                const struct lock_struct *plock)
590 {
591         unsigned int i, count;
592         struct lock_struct *locks = br_lck->lock_data;
593         struct lock_struct *tp;
594         BOOL lock_was_added = False;
595         BOOL signal_pending_read = False;
596
597         /* No zero-zero locks for POSIX. */
598         if (plock->start == 0 && plock->size == 0) {
599                 return NT_STATUS_INVALID_PARAMETER;
600         }
601
602         /* Don't allow 64-bit lock wrap. */
603         if (plock->start + plock->size < plock->start ||
604                         plock->start + plock->size < plock->size) {
605                 return NT_STATUS_INVALID_PARAMETER;
606         }
607
608         /* The worst case scenario here is we have to split an
609            existing POSIX lock range into two, and add our lock,
610            so we need at most 2 more entries. */
611
612         tp = SMB_MALLOC_ARRAY(struct lock_struct, (br_lck->num_locks + 2));
613         if (!tp) {
614                 return NT_STATUS_NO_MEMORY;
615         }
616         
617         count = 0;
618         for (i=0; i < br_lck->num_locks; i++) {
619                 struct lock_struct *curr_lock = &locks[i];
620
621                 /* If we have a pending read lock, a lock downgrade should
622                    trigger a lock re-evaluation. */
623                 if (curr_lock->lock_type == PENDING_READ_LOCK &&
624                                 brl_pending_overlap(plock, curr_lock)) {
625                         signal_pending_read = True;
626                 }
627
628                 if (curr_lock->lock_flav == WINDOWS_LOCK) {
629                         /* Do any Windows flavour locks conflict ? */
630                         if (brl_conflict(curr_lock, plock)) {
631                                 /* No games with error messages. */
632                                 SAFE_FREE(tp);
633                                 return NT_STATUS_FILE_LOCK_CONFLICT;
634                         }
635                         /* Just copy the Windows lock into the new array. */
636                         memcpy(&tp[count], curr_lock, sizeof(struct lock_struct));
637                         count++;
638                 } else {
639                         /* POSIX conflict semantics are different. */
640                         if (brl_conflict_posix(curr_lock, plock)) {
641                                 /* Can't block ourselves with POSIX locks. */
642                                 /* No games with error messages. */
643                                 SAFE_FREE(tp);
644                                 return NT_STATUS_FILE_LOCK_CONFLICT;
645                         }
646
647                         /* Work out overlaps. */
648                         count += brlock_posix_split_merge(&tp[count], curr_lock, plock, &lock_was_added);
649                 }
650         }
651
652         if (!lock_was_added) {
653                 memcpy(&tp[count], plock, sizeof(struct lock_struct));
654                 count++;
655         }
656
657         /* We can get the POSIX lock, now see if it needs to
658            be mapped into a lower level POSIX one, and if so can
659            we get it ? */
660
661         if (!IS_PENDING_LOCK(plock->lock_type) && lp_posix_locking(br_lck->fsp->conn->params)) {
662                 int errno_ret;
663
664                 /* The lower layer just needs to attempt to
665                    get the system POSIX lock. We've weeded out
666                    any conflicts above. */
667
668                 if (!set_posix_lock_posix_flavour(br_lck->fsp,
669                                 plock->start,
670                                 plock->size,
671                                 plock->lock_type,
672                                 &errno_ret)) {
673                         if (errno_ret == EACCES || errno_ret == EAGAIN) {
674                                 SAFE_FREE(tp);
675                                 return NT_STATUS_FILE_LOCK_CONFLICT;
676                         } else {
677                                 SAFE_FREE(tp);
678                                 return map_nt_error_from_unix(errno);
679                         }
680                 }
681         }
682
683         /* Realloc so we don't leak entries per lock call. */
684         tp = (struct lock_struct *)SMB_REALLOC(tp, count * sizeof(*locks));
685         if (!tp) {
686                 return NT_STATUS_NO_MEMORY;
687         }
688         br_lck->num_locks = count;
689         SAFE_FREE(br_lck->lock_data);
690         br_lck->lock_data = tp;
691         locks = tp;
692         br_lck->modified = True;
693
694         /* A successful downgrade from write to read lock can trigger a lock
695            re-evalutation where waiting readers can now proceed. */
696
697         if (signal_pending_read) {
698                 /* Send unlock messages to any pending read waiters that overlap. */
699                 for (i=0; i < br_lck->num_locks; i++) {
700                         struct lock_struct *pend_lock = &locks[i];
701
702                         /* Ignore non-pending locks. */
703                         if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
704                                 continue;
705                         }
706
707                         if (pend_lock->lock_type == PENDING_READ_LOCK &&
708                                         brl_pending_overlap(plock, pend_lock)) {
709                                 DEBUG(10,("brl_lock_posix: sending unlock message to pid %s\n",
710                                         procid_str_static(&pend_lock->context.pid )));
711
712                                 messaging_send(msg_ctx, pend_lock->context.pid,
713                                                MSG_SMB_UNLOCK, &data_blob_null);
714                         }
715                 }
716         }
717
718         return NT_STATUS_OK;
719 }
720
721 /****************************************************************************
722  Lock a range of bytes.
723 ****************************************************************************/
724
725 NTSTATUS brl_lock(struct messaging_context *msg_ctx,
726                 struct byte_range_lock *br_lck,
727                 uint32 smbpid,
728                 struct server_id pid,
729                 br_off start,
730                 br_off size, 
731                 enum brl_type lock_type,
732                 enum brl_flavour lock_flav,
733                 BOOL blocking_lock)
734 {
735         NTSTATUS ret;
736         struct lock_struct lock;
737
738 #if !ZERO_ZERO
739         if (start == 0 && size == 0) {
740                 DEBUG(0,("client sent 0/0 lock - please report this\n"));
741         }
742 #endif
743
744         lock.context.smbpid = smbpid;
745         lock.context.pid = pid;
746         lock.context.tid = br_lck->fsp->conn->cnum;
747         lock.start = start;
748         lock.size = size;
749         lock.fnum = br_lck->fsp->fnum;
750         lock.lock_type = lock_type;
751         lock.lock_flav = lock_flav;
752
753         if (lock_flav == WINDOWS_LOCK) {
754                 ret = brl_lock_windows(br_lck, &lock, blocking_lock);
755         } else {
756                 ret = brl_lock_posix(msg_ctx, br_lck, &lock);
757         }
758
759 #if ZERO_ZERO
760         /* sort the lock list */
761         qsort(br_lck->lock_data, (size_t)br_lck->num_locks, sizeof(lock), lock_compare);
762 #endif
763
764         return ret;
765 }
766
767 /****************************************************************************
768  Unlock a range of bytes - Windows semantics.
769 ****************************************************************************/
770
771 static BOOL brl_unlock_windows(struct messaging_context *msg_ctx,
772                                struct byte_range_lock *br_lck,
773                                const struct lock_struct *plock)
774 {
775         unsigned int i, j;
776         struct lock_struct *locks = br_lck->lock_data;
777         enum brl_type deleted_lock_type = READ_LOCK; /* shut the compiler up.... */
778
779 #if ZERO_ZERO
780         /* Delete write locks by preference... The lock list
781            is sorted in the zero zero case. */
782
783         for (i = 0; i < br_lck->num_locks; i++) {
784                 struct lock_struct *lock = &locks[i];
785
786                 if (lock->lock_type == WRITE_LOCK &&
787                     brl_same_context(&lock->context, &plock->context) &&
788                     lock->fnum == plock->fnum &&
789                     lock->lock_flav == WINDOWS_LOCK &&
790                     lock->start == plock->start &&
791                     lock->size == plock->size) {
792
793                         /* found it - delete it */
794                         deleted_lock_type = lock->lock_type;
795                         break;
796                 }
797         }
798
799         if (i != br_lck->num_locks) {
800                 /* We found it - don't search again. */
801                 goto unlock_continue;
802         }
803 #endif
804
805         for (i = 0; i < br_lck->num_locks; i++) {
806                 struct lock_struct *lock = &locks[i];
807
808                 /* Only remove our own locks that match in start, size, and flavour. */
809                 if (brl_same_context(&lock->context, &plock->context) &&
810                                         lock->fnum == plock->fnum &&
811                                         lock->lock_flav == WINDOWS_LOCK &&
812                                         lock->start == plock->start &&
813                                         lock->size == plock->size ) {
814                         deleted_lock_type = lock->lock_type;
815                         break;
816                 }
817         }
818
819         if (i == br_lck->num_locks) {
820                 /* we didn't find it */
821                 return False;
822         }
823
824 #if ZERO_ZERO
825   unlock_continue:
826 #endif
827
828         /* Actually delete the lock. */
829         if (i < br_lck->num_locks - 1) {
830                 memmove(&locks[i], &locks[i+1], 
831                         sizeof(*locks)*((br_lck->num_locks-1) - i));
832         }
833
834         br_lck->num_locks -= 1;
835         br_lck->modified = True;
836
837         /* Unlock the underlying POSIX regions. */
838         if(lp_posix_locking(br_lck->fsp->conn->params)) {
839                 release_posix_lock_windows_flavour(br_lck->fsp,
840                                 plock->start,
841                                 plock->size,
842                                 deleted_lock_type,
843                                 &plock->context,
844                                 locks,
845                                 br_lck->num_locks);
846         }
847
848         /* Send unlock messages to any pending waiters that overlap. */
849         for (j=0; j < br_lck->num_locks; j++) {
850                 struct lock_struct *pend_lock = &locks[j];
851
852                 /* Ignore non-pending locks. */
853                 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
854                         continue;
855                 }
856
857                 /* We could send specific lock info here... */
858                 if (brl_pending_overlap(plock, pend_lock)) {
859                         DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
860                                 procid_str_static(&pend_lock->context.pid )));
861
862                         messaging_send(msg_ctx, pend_lock->context.pid,
863                                        MSG_SMB_UNLOCK, &data_blob_null);
864                 }
865         }
866
867         return True;
868 }
869
870 /****************************************************************************
871  Unlock a range of bytes - POSIX semantics.
872 ****************************************************************************/
873
874 static BOOL brl_unlock_posix(struct messaging_context *msg_ctx,
875                              struct byte_range_lock *br_lck,
876                              const struct lock_struct *plock)
877 {
878         unsigned int i, j, count;
879         struct lock_struct *tp;
880         struct lock_struct *locks = br_lck->lock_data;
881         BOOL overlap_found = False;
882
883         /* No zero-zero locks for POSIX. */
884         if (plock->start == 0 && plock->size == 0) {
885                 return False;
886         }
887
888         /* Don't allow 64-bit lock wrap. */
889         if (plock->start + plock->size < plock->start ||
890                         plock->start + plock->size < plock->size) {
891                 DEBUG(10,("brl_unlock_posix: lock wrap\n"));
892                 return False;
893         }
894
895         /* The worst case scenario here is we have to split an
896            existing POSIX lock range into two, so we need at most
897            1 more entry. */
898
899         tp = SMB_MALLOC_ARRAY(struct lock_struct, (br_lck->num_locks + 1));
900         if (!tp) {
901                 DEBUG(10,("brl_unlock_posix: malloc fail\n"));
902                 return False;
903         }
904
905         count = 0;
906         for (i = 0; i < br_lck->num_locks; i++) {
907                 struct lock_struct *lock = &locks[i];
908                 struct lock_struct tmp_lock[3];
909                 BOOL lock_was_added = False;
910                 unsigned int tmp_count;
911
912                 /* Only remove our own locks - ignore fnum. */
913                 if (IS_PENDING_LOCK(lock->lock_type) ||
914                                 !brl_same_context(&lock->context, &plock->context)) {
915                         memcpy(&tp[count], lock, sizeof(struct lock_struct));
916                         count++;
917                         continue;
918                 }
919
920                 /* Work out overlaps. */
921                 tmp_count = brlock_posix_split_merge(&tmp_lock[0], &locks[i], plock, &lock_was_added);
922
923                 if (tmp_count == 1) {
924                         /* Ether the locks didn't overlap, or the unlock completely
925                            overlapped this lock. If it didn't overlap, then there's
926                            no change in the locks. */
927                         if (tmp_lock[0].lock_type != UNLOCK_LOCK) {
928                                 SMB_ASSERT(tmp_lock[0].lock_type == locks[i].lock_type);
929                                 /* No change in this lock. */
930                                 memcpy(&tp[count], &tmp_lock[0], sizeof(struct lock_struct));
931                                 count++;
932                         } else {
933                                 SMB_ASSERT(tmp_lock[0].lock_type == UNLOCK_LOCK);
934                                 overlap_found = True;
935                         }
936                         continue;
937                 } else if (tmp_count == 2) {
938                         /* The unlock overlapped an existing lock. Copy the truncated
939                            lock into the lock array. */
940                         if (tmp_lock[0].lock_type != UNLOCK_LOCK) {
941                                 SMB_ASSERT(tmp_lock[0].lock_type == locks[i].lock_type);
942                                 SMB_ASSERT(tmp_lock[1].lock_type == UNLOCK_LOCK);
943                                 memcpy(&tp[count], &tmp_lock[0], sizeof(struct lock_struct));
944                                 if (tmp_lock[0].size != locks[i].size) {
945                                         overlap_found = True;
946                                 }
947                         } else {
948                                 SMB_ASSERT(tmp_lock[0].lock_type == UNLOCK_LOCK);
949                                 SMB_ASSERT(tmp_lock[1].lock_type == locks[i].lock_type);
950                                 memcpy(&tp[count], &tmp_lock[1], sizeof(struct lock_struct));
951                                 if (tmp_lock[1].start != locks[i].start) {
952                                         overlap_found = True;
953                                 }
954                         }
955                         count++;
956                         continue;
957                 } else {
958                         /* tmp_count == 3 - (we split a lock range in two). */
959                         SMB_ASSERT(tmp_lock[0].lock_type == locks[i].lock_type);
960                         SMB_ASSERT(tmp_lock[1].lock_type == UNLOCK_LOCK);
961                         SMB_ASSERT(tmp_lock[2].lock_type == locks[i].lock_type);
962
963                         memcpy(&tp[count], &tmp_lock[0], sizeof(struct lock_struct));
964                         count++;
965                         memcpy(&tp[count], &tmp_lock[2], sizeof(struct lock_struct));
966                         count++;
967                         overlap_found = True;
968                         /* Optimisation... */
969                         /* We know we're finished here as we can't overlap any
970                            more POSIX locks. Copy the rest of the lock array. */
971                         if (i < br_lck->num_locks - 1) {
972                                 memcpy(&tp[count], &locks[i+1], 
973                                         sizeof(*locks)*((br_lck->num_locks-1) - i));
974                                 count += ((br_lck->num_locks-1) - i);
975                         }
976                         break;
977                 }
978         }
979
980         if (!overlap_found) {
981                 /* Just ignore - no change. */
982                 SAFE_FREE(tp);
983                 DEBUG(10,("brl_unlock_posix: No overlap - unlocked.\n"));
984                 return True;
985         }
986
987         /* Unlock any POSIX regions. */
988         if(lp_posix_locking(br_lck->fsp->conn->params)) {
989                 release_posix_lock_posix_flavour(br_lck->fsp,
990                                                 plock->start,
991                                                 plock->size,
992                                                 &plock->context,
993                                                 tp,
994                                                 count);
995         }
996
997         /* Realloc so we don't leak entries per unlock call. */
998         if (count) {
999                 tp = (struct lock_struct *)SMB_REALLOC(tp, count * sizeof(*locks));
1000                 if (!tp) {
1001                         DEBUG(10,("brl_unlock_posix: realloc fail\n"));
1002                         return False;
1003                 }
1004         } else {
1005                 /* We deleted the last lock. */
1006                 SAFE_FREE(tp);
1007                 tp = NULL;
1008         }
1009
1010         br_lck->num_locks = count;
1011         SAFE_FREE(br_lck->lock_data);
1012         locks = tp;
1013         br_lck->lock_data = tp;
1014         br_lck->modified = True;
1015
1016         /* Send unlock messages to any pending waiters that overlap. */
1017
1018         for (j=0; j < br_lck->num_locks; j++) {
1019                 struct lock_struct *pend_lock = &locks[j];
1020
1021                 /* Ignore non-pending locks. */
1022                 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1023                         continue;
1024                 }
1025
1026                 /* We could send specific lock info here... */
1027                 if (brl_pending_overlap(plock, pend_lock)) {
1028                         DEBUG(10,("brl_unlock: sending unlock message to pid %s\n",
1029                                 procid_str_static(&pend_lock->context.pid )));
1030
1031                         messaging_send(msg_ctx, pend_lock->context.pid,
1032                                        MSG_SMB_UNLOCK, &data_blob_null);
1033                 }
1034         }
1035
1036         return True;
1037 }
1038
1039 /****************************************************************************
1040  Unlock a range of bytes.
1041 ****************************************************************************/
1042
1043 BOOL brl_unlock(struct messaging_context *msg_ctx,
1044                 struct byte_range_lock *br_lck,
1045                 uint32 smbpid,
1046                 struct server_id pid,
1047                 br_off start,
1048                 br_off size,
1049                 enum brl_flavour lock_flav)
1050 {
1051         struct lock_struct lock;
1052
1053         lock.context.smbpid = smbpid;
1054         lock.context.pid = pid;
1055         lock.context.tid = br_lck->fsp->conn->cnum;
1056         lock.start = start;
1057         lock.size = size;
1058         lock.fnum = br_lck->fsp->fnum;
1059         lock.lock_type = UNLOCK_LOCK;
1060         lock.lock_flav = lock_flav;
1061
1062         if (lock_flav == WINDOWS_LOCK) {
1063                 return brl_unlock_windows(msg_ctx, br_lck, &lock);
1064         } else {
1065                 return brl_unlock_posix(msg_ctx, br_lck, &lock);
1066         }
1067 }
1068
1069 /****************************************************************************
1070  Test if we could add a lock if we wanted to.
1071  Returns True if the region required is currently unlocked, False if locked.
1072 ****************************************************************************/
1073
1074 BOOL brl_locktest(struct byte_range_lock *br_lck,
1075                 uint32 smbpid,
1076                 struct server_id pid,
1077                 br_off start,
1078                 br_off size, 
1079                 enum brl_type lock_type,
1080                 enum brl_flavour lock_flav)
1081 {
1082         BOOL ret = True;
1083         unsigned int i;
1084         struct lock_struct lock;
1085         const struct lock_struct *locks = br_lck->lock_data;
1086         files_struct *fsp = br_lck->fsp;
1087
1088         lock.context.smbpid = smbpid;
1089         lock.context.pid = pid;
1090         lock.context.tid = br_lck->fsp->conn->cnum;
1091         lock.start = start;
1092         lock.size = size;
1093         lock.fnum = fsp->fnum;
1094         lock.lock_type = lock_type;
1095         lock.lock_flav = lock_flav;
1096
1097         /* Make sure existing locks don't conflict */
1098         for (i=0; i < br_lck->num_locks; i++) {
1099                 /*
1100                  * Our own locks don't conflict.
1101                  */
1102                 if (brl_conflict_other(&locks[i], &lock)) {
1103                         return False;
1104                 }
1105         }
1106
1107         /*
1108          * There is no lock held by an SMB daemon, check to
1109          * see if there is a POSIX lock from a UNIX or NFS process.
1110          * This only conflicts with Windows locks, not POSIX locks.
1111          */
1112
1113         if(lp_posix_locking(fsp->conn->params) && (lock_flav == WINDOWS_LOCK)) {
1114                 ret = is_posix_locked(fsp, &start, &size, &lock_type, WINDOWS_LOCK);
1115
1116                 DEBUG(10,("brl_locktest: posix start=%.0f len=%.0f %s for fnum %d file %s\n",
1117                         (double)start, (double)size, ret ? "locked" : "unlocked",
1118                         fsp->fnum, fsp->fsp_name ));
1119
1120                 /* We need to return the inverse of is_posix_locked. */
1121                 ret = !ret;
1122         }
1123
1124         /* no conflicts - we could have added it */
1125         return ret;
1126 }
1127
1128 /****************************************************************************
1129  Query for existing locks.
1130 ****************************************************************************/
1131
1132 NTSTATUS brl_lockquery(struct byte_range_lock *br_lck,
1133                 uint32 *psmbpid,
1134                 struct server_id pid,
1135                 br_off *pstart,
1136                 br_off *psize, 
1137                 enum brl_type *plock_type,
1138                 enum brl_flavour lock_flav)
1139 {
1140         unsigned int i;
1141         struct lock_struct lock;
1142         const struct lock_struct *locks = br_lck->lock_data;
1143         files_struct *fsp = br_lck->fsp;
1144
1145         lock.context.smbpid = *psmbpid;
1146         lock.context.pid = pid;
1147         lock.context.tid = br_lck->fsp->conn->cnum;
1148         lock.start = *pstart;
1149         lock.size = *psize;
1150         lock.fnum = fsp->fnum;
1151         lock.lock_type = *plock_type;
1152         lock.lock_flav = lock_flav;
1153
1154         /* Make sure existing locks don't conflict */
1155         for (i=0; i < br_lck->num_locks; i++) {
1156                 const struct lock_struct *exlock = &locks[i];
1157                 BOOL conflict = False;
1158
1159                 if (exlock->lock_flav == WINDOWS_LOCK) {
1160                         conflict = brl_conflict(exlock, &lock);
1161                 } else {        
1162                         conflict = brl_conflict_posix(exlock, &lock);
1163                 }
1164
1165                 if (conflict) {
1166                         *psmbpid = exlock->context.smbpid;
1167                         *pstart = exlock->start;
1168                         *psize = exlock->size;
1169                         *plock_type = exlock->lock_type;
1170                         return NT_STATUS_LOCK_NOT_GRANTED;
1171                 }
1172         }
1173
1174         /*
1175          * There is no lock held by an SMB daemon, check to
1176          * see if there is a POSIX lock from a UNIX or NFS process.
1177          */
1178
1179         if(lp_posix_locking(fsp->conn->params)) {
1180                 BOOL ret = is_posix_locked(fsp, pstart, psize, plock_type, POSIX_LOCK);
1181
1182                 DEBUG(10,("brl_lockquery: posix start=%.0f len=%.0f %s for fnum %d file %s\n",
1183                         (double)*pstart, (double)*psize, ret ? "locked" : "unlocked",
1184                         fsp->fnum, fsp->fsp_name ));
1185
1186                 if (ret) {
1187                         /* Hmmm. No clue what to set smbpid to - use -1. */
1188                         *psmbpid = 0xFFFF;
1189                         return NT_STATUS_LOCK_NOT_GRANTED;
1190                 }
1191         }
1192
1193         return NT_STATUS_OK;
1194 }
1195
1196 /****************************************************************************
1197  Remove a particular pending lock.
1198 ****************************************************************************/
1199
1200 BOOL brl_lock_cancel(struct byte_range_lock *br_lck,
1201                 uint32 smbpid,
1202                 struct server_id pid,
1203                 br_off start,
1204                 br_off size,
1205                 enum brl_flavour lock_flav)
1206 {
1207         unsigned int i;
1208         struct lock_struct *locks = br_lck->lock_data;
1209         struct lock_context context;
1210
1211         context.smbpid = smbpid;
1212         context.pid = pid;
1213         context.tid = br_lck->fsp->conn->cnum;
1214
1215         for (i = 0; i < br_lck->num_locks; i++) {
1216                 struct lock_struct *lock = &locks[i];
1217
1218                 /* For pending locks we *always* care about the fnum. */
1219                 if (brl_same_context(&lock->context, &context) &&
1220                                 lock->fnum == br_lck->fsp->fnum &&
1221                                 IS_PENDING_LOCK(lock->lock_type) &&
1222                                 lock->lock_flav == lock_flav &&
1223                                 lock->start == start &&
1224                                 lock->size == size) {
1225                         break;
1226                 }
1227         }
1228
1229         if (i == br_lck->num_locks) {
1230                 /* Didn't find it. */
1231                 return False;
1232         }
1233
1234         if (i < br_lck->num_locks - 1) {
1235                 /* Found this particular pending lock - delete it */
1236                 memmove(&locks[i], &locks[i+1], 
1237                         sizeof(*locks)*((br_lck->num_locks-1) - i));
1238         }
1239
1240         br_lck->num_locks -= 1;
1241         br_lck->modified = True;
1242         return True;
1243 }
1244
1245 /****************************************************************************
1246  Remove any locks associated with a open file.
1247  We return True if this process owns any other Windows locks on this
1248  fd and so we should not immediately close the fd.
1249 ****************************************************************************/
1250
1251 void brl_close_fnum(struct messaging_context *msg_ctx,
1252                     struct byte_range_lock *br_lck)
1253 {
1254         files_struct *fsp = br_lck->fsp;
1255         uint16 tid = fsp->conn->cnum;
1256         int fnum = fsp->fnum;
1257         unsigned int i, j, dcount=0;
1258         int num_deleted_windows_locks = 0;
1259         struct lock_struct *locks = br_lck->lock_data;
1260         struct server_id pid = procid_self();
1261         BOOL unlock_individually = False;
1262
1263         if(lp_posix_locking(fsp->conn->params)) {
1264
1265                 /* Check if there are any Windows locks associated with this dev/ino
1266                    pair that are not this fnum. If so we need to call unlock on each
1267                    one in order to release the system POSIX locks correctly. */
1268
1269                 for (i=0; i < br_lck->num_locks; i++) {
1270                         struct lock_struct *lock = &locks[i];
1271
1272                         if (!procid_equal(&lock->context.pid, &pid)) {
1273                                 continue;
1274                         }
1275
1276                         if (lock->lock_type != READ_LOCK && lock->lock_type != WRITE_LOCK) {
1277                                 continue; /* Ignore pending. */
1278                         }
1279
1280                         if (lock->context.tid != tid || lock->fnum != fnum) {
1281                                 unlock_individually = True;
1282                                 break;
1283                         }
1284                 }
1285
1286                 if (unlock_individually) {
1287                         struct lock_struct *locks_copy;
1288                         unsigned int num_locks_copy;
1289
1290                         /* Copy the current lock array. */
1291                         if (br_lck->num_locks) {
1292                                 locks_copy = (struct lock_struct *)TALLOC_MEMDUP(br_lck, locks, br_lck->num_locks * sizeof(struct lock_struct));
1293                                 if (!locks_copy) {
1294                                         smb_panic("brl_close_fnum: talloc fail.\n");
1295                                 }
1296                         } else {        
1297                                 locks_copy = NULL;
1298                         }
1299
1300                         num_locks_copy = br_lck->num_locks;
1301
1302                         for (i=0; i < num_locks_copy; i++) {
1303                                 struct lock_struct *lock = &locks_copy[i];
1304
1305                                 if (lock->context.tid == tid && procid_equal(&lock->context.pid, &pid) &&
1306                                                 (lock->fnum == fnum)) {
1307                                         brl_unlock(msg_ctx,
1308                                                 br_lck,
1309                                                 lock->context.smbpid,
1310                                                 pid,
1311                                                 lock->start,
1312                                                 lock->size,
1313                                                 lock->lock_flav);
1314                                 }
1315                         }
1316                         return;
1317                 }
1318         }
1319
1320         /* We can bulk delete - any POSIX locks will be removed when the fd closes. */
1321
1322         /* Remove any existing locks for this fnum (or any fnum if they're POSIX). */
1323
1324         for (i=0; i < br_lck->num_locks; i++) {
1325                 struct lock_struct *lock = &locks[i];
1326                 BOOL del_this_lock = False;
1327
1328                 if (lock->context.tid == tid && procid_equal(&lock->context.pid, &pid)) {
1329                         if ((lock->lock_flav == WINDOWS_LOCK) && (lock->fnum == fnum)) {
1330                                 del_this_lock = True;
1331                                 num_deleted_windows_locks++;
1332                         } else if (lock->lock_flav == POSIX_LOCK) {
1333                                 del_this_lock = True;
1334                         }
1335                 }
1336
1337                 if (del_this_lock) {
1338                         /* Send unlock messages to any pending waiters that overlap. */
1339                         for (j=0; j < br_lck->num_locks; j++) {
1340                                 struct lock_struct *pend_lock = &locks[j];
1341
1342                                 /* Ignore our own or non-pending locks. */
1343                                 if (!IS_PENDING_LOCK(pend_lock->lock_type)) {
1344                                         continue;
1345                                 }
1346
1347                                 /* Optimisation - don't send to this fnum as we're
1348                                    closing it. */
1349                                 if (pend_lock->context.tid == tid &&
1350                                     procid_equal(&pend_lock->context.pid, &pid) &&
1351                                     pend_lock->fnum == fnum) {
1352                                         continue;
1353                                 }
1354
1355                                 /* We could send specific lock info here... */
1356                                 if (brl_pending_overlap(lock, pend_lock)) {
1357                                         messaging_send(msg_ctx, pend_lock->context.pid,
1358                                                        MSG_SMB_UNLOCK, &data_blob_null);
1359                                 }
1360                         }
1361
1362                         /* found it - delete it */
1363                         if (br_lck->num_locks > 1 && i < br_lck->num_locks - 1) {
1364                                 memmove(&locks[i], &locks[i+1], 
1365                                         sizeof(*locks)*((br_lck->num_locks-1) - i));
1366                         }
1367                         br_lck->num_locks--;
1368                         br_lck->modified = True;
1369                         i--;
1370                         dcount++;
1371                 }
1372         }
1373
1374         if(lp_posix_locking(fsp->conn->params) && num_deleted_windows_locks) {
1375                 /* Reduce the Windows lock POSIX reference count on this dev/ino pair. */
1376                 reduce_windows_lock_ref_count(fsp, num_deleted_windows_locks);
1377         }
1378 }
1379
1380 /****************************************************************************
1381  Ensure this set of lock entries is valid.
1382 ****************************************************************************/
1383
1384 static BOOL validate_lock_entries(unsigned int *pnum_entries, struct lock_struct **pplocks)
1385 {
1386         unsigned int i;
1387         unsigned int num_valid_entries = 0;
1388         struct lock_struct *locks = *pplocks;
1389
1390         for (i = 0; i < *pnum_entries; i++) {
1391                 struct lock_struct *lock_data = &locks[i];
1392                 if (!process_exists(lock_data->context.pid)) {
1393                         /* This process no longer exists - mark this
1394                            entry as invalid by zeroing it. */
1395                         ZERO_STRUCTP(lock_data);
1396                 } else {
1397                         num_valid_entries++;
1398                 }
1399         }
1400
1401         if (num_valid_entries != *pnum_entries) {
1402                 struct lock_struct *new_lock_data = NULL;
1403
1404                 if (num_valid_entries) {
1405                         new_lock_data = SMB_MALLOC_ARRAY(struct lock_struct, num_valid_entries);
1406                         if (!new_lock_data) {
1407                                 DEBUG(3, ("malloc fail\n"));
1408                                 return False;
1409                         }
1410
1411                         num_valid_entries = 0;
1412                         for (i = 0; i < *pnum_entries; i++) {
1413                                 struct lock_struct *lock_data = &locks[i];
1414                                 if (lock_data->context.smbpid &&
1415                                                 lock_data->context.tid) {
1416                                         /* Valid (nonzero) entry - copy it. */
1417                                         memcpy(&new_lock_data[num_valid_entries],
1418                                                 lock_data, sizeof(struct lock_struct));
1419                                         num_valid_entries++;
1420                                 }
1421                         }
1422                 }
1423
1424                 SAFE_FREE(*pplocks);
1425                 *pplocks = new_lock_data;
1426                 *pnum_entries = num_valid_entries;
1427         }
1428
1429         return True;
1430 }
1431
1432 /****************************************************************************
1433  Traverse the whole database with this function, calling traverse_callback
1434  on each lock.
1435 ****************************************************************************/
1436
1437 static int traverse_fn(TDB_CONTEXT *ttdb, TDB_DATA kbuf, TDB_DATA dbuf, void *state)
1438 {
1439         struct lock_struct *locks;
1440         struct lock_key *key;
1441         unsigned int i;
1442         unsigned int num_locks = 0;
1443         unsigned int orig_num_locks = 0;
1444
1445         BRLOCK_FN(traverse_callback) = (BRLOCK_FN_CAST())state;
1446
1447         /* In a traverse function we must make a copy of
1448            dbuf before modifying it. */
1449
1450         locks = (struct lock_struct *)memdup(dbuf.dptr, dbuf.dsize);
1451         if (!locks) {
1452                 return -1; /* Terminate traversal. */
1453         }
1454
1455         key = (struct lock_key *)kbuf.dptr;
1456         orig_num_locks = num_locks = dbuf.dsize/sizeof(*locks);
1457
1458         /* Ensure the lock db is clean of entries from invalid processes. */
1459
1460         if (!validate_lock_entries(&num_locks, &locks)) {
1461                 SAFE_FREE(locks);
1462                 return -1; /* Terminate traversal */
1463         }
1464
1465         if (orig_num_locks != num_locks) {
1466                 dbuf.dptr = (uint8 *)locks;
1467                 dbuf.dsize = num_locks * sizeof(*locks);
1468
1469                 if (dbuf.dsize) {
1470                         tdb_store(ttdb, kbuf, dbuf, TDB_REPLACE);
1471                 } else {
1472                         tdb_delete(ttdb, kbuf);
1473                 }
1474         }
1475
1476         for ( i=0; i<num_locks; i++) {
1477                 traverse_callback(key->device,
1478                                   key->inode,
1479                                   locks[i].context.pid,
1480                                   locks[i].lock_type,
1481                                   locks[i].lock_flav,
1482                                   locks[i].start,
1483                                   locks[i].size);
1484         }
1485
1486         SAFE_FREE(locks);
1487         return 0;
1488 }
1489
1490 /*******************************************************************
1491  Call the specified function on each lock in the database.
1492 ********************************************************************/
1493
1494 int brl_forall(BRLOCK_FN(fn))
1495 {
1496         if (!tdb) {
1497                 return 0;
1498         }
1499         return tdb_traverse(tdb, traverse_fn, (void *)fn);
1500 }
1501
1502 /*******************************************************************
1503  Store a potentially modified set of byte range lock data back into
1504  the database.
1505  Unlock the record.
1506 ********************************************************************/
1507
1508 static int byte_range_lock_destructor(struct byte_range_lock *br_lck)
1509 {
1510         TDB_DATA key;
1511
1512         key.dptr = (uint8 *)&br_lck->key;
1513         key.dsize = sizeof(struct lock_key);
1514
1515         if (br_lck->read_only) {
1516                 SMB_ASSERT(!br_lck->modified);
1517         }
1518
1519         if (!br_lck->modified) {
1520                 goto done;
1521         }
1522
1523         if (br_lck->num_locks == 0) {
1524                 /* No locks - delete this entry. */
1525                 if (tdb_delete(tdb, key) == -1) {
1526                         smb_panic("Could not delete byte range lock entry\n");
1527                 }
1528         } else {
1529                 TDB_DATA data;
1530                 data.dptr = (uint8 *)br_lck->lock_data;
1531                 data.dsize = br_lck->num_locks * sizeof(struct lock_struct);
1532
1533                 if (tdb_store(tdb, key, data, TDB_REPLACE) == -1) {
1534                         smb_panic("Could not store byte range mode entry\n");
1535                 }
1536         }
1537
1538  done:
1539
1540         if (!br_lck->read_only) {
1541                 tdb_chainunlock(tdb, key);
1542         }
1543         SAFE_FREE(br_lck->lock_data);
1544         return 0;
1545 }
1546
1547 /*******************************************************************
1548  Fetch a set of byte range lock data from the database.
1549  Leave the record locked.
1550  TALLOC_FREE(brl) will release the lock in the destructor.
1551 ********************************************************************/
1552
1553 static struct byte_range_lock *brl_get_locks_internal(TALLOC_CTX *mem_ctx,
1554                                         files_struct *fsp, BOOL read_only)
1555 {
1556         TDB_DATA key;
1557         TDB_DATA data;
1558         struct byte_range_lock *br_lck = TALLOC_P(mem_ctx, struct byte_range_lock);
1559
1560         if (br_lck == NULL) {
1561                 return NULL;
1562         }
1563
1564         br_lck->fsp = fsp;
1565         br_lck->num_locks = 0;
1566         br_lck->modified = False;
1567         memset(&br_lck->key, '\0', sizeof(struct lock_key));
1568         br_lck->key.device = fsp->dev;
1569         br_lck->key.inode = fsp->inode;
1570
1571         key.dptr = (uint8 *)&br_lck->key;
1572         key.dsize = sizeof(struct lock_key);
1573
1574         if (!fsp->lockdb_clean) {
1575                 /* We must be read/write to clean
1576                    the dead entries. */
1577                 read_only = False;
1578         }
1579
1580         if (read_only) {
1581                 br_lck->read_only = True;
1582         } else {
1583                 if (tdb_chainlock(tdb, key) != 0) {
1584                         DEBUG(3, ("Could not lock byte range lock entry\n"));
1585                         TALLOC_FREE(br_lck);
1586                         return NULL;
1587                 }
1588                 br_lck->read_only = False;
1589         }
1590
1591         talloc_set_destructor(br_lck, byte_range_lock_destructor);
1592
1593         data = tdb_fetch(tdb, key);
1594         br_lck->lock_data = (struct lock_struct *)data.dptr;
1595         br_lck->num_locks = data.dsize / sizeof(struct lock_struct);
1596
1597         if (!fsp->lockdb_clean) {
1598
1599                 /* This is the first time we've accessed this. */
1600                 /* Go through and ensure all entries exist - remove any that don't. */
1601                 /* Makes the lockdb self cleaning at low cost. */
1602
1603                 if (!validate_lock_entries(&br_lck->num_locks,
1604                                            &br_lck->lock_data)) {
1605                         SAFE_FREE(br_lck->lock_data);
1606                         TALLOC_FREE(br_lck);
1607                         return NULL;
1608                 }
1609
1610                 /* Mark the lockdb as "clean" as seen from this open file. */
1611                 fsp->lockdb_clean = True;
1612         }
1613
1614         if (DEBUGLEVEL >= 10) {
1615                 unsigned int i;
1616                 struct lock_struct *locks = br_lck->lock_data;
1617                 DEBUG(10,("brl_get_locks_internal: %u current locks on dev=%.0f, inode=%.0f\n",
1618                         br_lck->num_locks,
1619                         (double)fsp->dev, (double)fsp->inode ));
1620                 for( i = 0; i < br_lck->num_locks; i++) {
1621                         print_lock_struct(i, &locks[i]);
1622                 }
1623         }
1624         return br_lck;
1625 }
1626
1627 struct byte_range_lock *brl_get_locks(TALLOC_CTX *mem_ctx,
1628                                         files_struct *fsp)
1629 {
1630         return brl_get_locks_internal(mem_ctx, fsp, False);
1631 }
1632
1633 struct byte_range_lock *brl_get_locks_readonly(TALLOC_CTX *mem_ctx,
1634                                         files_struct *fsp)
1635 {
1636         return brl_get_locks_internal(mem_ctx, fsp, True);
1637 }