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