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