2 * Copyright 2000, International Business Machines Corporation and others.
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
13 #include <afsconfig.h>
14 #include "../afs/param.h"
18 #include "../afs/sysincludes.h" /*Standard vendor system headers*/
19 #include "../afs/afsincludes.h" /*AFS-based standard headers*/
20 #include "../afs/afs_stats.h" /* statistics */
21 #include "../afs/afs_cbqueue.h"
22 #include "../afs/afs_osidnlc.h"
24 /* Forward declarations. */
25 static void afs_GetDownD(int anumber, int *aneedSpace);
26 static void afs_FreeDiscardedDCache(void);
27 static void afs_DiscardDCache(struct dcache *);
29 /* Imported variables */
30 extern afs_rwlock_t afs_xvcache;
31 extern afs_rwlock_t afs_xcbhash;
32 extern afs_int32 afs_mariner;
33 extern afs_int32 cacheInfoModTime; /*Last time cache info modified*/
37 * --------------------- Exported definitions ---------------------
39 afs_lock_t afs_xdcache; /*Lock: alloc new disk cache entries*/
40 afs_int32 afs_freeDCList; /*Free list for disk cache entries*/
41 afs_int32 afs_freeDCCount; /*Count of elts in freeDCList*/
42 afs_int32 afs_discardDCList; /*Discarded disk cache entries*/
43 afs_int32 afs_discardDCCount; /*Count of elts in discardDCList*/
44 struct dcache *afs_freeDSList; /*Free list for disk slots */
45 struct dcache *afs_Initial_freeDSList; /*Initial list for above*/
46 ino_t cacheInode; /*Inode for CacheItems file*/
47 struct osi_file *afs_cacheInodep = 0; /* file for CacheItems inode */
48 struct afs_q afs_DLRU; /*dcache LRU*/
49 afs_int32 afs_dhashsize = 1024;
50 afs_int32 *afs_dvhashTbl; /*Data cache hash table*/
51 afs_int32 *afs_dchashTbl; /*Data cache hash table*/
52 afs_int32 *afs_dvnextTbl; /*Dcache hash table links */
53 afs_int32 *afs_dcnextTbl; /*Dcache hash table links */
54 struct dcache **afs_indexTable; /*Pointers to dcache entries*/
55 afs_hyper_t *afs_indexTimes; /*Dcache entry Access times*/
56 afs_int32 *afs_indexUnique; /*dcache entry Fid.Unique */
57 unsigned char *afs_indexFlags; /*(only one) Is there data there?*/
58 afs_hyper_t afs_indexCounter; /*Fake time for marking index
60 afs_int32 afs_cacheFiles =0; /*Size of afs_indexTable*/
61 afs_int32 afs_cacheBlocks; /*1K blocks in cache*/
62 afs_int32 afs_cacheStats; /*Stat entries in cache*/
63 afs_int32 afs_blocksUsed; /*Number of blocks in use*/
64 afs_int32 afs_blocksDiscarded; /*Blocks freed but not truncated */
65 afs_int32 afs_fsfragsize = 1023; /*Underlying Filesystem minimum unit
66 *of disk allocation usually 1K
67 *this value is (truefrag -1 ) to
68 *save a bunch of subtracts... */
70 /* The following is used to ensure that new dcache's aren't obtained when
71 * the cache is nearly full.
73 int afs_WaitForCacheDrain = 0;
74 int afs_TruncateDaemonRunning = 0;
75 int afs_CacheTooFull = 0;
77 afs_int32 afs_dcentries; /* In-memory dcache entries */
80 int dcacheDisabled = 0;
82 extern struct dcache *afs_UFSGetDSlot();
83 extern struct volume *afs_UFSGetVolSlot();
84 extern int osi_UFSTruncate(), afs_osi_Read(), afs_osi_Write(), osi_UFSClose();
85 extern int afs_UFSRead(), afs_UFSWrite();
86 static int afs_UFSCacheFetchProc(), afs_UFSCacheStoreProc();
87 extern int afs_UFSHandleLink();
88 struct afs_cacheOps afs_UfsCacheOps = {
96 afs_UFSCacheFetchProc,
97 afs_UFSCacheStoreProc,
103 extern void *afs_MemCacheOpen();
104 extern struct dcache *afs_MemGetDSlot();
105 extern struct volume *afs_MemGetVolSlot();
106 extern int afs_MemCacheTruncate(), afs_MemReadBlk(), afs_MemWriteBlk(), afs_MemCacheClose();
107 extern int afs_MemRead(), afs_MemWrite(), afs_MemCacheFetchProc(), afs_MemCacheStoreProc();
108 extern int afs_MemHandleLink();
109 struct afs_cacheOps afs_MemCacheOps = {
111 afs_MemCacheTruncate,
117 afs_MemCacheFetchProc,
118 afs_MemCacheStoreProc,
124 int cacheDiskType; /*Type of backing disk for cache*/
125 struct afs_cacheOps *afs_cacheType;
134 * Warn about failing to store a file.
137 * acode : Associated error code.
138 * avolume : Volume involved.
139 * aflags : How to handle the output:
140 * aflags & 1: Print out on console
141 * aflags & 2: Print out on controlling tty
144 * Call this from close call when vnodeops is RCS unlocked.
148 afs_StoreWarn(acode, avolume, aflags)
149 register afs_int32 acode;
151 register afs_int32 aflags;
155 static char problem_fmt[] =
156 "afs: failed to store file in volume %d (%s)\n";
157 static char problem_fmt_w_error[] =
158 "afs: failed to store file in volume %d (error %d)\n";
159 static char netproblems[] = "network problems";
160 static char partfull[] = "partition full";
161 static char overquota[] = "over quota";
162 static char unknownerr[] = "unknown error";
164 AFS_STATCNT(afs_StoreWarn);
170 afs_warn(problem_fmt, avolume, netproblems);
172 afs_warnuser(problem_fmt, avolume, netproblems);
175 if (acode == ENOSPC) {
180 afs_warn(problem_fmt, avolume, partfull);
182 afs_warnuser(problem_fmt, avolume, partfull);
186 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
187 * Instead ENOSPC will be sent...
189 if (acode == EDQUOT) {
194 afs_warn(problem_fmt, avolume, overquota);
196 afs_warnuser(problem_fmt, avolume, overquota);
204 afs_warn(problem_fmt_w_error, avolume, acode);
206 afs_warnuser(problem_fmt_w_error, avolume, acode);
210 /* Keep statistics on run time for afs_CacheTruncateDaemon. This is a
211 * struct so we need only export one symbol for AIX.
214 osi_timeval_t CTD_beforeSleep;
215 osi_timeval_t CTD_afterSleep;
216 osi_timeval_t CTD_sleepTime;
217 osi_timeval_t CTD_runTime;
221 u_int afs_min_cache = 0;
222 void afs_CacheTruncateDaemon() {
223 osi_timeval_t CTD_tmpTime;
226 u_int dc_hiwat = (100-CM_DCACHECOUNTFREEPCT+CM_DCACHEEXTRAPCT)*afs_cacheFiles/100;
227 afs_min_cache = (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize)>>10;
229 osi_GetuTime(&CTD_stats.CTD_afterSleep);
230 afs_TruncateDaemonRunning = 1;
232 cb_lowat = ((CM_DCACHESPACEFREEPCT-CM_DCACHEEXTRAPCT)
233 * afs_cacheBlocks) / 100;
234 MObtainWriteLock(&afs_xdcache,266);
235 if (afs_CacheTooFull) {
236 int space_needed, slots_needed;
237 /* if we get woken up, we should try to clean something out */
238 for (counter = 0; counter < 10; counter++) {
239 space_needed = afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
240 slots_needed = dc_hiwat - afs_freeDCCount - afs_discardDCCount;
241 afs_GetDownD(slots_needed, &space_needed);
242 if ((space_needed <= 0) && (slots_needed <= 0)) {
245 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
248 if (!afs_CacheIsTooFull())
249 afs_CacheTooFull = 0;
251 MReleaseWriteLock(&afs_xdcache);
254 * This is a defensive check to try to avoid starving threads
255 * that may need the global lock so thay can help free some
256 * cache space. If this thread won't be sleeping or truncating
257 * any cache files then give up the global lock so other
258 * threads get a chance to run.
260 if ((afs_termState!=AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull &&
261 (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
262 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
266 * This is where we free the discarded cache elements.
268 while(afs_blocksDiscarded && !afs_WaitForCacheDrain &&
269 (afs_termState!=AFSOP_STOP_TRUNCDAEMON))
271 afs_FreeDiscardedDCache();
274 /* See if we need to continue to run. Someone may have
275 * signalled us while we were executing.
277 if (!afs_WaitForCacheDrain && !afs_CacheTooFull &&
278 (afs_termState!=AFSOP_STOP_TRUNCDAEMON))
280 /* Collect statistics on truncate daemon. */
281 CTD_stats.CTD_nSleeps++;
282 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
283 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
284 CTD_stats.CTD_beforeSleep);
285 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
287 afs_TruncateDaemonRunning = 0;
288 afs_osi_Sleep((char *)afs_CacheTruncateDaemon);
289 afs_TruncateDaemonRunning = 1;
291 osi_GetuTime(&CTD_stats.CTD_afterSleep);
292 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
293 CTD_stats.CTD_afterSleep);
294 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
296 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
297 afs_termState = AFSOP_STOP_RXEVENT;
298 afs_osi_Wakeup(&afs_termState);
309 * Make adjustment for the new size in the disk cache entry
311 * Major Assumptions Here:
312 * Assumes that frag size is an integral power of two, less one,
313 * and that this is a two's complement machine. I don't
314 * know of any filesystems which violate this assumption...
317 * adc : Ptr to dcache entry.
318 * anewsize : New size desired.
322 afs_AdjustSize(adc, anewSize)
323 register struct dcache *adc;
324 register afs_int32 anewSize;
328 register afs_int32 oldSize;
330 AFS_STATCNT(afs_AdjustSize);
331 adc->flags |= DFEntryMod;
332 oldSize = ((adc->f.chunkBytes + afs_fsfragsize)^afs_fsfragsize)>>10;/* round up */
333 adc->f.chunkBytes = anewSize;
334 anewSize = ((anewSize + afs_fsfragsize)^afs_fsfragsize)>>10;/* round up */
335 if (anewSize > oldSize) {
336 /* We're growing the file, wakeup the daemon */
337 afs_MaybeWakeupTruncateDaemon();
339 afs_blocksUsed += (anewSize - oldSize);
340 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
352 * This routine is responsible for moving at least one entry (but up
353 * to some number of them) from the LRU queue to the free queue.
356 * anumber : Number of entries that should ideally be moved.
357 * aneedSpace : How much space we need (1K blocks);
360 * The anumber parameter is just a hint; at least one entry MUST be
361 * moved, of we'll panic. We must be called with afs_xdcache
362 * write-locked. We should try to satisfy both anumber and aneedspace,
363 * whichever is more demanding - need to do several things:
364 * 1. only grab up to anumber victims if aneedSpace <= 0, not
365 * the whole set of MAXATONCE.
366 * 2. dynamically choose MAXATONCE to reflect severity of
367 * demand: something like (*aneedSpace >> (logChunk - 9))
368 * N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
369 * indicates that the cache is not properly configured/tuned or
370 * something. We should be able to automatically correct that problem.
373 #define MAXATONCE 16 /* max we can obtain at once */
374 static void afs_GetDownD(int anumber, int *aneedSpace)
378 struct VenusFid *afid;
382 register struct vcache *tvc;
383 afs_uint32 victims[MAXATONCE];
384 struct dcache *victimDCs[MAXATONCE];
385 afs_hyper_t victimTimes[MAXATONCE];/* youngest (largest LRU time) first */
386 afs_uint32 victimPtr; /* next free item in victim arrays */
387 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
388 afs_uint32 maxVictimPtr; /* where it is */
391 AFS_STATCNT(afs_GetDownD);
392 if (CheckLock(&afs_xdcache) != -1)
393 osi_Panic("getdownd nolock");
394 /* decrement anumber first for all dudes in free list */
395 /* SHOULD always decrement anumber first, even if aneedSpace >0,
396 * because we should try to free space even if anumber <=0 */
397 if (!aneedSpace || *aneedSpace <= 0) {
398 anumber -= afs_freeDCCount;
399 if (anumber <= 0) return; /* enough already free */
401 /* bounds check parameter */
402 if (anumber > MAXATONCE)
403 anumber = MAXATONCE; /* all we can do */
406 * The phase variable manages reclaims. Set to 0, the first pass,
407 * we don't reclaim active entries. Set to 1, we reclaim even active
411 for (i = 0; i < afs_cacheFiles; i++)
412 /* turn off all flags */
413 afs_indexFlags[i] &= ~IFFlag;
415 while (anumber > 0 || (aneedSpace && *aneedSpace >0)) {
416 /* find oldest entries for reclamation */
417 maxVictimPtr = victimPtr = 0;
418 hzero(maxVictimTime);
419 /* select victims from access time array */
420 for (i = 0; i < afs_cacheFiles; i++) {
421 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
422 /* skip if dirty or already free */
425 tdc = afs_indexTable[i];
426 if (tdc && (tdc->refCount != 0)) {
427 /* Referenced; can't use it! */
430 hset(vtime, afs_indexTimes[i]);
432 /* if we've already looked at this one, skip it */
433 if (afs_indexFlags[i] & IFFlag) continue;
435 if (victimPtr < MAXATONCE) {
436 /* if there's at least one free victim slot left */
437 victims[victimPtr] = i;
438 hset(victimTimes[victimPtr], vtime);
439 if (hcmp(vtime, maxVictimTime) > 0) {
440 hset(maxVictimTime, vtime);
441 maxVictimPtr = victimPtr;
445 else if (hcmp(vtime, maxVictimTime) < 0) {
447 * We're older than youngest victim, so we replace at
450 /* find youngest (largest LRU) victim */
452 if (j == victimPtr) osi_Panic("getdownd local");
454 hset(victimTimes[j], vtime);
455 /* recompute maxVictimTime */
456 hset(maxVictimTime, vtime);
457 for(j = 0; j < victimPtr; j++)
458 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
459 hset(maxVictimTime, victimTimes[j]);
465 /* now really reclaim the victims */
466 j = 0; /* flag to track if we actually got any of the victims */
467 /* first, hold all the victims, since we're going to release the lock
468 * during the truncate operation.
470 for(i=0; i < victimPtr; i++)
471 victimDCs[i] = afs_GetDSlot(victims[i], 0);
472 for(i = 0; i < victimPtr; i++) {
473 /* q is first elt in dcache entry */
475 /* now, since we're dropping the afs_xdcache lock below, we
476 * have to verify, before proceeding, that there are no other
477 * references to this dcache entry, even now. Note that we
478 * compare with 1, since we bumped it above when we called
479 * afs_GetDSlot to preserve the entry's identity.
481 if (tdc->refCount == 1) {
482 unsigned char chunkFlags;
484 /* xdcache is lower than the xvcache lock */
485 MReleaseWriteLock(&afs_xdcache);
486 MObtainReadLock(&afs_xvcache);
487 tvc = afs_FindVCache(afid, 0,0, 0, 0 /* no stats, no vlru */ );
488 MReleaseReadLock(&afs_xvcache);
489 MObtainWriteLock(&afs_xdcache, 527);
491 if (tdc->refCount > 1) skip = 1;
493 chunkFlags = afs_indexFlags[tdc->index];
494 if (phase == 0 && osi_Active(tvc)) skip = 1;
495 if (phase > 0 && osi_Active(tvc) && (tvc->states & CDCLock)
496 && (chunkFlags & IFAnyPages)) skip = 1;
497 if (chunkFlags & IFDataMod) skip = 1;
498 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
499 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
501 (afs_int32)(chunkFlags & IFDirtyPages),
502 ICL_TYPE_INT32, AFS_CHUNKTOBASE(tdc->f.chunk));
504 #if defined(AFS_SUN5_ENV)
506 * Now we try to invalidate pages. We do this only for
507 * Solaris. For other platforms, it's OK to recycle a
508 * dcache entry out from under a page, because the strategy
509 * function can call afs_GetDCache().
511 if (!skip && (chunkFlags & IFAnyPages)) {
514 MReleaseWriteLock(&afs_xdcache);
515 MObtainWriteLock(&tvc->vlock, 543);
516 if (tvc->multiPage) {
520 /* block locking pages */
521 tvc->vstates |= VPageCleaning;
522 /* block getting new pages */
524 MReleaseWriteLock(&tvc->vlock);
525 /* One last recheck */
526 MObtainWriteLock(&afs_xdcache, 333);
527 chunkFlags = afs_indexFlags[tdc->index];
528 if (tdc->refCount > 1
529 || (chunkFlags & IFDataMod)
530 || (osi_Active(tvc) && (tvc->states & CDCLock)
531 && (chunkFlags & IFAnyPages))) {
533 MReleaseWriteLock(&afs_xdcache);
536 MReleaseWriteLock(&afs_xdcache);
538 code = osi_VM_GetDownD(tvc, tdc);
540 MObtainWriteLock(&afs_xdcache,269);
541 /* we actually removed all pages, clean and dirty */
543 afs_indexFlags[tdc->index] &= ~(IFDirtyPages| IFAnyPages);
546 MReleaseWriteLock(&afs_xdcache);
548 MObtainWriteLock(&tvc->vlock, 544);
549 if (--tvc->activeV == 0 && (tvc->vstates & VRevokeWait)) {
550 tvc->vstates &= ~VRevokeWait;
551 afs_osi_Wakeup((char *)&tvc->vstates);
554 if (tvc->vstates & VPageCleaning) {
555 tvc->vstates &= ~VPageCleaning;
556 afs_osi_Wakeup((char *)&tvc->vstates);
559 MReleaseWriteLock(&tvc->vlock);
561 #endif /* AFS_SUN5_ENV */
563 MReleaseWriteLock(&afs_xdcache);
567 MObtainWriteLock(&afs_xdcache, 528);
568 if (afs_indexFlags[tdc->index] &
569 (IFDataMod | IFDirtyPages | IFAnyPages)) skip = 1;
570 if (tdc->refCount > 1) skip = 1;
572 #if defined(AFS_SUN5_ENV)
574 /* no vnode, so IFDirtyPages is spurious (we don't
575 * sweep dcaches on vnode recycling, so we can have
576 * DIRTYPAGES set even when all pages are gone). Just
578 * Hold vcache lock to prevent vnode from being
579 * created while we're clearing IFDirtyPages.
581 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
585 /* skip this guy and mark him as recently used */
586 afs_indexFlags[tdc->index] |= IFFlag;
589 /* flush this dude from the data cache and reclaim;
590 * first, make sure no one will care that we damage
591 * it, by removing it from all hash tables. Then,
592 * melt it down for parts. Note that any concurrent
593 * (new possibility!) calls to GetDownD won't touch
594 * this guy because his reference count is > 0. */
596 AFS_STATCNT(afs_gget);
598 afs_HashOutDCache(tdc);
599 if (tdc->f.chunkBytes != 0) {
602 *aneedSpace -= (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
607 afs_DiscardDCache(tdc);
612 j = 1; /* we reclaimed at least one victim */
618 tdc->refCount--; /* put it back */
623 /* Phase is 0 and no one was found, so try phase 1 (ignore
624 * osi_Active flag) */
627 for (i = 0; i < afs_cacheFiles; i++)
628 /* turn off all flags */
629 afs_indexFlags[i] &= ~IFFlag;
633 /* found no one in phase 1, we're hosed */
634 if (victimPtr == 0) break;
636 } /* big while loop */
643 * Description: remove adc from any hash tables that would allow it to be located
644 * again by afs_FindDCache or afs_GetDCache.
646 * Parameters: adc -- pointer to dcache entry to remove from hash tables.
648 * Locks: Must have the afs_xdcache lock write-locked to call this function.
650 afs_HashOutDCache(adc)
653 { /*afs_HashOutDCache*/
658 AFS_STATCNT(afs_glink);
660 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
662 /* if this guy is in the hash table, pull him out */
663 if (adc->f.fid.Fid.Volume != 0) {
664 /* remove entry from first hash chains */
665 i = DCHash(&adc->f.fid, adc->f.chunk);
666 us = afs_dchashTbl[i];
667 if (us == adc->index) {
668 /* first dude in the list */
669 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
672 /* somewhere on the chain */
673 while (us != NULLIDX) {
674 if (afs_dcnextTbl[us] == adc->index) {
675 /* found item pointing at the one to delete */
676 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
679 us = afs_dcnextTbl[us];
681 if (us == NULLIDX) osi_Panic("dcache hc");
683 /* remove entry from *other* hash chain */
684 i = DVHash(&adc->f.fid);
685 us = afs_dvhashTbl[i];
686 if (us == adc->index) {
687 /* first dude in the list */
688 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
691 /* somewhere on the chain */
692 while (us != NULLIDX) {
693 if (afs_dvnextTbl[us] == adc->index) {
694 /* found item pointing at the one to delete */
695 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
698 us = afs_dvnextTbl[us];
700 if (us == NULLIDX) osi_Panic("dcache hv");
704 /* prevent entry from being found on a reboot (it is already out of
705 * the hash table, but after a crash, we just look at fid fields of
706 * stable (old) entries).
708 adc->f.fid.Fid.Volume = 0; /* invalid */
710 /* mark entry as modified */
711 adc->flags |= DFEntryMod;
715 } /*afs_HashOutDCache */
722 * Flush the given dcache entry, pulling it from hash chains
723 * and truncating the associated cache file.
726 * adc: Ptr to dcache entry to flush.
729 * This routine must be called with the afs_xdcache lock held
735 register struct dcache *adc;
736 { /*afs_FlushDCache*/
738 AFS_STATCNT(afs_FlushDCache);
740 * Bump the number of cache files flushed.
742 afs_stats_cmperf.cacheFlushes++;
744 /* remove from all hash tables */
745 afs_HashOutDCache(adc);
747 /* Free its space; special case null operation, since truncate operation
748 * in UFS is slow even in this case, and this allows us to pre-truncate
749 * these files at more convenient times with fewer locks set
750 * (see afs_GetDownD).
752 if (adc->f.chunkBytes != 0) {
753 afs_DiscardDCache(adc);
754 afs_MaybeWakeupTruncateDaemon();
759 if (afs_WaitForCacheDrain) {
760 if (afs_blocksUsed <=
761 (CM_CACHESIZEDRAINEDPCT*afs_cacheBlocks)/100) {
762 afs_WaitForCacheDrain = 0;
763 afs_osi_Wakeup(&afs_WaitForCacheDrain);
766 } /*afs_FlushDCache*/
772 * Description: put a dcache entry on the free dcache entry list.
774 * Parameters: adc -- dcache entry to free
776 * Environment: called with afs_xdcache lock write-locked.
779 register struct dcache *adc; {
780 /* Thread on free list, update free list count and mark entry as
781 * freed in its indexFlags element. Also, ensure DCache entry gets
782 * written out (set DFEntryMod).
785 afs_dvnextTbl[adc->index] = afs_freeDCList;
786 afs_freeDCList = adc->index;
788 afs_indexFlags[adc->index] |= IFFree;
789 adc->flags |= DFEntryMod;
791 if (afs_WaitForCacheDrain) {
792 if ((afs_blocksUsed - afs_blocksDiscarded) <=
793 (CM_CACHESIZEDRAINEDPCT*afs_cacheBlocks)/100) {
794 afs_WaitForCacheDrain = 0;
795 afs_osi_Wakeup(&afs_WaitForCacheDrain);
805 * Discard the cache element by moving it to the discardDCList.
806 * This puts the cache element into a quasi-freed state, where
807 * the space may be reused, but the file has not been truncated.
809 * Major Assumptions Here:
810 * Assumes that frag size is an integral power of two, less one,
811 * and that this is a two's complement machine. I don't
812 * know of any filesystems which violate this assumption...
815 * adc : Ptr to dcache entry.
819 afs_DiscardDCache(adc)
820 register struct dcache *adc;
822 { /*afs_DiscardDCache*/
824 register afs_int32 size;
826 AFS_STATCNT(afs_DiscardDCache);
827 size = ((adc->f.chunkBytes + afs_fsfragsize)^afs_fsfragsize)>>10;/* round up */
828 afs_blocksDiscarded += size;
829 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
831 afs_dvnextTbl[adc->index] = afs_discardDCList;
832 afs_discardDCList = adc->index;
833 afs_discardDCCount++;
835 adc->f.fid.Fid.Volume = 0;
836 adc->flags |= DFEntryMod;
837 afs_indexFlags[adc->index] |= IFDiscarded;
839 if (afs_WaitForCacheDrain) {
840 if ((afs_blocksUsed - afs_blocksDiscarded) <=
841 (CM_CACHESIZEDRAINEDPCT*afs_cacheBlocks)/100) {
842 afs_WaitForCacheDrain = 0;
843 afs_osi_Wakeup(&afs_WaitForCacheDrain);
847 } /*afs_DiscardDCache*/
850 * afs_FreeDiscardedDCache
853 * Free the next element on the list of discarded cache elements.
856 afs_FreeDiscardedDCache()
858 register struct dcache *tdc;
859 register struct osi_file *tfile;
860 register afs_int32 size;
862 AFS_STATCNT(afs_FreeDiscardedDCache);
864 MObtainWriteLock(&afs_xdcache,510);
865 if (!afs_blocksDiscarded) {
866 MReleaseWriteLock(&afs_xdcache);
871 * Get an entry from the list of discarded cache elements
873 tdc = afs_GetDSlot(afs_discardDCList, 0);
874 afs_discardDCList = afs_dvnextTbl[tdc->index];
875 afs_dvnextTbl[tdc->index] = NULLIDX;
876 afs_discardDCCount--;
877 size = ((tdc->f.chunkBytes + afs_fsfragsize)^afs_fsfragsize)>>10;/* round up */
878 afs_blocksDiscarded -= size;
879 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
880 MReleaseWriteLock(&afs_xdcache);
883 * Truncate the element to reclaim its space
885 tfile = afs_CFileOpen(tdc->f.inode);
886 afs_CFileTruncate(tfile, 0);
887 afs_CFileClose(tfile);
888 afs_AdjustSize(tdc, 0);
891 * Free the element we just truncated
893 MObtainWriteLock(&afs_xdcache,511);
894 afs_indexFlags[tdc->index] &= ~IFDiscarded;
897 MReleaseWriteLock(&afs_xdcache);
901 * afs_MaybeFreeDiscardedDCache
904 * Free as many entries from the list of discarded cache elements
905 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
910 afs_MaybeFreeDiscardedDCache()
913 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
915 while (afs_blocksDiscarded &&
916 (afs_blocksUsed > (CM_WAITFORDRAINPCT*afs_cacheBlocks)/100)) {
917 afs_FreeDiscardedDCache();
926 * Try to free up a certain number of disk slots.
929 * anumber : Targeted number of disk slots to free up.
931 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
932 extern SV_TYPE afs_sgibksync;
933 extern SV_TYPE afs_sgibkwait;
934 extern lock_t afs_sgibklock;
935 extern struct dcache *afs_sgibklist;
939 afs_GetDownDSlot(anumber)
942 { /*afs_GetDownDSlot*/
944 struct afs_q *tq, *nq;
950 AFS_STATCNT(afs_GetDownDSlot);
951 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
952 osi_Panic("diskless getdowndslot");
954 if (CheckLock(&afs_xdcache) != -1)
955 osi_Panic("getdowndslot nolock");
957 /* decrement anumber first for all dudes in free list */
958 for(tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
961 return; /* enough already free */
963 for(cnt=0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
965 tdc = (struct dcache *) tq; /* q is first elt in dcache entry */
966 nq = QPrev(tq); /* in case we remove it */
967 if (tdc->refCount == 0) {
968 if ((ix=tdc->index) == NULLIDX) osi_Panic("getdowndslot");
969 /* pull the entry out of the lruq and put it on the free list */
972 /* write-through if modified */
973 if (tdc->flags & DFEntryMod) {
974 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
976 * ask proxy to do this for us - we don't have the stack space
978 while (tdc->flags & DFEntryMod) {
981 s = SPLOCK(afs_sgibklock);
982 if (afs_sgibklist == NULL) {
983 /* if slot is free, grab it. */
985 SV_SIGNAL(&afs_sgibksync);
987 /* wait for daemon to (start, then) finish. */
988 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
992 tdc->flags &= ~DFEntryMod;
993 afs_WriteDCache(tdc, 1);
1000 struct osi_file * f = (struct osi_file *)tdc->ihint;
1008 /* finally put the entry in the free list */
1009 afs_indexTable[ix] = (struct dcache *) 0;
1010 afs_indexFlags[ix] &= ~IFEverUsed;
1011 tdc->index = NULLIDX;
1012 tdc->lruq.next = (struct afs_q *) afs_freeDSList;
1013 afs_freeDSList = tdc;
1017 } /*afs_GetDownDSlot*/
1025 * Decrement the reference count on a disk cache entry.
1028 * ad : Ptr to the dcache entry to decrement.
1031 * Nothing interesting.
1034 register struct dcache *ad;
1037 AFS_STATCNT(afs_PutDCache);
1038 #ifndef AFS_SUN5_ENVX
1039 MObtainWriteLock(&afs_xdcache,276);
1041 if (ad->refCount <= 0)
1042 osi_Panic("putdcache");
1044 #ifdef AFS_SUN5_ENVX
1045 MReleaseWriteLock(&ad->lock);
1047 MReleaseWriteLock(&afs_xdcache);
1058 * Try to discard all data associated with this file from the
1062 * avc : Pointer to the cache info for the file.
1065 * Both pvnLock and lock are write held.
1068 afs_TryToSmush(avc, acred, sync)
1069 register struct vcache *avc;
1070 struct AFS_UCRED *acred;
1072 { /*afs_TryToSmush*/
1074 register struct dcache *tdc;
1077 AFS_STATCNT(afs_TryToSmush);
1078 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1079 ICL_TYPE_INT32, avc->m.Length);
1080 sync = 1; /* XX Temp testing XX*/
1082 #if defined(AFS_SUN5_ENV)
1083 ObtainWriteLock(&avc->vlock, 573);
1084 avc->activeV++; /* block new getpages */
1085 ReleaseWriteLock(&avc->vlock);
1088 /* Flush VM pages */
1089 osi_VM_TryToSmush(avc, acred, sync);
1092 * Get the hash chain containing all dce's for this fid
1094 i = DVHash(&avc->fid);
1095 MObtainWriteLock(&afs_xdcache,277);
1096 for(index = afs_dvhashTbl[i]; index != NULLIDX; index=i) {
1097 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1098 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1099 tdc = afs_GetDSlot(index, (struct dcache *)0);
1100 if (!FidCmp(&tdc->f.fid, &avc->fid)) {
1102 if ((afs_indexFlags[index] & IFDataMod) == 0 &&
1103 tdc->refCount == 1) {
1104 afs_FlushDCache(tdc);
1107 afs_indexTable[index] = 0;
1109 lockedPutDCache(tdc);
1112 #if defined(AFS_SUN5_ENV)
1113 ObtainWriteLock(&avc->vlock, 545);
1114 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1115 avc->vstates &= ~VRevokeWait;
1116 afs_osi_Wakeup((char *)&avc->vstates);
1118 ReleaseWriteLock(&avc->vlock);
1120 MReleaseWriteLock(&afs_xdcache);
1122 * It's treated like a callback so that when we do lookups we'll invalidate the unique bit if any
1123 * trytoSmush occured during the lookup call
1126 } /*afs_TryToSmush*/
1132 * Given the cached info for a file and a byte offset into the
1133 * file, make sure the dcache entry for that file and containing
1134 * the given byte is available, returning it to our caller.
1137 * avc : Pointer to the (held) vcache entry to look in.
1138 * abyte : Which byte we want to get to.
1141 * Pointer to the dcache entry covering the file & desired byte,
1142 * or NULL if not found.
1145 * The vcache entry is held upon entry.
1148 struct dcache *afs_FindDCache(avc, abyte)
1149 register struct vcache *avc;
1152 { /*afs_FindDCache*/
1155 register afs_int32 i, index;
1156 register struct dcache *tdc;
1158 AFS_STATCNT(afs_FindDCache);
1159 chunk = AFS_CHUNK(abyte);
1162 * Hash on the [fid, chunk] and get the corresponding dcache index
1163 * after write-locking the dcache.
1165 i = DCHash(&avc->fid, chunk);
1166 MObtainWriteLock(&afs_xdcache,278);
1167 for(index = afs_dchashTbl[i]; index != NULLIDX;) {
1168 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1169 tdc = afs_GetDSlot(index, (struct dcache *)0);
1170 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1171 break; /* leaving refCount high for caller */
1173 lockedPutDCache(tdc);
1175 index = afs_dcnextTbl[index];
1177 MReleaseWriteLock(&afs_xdcache);
1178 if (index != NULLIDX) {
1179 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1180 hadd32(afs_indexCounter, 1);
1184 return(struct dcache *) 0;
1186 } /*afs_FindDCache*/
1190 * afs_UFSCacheStoreProc
1193 * Called upon store.
1196 * acall : Ptr to the Rx call structure involved.
1197 * afile : Ptr to the related file descriptor.
1198 * alen : Size of the file in bytes.
1199 * avc : Ptr to the vcache entry.
1200 * shouldWake : is it "safe" to return early from close() ?
1201 * abytesToXferP : Set to the number of bytes to xfer.
1202 * NOTE: This parameter is only used if AFS_NOSTATS
1204 * abytesXferredP : Set to the number of bytes actually xferred.
1205 * NOTE: This parameter is only used if AFS_NOSTATS
1209 * Nothing interesting.
1211 static int afs_UFSCacheStoreProc(acall, afile, alen, avc, shouldWake,
1212 abytesToXferP, abytesXferredP)
1213 register struct rx_call *acall;
1214 struct osi_file *afile;
1215 register afs_int32 alen;
1218 afs_int32 *abytesToXferP;
1219 afs_int32 *abytesXferredP;
1220 { /* afs_UFSCacheStoreProc*/
1222 afs_int32 code, got;
1223 register char *tbuffer;
1226 AFS_STATCNT(UFS_CacheStoreProc);
1230 * In this case, alen is *always* the amount of data we'll be trying
1233 (*abytesToXferP) = alen;
1234 (*abytesXferredP) = 0;
1235 #endif /* AFS_NOSTATS */
1237 afs_Trace3(afs_iclSetp, CM_TRACE_STOREPROC, ICL_TYPE_POINTER, avc,
1238 ICL_TYPE_INT32, avc->m.Length, ICL_TYPE_INT32, alen);
1239 tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1241 tlen = (alen > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : alen);
1242 got = afs_osi_Read(afile, -1, tbuffer, tlen);
1244 #if !defined(AFS_SUN5_ENV) && !defined(AFS_OSF_ENV) && !defined(AFS_SGI64_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_FBSD_ENV)
1245 || (got != tlen && getuerror())
1248 osi_FreeLargeSpace(tbuffer);
1251 #ifdef RX_ENABLE_LOCKS
1253 #endif /* RX_ENABLE_LOCKS */
1254 code = rx_Write(acall, tbuffer, got); /* writing 0 bytes will
1255 * push a short packet. Is that really what we want, just because the
1256 * data didn't come back from the disk yet? Let's try it and see. */
1257 #ifdef RX_ENABLE_LOCKS
1259 #endif /* RX_ENABLE_LOCKS */
1261 (*abytesXferredP) += code;
1262 #endif /* AFS_NOSTATS */
1264 osi_FreeLargeSpace(tbuffer);
1269 * If file has been locked on server, we can allow the store
1272 if (shouldWake && *shouldWake && (rx_GetRemoteStatus(acall) & 1)) {
1273 *shouldWake = 0; /* only do this once */
1277 osi_FreeLargeSpace(tbuffer);
1280 } /* afs_UFSCacheStoreProc*/
1284 * afs_UFSCacheFetchProc
1287 * Routine called on fetch; also tells people waiting for data
1288 * that more has arrived.
1291 * acall : Ptr to the Rx call structure.
1292 * afile : File descriptor for the cache file.
1293 * abase : Base offset to fetch.
1294 * adc : Ptr to the dcache entry for the file.
1295 * avc : Ptr to the vcache entry for the file.
1296 * abytesToXferP : Set to the number of bytes to xfer.
1297 * NOTE: This parameter is only used if AFS_NOSTATS
1299 * abytesXferredP : Set to the number of bytes actually xferred.
1300 * NOTE: This parameter is only used if AFS_NOSTATS
1304 * Nothing interesting.
1307 static int afs_UFSCacheFetchProc(acall, afile, abase, adc, avc,
1308 abytesToXferP, abytesXferredP)
1309 register struct rx_call *acall;
1313 struct osi_file *afile;
1314 afs_int32 *abytesToXferP;
1315 afs_int32 *abytesXferredP;
1317 { /*UFS_CacheFetchProc*/
1320 register afs_int32 code;
1321 register char *tbuffer;
1325 AFS_STATCNT(UFS_CacheFetchProc);
1326 afile->offset = 0; /* Each time start from the beginning */
1328 (*abytesToXferP) = 0;
1329 (*abytesXferredP) = 0;
1330 #endif /* AFS_NOSTATS */
1331 tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1333 #ifdef RX_ENABLE_LOCKS
1335 #endif /* RX_ENABLE_LOCKS */
1336 code = rx_Read(acall, (char *)&length, sizeof(afs_int32));
1337 #ifdef RX_ENABLE_LOCKS
1339 #endif /* RX_ENABLE_LOCKS */
1340 if (code != sizeof(afs_int32)) {
1341 osi_FreeLargeSpace(tbuffer);
1342 code = rx_Error(acall);
1343 return (code?code:-1); /* try to return code, not -1 */
1345 length = ntohl(length);
1347 * The fetch protocol is extended for the AFS/DFS translator
1348 * to allow multiple blocks of data, each with its own length,
1349 * to be returned. As long as the top bit is set, there are more
1352 * We do not do this for AFS file servers because they sometimes
1353 * return large negative numbers as the transfer size.
1355 if (avc->states & CForeign) {
1356 moredata = length & 0x80000000;
1357 length &= ~0x80000000;
1362 (*abytesToXferP) += length;
1363 #endif /* AFS_NOSTATS */
1364 while (length > 0) {
1365 tlen = (length > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : length);
1366 #ifdef RX_ENABLE_LOCKS
1368 #endif /* RX_ENABLE_LOCKS */
1369 code = rx_Read(acall, tbuffer, tlen);
1370 #ifdef RX_ENABLE_LOCKS
1372 #endif /* RX_ENABLE_LOCKS */
1374 (*abytesXferredP) += code;
1375 #endif /* AFS_NOSTATS */
1377 osi_FreeLargeSpace(tbuffer);
1380 code = afs_osi_Write(afile, -1, tbuffer, tlen);
1382 osi_FreeLargeSpace(tbuffer);
1387 adc->validPos = abase;
1388 if (adc->flags & DFWaiting) {
1389 adc->flags &= ~DFWaiting;
1390 afs_osi_Wakeup(&adc->validPos);
1394 osi_FreeLargeSpace(tbuffer);
1397 } /* afs_UFSCacheFetchProc*/
1403 * This function is called to obtain a reference to data stored in
1404 * the disk cache, locating a chunk of data containing the desired
1405 * byte and returning a reference to the disk cache entry, with its
1406 * reference count incremented.
1410 * avc : Ptr to a vcache entry (unlocked)
1411 * abyte : Byte position in the file desired
1412 * areq : Request structure identifying the requesting user.
1413 * aflags : Settings as follows:
1415 * 2 : Return after creating entry.
1417 * aoffset : Set to the offset within the chunk where the resident
1419 * alen : Set to the number of bytes of data after the desired
1420 * byte (including the byte itself) which can be read
1424 * The vcache entry pointed to by avc is unlocked upon entry.
1428 struct AFSVolSync tsync;
1429 struct AFSFetchStatus OutStatus;
1430 struct AFSCallBack CallBack;
1433 /* these fields are protected by the lock on the vcache and luck
1435 #define updateV2DC(l,v,d,src) { if (l) ObtainWriteLock(&((v)->lock),src);\
1436 if (hsame((v)->m.DataVersion, (d)->f.versionNo) && (v)->callback) { \
1437 (v)->quick.dc = (d); \
1438 (v)->quick.stamp = (d)->stamp = MakeStamp(); \
1439 (v)->quick.minLoc = AFS_CHUNKTOBASE((d)->f.chunk); \
1440 /* Don't think I need these next two lines forever */ \
1441 (v)->quick.len = (d)->f.chunkBytes; \
1442 (v)->h1.dchint = (d); } if(l) ReleaseWriteLock(&((v)->lock)); }
1444 struct dcache *afs_GetDCache(avc, abyte, areq, aoffset, alen, aflags)
1445 register struct vcache *avc; /*Held*/
1448 afs_int32 *aoffset, *alen;
1449 register struct vrequest *areq;
1453 register afs_int32 i, code, code1, shortcut , adjustsize=0;
1458 afs_int32 maxGoodLength; /* amount of good data at server */
1459 struct rx_call *tcall;
1460 afs_int32 Position = 0;
1461 afs_int32 size; /* size of segment to transfer */
1462 struct tlocal1 *tsmall;
1463 register struct dcache *tdc;
1464 register struct osi_file *file;
1465 register struct conn *tc;
1469 struct afs_stats_xferData *xferP; /* Ptr to this op's xfer struct */
1470 osi_timeval_t xferStartTime, /*FS xfer start time*/
1471 xferStopTime; /*FS xfer stop time*/
1472 afs_int32 bytesToXfer; /* # bytes to xfer*/
1473 afs_int32 bytesXferred; /* # bytes actually xferred*/
1474 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats*/
1475 int fromReplica; /*Are we reading from a replica?*/
1476 int numFetchLoops; /*# times around the fetch/analyze loop*/
1477 #endif /* AFS_NOSTATS */
1479 AFS_STATCNT(afs_GetDCache);
1485 * Determine the chunk number and offset within the chunk corresponding
1486 * to the desired byte.
1488 if (vType(avc) == VDIR) {
1492 chunk = AFS_CHUNK(abyte);
1495 setLocks = aflags & 1;
1497 /* come back to here if we waited for the cache to drain. */
1501 /* check hints first! (might could use bcmp or some such...) */
1503 if (tdc = avc->h1.dchint) {
1504 MObtainReadLock(&afs_xdcache);
1505 if ( (tdc->index != NULLIDX) && !FidCmp(&tdc->f.fid, &avc->fid) &&
1506 chunk == tdc->f.chunk &&
1507 !(afs_indexFlags[tdc->index] & (IFFree|IFDiscarded))) {
1508 /* got the right one. It might not be the right version, and it
1509 * might be fetching, but it's the right dcache entry.
1511 /* All this code should be integrated better with what follows:
1512 * I can save a good bit more time under a write lock if I do..
1514 /* does avc need to be locked? */
1515 /* Note that the race labeled LOCKXXX is inconsequential: the xdcache
1516 * lock protects both the dcache slots AND the DLRU list. While
1517 * the slots and hash table and DLRU list all may change in the race,
1518 * THIS particular dcache structure cannot be recycled and its LRU
1519 * pointers must still be valid once we get the lock again. Still
1520 * we should either create another lock or invent a new method of
1521 * managing dcache structs -- CLOCK or something. */
1523 #ifdef AFS_SUN5_ENVX
1524 MObtainWriteLock(&tdc->lock,279);
1527 if (hsame(tdc->f.versionNo, avc->m.DataVersion)
1528 && !(tdc->flags & DFFetching)) {
1529 afs_stats_cmperf.dcacheHits++;
1530 MReleaseReadLock(&afs_xdcache);
1532 MObtainWriteLock(&afs_xdcache, 559); /* LOCKXXX */
1533 QRemove(&tdc->lruq);
1534 QAdd(&afs_DLRU, &tdc->lruq);
1535 MReleaseWriteLock(&afs_xdcache);
1538 #ifdef AFS_SUN5_ENVX
1539 MReleaseWriteLock(&tdc->lock);
1542 MReleaseReadLock(&afs_xdcache);
1548 * Hash on the [fid, chunk] and get the corresponding dcache index
1549 * after write-locking the dcache.
1552 i = DCHash(&avc->fid, chunk);
1553 afs_MaybeWakeupTruncateDaemon(); /* check to make sure our space is fine */
1554 MObtainWriteLock(&afs_xdcache,280);
1556 for(index = afs_dchashTbl[i]; index != NULLIDX;) {
1557 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1558 tdc = afs_GetDSlot(index, (struct dcache *)0);
1559 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1560 /* Move it up in the beginning of the list */
1561 if (afs_dchashTbl[i] != index) {
1562 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1563 afs_dcnextTbl[index] = afs_dchashTbl[i];
1564 afs_dchashTbl[i] = index;
1566 MReleaseWriteLock(&afs_xdcache);
1567 break; /* leaving refCount high for caller */
1569 lockedPutDCache(tdc);
1572 index = afs_dcnextTbl[index];
1575 * If we didn't find the entry, we'll create one.
1577 if (index == NULLIDX) {
1578 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER, avc,
1579 ICL_TYPE_INT32, chunk);
1581 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1583 if (!setLocks) avc->states |= CDCLock;
1584 afs_GetDownD(5, (int*)0); /* just need slots */
1585 if (!setLocks) avc->states &= (~CDCLock);
1586 if (afs_discardDCList != NULLIDX || afs_freeDCList != NULLIDX)
1588 /* If we can't get space for 5 mins we give up and panic */
1589 if (++downDCount > 300)
1590 osi_Panic("getdcache");
1591 MReleaseWriteLock(&afs_xdcache);
1592 afs_osi_Wait(1000, 0, 0);
1596 if (afs_discardDCList == NULLIDX ||
1597 ((aflags & 2) && afs_freeDCList != NULLIDX)) {
1598 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1599 tdc = afs_GetDSlot(afs_freeDCList, 0);
1600 afs_freeDCList = afs_dvnextTbl[tdc->index];
1603 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1604 tdc = afs_GetDSlot(afs_discardDCList, 0);
1605 afs_discardDCList = afs_dvnextTbl[tdc->index];
1606 afs_discardDCCount--;
1607 size = ((tdc->f.chunkBytes + afs_fsfragsize)^afs_fsfragsize)>>10;
1608 afs_blocksDiscarded -= size;
1609 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1611 /* Truncate the chunk so zeroes get filled properly */
1612 file = afs_CFileOpen(tdc->f.inode);
1613 afs_CFileTruncate(file, 0);
1614 afs_CFileClose(file);
1615 afs_AdjustSize(tdc, 0);
1620 * Fill in the newly-allocated dcache record.
1622 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1623 tdc->f.fid = avc->fid;
1624 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1625 hones(tdc->f.versionNo); /* invalid value */
1626 tdc->f.chunk = chunk;
1628 if (tdc->lruq.prev == &tdc->lruq) osi_Panic("lruq 1");
1630 * Now add to the two hash chains - note that i is still set
1631 * from the above DCHash call.
1633 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1634 afs_dchashTbl[i] = tdc->index;
1635 i = DVHash(&avc->fid);
1636 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1637 afs_dvhashTbl[i] = tdc->index;
1638 tdc->flags = DFEntryMod;
1640 afs_MaybeWakeupTruncateDaemon();
1641 MReleaseWriteLock(&afs_xdcache);
1643 } /* else hint failed... */
1645 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1646 ICL_TYPE_POINTER, tdc,
1647 ICL_TYPE_INT32, hgetlo(tdc->f.versionNo),
1648 ICL_TYPE_INT32, hgetlo(avc->m.DataVersion));
1650 * Here we have the unlocked entry in tdc, with its refCount
1651 * incremented. Note: we don't use the S-lock; it costs concurrency
1652 * when storing a file back to the server.
1654 if (setLocks) ObtainReadLock(&avc->lock);
1657 * Not a newly created file so we need to check the file's length and
1658 * compare data versions since someone could have changed the data or we're
1659 * reading a file written elsewhere. We only want to bypass doing no-op
1660 * read rpcs on newly created files (dv of 0) since only then we guarantee
1661 * that this chunk's data hasn't been filled by another client.
1663 if (!hiszero(avc->m.DataVersion))
1665 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1667 #ifdef AFS_SGI64_ENV
1668 if (aflags & 4) adjustsize = NBPP;
1670 if (aflags & 4) adjustsize = 8192;
1673 if (aflags & 4) adjustsize = 4096;
1675 if (AFS_CHUNKTOBASE(chunk)+adjustsize >= avc->m.Length &&
1677 #if defined(AFS_SUN_ENV) || defined(AFS_OSF_ENV)
1678 if (((aflags & 4) || (AFS_CHUNKTOBASE(chunk) >= avc->m.Length)) &&
1680 if (AFS_CHUNKTOBASE(chunk) >= avc->m.Length &&
1683 !hsame(avc->m.DataVersion, tdc->f.versionNo)) {
1684 /* no data in file to read at this position */
1686 ReleaseReadLock(&avc->lock);
1687 ObtainWriteLock(&avc->lock,64);
1689 /* check again, now that we have a write lock */
1690 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1691 if (AFS_CHUNKTOBASE(chunk)+adjustsize >= avc->m.Length &&
1693 #if defined(AFS_SUN_ENV) || defined(AFS_OSF_ENV)
1694 if (((aflags & 4) || (AFS_CHUNKTOBASE(chunk) >= avc->m.Length)) &&
1696 if (AFS_CHUNKTOBASE(chunk) >= avc->m.Length &&
1699 !hsame(avc->m.DataVersion, tdc->f.versionNo)) {
1700 file = afs_CFileOpen(tdc->f.inode);
1701 afs_CFileTruncate(file, 0);
1702 afs_CFileClose(file);
1703 afs_AdjustSize(tdc, 0);
1704 hset(tdc->f.versionNo, avc->m.DataVersion);
1705 tdc->flags |= DFEntryMod;
1708 ReleaseWriteLock(&avc->lock);
1709 ObtainReadLock(&avc->lock);
1712 if (setLocks) ReleaseReadLock(&avc->lock);
1715 * We must read in the whole chunk iff the version number doesn't
1719 /* don't need data, just a unique dcache entry */
1720 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1721 hadd32(afs_indexCounter, 1);
1722 updateV2DC(setLocks,avc,tdc,567);
1723 return tdc; /* check if we're done */
1725 osi_Assert(setLocks || WriteLocked(&avc->lock));
1727 if (setLocks) ObtainReadLock(&avc->lock);
1728 if (!hsame(avc->m.DataVersion, tdc->f.versionNo)) {
1730 * Version number mismatch.
1733 ReleaseReadLock(&avc->lock);
1734 ObtainWriteLock(&avc->lock,65);
1738 * If data ever existed for this vnode, and this is a text object,
1739 * do some clearing. Now, you'd think you need only do the flush
1740 * when VTEXT is on, but VTEXT is turned off when the text object
1741 * is freed, while pages are left lying around in memory marked
1742 * with this vnode. If we would reactivate (create a new text
1743 * object from) this vnode, we could easily stumble upon some of
1744 * these old pages in pagein. So, we always flush these guys.
1745 * Sun has a wonderful lack of useful invariants in this system.
1747 * avc->flushDV is the data version # of the file at the last text
1748 * flush. Clearly, at least, we don't have to flush the file more
1749 * often than it changes
1751 if (hcmp(avc->flushDV, avc->m.DataVersion) < 0) {
1753 * By here, the cache entry is always write-locked. We can
1754 * deadlock if we call osi_Flush with the cache entry locked...
1756 ReleaseWriteLock(&avc->lock);
1759 * Call osi_FlushPages in open, read/write, and map, since it
1760 * is too hard here to figure out if we should lock the
1763 ObtainWriteLock(&avc->lock,66);
1766 /* Watch for standard race condition */
1767 if (hsame(avc->m.DataVersion, tdc->f.versionNo)) {
1768 updateV2DC(0,avc,tdc,569); /* set hint */
1769 if (setLocks) ReleaseWriteLock(&avc->lock);
1770 afs_stats_cmperf.dcacheHits++;
1774 /* Sleep here when cache needs to be drained. */
1776 (afs_blocksUsed > (CM_WAITFORDRAINPCT*afs_cacheBlocks)/100)) {
1777 /* Make sure truncate daemon is running */
1778 afs_MaybeWakeupTruncateDaemon();
1779 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
1780 ReleaseWriteLock(&avc->lock);
1781 while ((afs_blocksUsed-afs_blocksDiscarded) >
1782 (CM_WAITFORDRAINPCT*afs_cacheBlocks)/100) {
1783 afs_WaitForCacheDrain = 1;
1784 afs_osi_Sleep(&afs_WaitForCacheDrain);
1786 afs_MaybeFreeDiscardedDCache();
1787 /* need to check if someone else got the chunk first. */
1788 goto RetryGetDCache;
1791 /* Do not fetch data beyond truncPos. */
1792 maxGoodLength = avc->m.Length;
1793 if (avc->truncPos < maxGoodLength) maxGoodLength = avc->truncPos;
1794 Position = AFS_CHUNKBASE(abyte);
1795 if (vType(avc) == VDIR) {
1796 size = avc->m.Length;
1797 if (size > tdc->f.chunkBytes) {
1798 /* pre-reserve space for file */
1799 afs_AdjustSize(tdc, size);
1801 size = 999999999; /* max size for transfer */
1804 size = AFS_CHUNKSIZE(abyte); /* expected max size */
1805 /* don't read past end of good data on server */
1806 if (Position + size > maxGoodLength)
1807 size = maxGoodLength - Position;
1808 if (size < 0) size = 0; /* Handle random races */
1809 if (size > tdc->f.chunkBytes) {
1810 /* pre-reserve space for file */
1811 afs_AdjustSize(tdc, size); /* changes chunkBytes */
1812 /* max size for transfer still in size */
1815 if (afs_mariner && !tdc->f.chunk)
1816 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter );*/
1818 * Right now, we only have one tool, and it's a hammer. So, we
1819 * fetch the whole file.
1821 DZap(&tdc->f.inode); /* pages in cache may be old */
1823 if (file = tdc->ihint) {
1824 if (tdc->f.inode == file->inum )
1831 file = osi_UFSOpen(tdc->f.inode);
1836 file = afs_CFileOpen(tdc->f.inode);
1837 afs_RemoveVCB(&avc->fid);
1838 tdc->f.states |= DWriting;
1839 tdc->flags |= DFFetching;
1840 tdc->validPos = Position; /*Last valid position in this chunk*/
1841 if (tdc->flags & DFFetchReq) {
1842 tdc->flags &= ~DFFetchReq;
1843 afs_osi_Wakeup(&tdc->validPos);
1845 tsmall = (struct tlocal1 *) osi_AllocLargeSpace(sizeof(struct tlocal1));
1848 * Remember if we are doing the reading from a replicated volume,
1849 * and how many times we've zipped around the fetch/analyze loop.
1851 fromReplica = (avc->states & CRO) ? 1 : 0;
1853 accP = &(afs_stats_cmfullperf.accessinf);
1855 (accP->replicatedRefs)++;
1857 (accP->unreplicatedRefs)++;
1858 #endif /* AFS_NOSTATS */
1859 /* this is a cache miss */
1860 afs_stats_cmperf.dcacheMisses++;
1861 afs_Trace3(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
1862 ICL_TYPE_INT32, Position, ICL_TYPE_INT32, size);
1864 tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
1869 (accP->numReplicasAccessed)++;
1871 #endif /* AFS_NOSTATS */
1872 avc->callback = tc->srvr->server;
1873 ConvertWToSLock(&avc->lock);
1875 #ifdef RX_ENABLE_LOCKS
1877 #endif /* RX_ENABLE_LOCKS */
1878 tcall = rx_NewCall(tc->id);
1879 #ifdef RX_ENABLE_LOCKS
1881 #endif /* RX_ENABLE_LOCKS */
1884 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
1885 #ifdef RX_ENABLE_LOCKS
1887 #endif /* RX_ENABLE_LOCKS */
1888 code = StartRXAFS_FetchData(tcall,
1889 (struct AFSFid *) &avc->fid.Fid,
1891 #ifdef RX_ENABLE_LOCKS
1893 #endif /* RX_ENABLE_LOCKS */
1897 xferP = &(afs_stats_cmfullperf.rpc.fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
1898 osi_GetuTime(&xferStartTime);
1900 code = afs_CacheFetchProc(tcall, file, Position, tdc, avc,
1901 &bytesToXfer, &bytesXferred);
1903 osi_GetuTime(&xferStopTime);
1904 (xferP->numXfers)++;
1906 (xferP->numSuccesses)++;
1907 afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_FETCHDATA] += bytesXferred;
1908 (xferP->sumBytes) += (afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
1909 afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
1910 if (bytesXferred < xferP->minBytes)
1911 xferP->minBytes = bytesXferred;
1912 if (bytesXferred > xferP->maxBytes)
1913 xferP->maxBytes = bytesXferred;
1916 * Tally the size of the object. Note: we tally the actual size,
1917 * NOT the number of bytes that made it out over the wire.
1919 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
1920 (xferP->count[0])++;
1922 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET1)
1923 (xferP->count[1])++;
1925 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET2)
1926 (xferP->count[2])++;
1928 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET3)
1929 (xferP->count[3])++;
1931 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET4)
1932 (xferP->count[4])++;
1934 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET5)
1935 (xferP->count[5])++;
1937 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET6)
1938 (xferP->count[6])++;
1940 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET7)
1941 (xferP->count[7])++;
1943 (xferP->count[8])++;
1945 afs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
1946 afs_stats_AddTo((xferP->sumTime), elapsedTime);
1947 afs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
1948 if (afs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
1949 afs_stats_TimeAssign((xferP->minTime), elapsedTime);
1951 if (afs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
1952 afs_stats_TimeAssign((xferP->maxTime), elapsedTime);
1956 code = afs_CacheFetchProc(tcall, file, Position, tdc, avc, 0, 0);
1957 #endif /* AFS_NOSTATS */
1960 #ifdef RX_ENABLE_LOCKS
1962 #endif /* RX_ENABLE_LOCKS */
1963 code = EndRXAFS_FetchData(tcall,
1967 #ifdef RX_ENABLE_LOCKS
1969 #endif /* RX_ENABLE_LOCKS */
1972 code1 = rx_EndCall(tcall, code);
1973 UpgradeSToWLock(&avc->lock,27);
1978 if ( !code && code1 )
1982 /* callback could have been broken (or expired) in a race here,
1983 * but we return the data anyway. It's as good as we knew about
1984 * when we started. */
1986 * validPos is updated by CacheFetchProc, and can only be
1987 * modifed under an S or W lock, which we've blocked out
1989 size = tdc->validPos - Position; /* actual segment size */
1990 if (size < 0) size = 0;
1991 afs_CFileTruncate(file, size); /* prune it */
1994 ObtainWriteLock(&afs_xcbhash, 453);
1995 afs_DequeueCallback(avc);
1996 avc->states &= ~(CStatd | CUnique);
1997 avc->callback = (struct server *)0;
1998 ReleaseWriteLock(&afs_xcbhash);
1999 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2000 osi_dnlc_purgedp(avc);
2004 (afs_Analyze(tc, code, &avc->fid, areq,
2005 AFS_STATS_FS_RPCIDX_FETCHDATA,
2006 SHARED_LOCK, (struct cell *)0));
2010 * In the case of replicated access, jot down info on the number of
2011 * attempts it took before we got through or gave up.
2014 if (numFetchLoops <= 1)
2015 (accP->refFirstReplicaOK)++;
2016 if (numFetchLoops > accP->maxReplicasPerRef)
2017 accP->maxReplicasPerRef = numFetchLoops;
2019 #endif /* AFS_NOSTATS */
2021 tdc->flags &= ~DFFetching;
2022 if (tdc->flags & DFWaiting) {
2023 tdc->flags &= ~DFWaiting;
2024 afs_osi_Wakeup(&tdc->validPos);
2026 if (avc->execsOrWriters == 0) tdc->f.states &= ~DWriting;
2028 /* now, if code != 0, we have an error and should punt */
2030 afs_CFileTruncate(file, 0);
2031 afs_AdjustSize(tdc, 0);
2032 afs_CFileClose(file);
2033 ZapDCE(tdc); /* sets DFEntryMod */
2034 if (vType(avc) == VDIR) {
2035 DZap(&tdc->f.inode);
2037 #ifdef AFS_SUN5_ENVX
2042 ObtainWriteLock(&afs_xcbhash, 454);
2043 afs_DequeueCallback(avc);
2044 avc->states &= ~( CStatd | CUnique );
2045 ReleaseWriteLock(&afs_xcbhash);
2046 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2047 osi_dnlc_purgedp(avc);
2048 if (setLocks) ReleaseWriteLock(&avc->lock);
2049 osi_FreeLargeSpace(tsmall);
2050 tdc = (struct dcache *) 0;
2054 /* otherwise we copy in the just-fetched info */
2055 afs_CFileClose(file);
2056 afs_AdjustSize(tdc, size); /* new size */
2058 * Copy appropriate fields into vcache
2060 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2061 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh, tsmall->OutStatus.DataVersion);
2062 tdc->flags |= DFEntryMod;
2063 afs_indexFlags[tdc->index] |= IFEverUsed;
2064 if (setLocks) ReleaseWriteLock(&avc->lock);
2065 osi_FreeLargeSpace(tsmall);
2066 } /*Data version numbers don't match*/
2069 * Data version numbers match. Release locks if we locked
2070 * them, and remember we've had a cache hit.
2073 ReleaseReadLock(&avc->lock);
2074 afs_stats_cmperf.dcacheHits++;
2075 } /*Data version numbers match*/
2077 updateV2DC(setLocks,avc,tdc,332); /* set hint */
2080 * See if this was a reference to a file in the local cell.
2082 if (avc->fid.Cell == LOCALCELL)
2083 afs_stats_cmperf.dlocalAccesses++;
2085 afs_stats_cmperf.dremoteAccesses++;
2087 /* Fix up LRU info */
2090 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2091 hadd32(afs_indexCounter, 1);
2093 /* return the data */
2094 if (vType(avc) == VDIR)
2097 *aoffset = AFS_CHUNKOFFSET(abyte);
2098 *alen = (tdc->f.chunkBytes - *aoffset);
2107 * afs_WriteThroughDSlots
2110 * Sweep through the dcache slots and write out any modified
2111 * in-memory data back on to our caching store.
2117 * The afs_xdcache is write-locked through this whole affair.
2120 afs_WriteThroughDSlots()
2122 { /*afs_WriteThroughDSlots*/
2124 register struct dcache *tdc;
2125 register afs_int32 i, touchedit=0;
2127 AFS_STATCNT(afs_WriteThroughDSlots);
2128 MObtainWriteLock(&afs_xdcache,283);
2129 for(i = 0; i < afs_cacheFiles; i++) {
2130 tdc = afs_indexTable[i];
2131 if (tdc && (tdc->flags & DFEntryMod)) {
2132 tdc->flags &= ~DFEntryMod;
2133 afs_WriteDCache(tdc, 1);
2137 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2138 /* Touch the file to make sure that the mtime on the file is kept up-to-date
2139 * to avoid losing cached files on cold starts because their mtime seems old...
2141 struct afs_fheader theader;
2143 theader.magic = AFS_FHMAGIC;
2144 theader.firstCSize = AFS_FIRSTCSIZE;
2145 theader.otherCSize = AFS_OTHERCSIZE;
2146 theader.version = AFS_CI_VERSION;
2147 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2149 MReleaseWriteLock(&afs_xdcache);
2151 } /*afs_WriteThroughDSlots*/
2157 * Return a pointer to an freshly initialized dcache entry using
2158 * a memory-based cache.
2161 * aslot : Dcache slot to look at.
2162 * tmpdc : Ptr to dcache entry.
2165 * Nothing interesting.
2168 struct dcache *afs_MemGetDSlot(aslot, tmpdc)
2169 register afs_int32 aslot;
2170 register struct dcache *tmpdc;
2172 { /*afs_MemGetDSlot*/
2174 register afs_int32 code;
2175 register struct dcache *tdc;
2176 register char *tfile;
2178 AFS_STATCNT(afs_MemGetDSlot);
2179 if (CheckLock(&afs_xdcache) != -1) osi_Panic("getdslot nolock");
2180 if (aslot < 0 || aslot >= afs_cacheFiles) osi_Panic("getdslot slot");
2181 tdc = afs_indexTable[aslot];
2183 QRemove(&tdc->lruq); /* move to queue head */
2184 QAdd(&afs_DLRU, &tdc->lruq);
2188 if (tmpdc == (struct dcache *)0) {
2189 if (!afs_freeDSList) afs_GetDownDSlot(4);
2190 if (!afs_freeDSList) {
2191 /* none free, making one is better than a panic */
2192 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2193 tdc = (struct dcache *) afs_osi_Alloc(sizeof (struct dcache));
2194 #ifdef AFS_AIX32_ENV
2195 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2198 tdc = afs_freeDSList;
2199 afs_freeDSList = (struct dcache *) tdc->lruq.next;
2201 tdc->flags = 0; /* up-to-date, not in free q */
2202 QAdd(&afs_DLRU, &tdc->lruq);
2203 if (tdc->lruq.prev == &tdc->lruq) osi_Panic("lruq 3");
2210 /* initialize entry */
2211 tdc->f.fid.Cell = 0;
2212 tdc->f.fid.Fid.Volume = 0;
2214 hones(tdc->f.versionNo);
2215 tdc->f.inode = aslot;
2216 tdc->flags |= DFEntryMod;
2219 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2221 if (tmpdc == (struct dcache *)0)
2222 afs_indexTable[aslot] = tdc;
2225 } /*afs_MemGetDSlot*/
2227 unsigned int last_error = 0, lasterrtime = 0;
2233 * Return a pointer to an freshly initialized dcache entry using
2234 * a UFS-based disk cache.
2237 * aslot : Dcache slot to look at.
2238 * tmpdc : Ptr to dcache entry.
2241 * afs_xdcache lock write-locked.
2243 struct dcache *afs_UFSGetDSlot(aslot, tmpdc)
2244 register afs_int32 aslot;
2245 register struct dcache *tmpdc;
2247 { /*afs_UFSGetDSlot*/
2249 register afs_int32 code;
2250 register struct dcache *tdc;
2252 AFS_STATCNT(afs_UFSGetDSlot);
2253 if (CheckLock(&afs_xdcache) != -1) osi_Panic("getdslot nolock");
2254 if (aslot < 0 || aslot >= afs_cacheFiles) osi_Panic("getdslot slot");
2255 tdc = afs_indexTable[aslot];
2257 #ifdef AFS_SUN5_ENVX
2258 mutex_enter(&tdc->lock);
2260 QRemove(&tdc->lruq); /* move to queue head */
2261 QAdd(&afs_DLRU, &tdc->lruq);
2265 /* otherwise we should read it in from the cache file */
2267 * If we weren't passed an in-memory region to place the file info,
2268 * we have to allocate one.
2270 if (tmpdc == (struct dcache *)0) {
2271 if (!afs_freeDSList) afs_GetDownDSlot(4);
2272 if (!afs_freeDSList) {
2273 /* none free, making one is better than a panic */
2274 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2275 tdc = (struct dcache *) afs_osi_Alloc(sizeof (struct dcache));
2276 #ifdef AFS_AIX32_ENV
2277 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2280 tdc = afs_freeDSList;
2281 afs_freeDSList = (struct dcache *) tdc->lruq.next;
2283 tdc->flags = 0; /* up-to-date, not in free q */
2284 QAdd(&afs_DLRU, &tdc->lruq);
2285 if (tdc->lruq.prev == &tdc->lruq) osi_Panic("lruq 3");
2293 #ifdef AFS_SUN5_ENVX
2294 mutex_enter(&tdc->lock);
2297 * Seek to the aslot'th entry and read it in.
2299 code = afs_osi_Read(afs_cacheInodep, sizeof(struct fcache) * aslot + sizeof(struct afs_fheader),
2300 (char *)(&tdc->f), sizeof(struct fcache));
2301 if (code != sizeof(struct fcache)) {
2302 tdc->f.fid.Cell = 0;
2303 tdc->f.fid.Fid.Volume = 0;
2305 hones(tdc->f.versionNo);
2306 tdc->flags |= DFEntryMod;
2307 #if !defined(AFS_SUN5_ENV) && !defined(AFS_OSF_ENV) && !defined(AFS_SGI64_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_FBSD_ENV)
2308 last_error = getuerror();
2310 lasterrtime = osi_Time();
2311 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2317 * If we didn't read into a temporary dcache region, update the
2318 * slot pointer table.
2320 if (tmpdc == (struct dcache *)0)
2321 afs_indexTable[aslot] = tdc;
2324 } /*afs_UFSGetDSlot*/
2332 * write a particular dcache entry back to its home in the
2336 * adc : Pointer to the dcache entry to write.
2337 * atime : If true, set the modtime on the file to the current time.
2340 * Must be called with the afs_xdcache lock at least read-locked.
2341 * The reference count is not changed.
2344 afs_WriteDCache(adc, atime)
2346 register struct dcache *adc;
2348 { /*afs_WriteDCache*/
2350 register struct osi_file *tfile;
2351 register afs_int32 code;
2353 if (cacheDiskType == AFS_FCACHE_TYPE_MEM) return 0;
2354 AFS_STATCNT(afs_WriteDCache);
2356 adc->f.modTime = osi_Time();
2358 * Seek to the right dcache slot and write the in-memory image out to disk.
2360 code = afs_osi_Write(afs_cacheInodep, sizeof(struct fcache) * adc->index + sizeof(struct afs_fheader),
2361 (char *)(&adc->f), sizeof(struct fcache));
2362 if (code != sizeof(struct fcache)) return EIO;
2365 } /*afs_WriteDCache*/
2373 * Wake up users of a particular file waiting for stores to take
2377 * avc : Ptr to related vcache entry.
2380 * Nothing interesting.
2384 register struct vcache *avc;
2389 register struct brequest *tb;
2391 AFS_STATCNT(afs_wakeup);
2392 for (i = 0; i < NBRS; i++, tb++) {
2393 /* if request is valid and for this file, we've found it */
2394 if (tb->refCount > 0 && avc == tb->vnode) {
2397 * If CSafeStore is on, then we don't awaken the guy
2398 * waiting for the store until the whole store has finished.
2399 * Otherwise, we do it now. Note that if CSafeStore is on,
2400 * the BStore routine actually wakes up the user, instead
2402 * I think this is redundant now because this sort of thing
2403 * is already being handled by the higher-level code.
2405 if ((avc->states & CSafeStore) == 0) {
2407 tb->flags |= BUVALID;
2408 if (tb->flags & BUWAIT) {
2409 tb->flags &= ~BUWAIT;
2425 * Given a file name and inode, set up that file to be an
2426 * active member in the AFS cache. This also involves checking
2427 * the usability of its data.
2430 * afile : Name of the cache file to initialize.
2431 * ainode : Inode of the file.
2434 * This function is called only during initialization.
2437 int afs_InitCacheFile(afile, ainode)
2441 { /*afs_InitCacheFile*/
2443 register afs_int32 code;
2444 #ifdef AFS_LINUX22_ENV
2445 struct dentry *filevp;
2447 struct vnode *filevp;
2451 struct osi_file *tfile;
2452 struct osi_stat tstat;
2453 register struct dcache *tdc;
2455 AFS_STATCNT(afs_InitCacheFile);
2456 index = afs_stats_cmperf.cacheNumEntries;
2457 if (index >= afs_cacheFiles) return EINVAL;
2459 MObtainWriteLock(&afs_xdcache,282);
2460 tdc = afs_GetDSlot(index, (struct dcache *)0);
2461 MReleaseWriteLock(&afs_xdcache);
2463 code = gop_lookupname(afile,
2466 (struct vnode **) 0,
2473 * We have a VN_HOLD on filevp. Get the useful info out and
2474 * return. We make use of the fact that the cache is in the
2475 * UFS file system, and just record the inode number.
2477 #ifdef AFS_LINUX22_ENV
2478 tdc->f.inode = VTOI(filevp->d_inode)->i_number;
2481 tdc->f.inode = afs_vnodeToInumber(filevp);
2485 AFS_RELE((struct vnode *)filevp);
2487 #endif /* AFS_LINUX22_ENV */
2490 tdc->f.inode = ainode;
2493 if ((tdc->f.states & DWriting) ||
2494 tdc->f.fid.Fid.Volume == 0) fileIsBad = 1;
2495 tfile = osi_UFSOpen(tdc->f.inode);
2496 code = afs_osi_Stat(tfile, &tstat);
2497 if (code) osi_Panic("initcachefile stat");
2500 * If file size doesn't match the cache info file, it's probably bad.
2502 if (tdc->f.chunkBytes != tstat.size) fileIsBad = 1;
2503 tdc->f.chunkBytes = 0;
2506 * If file changed within T (120?) seconds of cache info file, it's
2507 * probably bad. In addition, if slot changed within last T seconds,
2508 * the cache info file may be incorrectly identified, and so slot
2511 if (cacheInfoModTime < tstat.mtime + 120) fileIsBad = 1;
2512 if (cacheInfoModTime < tdc->f.modTime + 120) fileIsBad = 1;
2513 /* In case write through is behind, make sure cache items entry is
2514 * at least as new as the chunk.
2516 if (tdc->f.modTime < tstat.mtime) fileIsBad = 1;
2518 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
2519 if (tstat.size != 0)
2520 osi_UFSTruncate(tfile, 0);
2521 /* put entry in free cache slot list */
2522 afs_dvnextTbl[tdc->index] = afs_freeDCList;
2523 afs_freeDCList = index;
2525 afs_indexFlags[index] |= IFFree;
2526 afs_indexUnique[index] = 0;
2530 * We must put this entry in the appropriate hash tables.
2531 * Note that i is still set from the above DCHash call
2533 code = DCHash(&tdc->f.fid, tdc->f.chunk);
2534 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
2535 afs_dchashTbl[code] = tdc->index;
2536 code = DVHash(&tdc->f.fid);
2537 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
2538 afs_dvhashTbl[code] = tdc->index;
2539 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
2541 /* has nontrivial amt of data */
2542 afs_indexFlags[index] |= IFEverUsed;
2543 afs_stats_cmperf.cacheFilesReused++;
2545 * Initialize index times to file's mod times; init indexCounter
2548 hset32(afs_indexTimes[index], tstat.atime);
2549 if (hgetlo(afs_indexCounter) < tstat.atime) {
2550 hset32(afs_indexCounter, tstat.atime);
2552 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
2553 } /*File is not bad*/
2555 osi_UFSClose(tfile);
2556 tdc->f.states &= ~DWriting;
2557 tdc->flags &= ~DFEntryMod;
2558 /* don't set f.modTime; we're just cleaning up */
2559 afs_WriteDCache(tdc, 0);
2561 afs_stats_cmperf.cacheNumEntries++;
2564 } /*afs_InitCacheFile*/
2567 /*Max # of struct dcache's resident at any time*/
2569 * If 'dchint' is enabled then in-memory dcache min is increased because of
2578 * Initialize dcache related variables.
2580 void afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk,
2583 register struct dcache *tdp;
2587 afs_freeDCList = NULLIDX;
2588 afs_discardDCList = NULLIDX;
2589 afs_freeDCCount = 0;
2590 afs_freeDSList = (struct dcache *)0;
2591 hzero(afs_indexCounter);
2593 LOCK_INIT(&afs_xdcache, "afs_xdcache");
2599 if (achunk < 0 || achunk > 30)
2600 achunk = 13; /* Use default */
2601 AFS_SETCHUNKSIZE(achunk);
2607 if(aflags & AFSCALL_INIT_MEMCACHE) {
2609 * Use a memory cache instead of a disk cache
2611 cacheDiskType = AFS_FCACHE_TYPE_MEM;
2612 afs_cacheType = &afs_MemCacheOps;
2613 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
2614 ablocks = afiles * (AFS_FIRSTCSIZE/1024);
2615 /* ablocks is reported in 1K blocks */
2616 code = afs_InitMemCache(afiles * AFS_FIRSTCSIZE, AFS_FIRSTCSIZE, aflags);
2618 printf("afsd: memory cache too large for available memory.\n");
2619 printf("afsd: AFS files cannot be accessed.\n\n");
2621 afiles = ablocks = 0;
2624 printf("Memory cache: Allocating %d dcache entries...", aDentries);
2626 cacheDiskType = AFS_FCACHE_TYPE_UFS;
2627 afs_cacheType = &afs_UfsCacheOps;
2630 if (aDentries > 512)
2631 afs_dhashsize = 2048;
2632 /* initialize hash tables */
2633 afs_dvhashTbl = (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
2634 afs_dchashTbl = (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
2635 for(i=0;i< afs_dhashsize;i++) {
2636 afs_dvhashTbl[i] = NULLIDX;
2637 afs_dchashTbl[i] = NULLIDX;
2639 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
2640 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
2641 for(i=0;i< afiles;i++) {
2642 afs_dvnextTbl[i] = NULLIDX;
2643 afs_dcnextTbl[i] = NULLIDX;
2646 /* Allocate and zero the pointer array to the dcache entries */
2647 afs_indexTable = (struct dcache **)
2648 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
2649 bzero((char *)afs_indexTable, sizeof(struct dcache *) * afiles);
2650 afs_indexTimes = (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
2651 bzero((char *)afs_indexTimes, afiles * sizeof(afs_hyper_t));
2652 afs_indexUnique = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
2653 bzero((char *)afs_indexUnique, afiles * sizeof(afs_uint32));
2654 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
2655 bzero((char *)afs_indexFlags, afiles * sizeof(char));
2657 /* Allocate and thread the struct dcache entries themselves */
2658 tdp = afs_Initial_freeDSList =
2659 (struct dcache *) afs_osi_Alloc(aDentries * sizeof(struct dcache));
2660 bzero((char *)tdp, aDentries * sizeof(struct dcache));
2661 #ifdef AFS_AIX32_ENV
2662 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles);/* XXX */
2663 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
2664 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
2665 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
2666 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
2667 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
2668 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
2669 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
2670 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
2673 afs_freeDSList = &tdp[0];
2674 for(i=0; i < aDentries-1; i++) {
2675 tdp[i].lruq.next = (struct afs_q *) (&tdp[i+1]);
2677 tdp[aDentries-1].lruq.next = (struct afs_q *) 0;
2679 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal = afs_cacheBlocks = ablocks;
2680 afs_ComputeCacheParms(); /* compute parms based on cache size */
2682 afs_dcentries = aDentries;
2693 void shutdown_dcache(void)
2697 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
2698 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
2699 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
2700 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
2701 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
2702 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
2703 afs_osi_Free(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
2704 #ifdef AFS_AIX32_ENV
2705 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
2706 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
2707 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
2708 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
2709 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
2710 unpin((u_char *)afs_indexFlags, afs_cacheFiles * sizeof(u_char));
2711 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
2715 for(i=0;i< afs_dhashsize;i++) {
2716 afs_dvhashTbl[i] = NULLIDX;
2717 afs_dchashTbl[i] = NULLIDX;
2721 afs_blocksUsed = afs_dcentries = 0;
2722 hzero(afs_indexCounter);
2724 afs_freeDCCount = 0;
2725 afs_freeDCList = NULLIDX;
2726 afs_discardDCList = NULLIDX;
2727 afs_freeDSList = afs_Initial_freeDSList = 0;
2729 LOCK_INIT(&afs_xdcache, "afs_xdcache");