0b56b262fb6fe25c0ebf8277f6cf9adb989ba4eb
[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 RCSID
14     ("$Header$");
15
16 #include "afs/sysincludes.h"
17 #include "afsincludes.h"
18 #if !defined(UKERNEL)
19 #include "h/param.h"
20 #include "h/types.h"
21 #include "h/time.h"
22 #if     defined(AFS_AIX31_ENV) || defined(AFS_DEC_ENV)
23 #include "h/limits.h"
24 #endif
25 #if     !defined(AFS_AIX_ENV) && !defined(AFS_SUN5_ENV) && !defined(AFS_SGI_ENV) && !defined(AFS_LINUX20_ENV)
26 #include "h/kernel.h"           /* Doesn't needed, so it should go */
27 #endif
28 #endif /* !defined(UKERNEL) */
29
30 #include "afs/afs_osi.h"
31 #include "afsint.h"
32 #include "afs/lock.h"
33
34 #if !defined(UKERNEL) && !defined(AFS_LINUX20_ENV)
35 #include "h/buf.h"
36 #endif /* !defined(UKERNEL) */
37
38 #include "afs/stds.h"
39 #include "afs/volerrors.h"
40 #include "afs/exporter.h"
41 #include "afs/prs_fs.h"
42 #include "afs/afs_chunkops.h"
43 #include "afs/dir.h"
44
45 #include "afs/afs_stats.h"
46 #include "afs/longc_procs.h"
47 #include "afs/afs.h"
48
49 #ifndef BUF_TIME_MAX
50 #define BUF_TIME_MAX    0x7fffffff
51 #endif
52 /* number of pages per Unix buffer, when we're using Unix buffer pool */
53 #define NPB 4
54 /* page size */
55 #define AFS_BUFFER_PAGESIZE 2048
56 /* log page size */
57 #define LOGPS 11
58 /* If you change any of this PH stuff, make sure you don't break DZap() */
59 /* use last two bits for page */
60 #define PHPAGEMASK 3
61 /* use next five bits for fid */
62 #define PHFIDMASK 124
63 /* page hash table size - this is pretty intertwined with pHash */
64 #define PHSIZE (PHPAGEMASK + PHFIDMASK + 1)
65 /* the pHash macro */
66 #define pHash(fid,page) ((((afs_int32)((fid)->inode)) & PHFIDMASK) \
67                          | (page & PHPAGEMASK))
68
69 #ifdef  dirty
70 #undef dirty                    /* XXX */
71 #endif
72
73 static struct buffer *Buffers = 0;
74 static char *BufferData;
75
76 #ifdef  AFS_AIX_ENV
77 extern struct buf *geteblk();
78 #endif
79 #ifdef AFS_FBSD_ENV
80 #define timecounter afs_timecounter
81 #endif
82 /* The locks for individual buffer entries are now sometimes obtained while holding the
83  * afs_bufferLock. Thus we now have a locking hierarchy: afs_bufferLock -> Buffers[].lock.
84  */
85 static afs_lock_t afs_bufferLock;
86 static struct buffer *phTable[PHSIZE];  /* page hash table */
87 static int nbuffers;
88 static afs_int32 timecounter;
89
90 /* Prototypes for static routines */
91 static struct buffer *afs_newslot(struct fcache * afid, afs_int32 apage,
92                                   register struct buffer *lp);
93
94 static int dinit_flag = 0;
95 void
96 DInit(int abuffers)
97 {
98     /* Initialize the venus buffer system. */
99     register int i;
100     register struct buffer *tb;
101 #if AFS_USEBUFFERS
102     struct buf *tub;            /* unix buffer for allocation */
103 #endif
104
105     AFS_STATCNT(DInit);
106     if (dinit_flag)
107         return;
108     dinit_flag = 1;
109 #if AFS_USEBUFFERS
110     /* round up to next multiple of NPB, since we allocate multiple pages per chunk */
111     abuffers = ((abuffers - 1) | (NPB - 1)) + 1;
112 #endif
113     LOCK_INIT(&afs_bufferLock, "afs_bufferLock");
114     Buffers =
115         (struct buffer *)afs_osi_Alloc(abuffers * sizeof(struct buffer));
116 #if !AFS_USEBUFFERS
117     BufferData = (char *)afs_osi_Alloc(abuffers * AFS_BUFFER_PAGESIZE);
118 #endif
119     timecounter = 1;
120     afs_stats_cmperf.bufAlloced = nbuffers = abuffers;
121     for (i = 0; i < PHSIZE; i++)
122         phTable[i] = 0;
123     for (i = 0; i < abuffers; i++) {
124 #if AFS_USEBUFFERS
125         if ((i & (NPB - 1)) == 0) {
126             /* time to allocate a fresh buffer */
127             tub = geteblk(AFS_BUFFER_PAGESIZE * NPB);
128             BufferData = (char *)tub->b_un.b_addr;
129         }
130 #endif
131         /* Fill in each buffer with an empty indication. */
132         tb = &Buffers[i];
133         dirp_Zap(tb->fid);
134         tb->accesstime = 0;
135         tb->lockers = 0;
136 #if AFS_USEBUFFERS
137         if ((i & (NPB - 1)) == 0)
138             tb->bufp = tub;
139         else
140             tb->bufp = 0;
141         tb->data = &BufferData[AFS_BUFFER_PAGESIZE * (i & (NPB - 1))];
142 #else
143         tb->data = &BufferData[AFS_BUFFER_PAGESIZE * i];
144 #endif
145         tb->hashIndex = 0;
146         tb->dirty = 0;
147         RWLOCK_INIT(&tb->lock, "buffer lock");
148     }
149     return;
150 }
151
152 void *
153 DRead(register struct fcache * fid, register int page)
154 {
155     /* Read a page from the disk. */
156     register struct buffer *tb, *tb2;
157     struct osi_file *tfile;
158     int code;
159
160     AFS_STATCNT(DRead);
161     MObtainWriteLock(&afs_bufferLock, 256);
162
163 #define bufmatch(tb) (tb->page == page && dirp_Eq(tb->fid, fid))
164 #define buf_Front(head,parent,p) {(parent)->hashNext = (p)->hashNext; (p)->hashNext= *(head);*(head)=(p);}
165
166     /* this apparently-complicated-looking code is simply an example of
167      * a little bit of loop unrolling, and is a standard linked-list 
168      * traversal trick. It saves a few assignments at the the expense
169      * of larger code size.  This could be simplified by better use of
170      * macros. 
171      */
172     if ((tb = phTable[pHash(fid, page)])) {
173         if (bufmatch(tb)) {
174             MObtainWriteLock(&tb->lock, 257);
175             ReleaseWriteLock(&afs_bufferLock);
176             tb->lockers++;
177             tb->accesstime = timecounter++;
178             AFS_STATS(afs_stats_cmperf.bufHits++);
179             MReleaseWriteLock(&tb->lock);
180             return tb->data;
181         } else {
182             register struct buffer **bufhead;
183             bufhead = &(phTable[pHash(fid, page)]);
184             while ((tb2 = tb->hashNext)) {
185                 if (bufmatch(tb2)) {
186                     buf_Front(bufhead, tb, tb2);
187                     MObtainWriteLock(&tb2->lock, 258);
188                     ReleaseWriteLock(&afs_bufferLock);
189                     tb2->lockers++;
190                     tb2->accesstime = timecounter++;
191                     AFS_STATS(afs_stats_cmperf.bufHits++);
192                     MReleaseWriteLock(&tb2->lock);
193                     return tb2->data;
194                 }
195                 if ((tb = tb2->hashNext)) {
196                     if (bufmatch(tb)) {
197                         buf_Front(bufhead, tb2, tb);
198                         MObtainWriteLock(&tb->lock, 259);
199                         ReleaseWriteLock(&afs_bufferLock);
200                         tb->lockers++;
201                         tb->accesstime = timecounter++;
202                         AFS_STATS(afs_stats_cmperf.bufHits++);
203                         MReleaseWriteLock(&tb->lock);
204                         return tb->data;
205                     }
206                 } else
207                     break;
208             }
209         }
210     } else
211         tb2 = NULL;
212
213     AFS_STATS(afs_stats_cmperf.bufMisses++);
214     /* can't find it */
215     /* The last thing we looked at was either tb or tb2 (or nothing). That
216      * is at least the oldest buffer on one particular hash chain, so it's 
217      * a pretty good place to start looking for the truly oldest buffer.
218      */
219     tb = afs_newslot(fid, page, (tb ? tb : tb2));
220     if (!tb) {
221         MReleaseWriteLock(&afs_bufferLock);
222         return NULL;
223     }
224     MObtainWriteLock(&tb->lock, 260);
225     MReleaseWriteLock(&afs_bufferLock);
226     tb->lockers++;
227     if (page * AFS_BUFFER_PAGESIZE >= fid->chunkBytes) {
228         dirp_Zap(tb->fid);
229         tb->lockers--;
230         MReleaseWriteLock(&tb->lock);
231         return NULL;
232     }
233     tfile = afs_CFileOpen(fid->inode);
234     code =
235         afs_CFileRead(tfile, tb->page * AFS_BUFFER_PAGESIZE, tb->data,
236                       AFS_BUFFER_PAGESIZE);
237     afs_CFileClose(tfile);
238     if (code < AFS_BUFFER_PAGESIZE) {
239         dirp_Zap(tb->fid);
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 fcache * afid, 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         tfile = afs_CFileOpen(lp->fid->inode);
344         afs_CFileWrite(tfile, lp->page * AFS_BUFFER_PAGESIZE, lp->data,
345                        AFS_BUFFER_PAGESIZE);
346         lp->dirty = 0;
347         afs_CFileClose(tfile);
348         AFS_STATS(afs_stats_cmperf.bufFlushDirty++);
349     }
350
351     /* Now fill in the header. */
352     dirp_Cpy(lp->fid, afid);    /* set this */
353     lp->page = apage;
354     lp->accesstime = timecounter++;
355     FixupBucket(lp);            /* move to the right hash bucket */
356
357     return lp;
358 }
359
360 void
361 DRelease(register struct buffer *bp, int flag)
362 {
363     /* Release a buffer, specifying whether or not the buffer has been
364      * modified by the locker. */
365     register int index;
366 #if AFS_USEBUFFERS
367     register struct buffer *tp;
368 #endif
369
370     AFS_STATCNT(DRelease);
371     if (!bp)
372         return;
373 #if AFS_USEBUFFERS
374     /* look for buffer by scanning Unix buffers for appropriate address */
375     tp = Buffers;
376     for (index = 0; index < nbuffers; index += NPB, tp += NPB) {
377         if ((afs_int32) bp >= (afs_int32) tp->data
378             && (afs_int32) bp <
379             (afs_int32) tp->data + AFS_BUFFER_PAGESIZE * NPB) {
380             /* we found the right range */
381             index += ((afs_int32) bp - (afs_int32) tp->data) >> LOGPS;
382             break;
383         }
384     }
385 #else
386     index = (((char *)bp) - ((char *)BufferData)) >> LOGPS;
387 #endif
388     bp = &(Buffers[index]);
389     MObtainWriteLock(&bp->lock, 261);
390     bp->lockers--;
391     if (flag)
392         bp->dirty = 1;
393     MReleaseWriteLock(&bp->lock);
394 }
395
396 int
397 DVOffset(register void *ap)
398 {
399     /* Return the byte within a file represented by a buffer pointer. */
400     register struct buffer *bp;
401     register int index;
402 #if AFS_USEBUFFERS
403     register struct buffer *tp;
404 #endif
405     AFS_STATCNT(DVOffset);
406     bp = ap;
407 #if AFS_USEBUFFERS
408     /* look for buffer by scanning Unix buffers for appropriate address */
409     tp = Buffers;
410     for (index = 0; index < nbuffers; index += NPB, tp += NPB) {
411         if ((afs_int32) bp >= (afs_int32) tp->data
412             && (afs_int32) bp <
413             (afs_int32) tp->data + AFS_BUFFER_PAGESIZE * NPB) {
414             /* we found the right range */
415             index += ((afs_int32) bp - (afs_int32) tp->data) >> LOGPS;
416             break;
417         }
418     }
419 #else
420     index = (((char *)bp) - ((char *)BufferData)) >> LOGPS;
421 #endif
422     if (index < 0 || index >= nbuffers)
423         return -1;
424     bp = &(Buffers[index]);
425     return AFS_BUFFER_PAGESIZE * bp->page + (int)(((char *)ap) - bp->data);
426 }
427
428 /* 1/1/91 - I've modified the hash function to take the page as well
429  * as the *fid, so that lookup will be a bit faster.  That presents some
430  * difficulties for Zap, which now has to have some knowledge of the nature
431  * of the hash function.  Oh well.  This should use the list traversal 
432  * method of DRead...
433  */
434 void
435 DZap(struct fcache * fid)
436 {
437     register int i;
438     /* Destroy all buffers pertaining to a particular fid. */
439     register struct buffer *tb;
440
441     AFS_STATCNT(DZap);
442     MObtainReadLock(&afs_bufferLock);
443
444     for (i = 0; i <= PHPAGEMASK; i++)
445         for (tb = phTable[pHash(fid, i)]; tb; tb = tb->hashNext)
446             if (dirp_Eq(tb->fid, fid)) {
447                 MObtainWriteLock(&tb->lock, 262);
448                 dirp_Zap(tb->fid);
449                 tb->dirty = 0;
450                 MReleaseWriteLock(&tb->lock);
451             }
452     MReleaseReadLock(&afs_bufferLock);
453 }
454
455 void
456 DFlush(void)
457 {
458     /* Flush all the modified buffers. */
459     register int i;
460     register struct buffer *tb;
461     struct osi_file *tfile;
462
463     AFS_STATCNT(DFlush);
464     tb = Buffers;
465     MObtainReadLock(&afs_bufferLock);
466     for (i = 0; i < nbuffers; i++, tb++) {
467         if (tb->dirty) {
468             MObtainWriteLock(&tb->lock, 263);
469             tb->lockers++;
470             MReleaseReadLock(&afs_bufferLock);
471             if (tb->dirty) {
472                 tfile = afs_CFileOpen(tb->fid->inode);
473                 afs_CFileWrite(tfile, tb->page * AFS_BUFFER_PAGESIZE,
474                                tb->data, AFS_BUFFER_PAGESIZE);
475                 tb->dirty = 0;  /* Clear the dirty flag */
476                 afs_CFileClose(tfile);
477             }
478             tb->lockers--;
479             MReleaseWriteLock(&tb->lock);
480             MObtainReadLock(&afs_bufferLock);
481         }
482     }
483     MReleaseReadLock(&afs_bufferLock);
484 }
485
486 void *
487 DNew(register struct fcache * fid, register int page)
488 {
489     /* Same as read, only do *not* even try to read the page, since it probably doesn't exist. */
490     register struct buffer *tb;
491     AFS_STATCNT(DNew);
492     MObtainWriteLock(&afs_bufferLock, 264);
493     if ((tb = afs_newslot(fid, page, NULL)) == 0) {
494         MReleaseWriteLock(&afs_bufferLock);
495         return 0;
496     }
497     MObtainWriteLock(&tb->lock, 265);
498     MReleaseWriteLock(&afs_bufferLock);
499     tb->lockers++;
500     MReleaseWriteLock(&tb->lock);
501     return tb->data;
502 }
503
504 void
505 shutdown_bufferpackage(void)
506 {
507 #if AFS_USEBUFFERS
508     register struct buffer *tp;
509 #endif
510     int i;
511     extern int afs_cold_shutdown;
512
513     AFS_STATCNT(shutdown_bufferpackage);
514     /* Free all allocated Buffers and associated buffer pages */
515     DFlush();
516     if (afs_cold_shutdown) {
517         dinit_flag = 0;
518 #if !AFS_USEBUFFERS
519         afs_osi_Free(BufferData, nbuffers * AFS_BUFFER_PAGESIZE);
520 #else
521         tp = Buffers;
522         for (i = 0; i < nbuffers; i += NPB, tp += NPB) {
523             /* The following check shouldn't be necessary and it will be removed soon */
524             if (!tp->bufp)
525                 afs_warn
526                     ("shutdown_bufferpackage: bufp == 0!! Shouldn't happen\n");
527             else {
528                 brelse(tp->bufp);
529                 tp->bufp = 0;
530             }
531         }
532 #endif
533         afs_osi_Free(Buffers, nbuffers * sizeof(struct buffer));
534         nbuffers = 0;
535         timecounter = 1;
536         for (i = 0; i < PHSIZE; i++)
537             phTable[i] = 0;
538         memset((char *)&afs_bufferLock, 0, sizeof(afs_lock_t));
539     }
540 }