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