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