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