Windows: Fix test for setting FILE_ATTR_READONLY
[openafs.git] / src / afs / afs_buffer.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include "afs/param.h"
12
13
14 #include "afs/sysincludes.h"
15 #include "afsincludes.h"
16 #if !defined(UKERNEL)
17 #include "h/param.h"
18 #include "h/types.h"
19 #include "h/time.h"
20 #if     defined(AFS_AIX31_ENV) 
21 #include "h/limits.h"
22 #endif
23 #if     !defined(AFS_AIX_ENV) && !defined(AFS_SUN5_ENV) && !defined(AFS_SGI_ENV) && !defined(AFS_LINUX20_ENV)
24 #include "h/kernel.h"           /* Doesn't needed, so it should go */
25 #endif
26 #endif /* !defined(UKERNEL) */
27
28 #include "afs/afs_osi.h"
29 #include "afsint.h"
30 #include "afs/lock.h"
31
32 #if !defined(UKERNEL) && !defined(AFS_LINUX20_ENV)
33 #include "h/buf.h"
34 #endif /* !defined(UKERNEL) */
35
36 #include "afs/stds.h"
37 #include "afs/volerrors.h"
38 #include "afs/exporter.h"
39 #include "afs/prs_fs.h"
40 #include "afs/afs_chunkops.h"
41 #include "afs/dir.h"
42
43 #include "afs/afs_stats.h"
44 #include "afs/afs.h"
45
46 #ifndef BUF_TIME_MAX
47 #define BUF_TIME_MAX    0x7fffffff
48 #endif
49 #if defined(AFS_USEBUFFERS)
50 /* number of pages per Unix buffer, when we're using Unix buffer pool */
51 #define NPB 4
52 #else
53 #define NPB 8                   /* must be a pwer of 2 */
54 #endif
55 static int afs_max_buffers;     /* should be an integral multiple of NPB */
56
57 /* page size */
58 #define AFS_BUFFER_PAGESIZE 2048
59 /* log page size */
60 #define LOGPS 11
61 /* If you change any of this PH stuff, make sure you don't break DZap() */
62 /* use last two bits for page */
63 #define PHPAGEMASK 3
64 /* use next five bits for fid */
65 #define PHFIDMASK 124
66 /* page hash table size - this is pretty intertwined with pHash */
67 #define PHSIZE (PHPAGEMASK + PHFIDMASK + 1)
68 /* the pHash macro */
69 #define pHash(fid,page) ((((afs_int32)(fid)) & PHFIDMASK) \
70                          | (page & PHPAGEMASK))
71
72 #ifdef  dirty
73 #undef dirty                    /* XXX */
74 #endif
75
76 static struct buffer *Buffers = 0;
77 static char *BufferData;
78
79 #ifdef  AFS_AIX_ENV
80 extern struct buf *geteblk();
81 #endif
82 #ifdef AFS_FBSD_ENV
83 #define timecounter afs_timecounter
84 #endif
85
86 /* A note on locking in 'struct buffer'
87  *
88  * afs_bufferLock protects the hash chain, and the 'lockers' field where that
89  * has a zero value. It must be held whenever lockers is incremented from zero.
90  *
91  * The individual buffer lock protects the contents of the structure, including
92  * the lockers field.
93  *
94  * For safety: afs_bufferLock and the individual buffer lock must be held
95  * when obtaining a reference on a structure. Only the individual buffer lock
96  * need be held when releasing a reference.
97  *
98  * The locking hierarchy is afs_bufferLock-> buffer.lock
99  *
100  */
101
102 static afs_lock_t afs_bufferLock;
103 static struct buffer *phTable[PHSIZE];  /* page hash table */
104 static int nbuffers;
105 static afs_int32 timecounter;
106
107 /* Prototypes for static routines */
108 static struct buffer *afs_newslot(struct dcache *adc, afs_int32 apage,
109                                   register struct buffer *lp);
110
111 static int dinit_flag = 0;
112 void
113 DInit(int abuffers)
114 {
115     /* Initialize the venus buffer system. */
116     register int i;
117     register struct buffer *tb;
118 #if defined(AFS_USEBUFFERS)
119     struct buf *tub;            /* unix buffer for allocation */
120 #endif
121
122     AFS_STATCNT(DInit);
123     if (dinit_flag)
124         return;
125     dinit_flag = 1;
126     /* round up to next multiple of NPB, since we allocate multiple pages per chunk */
127     abuffers = ((abuffers - 1) | (NPB - 1)) + 1;
128 #if defined(AFS_USEBUFFERS)
129     afs_max_buffers = abuffers;
130 #else
131     afs_max_buffers = abuffers << 2;            /* possibly grow up to 4 times as big */
132 #endif
133     LOCK_INIT(&afs_bufferLock, "afs_bufferLock");
134     Buffers =
135         (struct buffer *)afs_osi_Alloc(afs_max_buffers * sizeof(struct buffer));
136     timecounter = 1;
137     afs_stats_cmperf.bufAlloced = nbuffers = abuffers;
138     for (i = 0; i < PHSIZE; i++)
139         phTable[i] = 0;
140     for (i = 0; i < abuffers; i++) {
141         if ((i & (NPB - 1)) == 0) {
142             /* time to allocate a fresh buffer */
143 #if defined(AFS_USEBUFFERS)
144             tub = geteblk(AFS_BUFFER_PAGESIZE * NPB);
145             BufferData = (char *)tub->b_un.b_addr;
146 #else
147             BufferData = (char *) afs_osi_Alloc(AFS_BUFFER_PAGESIZE * NPB);
148 #endif
149         }
150         /* Fill in each buffer with an empty indication. */
151         tb = &Buffers[i];
152         tb->fid = NULLIDX;
153         afs_reset_inode(&tb->inode);
154         tb->accesstime = 0;
155         tb->lockers = 0;
156 #if defined(AFS_USEBUFFERS)
157         if ((i & (NPB - 1)) == 0)
158             tb->bufp = tub;
159         else
160             tb->bufp = 0;
161 #endif
162         tb->data = &BufferData[AFS_BUFFER_PAGESIZE * (i & (NPB - 1))];
163         tb->hashIndex = 0;
164         tb->dirty = 0;
165         AFS_RWLOCK_INIT(&tb->lock, "buffer lock");
166     }
167     return;
168 }
169
170 void *
171 DRead(register struct dcache *adc, register int page)
172 {
173     /* Read a page from the disk. */
174     register struct buffer *tb, *tb2;
175     struct osi_file *tfile;
176     int code;
177
178     AFS_STATCNT(DRead);
179     ObtainWriteLock(&afs_bufferLock, 256);
180
181 #define bufmatch(tb) (tb->page == page && tb->fid == adc->index)
182 #define buf_Front(head,parent,p) {(parent)->hashNext = (p)->hashNext; (p)->hashNext= *(head);*(head)=(p);}
183
184     /* this apparently-complicated-looking code is simply an example of
185      * a little bit of loop unrolling, and is a standard linked-list 
186      * traversal trick. It saves a few assignments at the the expense
187      * of larger code size.  This could be simplified by better use of
188      * macros. 
189      */
190     if ((tb = phTable[pHash(adc->index, page)])) {
191         if (bufmatch(tb)) {
192             ObtainWriteLock(&tb->lock, 257);
193             tb->lockers++;
194             ReleaseWriteLock(&afs_bufferLock);
195             tb->accesstime = timecounter++;
196             AFS_STATS(afs_stats_cmperf.bufHits++);
197             ReleaseWriteLock(&tb->lock);
198             return tb->data;
199         } else {
200             register struct buffer **bufhead;
201             bufhead = &(phTable[pHash(adc->index, page)]);
202             while ((tb2 = tb->hashNext)) {
203                 if (bufmatch(tb2)) {
204                     buf_Front(bufhead, tb, tb2);
205                     ObtainWriteLock(&tb2->lock, 258);
206                     tb2->lockers++;
207                     ReleaseWriteLock(&afs_bufferLock);
208                     tb2->accesstime = timecounter++;
209                     AFS_STATS(afs_stats_cmperf.bufHits++);
210                     ReleaseWriteLock(&tb2->lock);
211                     return tb2->data;
212                 }
213                 if ((tb = tb2->hashNext)) {
214                     if (bufmatch(tb)) {
215                         buf_Front(bufhead, tb2, tb);
216                         ObtainWriteLock(&tb->lock, 259);
217                         tb->lockers++;
218                         ReleaseWriteLock(&afs_bufferLock);
219                         tb->accesstime = timecounter++;
220                         AFS_STATS(afs_stats_cmperf.bufHits++);
221                         ReleaseWriteLock(&tb->lock);
222                         return tb->data;
223                     }
224                 } else
225                     break;
226             }
227         }
228     } else
229         tb2 = NULL;
230
231     AFS_STATS(afs_stats_cmperf.bufMisses++);
232     /* can't find it */
233     /* The last thing we looked at was either tb or tb2 (or nothing). That
234      * is at least the oldest buffer on one particular hash chain, so it's 
235      * a pretty good place to start looking for the truly oldest buffer.
236      */
237     tb = afs_newslot(adc, page, (tb ? tb : tb2));
238     if (!tb) {
239         ReleaseWriteLock(&afs_bufferLock);
240         return NULL;
241     }
242     ObtainWriteLock(&tb->lock, 260);
243     tb->lockers++;
244     ReleaseWriteLock(&afs_bufferLock);
245     if (page * AFS_BUFFER_PAGESIZE >= adc->f.chunkBytes) {
246         tb->fid = NULLIDX;
247         afs_reset_inode(&tb->inode);
248         tb->lockers--;
249         ReleaseWriteLock(&tb->lock);
250         return NULL;
251     }
252     tfile = afs_CFileOpen(&adc->f.inode);
253     code =
254         afs_CFileRead(tfile, tb->page * AFS_BUFFER_PAGESIZE, tb->data,
255                       AFS_BUFFER_PAGESIZE);
256     afs_CFileClose(tfile);
257     if (code < AFS_BUFFER_PAGESIZE) {
258         tb->fid = NULLIDX;
259         afs_reset_inode(&tb->inode);
260         tb->lockers--;
261         ReleaseWriteLock(&tb->lock);
262         return NULL;
263     }
264     /* Note that findslot sets the page field in the buffer equal to
265      * what it is searching for. */
266     ReleaseWriteLock(&tb->lock);
267     return tb->data;
268 }
269
270 static void
271 FixupBucket(register struct buffer *ap)
272 {
273     register struct buffer **lp, *tp;
274     register int i;
275     /* first try to get it out of its current hash bucket, in which it
276      * might not be */
277     AFS_STATCNT(FixupBucket);
278     i = ap->hashIndex;
279     lp = &phTable[i];
280     for (tp = *lp; tp; tp = tp->hashNext) {
281         if (tp == ap) {
282             *lp = tp->hashNext;
283             break;
284         }
285         lp = &tp->hashNext;
286     }
287     /* now figure the new hash bucket */
288     i = pHash(ap->fid, ap->page);
289     ap->hashIndex = i;          /* remember where we are for deletion */
290     ap->hashNext = phTable[i];  /* add us to the list */
291     phTable[i] = ap;            /* at the front, since it's LRU */
292 }
293
294 /* lp is pointer to a fairly-old buffer */
295 static struct buffer *
296 afs_newslot(struct dcache *adc, afs_int32 apage, register struct buffer *lp)
297 {
298     /* Find a usable buffer slot */
299     register afs_int32 i;
300     afs_int32 lt = 0;
301     register struct buffer *tp;
302     struct osi_file *tfile;
303
304     AFS_STATCNT(afs_newslot);
305     /* we take a pointer here to a buffer which was at the end of an
306      * LRU hash chain.  Odds are, it's one of the older buffers, not
307      * one of the newer.  Having an older buffer to start with may
308      * permit us to avoid a few of the assignments in the "typical
309      * case" for loop below.
310      */
311     if (lp && (lp->lockers == 0)) {
312         lt = lp->accesstime;
313     } else {
314         lp = NULL;
315     }
316
317     /* timecounter might have wrapped, if machine is very very busy
318      * and stays up for a long time.  Timecounter mustn't wrap twice
319      * (positive->negative->positive) before calling newslot, but that
320      * would require 2 billion consecutive cache hits... Anyway, the
321      * penalty is only that the cache replacement policy will be
322      * almost MRU for the next ~2 billion DReads...  newslot doesn't
323      * get called nearly as often as DRead, so in order to avoid the
324      * performance penalty of using the hypers, it's worth doing the
325      * extra check here every time.  It's probably cheaper than doing
326      * hcmp, anyway.  There is a little performance hit resulting from
327      * resetting all the access times to 0, but it only happens once
328      * every month or so, and the access times will rapidly sort
329      * themselves back out after just a few more DReads.
330      */
331     if (timecounter < 0) {
332         timecounter = 1;
333         tp = Buffers;
334         for (i = 0; i < nbuffers; i++, tp++) {
335             tp->accesstime = 0;
336             if (!lp && !tp->lockers)    /* one is as good as the rest, I guess */
337                 lp = tp;
338         }
339     } else {
340         /* this is the typical case */
341         tp = Buffers;
342         for (i = 0; i < nbuffers; i++, tp++) {
343             if (tp->lockers == 0) {
344                 if (!lp || tp->accesstime < lt) {
345                     lp = tp;
346                     lt = tp->accesstime;
347                 }
348             }
349         }
350     }
351
352     if (lp == 0) {
353         /* No unlocked buffers. If still possible, allocate a new increment */
354         if (nbuffers + NPB > afs_max_buffers) {
355             /* There are no unlocked buffers -- this used to panic, but that
356              * seems extreme.  To the best of my knowledge, all the callers
357              * of DRead are prepared to handle a zero return.  Some of them
358              * just panic directly, but not all of them. */
359             afs_warn("afs: all buffers locked\n");
360             return 0;
361         }
362
363         BufferData = (char *) afs_osi_Alloc(AFS_BUFFER_PAGESIZE * NPB);
364         for (i = 0; i< NPB; i++) {
365             /* Fill in each buffer with an empty indication. */
366             tp = &Buffers[i + nbuffers];
367             tp->fid = NULLIDX;
368             afs_reset_inode(&tp->inode);
369             tp->accesstime = 0;
370             tp->lockers = 0;
371             tp->data = &BufferData[AFS_BUFFER_PAGESIZE * i];
372             tp->hashIndex = 0;
373             tp->dirty = 0;
374             AFS_RWLOCK_INIT(&tp->lock, "buffer lock");
375         }
376         lp = &Buffers[nbuffers];
377         nbuffers += NPB;
378     }
379
380     if (lp->dirty) {
381         /* see DFlush for rationale for not getting and locking the dcache */
382         tfile = afs_CFileOpen(&lp->inode);
383         afs_CFileWrite(tfile, lp->page * AFS_BUFFER_PAGESIZE, lp->data,
384                        AFS_BUFFER_PAGESIZE);
385         lp->dirty = 0;
386         afs_CFileClose(tfile);
387         AFS_STATS(afs_stats_cmperf.bufFlushDirty++);
388     }
389
390     /* Now fill in the header. */
391     lp->fid = adc->index;
392     afs_copy_inode(&lp->inode, &adc->f.inode);
393     lp->page = apage;
394     lp->accesstime = timecounter++;
395     FixupBucket(lp);            /* move to the right hash bucket */
396
397     return lp;
398 }
399
400 void
401 DRelease(void *loc, int flag)
402 {
403     /* Release a buffer, specifying whether or not the buffer has been
404      * modified by the locker. */
405     register struct buffer *bp = (struct buffer *)loc;
406     register int index;
407     register struct buffer *tp;
408
409     AFS_STATCNT(DRelease);
410     if (!bp)
411         return;
412     /* look for buffer by scanning Unix buffers for appropriate address */
413     /* careful: despite the declaration above at this point bp is still simply
414      * an address inside the buffer, not a pointer to the buffer header */
415     tp = Buffers;
416     for (index = 0; index < nbuffers; index += NPB, tp += NPB) {
417         if ( (char *) bp >= (char *) tp->data &&
418              (char *) bp < (char *) tp->data + AFS_BUFFER_PAGESIZE * NPB) {
419             /* we found the right range */
420             index += ((char *) bp - (char *) tp->data) >> LOGPS;
421             break;
422         }
423     }
424     tp = &(Buffers[index]);
425     MObtainWriteLock(&tp->lock, 261);
426     tp->lockers--;
427     if (flag)
428         tp->dirty = 1;
429     MReleaseWriteLock(&tp->lock);
430 }
431
432 int
433 DVOffset(register void *ap)
434 {
435     /* Return the byte within a file represented by a buffer pointer. */
436     register int index;
437     register struct buffer *tp;
438     AFS_STATCNT(DVOffset);
439     /* look for buffer by scanning Unix buffers for appropriate address */
440     /* see comment in DRelease about the meaning of ap/bp */
441     tp = Buffers;
442     for (index = 0; index < nbuffers; index += NPB, tp += NPB) {
443         if ( (char *) ap >= (char *) tp->data &&
444              (char *) ap < (char *) tp->data + AFS_BUFFER_PAGESIZE * NPB) {
445             /* we found the right range */
446             index += ((char *) ap - (char *) tp->data) >> LOGPS;
447             break;
448         }
449     }
450     if (index < 0 || index >= nbuffers)
451         return -1;
452     tp = &(Buffers[index]);
453     return AFS_BUFFER_PAGESIZE * tp->page + (int)(((char *)ap) - tp->data);
454 }
455
456 /*! 
457  * Zap one dcache entry: destroy one FID's buffers.
458  *
459  * 1/1/91 - I've modified the hash function to take the page as well
460  * as the *fid, so that lookup will be a bit faster.  That presents some
461  * difficulties for Zap, which now has to have some knowledge of the nature
462  * of the hash function.  Oh well.  This should use the list traversal 
463  * method of DRead...
464  *
465  * \param adc The dcache entry to be zapped.
466  */
467 void
468 DZap(struct dcache *adc)
469 {
470     register int i;
471     /* Destroy all buffers pertaining to a particular fid. */
472     register struct buffer *tb;
473
474     AFS_STATCNT(DZap);
475     ObtainReadLock(&afs_bufferLock);
476
477     for (i = 0; i <= PHPAGEMASK; i++)
478         for (tb = phTable[pHash(adc->index, i)]; tb; tb = tb->hashNext)
479             if (tb->fid == adc->index) {
480                 ObtainWriteLock(&tb->lock, 262);
481                 tb->fid = NULLIDX;
482                 afs_reset_inode(&tb->inode);
483                 tb->dirty = 0;
484                 ReleaseWriteLock(&tb->lock);
485             }
486     ReleaseReadLock(&afs_bufferLock);
487 }
488
489 static void
490 DFlushBuffer(struct buffer *ab) {
491     struct osi_file *tfile;
492     
493     tfile = afs_CFileOpen(&ab->inode);
494     afs_CFileWrite(tfile, ab->page * AFS_BUFFER_PAGESIZE,
495                    ab->data, AFS_BUFFER_PAGESIZE);
496     ab->dirty = 0;      /* Clear the dirty flag */
497     afs_CFileClose(tfile);
498 }
499
500 void
501 DFlushDCache(struct dcache *adc) 
502 {
503     int i;
504     struct buffer *tb;
505
506     ObtainReadLock(&afs_bufferLock);
507
508     for (i = 0; i <= PHPAGEMASK; i++)
509         for (tb = phTable[pHash(adc->index, i)]; tb; tb = tb->hashNext)
510             if (tb->fid == adc->index) {
511                 ObtainWriteLock(&tb->lock, 701);
512                 tb->lockers++;
513                 ReleaseReadLock(&afs_bufferLock);
514                 if (tb->dirty) {
515                     DFlushBuffer(tb);
516                 }
517                 tb->lockers--;
518                 ReleaseWriteLock(&tb->lock);
519                 ObtainReadLock(&afs_bufferLock);
520             }
521
522     ReleaseReadLock(&afs_bufferLock);
523 }
524
525 void
526 DFlush(void)
527 {
528     /* Flush all the modified buffers. */
529     register int i;
530     register struct buffer *tb;
531
532     AFS_STATCNT(DFlush);
533     tb = Buffers;
534     ObtainReadLock(&afs_bufferLock);
535     for (i = 0; i < nbuffers; i++, tb++) {
536         if (tb->dirty) {
537             ObtainWriteLock(&tb->lock, 263);
538             tb->lockers++;
539             ReleaseReadLock(&afs_bufferLock);
540             if (tb->dirty) {
541                 /* it seems safe to do this I/O without having the dcache
542                  * locked, since the only things that will update the data in
543                  * a directory are the buffer package, which holds the relevant
544                  * tb->lock while doing the write, or afs_GetDCache, which 
545                  * DZap's the directory while holding the dcache lock.
546                  * It is not possible to lock the dcache or even call
547                  * afs_GetDSlot to map the index to the dcache since the dir
548                  * package's caller has some dcache object locked already (so
549                  * we cannot lock afs_xdcache). In addition, we cannot obtain
550                  * a dcache lock while holding the tb->lock of the same file
551                  * since that can deadlock with DRead/DNew */
552                 DFlushBuffer(tb);
553             }
554             tb->lockers--;
555             ReleaseWriteLock(&tb->lock);
556             ObtainReadLock(&afs_bufferLock);
557         }
558     }
559     ReleaseReadLock(&afs_bufferLock);
560 }
561
562 void *
563 DNew(register struct dcache *adc, register int page)
564 {
565     /* Same as read, only do *not* even try to read the page, since it probably doesn't exist. */
566     register struct buffer *tb;
567     AFS_STATCNT(DNew);
568     ObtainWriteLock(&afs_bufferLock, 264);
569     if ((tb = afs_newslot(adc, page, NULL)) == 0) {
570         ReleaseWriteLock(&afs_bufferLock);
571         return 0;
572     }
573     /* extend the chunk, if needed */
574     /* Do it now, not in DFlush or afs_newslot when the data is written out,
575      * since now our caller has adc->lock writelocked, and we can't acquire
576      * that lock (or even map from a fid to a dcache) in afs_newslot or
577      * DFlush due to lock hierarchy issues */
578     if ((page + 1) * AFS_BUFFER_PAGESIZE > adc->f.chunkBytes) {
579         afs_AdjustSize(adc, (page + 1) * AFS_BUFFER_PAGESIZE);
580         afs_WriteDCache(adc, 1);
581     }
582     ObtainWriteLock(&tb->lock, 265);
583     tb->lockers++;
584     ReleaseWriteLock(&afs_bufferLock);
585     ReleaseWriteLock(&tb->lock);
586     return tb->data;
587 }
588
589 void
590 shutdown_bufferpackage(void)
591 {
592     register struct buffer *tp;
593     int i;
594
595     AFS_STATCNT(shutdown_bufferpackage);
596     /* Free all allocated Buffers and associated buffer pages */
597     DFlush();
598     if (afs_cold_shutdown) {
599         dinit_flag = 0;
600         tp = Buffers;
601         for (i = 0; i < nbuffers; i += NPB, tp += NPB) {
602 #if defined(AFS_USEBUFFERS)
603             /* The following check shouldn't be necessary and it will be removed soon */
604             if (!tp->bufp)
605                 afs_warn
606                     ("afs: shutdown_bufferpackage: bufp == 0!! Shouldn't happen\n");
607             else {
608                 brelse(tp->bufp);
609                 tp->bufp = 0;
610             }
611 #else
612             afs_osi_Free(tp->data, NPB * AFS_BUFFER_PAGESIZE);
613 #endif
614         }
615         afs_osi_Free(Buffers, nbuffers * sizeof(struct buffer));
616         nbuffers = 0;
617         timecounter = 1;
618         for (i = 0; i < PHSIZE; i++)
619             phTable[i] = 0;
620         memset(&afs_bufferLock, 0, sizeof(afs_lock_t));
621     }
622 }