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