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