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