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