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