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