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