bypasscache-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     if (dcacheDisabled)
1851         return NULL;
1852
1853     setLocks = aflags & 1;
1854
1855     /*
1856      * Determine the chunk number and offset within the chunk corresponding
1857      * to the desired byte.
1858      */
1859     if (avc->fid.Fid.Vnode & 1) {       /* if (vType(avc) == VDIR) */
1860         chunk = 0;
1861     } else {
1862         chunk = AFS_CHUNK(abyte);
1863     }
1864
1865     /* come back to here if we waited for the cache to drain. */
1866   RetryGetDCache:
1867
1868     setNewCallback = setVcacheStatus = 0;
1869
1870     if (setLocks) {
1871         if (slowPass)
1872             ObtainWriteLock(&avc->lock, 616);
1873         else
1874             ObtainReadLock(&avc->lock);
1875     }
1876
1877     /*
1878      * Locks held:
1879      * avc->lock(R) if setLocks && !slowPass
1880      * avc->lock(W) if !setLocks || slowPass
1881      */
1882
1883     shortcut = 0;
1884
1885     /* check hints first! (might could use bcmp or some such...) */
1886     if ((tdc = avc->dchint)) {
1887         int dcLocked;
1888
1889         /*
1890          * The locking order between afs_xdcache and dcache lock matters.
1891          * The hint dcache entry could be anywhere, even on the free list.
1892          * Locking afs_xdcache ensures that noone is trying to pull dcache
1893          * entries from the free list, and thereby assuming them to be not
1894          * referenced and not locked.
1895          */
1896         MObtainReadLock(&afs_xdcache);
1897         dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1898
1899         if (dcLocked && (tdc->index != NULLIDX)
1900             && !FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk
1901             && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1902             /* got the right one.  It might not be the right version, and it 
1903              * might be fetching, but it's the right dcache entry.
1904              */
1905             /* All this code should be integrated better with what follows:
1906              * I can save a good bit more time under a write lock if I do..
1907              */
1908             ObtainWriteLock(&tdc->tlock, 603);
1909             tdc->refCount++;
1910             ReleaseWriteLock(&tdc->tlock);
1911
1912             MReleaseReadLock(&afs_xdcache);
1913             shortcut = 1;
1914
1915             if (hsame(tdc->f.versionNo, avc->m.DataVersion)
1916                 && !(tdc->dflags & DFFetching)) {
1917
1918                 afs_stats_cmperf.dcacheHits++;
1919                 MObtainWriteLock(&afs_xdcache, 559);
1920                 QRemove(&tdc->lruq);
1921                 QAdd(&afs_DLRU, &tdc->lruq);
1922                 MReleaseWriteLock(&afs_xdcache);
1923
1924                 /* Locks held:
1925                  * avc->lock(R) if setLocks && !slowPass
1926                  * avc->lock(W) if !setLocks || slowPass
1927                  * tdc->lock(S)
1928                  */
1929                 goto done;
1930             }
1931         } else {
1932             if (dcLocked)
1933                 ReleaseSharedLock(&tdc->lock);
1934             MReleaseReadLock(&afs_xdcache);
1935         }
1936
1937         if (!shortcut)
1938             tdc = 0;
1939     }
1940
1941     /* Locks held:
1942      * avc->lock(R) if setLocks && !slowPass
1943      * avc->lock(W) if !setLocks || slowPass
1944      * tdc->lock(S) if tdc
1945      */
1946
1947     if (!tdc) {                 /* If the hint wasn't the right dcache entry */
1948         /*
1949          * Hash on the [fid, chunk] and get the corresponding dcache index
1950          * after write-locking the dcache.
1951          */
1952       RetryLookup:
1953
1954         /* Locks held:
1955          * avc->lock(R) if setLocks && !slowPass
1956          * avc->lock(W) if !setLocks || slowPass
1957          */
1958
1959         i = DCHash(&avc->fid, chunk);
1960         /* check to make sure our space is fine */
1961         afs_MaybeWakeupTruncateDaemon();
1962
1963         MObtainWriteLock(&afs_xdcache, 280);
1964         us = NULLIDX;
1965         for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1966             if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1967                 tdc = afs_GetDSlot(index, NULL);
1968                 ReleaseReadLock(&tdc->tlock);
1969                 /*
1970                  * Locks held:
1971                  * avc->lock(R) if setLocks && !slowPass
1972                  * avc->lock(W) if !setLocks || slowPass
1973                  * afs_xdcache(W)
1974                  */
1975                 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1976                     /* Move it up in the beginning of the list */
1977                     if (afs_dchashTbl[i] != index) {
1978                         afs_dcnextTbl[us] = afs_dcnextTbl[index];
1979                         afs_dcnextTbl[index] = afs_dchashTbl[i];
1980                         afs_dchashTbl[i] = index;
1981                     }
1982                     MReleaseWriteLock(&afs_xdcache);
1983                     ObtainSharedLock(&tdc->lock, 606);
1984                     break;      /* leaving refCount high for caller */
1985                 }
1986                 afs_PutDCache(tdc);
1987                 tdc = 0;
1988             }
1989             us = index;
1990             index = afs_dcnextTbl[index];
1991         }
1992
1993         /*
1994          * If we didn't find the entry, we'll create one.
1995          */
1996         if (index == NULLIDX) {
1997             /*
1998              * Locks held:
1999              * avc->lock(R) if setLocks
2000              * avc->lock(W) if !setLocks
2001              * afs_xdcache(W)
2002              */
2003             afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
2004                        avc, ICL_TYPE_INT32, chunk);
2005
2006             /* Make sure there is a free dcache entry for us to use */
2007             if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
2008                 while (1) {
2009                     if (!setLocks)
2010                         avc->states |= CDCLock;
2011                     /* just need slots */
2012                     afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
2013                     if (!setLocks)
2014                         avc->states &= ~CDCLock;
2015                     if (afs_discardDCList != NULLIDX
2016                         || afs_freeDCList != NULLIDX)
2017                         break;
2018                     /* If we can't get space for 5 mins we give up and panic */
2019                     if (++downDCount > 300) {
2020 #if defined(AFS_CACHE_BYPASS)
2021                         afs_warn("GetDCache calling osi_Panic: No space in five minutes.\n downDCount: %d\n aoffset: %d alen: %d\n", downDCount, aoffset, alen);
2022 #endif
2023                         osi_Panic("getdcache");
2024                     }
2025                     MReleaseWriteLock(&afs_xdcache);
2026                     /*
2027                      * Locks held:
2028                      * avc->lock(R) if setLocks
2029                      * avc->lock(W) if !setLocks
2030                      */
2031                     afs_osi_Wait(1000, 0, 0);
2032                     goto RetryLookup;
2033                 }
2034             }
2035
2036             tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
2037
2038             /*
2039              * Now add to the two hash chains - note that i is still set
2040              * from the above DCHash call.
2041              */
2042             afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
2043             afs_dchashTbl[i] = tdc->index;
2044             i = DVHash(&avc->fid);
2045             afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
2046             afs_dvhashTbl[i] = tdc->index;
2047             tdc->dflags = DFEntryMod;
2048             tdc->mflags = 0;
2049             afs_MaybeWakeupTruncateDaemon();
2050             MReleaseWriteLock(&afs_xdcache);
2051             ConvertWToSLock(&tdc->lock);
2052         }
2053     }
2054
2055
2056     /* vcache->dcache hint failed */
2057     /*
2058      * Locks held:
2059      * avc->lock(R) if setLocks && !slowPass
2060      * avc->lock(W) if !setLocks || slowPass
2061      * tdc->lock(S)
2062      */
2063     afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
2064                ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2065                hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
2066                hgetlo(avc->m.DataVersion));
2067     /*
2068      * Here we have the entry in tdc, with its refCount incremented.
2069      * Note: we don't use the S-lock on avc; it costs concurrency when
2070      * storing a file back to the server.
2071      */
2072
2073     /*
2074      * Not a newly created file so we need to check the file's length and
2075      * compare data versions since someone could have changed the data or we're
2076      * reading a file written elsewhere. We only want to bypass doing no-op
2077      * read rpcs on newly created files (dv of 0) since only then we guarantee
2078      * that this chunk's data hasn't been filled by another client.
2079      */
2080     size = AFS_CHUNKSIZE(abyte);
2081     if (aflags & 4)             /* called from write */
2082         tlen = *alen;
2083     else                        /* called from read */
2084         tlen = tdc->validPos - abyte;
2085     Position = AFS_CHUNKTOBASE(chunk);
2086     afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
2087                ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
2088                ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
2089                ICL_HANDLE_OFFSET(Position));
2090     if ((aflags & 4) && (hiszero(avc->m.DataVersion)))
2091         doAdjustSize = 1;
2092     if ((AFS_CHUNKTOBASE(chunk) >= avc->m.Length) ||
2093          ((aflags & 4) && (abyte == Position) && (tlen >= size)))
2094         overWriteWholeChunk = 1;
2095     if (doAdjustSize || overWriteWholeChunk) {
2096 #if     defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
2097 #ifdef  AFS_SGI_ENV
2098 #ifdef AFS_SGI64_ENV
2099         if (doAdjustSize)
2100             adjustsize = NBPP;
2101 #else /* AFS_SGI64_ENV */
2102         if (doAdjustSize)
2103             adjustsize = 8192;
2104 #endif /* AFS_SGI64_ENV */
2105 #else /* AFS_SGI_ENV */
2106         if (doAdjustSize)
2107             adjustsize = 4096;
2108 #endif /* AFS_SGI_ENV */
2109         if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->m.Length &&
2110 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2111 #if     defined(AFS_SUN5_ENV)  || defined(AFS_OSF_ENV)
2112         if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->m.Length)) &&
2113 #else
2114         if (AFS_CHUNKTOBASE(chunk) >= avc->m.Length &&
2115 #endif
2116 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2117             !hsame(avc->m.DataVersion, tdc->f.versionNo))
2118             doReallyAdjustSize = 1;
2119
2120         if (doReallyAdjustSize || overWriteWholeChunk) {
2121             /* no data in file to read at this position */
2122             UpgradeSToWLock(&tdc->lock, 607);
2123
2124             file = afs_CFileOpen(tdc->f.inode);
2125             afs_CFileTruncate(file, 0);
2126             afs_CFileClose(file);
2127             afs_AdjustSize(tdc, 0);
2128             hset(tdc->f.versionNo, avc->m.DataVersion);
2129             tdc->dflags |= DFEntryMod;
2130
2131             ConvertWToSLock(&tdc->lock);
2132         }
2133     }
2134
2135     /*
2136      * We must read in the whole chunk if the version number doesn't
2137      * match.
2138      */
2139     if (aflags & 2) {
2140         /* don't need data, just a unique dcache entry */
2141         ObtainWriteLock(&afs_xdcache, 608);
2142         hset(afs_indexTimes[tdc->index], afs_indexCounter);
2143         hadd32(afs_indexCounter, 1);
2144         ReleaseWriteLock(&afs_xdcache);
2145
2146         updateV2DC(setLocks, avc, tdc, 553);
2147         if (vType(avc) == VDIR)
2148             *aoffset = abyte;
2149         else
2150             *aoffset = AFS_CHUNKOFFSET(abyte);
2151         if (tdc->validPos < abyte)
2152             *alen = (afs_size_t) 0;
2153         else
2154             *alen = tdc->validPos - abyte;
2155         ReleaseSharedLock(&tdc->lock);
2156         if (setLocks) {
2157             if (slowPass)
2158                 ReleaseWriteLock(&avc->lock);
2159             else
2160                 ReleaseReadLock(&avc->lock);
2161         }
2162         return tdc;             /* check if we're done */
2163     }
2164
2165     /*
2166      * Locks held:
2167      * avc->lock(R) if setLocks && !slowPass
2168      * avc->lock(W) if !setLocks || slowPass
2169      * tdc->lock(S)
2170      */
2171     osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
2172
2173     setNewCallback = setVcacheStatus = 0;
2174
2175     /*
2176      * Locks held:
2177      * avc->lock(R) if setLocks && !slowPass
2178      * avc->lock(W) if !setLocks || slowPass
2179      * tdc->lock(S)
2180      */
2181     if (!hsame(avc->m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
2182         /*
2183          * Version number mismatch.
2184          */
2185         /*
2186          * If we are disconnected, then we can't do much of anything
2187          * because the data doesn't match the file.
2188          */
2189         if (AFS_IS_DISCONNECTED) {
2190             ReleaseSharedLock(&tdc->lock);
2191             if (setLocks) {
2192                 if (slowPass)
2193                     ReleaseWriteLock(&avc->lock);
2194                 else
2195                     ReleaseReadLock(&avc->lock);
2196             }
2197             /* Flush the Dcache */
2198             afs_PutDCache(tdc);
2199
2200             return NULL;
2201         }
2202         UpgradeSToWLock(&tdc->lock, 609);
2203
2204         /*
2205          * If data ever existed for this vnode, and this is a text object,
2206          * do some clearing.  Now, you'd think you need only do the flush
2207          * when VTEXT is on, but VTEXT is turned off when the text object
2208          * is freed, while pages are left lying around in memory marked
2209          * with this vnode.  If we would reactivate (create a new text
2210          * object from) this vnode, we could easily stumble upon some of
2211          * these old pages in pagein.  So, we always flush these guys.
2212          * Sun has a wonderful lack of useful invariants in this system.
2213          *
2214          * avc->flushDV is the data version # of the file at the last text
2215          * flush.  Clearly, at least, we don't have to flush the file more
2216          * often than it changes
2217          */
2218         if (hcmp(avc->flushDV, avc->m.DataVersion) < 0) {
2219             /*
2220              * By here, the cache entry is always write-locked.  We can
2221              * deadlock if we call osi_Flush with the cache entry locked...
2222              * Unlock the dcache too.
2223              */
2224             ReleaseWriteLock(&tdc->lock);
2225             if (setLocks && !slowPass)
2226                 ReleaseReadLock(&avc->lock);
2227             else
2228                 ReleaseWriteLock(&avc->lock);
2229
2230             osi_FlushText(avc);
2231             /*
2232              * Call osi_FlushPages in open, read/write, and map, since it
2233              * is too hard here to figure out if we should lock the
2234              * pvnLock.
2235              */
2236             if (setLocks && !slowPass)
2237                 ObtainReadLock(&avc->lock);
2238             else
2239                 ObtainWriteLock(&avc->lock, 66);
2240             ObtainWriteLock(&tdc->lock, 610);
2241         }
2242
2243         /*
2244          * Locks held:
2245          * avc->lock(R) if setLocks && !slowPass
2246          * avc->lock(W) if !setLocks || slowPass
2247          * tdc->lock(W)
2248          */
2249
2250         /* Watch for standard race condition around osi_FlushText */
2251         if (hsame(avc->m.DataVersion, tdc->f.versionNo)) {
2252             updateV2DC(setLocks, avc, tdc, 569);        /* set hint */
2253             afs_stats_cmperf.dcacheHits++;
2254             ConvertWToSLock(&tdc->lock);
2255             goto done;
2256         }
2257
2258         /* Sleep here when cache needs to be drained. */
2259         if (setLocks && !slowPass
2260             && (afs_blocksUsed >
2261                 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2262             /* Make sure truncate daemon is running */
2263             afs_MaybeWakeupTruncateDaemon();
2264             ObtainWriteLock(&tdc->tlock, 614);
2265             tdc->refCount--;    /* we'll re-obtain the dcache when we re-try. */
2266             ReleaseWriteLock(&tdc->tlock);
2267             ReleaseWriteLock(&tdc->lock);
2268             ReleaseReadLock(&avc->lock);
2269             while ((afs_blocksUsed - afs_blocksDiscarded) >
2270                    PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2271                 afs_WaitForCacheDrain = 1;
2272                 afs_osi_Sleep(&afs_WaitForCacheDrain);
2273             }
2274             afs_MaybeFreeDiscardedDCache();
2275             /* need to check if someone else got the chunk first. */
2276             goto RetryGetDCache;
2277         }
2278
2279         /* Do not fetch data beyond truncPos. */
2280         maxGoodLength = avc->m.Length;
2281         if (avc->truncPos < maxGoodLength)
2282             maxGoodLength = avc->truncPos;
2283         Position = AFS_CHUNKBASE(abyte);
2284         if (vType(avc) == VDIR) {
2285             size = avc->m.Length;
2286             if (size > tdc->f.chunkBytes) {
2287                 /* pre-reserve space for file */
2288                 afs_AdjustSize(tdc, size);
2289             }
2290             size = 999999999;   /* max size for transfer */
2291         } else {
2292             size = AFS_CHUNKSIZE(abyte);        /* expected max size */
2293             /* don't read past end of good data on server */
2294             if (Position + size > maxGoodLength)
2295                 size = maxGoodLength - Position;
2296             if (size < 0)
2297                 size = 0;       /* Handle random races */
2298             if (size > tdc->f.chunkBytes) {
2299                 /* pre-reserve space for file */
2300                 afs_AdjustSize(tdc, size);      /* changes chunkBytes */
2301                 /* max size for transfer still in size */
2302             }
2303         }
2304         if (afs_mariner && !tdc->f.chunk)
2305             afs_MarinerLog("fetch$Fetching", avc);      /* , Position, size, afs_indexCounter ); */
2306         /*
2307          * Right now, we only have one tool, and it's a hammer.  So, we
2308          * fetch the whole file.
2309          */
2310         DZap(tdc);      /* pages in cache may be old */
2311         file = afs_CFileOpen(tdc->f.inode);
2312         afs_RemoveVCB(&avc->fid);
2313         tdc->f.states |= DWriting;
2314         tdc->dflags |= DFFetching;
2315         tdc->validPos = Position;       /*  which is AFS_CHUNKBASE(abyte) */
2316         if (tdc->mflags & DFFetchReq) {
2317             tdc->mflags &= ~DFFetchReq;
2318             if (afs_osi_Wakeup(&tdc->validPos) == 0)
2319                 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2320                            __FILE__, ICL_TYPE_INT32, __LINE__,
2321                            ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2322                            tdc->dflags);
2323         }
2324         tsmall =
2325             (struct tlocal1 *)osi_AllocLargeSpace(sizeof(struct tlocal1));
2326         setVcacheStatus = 0;
2327 #ifndef AFS_NOSTATS
2328         /*
2329          * Remember if we are doing the reading from a replicated volume,
2330          * and how many times we've zipped around the fetch/analyze loop.
2331          */
2332         fromReplica = (avc->states & CRO) ? 1 : 0;
2333         numFetchLoops = 0;
2334         accP = &(afs_stats_cmfullperf.accessinf);
2335         if (fromReplica)
2336             (accP->replicatedRefs)++;
2337         else
2338             (accP->unreplicatedRefs)++;
2339 #endif /* AFS_NOSTATS */
2340         /* this is a cache miss */
2341         afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2342                    ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
2343                    ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2344
2345         if (size)
2346             afs_stats_cmperf.dcacheMisses++;
2347         code = 0;
2348         /*
2349          * Dynamic root support:  fetch data from local memory.
2350          */
2351         if (afs_IsDynroot(avc)) {
2352             char *dynrootDir;
2353             int dynrootLen;
2354
2355             afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2356
2357             dynrootDir += Position;
2358             dynrootLen -= Position;
2359             if (size > dynrootLen)
2360                 size = dynrootLen;
2361             if (size < 0)
2362                 size = 0;
2363             code = afs_CFileWrite(file, 0, dynrootDir, size);
2364             afs_PutDynroot();
2365
2366             if (code == size)
2367                 code = 0;
2368             else
2369                 code = -1;
2370
2371             tdc->validPos = Position + size;
2372             afs_CFileTruncate(file, size);      /* prune it */
2373         } else if (afs_IsDynrootMount(avc)) {
2374             char *dynrootDir;
2375             int dynrootLen;
2376
2377             afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2378
2379             dynrootDir += Position;
2380             dynrootLen -= Position;
2381             if (size > dynrootLen)
2382                 size = dynrootLen;
2383             if (size < 0)
2384                 size = 0;
2385             code = afs_CFileWrite(file, 0, dynrootDir, size);
2386             afs_PutDynroot();
2387
2388             if (code == size)
2389                 code = 0;
2390             else
2391                 code = -1;
2392
2393             tdc->validPos = Position + size;
2394             afs_CFileTruncate(file, size);      /* prune it */
2395         } else
2396             /*
2397              * Not a dynamic vnode:  do the real fetch.
2398              */
2399             do {
2400                 /*
2401                  * Locks held:
2402                  * avc->lock(R) if setLocks && !slowPass
2403                  * avc->lock(W) if !setLocks || slowPass
2404                  * tdc->lock(W)
2405                  */
2406
2407                 tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
2408                 if (tc) {
2409                     afs_int32 length_hi, length, bytes;
2410 #ifndef AFS_NOSTATS
2411                     numFetchLoops++;
2412                     if (fromReplica)
2413                         (accP->numReplicasAccessed)++;
2414
2415 #endif /* AFS_NOSTATS */
2416                     if (!setLocks || slowPass) {
2417                         avc->callback = tc->srvr->server;
2418                     } else {
2419                         newCallback = tc->srvr->server;
2420                         setNewCallback = 1;
2421                     }
2422                     i = osi_Time();
2423                     RX_AFS_GUNLOCK();
2424                     tcall = rx_NewCall(tc->id);
2425                     RX_AFS_GLOCK();
2426
2427                     XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
2428 #ifdef AFS_64BIT_CLIENT
2429                     length_hi = code = 0;
2430                     if (!afs_serverHasNo64Bit(tc)) {
2431                         tsize = size;
2432                         RX_AFS_GUNLOCK();
2433                         code =
2434                             StartRXAFS_FetchData64(tcall,
2435                                                    (struct AFSFid *)&avc->fid.
2436                                                    Fid, Position, tsize);
2437                         if (code != 0) {
2438                             RX_AFS_GLOCK();
2439                             afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2440                                        ICL_TYPE_POINTER, avc, ICL_TYPE_INT32,
2441                                        code);
2442                         } else {
2443                             bytes =
2444                                 rx_Read(tcall, (char *)&length_hi,
2445                                         sizeof(afs_int32));
2446                             RX_AFS_GLOCK();
2447                             if (bytes == sizeof(afs_int32)) {
2448                                 length_hi = ntohl(length_hi);
2449                             } else {
2450                                 length_hi = 0;
2451                                 code = rx_Error(tcall);
2452                                 RX_AFS_GUNLOCK();
2453                                 code1 = rx_EndCall(tcall, code);
2454                                 RX_AFS_GLOCK();
2455                                 tcall = (struct rx_call *)0;
2456                             }
2457                         }
2458                     }
2459                     if (code == RXGEN_OPCODE || afs_serverHasNo64Bit(tc)) {
2460                         if (Position > 0x7FFFFFFF) {
2461                             code = EFBIG;
2462                         } else {
2463                             afs_int32 pos;
2464                             pos = Position;
2465                             RX_AFS_GUNLOCK();
2466                             if (!tcall)
2467                                 tcall = rx_NewCall(tc->id);
2468                             code =
2469                                 StartRXAFS_FetchData(tcall, (struct AFSFid *)
2470                                                      &avc->fid.Fid, pos,
2471                                                      size);
2472                             RX_AFS_GLOCK();
2473                         }
2474                         afs_serverSetNo64Bit(tc);
2475                     }
2476                     if (code == 0) {
2477                         RX_AFS_GUNLOCK();
2478                         bytes =
2479                             rx_Read(tcall, (char *)&length,
2480                                     sizeof(afs_int32));
2481                         RX_AFS_GLOCK();
2482                         if (bytes == sizeof(afs_int32)) {
2483                             length = ntohl(length);
2484                         } else {
2485                             code = rx_Error(tcall);
2486                         }
2487                     }
2488                     FillInt64(lengthFound, length_hi, length);
2489                     afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64LENG,
2490                                ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
2491                                ICL_TYPE_OFFSET,
2492                                ICL_HANDLE_OFFSET(lengthFound));
2493 #else /* AFS_64BIT_CLIENT */
2494                     RX_AFS_GUNLOCK();
2495                     code =
2496                         StartRXAFS_FetchData(tcall,
2497                                              (struct AFSFid *)&avc->fid.Fid,
2498                                              Position, size);
2499                     RX_AFS_GLOCK();
2500                     if (code == 0) {
2501                         RX_AFS_GUNLOCK();
2502                         bytes =
2503                             rx_Read(tcall, (char *)&length,
2504                                     sizeof(afs_int32));
2505                         RX_AFS_GLOCK();
2506                         if (bytes == sizeof(afs_int32)) {
2507                             length = ntohl(length);
2508                         } else {
2509                             code = rx_Error(tcall);
2510                         }
2511                     }
2512 #endif /* AFS_64BIT_CLIENT */
2513                     if (code == 0) {
2514
2515 #ifndef AFS_NOSTATS
2516                         xferP =
2517                             &(afs_stats_cmfullperf.rpc.
2518                               fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
2519                         osi_GetuTime(&xferStartTime);
2520
2521                         code =
2522                             afs_CacheFetchProc(tcall, file,
2523                                                (afs_size_t) Position, tdc,
2524                                                avc, &bytesToXfer,
2525                                                &bytesXferred, length);
2526
2527                         osi_GetuTime(&xferStopTime);
2528                         (xferP->numXfers)++;
2529                         if (!code) {
2530                             (xferP->numSuccesses)++;
2531                             afs_stats_XferSumBytes
2532                                 [AFS_STATS_FS_XFERIDX_FETCHDATA] +=
2533                                 bytesXferred;
2534                             (xferP->sumBytes) +=
2535                                 (afs_stats_XferSumBytes
2536                                  [AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
2537                             afs_stats_XferSumBytes
2538                                 [AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
2539                             if (bytesXferred < xferP->minBytes)
2540                                 xferP->minBytes = bytesXferred;
2541                             if (bytesXferred > xferP->maxBytes)
2542                                 xferP->maxBytes = bytesXferred;
2543
2544                             /*
2545                              * Tally the size of the object.  Note: we tally the actual size,
2546                              * NOT the number of bytes that made it out over the wire.
2547                              */
2548                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
2549                                 (xferP->count[0])++;
2550                             else if (bytesToXfer <=
2551                                      AFS_STATS_MAXBYTES_BUCKET1)
2552                                 (xferP->count[1])++;
2553                             else if (bytesToXfer <=
2554                                      AFS_STATS_MAXBYTES_BUCKET2)
2555                                 (xferP->count[2])++;
2556                             else if (bytesToXfer <=
2557                                      AFS_STATS_MAXBYTES_BUCKET3)
2558                                 (xferP->count[3])++;
2559                             else if (bytesToXfer <=
2560                                      AFS_STATS_MAXBYTES_BUCKET4)
2561                                 (xferP->count[4])++;
2562                             else if (bytesToXfer <=
2563                                      AFS_STATS_MAXBYTES_BUCKET5)
2564                                 (xferP->count[5])++;
2565                             else if (bytesToXfer <=
2566                                      AFS_STATS_MAXBYTES_BUCKET6)
2567                                 (xferP->count[6])++;
2568                             else if (bytesToXfer <=
2569                                      AFS_STATS_MAXBYTES_BUCKET7)
2570                                 (xferP->count[7])++;
2571                             else
2572                                 (xferP->count[8])++;
2573
2574                             afs_stats_GetDiff(elapsedTime, xferStartTime,
2575                                               xferStopTime);
2576                             afs_stats_AddTo((xferP->sumTime), elapsedTime);
2577                             afs_stats_SquareAddTo((xferP->sqrTime),
2578                                                   elapsedTime);
2579                             if (afs_stats_TimeLessThan
2580                                 (elapsedTime, (xferP->minTime))) {
2581                                 afs_stats_TimeAssign((xferP->minTime),
2582                                                      elapsedTime);
2583                             }
2584                             if (afs_stats_TimeGreaterThan
2585                                 (elapsedTime, (xferP->maxTime))) {
2586                                 afs_stats_TimeAssign((xferP->maxTime),
2587                                                      elapsedTime);
2588                             }
2589                         }
2590 #else
2591                         code =
2592                             afs_CacheFetchProc(tcall, file, Position, tdc,
2593                                                avc, 0, 0, length);
2594 #endif /* AFS_NOSTATS */
2595                     }
2596                     if (code == 0) {
2597                         RX_AFS_GUNLOCK();
2598                         code =
2599                             EndRXAFS_FetchData(tcall, &tsmall->OutStatus,
2600                                                &tsmall->CallBack,
2601                                                &tsmall->tsync);
2602                         RX_AFS_GLOCK();
2603                     }
2604                     XSTATS_END_TIME;
2605                     RX_AFS_GUNLOCK();
2606                     if (tcall)
2607                         code1 = rx_EndCall(tcall, code);
2608                     RX_AFS_GLOCK();
2609                 } else {
2610                     code = -1;
2611                 }
2612                 if (!code && code1)
2613                     code = code1;
2614
2615                 if (code == 0) {
2616                     /* callback could have been broken (or expired) in a race here, 
2617                      * but we return the data anyway.  It's as good as we knew about
2618                      * when we started. */
2619                     /* 
2620                      * validPos is updated by CacheFetchProc, and can only be 
2621                      * modifed under a dcache write lock, which we've blocked out 
2622                      */
2623                     size = tdc->validPos - Position;    /* actual segment size */
2624                     if (size < 0)
2625                         size = 0;
2626                     afs_CFileTruncate(file, size);      /* prune it */
2627                 } else {
2628                     if (!setLocks || slowPass) {
2629                         ObtainWriteLock(&afs_xcbhash, 453);
2630                         afs_DequeueCallback(avc);
2631                         avc->states &= ~(CStatd | CUnique);
2632                         avc->callback = NULL;
2633                         ReleaseWriteLock(&afs_xcbhash);
2634                         if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2635                             osi_dnlc_purgedp(avc);
2636                     } else {
2637                         /* Something lost.  Forget about performance, and go
2638                          * back with a vcache write lock.
2639                          */
2640                         afs_CFileTruncate(file, 0);
2641                         afs_AdjustSize(tdc, 0);
2642                         afs_CFileClose(file);
2643                         osi_FreeLargeSpace(tsmall);
2644                         tsmall = 0;
2645                         ReleaseWriteLock(&tdc->lock);
2646                         afs_PutDCache(tdc);
2647                         tdc = 0;
2648                         ReleaseReadLock(&avc->lock);
2649                         slowPass = 1;
2650                         goto RetryGetDCache;
2651                     }
2652                 }
2653
2654             } while (afs_Analyze
2655                      (tc, code, &avc->fid, areq,
2656                       AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2657
2658         /*
2659          * Locks held:
2660          * avc->lock(R) if setLocks && !slowPass
2661          * avc->lock(W) if !setLocks || slowPass
2662          * tdc->lock(W)
2663          */
2664
2665 #ifndef AFS_NOSTATS
2666         /*
2667          * In the case of replicated access, jot down info on the number of
2668          * attempts it took before we got through or gave up.
2669          */
2670         if (fromReplica) {
2671             if (numFetchLoops <= 1)
2672                 (accP->refFirstReplicaOK)++;
2673             if (numFetchLoops > accP->maxReplicasPerRef)
2674                 accP->maxReplicasPerRef = numFetchLoops;
2675         }
2676 #endif /* AFS_NOSTATS */
2677
2678         tdc->dflags &= ~DFFetching;
2679         if (afs_osi_Wakeup(&tdc->validPos) == 0)
2680             afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2681                        __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2682                        tdc, ICL_TYPE_INT32, tdc->dflags);
2683         if (avc->execsOrWriters == 0)
2684             tdc->f.states &= ~DWriting;
2685
2686         /* now, if code != 0, we have an error and should punt.
2687          * note that we have the vcache write lock, either because
2688          * !setLocks or slowPass.
2689          */
2690         if (code) {
2691             afs_CFileTruncate(file, 0);
2692             afs_AdjustSize(tdc, 0);
2693             afs_CFileClose(file);
2694             ZapDCE(tdc);        /* sets DFEntryMod */
2695             if (vType(avc) == VDIR) {
2696                 DZap(tdc);
2697             }
2698             tdc->f.states &= ~(DRO|DBackup|DRW);
2699             afs_DCMoveBucket(tdc, 0, 0);
2700             ReleaseWriteLock(&tdc->lock);
2701             afs_PutDCache(tdc);
2702             if (!afs_IsDynroot(avc)) {
2703                 ObtainWriteLock(&afs_xcbhash, 454);
2704                 afs_DequeueCallback(avc);
2705                 avc->states &= ~(CStatd | CUnique);
2706                 ReleaseWriteLock(&afs_xcbhash);
2707                 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2708                     osi_dnlc_purgedp(avc);
2709                 /*
2710                  * Locks held:
2711                  * avc->lock(W); assert(!setLocks || slowPass)
2712                  */
2713                 osi_Assert(!setLocks || slowPass);
2714             }
2715             tdc->f.states &= ~(DRO|DBackup|DRW);
2716             afs_DCMoveBucket(tdc, 0, 0);
2717             tdc = NULL;
2718             goto done;
2719         }
2720
2721         /* otherwise we copy in the just-fetched info */
2722         afs_CFileClose(file);
2723         afs_AdjustSize(tdc, size);      /* new size */
2724         /*
2725          * Copy appropriate fields into vcache.  Status is
2726          * copied later where we selectively acquire the
2727          * vcache write lock.
2728          */
2729         if (slowPass)
2730             afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2731         else
2732             setVcacheStatus = 1;
2733         hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2734                tsmall->OutStatus.DataVersion);
2735         tdc->dflags |= DFEntryMod;
2736         afs_indexFlags[tdc->index] |= IFEverUsed;
2737         ConvertWToSLock(&tdc->lock);
2738     } /*Data version numbers don't match */
2739     else {
2740         /*
2741          * Data version numbers match.
2742          */
2743         afs_stats_cmperf.dcacheHits++;
2744     }                           /*Data version numbers match */
2745
2746     updateV2DC(setLocks, avc, tdc, 335);        /* set hint */
2747   done:
2748     /*
2749      * Locks held:
2750      * avc->lock(R) if setLocks && !slowPass
2751      * avc->lock(W) if !setLocks || slowPass
2752      * tdc->lock(S) if tdc
2753      */
2754
2755     /*
2756      * See if this was a reference to a file in the local cell.
2757      */
2758     if (afs_IsPrimaryCellNum(avc->fid.Cell))
2759         afs_stats_cmperf.dlocalAccesses++;
2760     else
2761         afs_stats_cmperf.dremoteAccesses++;
2762
2763     /* Fix up LRU info */
2764
2765     if (tdc) {
2766         MObtainWriteLock(&afs_xdcache, 602);
2767         hset(afs_indexTimes[tdc->index], afs_indexCounter);
2768         hadd32(afs_indexCounter, 1);
2769         MReleaseWriteLock(&afs_xdcache);
2770
2771         /* return the data */
2772         if (vType(avc) == VDIR)
2773             *aoffset = abyte;
2774         else
2775             *aoffset = AFS_CHUNKOFFSET(abyte);
2776         *alen = (tdc->f.chunkBytes - *aoffset);
2777         ReleaseSharedLock(&tdc->lock);
2778     }
2779
2780     /*
2781      * Locks held:
2782      * avc->lock(R) if setLocks && !slowPass
2783      * avc->lock(W) if !setLocks || slowPass
2784      */
2785
2786     /* Fix up the callback and status values in the vcache */
2787     doVcacheUpdate = 0;
2788     if (setLocks && !slowPass) {
2789         /* DCLOCKXXX
2790          *
2791          * This is our dirty little secret to parallel fetches.
2792          * We don't write-lock the vcache while doing the fetch,
2793          * but potentially we'll need to update the vcache after
2794          * the fetch is done.
2795          *
2796          * Drop the read lock and try to re-obtain the write
2797          * lock.  If the vcache still has the same DV, it's
2798          * ok to go ahead and install the new data.
2799          */
2800         afs_hyper_t currentDV, statusDV;
2801
2802         hset(currentDV, avc->m.DataVersion);
2803
2804         if (setNewCallback && avc->callback != newCallback)
2805             doVcacheUpdate = 1;
2806
2807         if (tsmall) {
2808             hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2809                    tsmall->OutStatus.DataVersion);
2810
2811             if (setVcacheStatus && avc->m.Length != tsmall->OutStatus.Length)
2812                 doVcacheUpdate = 1;
2813             if (setVcacheStatus && !hsame(currentDV, statusDV))
2814                 doVcacheUpdate = 1;
2815         }
2816
2817         ReleaseReadLock(&avc->lock);
2818
2819         if (doVcacheUpdate) {
2820             ObtainWriteLock(&avc->lock, 615);
2821             if (!hsame(avc->m.DataVersion, currentDV)) {
2822                 /* We lose.  Someone will beat us to it. */
2823                 doVcacheUpdate = 0;
2824                 ReleaseWriteLock(&avc->lock);
2825             }
2826         }
2827     }
2828
2829     /* With slow pass, we've already done all the updates */
2830     if (slowPass) {
2831         ReleaseWriteLock(&avc->lock);
2832     }
2833
2834     /* Check if we need to perform any last-minute fixes with a write-lock */
2835     if (!setLocks || doVcacheUpdate) {
2836         if (setNewCallback)
2837             avc->callback = newCallback;
2838         if (tsmall && setVcacheStatus)
2839             afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2840         if (setLocks)
2841             ReleaseWriteLock(&avc->lock);
2842     }
2843
2844     if (tsmall)
2845         osi_FreeLargeSpace(tsmall);
2846
2847     return tdc;
2848 }                               /*afs_GetDCache */
2849
2850
2851 /*
2852  * afs_WriteThroughDSlots
2853  *
2854  * Description:
2855  *      Sweep through the dcache slots and write out any modified
2856  *      in-memory data back on to our caching store.
2857  *
2858  * Parameters:
2859  *      None.
2860  *
2861  * Environment:
2862  *      The afs_xdcache is write-locked through this whole affair.
2863  */
2864 void
2865 afs_WriteThroughDSlots(void)
2866 {
2867     register struct dcache *tdc;
2868     register afs_int32 i, touchedit = 0;
2869
2870     struct afs_q DirtyQ, *tq;
2871
2872     AFS_STATCNT(afs_WriteThroughDSlots);
2873
2874     /*
2875      * Because of lock ordering, we can't grab dcache locks while
2876      * holding afs_xdcache.  So we enter xdcache, get a reference
2877      * for every dcache entry, and exit xdcache.
2878      */
2879     MObtainWriteLock(&afs_xdcache, 283);
2880     QInit(&DirtyQ);
2881     for (i = 0; i < afs_cacheFiles; i++) {
2882         tdc = afs_indexTable[i];
2883
2884         /* Grab tlock in case the existing refcount isn't zero */
2885         if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2886             ObtainWriteLock(&tdc->tlock, 623);
2887             tdc->refCount++;
2888             ReleaseWriteLock(&tdc->tlock);
2889
2890             QAdd(&DirtyQ, &tdc->dirty);
2891         }
2892     }
2893     MReleaseWriteLock(&afs_xdcache);
2894
2895     /*
2896      * Now, for each dcache entry we found, check if it's dirty.
2897      * If so, get write-lock, get afs_xdcache, which protects
2898      * afs_cacheInodep, and flush it.  Don't forget to put back
2899      * the refcounts.
2900      */
2901
2902 #define DQTODC(q)       ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2903
2904     for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2905         tdc = DQTODC(tq);
2906         if (tdc->dflags & DFEntryMod) {
2907             int wrLock;
2908
2909             wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2910
2911             /* Now that we have the write lock, double-check */
2912             if (wrLock && (tdc->dflags & DFEntryMod)) {
2913                 tdc->dflags &= ~DFEntryMod;
2914                 MObtainWriteLock(&afs_xdcache, 620);
2915                 afs_WriteDCache(tdc, 1);
2916                 MReleaseWriteLock(&afs_xdcache);
2917                 touchedit = 1;
2918             }
2919             if (wrLock)
2920                 ReleaseWriteLock(&tdc->lock);
2921         }
2922
2923         afs_PutDCache(tdc);
2924     }
2925
2926     MObtainWriteLock(&afs_xdcache, 617);
2927     if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2928         /* Touch the file to make sure that the mtime on the file is kept
2929          * up-to-date to avoid losing cached files on cold starts because
2930          * their mtime seems old...
2931          */
2932         struct afs_fheader theader;
2933
2934         theader.magic = AFS_FHMAGIC;
2935         theader.firstCSize = AFS_FIRSTCSIZE;
2936         theader.otherCSize = AFS_OTHERCSIZE;
2937         theader.version = AFS_CI_VERSION;
2938         afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2939     }
2940     MReleaseWriteLock(&afs_xdcache);
2941 }
2942
2943 /*
2944  * afs_MemGetDSlot
2945  *
2946  * Description:
2947  *      Return a pointer to an freshly initialized dcache entry using
2948  *      a memory-based cache.  The tlock will be read-locked.
2949  *
2950  * Parameters:
2951  *      aslot : Dcache slot to look at.
2952  *      tmpdc : Ptr to dcache entry.
2953  *
2954  * Environment:
2955  *      Must be called with afs_xdcache write-locked.
2956  */
2957
2958 struct dcache *
2959 afs_MemGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2960 {
2961     register struct dcache *tdc;
2962     int existing = 0;
2963
2964     AFS_STATCNT(afs_MemGetDSlot);
2965     if (CheckLock(&afs_xdcache) != -1)
2966         osi_Panic("getdslot nolock");
2967     if (aslot < 0 || aslot >= afs_cacheFiles)
2968         osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2969     tdc = afs_indexTable[aslot];
2970     if (tdc) {
2971         QRemove(&tdc->lruq);    /* move to queue head */
2972         QAdd(&afs_DLRU, &tdc->lruq);
2973         /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2974         ObtainWriteLock(&tdc->tlock, 624);
2975         tdc->refCount++;
2976         ConvertWToRLock(&tdc->tlock);
2977         return tdc;
2978     }
2979     if (tmpdc == NULL) {
2980         if (!afs_freeDSList)
2981             afs_GetDownDSlot(4);
2982         if (!afs_freeDSList) {
2983             /* none free, making one is better than a panic */
2984             afs_stats_cmperf.dcacheXAllocs++;   /* count in case we have a leak */
2985             tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2986 #ifdef  KERNEL_HAVE_PIN
2987             pin((char *)tdc, sizeof(struct dcache));    /* XXX */
2988 #endif
2989         } else {
2990             tdc = afs_freeDSList;
2991             afs_freeDSList = (struct dcache *)tdc->lruq.next;
2992             existing = 1;
2993         }
2994         tdc->dflags = 0;        /* up-to-date, not in free q */
2995         tdc->mflags = 0;
2996         QAdd(&afs_DLRU, &tdc->lruq);
2997         if (tdc->lruq.prev == &tdc->lruq)
2998             osi_Panic("lruq 3");
2999     } else {
3000         tdc = tmpdc;
3001         tdc->f.states = 0;
3002     }
3003
3004     /* initialize entry */
3005     tdc->f.fid.Cell = 0;
3006     tdc->f.fid.Fid.Volume = 0;
3007     tdc->f.chunk = -1;
3008     hones(tdc->f.versionNo);
3009     tdc->f.inode = aslot;
3010     tdc->dflags |= DFEntryMod;
3011     tdc->refCount = 1;
3012     tdc->index = aslot;
3013     afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3014
3015     if (existing) {
3016         osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3017         osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3018         osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3019     }
3020
3021     RWLOCK_INIT(&tdc->lock, "dcache lock");
3022     RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3023     RWLOCK_INIT(&tdc->mflock, "dcache flock");
3024     ObtainReadLock(&tdc->tlock);
3025
3026     if (tmpdc == NULL)
3027         afs_indexTable[aslot] = tdc;
3028     return tdc;
3029
3030 }                               /*afs_MemGetDSlot */
3031
3032 unsigned int last_error = 0, lasterrtime = 0;
3033
3034 /*
3035  * afs_UFSGetDSlot
3036  *
3037  * Description:
3038  *      Return a pointer to an freshly initialized dcache entry using
3039  *      a UFS-based disk cache.  The dcache tlock will be read-locked.
3040  *
3041  * Parameters:
3042  *      aslot : Dcache slot to look at.
3043  *      tmpdc : Ptr to dcache entry.
3044  *
3045  * Environment:
3046  *      afs_xdcache lock write-locked.
3047  */
3048 struct dcache *
3049 afs_UFSGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
3050 {
3051     register afs_int32 code;
3052     register struct dcache *tdc;
3053     int existing = 0;
3054     int entryok;
3055
3056     AFS_STATCNT(afs_UFSGetDSlot);
3057     if (CheckLock(&afs_xdcache) != -1)
3058         osi_Panic("getdslot nolock");
3059     if (aslot < 0 || aslot >= afs_cacheFiles)
3060         osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3061     tdc = afs_indexTable[aslot];
3062     if (tdc) {
3063         QRemove(&tdc->lruq);    /* move to queue head */
3064         QAdd(&afs_DLRU, &tdc->lruq);
3065         /* Grab tlock in case refCount != 0 */
3066         ObtainWriteLock(&tdc->tlock, 625);
3067         tdc->refCount++;
3068         ConvertWToRLock(&tdc->tlock);
3069         return tdc;
3070     }
3071     /* otherwise we should read it in from the cache file */
3072     /*
3073      * If we weren't passed an in-memory region to place the file info,
3074      * we have to allocate one.
3075      */
3076     if (tmpdc == NULL) {
3077         if (!afs_freeDSList)
3078             afs_GetDownDSlot(4);
3079         if (!afs_freeDSList) {
3080             /* none free, making one is better than a panic */
3081             afs_stats_cmperf.dcacheXAllocs++;   /* count in case we have a leak */
3082             tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
3083 #ifdef  KERNEL_HAVE_PIN
3084             pin((char *)tdc, sizeof(struct dcache));    /* XXX */
3085 #endif
3086         } else {
3087             tdc = afs_freeDSList;
3088             afs_freeDSList = (struct dcache *)tdc->lruq.next;
3089             existing = 1;
3090         }
3091         tdc->dflags = 0;        /* up-to-date, not in free q */
3092         tdc->mflags = 0;
3093         QAdd(&afs_DLRU, &tdc->lruq);
3094         if (tdc->lruq.prev == &tdc->lruq)
3095             osi_Panic("lruq 3");
3096     } else {
3097         tdc = tmpdc;
3098         tdc->f.states = 0;
3099     }
3100
3101     /*
3102      * Seek to the aslot'th entry and read it in.
3103      */
3104     code =
3105         afs_osi_Read(afs_cacheInodep,
3106                      sizeof(struct fcache) * aslot +
3107                      sizeof(struct afs_fheader), (char *)(&tdc->f),
3108                      sizeof(struct fcache));
3109     entryok = 1;
3110     if (code != sizeof(struct fcache))
3111         entryok = 0;
3112     if (!afs_CellNumValid(tdc->f.fid.Cell))
3113         entryok = 0;
3114
3115     if (!entryok) {
3116         tdc->f.fid.Cell = 0;
3117         tdc->f.fid.Fid.Volume = 0;
3118         tdc->f.chunk = -1;
3119         hones(tdc->f.versionNo);
3120         tdc->dflags |= DFEntryMod;
3121 #if defined(KERNEL_HAVE_UERROR)
3122         last_error = getuerror();
3123 #endif
3124         lasterrtime = osi_Time();
3125         afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3126         tdc->f.states &= ~(DRO|DBackup|DRW);
3127         afs_DCMoveBucket(tdc, 0, 0);
3128     } else {
3129         if (&tdc->f != 0) {
3130             if (tdc->f.states & DRO) {
3131                 afs_DCMoveBucket(tdc, 0, 2);
3132             } else if (tdc->f.states & DBackup) {
3133                 afs_DCMoveBucket(tdc, 0, 1);
3134             } else {
3135                 afs_DCMoveBucket(tdc, 0, 1); 
3136             }
3137         } 
3138     }
3139     tdc->refCount = 1;
3140     tdc->index = aslot;
3141     if (tdc->f.chunk >= 0)
3142         tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
3143     else
3144         tdc->validPos = 0;
3145
3146     if (existing) {
3147         osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3148         osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3149         osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3150     }
3151
3152     RWLOCK_INIT(&tdc->lock, "dcache lock");
3153     RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3154     RWLOCK_INIT(&tdc->mflock, "dcache flock");
3155     ObtainReadLock(&tdc->tlock);
3156
3157     /*
3158      * If we didn't read into a temporary dcache region, update the
3159      * slot pointer table.
3160      */
3161     if (tmpdc == NULL)
3162         afs_indexTable[aslot] = tdc;
3163     return tdc;
3164
3165 }                               /*afs_UFSGetDSlot */
3166
3167
3168
3169 /*
3170  * afs_WriteDCache
3171  *
3172  * Description:
3173  *      write a particular dcache entry back to its home in the
3174  *      CacheInfo file.
3175  *
3176  * Parameters:
3177  *      adc   : Pointer to the dcache entry to write.
3178  *      atime : If true, set the modtime on the file to the current time.
3179  *
3180  * Environment:
3181  *      Must be called with the afs_xdcache lock at least read-locked,
3182  *      and dcache entry at least read-locked.
3183  *      The reference count is not changed.
3184  */
3185
3186 int
3187 afs_WriteDCache(register struct dcache *adc, int atime)
3188 {
3189     register afs_int32 code;
3190
3191     if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3192         return 0;
3193     AFS_STATCNT(afs_WriteDCache);
3194     osi_Assert(WriteLocked(&afs_xdcache));
3195     if (atime)
3196         adc->f.modTime = osi_Time();
3197     /*
3198      * Seek to the right dcache slot and write the in-memory image out to disk.
3199      */
3200     afs_cellname_write();
3201     code =
3202         afs_osi_Write(afs_cacheInodep,
3203                       sizeof(struct fcache) * adc->index +
3204                       sizeof(struct afs_fheader), (char *)(&adc->f),
3205                       sizeof(struct fcache));
3206     if (code != sizeof(struct fcache))
3207         return EIO;
3208     return 0;
3209 }
3210
3211
3212
3213 /*
3214  * afs_wakeup
3215  *
3216  * Description:
3217  *      Wake up users of a particular file waiting for stores to take
3218  *      place.
3219  *
3220  * Parameters:
3221  *      avc : Ptr to related vcache entry.
3222  *
3223  * Environment:
3224  *      Nothing interesting.
3225  */
3226
3227 int
3228 afs_wakeup(register struct vcache *avc)
3229 {
3230     register int i;
3231     register struct brequest *tb;
3232     tb = afs_brs;
3233     AFS_STATCNT(afs_wakeup);
3234     for (i = 0; i < NBRS; i++, tb++) {
3235         /* if request is valid and for this file, we've found it */
3236         if (tb->refCount > 0 && avc == tb->vc) {
3237
3238             /*
3239              * If CSafeStore is on, then we don't awaken the guy
3240              * waiting for the store until the whole store has finished.
3241              * Otherwise, we do it now.  Note that if CSafeStore is on,
3242              * the BStore routine actually wakes up the user, instead
3243              * of us.
3244              * I think this is redundant now because this sort of thing
3245              * is already being handled by the higher-level code.
3246              */
3247             if ((avc->states & CSafeStore) == 0) {
3248                 tb->code = 0;
3249                 tb->flags |= BUVALID;
3250                 if (tb->flags & BUWAIT) {
3251                     tb->flags &= ~BUWAIT;
3252                     afs_osi_Wakeup(tb);
3253                 }
3254             }
3255             break;
3256         }
3257     }
3258     return 0;
3259 }
3260
3261
3262 /*
3263  * afs_InitCacheFile
3264  *
3265  * Description:
3266  *      Given a file name and inode, set up that file to be an
3267  *      active member in the AFS cache.  This also involves checking
3268  *      the usability of its data.
3269  *
3270  * Parameters:
3271  *      afile  : Name of the cache file to initialize.
3272  *      ainode : Inode of the file.
3273  *
3274  * Environment:
3275  *      This function is called only during initialization.
3276  */
3277
3278 int
3279 afs_InitCacheFile(char *afile, ino_t ainode)
3280 {
3281     register afs_int32 code;
3282 #if defined(AFS_LINUX22_ENV)
3283     struct dentry *filevp;
3284 #else
3285     struct vnode *filevp;
3286 #endif
3287     afs_int32 index;
3288     int fileIsBad;
3289     struct osi_file *tfile;
3290     struct osi_stat tstat;
3291     register struct dcache *tdc;
3292
3293     AFS_STATCNT(afs_InitCacheFile);
3294     index = afs_stats_cmperf.cacheNumEntries;
3295     if (index >= afs_cacheFiles)
3296         return EINVAL;
3297
3298     MObtainWriteLock(&afs_xdcache, 282);
3299     tdc = afs_GetDSlot(index, NULL);
3300     ReleaseReadLock(&tdc->tlock);
3301     MReleaseWriteLock(&afs_xdcache);
3302
3303     ObtainWriteLock(&tdc->lock, 621);
3304     MObtainWriteLock(&afs_xdcache, 622);
3305     if (afile) {
3306         code = gop_lookupname(afile, AFS_UIOSYS, 0, &filevp);
3307         if (code) {
3308             ReleaseWriteLock(&afs_xdcache);
3309             ReleaseWriteLock(&tdc->lock);
3310             afs_PutDCache(tdc);
3311             return code;
3312         }
3313         /*
3314          * We have a VN_HOLD on filevp.  Get the useful info out and
3315          * return.  We make use of the fact that the cache is in the
3316          * UFS file system, and just record the inode number.
3317          */
3318 #ifdef AFS_LINUX22_ENV
3319         tdc->f.inode = VTOI(filevp->d_inode)->i_number;
3320         dput(filevp);
3321 #else
3322         tdc->f.inode = afs_vnodeToInumber(filevp);
3323         AFS_RELE(filevp);
3324 #endif /* AFS_LINUX22_ENV */
3325     } else {
3326         tdc->f.inode = ainode;
3327     }
3328     fileIsBad = 0;
3329     if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3330         fileIsBad = 1;
3331     tfile = osi_UFSOpen(tdc->f.inode);
3332     code = afs_osi_Stat(tfile, &tstat);
3333     if (code)
3334         osi_Panic("initcachefile stat");
3335
3336     /*
3337      * If file size doesn't match the cache info file, it's probably bad.
3338      */
3339     if (tdc->f.chunkBytes != tstat.size)
3340         fileIsBad = 1;
3341     tdc->f.chunkBytes = 0;
3342
3343     /*
3344      * If file changed within T (120?) seconds of cache info file, it's
3345      * probably bad.  In addition, if slot changed within last T seconds,
3346      * the cache info file may be incorrectly identified, and so slot
3347      * may be bad.
3348      */
3349     if (cacheInfoModTime < tstat.mtime + 120)
3350         fileIsBad = 1;
3351     if (cacheInfoModTime < tdc->f.modTime + 120)
3352         fileIsBad = 1;
3353     /* In case write through is behind, make sure cache items entry is
3354      * at least as new as the chunk.
3355      */
3356     if (tdc->f.modTime < tstat.mtime)
3357         fileIsBad = 1;
3358     if (fileIsBad) {
3359         tdc->f.fid.Fid.Volume = 0;      /* not in the hash table */
3360         if (tstat.size != 0)
3361             osi_UFSTruncate(tfile, 0);
3362         tdc->f.states &= ~(DRO|DBackup|DRW);
3363         afs_DCMoveBucket(tdc, 0, 0);
3364         /* put entry in free cache slot list */
3365         afs_dvnextTbl[tdc->index] = afs_freeDCList;
3366         afs_freeDCList = index;
3367         afs_freeDCCount++;
3368         afs_indexFlags[index] |= IFFree;
3369         afs_indexUnique[index] = 0;
3370     } else {
3371         /*
3372          * We must put this entry in the appropriate hash tables.
3373          * Note that i is still set from the above DCHash call
3374          */
3375         code = DCHash(&tdc->f.fid, tdc->f.chunk);
3376         afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3377         afs_dchashTbl[code] = tdc->index;
3378         code = DVHash(&tdc->f.fid);
3379         afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3380         afs_dvhashTbl[code] = tdc->index;
3381         afs_AdjustSize(tdc, tstat.size);        /* adjust to new size */
3382         if (tstat.size > 0)
3383             /* has nontrivial amt of data */
3384             afs_indexFlags[index] |= IFEverUsed;
3385         afs_stats_cmperf.cacheFilesReused++;
3386         /*
3387          * Initialize index times to file's mod times; init indexCounter
3388          * to max thereof
3389          */
3390         hset32(afs_indexTimes[index], tstat.atime);
3391         if (hgetlo(afs_indexCounter) < tstat.atime) {
3392             hset32(afs_indexCounter, tstat.atime);
3393         }
3394         afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3395     }                           /*File is not bad */
3396
3397     osi_UFSClose(tfile);
3398     tdc->f.states &= ~DWriting;
3399     tdc->dflags &= ~DFEntryMod;
3400     /* don't set f.modTime; we're just cleaning up */
3401     afs_WriteDCache(tdc, 0);
3402     ReleaseWriteLock(&afs_xdcache);
3403     ReleaseWriteLock(&tdc->lock);
3404     afs_PutDCache(tdc);
3405     afs_stats_cmperf.cacheNumEntries++;
3406     return 0;
3407 }
3408
3409
3410 /*Max # of struct dcache's resident at any time*/
3411 /*
3412  * If 'dchint' is enabled then in-memory dcache min is increased because of
3413  * crashes...
3414  */
3415 #define DDSIZE 200
3416
3417 /* 
3418  * afs_dcacheInit
3419  *
3420  * Description:
3421  *      Initialize dcache related variables.
3422  */
3423 void
3424 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3425 {
3426     register struct dcache *tdp;
3427     int i;
3428     int code;
3429
3430     afs_freeDCList = NULLIDX;
3431     afs_discardDCList = NULLIDX;
3432     afs_freeDCCount = 0;
3433     afs_freeDSList = NULL;
3434     hzero(afs_indexCounter);
3435
3436     LOCK_INIT(&afs_xdcache, "afs_xdcache");
3437
3438     /*
3439      * Set chunk size
3440      */
3441     if (achunk) {
3442         if (achunk < 0 || achunk > 30)
3443             achunk = 13;        /* Use default */
3444         AFS_SETCHUNKSIZE(achunk);
3445     }
3446
3447     if (!aDentries)
3448         aDentries = DDSIZE;
3449
3450     if (aflags & AFSCALL_INIT_MEMCACHE) {
3451         /*
3452          * Use a memory cache instead of a disk cache
3453          */
3454         cacheDiskType = AFS_FCACHE_TYPE_MEM;
3455         afs_cacheType = &afs_MemCacheOps;
3456         afiles = (afiles < aDentries) ? afiles : aDentries;     /* min */
3457         ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3458         /* ablocks is reported in 1K blocks */
3459         code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3460         if (code != 0) {
3461             printf("afsd: memory cache too large for available memory.\n");
3462             printf("afsd: AFS files cannot be accessed.\n\n");
3463             dcacheDisabled = 1;
3464             afiles = ablocks = 0;
3465         } else
3466             printf("Memory cache: Allocating %d dcache entries...",
3467                    aDentries);
3468     } else {
3469         cacheDiskType = AFS_FCACHE_TYPE_UFS;
3470         afs_cacheType = &afs_UfsCacheOps;
3471     }
3472
3473     if (aDentries > 512)
3474         afs_dhashsize = 2048;
3475     /* initialize hash tables */
3476     afs_dvhashTbl =
3477         (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3478     afs_dchashTbl =
3479         (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3480     for (i = 0; i < afs_dhashsize; i++) {
3481         afs_dvhashTbl[i] = NULLIDX;
3482         afs_dchashTbl[i] = NULLIDX;
3483     }
3484     afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3485     afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3486     for (i = 0; i < afiles; i++) {
3487         afs_dvnextTbl[i] = NULLIDX;
3488         afs_dcnextTbl[i] = NULLIDX;
3489     }
3490
3491     /* Allocate and zero the pointer array to the dcache entries */
3492     afs_indexTable = (struct dcache **)
3493         afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3494     memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3495     afs_indexTimes =
3496         (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3497     memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3498     afs_indexUnique =
3499         (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3500     memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3501     afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3502     memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
3503
3504     /* Allocate and thread the struct dcache entries themselves */
3505     tdp = afs_Initial_freeDSList =
3506         (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3507     memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
3508 #ifdef  KERNEL_HAVE_PIN
3509     pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles);      /* XXX */
3510     pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles);  /* XXX */
3511     pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3512     pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles);   /* XXX */
3513     pin((char *)tdp, aDentries * sizeof(struct dcache));        /* XXX */
3514     pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize);      /* XXX */
3515     pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize);      /* XXX */
3516     pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles);     /* XXX */
3517     pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles);     /* XXX */
3518 #endif
3519
3520     afs_freeDSList = &tdp[0];
3521     for (i = 0; i < aDentries - 1; i++) {
3522         tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3523         RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3524         RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3525         RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3526     }
3527     tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3528     RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3529     RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3530     RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3531
3532     afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3533         afs_cacheBlocks = ablocks;
3534     afs_ComputeCacheParms();    /* compute parms based on cache size */
3535
3536     afs_dcentries = aDentries;
3537     afs_blocksUsed = 0;
3538     afs_stats_cmperf.cacheBucket0_Discarded = 
3539         afs_stats_cmperf.cacheBucket1_Discarded = 
3540         afs_stats_cmperf.cacheBucket2_Discarded = 0;
3541     afs_DCSizeInit();
3542     QInit(&afs_DLRU);
3543 }
3544
3545 /*
3546  * shutdown_dcache
3547  *
3548  */
3549 void
3550 shutdown_dcache(void)
3551 {
3552     int i;
3553
3554     afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3555     afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3556     afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3557     afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3558     afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3559     afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3560     afs_osi_Free(afs_Initial_freeDSList,
3561                  afs_dcentries * sizeof(struct dcache));
3562 #ifdef  KERNEL_HAVE_PIN
3563     unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3564     unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3565     unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3566     unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3567     unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3568     unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3569     unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3570 #endif
3571
3572
3573     for (i = 0; i < afs_dhashsize; i++) {
3574         afs_dvhashTbl[i] = NULLIDX;
3575         afs_dchashTbl[i] = NULLIDX;
3576     }
3577
3578     afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3579     afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3580
3581     afs_blocksUsed = afs_dcentries = 0;
3582     afs_stats_cmperf.cacheBucket0_Discarded = 
3583         afs_stats_cmperf.cacheBucket1_Discarded = 
3584         afs_stats_cmperf.cacheBucket2_Discarded = 0;
3585     hzero(afs_indexCounter);
3586
3587     afs_freeDCCount = 0;
3588     afs_freeDCList = NULLIDX;
3589     afs_discardDCList = NULLIDX;
3590     afs_freeDSList = afs_Initial_freeDSList = 0;
3591
3592     LOCK_INIT(&afs_xdcache, "afs_xdcache");
3593     QInit(&afs_DLRU);
3594
3595 }
3596
3597 #if defined(AFS_DISCON_ENV)
3598
3599 /*!
3600  * Make a shadow copy of a dir's dcaches. It's used for disconnected
3601  * operations like remove/create/rename to keep the original directory data.
3602  * On reconnection, we can diff the original data with the server and get the
3603  * server changes and with the local data to get the local changes.
3604  *
3605  * \param avc The dir vnode.
3606  *
3607  * \return 0 for success.
3608  *
3609  * \note The only lock allowed to be set is the dir's vcache entry, and it
3610  * must be set in write mode.
3611  * \note The vcache entry must be write locked.
3612  */
3613 int afs_MakeShadowDir(struct vcache *avc)
3614 {
3615     int j, i, index, code, ret_code = 0, offset, trans_size, block;
3616     struct dcache *tdc, *new_dc = NULL;
3617     struct osi_file *tfile_src, *tfile_dst;
3618     struct VenusFid shadow_fid;
3619     char *data;
3620     int lock_held = 0;
3621
3622     /* Is this a dir? */
3623     if (vType(avc) != VDIR)
3624         return ENOTDIR;
3625
3626     /* Generate a fid for the shadow dir. */
3627     shadow_fid.Cell = avc->fid.Cell;
3628     shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3629     afs_GenShadowFid(&shadow_fid);
3630
3631     /* For each dcache, do copy it into a new fresh one. */
3632     i = DVHash(&avc->fid);
3633     for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
3634         /* Making sure that this isn't going to get locked twice. */
3635         if (!lock_held) {
3636             /* XXX: Moved it from outside of the loop.
3637              * Maybe it's not quite okay because of the use of
3638              * dvhashTbl (once) in the for statement.
3639              */
3640             ObtainWriteLock(&afs_xdcache, 716);
3641             lock_held = 1;
3642         }
3643
3644         i = afs_dvnextTbl[index];
3645         if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
3646             tdc = afs_GetDSlot(index, NULL);
3647
3648             ReleaseReadLock(&tdc->tlock);
3649
3650             if (!FidCmp(&tdc->f.fid, &avc->fid)) {
3651
3652                 /* Got a dir's dcache. */
3653                 lock_held = 0;
3654
3655                 /* Get a fresh dcache. */
3656                 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3657
3658                 /* Unlock hash for now. Don't need it during operations on the
3659                  * dcache. Oh, and we can't use it because of the locking
3660                  * hierarchy...
3661                  */
3662                 /* XXX: So much for lock ierarchy, the afs_AllocDCache doesn't
3663                  * respect it.
3664                  */
3665                 //ReleaseWriteLock(&afs_xdcache);
3666
3667                 ObtainReadLock(&tdc->lock);
3668
3669                 /* Set up the new fid. */
3670                 /* Copy interesting data from original dir dcache. */
3671                 new_dc->mflags = tdc->mflags;
3672                 new_dc->dflags = tdc->dflags;
3673                 new_dc->f.modTime = tdc->f.modTime;
3674                 new_dc->f.versionNo = tdc->f.versionNo;
3675                 new_dc->f.states = tdc->f.states;
3676                 new_dc->f.chunk= tdc->f.chunk;
3677                 new_dc->f.chunkBytes = tdc->f.chunkBytes;
3678
3679                 /*
3680                  * Now add to the two hash chains - note that i is still set
3681                  * from the above DCHash call.
3682                  */
3683                 //ObtainWriteLock(&afs_xdcache, 713);
3684
3685                 j = DCHash(&shadow_fid, 0);
3686                 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[j];
3687                 afs_dchashTbl[j] = new_dc->index;
3688
3689                 j = DVHash(&shadow_fid);
3690                 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[j];
3691                 afs_dvhashTbl[j] = new_dc->index;
3692                 afs_MaybeWakeupTruncateDaemon();
3693
3694                 ReleaseWriteLock(&afs_xdcache);
3695
3696                 /* Alloc a 4k block. */
3697                 data = (char *) afs_osi_Alloc(4096);
3698                 if (!data) {
3699                     printf("afs_MakeShadowDir: could not alloc data\n");
3700                     ret_code = ENOMEM;
3701                     goto done;
3702                 }
3703
3704                 /* Open the files. */
3705                 tfile_src = afs_CFileOpen(tdc->f.inode);
3706                 tfile_dst = afs_CFileOpen(new_dc->f.inode);
3707
3708                 /* Init no of blocks to be read and offset. */
3709                 block = (tdc->f.chunkBytes / 4096);
3710                 offset = 0;
3711
3712                 /* And now copy dir dcache data into this dcache,
3713                  * 4k at a time.
3714                  */
3715                 while (block >= 0) {
3716
3717                     /* Last chunk might have less bytes to transfer. */
3718                     if (!block) {
3719                         /* Last block. */
3720                         trans_size = (tdc->f.chunkBytes % 4096);
3721                         if (!trans_size)
3722                             /* An exact no of 4k blocks. */
3723                             break;
3724                     } else
3725                         trans_size = 4096;
3726
3727                     /* Read a chunk from the dcache. */
3728                     code = afs_CFileRead(tfile_src, offset, data, trans_size);
3729                     if (code < trans_size) {
3730                         /* Can't access file, stop doing stuff and return error. */
3731                         ret_code = EIO;
3732                         break;
3733                     }
3734
3735                     /* Write it to the new dcache. */
3736                     code = afs_CFileWrite(tfile_dst, offset, data, trans_size);
3737                     if (code < trans_size) {
3738                         ret_code = EIO;
3739                         break;
3740                     }
3741
3742                     block--;
3743                     offset += 4096;
3744                 }               /* while (block) */
3745
3746                 afs_CFileClose(tfile_dst);
3747                 afs_CFileClose(tfile_src);
3748
3749                 afs_osi_Free(data, 4096);
3750
3751                 ReleaseWriteLock(&new_dc->lock);
3752                 ReleaseReadLock(&tdc->lock);
3753
3754                 afs_PutDCache(new_dc);
3755             }                   /* if dcache fid match */
3756             afs_PutDCache(tdc);
3757         }                       /* if unuiquifier match */
3758     }
3759 done:
3760     if (lock_held)
3761         ReleaseWriteLock(&afs_xdcache);
3762
3763     if (!ret_code) {
3764         if (!avc->ddirty_flags) {
3765             ObtainWriteLock(&afs_DDirtyVCListLock, 763);
3766             AFS_DISCON_ADD_DIRTY(avc);
3767             ReleaseWriteLock(&afs_DDirtyVCListLock);
3768         }
3769         avc->shVnode = shadow_fid.Fid.Vnode;
3770         avc->shUnique = shadow_fid.Fid.Unique;
3771         avc->ddirty_flags |= VDisconShadowed;
3772     }
3773
3774     return ret_code;
3775 }
3776
3777 /*!
3778  * Delete the dcaches of a shadow dir.
3779  *
3780  * \param avc The vcache containing the shadow fid.
3781  *
3782  * \note avc must be write locked.
3783  */
3784 void afs_DeleteShadowDir(struct vcache *avc)
3785 {
3786     struct dcache *tdc;
3787     struct VenusFid shadow_fid;
3788
3789     shadow_fid.Cell = avc->fid.Cell;
3790     shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3791     shadow_fid.Fid.Vnode = avc->shVnode;
3792     shadow_fid.Fid.Unique = avc->shUnique;
3793
3794     tdc = afs_FindDCacheByFid(&shadow_fid);
3795     if (tdc) {
3796         afs_HashOutDCache(tdc, 1);
3797         afs_DiscardDCache(tdc);
3798         afs_PutDCache(tdc);
3799     }
3800     /* Remove shadowed dir flag. */
3801     avc->ddirty_flags &= ~VDisconShadowed;
3802 }
3803 #endif