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