]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_lock.c
factorize lock test (fewer fcntl calls)
[netatalk.git] / libatalk / adouble / ad_lock.c
1 /* 
2  * $Id: ad_lock.c,v 1.17 2009-10-21 13:28:17 didg Exp $
3  *
4  * Copyright (c) 1998,1999 Adrian Sun (asun@zoology.washington.edu)
5  * All Rights Reserved. See COPYRIGHT for more information.
6  *
7  * Byte-range locks. This uses either whole-file flocks to fake byte
8  * locks or fcntl-based actual byte locks. Because fcntl locks are
9  * process-oriented, we need to keep around a list of file descriptors
10  * that refer to the same file. Currently, this doesn't serialize access 
11  * to the locks. as a result, there's the potential for race conditions. 
12  *
13  * TODO: fix the race when reading/writing.
14  *       keep a pool of both locks and reference counters around so that
15  *       we can save on mallocs. we should also use a tree to keep things
16  *       sorted.
17  */
18
19 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif /* HAVE_CONFIG_H */
22
23 #include <atalk/adouble.h>
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <errno.h>
28
29 #include <string.h>
30
31 #include "ad_private.h"
32
33 /* translate between ADLOCK styles and specific locking mechanisms */
34 #define XLATE_FLOCK(type) ((type) == ADLOCK_RD ? LOCK_SH : \
35 ((type) == ADLOCK_WR ? LOCK_EX : \
36  ((type) == ADLOCK_CLR ? LOCK_UN : -1)))
37
38 #ifdef DISABLE_LOCKING
39 #define fcntl(a, b, c ) (0)
40 #endif
41
42 /* ----------------------- */
43 static int XLATE_FCNTL_LOCK(int type) 
44 {
45     switch(type) {
46     case ADLOCK_RD:
47         return F_RDLCK;
48     case ADLOCK_WR:
49          return F_WRLCK;
50     case ADLOCK_CLR:
51          return F_UNLCK;
52     }
53     return -1;
54 }
55
56 /* ----------------------- */
57 static int OVERLAP(off_t a, off_t alen, off_t b, off_t blen) 
58 {
59  return (!alen && a <= b) || 
60         (!blen && b <= a) || 
61         ( (a + alen > b) && (b + blen > a) );
62 }
63
64 /* allocation for lock regions. we allocate aggressively and shrink
65  * only in large chunks. */
66 #define ARRAY_BLOCK_SIZE 10 
67 #define ARRAY_FREE_DELTA 100
68
69 /* remove a lock and compact space if necessary */
70 static void adf_freelock(struct ad_fd *ad, const int i)
71 {
72     adf_lock_t *lock = ad->adf_lock + i;
73
74     if (--(*lock->refcount) < 1) {
75         free(lock->refcount); 
76         if (!ad->adf_excl) {
77             lock->lock.l_type = F_UNLCK;
78             fcntl(ad->adf_fd, F_SETLK, &lock->lock); /* unlock */
79         }
80     }
81
82     ad->adf_lockcount--;
83
84     /* move another lock into the empty space */
85     if (i < ad->adf_lockcount) {
86         memcpy(lock, lock + ad->adf_lockcount - i, sizeof(adf_lock_t));
87     }
88
89     /* free extra cruft if we go past a boundary. we always want to
90      * keep at least some stuff around for allocations. this wastes
91      * a bit of space to save time on reallocations. */
92     if ((ad->adf_lockmax > ARRAY_FREE_DELTA) &&
93         (ad->adf_lockcount + ARRAY_FREE_DELTA < ad->adf_lockmax)) {
94             struct adf_lock_t *tmp;
95
96             tmp = (struct adf_lock_t *) 
97                     realloc(ad->adf_lock, sizeof(adf_lock_t)*
98                             (ad->adf_lockcount + ARRAY_FREE_DELTA));
99             if (tmp) {
100                 ad->adf_lock = tmp;
101                 ad->adf_lockmax = ad->adf_lockcount + ARRAY_FREE_DELTA;
102             }
103     }
104 }
105
106
107 /* this needs to deal with the following cases:
108  * 1) fork is the only user of the lock 
109  * 2) fork shares a read lock with another open fork
110  *
111  * i converted to using arrays of locks. everytime a lock
112  * gets removed, we shift all of the locks down.
113  */
114 static void adf_unlock(struct ad_fd *ad, const int fork)
115 {
116     adf_lock_t *lock = ad->adf_lock;
117     int i;
118
119     for (i = 0; i < ad->adf_lockcount; i++) {
120       if (lock[i].user == fork) {
121         /* we're really going to delete this lock. note: read locks
122            are the only ones that allow refcounts > 1 */
123          adf_freelock(ad, i);
124          i--; /* we shifted things down, so we need to backtrack */
125        }
126     }
127 }
128
129 /* relock any byte lock that overlaps off/len. unlock everything
130  * else. */
131 static void adf_relockrange(struct ad_fd *ad, int fd,
132                                        const off_t off, const off_t len)
133 {
134     adf_lock_t *lock = ad->adf_lock;
135     int i;
136     
137     if (!ad->adf_excl) for (i = 0; i < ad->adf_lockcount; i++) {
138       if (OVERLAP(off, len, lock[i].lock.l_start, lock[i].lock.l_len)) 
139         fcntl(fd, F_SETLK, &lock[i].lock);
140     }
141 }
142
143
144 /* find a byte lock that overlaps off/len for a particular open fork */
145 static int adf_findlock(struct ad_fd *ad,
146                                    const int fork, const int type,
147                                    const off_t off,
148                                    const off_t len)
149 {
150   adf_lock_t *lock = ad->adf_lock;
151   int i;
152   
153   for (i = 0; i < ad->adf_lockcount; i++) {
154     if ((((type & ADLOCK_RD) && (lock[i].lock.l_type == F_RDLCK)) ||
155         ((type & ADLOCK_WR) && (lock[i].lock.l_type == F_WRLCK))) &&
156         (lock[i].user == fork) && 
157         OVERLAP(off, len, lock[i].lock.l_start, lock[i].lock.l_len)) {
158       return i;
159     }
160   }
161
162   return -1;
163 }
164
165
166 /* search other fork lock lists */
167 static int adf_findxlock(struct ad_fd *ad, 
168                                      const int fork, const int type,
169                                      const off_t off,
170                                      const off_t len)
171 {
172   adf_lock_t *lock = ad->adf_lock;
173   int i;
174   
175   for (i = 0; i < ad->adf_lockcount; i++) {
176     if ((((type & ADLOCK_RD) && (lock[i].lock.l_type == F_RDLCK)) ||
177          ((type & ADLOCK_WR) && (lock[i].lock.l_type == F_WRLCK))) &&
178         (lock[i].user != fork) && 
179         OVERLAP(off, len, lock[i].lock.l_start, lock[i].lock.l_len)) 
180             return i;
181   } 
182   return -1;
183 }
184
185 /* okay, this needs to do the following:
186  * 1) check current list of locks. error on conflict.
187  * 2) apply the lock. error on conflict with another process.
188  * 3) update the list of locks this file has.
189  * 
190  * NOTE: this treats synchronization locks a little differently. we
191  *       do the following things for those:
192  *       1) if the header file exists, all the locks go in the beginning
193  *          of that.
194  *       2) if the header file doesn't exist, we stick the locks
195  *          in the locations specified by AD_FILELOCK_RD/WR.
196  */
197 #define LOCK_DATA_WR (0)
198 #define LOCK_DATA_RD (1)
199 #define LOCK_RSRC_WR (2)
200 #define LOCK_RSRC_RD (3)
201
202 #define LOCK_RSRC_DRD (4)
203 #define LOCK_RSRC_DWR (5)
204 #define LOCK_DATA_DRD (6)
205 #define LOCK_DATA_DWR (7)
206
207 #define LOCK_RSRC_NONE (8)
208 #define LOCK_DATA_NONE (9)
209
210 /* -------------- 
211         translate a data fork lock to an offset
212 */
213
214 static off_t df2off(int off)
215 {
216 int start = off;
217         if (off == AD_FILELOCK_OPEN_WR)
218                 start = LOCK_DATA_WR;
219         else if (off == AD_FILELOCK_OPEN_RD)
220                 start = LOCK_DATA_RD;
221     else if (off == AD_FILELOCK_DENY_RD)
222                 start = LOCK_DATA_DRD;
223         else if (off == AD_FILELOCK_DENY_WR)
224                 start = LOCK_DATA_DWR;
225         else if (off == AD_FILELOCK_OPEN_NONE)
226                 start = LOCK_DATA_NONE;
227         return start;
228 }
229
230 /* -------------- 
231         translate a resource fork lock to an offset
232 */
233
234 static off_t hf2off(int off)
235 {
236 int start = off;
237         if (off == AD_FILELOCK_OPEN_WR)
238                 start = LOCK_RSRC_WR;
239         else if (off == AD_FILELOCK_OPEN_RD)
240                 start = LOCK_RSRC_RD;
241     else if (off == AD_FILELOCK_DENY_RD)
242                 start = LOCK_RSRC_DRD;
243         else if (off == AD_FILELOCK_DENY_WR)
244                 start = LOCK_RSRC_DWR;
245         else if (off == AD_FILELOCK_OPEN_NONE)
246                 start = LOCK_RSRC_NONE;
247         return start;
248 }
249
250 /* ------------------ */
251 int ad_fcntl_lock(struct adouble *ad, const u_int32_t eid, const int locktype,
252                   const off_t off, const off_t len, const int fork)
253 {
254   struct flock lock;
255   struct ad_fd *adf;
256   adf_lock_t *adflock;
257   int oldlock;
258   int i;
259   int type;  
260
261   lock.l_start = off;
262   type = locktype;
263   if (eid == ADEID_DFORK) {
264     adf = &ad->ad_data_fork;
265     if ((type & ADLOCK_FILELOCK)) {
266         if (ad_meta_fileno(ad) != -1) { /* META */
267             adf = ad->ad_md;
268             lock.l_start = df2off(off);
269         }
270     }
271   } else { /* rfork */
272     if (ad_meta_fileno(ad) == -1 || ad_reso_fileno(ad) == -1) {
273         /* there's no meta data. return a lock error 
274          * otherwise if a second process is able to create it
275          * locks are a mess.
276          */
277         errno = EACCES;
278         return -1;
279     }
280     if (type & ADLOCK_FILELOCK) {
281       adf = ad->ad_md;                  /* either resource or meta data (set in ad_open) */
282       lock.l_start = hf2off(off);
283     }
284     else {
285       /* we really want the resource fork it's a byte lock */
286       adf = &ad->ad_resource_fork;
287       lock.l_start += ad_getentryoff(ad, eid);
288     }
289   }
290   /* NOTE: we can't write lock a read-only file. on those, we just
291     * make sure that we have a read lock set. that way, we at least prevent
292     * someone else from really setting a deny read/write on the file. 
293     */
294   if (!(adf->adf_flags & O_RDWR) && (type & ADLOCK_WR)) {
295       type = (type & ~ADLOCK_WR) | ADLOCK_RD;
296   }
297   
298   lock.l_type = XLATE_FCNTL_LOCK(type & ADLOCK_MASK);
299   lock.l_whence = SEEK_SET;
300   lock.l_len = len;
301
302   /* byte_lock(len=-1) lock whole file */
303   if (len == BYTELOCK_MAX) {
304       lock.l_len -= lock.l_start; /* otherwise  EOVERFLOW error */
305   }
306
307   /* see if it's locked by another fork. 
308    * NOTE: this guarantees that any existing locks must be at most
309    * read locks. we use ADLOCK_WR/RD because F_RD/WRLCK aren't
310    * guaranteed to be ORable. */
311   if (adf_findxlock(adf, fork, ADLOCK_WR | 
312                     ((type & ADLOCK_WR) ? ADLOCK_RD : 0), 
313                     lock.l_start, lock.l_len) > -1) {
314     errno = EACCES;
315     return -1;
316   }
317   
318   /* look for any existing lock that we may have */
319   i = adf_findlock(adf, fork, ADLOCK_RD | ADLOCK_WR, lock.l_start, lock.l_len);
320   adflock = (i < 0) ? NULL : adf->adf_lock + i;
321
322   /* here's what we check for:
323      1) we're trying to re-lock a lock, but we didn't specify an update.
324      2) we're trying to free only part of a lock. 
325      3) we're trying to free a non-existent lock. */
326   if ((!adflock && (lock.l_type == F_UNLCK)) ||
327       (adflock && !(type & ADLOCK_UPGRADE) && 
328        ((lock.l_type != F_UNLCK) || (adflock->lock.l_start != lock.l_start) ||
329         (adflock->lock.l_len != lock.l_len)))) {
330     errno = EINVAL;
331     return -1;
332   }
333
334
335   /* now, update our list of locks */
336   /* clear the lock */
337   if (lock.l_type == F_UNLCK) { 
338     adf_freelock(adf, i);
339     return 0;
340   }
341
342   /* attempt to lock the file. */
343   if (!adf->adf_excl && fcntl(adf->adf_fd, F_SETLK, &lock) < 0) 
344     return -1;
345
346   /* we upgraded this lock. */
347   if (adflock && (type & ADLOCK_UPGRADE)) {
348     memcpy(&adflock->lock, &lock, sizeof(lock));
349     return 0;
350   } 
351
352   /* it wasn't an upgrade */
353   oldlock = -1;
354   if (lock.l_type == F_RDLCK) {
355     oldlock = adf_findxlock(adf, fork, ADLOCK_RD, lock.l_start, lock.l_len);
356   } 
357     
358   /* no more space. this will also happen if lockmax == lockcount == 0 */
359   if (adf->adf_lockmax == adf->adf_lockcount) { 
360     adf_lock_t *tmp = (adf_lock_t *) 
361             realloc(adf->adf_lock, sizeof(adf_lock_t)*
362                     (adf->adf_lockmax + ARRAY_BLOCK_SIZE));
363     if (!tmp)
364       goto fcntl_lock_err;
365     adf->adf_lock = tmp;
366     adf->adf_lockmax += ARRAY_BLOCK_SIZE;
367   } 
368   adflock = adf->adf_lock + adf->adf_lockcount;
369
370   /* fill in fields */
371   memcpy(&adflock->lock, &lock, sizeof(lock));
372   adflock->user = fork;
373   if (oldlock > -1) {
374     adflock->refcount = (adf->adf_lock + oldlock)->refcount;
375   } else if ((adflock->refcount = calloc(1, sizeof(int))) == NULL) {
376     goto fcntl_lock_err;
377   }
378   
379   (*adflock->refcount)++;
380   adf->adf_lockcount++;
381   return 0;
382
383 fcntl_lock_err:
384   lock.l_type = F_UNLCK;
385   if (!adf->adf_excl) fcntl(adf->adf_fd, F_SETLK, &lock);
386   return -1;
387 }
388
389 /* -------------------------
390    we are using lock as tristate variable
391    
392    we have a lock ==> 1
393    no             ==> 0
394    error          ==> -1
395       
396 */
397 static int testlock(struct ad_fd *adf, off_t off, off_t len)
398 {
399   struct flock lock;
400   adf_lock_t *plock;
401   int i;
402
403   lock.l_start = off;
404
405   plock = adf->adf_lock;
406   lock.l_whence = SEEK_SET;
407   lock.l_len = len;
408
409   /* Do we have a lock? */
410   for (i = 0; i < adf->adf_lockcount; i++) {
411     if (OVERLAP(lock.l_start, 1, plock[i].lock.l_start, plock[i].lock.l_len)) 
412         return 1;   /* */
413   }
414   /* Does another process have a lock? 
415   */
416   lock.l_type = (adf->adf_flags & O_RDWR) ?F_WRLCK : F_RDLCK;
417
418   if (fcntl(adf->adf_fd, F_GETLK, &lock) < 0) {
419       /* is that kind of error possible ?*/
420       return (errno == EACCES || errno == EAGAIN)?1:-1;
421   }
422   
423   if (lock.l_type == F_UNLCK) {
424       return 0;
425   }
426   return 1;
427 }
428
429 /* --------------- */
430 int ad_testlock(struct adouble *ad, int eid, const off_t off)
431 {
432   struct ad_fd *adf;
433   off_t      lock_offset;
434
435   lock_offset = off;
436   if (eid == ADEID_DFORK) {
437     adf = &ad->ad_data_fork;
438     if (ad_meta_fileno(ad) != -1) {
439         adf = ad->ad_md;
440         lock_offset = df2off(off);
441     }
442   } 
443   else { /* rfork */
444     if (ad_meta_fileno(ad) == -1) {
445         /* there's no resource fork. return no lock */
446         return 0;
447     }
448     adf = ad->ad_md;
449     lock_offset = hf2off(off);
450   }
451   return testlock(adf, lock_offset, 1);
452 }
453
454 /* -------------------------
455    return if a file is open by another process.
456    Optimized for the common case:
457    - there's no locks held by another process (clients)
458    - or we already know the answer and don't need to test.
459 */
460 u_int16_t ad_openforks(struct adouble *ad, u_int16_t attrbits)
461 {
462   u_int16_t ret = 0;
463   struct ad_fd *adf;
464   off_t off;
465
466   if (!(attrbits & (ATTRBIT_DOPEN | ATTRBIT_ROPEN))) {
467       off_t len;
468       /* XXX know the locks layout: 
469          AD_FILELOCK_OPEN_WR is first 
470          and use it for merging requests
471       */
472       if (ad_meta_fileno(ad) != -1) {
473           /* there's a resource fork test the four bytes for
474            * data RW/RD and fork RW/RD locks in one request
475           */
476           adf = ad->ad_md;
477           off = LOCK_DATA_WR;
478           len = 4;
479       }
480       else {
481           /* no resource fork, only data RD/RW may exist */
482           adf = &ad->ad_data_fork;
483           off = AD_FILELOCK_OPEN_WR;
484           len = 2;
485       }
486       if (!testlock(adf, off, len))
487           return ret;
488   }
489   /* either there's a lock or we already know one 
490      fork is open
491   */
492   if (!(attrbits & ATTRBIT_DOPEN)) {
493       if (ad_meta_fileno(ad) != -1) {
494           adf = ad->ad_md;
495           off = LOCK_DATA_WR;
496       }
497       else {
498           adf = &ad->ad_data_fork;
499           off = AD_FILELOCK_OPEN_WR;
500       }
501       ret = testlock(adf, off, 2) > 0? ATTRBIT_DOPEN : 0;
502   }
503
504   if (!(attrbits & ATTRBIT_ROPEN)) {
505       if (ad_meta_fileno(ad) != -1) {
506           adf = ad->ad_md;
507           off = LOCK_RSRC_WR;
508           ret |= testlock(adf, off, 2) > 0? ATTRBIT_ROPEN : 0;
509       }
510   }
511
512   return ret;
513 }
514
515 /* -------------------------
516 */
517 int ad_fcntl_tmplock(struct adouble *ad, const u_int32_t eid, const int locktype,
518                      const off_t off, const off_t len, const int fork)
519 {
520   struct flock lock;
521   struct ad_fd *adf;
522   int err;
523   int type;  
524
525   lock.l_start = off;
526   type = locktype;
527   if (eid == ADEID_DFORK) {
528     adf = &ad->ad_data_fork;
529   } else {
530     /* FIXME META */
531     adf = &ad->ad_resource_fork;
532     if (adf->adf_fd == -1) {
533         /* there's no resource fork. return success */
534         return 0;
535     }
536     /* if ADLOCK_FILELOCK we want a lock from offset 0
537      * it's used when deleting a file:
538      * in open we put read locks on meta datas
539      * in delete a write locks on the whole file
540      * so if the file is open by somebody else it fails
541     */
542     if (!(type & ADLOCK_FILELOCK))
543         lock.l_start += ad_getentryoff(ad, eid);
544   }
545
546   if (!(adf->adf_flags & O_RDWR) && (type & ADLOCK_WR)) {
547       type = (type & ~ADLOCK_WR) | ADLOCK_RD;
548   }
549   
550   lock.l_type = XLATE_FCNTL_LOCK(type & ADLOCK_MASK);
551   lock.l_whence = SEEK_SET;
552   lock.l_len = len;
553
554   /* see if it's locked by another fork. */
555   if (fork && adf_findxlock(adf, fork, ADLOCK_WR | 
556                     ((type & ADLOCK_WR) ? ADLOCK_RD : 0), 
557                     lock.l_start, lock.l_len) > -1) {
558     errno = EACCES;
559     return -1;
560   }
561
562   /* okay, we might have ranges byte-locked. we need to make sure that
563    * we restore the appropriate ranges once we're done. so, we check
564    * for overlap on an unlock and relock. 
565    * XXX: in the future, all the byte locks will be sorted and contiguous.
566    *      we just want to upgrade all the locks and then downgrade them
567    *      here. */
568   if (!adf->adf_excl) {
569        err = fcntl(adf->adf_fd, F_SETLK, &lock);
570   }
571   else {
572       err = 0;
573   }
574   if (!err && (lock.l_type == F_UNLCK))
575     adf_relockrange(adf, adf->adf_fd, lock.l_start, len);
576
577   return err;
578 }
579
580 /* -------------------------
581    the fork is opened in Read Write, Deny Read, Deny Write mode
582    lock the whole file once   
583 */
584 int ad_excl_lock(struct adouble *ad, const u_int32_t eid)
585 {
586   struct ad_fd *adf;
587   struct flock lock;
588   int    err;
589   
590   lock.l_start = 0;
591   lock.l_type = F_WRLCK;
592   lock.l_whence = SEEK_SET;
593   lock.l_len = 0;
594
595   if (eid == ADEID_DFORK) {
596     adf = &ad->ad_data_fork;
597   } else {
598     adf = &ad->ad_resource_fork;
599     lock.l_start = ad_getentryoff(ad, eid);
600   }
601   
602   err = fcntl(adf->adf_fd, F_SETLK, &lock);
603   if (!err)
604       adf->adf_excl = 1;
605   return err;
606 }
607
608 /* --------------------- */
609 void ad_fcntl_unlock(struct adouble *ad, const int fork)
610 {
611   if (ad_data_fileno(ad) != -1) {
612     adf_unlock(&ad->ad_data_fork, fork);
613   }
614   if (ad_reso_fileno(ad) != -1) {
615     adf_unlock(&ad->ad_resource_fork, fork);
616   }
617
618   if (ad->ad_flags != AD_VERSION1_SFM) {
619     return;
620   }
621   if (ad_meta_fileno(ad) != -1) {
622     adf_unlock(&ad->ad_metadata_fork, fork);
623   }
624
625 }