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