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