fe9ff64e99a3e4db16425f332cd8f200b58a43f7
[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 if (afs_IsDynrootMount(avc)) {
2409             char *dynrootDir;
2410             int dynrootLen;
2411
2412             afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2413
2414             dynrootDir += Position;
2415             dynrootLen -= Position;
2416             if (size > dynrootLen)
2417                 size = dynrootLen;
2418             if (size < 0)
2419                 size = 0;
2420             code = afs_CFileWrite(file, 0, dynrootDir, size);
2421             afs_PutDynroot();
2422
2423             if (code == size)
2424                 code = 0;
2425             else
2426                 code = -1;
2427
2428             tdc->validPos = Position + size;
2429             afs_CFileTruncate(file, size);      /* prune it */
2430         } else
2431             /*
2432              * Not a dynamic vnode:  do the real fetch.
2433              */
2434             do {
2435                 /*
2436                  * Locks held:
2437                  * avc->lock(R) if setLocks && !slowPass
2438                  * avc->lock(W) if !setLocks || slowPass
2439                  * tdc->lock(W)
2440                  */
2441
2442                 tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
2443                 if (tc) {
2444                     afs_int32 length_hi, length, bytes;
2445 #ifndef AFS_NOSTATS
2446                     numFetchLoops++;
2447                     if (fromReplica)
2448                         (accP->numReplicasAccessed)++;
2449
2450 #endif /* AFS_NOSTATS */
2451                     if (!setLocks || slowPass) {
2452                         avc->callback = tc->srvr->server;
2453                     } else {
2454                         newCallback = tc->srvr->server;
2455                         setNewCallback = 1;
2456                     }
2457                     i = osi_Time();
2458                     RX_AFS_GUNLOCK();
2459                     tcall = rx_NewCall(tc->id);
2460                     RX_AFS_GLOCK();
2461
2462                     XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
2463 #ifdef AFS_64BIT_CLIENT
2464                     length_hi = code = 0;
2465                     if (!afs_serverHasNo64Bit(tc)) {
2466                         tsize = size;
2467                         RX_AFS_GUNLOCK();
2468                         code =
2469                             StartRXAFS_FetchData64(tcall,
2470                                                    (struct AFSFid *)&avc->fid.
2471                                                    Fid, Position, tsize);
2472                         if (code != 0) {
2473                             RX_AFS_GLOCK();
2474                             afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2475                                        ICL_TYPE_POINTER, avc, ICL_TYPE_INT32,
2476                                        code);
2477                         } else {
2478                             bytes =
2479                                 rx_Read(tcall, (char *)&length_hi,
2480                                         sizeof(afs_int32));
2481                             RX_AFS_GLOCK();
2482                             if (bytes == sizeof(afs_int32)) {
2483                                 length_hi = ntohl(length_hi);
2484                             } else {
2485                                 length_hi = 0;
2486                                 code = rx_Error(tcall);
2487                                 RX_AFS_GUNLOCK();
2488                                 code1 = rx_EndCall(tcall, code);
2489                                 RX_AFS_GLOCK();
2490                                 tcall = (struct rx_call *)0;
2491                             }
2492                         }
2493                     }
2494                     if (code == RXGEN_OPCODE || afs_serverHasNo64Bit(tc)) {
2495                         if (Position > 0x7FFFFFFF) {
2496                             code = EFBIG;
2497                         } else {
2498                             afs_int32 pos;
2499                             pos = Position;
2500                             RX_AFS_GUNLOCK();
2501                             if (!tcall)
2502                                 tcall = rx_NewCall(tc->id);
2503                             code =
2504                                 StartRXAFS_FetchData(tcall, (struct AFSFid *)
2505                                                      &avc->fid.Fid, pos,
2506                                                      size);
2507                             RX_AFS_GLOCK();
2508                         }
2509                         afs_serverSetNo64Bit(tc);
2510                     }
2511                     if (code == 0) {
2512                         RX_AFS_GUNLOCK();
2513                         bytes =
2514                             rx_Read(tcall, (char *)&length,
2515                                     sizeof(afs_int32));
2516                         RX_AFS_GLOCK();
2517                         if (bytes == sizeof(afs_int32)) {
2518                             length = ntohl(length);
2519                         } else {
2520                             code = rx_Error(tcall);
2521                         }
2522                     }
2523                     FillInt64(lengthFound, length_hi, length);
2524                     afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64LENG,
2525                                ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
2526                                ICL_TYPE_OFFSET,
2527                                ICL_HANDLE_OFFSET(lengthFound));
2528 #else /* AFS_64BIT_CLIENT */
2529                     RX_AFS_GUNLOCK();
2530                     code =
2531                         StartRXAFS_FetchData(tcall,
2532                                              (struct AFSFid *)&avc->fid.Fid,
2533                                              Position, size);
2534                     RX_AFS_GLOCK();
2535                     if (code == 0) {
2536                         RX_AFS_GUNLOCK();
2537                         bytes =
2538                             rx_Read(tcall, (char *)&length,
2539                                     sizeof(afs_int32));
2540                         RX_AFS_GLOCK();
2541                         if (bytes == sizeof(afs_int32)) {
2542                             length = ntohl(length);
2543                         } else {
2544                             code = rx_Error(tcall);
2545                         }
2546                     }
2547 #endif /* AFS_64BIT_CLIENT */
2548                     if (code == 0) {
2549
2550 #ifndef AFS_NOSTATS
2551                         xferP =
2552                             &(afs_stats_cmfullperf.rpc.
2553                               fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
2554                         osi_GetuTime(&xferStartTime);
2555
2556                         code =
2557                             afs_CacheFetchProc(tcall, file,
2558                                                (afs_size_t) Position, tdc,
2559                                                avc, &bytesToXfer,
2560                                                &bytesXferred, length);
2561
2562                         osi_GetuTime(&xferStopTime);
2563                         (xferP->numXfers)++;
2564                         if (!code) {
2565                             (xferP->numSuccesses)++;
2566                             afs_stats_XferSumBytes
2567                                 [AFS_STATS_FS_XFERIDX_FETCHDATA] +=
2568                                 bytesXferred;
2569                             (xferP->sumBytes) +=
2570                                 (afs_stats_XferSumBytes
2571                                  [AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
2572                             afs_stats_XferSumBytes
2573                                 [AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
2574                             if (bytesXferred < xferP->minBytes)
2575                                 xferP->minBytes = bytesXferred;
2576                             if (bytesXferred > xferP->maxBytes)
2577                                 xferP->maxBytes = bytesXferred;
2578
2579                             /*
2580                              * Tally the size of the object.  Note: we tally the actual size,
2581                              * NOT the number of bytes that made it out over the wire.
2582                              */
2583                             if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
2584                                 (xferP->count[0])++;
2585                             else if (bytesToXfer <=
2586                                      AFS_STATS_MAXBYTES_BUCKET1)
2587                                 (xferP->count[1])++;
2588                             else if (bytesToXfer <=
2589                                      AFS_STATS_MAXBYTES_BUCKET2)
2590                                 (xferP->count[2])++;
2591                             else if (bytesToXfer <=
2592                                      AFS_STATS_MAXBYTES_BUCKET3)
2593                                 (xferP->count[3])++;
2594                             else if (bytesToXfer <=
2595                                      AFS_STATS_MAXBYTES_BUCKET4)
2596                                 (xferP->count[4])++;
2597                             else if (bytesToXfer <=
2598                                      AFS_STATS_MAXBYTES_BUCKET5)
2599                                 (xferP->count[5])++;
2600                             else if (bytesToXfer <=
2601                                      AFS_STATS_MAXBYTES_BUCKET6)
2602                                 (xferP->count[6])++;
2603                             else if (bytesToXfer <=
2604                                      AFS_STATS_MAXBYTES_BUCKET7)
2605                                 (xferP->count[7])++;
2606                             else
2607                                 (xferP->count[8])++;
2608
2609                             afs_stats_GetDiff(elapsedTime, xferStartTime,
2610                                               xferStopTime);
2611                             afs_stats_AddTo((xferP->sumTime), elapsedTime);
2612                             afs_stats_SquareAddTo((xferP->sqrTime),
2613                                                   elapsedTime);
2614                             if (afs_stats_TimeLessThan
2615                                 (elapsedTime, (xferP->minTime))) {
2616                                 afs_stats_TimeAssign((xferP->minTime),
2617                                                      elapsedTime);
2618                             }
2619                             if (afs_stats_TimeGreaterThan
2620                                 (elapsedTime, (xferP->maxTime))) {
2621                                 afs_stats_TimeAssign((xferP->maxTime),
2622                                                      elapsedTime);
2623                             }
2624                         }
2625 #else
2626                         code =
2627                             afs_CacheFetchProc(tcall, file, Position, tdc,
2628                                                avc, 0, 0, length);
2629 #endif /* AFS_NOSTATS */
2630                     }
2631                     if (code == 0) {
2632                         RX_AFS_GUNLOCK();
2633                         code =
2634                             EndRXAFS_FetchData(tcall, &tsmall->OutStatus,
2635                                                &tsmall->CallBack,
2636                                                &tsmall->tsync);
2637                         RX_AFS_GLOCK();
2638                     }
2639                     XSTATS_END_TIME;
2640                     RX_AFS_GUNLOCK();
2641                     if (tcall)
2642                         code1 = rx_EndCall(tcall, code);
2643                     RX_AFS_GLOCK();
2644                 } else {
2645                     code = -1;
2646                 }
2647                 if (!code && code1)
2648                     code = code1;
2649
2650                 if (code == 0) {
2651                     /* callback could have been broken (or expired) in a race here, 
2652                      * but we return the data anyway.  It's as good as we knew about
2653                      * when we started. */
2654                     /* 
2655                      * validPos is updated by CacheFetchProc, and can only be 
2656                      * modifed under a dcache write lock, which we've blocked out 
2657                      */
2658                     size = tdc->validPos - Position;    /* actual segment size */
2659                     if (size < 0)
2660                         size = 0;
2661                     afs_CFileTruncate(file, size);      /* prune it */
2662                 } else {
2663                     if (!setLocks || slowPass) {
2664                         ObtainWriteLock(&afs_xcbhash, 453);
2665                         afs_DequeueCallback(avc);
2666                         avc->states &= ~(CStatd | CUnique);
2667                         avc->callback = NULL;
2668                         ReleaseWriteLock(&afs_xcbhash);
2669                         if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2670                             osi_dnlc_purgedp(avc);
2671                     } else {
2672                         /* Something lost.  Forget about performance, and go
2673                          * back with a vcache write lock.
2674                          */
2675                         afs_CFileTruncate(file, 0);
2676                         afs_AdjustSize(tdc, 0);
2677                         afs_CFileClose(file);
2678                         osi_FreeLargeSpace(tsmall);
2679                         tsmall = 0;
2680                         ReleaseWriteLock(&tdc->lock);
2681                         afs_PutDCache(tdc);
2682                         tdc = 0;
2683                         ReleaseReadLock(&avc->lock);
2684                         slowPass = 1;
2685                         goto RetryGetDCache;
2686                     }
2687                 }
2688
2689             } while (afs_Analyze
2690                      (tc, code, &avc->fid, areq,
2691                       AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2692
2693         /*
2694          * Locks held:
2695          * avc->lock(R) if setLocks && !slowPass
2696          * avc->lock(W) if !setLocks || slowPass
2697          * tdc->lock(W)
2698          */
2699
2700 #ifndef AFS_NOSTATS
2701         /*
2702          * In the case of replicated access, jot down info on the number of
2703          * attempts it took before we got through or gave up.
2704          */
2705         if (fromReplica) {
2706             if (numFetchLoops <= 1)
2707                 (accP->refFirstReplicaOK)++;
2708             if (numFetchLoops > accP->maxReplicasPerRef)
2709                 accP->maxReplicasPerRef = numFetchLoops;
2710         }
2711 #endif /* AFS_NOSTATS */
2712
2713         tdc->dflags &= ~DFFetching;
2714         if (afs_osi_Wakeup(&tdc->validPos) == 0)
2715             afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2716                        __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2717                        tdc, ICL_TYPE_INT32, tdc->dflags);
2718         if (avc->execsOrWriters == 0)
2719             tdc->f.states &= ~DWriting;
2720
2721         /* now, if code != 0, we have an error and should punt.
2722          * note that we have the vcache write lock, either because
2723          * !setLocks or slowPass.
2724          */
2725         if (code) {
2726             afs_CFileTruncate(file, 0);
2727             afs_AdjustSize(tdc, 0);
2728             afs_CFileClose(file);
2729             ZapDCE(tdc);        /* sets DFEntryMod */
2730             if (vType(avc) == VDIR) {
2731                 DZap(tdc);
2732             }
2733             tdc->f.states &= ~(DRO|DBackup|DRW);
2734             afs_DCMoveBucket(tdc, 0, 0);
2735             ReleaseWriteLock(&tdc->lock);
2736             afs_PutDCache(tdc);
2737             if (!afs_IsDynroot(avc)) {
2738                 ObtainWriteLock(&afs_xcbhash, 454);
2739                 afs_DequeueCallback(avc);
2740                 avc->states &= ~(CStatd | CUnique);
2741                 ReleaseWriteLock(&afs_xcbhash);
2742                 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2743                     osi_dnlc_purgedp(avc);
2744                 /*
2745                  * Locks held:
2746                  * avc->lock(W); assert(!setLocks || slowPass)
2747                  */
2748                 osi_Assert(!setLocks || slowPass);
2749             }
2750             tdc->f.states &= ~(DRO|DBackup|DRW);
2751             afs_DCMoveBucket(tdc, 0, 0);
2752             tdc = NULL;
2753             goto done;
2754         }
2755
2756         /* otherwise we copy in the just-fetched info */
2757         afs_CFileClose(file);
2758         afs_AdjustSize(tdc, size);      /* new size */
2759         /*
2760          * Copy appropriate fields into vcache.  Status is
2761          * copied later where we selectively acquire the
2762          * vcache write lock.
2763          */
2764         if (slowPass)
2765             afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2766         else
2767             setVcacheStatus = 1;
2768         hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2769                tsmall->OutStatus.DataVersion);
2770         tdc->dflags |= DFEntryMod;
2771         afs_indexFlags[tdc->index] |= IFEverUsed;
2772         ConvertWToSLock(&tdc->lock);
2773     } /*Data version numbers don't match */
2774     else {
2775         /*
2776          * Data version numbers match.
2777          */
2778         afs_stats_cmperf.dcacheHits++;
2779     }                           /*Data version numbers match */
2780
2781     updateV2DC(setLocks, avc, tdc, 335);        /* set hint */
2782   done:
2783     /*
2784      * Locks held:
2785      * avc->lock(R) if setLocks && !slowPass
2786      * avc->lock(W) if !setLocks || slowPass
2787      * tdc->lock(S) if tdc
2788      */
2789
2790     /*
2791      * See if this was a reference to a file in the local cell.
2792      */
2793     if (afs_IsPrimaryCellNum(avc->fid.Cell))
2794         afs_stats_cmperf.dlocalAccesses++;
2795     else
2796         afs_stats_cmperf.dremoteAccesses++;
2797
2798     /* Fix up LRU info */
2799
2800     if (tdc) {
2801         MObtainWriteLock(&afs_xdcache, 602);
2802         hset(afs_indexTimes[tdc->index], afs_indexCounter);
2803         hadd32(afs_indexCounter, 1);
2804         MReleaseWriteLock(&afs_xdcache);
2805
2806         /* return the data */
2807         if (vType(avc) == VDIR)
2808             *aoffset = abyte;
2809         else
2810             *aoffset = AFS_CHUNKOFFSET(abyte);
2811         *alen = (tdc->f.chunkBytes - *aoffset);
2812         ReleaseSharedLock(&tdc->lock);
2813     }
2814
2815     /*
2816      * Locks held:
2817      * avc->lock(R) if setLocks && !slowPass
2818      * avc->lock(W) if !setLocks || slowPass
2819      */
2820
2821     /* Fix up the callback and status values in the vcache */
2822     doVcacheUpdate = 0;
2823     if (setLocks && !slowPass) {
2824         /* DCLOCKXXX
2825          *
2826          * This is our dirty little secret to parallel fetches.
2827          * We don't write-lock the vcache while doing the fetch,
2828          * but potentially we'll need to update the vcache after
2829          * the fetch is done.
2830          *
2831          * Drop the read lock and try to re-obtain the write
2832          * lock.  If the vcache still has the same DV, it's
2833          * ok to go ahead and install the new data.
2834          */
2835         afs_hyper_t currentDV, statusDV;
2836
2837         hset(currentDV, avc->m.DataVersion);
2838
2839         if (setNewCallback && avc->callback != newCallback)
2840             doVcacheUpdate = 1;
2841
2842         if (tsmall) {
2843             hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2844                    tsmall->OutStatus.DataVersion);
2845
2846             if (setVcacheStatus && avc->m.Length != tsmall->OutStatus.Length)
2847                 doVcacheUpdate = 1;
2848             if (setVcacheStatus && !hsame(currentDV, statusDV))
2849                 doVcacheUpdate = 1;
2850         }
2851
2852         ReleaseReadLock(&avc->lock);
2853
2854         if (doVcacheUpdate) {
2855             ObtainWriteLock(&avc->lock, 615);
2856             if (!hsame(avc->m.DataVersion, currentDV)) {
2857                 /* We lose.  Someone will beat us to it. */
2858                 doVcacheUpdate = 0;
2859                 ReleaseWriteLock(&avc->lock);
2860             }
2861         }
2862     }
2863
2864     /* With slow pass, we've already done all the updates */
2865     if (slowPass) {
2866         ReleaseWriteLock(&avc->lock);
2867     }
2868
2869     /* Check if we need to perform any last-minute fixes with a write-lock */
2870     if (!setLocks || doVcacheUpdate) {
2871         if (setNewCallback)
2872             avc->callback = newCallback;
2873         if (tsmall && setVcacheStatus)
2874             afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2875         if (setLocks)
2876             ReleaseWriteLock(&avc->lock);
2877     }
2878
2879     if (tsmall)
2880         osi_FreeLargeSpace(tsmall);
2881
2882     return tdc;
2883 }                               /*afs_GetDCache */
2884
2885
2886 /*
2887  * afs_WriteThroughDSlots
2888  *
2889  * Description:
2890  *      Sweep through the dcache slots and write out any modified
2891  *      in-memory data back on to our caching store.
2892  *
2893  * Parameters:
2894  *      None.
2895  *
2896  * Environment:
2897  *      The afs_xdcache is write-locked through this whole affair.
2898  */
2899 void
2900 afs_WriteThroughDSlots(void)
2901 {
2902     register struct dcache *tdc;
2903     register afs_int32 i, touchedit = 0;
2904
2905     struct afs_q DirtyQ, *tq;
2906
2907     AFS_STATCNT(afs_WriteThroughDSlots);
2908
2909     /*
2910      * Because of lock ordering, we can't grab dcache locks while
2911      * holding afs_xdcache.  So we enter xdcache, get a reference
2912      * for every dcache entry, and exit xdcache.
2913      */
2914     MObtainWriteLock(&afs_xdcache, 283);
2915     QInit(&DirtyQ);
2916     for (i = 0; i < afs_cacheFiles; i++) {
2917         tdc = afs_indexTable[i];
2918
2919         /* Grab tlock in case the existing refcount isn't zero */
2920         if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2921             ObtainWriteLock(&tdc->tlock, 623);
2922             tdc->refCount++;
2923             ReleaseWriteLock(&tdc->tlock);
2924
2925             QAdd(&DirtyQ, &tdc->dirty);
2926         }
2927     }
2928     MReleaseWriteLock(&afs_xdcache);
2929
2930     /*
2931      * Now, for each dcache entry we found, check if it's dirty.
2932      * If so, get write-lock, get afs_xdcache, which protects
2933      * afs_cacheInodep, and flush it.  Don't forget to put back
2934      * the refcounts.
2935      */
2936
2937 #define DQTODC(q)       ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2938
2939     for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2940         tdc = DQTODC(tq);
2941         if (tdc->dflags & DFEntryMod) {
2942             int wrLock;
2943
2944             wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2945
2946             /* Now that we have the write lock, double-check */
2947             if (wrLock && (tdc->dflags & DFEntryMod)) {
2948                 tdc->dflags &= ~DFEntryMod;
2949                 MObtainWriteLock(&afs_xdcache, 620);
2950                 afs_WriteDCache(tdc, 1);
2951                 MReleaseWriteLock(&afs_xdcache);
2952                 touchedit = 1;
2953             }
2954             if (wrLock)
2955                 ReleaseWriteLock(&tdc->lock);
2956         }
2957
2958         afs_PutDCache(tdc);
2959     }
2960
2961     MObtainWriteLock(&afs_xdcache, 617);
2962     if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2963         /* Touch the file to make sure that the mtime on the file is kept
2964          * up-to-date to avoid losing cached files on cold starts because
2965          * their mtime seems old...
2966          */
2967         struct afs_fheader theader;
2968
2969         theader.magic = AFS_FHMAGIC;
2970         theader.firstCSize = AFS_FIRSTCSIZE;
2971         theader.otherCSize = AFS_OTHERCSIZE;
2972         theader.version = AFS_CI_VERSION;
2973         afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2974     }
2975     MReleaseWriteLock(&afs_xdcache);
2976 }
2977
2978 /*
2979  * afs_MemGetDSlot
2980  *
2981  * Description:
2982  *      Return a pointer to an freshly initialized dcache entry using
2983  *      a memory-based cache.  The tlock will be read-locked.
2984  *
2985  * Parameters:
2986  *      aslot : Dcache slot to look at.
2987  *      tmpdc : Ptr to dcache entry.
2988  *
2989  * Environment:
2990  *      Must be called with afs_xdcache write-locked.
2991  */
2992
2993 struct dcache *
2994 afs_MemGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2995 {
2996     register struct dcache *tdc;
2997     int existing = 0;
2998
2999     AFS_STATCNT(afs_MemGetDSlot);
3000     if (CheckLock(&afs_xdcache) != -1)
3001         osi_Panic("getdslot nolock");
3002     if (aslot < 0 || aslot >= afs_cacheFiles)
3003         osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3004     tdc = afs_indexTable[aslot];
3005     if (tdc) {
3006         QRemove(&tdc->lruq);    /* move to queue head */
3007         QAdd(&afs_DLRU, &tdc->lruq);
3008         /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
3009         ObtainWriteLock(&tdc->tlock, 624);
3010         tdc->refCount++;
3011         ConvertWToRLock(&tdc->tlock);
3012         return tdc;
3013     }
3014     if (tmpdc == NULL) {
3015         if (!afs_freeDSList)
3016             afs_GetDownDSlot(4);
3017         if (!afs_freeDSList) {
3018             /* none free, making one is better than a panic */
3019             afs_stats_cmperf.dcacheXAllocs++;   /* count in case we have a leak */
3020             tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
3021 #ifdef  KERNEL_HAVE_PIN
3022             pin((char *)tdc, sizeof(struct dcache));    /* XXX */
3023 #endif
3024         } else {
3025             tdc = afs_freeDSList;
3026             afs_freeDSList = (struct dcache *)tdc->lruq.next;
3027             existing = 1;
3028         }
3029         tdc->dflags = 0;        /* up-to-date, not in free q */
3030         tdc->mflags = 0;
3031         QAdd(&afs_DLRU, &tdc->lruq);
3032         if (tdc->lruq.prev == &tdc->lruq)
3033             osi_Panic("lruq 3");
3034     } else {
3035         tdc = tmpdc;
3036         tdc->f.states = 0;
3037     }
3038
3039     /* initialize entry */
3040     tdc->f.fid.Cell = 0;
3041     tdc->f.fid.Fid.Volume = 0;
3042     tdc->f.chunk = -1;
3043     hones(tdc->f.versionNo);
3044     tdc->f.inode = aslot;
3045     tdc->dflags |= DFEntryMod;
3046     tdc->refCount = 1;
3047     tdc->index = aslot;
3048     afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3049
3050     if (existing) {
3051         osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3052         osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3053         osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3054     }
3055
3056     RWLOCK_INIT(&tdc->lock, "dcache lock");
3057     RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3058     RWLOCK_INIT(&tdc->mflock, "dcache flock");
3059     ObtainReadLock(&tdc->tlock);
3060
3061     if (tmpdc == NULL)
3062         afs_indexTable[aslot] = tdc;
3063     return tdc;
3064
3065 }                               /*afs_MemGetDSlot */
3066
3067 unsigned int last_error = 0, lasterrtime = 0;
3068
3069 /*
3070  * afs_UFSGetDSlot
3071  *
3072  * Description:
3073  *      Return a pointer to an freshly initialized dcache entry using
3074  *      a UFS-based disk cache.  The dcache tlock will be read-locked.
3075  *
3076  * Parameters:
3077  *      aslot : Dcache slot to look at.
3078  *      tmpdc : Ptr to dcache entry.
3079  *
3080  * Environment:
3081  *      afs_xdcache lock write-locked.
3082  */
3083 struct dcache *
3084 afs_UFSGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
3085 {
3086     register afs_int32 code;
3087     register struct dcache *tdc;
3088     int existing = 0;
3089     int entryok;
3090
3091     AFS_STATCNT(afs_UFSGetDSlot);
3092     if (CheckLock(&afs_xdcache) != -1)
3093         osi_Panic("getdslot nolock");
3094     if (aslot < 0 || aslot >= afs_cacheFiles)
3095         osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3096     tdc = afs_indexTable[aslot];
3097     if (tdc) {
3098         QRemove(&tdc->lruq);    /* move to queue head */
3099         QAdd(&afs_DLRU, &tdc->lruq);
3100         /* Grab tlock in case refCount != 0 */
3101         ObtainWriteLock(&tdc->tlock, 625);
3102         tdc->refCount++;
3103         ConvertWToRLock(&tdc->tlock);
3104         return tdc;
3105     }
3106     /* otherwise we should read it in from the cache file */
3107     /*
3108      * If we weren't passed an in-memory region to place the file info,
3109      * we have to allocate one.
3110      */
3111     if (tmpdc == NULL) {
3112         if (!afs_freeDSList)
3113             afs_GetDownDSlot(4);
3114         if (!afs_freeDSList) {
3115             /* none free, making one is better than a panic */
3116             afs_stats_cmperf.dcacheXAllocs++;   /* count in case we have a leak */
3117             tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
3118 #ifdef  KERNEL_HAVE_PIN
3119             pin((char *)tdc, sizeof(struct dcache));    /* XXX */
3120 #endif
3121         } else {
3122             tdc = afs_freeDSList;
3123             afs_freeDSList = (struct dcache *)tdc->lruq.next;
3124             existing = 1;
3125         }
3126         tdc->dflags = 0;        /* up-to-date, not in free q */
3127         tdc->mflags = 0;
3128         QAdd(&afs_DLRU, &tdc->lruq);
3129         if (tdc->lruq.prev == &tdc->lruq)
3130             osi_Panic("lruq 3");
3131     } else {
3132         tdc = tmpdc;
3133         tdc->f.states = 0;
3134     }
3135
3136     /*
3137      * Seek to the aslot'th entry and read it in.
3138      */
3139     code =
3140         afs_osi_Read(afs_cacheInodep,
3141                      sizeof(struct fcache) * aslot +
3142                      sizeof(struct afs_fheader), (char *)(&tdc->f),
3143                      sizeof(struct fcache));
3144     entryok = 1;
3145     if (code != sizeof(struct fcache))
3146         entryok = 0;
3147     if (!afs_CellNumValid(tdc->f.fid.Cell))
3148         entryok = 0;
3149
3150     if (!entryok) {
3151         tdc->f.fid.Cell = 0;
3152         tdc->f.fid.Fid.Volume = 0;
3153         tdc->f.chunk = -1;
3154         hones(tdc->f.versionNo);
3155         tdc->dflags |= DFEntryMod;
3156 #if defined(KERNEL_HAVE_UERROR)
3157         last_error = getuerror();
3158 #endif
3159         lasterrtime = osi_Time();
3160         afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3161         tdc->f.states &= ~(DRO|DBackup|DRW);
3162         afs_DCMoveBucket(tdc, 0, 0);
3163     } else {
3164         if (&tdc->f != 0) {
3165             if (tdc->f.states & DRO) {
3166                 afs_DCMoveBucket(tdc, 0, 2);
3167             } else if (tdc->f.states & DBackup) {
3168                 afs_DCMoveBucket(tdc, 0, 1);
3169             } else {
3170                 afs_DCMoveBucket(tdc, 0, 1); 
3171             }
3172         } 
3173     }
3174     tdc->refCount = 1;
3175     tdc->index = aslot;
3176     if (tdc->f.chunk >= 0)
3177         tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
3178     else
3179         tdc->validPos = 0;
3180
3181     if (existing) {
3182         osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3183         osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3184         osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3185     }
3186
3187     RWLOCK_INIT(&tdc->lock, "dcache lock");
3188     RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3189     RWLOCK_INIT(&tdc->mflock, "dcache flock");
3190     ObtainReadLock(&tdc->tlock);
3191
3192     /*
3193      * If we didn't read into a temporary dcache region, update the
3194      * slot pointer table.
3195      */
3196     if (tmpdc == NULL)
3197         afs_indexTable[aslot] = tdc;
3198     return tdc;
3199
3200 }                               /*afs_UFSGetDSlot */
3201
3202
3203
3204 /*!
3205  * Write a particular dcache entry back to its home in the
3206  * CacheInfo file.
3207  *
3208  * \param adc Pointer to the dcache entry to write.
3209  * \param atime If true, set the modtime on the file to the current time.
3210  *
3211  * \note Environment:
3212  *      Must be called with the afs_xdcache lock at least read-locked,
3213  *      and dcache entry at least read-locked.
3214  *      The reference count is not changed.
3215  */
3216
3217 int
3218 afs_WriteDCache(register struct dcache *adc, int atime)
3219 {
3220     register afs_int32 code;
3221
3222     if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3223         return 0;
3224     AFS_STATCNT(afs_WriteDCache);
3225     osi_Assert(WriteLocked(&afs_xdcache));
3226     if (atime)
3227         adc->f.modTime = osi_Time();
3228     /*
3229      * Seek to the right dcache slot and write the in-memory image out to disk.
3230      */
3231     afs_cellname_write();
3232     code =
3233         afs_osi_Write(afs_cacheInodep,
3234                       sizeof(struct fcache) * adc->index +
3235                       sizeof(struct afs_fheader), (char *)(&adc->f),
3236                       sizeof(struct fcache));
3237     if (code != sizeof(struct fcache))
3238         return EIO;
3239     return 0;
3240 }
3241
3242
3243
3244 /*!
3245  * Wake up users of a particular file waiting for stores to take
3246  * place.
3247  *
3248  * \param avc Ptr to related vcache entry.
3249  *
3250  * \note Environment:
3251  *      Nothing interesting.
3252  */
3253 int
3254 afs_wakeup(register struct vcache *avc)
3255 {
3256     register int i;
3257     register struct brequest *tb;
3258     tb = afs_brs;
3259     AFS_STATCNT(afs_wakeup);
3260     for (i = 0; i < NBRS; i++, tb++) {
3261         /* if request is valid and for this file, we've found it */
3262         if (tb->refCount > 0 && avc == tb->vc) {
3263
3264             /*
3265              * If CSafeStore is on, then we don't awaken the guy
3266              * waiting for the store until the whole store has finished.
3267              * Otherwise, we do it now.  Note that if CSafeStore is on,
3268              * the BStore routine actually wakes up the user, instead
3269              * of us.
3270              * I think this is redundant now because this sort of thing
3271              * is already being handled by the higher-level code.
3272              */
3273             if ((avc->states & CSafeStore) == 0) {
3274                 tb->code = 0;
3275                 tb->flags |= BUVALID;
3276                 if (tb->flags & BUWAIT) {
3277                     tb->flags &= ~BUWAIT;
3278                     afs_osi_Wakeup(tb);
3279                 }
3280             }
3281             break;
3282         }
3283     }
3284     return 0;
3285 }
3286
3287
3288 /*!
3289  * Given a file name and inode, set up that file to be an
3290  * active member in the AFS cache.  This also involves checking
3291  * the usability of its data.
3292  *
3293  * \param afile Name of the cache file to initialize.
3294  * \param ainode Inode of the file.
3295  *
3296  * \note Environment:
3297  *      This function is called only during initialization.
3298  */
3299 int
3300 afs_InitCacheFile(char *afile, ino_t ainode)
3301 {
3302     register afs_int32 code;
3303 #if defined(AFS_LINUX22_ENV)
3304     struct dentry *filevp;
3305 #else
3306     struct vnode *filevp;
3307 #endif
3308     afs_int32 index;
3309     int fileIsBad;
3310     struct osi_file *tfile;
3311     struct osi_stat tstat;
3312     register struct dcache *tdc;
3313
3314     AFS_STATCNT(afs_InitCacheFile);
3315     index = afs_stats_cmperf.cacheNumEntries;
3316     if (index >= afs_cacheFiles)
3317         return EINVAL;
3318
3319     MObtainWriteLock(&afs_xdcache, 282);
3320     tdc = afs_GetDSlot(index, NULL);
3321     ReleaseReadLock(&tdc->tlock);
3322     MReleaseWriteLock(&afs_xdcache);
3323
3324     ObtainWriteLock(&tdc->lock, 621);
3325     MObtainWriteLock(&afs_xdcache, 622);
3326     if (afile) {
3327         code = gop_lookupname(afile, AFS_UIOSYS, 0, &filevp);
3328         if (code) {
3329             ReleaseWriteLock(&afs_xdcache);
3330             ReleaseWriteLock(&tdc->lock);
3331             afs_PutDCache(tdc);
3332             return code;
3333         }
3334         /*
3335          * We have a VN_HOLD on filevp.  Get the useful info out and
3336          * return.  We make use of the fact that the cache is in the
3337          * UFS file system, and just record the inode number.
3338          */
3339 #ifdef AFS_LINUX22_ENV
3340         tdc->f.inode = VTOI(filevp->d_inode)->i_number;
3341         dput(filevp);
3342 #else
3343         tdc->f.inode = afs_vnodeToInumber(filevp);
3344         AFS_RELE(filevp);
3345 #endif /* AFS_LINUX22_ENV */
3346     } else {
3347         tdc->f.inode = ainode;
3348     }
3349     fileIsBad = 0;
3350     if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3351         fileIsBad = 1;
3352     tfile = osi_UFSOpen(tdc->f.inode);
3353     code = afs_osi_Stat(tfile, &tstat);
3354     if (code)
3355         osi_Panic("initcachefile stat");
3356
3357     /*
3358      * If file size doesn't match the cache info file, it's probably bad.
3359      */
3360     if (tdc->f.chunkBytes != tstat.size)
3361         fileIsBad = 1;
3362     tdc->f.chunkBytes = 0;
3363
3364     /*
3365      * If file changed within T (120?) seconds of cache info file, it's
3366      * probably bad.  In addition, if slot changed within last T seconds,
3367      * the cache info file may be incorrectly identified, and so slot
3368      * may be bad.
3369      */
3370     if (cacheInfoModTime < tstat.mtime + 120)
3371         fileIsBad = 1;
3372     if (cacheInfoModTime < tdc->f.modTime + 120)
3373         fileIsBad = 1;
3374     /* In case write through is behind, make sure cache items entry is
3375      * at least as new as the chunk.
3376      */
3377     if (tdc->f.modTime < tstat.mtime)
3378         fileIsBad = 1;
3379     if (fileIsBad) {
3380         tdc->f.fid.Fid.Volume = 0;      /* not in the hash table */
3381         if (tstat.size != 0)
3382             osi_UFSTruncate(tfile, 0);
3383         tdc->f.states &= ~(DRO|DBackup|DRW);
3384         afs_DCMoveBucket(tdc, 0, 0);
3385         /* put entry in free cache slot list */
3386         afs_dvnextTbl[tdc->index] = afs_freeDCList;
3387         afs_freeDCList = index;
3388         afs_freeDCCount++;
3389         afs_indexFlags[index] |= IFFree;
3390         afs_indexUnique[index] = 0;
3391     } else {
3392         /*
3393          * We must put this entry in the appropriate hash tables.
3394          * Note that i is still set from the above DCHash call
3395          */
3396         code = DCHash(&tdc->f.fid, tdc->f.chunk);
3397         afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3398         afs_dchashTbl[code] = tdc->index;
3399         code = DVHash(&tdc->f.fid);
3400         afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3401         afs_dvhashTbl[code] = tdc->index;
3402         afs_AdjustSize(tdc, tstat.size);        /* adjust to new size */
3403         if (tstat.size > 0)
3404             /* has nontrivial amt of data */
3405             afs_indexFlags[index] |= IFEverUsed;
3406         afs_stats_cmperf.cacheFilesReused++;
3407         /*
3408          * Initialize index times to file's mod times; init indexCounter
3409          * to max thereof
3410          */
3411         hset32(afs_indexTimes[index], tstat.atime);
3412         if (hgetlo(afs_indexCounter) < tstat.atime) {
3413             hset32(afs_indexCounter, tstat.atime);
3414         }
3415         afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3416     }                           /*File is not bad */
3417
3418     osi_UFSClose(tfile);
3419     tdc->f.states &= ~DWriting;
3420     tdc->dflags &= ~DFEntryMod;
3421     /* don't set f.modTime; we're just cleaning up */
3422     afs_WriteDCache(tdc, 0);
3423     ReleaseWriteLock(&afs_xdcache);
3424     ReleaseWriteLock(&tdc->lock);
3425     afs_PutDCache(tdc);
3426     afs_stats_cmperf.cacheNumEntries++;
3427     return 0;
3428 }
3429
3430
3431 /*Max # of struct dcache's resident at any time*/
3432 /*
3433  * If 'dchint' is enabled then in-memory dcache min is increased because of
3434  * crashes...
3435  */
3436 #define DDSIZE 200
3437
3438 /*!
3439  * Initialize dcache related variables.
3440  *
3441  * \param afiles
3442  * \param ablocks 
3443  * \param aDentries
3444  * \param achunk
3445  * \param aflags
3446  *
3447  */
3448 void
3449 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3450 {
3451     register struct dcache *tdp;
3452     int i;
3453     int code;
3454
3455     afs_freeDCList = NULLIDX;
3456     afs_discardDCList = NULLIDX;
3457     afs_freeDCCount = 0;
3458     afs_freeDSList = NULL;
3459     hzero(afs_indexCounter);
3460
3461     LOCK_INIT(&afs_xdcache, "afs_xdcache");
3462
3463     /*
3464      * Set chunk size
3465      */
3466     if (achunk) {
3467         if (achunk < 0 || achunk > 30)
3468             achunk = 13;        /* Use default */
3469         AFS_SETCHUNKSIZE(achunk);
3470     }
3471
3472     if (!aDentries)
3473         aDentries = DDSIZE;
3474
3475     if (aflags & AFSCALL_INIT_MEMCACHE) {
3476         /*
3477          * Use a memory cache instead of a disk cache
3478          */
3479         cacheDiskType = AFS_FCACHE_TYPE_MEM;
3480         afs_cacheType = &afs_MemCacheOps;
3481         afiles = (afiles < aDentries) ? afiles : aDentries;     /* min */
3482         ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3483         /* ablocks is reported in 1K blocks */
3484         code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3485         if (code != 0) {
3486             printf("afsd: memory cache too large for available memory.\n");
3487             printf("afsd: AFS files cannot be accessed.\n\n");
3488             dcacheDisabled = 1;
3489             afiles = ablocks = 0;
3490         } else
3491             printf("Memory cache: Allocating %d dcache entries...",
3492                    aDentries);
3493     } else {
3494         cacheDiskType = AFS_FCACHE_TYPE_UFS;
3495         afs_cacheType = &afs_UfsCacheOps;
3496     }
3497
3498     if (aDentries > 512)
3499         afs_dhashsize = 2048;
3500     /* initialize hash tables */
3501     afs_dvhashTbl =
3502         (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3503     afs_dchashTbl =
3504         (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3505     for (i = 0; i < afs_dhashsize; i++) {
3506         afs_dvhashTbl[i] = NULLIDX;
3507         afs_dchashTbl[i] = NULLIDX;
3508     }
3509     afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3510     afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3511     for (i = 0; i < afiles; i++) {
3512         afs_dvnextTbl[i] = NULLIDX;
3513         afs_dcnextTbl[i] = NULLIDX;
3514     }
3515
3516     /* Allocate and zero the pointer array to the dcache entries */
3517     afs_indexTable = (struct dcache **)
3518         afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3519     memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3520     afs_indexTimes =
3521         (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3522     memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3523     afs_indexUnique =
3524         (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3525     memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3526     afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3527     memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
3528
3529     /* Allocate and thread the struct dcache entries themselves */
3530     tdp = afs_Initial_freeDSList =
3531         (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3532     memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
3533 #ifdef  KERNEL_HAVE_PIN
3534     pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles);      /* XXX */
3535     pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles);  /* XXX */
3536     pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3537     pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles);   /* XXX */
3538     pin((char *)tdp, aDentries * sizeof(struct dcache));        /* XXX */
3539     pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize);      /* XXX */
3540     pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize);      /* XXX */
3541     pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles);     /* XXX */
3542     pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles);     /* XXX */
3543 #endif
3544
3545     afs_freeDSList = &tdp[0];
3546     for (i = 0; i < aDentries - 1; i++) {
3547         tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3548         RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3549         RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3550         RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3551     }
3552     tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3553     RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3554     RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3555     RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3556
3557     afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3558         afs_cacheBlocks = ablocks;
3559     afs_ComputeCacheParms();    /* compute parms based on cache size */
3560
3561     afs_dcentries = aDentries;
3562     afs_blocksUsed = 0;
3563     afs_stats_cmperf.cacheBucket0_Discarded = 
3564         afs_stats_cmperf.cacheBucket1_Discarded = 
3565         afs_stats_cmperf.cacheBucket2_Discarded = 0;
3566     afs_DCSizeInit();
3567     QInit(&afs_DLRU);
3568 }
3569
3570 /*!
3571  * Shuts down the cache.
3572  *
3573  */
3574 void
3575 shutdown_dcache(void)
3576 {
3577     int i;
3578
3579     afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3580     afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3581     afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3582     afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3583     afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3584     afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3585     afs_osi_Free(afs_Initial_freeDSList,
3586                  afs_dcentries * sizeof(struct dcache));
3587 #ifdef  KERNEL_HAVE_PIN
3588     unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3589     unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3590     unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3591     unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3592     unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3593     unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3594     unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3595 #endif
3596
3597
3598     for (i = 0; i < afs_dhashsize; i++) {
3599         afs_dvhashTbl[i] = NULLIDX;
3600         afs_dchashTbl[i] = NULLIDX;
3601     }
3602
3603     afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3604     afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3605
3606     afs_blocksUsed = afs_dcentries = 0;
3607     afs_stats_cmperf.cacheBucket0_Discarded = 
3608         afs_stats_cmperf.cacheBucket1_Discarded = 
3609         afs_stats_cmperf.cacheBucket2_Discarded = 0;
3610     hzero(afs_indexCounter);
3611
3612     afs_freeDCCount = 0;
3613     afs_freeDCList = NULLIDX;
3614     afs_discardDCList = NULLIDX;
3615     afs_freeDSList = afs_Initial_freeDSList = 0;
3616
3617     LOCK_INIT(&afs_xdcache, "afs_xdcache");
3618     QInit(&afs_DLRU);
3619
3620 }
3621
3622 #if defined(AFS_DISCON_ENV)
3623
3624 /*!
3625  * Make a shadow copy of a dir's dcaches. It's used for disconnected
3626  * operations like remove/create/rename to keep the original directory data.
3627  * On reconnection, we can diff the original data with the server and get the
3628  * server changes and with the local data to get the local changes.
3629  *
3630  * \param avc The dir vnode.
3631  *
3632  * \return 0 for success.
3633  *
3634  * \note The only lock allowed to be set is the dir's vcache entry, and it
3635  * must be set in write mode.
3636  * \note The vcache entry must be write locked.
3637  */
3638 int afs_MakeShadowDir(struct vcache *avc)
3639 {
3640     int j, i, index, code, ret_code = 0, offset, trans_size, block;
3641     struct dcache *tdc, *new_dc = NULL;
3642     struct osi_file *tfile_src, *tfile_dst;
3643     struct VenusFid shadow_fid;
3644     char *data;
3645     int lock_held = 0;
3646
3647     /* Is this a dir? */
3648     if (vType(avc) != VDIR)
3649         return ENOTDIR;
3650
3651     /* Generate a fid for the shadow dir. */
3652     shadow_fid.Cell = avc->fid.Cell;
3653     shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3654     afs_GenShadowFid(&shadow_fid);
3655
3656     /* For each dcache, do copy it into a new fresh one. */
3657     i = DVHash(&avc->fid);
3658     for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
3659         /* Making sure that this isn't going to get locked twice. */
3660         if (!lock_held) {
3661             /* XXX: Moved it from outside of the loop.
3662              * Maybe it's not quite okay because of the use of
3663              * dvhashTbl (once) in the for statement.
3664              */
3665             ObtainWriteLock(&afs_xdcache, 716);
3666             lock_held = 1;
3667         }
3668
3669         i = afs_dvnextTbl[index];
3670         if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
3671             tdc = afs_GetDSlot(index, NULL);
3672
3673             ReleaseReadLock(&tdc->tlock);
3674
3675             if (!FidCmp(&tdc->f.fid, &avc->fid)) {
3676
3677                 /* Got a dir's dcache. */
3678                 lock_held = 0;
3679
3680                 /* Get a fresh dcache. */
3681                 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3682
3683                 /* Unlock hash for now. Don't need it during operations on the
3684                  * dcache. Oh, and we can't use it because of the locking
3685                  * hierarchy...
3686                  */
3687                 /* XXX: So much for lock ierarchy, the afs_AllocDCache doesn't
3688                  * respect it.
3689                  */
3690                 //ReleaseWriteLock(&afs_xdcache);
3691
3692                 ObtainReadLock(&tdc->lock);
3693
3694                 /* Set up the new fid. */
3695                 /* Copy interesting data from original dir dcache. */
3696                 new_dc->mflags = tdc->mflags;
3697                 new_dc->dflags = tdc->dflags;
3698                 new_dc->f.modTime = tdc->f.modTime;
3699                 new_dc->f.versionNo = tdc->f.versionNo;
3700                 new_dc->f.states = tdc->f.states;
3701                 new_dc->f.chunk= tdc->f.chunk;
3702                 new_dc->f.chunkBytes = tdc->f.chunkBytes;
3703
3704                 /*
3705                  * Now add to the two hash chains - note that i is still set
3706                  * from the above DCHash call.
3707                  */
3708                 //ObtainWriteLock(&afs_xdcache, 713);
3709
3710                 j = DCHash(&shadow_fid, 0);
3711                 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[j];
3712                 afs_dchashTbl[j] = new_dc->index;
3713
3714                 j = DVHash(&shadow_fid);
3715                 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[j];
3716                 afs_dvhashTbl[j] = new_dc->index;
3717                 afs_MaybeWakeupTruncateDaemon();
3718
3719                 ReleaseWriteLock(&afs_xdcache);
3720
3721                 /* Alloc a 4k block. */
3722                 data = (char *) afs_osi_Alloc(4096);
3723                 if (!data) {
3724                     printf("afs_MakeShadowDir: could not alloc data\n");
3725                     ret_code = ENOMEM;
3726                     goto done;
3727                 }
3728
3729                 /* Open the files. */
3730                 tfile_src = afs_CFileOpen(tdc->f.inode);
3731                 tfile_dst = afs_CFileOpen(new_dc->f.inode);
3732
3733                 /* Init no of blocks to be read and offset. */
3734                 block = (tdc->f.chunkBytes / 4096);
3735                 offset = 0;
3736
3737                 /* And now copy dir dcache data into this dcache,
3738                  * 4k at a time.
3739                  */
3740                 while (block >= 0) {
3741
3742                     /* Last chunk might have less bytes to transfer. */
3743                     if (!block) {
3744                         /* Last block. */
3745                         trans_size = (tdc->f.chunkBytes % 4096);
3746                         if (!trans_size)
3747                             /* An exact no of 4k blocks. */
3748                             break;
3749                     } else
3750                         trans_size = 4096;
3751
3752                     /* Read a chunk from the dcache. */
3753                     code = afs_CFileRead(tfile_src, offset, data, trans_size);
3754                     if (code < trans_size) {
3755                         /* Can't access file, stop doing stuff and return error. */
3756                         ret_code = EIO;
3757                         break;
3758                     }
3759
3760                     /* Write it to the new dcache. */
3761                     code = afs_CFileWrite(tfile_dst, offset, data, trans_size);
3762                     if (code < trans_size) {
3763                         ret_code = EIO;
3764                         break;
3765                     }
3766
3767                     block--;
3768                     offset += 4096;
3769                 }               /* while (block) */
3770
3771                 afs_CFileClose(tfile_dst);
3772                 afs_CFileClose(tfile_src);
3773
3774                 afs_osi_Free(data, 4096);
3775
3776                 ReleaseWriteLock(&new_dc->lock);
3777                 ReleaseReadLock(&tdc->lock);
3778
3779                 afs_PutDCache(new_dc);
3780             }                   /* if dcache fid match */
3781             afs_PutDCache(tdc);
3782         }                       /* if unuiquifier match */
3783     }
3784 done:
3785     if (lock_held)
3786         ReleaseWriteLock(&afs_xdcache);
3787
3788     if (!ret_code) {
3789         if (!avc->ddirty_flags) {
3790             ObtainWriteLock(&afs_DDirtyVCListLock, 763);
3791             AFS_DISCON_ADD_DIRTY(avc);
3792             ReleaseWriteLock(&afs_DDirtyVCListLock);
3793         }
3794         avc->shVnode = shadow_fid.Fid.Vnode;
3795         avc->shUnique = shadow_fid.Fid.Unique;
3796         avc->ddirty_flags |= VDisconShadowed;
3797     }
3798
3799     return ret_code;
3800 }
3801
3802 /*!
3803  * Delete the dcaches of a shadow dir.
3804  *
3805  * \param avc The vcache containing the shadow fid.
3806  *
3807  * \note avc must be write locked.
3808  */
3809 void afs_DeleteShadowDir(struct vcache *avc)
3810 {
3811     struct dcache *tdc;
3812     struct VenusFid shadow_fid;
3813
3814     shadow_fid.Cell = avc->fid.Cell;
3815     shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3816     shadow_fid.Fid.Vnode = avc->shVnode;
3817     shadow_fid.Fid.Unique = avc->shUnique;
3818
3819     tdc = afs_FindDCacheByFid(&shadow_fid);
3820     if (tdc) {
3821         afs_HashOutDCache(tdc, 1);
3822         afs_DiscardDCache(tdc);
3823         afs_PutDCache(tdc);
3824     }
3825     /* Remove shadowed dir flag. */
3826     avc->ddirty_flags &= ~VDisconShadowed;
3827 }
3828 #endif