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