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