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