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