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