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