47a24d4d1a9512989f565c03aae5cb2de2bc85bc
[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)[0])) & 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(afs_inode_t * 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 afs_inode_t * 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     tfile = afs_CFileOpen(fid[0]);
228     if (page * AFS_BUFFER_PAGESIZE >= tfile->size) {
229         dirp_Zap(tb->fid);
230         tb->lockers--;
231         MReleaseWriteLock(&tb->lock);
232         afs_CFileClose(tfile);
233         return NULL;
234     }
235     code =
236         afs_CFileRead(tfile, tb->page * AFS_BUFFER_PAGESIZE, tb->data,
237                       AFS_BUFFER_PAGESIZE);
238     afs_CFileClose(tfile);
239     if (code < AFS_BUFFER_PAGESIZE) {
240         dirp_Zap(tb->fid);
241         tb->lockers--;
242         MReleaseWriteLock(&tb->lock);
243         return NULL;
244     }
245     /* Note that findslot sets the page field in the buffer equal to
246      * what it is searching for. */
247     MReleaseWriteLock(&tb->lock);
248     return tb->data;
249 }
250
251 static void
252 FixupBucket(register struct buffer *ap)
253 {
254     register struct buffer **lp, *tp;
255     register int i;
256     /* first try to get it out of its current hash bucket, in which it
257      * might not be */
258     AFS_STATCNT(FixupBucket);
259     i = ap->hashIndex;
260     lp = &phTable[i];
261     for (tp = *lp; tp; tp = tp->hashNext) {
262         if (tp == ap) {
263             *lp = tp->hashNext;
264             break;
265         }
266         lp = &tp->hashNext;
267     }
268     /* now figure the new hash bucket */
269     i = pHash(ap->fid, ap->page);
270     ap->hashIndex = i;          /* remember where we are for deletion */
271     ap->hashNext = phTable[i];  /* add us to the list */
272     phTable[i] = ap;            /* at the front, since it's LRU */
273 }
274
275 /* lp is pointer to a fairly-old buffer */
276 static struct buffer *
277 afs_newslot(afs_inode_t * afid, afs_int32 apage, register struct buffer *lp)
278 {
279     /* Find a usable buffer slot */
280     register afs_int32 i;
281     afs_int32 lt;
282     register struct buffer *tp;
283     struct osi_file *tfile;
284
285     AFS_STATCNT(afs_newslot);
286     /* we take a pointer here to a buffer which was at the end of an
287      * LRU hash chain.  Odds are, it's one of the older buffers, not
288      * one of the newer.  Having an older buffer to start with may
289      * permit us to avoid a few of the assignments in the "typical
290      * case" for loop below.
291      */
292     if (lp && (lp->lockers == 0)) {
293         lt = lp->accesstime;
294     } else {
295         lp = 0;
296         lt = BUF_TIME_MAX;
297     }
298
299     /* timecounter might have wrapped, if machine is very very busy
300      * and stays up for a long time.  Timecounter mustn't wrap twice
301      * (positive->negative->positive) before calling newslot, but that
302      * would require 2 billion consecutive cache hits... Anyway, the
303      * penalty is only that the cache replacement policy will be
304      * almost MRU for the next ~2 billion DReads...  newslot doesn't
305      * get called nearly as often as DRead, so in order to avoid the
306      * performance penalty of using the hypers, it's worth doing the
307      * extra check here every time.  It's probably cheaper than doing
308      * hcmp, anyway.  There is a little performance hit resulting from
309      * resetting all the access times to 0, but it only happens once
310      * every month or so, and the access times will rapidly sort
311      * themselves back out after just a few more DReads.
312      */
313     if (timecounter < 0) {
314         timecounter = 1;
315         tp = Buffers;
316         for (i = 0; i < nbuffers; i++, tp++) {
317             tp->accesstime = 0;
318             if (!lp && !tp->lockers)    /* one is as good as the rest, I guess */
319                 lp = tp;
320         }
321     } else {
322         /* this is the typical case */
323         tp = Buffers;
324         for (i = 0; i < nbuffers; i++, tp++) {
325             if (tp->lockers == 0) {
326                 if (tp->accesstime < lt) {
327                     lp = tp;
328                     lt = tp->accesstime;
329                 }
330             }
331         }
332     }
333
334     if (lp == 0) {
335         /* There are no unlocked buffers -- this used to panic, but that
336          * seems extreme.  To the best of my knowledge, all the callers
337          * of DRead are prepared to handle a zero return.  Some of them
338          * just panic directly, but not all of them. */
339         afs_warn("all buffers locked");
340         return 0;
341     }
342
343     if (lp->dirty) {
344         tfile = afs_CFileOpen(lp->fid[0]);
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     dirp_Cpy(lp->fid, afid);    /* set this */
354     lp->page = apage;
355     lp->accesstime = timecounter++;
356     FixupBucket(lp);            /* move to the right hash bucket */
357
358     return lp;
359 }
360
361 void
362 DRelease(register struct buffer *bp, int flag)
363 {
364     /* Release a buffer, specifying whether or not the buffer has been
365      * modified by the locker. */
366     register int index;
367 #if AFS_USEBUFFERS
368     register struct buffer *tp;
369 #endif
370
371     AFS_STATCNT(DRelease);
372     if (!bp)
373         return;
374 #if AFS_USEBUFFERS
375     /* look for buffer by scanning Unix buffers for appropriate address */
376     tp = Buffers;
377     for (index = 0; index < nbuffers; index += NPB, tp += NPB) {
378         if ((afs_int32) bp >= (afs_int32) tp->data
379             && (afs_int32) bp <
380             (afs_int32) tp->data + AFS_BUFFER_PAGESIZE * NPB) {
381             /* we found the right range */
382             index += ((afs_int32) bp - (afs_int32) tp->data) >> LOGPS;
383             break;
384         }
385     }
386 #else
387     index = (((char *)bp) - ((char *)BufferData)) >> LOGPS;
388 #endif
389     bp = &(Buffers[index]);
390     MObtainWriteLock(&bp->lock, 261);
391     bp->lockers--;
392     if (flag)
393         bp->dirty = 1;
394     MReleaseWriteLock(&bp->lock);
395 }
396
397 int
398 DVOffset(register void *ap)
399 {
400     /* Return the byte within a file represented by a buffer pointer. */
401     register struct buffer *bp;
402     register int index;
403 #if AFS_USEBUFFERS
404     register struct buffer *tp;
405 #endif
406     AFS_STATCNT(DVOffset);
407     bp = ap;
408 #if AFS_USEBUFFERS
409     /* look for buffer by scanning Unix buffers for appropriate address */
410     tp = Buffers;
411     for (index = 0; index < nbuffers; index += NPB, tp += NPB) {
412         if ((afs_int32) bp >= (afs_int32) tp->data
413             && (afs_int32) bp <
414             (afs_int32) tp->data + AFS_BUFFER_PAGESIZE * NPB) {
415             /* we found the right range */
416             index += ((afs_int32) bp - (afs_int32) tp->data) >> LOGPS;
417             break;
418         }
419     }
420 #else
421     index = (((char *)bp) - ((char *)BufferData)) >> LOGPS;
422 #endif
423     if (index < 0 || index >= nbuffers)
424         return -1;
425     bp = &(Buffers[index]);
426     return AFS_BUFFER_PAGESIZE * bp->page + (int)(((char *)ap) - bp->data);
427 }
428
429 /* 1/1/91 - I've modified the hash function to take the page as well
430  * as the *fid, so that lookup will be a bit faster.  That presents some
431  * difficulties for Zap, which now has to have some knowledge of the nature
432  * of the hash function.  Oh well.  This should use the list traversal 
433  * method of DRead...
434  */
435 void
436 DZap(afs_inode_t * fid)
437 {
438     register int i;
439     /* Destroy all buffers pertaining to a particular fid. */
440     register struct buffer *tb;
441
442     AFS_STATCNT(DZap);
443     MObtainReadLock(&afs_bufferLock);
444
445     for (i = 0; i <= PHPAGEMASK; i++)
446         for (tb = phTable[pHash(fid, i)]; tb; tb = tb->hashNext)
447             if (dirp_Eq(tb->fid, fid)) {
448                 MObtainWriteLock(&tb->lock, 262);
449                 dirp_Zap(tb->fid);
450                 tb->dirty = 0;
451                 MReleaseWriteLock(&tb->lock);
452             }
453     MReleaseReadLock(&afs_bufferLock);
454 }
455
456 void
457 DFlush(void)
458 {
459     /* Flush all the modified buffers. */
460     register int i;
461     register struct buffer *tb;
462     struct osi_file *tfile;
463
464     AFS_STATCNT(DFlush);
465     tb = Buffers;
466     MObtainReadLock(&afs_bufferLock);
467     for (i = 0; i < nbuffers; i++, tb++) {
468         if (tb->dirty) {
469             MObtainWriteLock(&tb->lock, 263);
470             tb->lockers++;
471             MReleaseReadLock(&afs_bufferLock);
472             if (tb->dirty) {
473                 tfile = afs_CFileOpen(tb->fid[0]);
474                 afs_CFileWrite(tfile, tb->page * AFS_BUFFER_PAGESIZE,
475                                tb->data, AFS_BUFFER_PAGESIZE);
476                 tb->dirty = 0;  /* Clear the dirty flag */
477                 afs_CFileClose(tfile);
478             }
479             tb->lockers--;
480             MReleaseWriteLock(&tb->lock);
481             MObtainReadLock(&afs_bufferLock);
482         }
483     }
484     MReleaseReadLock(&afs_bufferLock);
485 }
486
487 void *
488 DNew(register afs_inode_t * fid, register int page)
489 {
490     /* Same as read, only do *not* even try to read the page, since it probably doesn't exist. */
491     register struct buffer *tb;
492     AFS_STATCNT(DNew);
493     MObtainWriteLock(&afs_bufferLock, 264);
494     if ((tb = afs_newslot(fid, page, NULL)) == 0) {
495         MReleaseWriteLock(&afs_bufferLock);
496         return 0;
497     }
498     MObtainWriteLock(&tb->lock, 265);
499     MReleaseWriteLock(&afs_bufferLock);
500     tb->lockers++;
501     MReleaseWriteLock(&tb->lock);
502     return tb->data;
503 }
504
505 void
506 shutdown_bufferpackage(void)
507 {
508 #if AFS_USEBUFFERS
509     register struct buffer *tp;
510 #endif
511     int i;
512     extern int afs_cold_shutdown;
513
514     AFS_STATCNT(shutdown_bufferpackage);
515     /* Free all allocated Buffers and associated buffer pages */
516     DFlush();
517     if (afs_cold_shutdown) {
518         dinit_flag = 0;
519 #if !AFS_USEBUFFERS
520         afs_osi_Free(BufferData, nbuffers * AFS_BUFFER_PAGESIZE);
521 #else
522         tp = Buffers;
523         for (i = 0; i < nbuffers; i += NPB, tp += NPB) {
524             /* The following check shouldn't be necessary and it will be removed soon */
525             if (!tp->bufp)
526                 afs_warn
527                     ("shutdown_bufferpackage: bufp == 0!! Shouldn't happen\n");
528             else {
529                 brelse(tp->bufp);
530                 tp->bufp = 0;
531             }
532         }
533 #endif
534         afs_osi_Free(Buffers, nbuffers * sizeof(struct buffer));
535         nbuffers = 0;
536         timecounter = 1;
537         for (i = 0; i < PHSIZE; i++)
538             phTable[i] = 0;
539         memset((char *)&afs_bufferLock, 0, sizeof(afs_lock_t));
540     }
541 }