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