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