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