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