dcache-finegrained-locks-20011121
[openafs.git] / src / afs / afs_dcache.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 /*
11  * Implements:
12  */
13 #include <afsconfig.h>
14 #include "../afs/param.h"
15
16 RCSID("$Header$");
17
18 #include "../afs/sysincludes.h" /*Standard vendor system headers*/
19 #include "../afs/afsincludes.h" /*AFS-based standard headers*/
20 #include "../afs/afs_stats.h"  /* statistics */
21 #include "../afs/afs_cbqueue.h"
22 #include "../afs/afs_osidnlc.h"
23
24 /* Forward declarations. */
25 static void afs_GetDownD(int anumber, int *aneedSpace);
26 static void afs_FreeDiscardedDCache(void);
27 static void afs_DiscardDCache(struct dcache *);
28 static void afs_FreeDCache(struct dcache *);
29
30 /* Imported variables */
31 extern afs_rwlock_t afs_xvcache;
32 extern afs_rwlock_t afs_xcbhash;
33 extern afs_int32 afs_mariner;
34 extern afs_int32 cacheInfoModTime;                      /*Last time cache info modified*/
35
36
37 /*
38  * --------------------- Exported definitions ---------------------
39  */
40 afs_lock_t afs_xdcache;                 /*Lock: alloc new disk cache entries*/
41 afs_int32 afs_freeDCList;               /*Free list for disk cache entries*/
42 afs_int32 afs_freeDCCount;              /*Count of elts in freeDCList*/
43 afs_int32 afs_discardDCList;            /*Discarded disk cache entries*/
44 afs_int32 afs_discardDCCount;           /*Count of elts in discardDCList*/
45 struct dcache *afs_freeDSList;          /*Free list for disk slots */
46 struct dcache *afs_Initial_freeDSList;  /*Initial list for above*/
47 ino_t cacheInode;                       /*Inode for CacheItems file*/
48 struct osi_file *afs_cacheInodep = 0;   /* file for CacheItems inode */
49 struct afs_q afs_DLRU;                  /*dcache LRU*/
50 afs_int32 afs_dhashsize = 1024;
51 afs_int32 *afs_dvhashTbl;               /*Data cache hash table*/
52 afs_int32 *afs_dchashTbl;               /*Data cache hash table*/
53 afs_int32 *afs_dvnextTbl;               /*Dcache hash table links */
54 afs_int32 *afs_dcnextTbl;               /*Dcache hash table links */
55 struct dcache **afs_indexTable;         /*Pointers to dcache entries*/
56 afs_hyper_t *afs_indexTimes;            /*Dcache entry Access times*/
57 afs_int32 *afs_indexUnique;             /*dcache entry Fid.Unique */
58 unsigned char *afs_indexFlags;          /*(only one) Is there data there?*/
59 afs_hyper_t afs_indexCounter;           /*Fake time for marking index
60                                           entries*/
61 afs_int32 afs_cacheFiles =0;            /*Size of afs_indexTable*/
62 afs_int32 afs_cacheBlocks;              /*1K blocks in cache*/
63 afs_int32 afs_cacheStats;               /*Stat entries in cache*/
64 afs_int32 afs_blocksUsed;               /*Number of blocks in use*/
65 afs_int32 afs_blocksDiscarded;          /*Blocks freed but not truncated */
66 afs_int32 afs_fsfragsize = 1023;        /*Underlying Filesystem minimum unit 
67                                          *of disk allocation usually 1K
68                                          *this value is (truefrag -1 ) to
69                                          *save a bunch of subtracts... */
70 #ifdef AFS_64BIT_CLIENT
71 #ifdef AFS_VM_RDWR_ENV
72 afs_size_t afs_vmMappingEnd;            /* for large files (>= 2GB) the VM
73                                          * mapping an 32bit addressing machines
74                                          * can only be used below the 2 GB
75                                          * line. From this point upwards we
76                                          * must do direct I/O into the cache
77                                          * files. The value should be on a
78                                          * chunk boundary. */
79 #endif /* AFS_VM_RDWR_ENV */
80 #endif /* AFS_64BIT_CLIENT */
81
82 /* The following is used to ensure that new dcache's aren't obtained when
83  * the cache is nearly full.
84  */
85 int afs_WaitForCacheDrain = 0;
86 int afs_TruncateDaemonRunning = 0;
87 int afs_CacheTooFull = 0;
88
89 afs_int32  afs_dcentries;               /* In-memory dcache entries */
90
91
92 int dcacheDisabled = 0;
93
94 extern struct dcache *afs_UFSGetDSlot();
95 extern struct volume *afs_UFSGetVolSlot();
96 extern int osi_UFSTruncate(), afs_osi_Read(), afs_osi_Write(), osi_UFSClose();
97 extern int afs_UFSRead(), afs_UFSWrite();
98 static int afs_UFSCacheFetchProc(), afs_UFSCacheStoreProc();
99 extern int afs_UFSHandleLink();
100 struct afs_cacheOps afs_UfsCacheOps = {
101     osi_UFSOpen,
102     osi_UFSTruncate,
103     afs_osi_Read,
104     afs_osi_Write,
105     osi_UFSClose,
106     afs_UFSRead,
107     afs_UFSWrite,
108     afs_UFSCacheFetchProc,
109     afs_UFSCacheStoreProc,
110     afs_UFSGetDSlot,
111     afs_UFSGetVolSlot,
112     afs_UFSHandleLink,
113 };
114
115 extern void *afs_MemCacheOpen();
116 extern struct dcache *afs_MemGetDSlot();
117 extern struct volume *afs_MemGetVolSlot();
118 extern int afs_MemCacheTruncate(), afs_MemReadBlk(), afs_MemWriteBlk(), afs_MemCacheClose();
119 extern int afs_MemRead(), afs_MemWrite(), afs_MemCacheFetchProc(), afs_MemCacheStoreProc();
120 extern int afs_MemHandleLink();
121 struct afs_cacheOps afs_MemCacheOps = {
122     afs_MemCacheOpen,
123     afs_MemCacheTruncate,
124     afs_MemReadBlk,
125     afs_MemWriteBlk,
126     afs_MemCacheClose,
127     afs_MemRead,
128     afs_MemWrite,
129     afs_MemCacheFetchProc,
130     afs_MemCacheStoreProc,
131     afs_MemGetDSlot,
132     afs_MemGetVolSlot,
133     afs_MemHandleLink,
134 };
135
136 int cacheDiskType;                      /*Type of backing disk for cache*/
137 struct afs_cacheOps *afs_cacheType;
138
139
140
141
142 /*
143  * afs_StoreWarn
144  *
145  * Description:
146  *      Warn about failing to store a file.
147  *
148  * Parameters:
149  *      acode   : Associated error code.
150  *      avolume : Volume involved.
151  *      aflags  : How to handle the output:
152  *                      aflags & 1: Print out on console
153  *                      aflags & 2: Print out on controlling tty
154  *
155  * Environment:
156  *      Call this from close call when vnodeops is RCS unlocked.
157  */
158
159 void
160 afs_StoreWarn(acode, avolume, aflags)
161     register afs_int32 acode;
162     afs_int32 avolume;
163     register afs_int32 aflags;
164
165 { /*afs_StoreWarn*/
166
167     static char problem_fmt[] =
168         "afs: failed to store file in volume %d (%s)\n";
169     static char problem_fmt_w_error[] =
170         "afs: failed to store file in volume %d (error %d)\n";
171     static char netproblems[] = "network problems";
172     static char partfull[]    = "partition full";
173     static char overquota[]   = "over quota";
174     static char unknownerr[]  = "unknown error";
175
176     AFS_STATCNT(afs_StoreWarn);
177     if (acode < 0) {
178         /*
179          * Network problems
180          */
181         if (aflags & 1)
182             afs_warn(problem_fmt, avolume, netproblems);
183         if (aflags & 2)
184             afs_warnuser(problem_fmt, avolume, netproblems);
185     }
186     else
187         if (acode == ENOSPC) {
188             /*
189              * Partition full
190              */
191             if (aflags & 1)
192                 afs_warn(problem_fmt, avolume, partfull);
193             if (aflags & 2)
194                 afs_warnuser(problem_fmt, avolume, partfull);
195         }
196         else
197 #ifndef AFS_SUN5_ENV
198             /* EDQUOT doesn't exist on solaris and won't be sent by the server.
199              * Instead ENOSPC will be sent...
200              */
201             if (acode == EDQUOT) {
202                 /*
203                  * Quota exceeded
204                  */
205                 if (aflags & 1)
206                     afs_warn(problem_fmt, avolume, overquota);
207                 if (aflags & 2)
208                     afs_warnuser(problem_fmt, avolume, overquota);
209             } else
210 #endif
211             {
212                 /*
213                  * Unknown error
214                  */
215                 if (aflags & 1)
216                     afs_warn(problem_fmt_w_error, avolume, acode);
217                 if (aflags & 2)
218                     afs_warnuser(problem_fmt_w_error, avolume, acode);
219             }
220 } /*afs_StoreWarn*/
221
222 void afs_MaybeWakeupTruncateDaemon() {
223     if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
224         afs_CacheTooFull = 1;
225         if (!afs_TruncateDaemonRunning)
226             afs_osi_Wakeup((char *)afs_CacheTruncateDaemon);
227     } else if (!afs_TruncateDaemonRunning &&
228                 afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
229         afs_osi_Wakeup((char *)afs_CacheTruncateDaemon);
230     }
231 }
232
233 /* Keep statistics on run time for afs_CacheTruncateDaemon. This is a
234  * struct so we need only export one symbol for AIX.
235  */
236 struct CTD_stats {
237     osi_timeval_t CTD_beforeSleep;
238     osi_timeval_t CTD_afterSleep;
239     osi_timeval_t CTD_sleepTime;
240     osi_timeval_t CTD_runTime;
241     int CTD_nSleeps;
242 } CTD_stats;
243
244 u_int afs_min_cache = 0;
245 void afs_CacheTruncateDaemon() {
246     osi_timeval_t CTD_tmpTime;
247     u_int counter;
248     u_int cb_lowat;
249     u_int dc_hiwat = (100-CM_DCACHECOUNTFREEPCT+CM_DCACHEEXTRAPCT)*afs_cacheFiles/100;
250     afs_min_cache = (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize)>>10;
251
252     osi_GetuTime(&CTD_stats.CTD_afterSleep);
253     afs_TruncateDaemonRunning = 1;
254     while (1) {
255         cb_lowat =  ((CM_DCACHESPACEFREEPCT-CM_DCACHEEXTRAPCT)
256                      * afs_cacheBlocks) / 100;
257         MObtainWriteLock(&afs_xdcache,266);
258         if (afs_CacheTooFull) {
259           int space_needed, slots_needed;
260             /* if we get woken up, we should try to clean something out */
261             for (counter = 0; counter < 10; counter++) {
262                 space_needed = afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
263                 slots_needed = dc_hiwat - afs_freeDCCount - afs_discardDCCount;
264                 afs_GetDownD(slots_needed, &space_needed);      
265                 if ((space_needed <= 0) && (slots_needed <= 0)) {
266                     break;
267                 }
268                 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
269                     break;
270             }
271             if (!afs_CacheIsTooFull())
272                 afs_CacheTooFull = 0;
273         }
274         MReleaseWriteLock(&afs_xdcache);
275
276         /*
277          * This is a defensive check to try to avoid starving threads
278          * that may need the global lock so thay can help free some
279          * cache space. If this thread won't be sleeping or truncating
280          * any cache files then give up the global lock so other
281          * threads get a chance to run.
282          */
283         if ((afs_termState!=AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull &&
284             (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
285             afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
286         }
287
288         /*
289          * This is where we free the discarded cache elements.
290          */
291         while(afs_blocksDiscarded && !afs_WaitForCacheDrain && 
292               (afs_termState!=AFSOP_STOP_TRUNCDAEMON))
293         {
294             afs_FreeDiscardedDCache();
295         }
296
297         /* See if we need to continue to run. Someone may have
298          * signalled us while we were executing.
299          */
300         if (!afs_WaitForCacheDrain && !afs_CacheTooFull &&
301                         (afs_termState!=AFSOP_STOP_TRUNCDAEMON))
302         {
303             /* Collect statistics on truncate daemon. */
304             CTD_stats.CTD_nSleeps++;
305             osi_GetuTime(&CTD_stats.CTD_beforeSleep);
306             afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
307                               CTD_stats.CTD_beforeSleep);
308             afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
309
310             afs_TruncateDaemonRunning = 0;
311             afs_osi_Sleep((char *)afs_CacheTruncateDaemon);  
312             afs_TruncateDaemonRunning = 1;
313
314             osi_GetuTime(&CTD_stats.CTD_afterSleep);
315             afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
316                               CTD_stats.CTD_afterSleep);
317             afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
318         }
319         if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
320 #ifdef AFS_AFSDB_ENV
321             afs_termState = AFSOP_STOP_AFSDB;
322 #else
323             afs_termState = AFSOP_STOP_RXEVENT;
324 #endif
325             afs_osi_Wakeup(&afs_termState);
326             break;
327         }
328     }
329 }
330
331
332 /*
333  * afs_AdjustSize
334  *
335  * Description:
336  *      Make adjustment for the new size in the disk cache entry
337  *
338  * Major Assumptions Here:
339  *      Assumes that frag size is an integral power of two, less one,
340  *      and that this is a two's complement machine.  I don't
341  *      know of any filesystems which violate this assumption...
342  *
343  * Parameters:
344  *      adc      : Ptr to dcache entry.
345  *      anewsize : New size desired.
346  */
347
348 void
349 afs_AdjustSize(adc, newSize)
350     register struct dcache *adc;
351     register afs_int32 newSize;
352
353 { /*afs_AdjustSize*/
354
355     register afs_int32 oldSize;
356
357     AFS_STATCNT(afs_AdjustSize);
358
359     adc->dflags |= DFEntryMod;
360     oldSize = ((adc->f.chunkBytes + afs_fsfragsize)^afs_fsfragsize)>>10;/* round up */
361     adc->f.chunkBytes = newSize;
362     newSize = ((newSize + afs_fsfragsize)^afs_fsfragsize)>>10;/* round up */
363     if (newSize > oldSize) {
364         /* We're growing the file, wakeup the daemon */
365         afs_MaybeWakeupTruncateDaemon();
366     }
367     afs_blocksUsed += (newSize - oldSize);
368     afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
369
370 } /*afs_AdjustSize*/
371
372
373
374
375
376 /*
377  * afs_GetDownD
378  *
379  * Description:
380  *      This routine is responsible for moving at least one entry (but up
381  *      to some number of them) from the LRU queue to the free queue.
382  *
383  * Parameters:
384  *      anumber    : Number of entries that should ideally be moved.
385  *      aneedSpace : How much space we need (1K blocks);
386  *
387  * Environment:
388  *      The anumber parameter is just a hint; at least one entry MUST be
389  *      moved, or we'll panic.  We must be called with afs_xdcache
390  *      write-locked.  We should try to satisfy both anumber and aneedspace,
391  *      whichever is more demanding - need to do several things:
392  *      1.  only grab up to anumber victims if aneedSpace <= 0, not
393  *          the whole set of MAXATONCE.
394  *      2.  dynamically choose MAXATONCE to reflect severity of
395  *          demand: something like (*aneedSpace >> (logChunk - 9)) 
396  *  N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
397  *  indicates that the cache is not properly configured/tuned or
398  *  something. We should be able to automatically correct that problem.
399  */
400
401 #define MAXATONCE   16          /* max we can obtain at once */
402 static void afs_GetDownD(int anumber, int *aneedSpace)
403 {
404
405     struct dcache *tdc;
406     struct VenusFid *afid;
407     afs_int32 i, j, k;
408     afs_hyper_t vtime;
409     int skip, phase;
410     register struct vcache *tvc;
411     afs_uint32 victims[MAXATONCE];
412     struct dcache *victimDCs[MAXATONCE];
413     afs_hyper_t victimTimes[MAXATONCE];/* youngest (largest LRU time) first */
414     afs_uint32 victimPtr;           /* next free item in victim arrays */
415     afs_hyper_t maxVictimTime;      /* youngest (largest LRU time) victim */
416     afs_uint32 maxVictimPtr;                /* where it is */
417     int discard;
418
419     AFS_STATCNT(afs_GetDownD);
420     if (CheckLock(&afs_xdcache) != -1)
421         osi_Panic("getdownd nolock");
422     /* decrement anumber first for all dudes in free list */
423     /* SHOULD always decrement anumber first, even if aneedSpace >0, 
424      * because we should try to free space even if anumber <=0 */
425     if (!aneedSpace || *aneedSpace <= 0) {
426         anumber -= afs_freeDCCount;
427         if (anumber <= 0) return;       /* enough already free */
428     }
429     /* bounds check parameter */
430     if (anumber > MAXATONCE)
431         anumber = MAXATONCE;   /* all we can do */
432
433     /*
434      * The phase variable manages reclaims.  Set to 0, the first pass,
435      * we don't reclaim active entries.  Set to 1, we reclaim even active
436      * ones.
437      */
438     phase = 0;
439     for (i = 0; i < afs_cacheFiles; i++)
440         /* turn off all flags */
441         afs_indexFlags[i] &= ~IFFlag;
442
443     while (anumber > 0 || (aneedSpace && *aneedSpace >0)) {
444         /* find oldest entries for reclamation */
445         maxVictimPtr = victimPtr = 0;
446         hzero(maxVictimTime);
447         /* select victims from access time array */
448         for (i = 0; i < afs_cacheFiles; i++) {
449             if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
450               /* skip if dirty or already free */
451               continue;
452             }
453             tdc = afs_indexTable[i];
454             if (tdc && (tdc->refCount != 0)) {
455               /* Referenced; can't use it! */
456               continue;
457             }
458             hset(vtime, afs_indexTimes[i]);
459
460             /* if we've already looked at this one, skip it */
461             if (afs_indexFlags[i] & IFFlag) continue;
462
463             if (victimPtr < MAXATONCE) {
464                 /* if there's at least one free victim slot left */
465                 victims[victimPtr] = i;
466                 hset(victimTimes[victimPtr], vtime);
467                 if (hcmp(vtime, maxVictimTime) > 0) {
468                     hset(maxVictimTime, vtime);
469                     maxVictimPtr = victimPtr;
470                 }
471                 victimPtr++;
472             }
473             else if (hcmp(vtime, maxVictimTime) < 0) {
474                 /*
475                  * We're older than youngest victim, so we replace at
476                  * least one victim
477                  */
478                 /* find youngest (largest LRU) victim */
479                 j = maxVictimPtr;
480                 if (j == victimPtr) osi_Panic("getdownd local");
481                 victims[j] = i;
482                 hset(victimTimes[j], vtime);
483                 /* recompute maxVictimTime */
484                 hset(maxVictimTime, vtime);
485                 for(j = 0; j < victimPtr; j++)
486                     if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
487                         hset(maxVictimTime, victimTimes[j]);
488                         maxVictimPtr = j;
489                     }
490             }
491         } /* big for loop */
492
493         /* now really reclaim the victims */
494         j = 0;  /* flag to track if we actually got any of the victims */
495         /* first, hold all the victims, since we're going to release the lock
496          * during the truncate operation.
497          */
498         for(i=0; i < victimPtr; i++) {
499             tdc = afs_GetDSlot(victims[i], 0);
500             /* We got tdc->tlock(R) here */
501             if (tdc->refCount == 1)
502                 victimDCs[i] = tdc;
503             else
504                 victimDCs[i] = 0;
505             ReleaseReadLock(&tdc->tlock);
506             if (!victimDCs[i]) afs_PutDCache(tdc);
507         }
508         for(i = 0; i < victimPtr; i++) {
509             /* q is first elt in dcache entry */
510             tdc = victimDCs[i];
511             /* now, since we're dropping the afs_xdcache lock below, we
512              * have to verify, before proceeding, that there are no other
513              * references to this dcache entry, even now.  Note that we
514              * compare with 1, since we bumped it above when we called
515              * afs_GetDSlot to preserve the entry's identity.
516              */
517             if (tdc && tdc->refCount == 1) {
518                 unsigned char chunkFlags;
519                 afs_size_t tchunkoffset;
520                 afid = &tdc->f.fid;
521                 /* xdcache is lower than the xvcache lock */
522                 MReleaseWriteLock(&afs_xdcache);
523                 MObtainReadLock(&afs_xvcache);
524                 tvc = afs_FindVCache(afid, 0,0, 0, 0 /* no stats, no vlru */ );
525                 MReleaseReadLock(&afs_xvcache);
526                 MObtainWriteLock(&afs_xdcache, 527);
527                 skip = 0;
528                 if (tdc->refCount > 1) skip = 1;
529                 if (tvc) {
530                     tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
531                     chunkFlags = afs_indexFlags[tdc->index];
532                     if (phase == 0 && osi_Active(tvc)) skip = 1;
533                     if (phase > 0 && osi_Active(tvc) && (tvc->states & CDCLock)
534                                 && (chunkFlags & IFAnyPages)) skip = 1;
535                     if (chunkFlags & IFDataMod) skip = 1;
536                     afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
537                                ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
538                                ICL_TYPE_INT32, tdc->index,
539                                ICL_TYPE_OFFSET, 
540                                ICL_HANDLE_OFFSET(tchunkoffset));
541
542 #if     defined(AFS_SUN5_ENV)
543                     /*
544                      * Now we try to invalidate pages.  We do this only for
545                      * Solaris.  For other platforms, it's OK to recycle a
546                      * dcache entry out from under a page, because the strategy
547                      * function can call afs_GetDCache().
548                      */
549                     if (!skip && (chunkFlags & IFAnyPages)) {
550                         int code;
551
552                         MReleaseWriteLock(&afs_xdcache);
553                         MObtainWriteLock(&tvc->vlock, 543);
554                         if (tvc->multiPage) {
555                             skip = 1;
556                             goto endmultipage;
557                         }
558                         /* block locking pages */
559                         tvc->vstates |= VPageCleaning;
560                         /* block getting new pages */
561                         tvc->activeV++;
562                         MReleaseWriteLock(&tvc->vlock);
563                         /* One last recheck */
564                         MObtainWriteLock(&afs_xdcache, 333);
565                         chunkFlags = afs_indexFlags[tdc->index];
566                         if (tdc->refCount > 1
567                             || (chunkFlags & IFDataMod)
568                             || (osi_Active(tvc) && (tvc->states & CDCLock)
569                                 && (chunkFlags & IFAnyPages))) {
570                             skip = 1;
571                             MReleaseWriteLock(&afs_xdcache);
572                             goto endputpage;
573                         }
574                         MReleaseWriteLock(&afs_xdcache);
575
576                         code = osi_VM_GetDownD(tvc, tdc);
577
578                         MObtainWriteLock(&afs_xdcache,269);
579                         /* we actually removed all pages, clean and dirty */
580                         if (code == 0) {
581                             afs_indexFlags[tdc->index] &= ~(IFDirtyPages| IFAnyPages);
582                         } else
583                             skip = 1;
584                         MReleaseWriteLock(&afs_xdcache);
585 endputpage:
586                         MObtainWriteLock(&tvc->vlock, 544);
587                         if (--tvc->activeV == 0 && (tvc->vstates & VRevokeWait)) {
588                             tvc->vstates &= ~VRevokeWait;
589                             afs_osi_Wakeup((char *)&tvc->vstates);
590
591                         }
592                         if (tvc->vstates & VPageCleaning) {
593                             tvc->vstates &= ~VPageCleaning;
594                             afs_osi_Wakeup((char *)&tvc->vstates);
595                         }
596 endmultipage:
597                         MReleaseWriteLock(&tvc->vlock);
598                     } else
599 #endif  /* AFS_SUN5_ENV */
600                     {
601                         MReleaseWriteLock(&afs_xdcache);
602                     }
603
604                     AFS_FAST_RELE(tvc);
605                     MObtainWriteLock(&afs_xdcache, 528);
606                     if (afs_indexFlags[tdc->index] &
607                          (IFDataMod | IFDirtyPages | IFAnyPages)) skip = 1;
608                     if (tdc->refCount > 1) skip = 1;
609                 }
610 #if     defined(AFS_SUN5_ENV)
611                 else {
612                     /* no vnode, so IFDirtyPages is spurious (we don't
613                      * sweep dcaches on vnode recycling, so we can have
614                      * DIRTYPAGES set even when all pages are gone).  Just
615                      * clear the flag.
616                      * Hold vcache lock to prevent vnode from being
617                      * created while we're clearing IFDirtyPages.
618                      */
619                     afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
620                 }
621 #endif
622                 if (skip) {
623                     /* skip this guy and mark him as recently used */
624                     afs_indexFlags[tdc->index] |= IFFlag;
625                     afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
626                                ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
627                                ICL_TYPE_INT32, tdc->index,
628                                ICL_TYPE_OFFSET, 
629                                ICL_HANDLE_OFFSET(tchunkoffset));
630                 }
631                 else {
632                     /* flush this dude from the data cache and reclaim;
633                      * first, make sure no one will care that we damage
634                      * it, by removing it from all hash tables.  Then,
635                      * melt it down for parts.  Note that any concurrent
636                      * (new possibility!) calls to GetDownD won't touch
637                      * this guy because his reference count is > 0. */
638                     afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
639                                ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
640                                ICL_TYPE_INT32, tdc->index,
641                                ICL_TYPE_OFFSET, 
642                                ICL_HANDLE_OFFSET(tchunkoffset));
643 #ifndef AFS_DEC_ENV
644                     AFS_STATCNT(afs_gget);
645 #endif
646                     afs_HashOutDCache(tdc);
647                     if (tdc->f.chunkBytes != 0) {
648                         discard = 1;
649                         if (aneedSpace)
650                           *aneedSpace -= (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
651                     } else {
652                         discard = 0;
653                     }
654                     if (discard) {
655                         afs_DiscardDCache(tdc);
656                     } else {
657                         afs_FreeDCache(tdc);
658                     }
659                     anumber--;
660                     j = 1;      /* we reclaimed at least one victim */
661                 }
662             }
663             afs_PutDCache(tdc);
664         }
665         
666         if (phase == 0) {
667             /* Phase is 0 and no one was found, so try phase 1 (ignore
668              * osi_Active flag) */
669             if (j == 0) {
670                 phase = 1;
671                 for (i = 0; i < afs_cacheFiles; i++)
672                     /* turn off all flags */
673                     afs_indexFlags[i] &= ~IFFlag;
674             }
675         }
676         else {
677             /* found no one in phase 1, we're hosed */
678             if (victimPtr == 0) break;
679         }
680     } /* big while loop */
681     return;
682
683 } /*afs_GetDownD*/
684
685
686 /*
687  * Description: remove adc from any hash tables that would allow it to be located
688  * again by afs_FindDCache or afs_GetDCache.
689  *
690  * Parameters: adc -- pointer to dcache entry to remove from hash tables.
691  *
692  * Locks: Must have the afs_xdcache lock write-locked to call this function.
693  */
694 afs_HashOutDCache(adc)
695     struct dcache *adc;
696
697 { /*afs_HashOutDCache*/
698
699     int i, us;
700
701 #ifndef AFS_DEC_ENV
702     AFS_STATCNT(afs_glink);
703 #endif
704     /* we know this guy's in the LRUQ.  We'll move dude into DCQ below */
705     DZap(&adc->f.inode);
706     /* if this guy is in the hash table, pull him out */
707     if (adc->f.fid.Fid.Volume != 0) {
708         /* remove entry from first hash chains */
709         i = DCHash(&adc->f.fid, adc->f.chunk);
710         us = afs_dchashTbl[i];
711         if (us == adc->index) {
712             /* first dude in the list */
713             afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
714         }
715         else {
716             /* somewhere on the chain */
717             while (us != NULLIDX) {
718                 if (afs_dcnextTbl[us] == adc->index) {
719                     /* found item pointing at the one to delete */
720                     afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
721                     break;
722                 }
723                 us = afs_dcnextTbl[us];
724             }
725             if (us == NULLIDX) osi_Panic("dcache hc");
726         }
727         /* remove entry from *other* hash chain */
728         i = DVHash(&adc->f.fid);
729         us = afs_dvhashTbl[i];
730         if (us == adc->index) {
731             /* first dude in the list */
732             afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
733         }
734         else {
735             /* somewhere on the chain */
736             while (us != NULLIDX) {
737                 if (afs_dvnextTbl[us] == adc->index) {
738                     /* found item pointing at the one to delete */
739                     afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
740                     break;
741                 }
742                 us = afs_dvnextTbl[us];
743             }
744             if (us == NULLIDX) osi_Panic("dcache hv");
745         }
746     }
747
748     /* prevent entry from being found on a reboot (it is already out of
749      * the hash table, but after a crash, we just look at fid fields of
750      * stable (old) entries).
751      */
752     adc->f.fid.Fid.Volume = 0;  /* invalid */
753
754     /* mark entry as modified */
755     adc->dflags |= DFEntryMod;
756
757     /* all done */
758     return 0;
759 } /*afs_HashOutDCache */
760
761
762 /*
763  * afs_FlushDCache
764  *
765  * Description:
766  *      Flush the given dcache entry, pulling it from hash chains
767  *      and truncating the associated cache file.
768  *
769  * Arguments:
770  *      adc: Ptr to dcache entry to flush.
771  *
772  * Environment:
773  *      This routine must be called with the afs_xdcache lock held
774  *      (in write mode)
775  */
776
777 void
778 afs_FlushDCache(adc)
779 register struct dcache *adc;
780 { /*afs_FlushDCache*/
781
782     AFS_STATCNT(afs_FlushDCache);
783     /*
784      * Bump the number of cache files flushed.
785      */
786     afs_stats_cmperf.cacheFlushes++;
787
788     /* remove from all hash tables */
789     afs_HashOutDCache(adc);
790
791     /* Free its space; special case null operation, since truncate operation
792      * in UFS is slow even in this case, and this allows us to pre-truncate
793      * these files at more convenient times with fewer locks set
794      * (see afs_GetDownD).
795      */
796     if (adc->f.chunkBytes != 0) {
797         afs_DiscardDCache(adc);
798         afs_MaybeWakeupTruncateDaemon();
799     } else {
800         afs_FreeDCache(adc);
801     }
802
803     if (afs_WaitForCacheDrain) {
804         if (afs_blocksUsed <=
805             (CM_CACHESIZEDRAINEDPCT*afs_cacheBlocks)/100) {
806             afs_WaitForCacheDrain = 0;
807             afs_osi_Wakeup(&afs_WaitForCacheDrain);
808         }
809     }
810 } /*afs_FlushDCache*/
811
812
813 /*
814  * afs_FreeDCache
815  *
816  * Description: put a dcache entry on the free dcache entry list.
817  *
818  * Parameters: adc -- dcache entry to free
819  *
820  * Environment: called with afs_xdcache lock write-locked.
821  */
822 static void afs_FreeDCache(adc)
823     register struct dcache *adc;
824 {
825     /* Thread on free list, update free list count and mark entry as
826      * freed in its indexFlags element.  Also, ensure DCache entry gets
827      * written out (set DFEntryMod).
828      */
829
830     afs_dvnextTbl[adc->index] = afs_freeDCList;
831     afs_freeDCList = adc->index;
832     afs_freeDCCount++;
833     afs_indexFlags[adc->index] |= IFFree;
834     adc->dflags |= DFEntryMod;
835
836     if (afs_WaitForCacheDrain) {
837         if ((afs_blocksUsed - afs_blocksDiscarded) <=
838             (CM_CACHESIZEDRAINEDPCT*afs_cacheBlocks)/100) {
839             afs_WaitForCacheDrain = 0;
840             afs_osi_Wakeup(&afs_WaitForCacheDrain);
841         }
842     }
843 }
844
845 /*
846  * afs_DiscardDCache
847  *
848  * Description:
849  *      Discard the cache element by moving it to the discardDCList.
850  *      This puts the cache element into a quasi-freed state, where
851  *      the space may be reused, but the file has not been truncated.
852  *
853  * Major Assumptions Here:
854  *      Assumes that frag size is an integral power of two, less one,
855  *      and that this is a two's complement machine.  I don't
856  *      know of any filesystems which violate this assumption...
857  *
858  * Parameters:
859  *      adc      : Ptr to dcache entry.
860  *
861  * Environment:
862  *      Must be called with afs_xdcache write-locked.
863  */
864
865 static void
866 afs_DiscardDCache(adc)
867     register struct dcache *adc;
868
869 { /*afs_DiscardDCache*/
870
871     register afs_int32 size;
872
873     AFS_STATCNT(afs_DiscardDCache);
874
875     osi_Assert(adc->refCount == 1);
876
877     size = ((adc->f.chunkBytes + afs_fsfragsize)^afs_fsfragsize)>>10;/* round up */
878     afs_blocksDiscarded += size;
879     afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
880
881     afs_dvnextTbl[adc->index] = afs_discardDCList;
882     afs_discardDCList = adc->index;
883     afs_discardDCCount++;
884
885     adc->f.fid.Fid.Volume = 0;
886     adc->dflags |= DFEntryMod;
887     afs_indexFlags[adc->index] |= IFDiscarded;
888
889     if (afs_WaitForCacheDrain) {
890         if ((afs_blocksUsed - afs_blocksDiscarded) <=
891             (CM_CACHESIZEDRAINEDPCT*afs_cacheBlocks)/100) {
892             afs_WaitForCacheDrain = 0;
893             afs_osi_Wakeup(&afs_WaitForCacheDrain);
894         }
895     }
896
897 } /*afs_DiscardDCache*/
898
899 /*
900  * afs_FreeDiscardedDCache
901  *
902  * Description:
903  *     Free the next element on the list of discarded cache elements.
904  */
905 static void
906 afs_FreeDiscardedDCache()
907 {
908     register struct dcache *tdc;
909     register struct osi_file *tfile; 
910     register afs_int32 size;
911
912     AFS_STATCNT(afs_FreeDiscardedDCache);
913
914     MObtainWriteLock(&afs_xdcache,510);
915     if (!afs_blocksDiscarded) {
916         MReleaseWriteLock(&afs_xdcache);
917         return;
918     }
919
920     /*
921      * Get an entry from the list of discarded cache elements
922      */
923     tdc = afs_GetDSlot(afs_discardDCList, 0);
924     osi_Assert(tdc->refCount == 1);
925     ReleaseReadLock(&tdc->tlock);
926
927     afs_discardDCList = afs_dvnextTbl[tdc->index];
928     afs_dvnextTbl[tdc->index] = NULLIDX;
929     afs_discardDCCount--;
930     size = ((tdc->f.chunkBytes + afs_fsfragsize)^afs_fsfragsize)>>10;/* round up */
931     afs_blocksDiscarded -= size;
932     afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
933     /* We can lock because we just took it off the free list */
934     ObtainWriteLock(&tdc->lock, 626);
935     MReleaseWriteLock(&afs_xdcache);
936
937     /*
938      * Truncate the element to reclaim its space
939      */
940     tfile = afs_CFileOpen(tdc->f.inode);
941     afs_CFileTruncate(tfile, 0);
942     afs_CFileClose(tfile);
943     afs_AdjustSize(tdc, 0);
944
945     /*
946      * Free the element we just truncated
947      */
948     MObtainWriteLock(&afs_xdcache,511);
949     afs_indexFlags[tdc->index] &= ~IFDiscarded;
950     afs_FreeDCache(tdc);
951     ReleaseWriteLock(&tdc->lock);
952     afs_PutDCache(tdc);
953     MReleaseWriteLock(&afs_xdcache);
954 }
955
956 /*
957  * afs_MaybeFreeDiscardedDCache
958  *
959  * Description:
960  *      Free as many entries from the list of discarded cache elements
961  *      as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
962  *
963  * Parameters:
964  *      None
965  */
966 afs_MaybeFreeDiscardedDCache()
967 {
968
969     AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
970
971     while (afs_blocksDiscarded &&
972            (afs_blocksUsed > (CM_WAITFORDRAINPCT*afs_cacheBlocks)/100)) {
973         afs_FreeDiscardedDCache();
974     }
975     return 0;
976 }
977
978 /*
979  * afs_GetDownDSlot
980  *
981  * Description:
982  *      Try to free up a certain number of disk slots.
983  *
984  * Parameters:
985  *      anumber : Targeted number of disk slots to free up.
986  *
987  * Environment:
988  *      Must be called with afs_xdcache write-locked.
989  */
990 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
991 extern SV_TYPE afs_sgibksync;
992 extern SV_TYPE afs_sgibkwait;
993 extern lock_t afs_sgibklock;
994 extern struct dcache *afs_sgibklist;
995 #endif
996
997 static void
998 afs_GetDownDSlot(anumber)
999     int anumber;
1000
1001 { /*afs_GetDownDSlot*/
1002
1003     struct afs_q *tq, *nq;
1004     struct dcache *tdc;
1005     int ix;
1006     unsigned int i=0;
1007     unsigned int cnt;
1008
1009     AFS_STATCNT(afs_GetDownDSlot);
1010     if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1011         osi_Panic("diskless getdowndslot");
1012
1013     if (CheckLock(&afs_xdcache) != -1)
1014         osi_Panic("getdowndslot nolock");
1015
1016     /* decrement anumber first for all dudes in free list */
1017     for(tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1018         anumber--;
1019     if (anumber <= 0)
1020         return;                         /* enough already free */
1021
1022     for(cnt=0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1023         tq = nq, cnt++) {
1024         tdc = (struct dcache *) tq;     /* q is first elt in dcache entry */
1025         nq = QPrev(tq); /* in case we remove it */
1026         if (tdc->refCount == 0) {
1027             if ((ix=tdc->index) == NULLIDX) osi_Panic("getdowndslot");
1028             /* pull the entry out of the lruq and put it on the free list */
1029             QRemove(&tdc->lruq);
1030
1031             /* write-through if modified */
1032             if (tdc->dflags & DFEntryMod) {
1033 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1034                 /*
1035                  * ask proxy to do this for us - we don't have the stack space
1036                  */
1037                 while (tdc->dflags & DFEntryMod) {
1038                     int s;
1039                     AFS_GUNLOCK();
1040                     s = SPLOCK(afs_sgibklock);
1041                     if (afs_sgibklist == NULL) {
1042                         /* if slot is free, grab it. */
1043                         afs_sgibklist = tdc;
1044                         SV_SIGNAL(&afs_sgibksync);
1045                     }
1046                     /* wait for daemon to (start, then) finish. */
1047                     SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1048                     AFS_GLOCK();
1049                 }
1050 #else
1051                 tdc->dflags &= ~DFEntryMod;
1052                 afs_WriteDCache(tdc, 1);
1053 #endif
1054             }
1055
1056             tdc->stamp = 0;
1057 #ifdef IHINT
1058              if (tdc->ihint) {
1059                  struct osi_file * f = (struct osi_file *)tdc->ihint;
1060                  tdc->ihint = 0;
1061                  afs_UFSClose(f);
1062                  nihints--;
1063              }
1064 #endif /* IHINT */
1065
1066
1067             /* finally put the entry in the free list */
1068             afs_indexTable[ix] = (struct dcache *) 0;
1069             afs_indexFlags[ix] &= ~IFEverUsed;
1070             tdc->index = NULLIDX;
1071             tdc->lruq.next = (struct afs_q *) afs_freeDSList;
1072             afs_freeDSList = tdc;
1073             anumber--;
1074         }
1075     }
1076 } /*afs_GetDownDSlot*/
1077
1078
1079 /*
1080  * afs_RefDCache
1081  *
1082  * Description:
1083  *      Increment the reference count on a disk cache entry,
1084  *      which already has a non-zero refcount.  In order to
1085  *      increment the refcount of a zero-reference entry, you
1086  *      have to hold afs_xdcache.
1087  *
1088  * Parameters:
1089  *      adc : Pointer to the dcache entry to increment.
1090  *
1091  * Environment:
1092  *      Nothing interesting.
1093  */
1094 afs_RefDCache(adc)
1095     struct dcache *adc;
1096 {
1097     ObtainWriteLock(&adc->tlock, 627);
1098     if (adc->refCount < 0)
1099         osi_Panic("RefDCache: negative refcount");
1100     adc->refCount++;
1101     ReleaseWriteLock(&adc->tlock);
1102     return 0;
1103 }
1104
1105
1106 /*
1107  * afs_PutDCache
1108  *
1109  * Description:
1110  *      Decrement the reference count on a disk cache entry.
1111  *
1112  * Parameters:
1113  *      ad : Ptr to the dcache entry to decrement.
1114  *
1115  * Environment:
1116  *      Nothing interesting.
1117  */
1118 afs_PutDCache(adc)
1119     register struct dcache *adc;
1120
1121 { /*afs_PutDCache*/
1122     AFS_STATCNT(afs_PutDCache);
1123     ObtainWriteLock(&adc->tlock, 276);
1124     if (adc->refCount <= 0)
1125         osi_Panic("putdcache");
1126     --adc->refCount;
1127     ReleaseWriteLock(&adc->tlock);
1128     return 0;
1129
1130 } /*afs_PutDCache*/
1131
1132
1133 /*
1134  * afs_TryToSmush
1135  *
1136  * Description:
1137  *      Try to discard all data associated with this file from the
1138  *      cache.
1139  *
1140  * Parameters:
1141  *      avc : Pointer to the cache info for the file.
1142  *
1143  * Environment:
1144  *      Both pvnLock and lock are write held.
1145  */
1146 void
1147 afs_TryToSmush(avc, acred, sync)
1148     register struct vcache *avc;
1149     struct AFS_UCRED *acred;
1150     int sync;
1151 { /*afs_TryToSmush*/
1152
1153     register struct dcache *tdc;
1154     register int index;
1155     register int i;
1156     AFS_STATCNT(afs_TryToSmush);
1157     afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1158                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->m.Length));
1159     sync = 1;                           /* XX Temp testing XX*/
1160
1161 #if     defined(AFS_SUN5_ENV)
1162     ObtainWriteLock(&avc->vlock, 573);
1163     avc->activeV++;     /* block new getpages */
1164     ReleaseWriteLock(&avc->vlock);
1165 #endif
1166
1167     /* Flush VM pages */
1168     osi_VM_TryToSmush(avc, acred, sync);
1169
1170     /*
1171      * Get the hash chain containing all dce's for this fid
1172      */
1173     i = DVHash(&avc->fid);
1174     MObtainWriteLock(&afs_xdcache,277);
1175     for(index = afs_dvhashTbl[i]; index != NULLIDX; index=i) {
1176       i = afs_dvnextTbl[index]; /* next pointer this hash table */
1177       if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1178         int releaseTlock = 1;
1179         tdc = afs_GetDSlot(index, (struct dcache *)0);
1180         if (!FidCmp(&tdc->f.fid, &avc->fid)) {
1181             if (sync) {
1182                 if ((afs_indexFlags[index] & IFDataMod) == 0 &&
1183                     tdc->refCount == 1) {
1184                     ReleaseReadLock(&tdc->tlock);
1185                     releaseTlock = 0;
1186                     afs_FlushDCache(tdc);
1187                 }
1188             } else
1189                 afs_indexTable[index] = 0;
1190         }
1191         if (releaseTlock) ReleaseReadLock(&tdc->tlock);
1192         afs_PutDCache(tdc);
1193       }
1194     }
1195 #if     defined(AFS_SUN5_ENV)
1196     ObtainWriteLock(&avc->vlock, 545);
1197     if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1198         avc->vstates &= ~VRevokeWait;
1199         afs_osi_Wakeup((char *)&avc->vstates);
1200     }
1201     ReleaseWriteLock(&avc->vlock);
1202 #endif
1203     MReleaseWriteLock(&afs_xdcache);
1204     /*
1205      * It's treated like a callback so that when we do lookups we'll invalidate the unique bit if any
1206      * trytoSmush occured during the lookup call
1207      */
1208     afs_allCBs++;
1209 } /*afs_TryToSmush*/
1210
1211 /*
1212  * afs_FindDCache
1213  *
1214  * Description:
1215  *      Given the cached info for a file and a byte offset into the
1216  *      file, make sure the dcache entry for that file and containing
1217  *      the given byte is available, returning it to our caller.
1218  *
1219  * Parameters:
1220  *      avc   : Pointer to the (held) vcache entry to look in.
1221  *      abyte : Which byte we want to get to.
1222  *
1223  * Returns:
1224  *      Pointer to the dcache entry covering the file & desired byte,
1225  *      or NULL if not found.
1226  *
1227  * Environment:
1228  *      The vcache entry is held upon entry.
1229  */
1230
1231 struct dcache *afs_FindDCache(avc, abyte)
1232     register struct vcache *avc;
1233     afs_size_t abyte;
1234
1235 { /*afs_FindDCache*/
1236
1237     afs_int32 chunk;
1238     register afs_int32 i, index;
1239     register struct dcache *tdc;
1240
1241     AFS_STATCNT(afs_FindDCache);
1242     chunk = AFS_CHUNK(abyte);
1243
1244     /*
1245      * Hash on the [fid, chunk] and get the corresponding dcache index
1246      * after write-locking the dcache.
1247      */
1248     i = DCHash(&avc->fid, chunk);
1249     MObtainWriteLock(&afs_xdcache,278);
1250     for(index = afs_dchashTbl[i]; index != NULLIDX;) {
1251       if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1252         tdc = afs_GetDSlot(index, (struct dcache *)0);
1253         ReleaseReadLock(&tdc->tlock);
1254         if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1255             break;  /* leaving refCount high for caller */
1256         }
1257         afs_PutDCache(tdc);
1258       }
1259       index = afs_dcnextTbl[index];
1260     }
1261     MReleaseWriteLock(&afs_xdcache);
1262     if (index != NULLIDX) {
1263         hset(afs_indexTimes[tdc->index], afs_indexCounter);
1264         hadd32(afs_indexCounter, 1);
1265         return tdc;
1266     }
1267     else
1268         return(struct dcache *) 0;
1269
1270 } /*afs_FindDCache*/
1271
1272
1273 /*
1274  * afs_UFSCacheStoreProc
1275  *
1276  * Description:
1277  *      Called upon store.
1278  *
1279  * Parameters:
1280  *      acall : Ptr to the Rx call structure involved.
1281  *      afile : Ptr to the related file descriptor.
1282  *      alen  : Size of the file in bytes.
1283  *      avc   : Ptr to the vcache entry.
1284  *      shouldWake : is it "safe" to return early from close() ?
1285  *      abytesToXferP  : Set to the number of bytes to xfer.
1286  *                       NOTE: This parameter is only used if AFS_NOSTATS
1287  *                              is not defined.
1288  *      abytesXferredP : Set to the number of bytes actually xferred.
1289  *                       NOTE: This parameter is only used if AFS_NOSTATS
1290  *                              is not defined.
1291  *
1292  * Environment:
1293  *      Nothing interesting.
1294  */
1295 static int afs_UFSCacheStoreProc(acall, afile, alen, avc, shouldWake,
1296                               abytesToXferP, abytesXferredP)
1297      register struct rx_call *acall;
1298      struct osi_file *afile;
1299      register afs_int32 alen;
1300      afs_size_t *abytesToXferP;
1301      afs_size_t *abytesXferredP;
1302      struct vcache *avc;
1303      int *shouldWake;
1304 { /* afs_UFSCacheStoreProc*/
1305
1306     afs_int32 code, got;
1307     register char *tbuffer;
1308     register int tlen;
1309
1310     AFS_STATCNT(UFS_CacheStoreProc);
1311
1312 #ifndef AFS_NOSTATS
1313     /*
1314      * In this case, alen is *always* the amount of data we'll be trying
1315      * to ship here.
1316      */
1317     (*abytesToXferP)  = alen;
1318     (*abytesXferredP) = 0;
1319 #endif /* AFS_NOSTATS */
1320
1321     afs_Trace4(afs_iclSetp, CM_TRACE_STOREPROC, ICL_TYPE_POINTER, avc,
1322                         ICL_TYPE_FID, &(avc->fid),
1323                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->m.Length), 
1324                         ICL_TYPE_INT32, alen);
1325     tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1326     while (alen > 0) {
1327         tlen = (alen > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : alen);
1328         got = afs_osi_Read(afile, -1, tbuffer, tlen);
1329         if ((got < 0) 
1330 #if     !defined(AFS_SUN5_ENV) && !defined(AFS_OSF_ENV) && !defined(AFS_SGI64_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_FBSD_ENV)
1331             || (got != tlen && getuerror())
1332 #endif
1333             ) {
1334             osi_FreeLargeSpace(tbuffer);
1335             return EIO;
1336         }
1337         afs_Trace1(afs_iclSetp, CM_TRACE_STOREPROC2, ICL_TYPE_INT32, got);
1338         RX_AFS_GUNLOCK();
1339         code = rx_Write(acall, tbuffer, got);  /* writing 0 bytes will
1340         * push a short packet.  Is that really what we want, just because the
1341         * data didn't come back from the disk yet?  Let's try it and see. */
1342         RX_AFS_GLOCK();
1343 #ifndef AFS_NOSTATS
1344         (*abytesXferredP) += code;
1345 #endif /* AFS_NOSTATS */
1346         if (code != got) {
1347             osi_FreeLargeSpace(tbuffer);
1348             return -33;
1349         }
1350         alen -= got;
1351         /*
1352          * If file has been locked on server, we can allow the store
1353          * to continue.
1354          */
1355         if (shouldWake && *shouldWake && (rx_GetRemoteStatus(acall) & 1)) {
1356             *shouldWake = 0;  /* only do this once */
1357             afs_wakeup(avc);
1358         }
1359     }
1360     afs_Trace4(afs_iclSetp, CM_TRACE_STOREPROC, ICL_TYPE_POINTER, avc,
1361                         ICL_TYPE_FID, &(avc->fid),
1362                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->m.Length), 
1363                         ICL_TYPE_INT32, alen);
1364     osi_FreeLargeSpace(tbuffer);
1365     return 0;
1366
1367 } /* afs_UFSCacheStoreProc*/
1368
1369
1370 /*
1371  * afs_UFSCacheFetchProc
1372  *
1373  * Description:
1374  *      Routine called on fetch; also tells people waiting for data
1375  *      that more has arrived.
1376  *
1377  * Parameters:
1378  *      acall : Ptr to the Rx call structure.
1379  *      afile : File descriptor for the cache file.
1380  *      abase : Base offset to fetch.
1381  *      adc   : Ptr to the dcache entry for the file, write-locked.
1382  *      avc   : Ptr to the vcache entry for the file.
1383  *      abytesToXferP  : Set to the number of bytes to xfer.
1384  *                       NOTE: This parameter is only used if AFS_NOSTATS
1385  *                              is not defined.
1386  *      abytesXferredP : Set to the number of bytes actually xferred.
1387  *                       NOTE: This parameter is only used if AFS_NOSTATS
1388  *                              is not defined.
1389  *
1390  * Environment:
1391  *      Nothing interesting.
1392  */
1393
1394 static int afs_UFSCacheFetchProc(acall, afile, abase, adc, avc,
1395                               abytesToXferP, abytesXferredP, lengthFound)
1396     register struct rx_call *acall;
1397     afs_size_t abase;
1398     afs_size_t *abytesToXferP;
1399     afs_size_t *abytesXferredP;
1400     struct dcache *adc;
1401     struct vcache *avc;
1402     struct osi_file *afile;
1403     afs_int32 lengthFound;
1404 { /*UFS_CacheFetchProc*/
1405     afs_int32 length;
1406     register afs_int32 code;
1407     register char *tbuffer;
1408     register int tlen;
1409     int moredata = 0;
1410
1411     AFS_STATCNT(UFS_CacheFetchProc);
1412     osi_Assert(WriteLocked(&adc->lock));
1413     afile->offset = 0;  /* Each time start from the beginning */
1414     length = lengthFound;
1415 #ifndef AFS_NOSTATS
1416     (*abytesToXferP)  = 0;
1417     (*abytesXferredP) = 0;
1418 #endif /* AFS_NOSTATS */
1419     tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1420     do {
1421         if (moredata) {
1422             RX_AFS_GUNLOCK();
1423             code = rx_Read(acall, (char *)&length, sizeof(afs_int32));
1424             RX_AFS_GLOCK();
1425             length = ntohl(length);
1426             if (code != sizeof(afs_int32)) {
1427                 osi_FreeLargeSpace(tbuffer);
1428                 code = rx_Error(acall);
1429                 return (code?code:-1);      /* try to return code, not -1 */
1430             }    
1431         }
1432         /*
1433          * The fetch protocol is extended for the AFS/DFS translator
1434          * to allow multiple blocks of data, each with its own length,
1435          * to be returned. As long as the top bit is set, there are more
1436          * blocks expected.
1437          *
1438          * We do not do this for AFS file servers because they sometimes
1439          * return large negative numbers as the transfer size.
1440          */
1441         if (avc->states & CForeign) {
1442             moredata = length & 0x80000000;
1443             length &= ~0x80000000;
1444         } else {
1445             moredata = 0;
1446         }
1447 #ifndef AFS_NOSTATS
1448         (*abytesToXferP) += length;
1449 #endif                          /* AFS_NOSTATS */
1450         while (length > 0) {
1451             tlen = (length > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : length);
1452             RX_AFS_GUNLOCK();
1453             code = rx_Read(acall, tbuffer, tlen);
1454             RX_AFS_GLOCK();
1455 #ifndef AFS_NOSTATS
1456             (*abytesXferredP) += code;
1457 #endif                          /* AFS_NOSTATS */
1458             if (code != tlen) {
1459                 osi_FreeLargeSpace(tbuffer);
1460                 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64READ,
1461                         ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
1462                         ICL_TYPE_INT32, length);
1463                 return -34;
1464             }
1465             code = afs_osi_Write(afile, -1, tbuffer, tlen);
1466             if (code != tlen) {
1467                 osi_FreeLargeSpace(tbuffer);
1468                 return EIO;
1469             }
1470             abase += tlen;
1471             length -= tlen;
1472             adc->validPos = abase;
1473             afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAIT,
1474                        ICL_TYPE_STRING, __FILE__,
1475                        ICL_TYPE_INT32, __LINE__,
1476                        ICL_TYPE_POINTER, adc,
1477                        ICL_TYPE_INT32, adc->dflags);
1478             afs_osi_Wakeup(&adc->validPos);
1479         }
1480     } while (moredata);
1481     osi_FreeLargeSpace(tbuffer);
1482     return 0;
1483
1484 } /* afs_UFSCacheFetchProc*/
1485
1486 /*
1487  * afs_GetDCache
1488  *
1489  * Description:
1490  *      This function is called to obtain a reference to data stored in
1491  *      the disk cache, locating a chunk of data containing the desired
1492  *      byte and returning a reference to the disk cache entry, with its
1493  *      reference count incremented.
1494  *
1495  * Parameters:
1496  * IN:
1497  *      avc     : Ptr to a vcache entry (unlocked)
1498  *      abyte   : Byte position in the file desired
1499  *      areq    : Request structure identifying the requesting user.
1500  *      aflags  : Settings as follows:
1501  *                      1 : Set locks
1502  *                      2 : Return after creating entry.
1503  *                      4 : called from afs_vnop_write.c
1504  *                          *alen contains length of data to be written.
1505  * OUT:
1506  *      aoffset : Set to the offset within the chunk where the resident
1507  *                byte is located.
1508  *      alen    : Set to the number of bytes of data after the desired
1509  *                byte (including the byte itself) which can be read
1510  *                from this chunk.
1511  *
1512  * Environment:
1513  *      The vcache entry pointed to by avc is unlocked upon entry.
1514  */
1515
1516 struct tlocal1 {
1517     struct AFSVolSync tsync;
1518     struct AFSFetchStatus OutStatus;
1519     struct AFSCallBack CallBack;
1520 };
1521
1522 /*
1523  * Update the vnode-to-dcache hint if we can get the vnode lock
1524  * right away.  Assumes dcache entry is at least read-locked.
1525  */
1526 void updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src) {
1527     if (!lockVc || 0 == NBObtainWriteLock(&v->lock,src)) {
1528         if (hsame(v->m.DataVersion, d->f.versionNo) && v->callback) {
1529             v->quick.dc = d;
1530             v->quick.stamp = d->stamp = MakeStamp();
1531             v->quick.minLoc = AFS_CHUNKTOBASE(d->f.chunk);
1532             /* Don't think I need these next two lines forever */
1533             v->quick.len = d->f.chunkBytes;
1534             v->h1.dchint = d;
1535         }
1536         if (lockVc) ReleaseWriteLock(&v->lock);
1537     }
1538 }
1539
1540 struct dcache *afs_GetDCache(avc, abyte, areq, aoffset, alen, aflags)
1541     register struct vcache *avc;    /* Write-locked unless aflags & 1 */
1542     afs_size_t abyte;
1543     afs_size_t *aoffset, *alen;
1544     int aflags;
1545     register struct vrequest *areq;
1546
1547 { /*afs_GetDCache*/
1548
1549     register afs_int32 i, code, code1, shortcut , adjustsize=0;
1550     int setLocks;
1551     afs_int32 index;
1552     afs_int32 us;
1553     afs_int32 chunk;
1554     afs_size_t maxGoodLength;           /* amount of good data at server */
1555     struct rx_call *tcall;
1556     afs_size_t Position = 0;
1557 #ifdef AFS_64BIT_CLIENT
1558     afs_size_t tsize;
1559 #endif /* AFS_64BIT_CLIENT */
1560     afs_int32 size, tlen;               /* size of segment to transfer */
1561     afs_size_t lengthFound;             /* as returned from server */
1562     struct tlocal1 *tsmall = 0;
1563     register struct dcache *tdc;
1564     register struct osi_file *file;
1565     register struct conn *tc;
1566     int downDCount = 0;
1567     struct server *newCallback;
1568     char setNewCallback;
1569     char setVcacheStatus;
1570     char doVcacheUpdate;
1571     char slowPass = 0;
1572     int doAdjustSize = 0;
1573     int doReallyAdjustSize = 0;
1574     int overWriteWholeChunk = 0;
1575
1576     XSTATS_DECLS
1577 #ifndef AFS_NOSTATS
1578     struct afs_stats_xferData *xferP;   /* Ptr to this op's xfer struct */
1579     osi_timeval_t  xferStartTime,       /*FS xfer start time*/
1580                    xferStopTime;        /*FS xfer stop time*/
1581     afs_size_t bytesToXfer;                     /* # bytes to xfer*/
1582     afs_size_t bytesXferred;                    /* # bytes actually xferred*/
1583     struct afs_stats_AccessInfo *accP;  /*Ptr to access record in stats*/
1584     int fromReplica;                    /*Are we reading from a replica?*/
1585     int numFetchLoops;                  /*# times around the fetch/analyze loop*/
1586 #endif /* AFS_NOSTATS */
1587
1588     AFS_STATCNT(afs_GetDCache);
1589
1590     if (dcacheDisabled)
1591         return NULL;
1592
1593     setLocks = aflags & 1;
1594
1595     /*
1596      * Determine the chunk number and offset within the chunk corresponding
1597      * to the desired byte.
1598      */
1599     if (avc->fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1600         chunk = 0;
1601     }
1602     else {
1603         chunk = AFS_CHUNK(abyte);
1604     }
1605
1606     /* come back to here if we waited for the cache to drain. */
1607 RetryGetDCache:
1608
1609     setNewCallback = setVcacheStatus = 0;
1610
1611     if (setLocks) {
1612         if (slowPass)
1613             ObtainWriteLock(&avc->lock, 616);
1614         else
1615             ObtainReadLock(&avc->lock);
1616     }
1617
1618     /*
1619      * Locks held:
1620      * avc->lock(R) if setLocks && !slowPass
1621      * avc->lock(W) if !setLocks || slowPass
1622      */
1623
1624     shortcut = 0;
1625
1626     /* check hints first! (might could use bcmp or some such...) */
1627     if (tdc = avc->h1.dchint) {
1628         int dcLocked;
1629
1630         /*
1631          * The locking order between afs_xdcache and dcache lock matters.
1632          * The hint dcache entry could be anywhere, even on the free list.
1633          * Locking afs_xdcache ensures that noone is trying to pull dcache
1634          * entries from the free list, and thereby assuming them to be not
1635          * referenced and not locked.
1636          */
1637         MObtainReadLock(&afs_xdcache);
1638         dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1639
1640         if (dcLocked &&
1641             (tdc->index != NULLIDX) && !FidCmp(&tdc->f.fid, &avc->fid) &&
1642             chunk == tdc->f.chunk &&
1643             !(afs_indexFlags[tdc->index] & (IFFree|IFDiscarded))) {
1644             /* got the right one.  It might not be the right version, and it 
1645              * might be fetching, but it's the right dcache entry.
1646              */
1647             /* All this code should be integrated better with what follows:
1648              * I can save a good bit more time under a write lock if I do..
1649              */
1650             ObtainWriteLock(&tdc->tlock, 603);
1651             tdc->refCount++;
1652             ReleaseWriteLock(&tdc->tlock);
1653
1654             MReleaseReadLock(&afs_xdcache);
1655             shortcut = 1;
1656
1657             if (hsame(tdc->f.versionNo, avc->m.DataVersion) &&
1658                 !(tdc->dflags & DFFetching)) {
1659
1660                 afs_stats_cmperf.dcacheHits++;
1661                 MObtainWriteLock(&afs_xdcache, 559);
1662                 QRemove(&tdc->lruq);
1663                 QAdd(&afs_DLRU, &tdc->lruq);
1664                 MReleaseWriteLock(&afs_xdcache);
1665
1666                 /* Locks held:
1667                  * avc->lock(R) if setLocks && !slowPass
1668                  * avc->lock(W) if !setLocks || slowPass
1669                  * tdc->lock(S)
1670                  */
1671                 goto done;
1672             }
1673         } else {
1674             if (dcLocked) ReleaseSharedLock(&tdc->lock);
1675             MReleaseReadLock(&afs_xdcache);
1676         }
1677
1678         if (!shortcut)
1679             tdc = 0;
1680     }
1681
1682     /* Locks held:
1683      * avc->lock(R) if setLocks && !slowPass
1684      * avc->lock(W) if !setLocks || slowPass
1685      * tdc->lock(S) if tdc
1686      */
1687
1688     if (!tdc) { /* If the hint wasn't the right dcache entry */
1689         /*
1690          * Hash on the [fid, chunk] and get the corresponding dcache index
1691          * after write-locking the dcache.
1692          */
1693 RetryLookup:
1694
1695         /* Locks held:
1696          * avc->lock(R) if setLocks && !slowPass
1697          * avc->lock(W) if !setLocks || slowPass
1698          */
1699
1700         i = DCHash(&avc->fid, chunk);
1701         /* check to make sure our space is fine */
1702         afs_MaybeWakeupTruncateDaemon();
1703
1704         MObtainWriteLock(&afs_xdcache,280);
1705         us = NULLIDX;
1706         for (index = afs_dchashTbl[i]; index != NULLIDX; ) {
1707             if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1708                 tdc = afs_GetDSlot(index, (struct dcache *)0);
1709                 ReleaseReadLock(&tdc->tlock);
1710                 /*
1711                  * Locks held:
1712                  * avc->lock(R) if setLocks && !slowPass
1713                  * avc->lock(W) if !setLocks || slowPass
1714                  * afs_xdcache(W)
1715                  */
1716                 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1717                     /* Move it up in the beginning of the list */
1718                     if (afs_dchashTbl[i] != index)  {
1719                         afs_dcnextTbl[us] = afs_dcnextTbl[index];
1720                         afs_dcnextTbl[index] = afs_dchashTbl[i];
1721                         afs_dchashTbl[i] = index;
1722                     }
1723                     MReleaseWriteLock(&afs_xdcache);
1724                     ObtainSharedLock(&tdc->lock, 606);
1725                     break;  /* leaving refCount high for caller */
1726                 }
1727                 afs_PutDCache(tdc);
1728                 tdc = 0;
1729             }
1730             us = index;
1731             index = afs_dcnextTbl[index];
1732         }
1733
1734         /*
1735          * If we didn't find the entry, we'll create one.
1736          */
1737         if (index == NULLIDX) {
1738             /*
1739              * Locks held:
1740              * avc->lock(R) if setLocks
1741              * avc->lock(W) if !setLocks
1742              * afs_xdcache(W)
1743              */
1744             afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1745                        avc, ICL_TYPE_INT32, chunk);
1746
1747             /* Make sure there is a free dcache entry for us to use */
1748             if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1749                 while (1) {
1750                     if (!setLocks) avc->states |= CDCLock;
1751                     afs_GetDownD(5, (int*)0);   /* just need slots */
1752                     if (!setLocks) avc->states &= ~CDCLock;
1753                     if (afs_discardDCList != NULLIDX || afs_freeDCList != NULLIDX)
1754                         break;
1755                     /* If we can't get space for 5 mins we give up and panic */
1756                     if (++downDCount > 300)
1757                         osi_Panic("getdcache"); 
1758                     MReleaseWriteLock(&afs_xdcache);
1759                     /*
1760                      * Locks held:
1761                      * avc->lock(R) if setLocks
1762                      * avc->lock(W) if !setLocks
1763                      */
1764                     afs_osi_Wait(1000, 0, 0);
1765                     goto RetryLookup;
1766                 }
1767             }
1768
1769             if (afs_discardDCList == NULLIDX ||
1770                 ((aflags & 2) && afs_freeDCList != NULLIDX)) {
1771
1772                 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1773                 tdc = afs_GetDSlot(afs_freeDCList, 0);
1774                 osi_Assert(tdc->refCount == 1);
1775                 ReleaseReadLock(&tdc->tlock);
1776                 ObtainWriteLock(&tdc->lock, 604);
1777                 afs_freeDCList = afs_dvnextTbl[tdc->index];
1778                 afs_freeDCCount--;
1779             } else {
1780                 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1781                 tdc = afs_GetDSlot(afs_discardDCList, 0);
1782                 osi_Assert(tdc->refCount == 1);
1783                 ReleaseReadLock(&tdc->tlock);
1784                 ObtainWriteLock(&tdc->lock, 605);
1785                 afs_discardDCList = afs_dvnextTbl[tdc->index];
1786                 afs_discardDCCount--;
1787                 size = ((tdc->f.chunkBytes + afs_fsfragsize)^afs_fsfragsize)>>10;
1788                 afs_blocksDiscarded -= size;
1789                 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1790                 if (aflags & 2) {
1791                     /* Truncate the chunk so zeroes get filled properly */
1792                     file = afs_CFileOpen(tdc->f.inode);
1793                     afs_CFileTruncate(file, 0);
1794                     afs_CFileClose(file);
1795                     afs_AdjustSize(tdc, 0);
1796                 }
1797             }
1798
1799             /*
1800              * Locks held:
1801              * avc->lock(R) if setLocks
1802              * avc->lock(W) if !setLocks
1803              * tdc->lock(W)
1804              * afs_xdcache(W)
1805              */
1806
1807             /*
1808              * Fill in the newly-allocated dcache record.
1809              */
1810             afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1811             tdc->f.fid = avc->fid;
1812             afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1813             hones(tdc->f.versionNo);        /* invalid value */
1814             tdc->f.chunk = chunk;
1815             tdc->validPos = AFS_CHUNKTOBASE(chunk);
1816             /* XXX */
1817             if (tdc->lruq.prev == &tdc->lruq) osi_Panic("lruq 1");
1818
1819             /*
1820              * Now add to the two hash chains - note that i is still set
1821              * from the above DCHash call.
1822              */
1823             afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1824             afs_dchashTbl[i] = tdc->index;
1825             i = DVHash(&avc->fid);
1826             afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1827             afs_dvhashTbl[i] = tdc->index;
1828             tdc->dflags = DFEntryMod;
1829             tdc->mflags = 0;
1830             tdc->f.states = 0;
1831             afs_MaybeWakeupTruncateDaemon();
1832             MReleaseWriteLock(&afs_xdcache);
1833             ConvertWToSLock(&tdc->lock);
1834         }
1835     } /* vcache->dcache hint failed */
1836
1837     /*
1838      * Locks held:
1839      * avc->lock(R) if setLocks && !slowPass
1840      * avc->lock(W) if !setLocks || slowPass
1841      * tdc->lock(S)
1842      */
1843
1844     afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1845                ICL_TYPE_POINTER, tdc,
1846                ICL_TYPE_INT32, hgetlo(tdc->f.versionNo),
1847                ICL_TYPE_INT32, hgetlo(avc->m.DataVersion));
1848     /*
1849      * Here we have the entry in tdc, with its refCount incremented.
1850      * Note: we don't use the S-lock on avc; it costs concurrency when
1851      * storing a file back to the server.
1852      */
1853
1854     /*
1855      * Not a newly created file so we need to check the file's length and
1856      * compare data versions since someone could have changed the data or we're
1857      * reading a file written elsewhere. We only want to bypass doing no-op
1858      * read rpcs on newly created files (dv of 0) since only then we guarantee
1859      * that this chunk's data hasn't been filled by another client.
1860      */
1861     size = AFS_CHUNKSIZE(abyte);
1862     if (aflags & 4)     /* called from write */
1863         tlen = *alen;
1864     else                /* called from read */
1865         tlen = tdc->validPos - abyte;
1866     Position = AFS_CHUNKTOBASE(chunk);
1867     afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, 
1868                ICL_TYPE_INT32, tlen,
1869                ICL_TYPE_INT32, aflags,
1870                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(abyte),
1871                ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(Position));
1872     if ((aflags & 4) && (hiszero(avc->m.DataVersion)))
1873         doAdjustSize = 1;
1874     if ((aflags & 4) && (abyte == Position) && (tlen >= size))
1875         overWriteWholeChunk = 1;
1876     if (doAdjustSize || overWriteWholeChunk) {
1877 #if     defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1878  #ifdef AFS_SGI_ENV
1879   #ifdef AFS_SGI64_ENV
1880         if (doAdjustSize) adjustsize = NBPP;
1881   #else /* AFS_SGI64_ENV */
1882         if (doAdjustSize) adjustsize = 8192;
1883   #endif /* AFS_SGI64_ENV */
1884  #else /* AFS_SGI_ENV */
1885         if (doAdjustSize) adjustsize = 4096;
1886  #endif /* AFS_SGI_ENV */
1887         if (AFS_CHUNKTOBASE(chunk)+adjustsize >= avc->m.Length &&
1888 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1889  #if    defined(AFS_SUN_ENV)  || defined(AFS_OSF_ENV)
1890         if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->m.Length)) &&
1891  #else
1892         if (AFS_CHUNKTOBASE(chunk) >= avc->m.Length &&
1893  #endif
1894 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1895         !hsame(avc->m.DataVersion, tdc->f.versionNo))
1896             doReallyAdjustSize = 1;
1897
1898         if (doReallyAdjustSize || overWriteWholeChunk) {
1899             /* no data in file to read at this position */
1900             UpgradeSToWLock(&tdc->lock, 607);
1901
1902             file = afs_CFileOpen(tdc->f.inode);
1903             afs_CFileTruncate(file, 0);
1904             afs_CFileClose(file);
1905             afs_AdjustSize(tdc, 0);
1906             hset(tdc->f.versionNo, avc->m.DataVersion);
1907             tdc->dflags |= DFEntryMod;
1908
1909             ConvertWToSLock(&tdc->lock);
1910         }
1911     }
1912
1913     /*
1914      * We must read in the whole chunk if the version number doesn't
1915      * match.
1916      */
1917     if (aflags & 2) {
1918         /* don't need data, just a unique dcache entry */
1919         ObtainWriteLock(&afs_xdcache, 608);
1920         hset(afs_indexTimes[tdc->index], afs_indexCounter);
1921         hadd32(afs_indexCounter, 1);
1922         ReleaseWriteLock(&afs_xdcache);
1923
1924         updateV2DC(setLocks, avc, tdc, 553);
1925         if (vType(avc) == VDIR)
1926             *aoffset = abyte;
1927         else
1928             *aoffset = AFS_CHUNKOFFSET(abyte);
1929         if (tdc->validPos < abyte)
1930             *alen = (afs_size_t) 0;
1931         else
1932             *alen = tdc->validPos - abyte;
1933         ReleaseSharedLock(&tdc->lock);
1934         if (setLocks) {
1935             if (slowPass)
1936                 ReleaseWriteLock(&avc->lock);
1937             else
1938                 ReleaseReadLock(&avc->lock);
1939         }
1940         return tdc;     /* check if we're done */
1941     }
1942
1943     /*
1944      * Locks held:
1945      * avc->lock(R) if setLocks && !slowPass
1946      * avc->lock(W) if !setLocks || slowPass
1947      * tdc->lock(S)
1948      */
1949     osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
1950
1951     setNewCallback = setVcacheStatus = 0;
1952
1953     /*
1954      * Locks held:
1955      * avc->lock(R) if setLocks && !slowPass
1956      * avc->lock(W) if !setLocks || slowPass
1957      * tdc->lock(S)
1958      */
1959     if (!hsame(avc->m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
1960         /*
1961          * Version number mismatch.
1962          */
1963         UpgradeSToWLock(&tdc->lock, 609);
1964
1965         /*
1966          * If data ever existed for this vnode, and this is a text object,
1967          * do some clearing.  Now, you'd think you need only do the flush
1968          * when VTEXT is on, but VTEXT is turned off when the text object
1969          * is freed, while pages are left lying around in memory marked
1970          * with this vnode.  If we would reactivate (create a new text
1971          * object from) this vnode, we could easily stumble upon some of
1972          * these old pages in pagein.  So, we always flush these guys.
1973          * Sun has a wonderful lack of useful invariants in this system.
1974          *
1975          * avc->flushDV is the data version # of the file at the last text
1976          * flush.  Clearly, at least, we don't have to flush the file more
1977          * often than it changes
1978          */
1979         if (hcmp(avc->flushDV, avc->m.DataVersion) < 0) {
1980             /*
1981              * By here, the cache entry is always write-locked.  We can
1982              * deadlock if we call osi_Flush with the cache entry locked...
1983              * Unlock the dcache too.
1984              */
1985             ReleaseWriteLock(&tdc->lock);
1986             if (setLocks && !slowPass)
1987                 ReleaseReadLock(&avc->lock);
1988             else
1989                 ReleaseWriteLock(&avc->lock);
1990
1991             osi_FlushText(avc);
1992             /*
1993              * Call osi_FlushPages in open, read/write, and map, since it
1994              * is too hard here to figure out if we should lock the
1995              * pvnLock.
1996              */
1997             if (setLocks && !slowPass)
1998                 ObtainReadLock(&avc->lock);
1999             else
2000                 ObtainWriteLock(&avc->lock, 66);
2001             ObtainWriteLock(&tdc->lock, 610);
2002         }
2003
2004         /*
2005          * Locks held:
2006          * avc->lock(R) if setLocks && !slowPass
2007          * avc->lock(W) if !setLocks || slowPass
2008          * tdc->lock(W)
2009          */
2010
2011         /* Watch for standard race condition around osi_FlushText */
2012         if (hsame(avc->m.DataVersion, tdc->f.versionNo)) {
2013             updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2014             afs_stats_cmperf.dcacheHits++;      
2015             ConvertWToSLock(&tdc->lock);
2016             goto done;
2017         }
2018
2019         /* Sleep here when cache needs to be drained. */
2020         if (setLocks && !slowPass &&
2021             (afs_blocksUsed > (CM_WAITFORDRAINPCT*afs_cacheBlocks)/100)) {
2022             /* Make sure truncate daemon is running */
2023             afs_MaybeWakeupTruncateDaemon();
2024             ObtainWriteLock(&tdc->tlock, 614);
2025             tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2026             ReleaseWriteLock(&tdc->tlock);
2027             ReleaseWriteLock(&tdc->lock);
2028             ReleaseReadLock(&avc->lock);
2029             while ((afs_blocksUsed-afs_blocksDiscarded) >
2030                    (CM_WAITFORDRAINPCT*afs_cacheBlocks)/100) {
2031                 afs_WaitForCacheDrain = 1;
2032                 afs_osi_Sleep(&afs_WaitForCacheDrain);
2033             }
2034             afs_MaybeFreeDiscardedDCache();
2035             /* need to check if someone else got the chunk first. */
2036             goto RetryGetDCache;
2037         }
2038
2039         /* Do not fetch data beyond truncPos. */
2040         maxGoodLength = avc->m.Length;
2041         if (avc->truncPos < maxGoodLength) maxGoodLength = avc->truncPos;
2042         Position = AFS_CHUNKBASE(abyte);
2043         if (vType(avc) == VDIR) {
2044             size = avc->m.Length;
2045             if (size > tdc->f.chunkBytes) {
2046                 /* pre-reserve space for file */
2047                 afs_AdjustSize(tdc, size);
2048             }
2049             size = 999999999;       /* max size for transfer */
2050         }
2051         else {
2052             size = AFS_CHUNKSIZE(abyte);        /* expected max size */
2053             /* don't read past end of good data on server */
2054             if (Position + size > maxGoodLength)
2055                 size = maxGoodLength - Position;
2056             if (size < 0) size = 0; /* Handle random races */
2057             if (size > tdc->f.chunkBytes) {
2058                 /* pre-reserve space for file */
2059                 afs_AdjustSize(tdc, size);      /* changes chunkBytes */
2060                 /* max size for transfer still in size */
2061             }
2062         }
2063         if (afs_mariner && !tdc->f.chunk) 
2064             afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter );*/
2065         /*
2066          * Right now, we only have one tool, and it's a hammer.  So, we
2067          * fetch the whole file.
2068          */
2069         DZap(&tdc->f.inode);    /* pages in cache may be old */
2070 #ifdef  IHINT
2071         if (file = tdc->ihint) {
2072           if (tdc->f.inode == file->inum ) 
2073             usedihint++;
2074           else {
2075             tdc->ihint = 0;
2076             afs_UFSClose(file);
2077             file = 0;
2078             nihints--;
2079             file = osi_UFSOpen(tdc->f.inode);
2080           }
2081         }
2082         else
2083 #endif /* IHINT */
2084         file = afs_CFileOpen(tdc->f.inode);
2085         afs_RemoveVCB(&avc->fid);
2086         tdc->f.states |= DWriting;
2087         tdc->dflags |= DFFetching;
2088         tdc->validPos = Position;       /*  which is AFS_CHUNKBASE(abyte) */
2089         if (tdc->mflags & DFFetchReq) {
2090             tdc->mflags &= ~DFFetchReq;
2091             afs_osi_Wakeup(&tdc->validPos);
2092         }
2093         tsmall = (struct tlocal1 *) osi_AllocLargeSpace(sizeof(struct tlocal1));
2094         setVcacheStatus = 0;
2095 #ifndef AFS_NOSTATS
2096         /*
2097          * Remember if we are doing the reading from a replicated volume,
2098          * and how many times we've zipped around the fetch/analyze loop.
2099          */
2100         fromReplica = (avc->states & CRO) ? 1 : 0;
2101         numFetchLoops = 0;
2102         accP = &(afs_stats_cmfullperf.accessinf);
2103         if (fromReplica)
2104             (accP->replicatedRefs)++;
2105         else
2106             (accP->unreplicatedRefs)++;
2107 #endif /* AFS_NOSTATS */
2108         /* this is a cache miss */
2109         afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2110                         ICL_TYPE_FID, &(avc->fid),
2111                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(Position), 
2112                         ICL_TYPE_INT32, size);
2113
2114         if (size) afs_stats_cmperf.dcacheMisses++; 
2115         code = 0;
2116         /*
2117          * Dynamic root support:  fetch data from local memory.
2118          */
2119         if (afs_IsDynroot(avc)) {
2120             char *dynrootDir;
2121             int dynrootLen;
2122
2123             afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2124
2125             dynrootDir += Position;
2126             dynrootLen -= Position;
2127             if (size > dynrootLen)
2128                 size = dynrootLen;
2129             if (size < 0) size = 0;
2130             code = afs_osi_Write(file, -1, dynrootDir, size);
2131             afs_PutDynroot();
2132
2133             if (code == size)
2134                 code = 0;
2135             else
2136                 code = -1;
2137
2138             tdc->validPos = Position + size;
2139             afs_CFileTruncate(file, size); /* prune it */
2140         } else
2141         /*
2142          * Not a dynamic vnode:  do the real fetch.
2143          */
2144         if (size) do {
2145             /*
2146              * Locks held:
2147              * avc->lock(R) if setLocks && !slowPass
2148              * avc->lock(W) if !setLocks || slowPass
2149              * tdc->lock(W)
2150              */
2151
2152             tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
2153             if (tc) {
2154                 afs_int32 length_hi, length, bytes;
2155 #ifndef AFS_NOSTATS
2156                 numFetchLoops++;
2157                 if (fromReplica)
2158                     (accP->numReplicasAccessed)++;
2159                 
2160 #endif /* AFS_NOSTATS */
2161                 if (!setLocks || slowPass) {
2162                     avc->callback = tc->srvr->server;
2163                 } else {
2164                     newCallback = tc->srvr->server;
2165                     setNewCallback = 1;
2166                 }
2167                 i = osi_Time();
2168                 RX_AFS_GUNLOCK();
2169                 tcall = rx_NewCall(tc->id);
2170                 RX_AFS_GLOCK();
2171
2172                 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
2173 #ifdef AFS_64BIT_CLIENT
2174                 length_hi = code = 0;
2175                 if (!afs_serverHasNo64Bit(tc)) {
2176                     tsize = size;
2177                     RX_AFS_GUNLOCK();
2178                     code = StartRXAFS_FetchData64(tcall,
2179                                             (struct AFSFid *) &avc->fid.Fid,
2180                                             Position, tsize);
2181                     if (code != 0) {
2182                         RX_AFS_GLOCK();
2183                         afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2184                                    ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code);
2185                     } else {
2186                         bytes = rx_Read(tcall, (char *)&length_hi, sizeof(afs_int32));
2187                         RX_AFS_GLOCK();
2188                         afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2189                                    ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code);
2190                         if (bytes == sizeof(afs_int32)) {
2191                             length_hi = ntohl(length_hi);
2192                         } else {
2193                             length_hi = 0;
2194                             code = rx_Error(tcall); 
2195                             RX_AFS_GUNLOCK();
2196                             code1 = rx_EndCall(tcall, code);
2197                             RX_AFS_GLOCK();
2198                             tcall = (struct rx_call *) 0;
2199                         }
2200                     }
2201                 }
2202                 if (code == RXGEN_OPCODE || afs_serverHasNo64Bit(tc)) {
2203                     if (Position > 0x7FFFFFFF) {
2204                         code = EFBIG;
2205                     } else {
2206                         afs_int32 pos;
2207                         pos = Position;
2208                         RX_AFS_GUNLOCK();
2209                         if (!tcall)
2210                             tcall = rx_NewCall(tc->id);
2211                         code = StartRXAFS_FetchData(tcall,
2212                                     (struct AFSFid *) &avc->fid.Fid, pos, size);
2213                         RX_AFS_GLOCK();
2214                     }
2215                     afs_serverSetNo64Bit(tc);
2216                 }
2217                 if (code == 0) {                
2218                     RX_AFS_GUNLOCK();
2219                     bytes = rx_Read(tcall, (char *)&length, sizeof(afs_int32));
2220                     RX_AFS_GLOCK();
2221                     if (bytes == sizeof(afs_int32)) {
2222                         length = ntohl(length);
2223                     } else {
2224                         code = rx_Error(tcall); 
2225                     }
2226                 }
2227                 FillInt64(lengthFound, length_hi, length);
2228                 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64LENG,
2229                         ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
2230                         ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(lengthFound));
2231 #else /* AFS_64BIT_CLIENT */
2232                 RX_AFS_GUNLOCK();
2233                 code = StartRXAFS_FetchData(tcall,
2234                                             (struct AFSFid *) &avc->fid.Fid,
2235                                             Position, size);
2236                 RX_AFS_GLOCK();
2237                 if (code == 0) {                
2238                     RX_AFS_GUNLOCK();
2239                     bytes = rx_Read(tcall, (char *)&length, sizeof(afs_int32));
2240                     RX_AFS_GLOCK();
2241                     if (bytes == sizeof(afs_int32)) {
2242                         length = ntohl(length);
2243                     } else {
2244                         code = rx_Error(tcall); 
2245                     }
2246                 }
2247 #endif /* AFS_64BIT_CLIENT */
2248                 if (code == 0) {
2249
2250 #ifndef AFS_NOSTATS
2251                     xferP = &(afs_stats_cmfullperf.rpc.fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
2252                     osi_GetuTime(&xferStartTime);
2253
2254                     code = afs_CacheFetchProc(tcall, file, 
2255                                 (afs_size_t) Position, tdc, avc,
2256                                 &bytesToXfer, &bytesXferred, length);
2257
2258                     osi_GetuTime(&xferStopTime);
2259                     (xferP->numXfers)++;
2260                     if (!code) {
2261                         (xferP->numSuccesses)++;
2262                         afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_FETCHDATA] += bytesXferred;
2263                         (xferP->sumBytes) += (afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
2264                         afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
2265                         if (bytesXferred < xferP->minBytes)
2266                            xferP->minBytes = bytesXferred;
2267                         if (bytesXferred > xferP->maxBytes)
2268                            xferP->maxBytes = bytesXferred;
2269                     
2270                         /*
2271                          * Tally the size of the object.  Note: we tally the actual size,
2272                          * NOT the number of bytes that made it out over the wire.
2273                          */
2274                         if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
2275                             (xferP->count[0])++;
2276                         else
2277                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET1)
2278                                 (xferP->count[1])++;
2279                         else
2280                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET2)
2281                                 (xferP->count[2])++;
2282                         else
2283                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET3)
2284                                 (xferP->count[3])++;
2285                         else
2286                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET4)
2287                                 (xferP->count[4])++;
2288                         else
2289                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET5)
2290                                 (xferP->count[5])++;
2291                         else
2292                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET6)
2293                                 (xferP->count[6])++;
2294                         else
2295                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET7)
2296                                 (xferP->count[7])++;
2297                         else
2298                             (xferP->count[8])++;
2299
2300                         afs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
2301                         afs_stats_AddTo((xferP->sumTime), elapsedTime);
2302                         afs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
2303                         if (afs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
2304                            afs_stats_TimeAssign((xferP->minTime), elapsedTime);
2305                         }
2306                         if (afs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
2307                            afs_stats_TimeAssign((xferP->maxTime), elapsedTime);
2308                         }
2309                     }
2310 #else
2311                     code = afs_CacheFetchProc(tcall, file, Position, tdc, avc, 0, 0, length);
2312 #endif /* AFS_NOSTATS */
2313                 }
2314                 if (code == 0) {
2315                     RX_AFS_GUNLOCK();
2316                     code = EndRXAFS_FetchData(tcall,
2317                                               &tsmall->OutStatus,
2318                                               &tsmall->CallBack,
2319                                               &tsmall->tsync);
2320                     RX_AFS_GLOCK();
2321                 }
2322                 XSTATS_END_TIME;
2323                 RX_AFS_GUNLOCK();
2324                 if (tcall)
2325                     code1 = rx_EndCall(tcall, code);
2326                 RX_AFS_GLOCK();
2327             }
2328             else {
2329                 code = -1;
2330             }
2331             if ( !code && code1 )
2332                 code = code1;
2333
2334             if (code == 0) {
2335                 /* callback could have been broken (or expired) in a race here, 
2336                  * but we return the data anyway.  It's as good as we knew about
2337                  * when we started. */
2338                 /* 
2339                  * validPos is updated by CacheFetchProc, and can only be 
2340                  * modifed under a dcache write lock, which we've blocked out 
2341                  */
2342                 size = tdc->validPos - Position;  /* actual segment size */
2343                 if (size < 0) size = 0;
2344                 afs_CFileTruncate(file, size); /* prune it */
2345             }
2346             else {
2347                 if (!setLocks || slowPass) {
2348                     ObtainWriteLock(&afs_xcbhash, 453);
2349                     afs_DequeueCallback(avc);
2350                     avc->states &= ~(CStatd | CUnique);   
2351                     avc->callback = (struct server *)0;
2352                     ReleaseWriteLock(&afs_xcbhash);
2353                     if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2354                         osi_dnlc_purgedp(avc);
2355                 } else {
2356                     /* Something lost.  Forget about performance, and go
2357                      * back with a vcache write lock.
2358                      */
2359                     afs_CFileTruncate(file, 0);
2360                     afs_AdjustSize(tdc, 0);
2361                     afs_CFileClose(file);
2362                     osi_FreeLargeSpace(tsmall);
2363                     tsmall = 0;
2364                     ReleaseWriteLock(&tdc->lock);
2365                     afs_PutDCache(tdc);
2366                     tdc = 0;
2367                     ReleaseReadLock(&avc->lock);
2368                     slowPass = 1;
2369                     goto RetryGetDCache;
2370                 }
2371             }
2372
2373         } while
2374             (afs_Analyze(tc, code, &avc->fid, areq,
2375                          AFS_STATS_FS_RPCIDX_FETCHDATA,
2376                          SHARED_LOCK, (struct cell *)0));
2377
2378         /*
2379          * Locks held:
2380          * avc->lock(R) if setLocks && !slowPass
2381          * avc->lock(W) if !setLocks || slowPass
2382          * tdc->lock(W)
2383          */
2384
2385 #ifndef AFS_NOSTATS
2386         /*
2387          * In the case of replicated access, jot down info on the number of
2388          * attempts it took before we got through or gave up.
2389          */
2390         if (fromReplica) {
2391             if (numFetchLoops <= 1)
2392                 (accP->refFirstReplicaOK)++;
2393             if (numFetchLoops > accP->maxReplicasPerRef)
2394                 accP->maxReplicasPerRef = numFetchLoops;
2395         }
2396 #endif /* AFS_NOSTATS */
2397
2398         tdc->dflags &= ~DFFetching;
2399         afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAIT,
2400                    ICL_TYPE_STRING, __FILE__,
2401                    ICL_TYPE_INT32, __LINE__,
2402                    ICL_TYPE_POINTER, tdc,
2403                    ICL_TYPE_INT32, tdc->dflags);
2404         afs_osi_Wakeup(&tdc->validPos);
2405         if (avc->execsOrWriters == 0) tdc->f.states &= ~DWriting;
2406
2407         /* now, if code != 0, we have an error and should punt.
2408          * note that we have the vcache write lock, either because
2409          * !setLocks or slowPass.
2410          */
2411         if (code) {
2412             afs_CFileTruncate(file, 0);
2413             afs_AdjustSize(tdc, 0);
2414             afs_CFileClose(file);
2415             ZapDCE(tdc);        /* sets DFEntryMod */
2416             if (vType(avc) == VDIR) {
2417                 DZap(&tdc->f.inode);
2418             }
2419             ReleaseWriteLock(&tdc->lock);
2420             afs_PutDCache(tdc);
2421             ObtainWriteLock(&afs_xcbhash, 454);
2422             afs_DequeueCallback(avc);
2423             avc->states &= ~( CStatd | CUnique );
2424             ReleaseWriteLock(&afs_xcbhash);
2425             if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2426                 osi_dnlc_purgedp(avc);
2427             /*
2428              * Locks held:
2429              * avc->lock(W); assert(!setLocks || slowPass)
2430              */
2431             osi_Assert(!setLocks || slowPass);
2432             tdc = (struct dcache *) 0;
2433             goto done;
2434         }
2435
2436         /* otherwise we copy in the just-fetched info */
2437         afs_CFileClose(file);
2438         afs_AdjustSize(tdc, size);  /* new size */
2439         /*
2440          * Copy appropriate fields into vcache.  Status is
2441          * copied later where we selectively acquire the
2442          * vcache write lock.
2443          */
2444         if (slowPass)
2445             afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2446         else
2447             setVcacheStatus = 1;
2448         hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh, tsmall->OutStatus.DataVersion);
2449         tdc->dflags |= DFEntryMod;
2450         afs_indexFlags[tdc->index] |= IFEverUsed;
2451         ConvertWToSLock(&tdc->lock);
2452     } /*Data version numbers don't match*/
2453     else {
2454         /*
2455          * Data version numbers match.
2456          */
2457         afs_stats_cmperf.dcacheHits++;
2458     }  /*Data version numbers match*/
2459
2460     updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2461 done:
2462     /*
2463      * Locks held:
2464      * avc->lock(R) if setLocks && !slowPass
2465      * avc->lock(W) if !setLocks || slowPass
2466      * tdc->lock(S) if tdc
2467      */
2468
2469     /*
2470      * See if this was a reference to a file in the local cell.
2471      */
2472     if (avc->fid.Cell == LOCALCELL)
2473         afs_stats_cmperf.dlocalAccesses++;
2474     else
2475         afs_stats_cmperf.dremoteAccesses++;
2476
2477     /* Fix up LRU info */
2478
2479     if (tdc) {
2480         MObtainWriteLock(&afs_xdcache, 602);
2481         hset(afs_indexTimes[tdc->index], afs_indexCounter);
2482         hadd32(afs_indexCounter, 1);
2483         MReleaseWriteLock(&afs_xdcache);
2484
2485         /* return the data */
2486         if (vType(avc) == VDIR)
2487             *aoffset = abyte;
2488         else
2489             *aoffset = AFS_CHUNKOFFSET(abyte);
2490         *alen = *aoffset + tdc->f.chunkBytes - abyte;
2491         ReleaseSharedLock(&tdc->lock);
2492     }
2493
2494     /*
2495      * Locks held:
2496      * avc->lock(R) if setLocks && !slowPass
2497      * avc->lock(W) if !setLocks || slowPass
2498      */
2499
2500     /* Fix up the callback and status values in the vcache */
2501     doVcacheUpdate = 0;
2502     if (setLocks && !slowPass) {
2503         /* DCLOCKXXX
2504          *
2505          * This is our dirty little secret to parallel fetches.
2506          * We don't write-lock the vcache while doing the fetch,
2507          * but potentially we'll need to update the vcache after
2508          * the fetch is done.
2509          *
2510          * Drop the read lock and try to re-obtain the write
2511          * lock.  If the vcache still has the same DV, it's
2512          * ok to go ahead and install the new data.
2513          */
2514         afs_hyper_t currentDV, statusDV;
2515
2516         hset(currentDV, avc->m.DataVersion);
2517
2518         if (setNewCallback && avc->callback != newCallback)
2519             doVcacheUpdate = 1;
2520
2521         if (tsmall) {
2522             hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2523                              tsmall->OutStatus.DataVersion);
2524
2525             if (setVcacheStatus && avc->m.Length != tsmall->OutStatus.Length)
2526                 doVcacheUpdate = 1;
2527             if (setVcacheStatus && !hsame(currentDV, statusDV))
2528                 doVcacheUpdate = 1;
2529         }
2530
2531         ReleaseReadLock(&avc->lock);
2532
2533         if (doVcacheUpdate) {
2534             ObtainWriteLock(&avc->lock, 615);
2535             if (!hsame(avc->m.DataVersion, currentDV)) {
2536                 /* We lose.  Someone will beat us to it. */
2537                 doVcacheUpdate = 0;
2538                 ReleaseWriteLock(&avc->lock);
2539             }
2540         }
2541     }
2542
2543     /* With slow pass, we've already done all the updates */
2544     if (slowPass) {
2545         ReleaseWriteLock(&avc->lock);
2546     }
2547
2548     /* Check if we need to perform any last-minute fixes with a write-lock */
2549     if (!setLocks || doVcacheUpdate) {
2550         if (setNewCallback) avc->callback = newCallback;
2551         if (tsmall) afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2552         if (setLocks) ReleaseWriteLock(&avc->lock);
2553     }
2554
2555     if (tsmall) osi_FreeLargeSpace(tsmall);
2556
2557     return tdc;
2558 } /*afs_GetDCache*/
2559
2560
2561 /*
2562  * afs_WriteThroughDSlots
2563  *
2564  * Description:
2565  *      Sweep through the dcache slots and write out any modified
2566  *      in-memory data back on to our caching store.
2567  *
2568  * Parameters:
2569  *      None.
2570  *
2571  * Environment:
2572  *      The afs_xdcache is write-locked through this whole affair.
2573  */
2574 void
2575 afs_WriteThroughDSlots()
2576
2577 { /*afs_WriteThroughDSlots*/
2578
2579     register struct dcache *tdc;
2580     register afs_int32 i, touchedit=0;
2581     struct dcache **ents;
2582     int entmax, entcount;
2583
2584     AFS_STATCNT(afs_WriteThroughDSlots);
2585
2586     /*
2587      * Because of lock ordering, we can't grab dcache locks while
2588      * holding afs_xdcache.  So we enter xdcache, get a reference
2589      * for every dcache entry, and exit xdcache.
2590      */
2591     MObtainWriteLock(&afs_xdcache,283);
2592     entmax = afs_cacheFiles;
2593     ents = afs_osi_Alloc(entmax * sizeof(struct dcache *));
2594     entcount = 0;
2595     for(i = 0; i < afs_cacheFiles; i++) {
2596         tdc = afs_indexTable[i];
2597
2598         /* Grab tlock in case the existing refcount isn't zero */
2599         if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2600             ObtainWriteLock(&tdc->tlock, 623);
2601             tdc->refCount++;
2602             ReleaseWriteLock(&tdc->tlock);
2603
2604             ents[entcount++] = tdc;
2605         }
2606     }
2607     MReleaseWriteLock(&afs_xdcache);
2608
2609     /*
2610      * Now, for each dcache entry we found, check if it's dirty.
2611      * If so, get write-lock, get afs_xdcache, which protects
2612      * afs_cacheInodep, and flush it.  Don't forget to put back
2613      * the refcounts.
2614      */
2615     for (i = 0; i < entcount; i++) {
2616         tdc = ents[i];
2617
2618         if (tdc->dflags & DFEntryMod) {
2619             int wrLock;
2620
2621             wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2622
2623             /* Now that we have the write lock, double-check */
2624             if (wrLock && (tdc->dflags & DFEntryMod)) {
2625                 tdc->dflags &= ~DFEntryMod;
2626                 MObtainWriteLock(&afs_xdcache, 620);
2627                 afs_WriteDCache(tdc, 1);
2628                 MReleaseWriteLock(&afs_xdcache);
2629                 touchedit = 1;
2630             }
2631             if (wrLock) ReleaseWriteLock(&tdc->lock);
2632         }
2633
2634         afs_PutDCache(tdc);
2635     }
2636     afs_osi_Free(ents, entmax * sizeof(struct dcache *));
2637
2638     MObtainWriteLock(&afs_xdcache, 617);
2639     if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2640         /* Touch the file to make sure that the mtime on the file is kept
2641          * up-to-date to avoid losing cached files on cold starts because
2642          * their mtime seems old...
2643          */
2644         struct afs_fheader theader;
2645
2646         theader.magic = AFS_FHMAGIC;
2647         theader.firstCSize = AFS_FIRSTCSIZE;
2648         theader.otherCSize = AFS_OTHERCSIZE;
2649         theader.version = AFS_CI_VERSION;
2650         afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2651     }
2652     MReleaseWriteLock(&afs_xdcache);
2653
2654 } /*afs_WriteThroughDSlots*/
2655
2656 /*
2657  * afs_MemGetDSlot
2658  *
2659  * Description:
2660  *      Return a pointer to an freshly initialized dcache entry using
2661  *      a memory-based cache.  The tlock will be read-locked.
2662  *
2663  * Parameters:
2664  *      aslot : Dcache slot to look at.
2665  *      tmpdc : Ptr to dcache entry.
2666  *
2667  * Environment:
2668  *      Must be called with afs_xdcache write-locked.
2669  */
2670
2671 struct dcache *afs_MemGetDSlot(aslot, tmpdc)
2672      register afs_int32 aslot;
2673      register struct dcache *tmpdc;
2674
2675 { /*afs_MemGetDSlot*/
2676
2677     register afs_int32 code;
2678     register struct dcache *tdc;
2679     register char *tfile;
2680     int existing = 0;
2681
2682     AFS_STATCNT(afs_MemGetDSlot);
2683     if (CheckLock(&afs_xdcache) != -1) osi_Panic("getdslot nolock");
2684     if (aslot < 0 || aslot >= afs_cacheFiles) osi_Panic("getdslot slot");
2685     tdc = afs_indexTable[aslot];
2686     if (tdc) {
2687         QRemove(&tdc->lruq);        /* move to queue head */
2688         QAdd(&afs_DLRU, &tdc->lruq);
2689         /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2690         ObtainWriteLock(&tdc->tlock, 624);
2691         tdc->refCount++;
2692         ConvertWToRLock(&tdc->tlock);
2693         return tdc;
2694     }
2695     if (tmpdc == (struct dcache *)0) {
2696         if (!afs_freeDSList) afs_GetDownDSlot(4); 
2697         if (!afs_freeDSList) {
2698             /* none free, making one is better than a panic */
2699             afs_stats_cmperf.dcacheXAllocs++;   /* count in case we have a leak */
2700             tdc = (struct dcache *) afs_osi_Alloc(sizeof (struct dcache));
2701 #ifdef  AFS_AIX32_ENV
2702             pin((char *)tdc, sizeof(struct dcache));    /* XXX */
2703 #endif
2704         } else {
2705             tdc = afs_freeDSList;
2706             afs_freeDSList = (struct dcache *) tdc->lruq.next;
2707             existing = 1;
2708         }
2709         tdc->dflags = 0;        /* up-to-date, not in free q */
2710         tdc->mflags = 0;
2711         QAdd(&afs_DLRU, &tdc->lruq);
2712         if (tdc->lruq.prev == &tdc->lruq) osi_Panic("lruq 3");
2713     }
2714     else {
2715         tdc = tmpdc;
2716         tdc->f.states = 0;
2717     }
2718     
2719     /* initialize entry */
2720     tdc->f.fid.Cell = 0;
2721     tdc->f.fid.Fid.Volume = 0;
2722     tdc->f.chunk = -1;
2723     hones(tdc->f.versionNo);
2724     tdc->f.inode = aslot;
2725     tdc->dflags |= DFEntryMod;
2726     tdc->refCount = 1;
2727     tdc->index = aslot;
2728     afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2729
2730     if (existing) {
2731         osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2732         osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2733         osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2734     }
2735
2736     RWLOCK_INIT(&tdc->lock, "dcache lock");
2737     RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2738     RWLOCK_INIT(&tdc->mflock, "dcache flock");
2739     ObtainReadLock(&tdc->tlock);
2740     
2741     if (tmpdc == (struct dcache *)0)
2742         afs_indexTable[aslot] = tdc;
2743     return tdc;
2744
2745 } /*afs_MemGetDSlot*/
2746
2747 unsigned int last_error = 0, lasterrtime = 0;
2748
2749 /*
2750  * afs_UFSGetDSlot
2751  *
2752  * Description:
2753  *      Return a pointer to an freshly initialized dcache entry using
2754  *      a UFS-based disk cache.  The dcache tlock will be read-locked.
2755  *
2756  * Parameters:
2757  *      aslot : Dcache slot to look at.
2758  *      tmpdc : Ptr to dcache entry.
2759  *
2760  * Environment:
2761  *      afs_xdcache lock write-locked.
2762  */
2763 struct dcache *afs_UFSGetDSlot(aslot, tmpdc)
2764     register afs_int32 aslot;
2765     register struct dcache *tmpdc;
2766
2767 { /*afs_UFSGetDSlot*/
2768
2769     register afs_int32 code;
2770     register struct dcache *tdc;
2771     int existing = 0;
2772
2773     AFS_STATCNT(afs_UFSGetDSlot);
2774     if (CheckLock(&afs_xdcache) != -1) osi_Panic("getdslot nolock");
2775     if (aslot < 0 || aslot >= afs_cacheFiles) osi_Panic("getdslot slot");
2776     tdc = afs_indexTable[aslot];
2777     if (tdc) {
2778         QRemove(&tdc->lruq);        /* move to queue head */
2779         QAdd(&afs_DLRU, &tdc->lruq);
2780         /* Grab tlock in case refCount != 0 */
2781         ObtainWriteLock(&tdc->tlock, 625);
2782         tdc->refCount++;
2783         ConvertWToRLock(&tdc->tlock);
2784         return tdc;
2785     }
2786     /* otherwise we should read it in from the cache file */
2787     /*
2788      * If we weren't passed an in-memory region to place the file info,
2789      * we have to allocate one.
2790      */
2791     if (tmpdc == (struct dcache *)0) {
2792         if (!afs_freeDSList) afs_GetDownDSlot(4);
2793         if (!afs_freeDSList) {
2794             /* none free, making one is better than a panic */
2795             afs_stats_cmperf.dcacheXAllocs++;   /* count in case we have a leak */
2796             tdc = (struct dcache *) afs_osi_Alloc(sizeof (struct dcache));
2797 #ifdef  AFS_AIX32_ENV
2798             pin((char *)tdc, sizeof(struct dcache));    /* XXX */
2799 #endif
2800         } else {
2801             tdc = afs_freeDSList;
2802             afs_freeDSList = (struct dcache *) tdc->lruq.next;
2803             existing = 1;
2804         }
2805         tdc->dflags = 0;        /* up-to-date, not in free q */
2806         tdc->mflags = 0;
2807         QAdd(&afs_DLRU, &tdc->lruq);
2808         if (tdc->lruq.prev == &tdc->lruq) osi_Panic("lruq 3");
2809     }
2810     else {
2811         tdc = tmpdc;
2812         tdc->f.states = 0;
2813         tdc->ihint = 0;
2814     }
2815
2816     /*
2817       * Seek to the aslot'th entry and read it in.
2818       */
2819     code = afs_osi_Read(afs_cacheInodep, sizeof(struct fcache) * aslot + sizeof(struct afs_fheader),
2820                     (char *)(&tdc->f), sizeof(struct fcache));
2821     if (code != sizeof(struct fcache)) {
2822         tdc->f.fid.Cell = 0;
2823         tdc->f.fid.Fid.Volume = 0;
2824         tdc->f.chunk = -1;
2825         hones(tdc->f.versionNo);
2826         tdc->dflags |= DFEntryMod;
2827 #if !defined(AFS_SUN5_ENV) && !defined(AFS_OSF_ENV) && !defined(AFS_SGI64_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_FBSD_ENV)
2828         last_error = getuerror();
2829 #endif
2830         lasterrtime = osi_Time();
2831         afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2832     }
2833     tdc->refCount = 1;
2834     tdc->index = aslot;
2835
2836     if (existing) {
2837         osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2838         osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2839         osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2840     }
2841
2842     RWLOCK_INIT(&tdc->lock, "dcache lock");
2843     RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2844     RWLOCK_INIT(&tdc->mflock, "dcache flock");
2845     ObtainReadLock(&tdc->tlock);
2846
2847     /*
2848      * If we didn't read into a temporary dcache region, update the
2849      * slot pointer table.
2850      */
2851     if (tmpdc == (struct dcache *)0)
2852         afs_indexTable[aslot] = tdc;
2853     return tdc;
2854
2855 }  /*afs_UFSGetDSlot*/
2856
2857
2858
2859 /*
2860  * afs_WriteDCache
2861  *
2862  * Description:
2863  *      write a particular dcache entry back to its home in the
2864  *      CacheInfo file.
2865  *
2866  * Parameters:
2867  *      adc   : Pointer to the dcache entry to write.
2868  *      atime : If true, set the modtime on the file to the current time.
2869  *
2870  * Environment:
2871  *      Must be called with the afs_xdcache lock at least read-locked,
2872  *      and dcache entry at least read-locked.
2873  *      The reference count is not changed.
2874  */
2875
2876 afs_WriteDCache(adc, atime)
2877     int atime;
2878     register struct dcache *adc;
2879
2880 { /*afs_WriteDCache*/
2881
2882     register struct osi_file *tfile;
2883     register afs_int32 code;
2884
2885     if (cacheDiskType == AFS_FCACHE_TYPE_MEM) return 0;
2886     AFS_STATCNT(afs_WriteDCache);
2887     if (atime)
2888         adc->f.modTime = osi_Time();
2889     /*
2890      * Seek to the right dcache slot and write the in-memory image out to disk.
2891      */
2892     code = afs_osi_Write(afs_cacheInodep, sizeof(struct fcache) * adc->index + sizeof(struct afs_fheader), 
2893                      (char *)(&adc->f), sizeof(struct fcache));
2894     if (code != sizeof(struct fcache)) return EIO;
2895     return 0;
2896
2897 } /*afs_WriteDCache*/
2898
2899
2900
2901 /*
2902  * afs_wakeup
2903  *
2904  * Description:
2905  *      Wake up users of a particular file waiting for stores to take
2906  *      place.
2907  *
2908  * Parameters:
2909  *      avc : Ptr to related vcache entry.
2910  *
2911  * Environment:
2912  *      Nothing interesting.
2913  */
2914
2915 afs_wakeup(avc)
2916     register struct vcache *avc;
2917
2918 { /*afs_wakeup*/
2919
2920     register int i;
2921     register struct brequest *tb;
2922     tb = afs_brs;
2923     AFS_STATCNT(afs_wakeup);
2924     for (i = 0; i < NBRS; i++, tb++) {
2925         /* if request is valid and for this file, we've found it */
2926         if (tb->refCount > 0 && avc == tb->vnode) {
2927
2928             /*
2929              * If CSafeStore is on, then we don't awaken the guy
2930              * waiting for the store until the whole store has finished.
2931              * Otherwise, we do it now.  Note that if CSafeStore is on,
2932              * the BStore routine actually wakes up the user, instead
2933              * of us.
2934              * I think this is redundant now because this sort of thing
2935              * is already being handled by the higher-level code.
2936              */
2937             if ((avc->states & CSafeStore) == 0) {
2938                 tb->code = 0;
2939                 tb->flags |= BUVALID;
2940                 if (tb->flags & BUWAIT) {
2941                     tb->flags &= ~BUWAIT;
2942                     afs_osi_Wakeup(tb);
2943                 }
2944             }
2945             break;
2946         }
2947     }
2948     return 0;
2949
2950 } /*afs_wakeup*/
2951
2952
2953 /*
2954  * afs_InitCacheFile
2955  *
2956  * Description:
2957  *      Given a file name and inode, set up that file to be an
2958  *      active member in the AFS cache.  This also involves checking
2959  *      the usability of its data.
2960  *
2961  * Parameters:
2962  *      afile  : Name of the cache file to initialize.
2963  *      ainode : Inode of the file.
2964  *
2965  * Environment:
2966  *      This function is called only during initialization.
2967  */
2968
2969 int afs_InitCacheFile(afile, ainode)
2970     ino_t ainode;
2971     char *afile;
2972
2973 { /*afs_InitCacheFile*/
2974
2975     register afs_int32 code;
2976 #if defined(AFS_LINUX22_ENV)
2977     struct dentry *filevp;
2978 #else
2979     struct vnode *filevp;
2980 #endif
2981     afs_int32 index;
2982     int fileIsBad;
2983     struct osi_file *tfile;
2984     struct osi_stat tstat;
2985     register struct dcache *tdc;
2986
2987     AFS_STATCNT(afs_InitCacheFile);
2988     index = afs_stats_cmperf.cacheNumEntries;
2989     if (index >= afs_cacheFiles) return EINVAL;
2990
2991     MObtainWriteLock(&afs_xdcache,282);
2992     tdc = afs_GetDSlot(index, (struct dcache *)0);
2993     ReleaseReadLock(&tdc->tlock);
2994     MReleaseWriteLock(&afs_xdcache);
2995
2996     ObtainWriteLock(&tdc->lock, 621);
2997     MObtainWriteLock(&afs_xdcache, 622);
2998     if (afile) {
2999         code = gop_lookupname(afile,
3000                               AFS_UIOSYS,
3001                               0,
3002                               (struct vnode **) 0,
3003                               &filevp);
3004         if (code) {
3005             ReleaseWriteLock(&afs_xdcache);
3006             ReleaseWriteLock(&tdc->lock);
3007             afs_PutDCache(tdc);
3008             return code;
3009         }
3010         /*
3011          * We have a VN_HOLD on filevp.  Get the useful info out and
3012          * return.  We make use of the fact that the cache is in the
3013          * UFS file system, and just record the inode number.
3014          */
3015 #ifdef AFS_LINUX22_ENV
3016         tdc->f.inode = VTOI(filevp->d_inode)->i_number;
3017         dput(filevp);
3018 #else
3019         tdc->f.inode = afs_vnodeToInumber(filevp);
3020 #ifdef AFS_DEC_ENV
3021         grele(filevp);
3022 #else
3023         AFS_RELE((struct vnode *)filevp);
3024 #endif
3025 #endif /* AFS_LINUX22_ENV */
3026     }
3027     else {
3028         tdc->f.inode = ainode;
3029     }
3030     fileIsBad = 0;
3031     if ((tdc->f.states & DWriting) ||
3032         tdc->f.fid.Fid.Volume == 0) fileIsBad = 1;
3033     tfile = osi_UFSOpen(tdc->f.inode);
3034     code = afs_osi_Stat(tfile, &tstat);
3035     if (code) osi_Panic("initcachefile stat");
3036
3037     /*
3038      * If file size doesn't match the cache info file, it's probably bad.
3039      */
3040     if (tdc->f.chunkBytes != tstat.size) fileIsBad = 1;
3041     tdc->f.chunkBytes = 0;
3042
3043     /*
3044      * If file changed within T (120?) seconds of cache info file, it's
3045      * probably bad.  In addition, if slot changed within last T seconds,
3046      * the cache info file may be incorrectly identified, and so slot
3047      * may be bad.
3048      */
3049     if (cacheInfoModTime < tstat.mtime + 120) fileIsBad = 1;
3050     if (cacheInfoModTime < tdc->f.modTime + 120) fileIsBad = 1;
3051     /* In case write through is behind, make sure cache items entry is
3052      * at least as new as the chunk.
3053      */
3054     if (tdc->f.modTime < tstat.mtime) fileIsBad = 1;
3055     if (fileIsBad) {
3056         tdc->f.fid.Fid.Volume = 0;  /* not in the hash table */
3057         if (tstat.size != 0)
3058             osi_UFSTruncate(tfile, 0);
3059         /* put entry in free cache slot list */
3060         afs_dvnextTbl[tdc->index] = afs_freeDCList;
3061         afs_freeDCList = index;
3062         afs_freeDCCount++;
3063         afs_indexFlags[index] |= IFFree;
3064         afs_indexUnique[index] = 0;
3065     }
3066     else {
3067         /*
3068          * We must put this entry in the appropriate hash tables.
3069          * Note that i is still set from the above DCHash call
3070          */
3071         code = DCHash(&tdc->f.fid, tdc->f.chunk);
3072         afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];        
3073         afs_dchashTbl[code] = tdc->index;
3074         code = DVHash(&tdc->f.fid);
3075         afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3076         afs_dvhashTbl[code] = tdc->index;
3077         afs_AdjustSize(tdc, tstat.size);    /* adjust to new size */
3078         if (tstat.size > 0)
3079             /* has nontrivial amt of data */
3080             afs_indexFlags[index] |= IFEverUsed;
3081         afs_stats_cmperf.cacheFilesReused++;
3082         /*
3083          * Initialize index times to file's mod times; init indexCounter
3084          * to max thereof
3085          */
3086         hset32(afs_indexTimes[index], tstat.atime);
3087         if (hgetlo(afs_indexCounter) < tstat.atime) {
3088             hset32(afs_indexCounter, tstat.atime);
3089         }
3090         afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3091     } /*File is not bad*/
3092
3093     osi_UFSClose(tfile);
3094     tdc->f.states &= ~DWriting;
3095     tdc->dflags &= ~DFEntryMod;
3096     /* don't set f.modTime; we're just cleaning up */
3097     afs_WriteDCache(tdc, 0);
3098     ReleaseWriteLock(&afs_xdcache);
3099     ReleaseWriteLock(&tdc->lock);
3100     afs_PutDCache(tdc);
3101     afs_stats_cmperf.cacheNumEntries++;
3102     return 0;
3103
3104 } /*afs_InitCacheFile*/
3105
3106
3107 /*Max # of struct dcache's resident at any time*/
3108 /*
3109  * If 'dchint' is enabled then in-memory dcache min is increased because of
3110  * crashes...
3111  */
3112 #define DDSIZE 200
3113
3114 /* 
3115  * afs_dcacheInit
3116  *
3117  * Description:
3118  *      Initialize dcache related variables.
3119  */
3120 void afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk,
3121                     int aflags)
3122 {
3123     register struct dcache *tdp;
3124     int i;
3125     int code;
3126
3127     afs_freeDCList = NULLIDX;
3128     afs_discardDCList = NULLIDX;
3129     afs_freeDCCount = 0;
3130     afs_freeDSList = (struct dcache *)0;
3131     hzero(afs_indexCounter);
3132
3133     LOCK_INIT(&afs_xdcache, "afs_xdcache");
3134    
3135     /*
3136      * Set chunk size
3137      */
3138     if (achunk) {
3139         if (achunk < 0 || achunk > 30)
3140             achunk = 13;                /* Use default */
3141         AFS_SETCHUNKSIZE(achunk);
3142     }
3143     
3144     if(!aDentries)
3145         aDentries = DDSIZE;
3146     
3147     if(aflags & AFSCALL_INIT_MEMCACHE) {
3148         /*
3149          * Use a memory cache instead of a disk cache
3150          */
3151         cacheDiskType = AFS_FCACHE_TYPE_MEM;
3152         afs_cacheType = &afs_MemCacheOps;
3153         afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3154         ablocks = afiles * (AFS_FIRSTCSIZE/1024);
3155         /* ablocks is reported in 1K blocks */
3156         code = afs_InitMemCache(afiles * AFS_FIRSTCSIZE, AFS_FIRSTCSIZE, aflags);
3157         if (code != 0) {
3158             printf("afsd: memory cache too large for available memory.\n");
3159             printf("afsd: AFS files cannot be accessed.\n\n");
3160             dcacheDisabled = 1;
3161             afiles = ablocks = 0;
3162         }
3163         else
3164             printf("Memory cache: Allocating %d dcache entries...", aDentries);
3165     } else {
3166         cacheDiskType = AFS_FCACHE_TYPE_UFS;
3167         afs_cacheType = &afs_UfsCacheOps;
3168     }
3169
3170     if (aDentries > 512) 
3171         afs_dhashsize = 2048;
3172     /* initialize hash tables */
3173     afs_dvhashTbl = (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3174     afs_dchashTbl = (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3175     for(i=0;i< afs_dhashsize;i++) {
3176         afs_dvhashTbl[i] = NULLIDX;
3177         afs_dchashTbl[i] = NULLIDX;
3178     }
3179     afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3180     afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3181     for(i=0;i< afiles;i++) {
3182         afs_dvnextTbl[i] = NULLIDX;
3183         afs_dcnextTbl[i] = NULLIDX;
3184     }
3185     
3186     /* Allocate and zero the pointer array to the dcache entries */
3187     afs_indexTable = (struct dcache **)
3188         afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3189     memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3190     afs_indexTimes = (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3191     memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3192     afs_indexUnique = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3193     memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3194     afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3195     memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
3196     
3197     /* Allocate and thread the struct dcache entries themselves */
3198     tdp = afs_Initial_freeDSList =
3199         (struct dcache *) afs_osi_Alloc(aDentries * sizeof(struct dcache));
3200     memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
3201 #ifdef  AFS_AIX32_ENV
3202     pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles);/* XXX */    
3203     pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles);  /* XXX */    
3204     pin((char *)afs_indexFlags, sizeof(char) * afiles);         /* XXX */    
3205     pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles);   /* XXX */    
3206     pin((char *)tdp, aDentries * sizeof(struct dcache));        /* XXX */    
3207     pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize);      /* XXX */    
3208     pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize);      /* XXX */    
3209     pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles);             /* XXX */    
3210     pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles);             /* XXX */    
3211 #endif
3212
3213     afs_freeDSList = &tdp[0];
3214     for(i=0; i < aDentries-1; i++) {
3215         tdp[i].lruq.next = (struct afs_q *) (&tdp[i+1]);
3216     }
3217     tdp[aDentries-1].lruq.next = (struct afs_q *) 0;
3218
3219     afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal = afs_cacheBlocks = ablocks;
3220     afs_ComputeCacheParms();    /* compute parms based on cache size */
3221
3222     afs_dcentries = aDentries;
3223     afs_blocksUsed = 0;
3224     QInit(&afs_DLRU);
3225 }
3226
3227 /*
3228  * shutdown_dcache
3229  *
3230  */
3231 void shutdown_dcache(void)
3232 {
3233     int i;
3234
3235     afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3236     afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3237     afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3238     afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3239     afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3240     afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3241     afs_osi_Free(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3242 #ifdef  AFS_AIX32_ENV
3243     unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3244     unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3245     unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3246     unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3247     unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3248     unpin((u_char *)afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3249     unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3250 #endif
3251
3252
3253     for(i=0;i< afs_dhashsize;i++) {
3254         afs_dvhashTbl[i] = NULLIDX;
3255         afs_dchashTbl[i] = NULLIDX;
3256     }
3257
3258
3259     afs_blocksUsed = afs_dcentries = 0;
3260     hzero(afs_indexCounter);
3261
3262     afs_freeDCCount =  0;
3263     afs_freeDCList = NULLIDX;
3264     afs_discardDCList = NULLIDX;
3265     afs_freeDSList = afs_Initial_freeDSList = 0;
3266
3267     LOCK_INIT(&afs_xdcache, "afs_xdcache");
3268     QInit(&afs_DLRU);
3269
3270 }