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) { \
1436 if (!l || 0 == NBObtainWriteLock(&((v)->lock),src)) { \
1437 if (hsame((v)->m.DataVersion, (d)->f.versionNo) && (v)->callback) { \
1438 (v)->quick.dc = (d); \
1439 (v)->quick.stamp = (d)->stamp = MakeStamp(); \
1440 (v)->quick.minLoc = AFS_CHUNKTOBASE((d)->f.chunk); \
1441 /* Don't think I need these next two lines forever */ \
1442 (v)->quick.len = (d)->f.chunkBytes; \
1443 (v)->h1.dchint = (d); \
1445 if(l) ReleaseWriteLock(&((v)->lock)); \
1448 struct dcache *afs_GetDCache(avc, abyte, areq, aoffset, alen, aflags)
1449 register struct vcache *avc; /*Held*/
1452 afs_int32 *aoffset, *alen;
1453 register struct vrequest *areq;
1457 register afs_int32 i, code, code1, shortcut , adjustsize=0;
1462 afs_int32 maxGoodLength; /* amount of good data at server */
1463 struct rx_call *tcall;
1464 afs_int32 Position = 0;
1465 afs_int32 size; /* size of segment to transfer */
1466 struct tlocal1 *tsmall;
1467 register struct dcache *tdc;
1468 register struct osi_file *file;
1469 register struct conn *tc;
1473 struct afs_stats_xferData *xferP; /* Ptr to this op's xfer struct */
1474 osi_timeval_t xferStartTime, /*FS xfer start time*/
1475 xferStopTime; /*FS xfer stop time*/
1476 afs_int32 bytesToXfer; /* # bytes to xfer*/
1477 afs_int32 bytesXferred; /* # bytes actually xferred*/
1478 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats*/
1479 int fromReplica; /*Are we reading from a replica?*/
1480 int numFetchLoops; /*# times around the fetch/analyze loop*/
1481 #endif /* AFS_NOSTATS */
1483 AFS_STATCNT(afs_GetDCache);
1489 * Determine the chunk number and offset within the chunk corresponding
1490 * to the desired byte.
1492 if (vType(avc) == VDIR) {
1496 chunk = AFS_CHUNK(abyte);
1499 setLocks = aflags & 1;
1501 /* come back to here if we waited for the cache to drain. */
1505 /* check hints first! (might could use bcmp or some such...) */
1507 if (tdc = avc->h1.dchint) {
1508 MObtainReadLock(&afs_xdcache);
1509 if ( (tdc->index != NULLIDX) && !FidCmp(&tdc->f.fid, &avc->fid) &&
1510 chunk == tdc->f.chunk &&
1511 !(afs_indexFlags[tdc->index] & (IFFree|IFDiscarded))) {
1512 /* got the right one. It might not be the right version, and it
1513 * might be fetching, but it's the right dcache entry.
1515 /* All this code should be integrated better with what follows:
1516 * I can save a good bit more time under a write lock if I do..
1518 /* does avc need to be locked? */
1519 /* Note that the race labeled LOCKXXX is inconsequential: the xdcache
1520 * lock protects both the dcache slots AND the DLRU list. While
1521 * the slots and hash table and DLRU list all may change in the race,
1522 * THIS particular dcache structure cannot be recycled and its LRU
1523 * pointers must still be valid once we get the lock again. Still
1524 * we should either create another lock or invent a new method of
1525 * managing dcache structs -- CLOCK or something. */
1527 #ifdef AFS_SUN5_ENVX
1528 MObtainWriteLock(&tdc->lock,279);
1531 if (hsame(tdc->f.versionNo, avc->m.DataVersion)
1532 && !(tdc->flags & DFFetching)) {
1533 afs_stats_cmperf.dcacheHits++;
1534 MReleaseReadLock(&afs_xdcache);
1536 MObtainWriteLock(&afs_xdcache, 559); /* LOCKXXX */
1537 QRemove(&tdc->lruq);
1538 QAdd(&afs_DLRU, &tdc->lruq);
1539 MReleaseWriteLock(&afs_xdcache);
1542 #ifdef AFS_SUN5_ENVX
1543 MReleaseWriteLock(&tdc->lock);
1546 MReleaseReadLock(&afs_xdcache);
1552 * Hash on the [fid, chunk] and get the corresponding dcache index
1553 * after write-locking the dcache.
1556 i = DCHash(&avc->fid, chunk);
1557 afs_MaybeWakeupTruncateDaemon(); /* check to make sure our space is fine */
1558 MObtainWriteLock(&afs_xdcache,280);
1560 for(index = afs_dchashTbl[i]; index != NULLIDX;) {
1561 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1562 tdc = afs_GetDSlot(index, (struct dcache *)0);
1563 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1564 /* Move it up in the beginning of the list */
1565 if (afs_dchashTbl[i] != index) {
1566 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1567 afs_dcnextTbl[index] = afs_dchashTbl[i];
1568 afs_dchashTbl[i] = index;
1570 MReleaseWriteLock(&afs_xdcache);
1571 break; /* leaving refCount high for caller */
1573 lockedPutDCache(tdc);
1576 index = afs_dcnextTbl[index];
1579 * If we didn't find the entry, we'll create one.
1581 if (index == NULLIDX) {
1582 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER, avc,
1583 ICL_TYPE_INT32, chunk);
1585 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1587 if (!setLocks) avc->states |= CDCLock;
1588 afs_GetDownD(5, (int*)0); /* just need slots */
1589 if (!setLocks) avc->states &= (~CDCLock);
1590 if (afs_discardDCList != NULLIDX || afs_freeDCList != NULLIDX)
1592 /* If we can't get space for 5 mins we give up and panic */
1593 if (++downDCount > 300)
1594 osi_Panic("getdcache");
1595 MReleaseWriteLock(&afs_xdcache);
1596 afs_osi_Wait(1000, 0, 0);
1600 if (afs_discardDCList == NULLIDX ||
1601 ((aflags & 2) && afs_freeDCList != NULLIDX)) {
1602 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1603 tdc = afs_GetDSlot(afs_freeDCList, 0);
1604 afs_freeDCList = afs_dvnextTbl[tdc->index];
1607 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1608 tdc = afs_GetDSlot(afs_discardDCList, 0);
1609 afs_discardDCList = afs_dvnextTbl[tdc->index];
1610 afs_discardDCCount--;
1611 size = ((tdc->f.chunkBytes + afs_fsfragsize)^afs_fsfragsize)>>10;
1612 afs_blocksDiscarded -= size;
1613 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1615 /* Truncate the chunk so zeroes get filled properly */
1616 file = afs_CFileOpen(tdc->f.inode);
1617 afs_CFileTruncate(file, 0);
1618 afs_CFileClose(file);
1619 afs_AdjustSize(tdc, 0);
1624 * Fill in the newly-allocated dcache record.
1626 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1627 tdc->f.fid = avc->fid;
1628 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1629 hones(tdc->f.versionNo); /* invalid value */
1630 tdc->f.chunk = chunk;
1632 if (tdc->lruq.prev == &tdc->lruq) osi_Panic("lruq 1");
1634 * Now add to the two hash chains - note that i is still set
1635 * from the above DCHash call.
1637 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1638 afs_dchashTbl[i] = tdc->index;
1639 i = DVHash(&avc->fid);
1640 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1641 afs_dvhashTbl[i] = tdc->index;
1642 tdc->flags = DFEntryMod;
1644 afs_MaybeWakeupTruncateDaemon();
1645 MReleaseWriteLock(&afs_xdcache);
1647 } /* else hint failed... */
1649 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1650 ICL_TYPE_POINTER, tdc,
1651 ICL_TYPE_INT32, hgetlo(tdc->f.versionNo),
1652 ICL_TYPE_INT32, hgetlo(avc->m.DataVersion));
1654 * Here we have the unlocked entry in tdc, with its refCount
1655 * incremented. Note: we don't use the S-lock; it costs concurrency
1656 * when storing a file back to the server.
1658 if (setLocks) ObtainReadLock(&avc->lock);
1661 * Not a newly created file so we need to check the file's length and
1662 * compare data versions since someone could have changed the data or we're
1663 * reading a file written elsewhere. We only want to bypass doing no-op
1664 * read rpcs on newly created files (dv of 0) since only then we guarantee
1665 * that this chunk's data hasn't been filled by another client.
1667 if (!hiszero(avc->m.DataVersion))
1669 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1671 #ifdef AFS_SGI64_ENV
1672 if (aflags & 4) adjustsize = NBPP;
1674 if (aflags & 4) adjustsize = 8192;
1677 if (aflags & 4) adjustsize = 4096;
1679 if (AFS_CHUNKTOBASE(chunk)+adjustsize >= avc->m.Length &&
1681 #if defined(AFS_SUN_ENV) || defined(AFS_OSF_ENV)
1682 if (((aflags & 4) || (AFS_CHUNKTOBASE(chunk) >= avc->m.Length)) &&
1684 if (AFS_CHUNKTOBASE(chunk) >= avc->m.Length &&
1687 !hsame(avc->m.DataVersion, tdc->f.versionNo)) {
1688 /* no data in file to read at this position */
1690 ReleaseReadLock(&avc->lock);
1691 ObtainWriteLock(&avc->lock,64);
1693 /* check again, now that we have a write lock */
1694 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1695 if (AFS_CHUNKTOBASE(chunk)+adjustsize >= avc->m.Length &&
1697 #if defined(AFS_SUN_ENV) || defined(AFS_OSF_ENV)
1698 if (((aflags & 4) || (AFS_CHUNKTOBASE(chunk) >= avc->m.Length)) &&
1700 if (AFS_CHUNKTOBASE(chunk) >= avc->m.Length &&
1703 !hsame(avc->m.DataVersion, tdc->f.versionNo)) {
1704 file = afs_CFileOpen(tdc->f.inode);
1705 afs_CFileTruncate(file, 0);
1706 afs_CFileClose(file);
1707 afs_AdjustSize(tdc, 0);
1708 hset(tdc->f.versionNo, avc->m.DataVersion);
1709 tdc->flags |= DFEntryMod;
1712 ReleaseWriteLock(&avc->lock);
1713 ObtainReadLock(&avc->lock);
1716 if (setLocks) ReleaseReadLock(&avc->lock);
1719 * We must read in the whole chunk iff the version number doesn't
1723 /* don't need data, just a unique dcache entry */
1724 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1725 hadd32(afs_indexCounter, 1);
1726 updateV2DC(setLocks,avc,tdc,567);
1727 return tdc; /* check if we're done */
1729 osi_Assert(setLocks || WriteLocked(&avc->lock));
1731 if (setLocks) ObtainReadLock(&avc->lock);
1732 if (!hsame(avc->m.DataVersion, tdc->f.versionNo)) {
1734 * Version number mismatch.
1737 ReleaseReadLock(&avc->lock);
1738 ObtainWriteLock(&avc->lock,65);
1742 * If data ever existed for this vnode, and this is a text object,
1743 * do some clearing. Now, you'd think you need only do the flush
1744 * when VTEXT is on, but VTEXT is turned off when the text object
1745 * is freed, while pages are left lying around in memory marked
1746 * with this vnode. If we would reactivate (create a new text
1747 * object from) this vnode, we could easily stumble upon some of
1748 * these old pages in pagein. So, we always flush these guys.
1749 * Sun has a wonderful lack of useful invariants in this system.
1751 * avc->flushDV is the data version # of the file at the last text
1752 * flush. Clearly, at least, we don't have to flush the file more
1753 * often than it changes
1755 if (hcmp(avc->flushDV, avc->m.DataVersion) < 0) {
1757 * By here, the cache entry is always write-locked. We can
1758 * deadlock if we call osi_Flush with the cache entry locked...
1760 ReleaseWriteLock(&avc->lock);
1763 * Call osi_FlushPages in open, read/write, and map, since it
1764 * is too hard here to figure out if we should lock the
1767 ObtainWriteLock(&avc->lock,66);
1770 /* Watch for standard race condition */
1771 if (hsame(avc->m.DataVersion, tdc->f.versionNo)) {
1772 updateV2DC(0,avc,tdc,569); /* set hint */
1773 if (setLocks) ReleaseWriteLock(&avc->lock);
1774 afs_stats_cmperf.dcacheHits++;
1778 /* Sleep here when cache needs to be drained. */
1780 (afs_blocksUsed > (CM_WAITFORDRAINPCT*afs_cacheBlocks)/100)) {
1781 /* Make sure truncate daemon is running */
1782 afs_MaybeWakeupTruncateDaemon();
1783 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
1784 ReleaseWriteLock(&avc->lock);
1785 while ((afs_blocksUsed-afs_blocksDiscarded) >
1786 (CM_WAITFORDRAINPCT*afs_cacheBlocks)/100) {
1787 afs_WaitForCacheDrain = 1;
1788 afs_osi_Sleep(&afs_WaitForCacheDrain);
1790 afs_MaybeFreeDiscardedDCache();
1791 /* need to check if someone else got the chunk first. */
1792 goto RetryGetDCache;
1795 /* Do not fetch data beyond truncPos. */
1796 maxGoodLength = avc->m.Length;
1797 if (avc->truncPos < maxGoodLength) maxGoodLength = avc->truncPos;
1798 Position = AFS_CHUNKBASE(abyte);
1799 if (vType(avc) == VDIR) {
1800 size = avc->m.Length;
1801 if (size > tdc->f.chunkBytes) {
1802 /* pre-reserve space for file */
1803 afs_AdjustSize(tdc, size);
1805 size = 999999999; /* max size for transfer */
1808 size = AFS_CHUNKSIZE(abyte); /* expected max size */
1809 /* don't read past end of good data on server */
1810 if (Position + size > maxGoodLength)
1811 size = maxGoodLength - Position;
1812 if (size < 0) size = 0; /* Handle random races */
1813 if (size > tdc->f.chunkBytes) {
1814 /* pre-reserve space for file */
1815 afs_AdjustSize(tdc, size); /* changes chunkBytes */
1816 /* max size for transfer still in size */
1819 if (afs_mariner && !tdc->f.chunk)
1820 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter );*/
1822 * Right now, we only have one tool, and it's a hammer. So, we
1823 * fetch the whole file.
1825 DZap(&tdc->f.inode); /* pages in cache may be old */
1827 if (file = tdc->ihint) {
1828 if (tdc->f.inode == file->inum )
1835 file = osi_UFSOpen(tdc->f.inode);
1840 file = afs_CFileOpen(tdc->f.inode);
1841 afs_RemoveVCB(&avc->fid);
1842 tdc->f.states |= DWriting;
1843 tdc->flags |= DFFetching;
1844 tdc->validPos = Position; /*Last valid position in this chunk*/
1845 if (tdc->flags & DFFetchReq) {
1846 tdc->flags &= ~DFFetchReq;
1847 afs_osi_Wakeup(&tdc->validPos);
1849 tsmall = (struct tlocal1 *) osi_AllocLargeSpace(sizeof(struct tlocal1));
1852 * Remember if we are doing the reading from a replicated volume,
1853 * and how many times we've zipped around the fetch/analyze loop.
1855 fromReplica = (avc->states & CRO) ? 1 : 0;
1857 accP = &(afs_stats_cmfullperf.accessinf);
1859 (accP->replicatedRefs)++;
1861 (accP->unreplicatedRefs)++;
1862 #endif /* AFS_NOSTATS */
1863 /* this is a cache miss */
1864 afs_stats_cmperf.dcacheMisses++;
1865 afs_Trace3(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
1866 ICL_TYPE_INT32, Position, ICL_TYPE_INT32, size);
1868 tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
1873 (accP->numReplicasAccessed)++;
1875 #endif /* AFS_NOSTATS */
1876 avc->callback = tc->srvr->server;
1877 ConvertWToSLock(&avc->lock);
1879 #ifdef RX_ENABLE_LOCKS
1881 #endif /* RX_ENABLE_LOCKS */
1882 tcall = rx_NewCall(tc->id);
1883 #ifdef RX_ENABLE_LOCKS
1885 #endif /* RX_ENABLE_LOCKS */
1888 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
1889 #ifdef RX_ENABLE_LOCKS
1891 #endif /* RX_ENABLE_LOCKS */
1892 code = StartRXAFS_FetchData(tcall,
1893 (struct AFSFid *) &avc->fid.Fid,
1895 #ifdef RX_ENABLE_LOCKS
1897 #endif /* RX_ENABLE_LOCKS */
1901 xferP = &(afs_stats_cmfullperf.rpc.fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
1902 osi_GetuTime(&xferStartTime);
1904 code = afs_CacheFetchProc(tcall, file, Position, tdc, avc,
1905 &bytesToXfer, &bytesXferred);
1907 osi_GetuTime(&xferStopTime);
1908 (xferP->numXfers)++;
1910 (xferP->numSuccesses)++;
1911 afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_FETCHDATA] += bytesXferred;
1912 (xferP->sumBytes) += (afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
1913 afs_stats_XferSumBytes[AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
1914 if (bytesXferred < xferP->minBytes)
1915 xferP->minBytes = bytesXferred;
1916 if (bytesXferred > xferP->maxBytes)
1917 xferP->maxBytes = bytesXferred;
1920 * Tally the size of the object. Note: we tally the actual size,
1921 * NOT the number of bytes that made it out over the wire.
1923 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
1924 (xferP->count[0])++;
1926 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET1)
1927 (xferP->count[1])++;
1929 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET2)
1930 (xferP->count[2])++;
1932 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET3)
1933 (xferP->count[3])++;
1935 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET4)
1936 (xferP->count[4])++;
1938 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET5)
1939 (xferP->count[5])++;
1941 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET6)
1942 (xferP->count[6])++;
1944 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET7)
1945 (xferP->count[7])++;
1947 (xferP->count[8])++;
1949 afs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
1950 afs_stats_AddTo((xferP->sumTime), elapsedTime);
1951 afs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
1952 if (afs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
1953 afs_stats_TimeAssign((xferP->minTime), elapsedTime);
1955 if (afs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
1956 afs_stats_TimeAssign((xferP->maxTime), elapsedTime);
1960 code = afs_CacheFetchProc(tcall, file, Position, tdc, avc, 0, 0);
1961 #endif /* AFS_NOSTATS */
1964 #ifdef RX_ENABLE_LOCKS
1966 #endif /* RX_ENABLE_LOCKS */
1967 code = EndRXAFS_FetchData(tcall,
1971 #ifdef RX_ENABLE_LOCKS
1973 #endif /* RX_ENABLE_LOCKS */
1976 code1 = rx_EndCall(tcall, code);
1977 UpgradeSToWLock(&avc->lock,27);
1982 if ( !code && code1 )
1986 /* callback could have been broken (or expired) in a race here,
1987 * but we return the data anyway. It's as good as we knew about
1988 * when we started. */
1990 * validPos is updated by CacheFetchProc, and can only be
1991 * modifed under an S or W lock, which we've blocked out
1993 size = tdc->validPos - Position; /* actual segment size */
1994 if (size < 0) size = 0;
1995 afs_CFileTruncate(file, size); /* prune it */
1998 ObtainWriteLock(&afs_xcbhash, 453);
1999 afs_DequeueCallback(avc);
2000 avc->states &= ~(CStatd | CUnique);
2001 avc->callback = (struct server *)0;
2002 ReleaseWriteLock(&afs_xcbhash);
2003 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2004 osi_dnlc_purgedp(avc);
2008 (afs_Analyze(tc, code, &avc->fid, areq,
2009 AFS_STATS_FS_RPCIDX_FETCHDATA,
2010 SHARED_LOCK, (struct cell *)0));
2014 * In the case of replicated access, jot down info on the number of
2015 * attempts it took before we got through or gave up.
2018 if (numFetchLoops <= 1)
2019 (accP->refFirstReplicaOK)++;
2020 if (numFetchLoops > accP->maxReplicasPerRef)
2021 accP->maxReplicasPerRef = numFetchLoops;
2023 #endif /* AFS_NOSTATS */
2025 tdc->flags &= ~DFFetching;
2026 if (tdc->flags & DFWaiting) {
2027 tdc->flags &= ~DFWaiting;
2028 afs_osi_Wakeup(&tdc->validPos);
2030 if (avc->execsOrWriters == 0) tdc->f.states &= ~DWriting;
2032 /* now, if code != 0, we have an error and should punt */
2034 afs_CFileTruncate(file, 0);
2035 afs_AdjustSize(tdc, 0);
2036 afs_CFileClose(file);
2037 ZapDCE(tdc); /* sets DFEntryMod */
2038 if (vType(avc) == VDIR) {
2039 DZap(&tdc->f.inode);
2041 #ifdef AFS_SUN5_ENVX
2046 ObtainWriteLock(&afs_xcbhash, 454);
2047 afs_DequeueCallback(avc);
2048 avc->states &= ~( CStatd | CUnique );
2049 ReleaseWriteLock(&afs_xcbhash);
2050 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2051 osi_dnlc_purgedp(avc);
2052 if (setLocks) ReleaseWriteLock(&avc->lock);
2053 osi_FreeLargeSpace(tsmall);
2054 tdc = (struct dcache *) 0;
2058 /* otherwise we copy in the just-fetched info */
2059 afs_CFileClose(file);
2060 afs_AdjustSize(tdc, size); /* new size */
2062 * Copy appropriate fields into vcache
2064 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2065 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh, tsmall->OutStatus.DataVersion);
2066 tdc->flags |= DFEntryMod;
2067 afs_indexFlags[tdc->index] |= IFEverUsed;
2068 if (setLocks) ReleaseWriteLock(&avc->lock);
2069 osi_FreeLargeSpace(tsmall);
2070 } /*Data version numbers don't match*/
2073 * Data version numbers match. Release locks if we locked
2074 * them, and remember we've had a cache hit.
2077 ReleaseReadLock(&avc->lock);
2078 afs_stats_cmperf.dcacheHits++;
2079 } /*Data version numbers match*/
2081 updateV2DC(setLocks,avc,tdc,332); /* set hint */
2084 * See if this was a reference to a file in the local cell.
2086 if (avc->fid.Cell == LOCALCELL)
2087 afs_stats_cmperf.dlocalAccesses++;
2089 afs_stats_cmperf.dremoteAccesses++;
2091 /* Fix up LRU info */
2094 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2095 hadd32(afs_indexCounter, 1);
2097 /* return the data */
2098 if (vType(avc) == VDIR)
2101 *aoffset = AFS_CHUNKOFFSET(abyte);
2102 *alen = (tdc->f.chunkBytes - *aoffset);
2111 * afs_WriteThroughDSlots
2114 * Sweep through the dcache slots and write out any modified
2115 * in-memory data back on to our caching store.
2121 * The afs_xdcache is write-locked through this whole affair.
2124 afs_WriteThroughDSlots()
2126 { /*afs_WriteThroughDSlots*/
2128 register struct dcache *tdc;
2129 register afs_int32 i, touchedit=0;
2131 AFS_STATCNT(afs_WriteThroughDSlots);
2132 MObtainWriteLock(&afs_xdcache,283);
2133 for(i = 0; i < afs_cacheFiles; i++) {
2134 tdc = afs_indexTable[i];
2135 if (tdc && (tdc->flags & DFEntryMod)) {
2136 tdc->flags &= ~DFEntryMod;
2137 afs_WriteDCache(tdc, 1);
2141 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2142 /* Touch the file to make sure that the mtime on the file is kept up-to-date
2143 * to avoid losing cached files on cold starts because their mtime seems old...
2145 struct afs_fheader theader;
2147 theader.magic = AFS_FHMAGIC;
2148 theader.firstCSize = AFS_FIRSTCSIZE;
2149 theader.otherCSize = AFS_OTHERCSIZE;
2150 theader.version = AFS_CI_VERSION;
2151 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2153 MReleaseWriteLock(&afs_xdcache);
2155 } /*afs_WriteThroughDSlots*/
2161 * Return a pointer to an freshly initialized dcache entry using
2162 * a memory-based cache.
2165 * aslot : Dcache slot to look at.
2166 * tmpdc : Ptr to dcache entry.
2169 * Nothing interesting.
2172 struct dcache *afs_MemGetDSlot(aslot, tmpdc)
2173 register afs_int32 aslot;
2174 register struct dcache *tmpdc;
2176 { /*afs_MemGetDSlot*/
2178 register afs_int32 code;
2179 register struct dcache *tdc;
2180 register char *tfile;
2182 AFS_STATCNT(afs_MemGetDSlot);
2183 if (CheckLock(&afs_xdcache) != -1) osi_Panic("getdslot nolock");
2184 if (aslot < 0 || aslot >= afs_cacheFiles) osi_Panic("getdslot slot");
2185 tdc = afs_indexTable[aslot];
2187 QRemove(&tdc->lruq); /* move to queue head */
2188 QAdd(&afs_DLRU, &tdc->lruq);
2192 if (tmpdc == (struct dcache *)0) {
2193 if (!afs_freeDSList) afs_GetDownDSlot(4);
2194 if (!afs_freeDSList) {
2195 /* none free, making one is better than a panic */
2196 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2197 tdc = (struct dcache *) afs_osi_Alloc(sizeof (struct dcache));
2198 #ifdef AFS_AIX32_ENV
2199 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2202 tdc = afs_freeDSList;
2203 afs_freeDSList = (struct dcache *) tdc->lruq.next;
2205 tdc->flags = 0; /* up-to-date, not in free q */
2206 QAdd(&afs_DLRU, &tdc->lruq);
2207 if (tdc->lruq.prev == &tdc->lruq) osi_Panic("lruq 3");
2214 /* initialize entry */
2215 tdc->f.fid.Cell = 0;
2216 tdc->f.fid.Fid.Volume = 0;
2218 hones(tdc->f.versionNo);
2219 tdc->f.inode = aslot;
2220 tdc->flags |= DFEntryMod;
2223 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2225 if (tmpdc == (struct dcache *)0)
2226 afs_indexTable[aslot] = tdc;
2229 } /*afs_MemGetDSlot*/
2231 unsigned int last_error = 0, lasterrtime = 0;
2237 * Return a pointer to an freshly initialized dcache entry using
2238 * a UFS-based disk cache.
2241 * aslot : Dcache slot to look at.
2242 * tmpdc : Ptr to dcache entry.
2245 * afs_xdcache lock write-locked.
2247 struct dcache *afs_UFSGetDSlot(aslot, tmpdc)
2248 register afs_int32 aslot;
2249 register struct dcache *tmpdc;
2251 { /*afs_UFSGetDSlot*/
2253 register afs_int32 code;
2254 register struct dcache *tdc;
2256 AFS_STATCNT(afs_UFSGetDSlot);
2257 if (CheckLock(&afs_xdcache) != -1) osi_Panic("getdslot nolock");
2258 if (aslot < 0 || aslot >= afs_cacheFiles) osi_Panic("getdslot slot");
2259 tdc = afs_indexTable[aslot];
2261 #ifdef AFS_SUN5_ENVX
2262 mutex_enter(&tdc->lock);
2264 QRemove(&tdc->lruq); /* move to queue head */
2265 QAdd(&afs_DLRU, &tdc->lruq);
2269 /* otherwise we should read it in from the cache file */
2271 * If we weren't passed an in-memory region to place the file info,
2272 * we have to allocate one.
2274 if (tmpdc == (struct dcache *)0) {
2275 if (!afs_freeDSList) afs_GetDownDSlot(4);
2276 if (!afs_freeDSList) {
2277 /* none free, making one is better than a panic */
2278 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2279 tdc = (struct dcache *) afs_osi_Alloc(sizeof (struct dcache));
2280 #ifdef AFS_AIX32_ENV
2281 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2284 tdc = afs_freeDSList;
2285 afs_freeDSList = (struct dcache *) tdc->lruq.next;
2287 tdc->flags = 0; /* up-to-date, not in free q */
2288 QAdd(&afs_DLRU, &tdc->lruq);
2289 if (tdc->lruq.prev == &tdc->lruq) osi_Panic("lruq 3");
2297 #ifdef AFS_SUN5_ENVX
2298 mutex_enter(&tdc->lock);
2301 * Seek to the aslot'th entry and read it in.
2303 code = afs_osi_Read(afs_cacheInodep, sizeof(struct fcache) * aslot + sizeof(struct afs_fheader),
2304 (char *)(&tdc->f), sizeof(struct fcache));
2305 if (code != sizeof(struct fcache)) {
2306 tdc->f.fid.Cell = 0;
2307 tdc->f.fid.Fid.Volume = 0;
2309 hones(tdc->f.versionNo);
2310 tdc->flags |= DFEntryMod;
2311 #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)
2312 last_error = getuerror();
2314 lasterrtime = osi_Time();
2315 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2321 * If we didn't read into a temporary dcache region, update the
2322 * slot pointer table.
2324 if (tmpdc == (struct dcache *)0)
2325 afs_indexTable[aslot] = tdc;
2328 } /*afs_UFSGetDSlot*/
2336 * write a particular dcache entry back to its home in the
2340 * adc : Pointer to the dcache entry to write.
2341 * atime : If true, set the modtime on the file to the current time.
2344 * Must be called with the afs_xdcache lock at least read-locked.
2345 * The reference count is not changed.
2348 afs_WriteDCache(adc, atime)
2350 register struct dcache *adc;
2352 { /*afs_WriteDCache*/
2354 register struct osi_file *tfile;
2355 register afs_int32 code;
2357 if (cacheDiskType == AFS_FCACHE_TYPE_MEM) return 0;
2358 AFS_STATCNT(afs_WriteDCache);
2360 adc->f.modTime = osi_Time();
2362 * Seek to the right dcache slot and write the in-memory image out to disk.
2364 code = afs_osi_Write(afs_cacheInodep, sizeof(struct fcache) * adc->index + sizeof(struct afs_fheader),
2365 (char *)(&adc->f), sizeof(struct fcache));
2366 if (code != sizeof(struct fcache)) return EIO;
2369 } /*afs_WriteDCache*/
2377 * Wake up users of a particular file waiting for stores to take
2381 * avc : Ptr to related vcache entry.
2384 * Nothing interesting.
2388 register struct vcache *avc;
2393 register struct brequest *tb;
2395 AFS_STATCNT(afs_wakeup);
2396 for (i = 0; i < NBRS; i++, tb++) {
2397 /* if request is valid and for this file, we've found it */
2398 if (tb->refCount > 0 && avc == tb->vnode) {
2401 * If CSafeStore is on, then we don't awaken the guy
2402 * waiting for the store until the whole store has finished.
2403 * Otherwise, we do it now. Note that if CSafeStore is on,
2404 * the BStore routine actually wakes up the user, instead
2406 * I think this is redundant now because this sort of thing
2407 * is already being handled by the higher-level code.
2409 if ((avc->states & CSafeStore) == 0) {
2411 tb->flags |= BUVALID;
2412 if (tb->flags & BUWAIT) {
2413 tb->flags &= ~BUWAIT;
2429 * Given a file name and inode, set up that file to be an
2430 * active member in the AFS cache. This also involves checking
2431 * the usability of its data.
2434 * afile : Name of the cache file to initialize.
2435 * ainode : Inode of the file.
2438 * This function is called only during initialization.
2441 int afs_InitCacheFile(afile, ainode)
2445 { /*afs_InitCacheFile*/
2447 register afs_int32 code;
2448 #ifdef AFS_LINUX22_ENV
2449 struct dentry *filevp;
2451 struct vnode *filevp;
2455 struct osi_file *tfile;
2456 struct osi_stat tstat;
2457 register struct dcache *tdc;
2459 AFS_STATCNT(afs_InitCacheFile);
2460 index = afs_stats_cmperf.cacheNumEntries;
2461 if (index >= afs_cacheFiles) return EINVAL;
2463 MObtainWriteLock(&afs_xdcache,282);
2464 tdc = afs_GetDSlot(index, (struct dcache *)0);
2465 MReleaseWriteLock(&afs_xdcache);
2467 code = gop_lookupname(afile,
2470 (struct vnode **) 0,
2477 * We have a VN_HOLD on filevp. Get the useful info out and
2478 * return. We make use of the fact that the cache is in the
2479 * UFS file system, and just record the inode number.
2481 #ifdef AFS_LINUX22_ENV
2482 tdc->f.inode = VTOI(filevp->d_inode)->i_number;
2485 tdc->f.inode = afs_vnodeToInumber(filevp);
2489 AFS_RELE((struct vnode *)filevp);
2491 #endif /* AFS_LINUX22_ENV */
2494 tdc->f.inode = ainode;
2497 if ((tdc->f.states & DWriting) ||
2498 tdc->f.fid.Fid.Volume == 0) fileIsBad = 1;
2499 tfile = osi_UFSOpen(tdc->f.inode);
2500 code = afs_osi_Stat(tfile, &tstat);
2501 if (code) osi_Panic("initcachefile stat");
2504 * If file size doesn't match the cache info file, it's probably bad.
2506 if (tdc->f.chunkBytes != tstat.size) fileIsBad = 1;
2507 tdc->f.chunkBytes = 0;
2510 * If file changed within T (120?) seconds of cache info file, it's
2511 * probably bad. In addition, if slot changed within last T seconds,
2512 * the cache info file may be incorrectly identified, and so slot
2515 if (cacheInfoModTime < tstat.mtime + 120) fileIsBad = 1;
2516 if (cacheInfoModTime < tdc->f.modTime + 120) fileIsBad = 1;
2517 /* In case write through is behind, make sure cache items entry is
2518 * at least as new as the chunk.
2520 if (tdc->f.modTime < tstat.mtime) fileIsBad = 1;
2522 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
2523 if (tstat.size != 0)
2524 osi_UFSTruncate(tfile, 0);
2525 /* put entry in free cache slot list */
2526 afs_dvnextTbl[tdc->index] = afs_freeDCList;
2527 afs_freeDCList = index;
2529 afs_indexFlags[index] |= IFFree;
2530 afs_indexUnique[index] = 0;
2534 * We must put this entry in the appropriate hash tables.
2535 * Note that i is still set from the above DCHash call
2537 code = DCHash(&tdc->f.fid, tdc->f.chunk);
2538 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
2539 afs_dchashTbl[code] = tdc->index;
2540 code = DVHash(&tdc->f.fid);
2541 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
2542 afs_dvhashTbl[code] = tdc->index;
2543 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
2545 /* has nontrivial amt of data */
2546 afs_indexFlags[index] |= IFEverUsed;
2547 afs_stats_cmperf.cacheFilesReused++;
2549 * Initialize index times to file's mod times; init indexCounter
2552 hset32(afs_indexTimes[index], tstat.atime);
2553 if (hgetlo(afs_indexCounter) < tstat.atime) {
2554 hset32(afs_indexCounter, tstat.atime);
2556 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
2557 } /*File is not bad*/
2559 osi_UFSClose(tfile);
2560 tdc->f.states &= ~DWriting;
2561 tdc->flags &= ~DFEntryMod;
2562 /* don't set f.modTime; we're just cleaning up */
2563 afs_WriteDCache(tdc, 0);
2565 afs_stats_cmperf.cacheNumEntries++;
2568 } /*afs_InitCacheFile*/
2571 /*Max # of struct dcache's resident at any time*/
2573 * If 'dchint' is enabled then in-memory dcache min is increased because of
2582 * Initialize dcache related variables.
2584 void afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk,
2587 register struct dcache *tdp;
2591 afs_freeDCList = NULLIDX;
2592 afs_discardDCList = NULLIDX;
2593 afs_freeDCCount = 0;
2594 afs_freeDSList = (struct dcache *)0;
2595 hzero(afs_indexCounter);
2597 LOCK_INIT(&afs_xdcache, "afs_xdcache");
2603 if (achunk < 0 || achunk > 30)
2604 achunk = 13; /* Use default */
2605 AFS_SETCHUNKSIZE(achunk);
2611 if(aflags & AFSCALL_INIT_MEMCACHE) {
2613 * Use a memory cache instead of a disk cache
2615 cacheDiskType = AFS_FCACHE_TYPE_MEM;
2616 afs_cacheType = &afs_MemCacheOps;
2617 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
2618 ablocks = afiles * (AFS_FIRSTCSIZE/1024);
2619 /* ablocks is reported in 1K blocks */
2620 code = afs_InitMemCache(afiles * AFS_FIRSTCSIZE, AFS_FIRSTCSIZE, aflags);
2622 printf("afsd: memory cache too large for available memory.\n");
2623 printf("afsd: AFS files cannot be accessed.\n\n");
2625 afiles = ablocks = 0;
2628 printf("Memory cache: Allocating %d dcache entries...", aDentries);
2630 cacheDiskType = AFS_FCACHE_TYPE_UFS;
2631 afs_cacheType = &afs_UfsCacheOps;
2634 if (aDentries > 512)
2635 afs_dhashsize = 2048;
2636 /* initialize hash tables */
2637 afs_dvhashTbl = (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
2638 afs_dchashTbl = (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
2639 for(i=0;i< afs_dhashsize;i++) {
2640 afs_dvhashTbl[i] = NULLIDX;
2641 afs_dchashTbl[i] = NULLIDX;
2643 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
2644 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
2645 for(i=0;i< afiles;i++) {
2646 afs_dvnextTbl[i] = NULLIDX;
2647 afs_dcnextTbl[i] = NULLIDX;
2650 /* Allocate and zero the pointer array to the dcache entries */
2651 afs_indexTable = (struct dcache **)
2652 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
2653 memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
2654 afs_indexTimes = (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
2655 memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
2656 afs_indexUnique = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
2657 memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
2658 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
2659 memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
2661 /* Allocate and thread the struct dcache entries themselves */
2662 tdp = afs_Initial_freeDSList =
2663 (struct dcache *) afs_osi_Alloc(aDentries * sizeof(struct dcache));
2664 memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
2665 #ifdef AFS_AIX32_ENV
2666 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles);/* XXX */
2667 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
2668 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
2669 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
2670 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
2671 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
2672 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
2673 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
2674 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
2677 afs_freeDSList = &tdp[0];
2678 for(i=0; i < aDentries-1; i++) {
2679 tdp[i].lruq.next = (struct afs_q *) (&tdp[i+1]);
2681 tdp[aDentries-1].lruq.next = (struct afs_q *) 0;
2683 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal = afs_cacheBlocks = ablocks;
2684 afs_ComputeCacheParms(); /* compute parms based on cache size */
2686 afs_dcentries = aDentries;
2697 void shutdown_dcache(void)
2701 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
2702 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
2703 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
2704 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
2705 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
2706 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
2707 afs_osi_Free(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
2708 #ifdef AFS_AIX32_ENV
2709 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
2710 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
2711 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
2712 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
2713 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
2714 unpin((u_char *)afs_indexFlags, afs_cacheFiles * sizeof(u_char));
2715 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
2719 for(i=0;i< afs_dhashsize;i++) {
2720 afs_dvhashTbl[i] = NULLIDX;
2721 afs_dchashTbl[i] = NULLIDX;
2725 afs_blocksUsed = afs_dcentries = 0;
2726 hzero(afs_indexCounter);
2728 afs_freeDCCount = 0;
2729 afs_freeDCList = NULLIDX;
2730 afs_discardDCList = NULLIDX;
2731 afs_freeDSList = afs_Initial_freeDSList = 0;
2733 LOCK_INIT(&afs_xdcache, "afs_xdcache");