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