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