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