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