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