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