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