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"
19 #include "afs/sysincludes.h" /*Standard vendor system headers */
20 #include "afsincludes.h" /*AFS-based standard headers */
21 #include "afs/afs_stats.h" /* statistics */
22 #include "afs/afs_cbqueue.h"
23 #include "afs/afs_osidnlc.h"
25 /* Forward declarations. */
26 static void afs_GetDownD(afs_int32 anumber, afs_size_t *aneedSpace, afs_int32 buckethint);
27 static void afs_FreeDiscardedDCache(void);
28 static void afs_DiscardDCache(struct dcache *);
29 static void afs_FreeDCache(struct dcache *);
31 static afs_int32 afs_DCGetBucket(struct vcache *);
32 static void afs_DCAdjustSize(struct dcache *, afs_int32, afs_int32);
33 static void afs_DCMoveBucket(struct dcache *, afs_int32, afs_int32);
34 static void afs_DCSizeInit(void);
35 static afs_int32 afs_DCWhichBucket(afs_int32, afs_int32);
39 * --------------------- Exported definitions ---------------------
42 afs_int32 afs_blocksUsed_0; /*1K blocks in cache - in theory is zero */
43 afs_int32 afs_blocksUsed_1; /*1K blocks in cache */
44 afs_int32 afs_blocksUsed_2; /*1K blocks in cache */
45 afs_int32 afs_pct1 = -1;
46 afs_int32 afs_pct2 = -1;
47 afs_uint32 afs_tpct1 = 0;
48 afs_uint32 afs_tpct2 = 0;
49 afs_uint32 splitdcache = 0;
51 afs_lock_t afs_xdcache; /*Lock: alloc new disk cache entries */
52 afs_int32 afs_freeDCList; /*Free list for disk cache entries */
53 afs_int32 afs_freeDCCount; /*Count of elts in freeDCList */
54 afs_int32 afs_discardDCList; /*Discarded disk cache entries */
55 afs_int32 afs_discardDCCount; /*Count of elts in discardDCList */
56 struct dcache *afs_freeDSList; /*Free list for disk slots */
57 struct dcache *afs_Initial_freeDSList; /*Initial list for above */
58 ino_t cacheInode; /*Inode for CacheItems file */
59 struct osi_file *afs_cacheInodep = 0; /* file for CacheItems inode */
60 struct afs_q afs_DLRU; /*dcache LRU */
61 afs_int32 afs_dhashsize = 1024;
62 afs_int32 *afs_dvhashTbl; /*Data cache hash table */
63 afs_int32 *afs_dchashTbl; /*Data cache hash table */
64 afs_int32 *afs_dvnextTbl; /*Dcache hash table links */
65 afs_int32 *afs_dcnextTbl; /*Dcache hash table links */
66 struct dcache **afs_indexTable; /*Pointers to dcache entries */
67 afs_hyper_t *afs_indexTimes; /*Dcache entry Access times */
68 afs_int32 *afs_indexUnique; /*dcache entry Fid.Unique */
69 unsigned char *afs_indexFlags; /*(only one) Is there data there? */
70 afs_hyper_t afs_indexCounter; /*Fake time for marking index
72 afs_int32 afs_cacheFiles = 0; /*Size of afs_indexTable */
73 afs_size_t afs_cacheBlocks; /*1K blocks in cache */
74 afs_int32 afs_cacheStats; /*Stat entries in cache */
75 afs_size_t afs_blocksUsed; /*Number of blocks in use */
76 afs_size_t afs_blocksDiscarded; /*Blocks freed but not truncated */
77 afs_int32 afs_fsfragsize = 1023; /*Underlying Filesystem minimum unit
78 *of disk allocation usually 1K
79 *this value is (truefrag -1 ) to
80 *save a bunch of subtracts... */
81 #ifdef AFS_64BIT_CLIENT
82 #ifdef AFS_VM_RDWR_ENV
83 afs_size_t afs_vmMappingEnd; /* for large files (>= 2GB) the VM
84 * mapping an 32bit addressing machines
85 * can only be used below the 2 GB
86 * line. From this point upwards we
87 * must do direct I/O into the cache
88 * files. The value should be on a
90 #endif /* AFS_VM_RDWR_ENV */
91 #endif /* AFS_64BIT_CLIENT */
93 /* The following is used to ensure that new dcache's aren't obtained when
94 * the cache is nearly full.
96 int afs_WaitForCacheDrain = 0;
97 int afs_TruncateDaemonRunning = 0;
98 int afs_CacheTooFull = 0;
100 afs_int32 afs_dcentries; /* In-memory dcache entries */
103 int dcacheDisabled = 0;
105 static int afs_UFSCacheFetchProc(), afs_UFSCacheStoreProc();
106 struct afs_cacheOps afs_UfsCacheOps = {
114 afs_UFSCacheFetchProc,
115 afs_UFSCacheStoreProc,
121 struct afs_cacheOps afs_MemCacheOps = {
123 afs_MemCacheTruncate,
129 afs_MemCacheFetchProc,
130 afs_MemCacheStoreProc,
136 int cacheDiskType; /*Type of backing disk for cache */
137 struct afs_cacheOps *afs_cacheType;
140 afs_DCGetBucket(struct vcache *avc)
142 /* This should be replaced with some sort of user configurable function */
143 if (avc->states & CRO) {
145 } else if (avc->states & CBackup) {
155 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
157 afs_int32 adjustSize = newSize - oldSize;
165 afs_blocksUsed_0 += adjustSize;
166 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
169 afs_blocksUsed_1 += adjustSize;
170 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
173 afs_blocksUsed_2 += adjustSize;
174 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
182 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
190 afs_blocksUsed_0 -= size;
193 afs_blocksUsed_1 -= size;
196 afs_blocksUsed_2 -= size;
200 adc->bucket = newBucket;
205 afs_blocksUsed_0 += size;
208 afs_blocksUsed_1 += size;
211 afs_blocksUsed_2 += size;
221 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
225 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
230 afs_pct1 = afs_blocksUsed_1*100/afs_cacheBlocks;
231 afs_pct2 = afs_blocksUsed_2*100/afs_cacheBlocks;
233 /* Short cut: if we don't know about it, try to kill it */
234 if (phase < 2 && afs_blocksUsed_0)
237 if (afs_pct1 > afs_tpct1)
239 if (afs_pct2 > afs_tpct2)
241 return 0; /* unlikely */
249 * Warn about failing to store a file.
252 * acode : Associated error code.
253 * avolume : Volume involved.
254 * aflags : How to handle the output:
255 * aflags & 1: Print out on console
256 * aflags & 2: Print out on controlling tty
259 * Call this from close call when vnodeops is RCS unlocked.
263 afs_StoreWarn(register afs_int32 acode, afs_int32 avolume,
264 register afs_int32 aflags)
266 static char problem_fmt[] =
267 "afs: failed to store file in volume %d (%s)\n";
268 static char problem_fmt_w_error[] =
269 "afs: failed to store file in volume %d (error %d)\n";
270 static char netproblems[] = "network problems";
271 static char partfull[] = "partition full";
272 static char overquota[] = "over quota";
274 AFS_STATCNT(afs_StoreWarn);
280 afs_warn(problem_fmt, avolume, netproblems);
282 afs_warnuser(problem_fmt, avolume, netproblems);
283 } else if (acode == ENOSPC) {
288 afs_warn(problem_fmt, avolume, partfull);
290 afs_warnuser(problem_fmt, avolume, partfull);
293 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
294 * Instead ENOSPC will be sent...
296 if (acode == EDQUOT) {
301 afs_warn(problem_fmt, avolume, overquota);
303 afs_warnuser(problem_fmt, avolume, overquota);
311 afs_warn(problem_fmt_w_error, avolume, acode);
313 afs_warnuser(problem_fmt_w_error, avolume, acode);
318 afs_MaybeWakeupTruncateDaemon(void)
320 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
321 afs_CacheTooFull = 1;
322 if (!afs_TruncateDaemonRunning)
323 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
324 } else if (!afs_TruncateDaemonRunning
325 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
326 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
330 /* Keep statistics on run time for afs_CacheTruncateDaemon. This is a
331 * struct so we need only export one symbol for AIX.
333 static struct CTD_stats {
334 osi_timeval_t CTD_beforeSleep;
335 osi_timeval_t CTD_afterSleep;
336 osi_timeval_t CTD_sleepTime;
337 osi_timeval_t CTD_runTime;
341 u_int afs_min_cache = 0;
343 afs_CacheTruncateDaemon(void)
345 osi_timeval_t CTD_tmpTime;
349 (100 - CM_DCACHECOUNTFREEPCT +
350 CM_DCACHEEXTRAPCT) * afs_cacheFiles / 100;
352 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
354 osi_GetuTime(&CTD_stats.CTD_afterSleep);
355 afs_TruncateDaemonRunning = 1;
357 cb_lowat = PERCENT(CM_DCACHESPACEFREEPCT-CM_DCACHEEXTRAPCT, afs_cacheBlocks);
358 MObtainWriteLock(&afs_xdcache, 266);
359 if (afs_CacheTooFull) {
360 afs_size_t space_needed;
361 afs_int32 slots_needed;
362 /* if we get woken up, we should try to clean something out */
363 for (counter = 0; counter < 10; counter++) {
365 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
367 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
368 afs_GetDownD(slots_needed, &space_needed, 0);
369 if ((space_needed <= 0) && (slots_needed <= 0)) {
372 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
375 if (!afs_CacheIsTooFull())
376 afs_CacheTooFull = 0;
378 MReleaseWriteLock(&afs_xdcache);
381 * This is a defensive check to try to avoid starving threads
382 * that may need the global lock so thay can help free some
383 * cache space. If this thread won't be sleeping or truncating
384 * any cache files then give up the global lock so other
385 * threads get a chance to run.
387 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
388 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
389 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
393 * This is where we free the discarded cache elements.
395 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
396 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
397 afs_FreeDiscardedDCache();
400 /* See if we need to continue to run. Someone may have
401 * signalled us while we were executing.
403 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
404 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
405 /* Collect statistics on truncate daemon. */
406 CTD_stats.CTD_nSleeps++;
407 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
408 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
409 CTD_stats.CTD_beforeSleep);
410 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
412 afs_TruncateDaemonRunning = 0;
413 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
414 afs_TruncateDaemonRunning = 1;
416 osi_GetuTime(&CTD_stats.CTD_afterSleep);
417 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
418 CTD_stats.CTD_afterSleep);
419 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
421 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
423 afs_termState = AFSOP_STOP_AFSDB;
425 afs_termState = AFSOP_STOP_RXEVENT;
427 afs_osi_Wakeup(&afs_termState);
438 * Make adjustment for the new size in the disk cache entry
440 * Major Assumptions Here:
441 * Assumes that frag size is an integral power of two, less one,
442 * and that this is a two's complement machine. I don't
443 * know of any filesystems which violate this assumption...
446 * adc : Ptr to dcache entry.
447 * anewsize : New size desired.
451 afs_AdjustSize(register struct dcache *adc, register afs_int32 newSize)
453 register afs_int32 oldSize;
455 AFS_STATCNT(afs_AdjustSize);
457 adc->dflags |= DFEntryMod;
458 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
459 adc->f.chunkBytes = newSize;
462 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
463 afs_DCAdjustSize(adc, oldSize, newSize);
464 if (newSize > oldSize) {
465 /* We're growing the file, wakeup the daemon */
466 afs_MaybeWakeupTruncateDaemon();
468 afs_blocksUsed += (newSize - oldSize);
469 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
477 * This routine is responsible for moving at least one entry (but up
478 * to some number of them) from the LRU queue to the free queue.
481 * anumber : Number of entries that should ideally be moved.
482 * aneedSpace : How much space we need (1K blocks);
485 * The anumber parameter is just a hint; at least one entry MUST be
486 * moved, or we'll panic. We must be called with afs_xdcache
487 * write-locked. We should try to satisfy both anumber and aneedspace,
488 * whichever is more demanding - need to do several things:
489 * 1. only grab up to anumber victims if aneedSpace <= 0, not
490 * the whole set of MAXATONCE.
491 * 2. dynamically choose MAXATONCE to reflect severity of
492 * demand: something like (*aneedSpace >> (logChunk - 9))
493 * N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
494 * indicates that the cache is not properly configured/tuned or
495 * something. We should be able to automatically correct that problem.
498 #define MAXATONCE 16 /* max we can obtain at once */
500 afs_GetDownD(afs_int32 anumber, afs_size_t *aneedSpace, afs_int32 buckethint)
504 struct VenusFid *afid;
508 register struct vcache *tvc;
509 afs_uint32 victims[MAXATONCE];
510 struct dcache *victimDCs[MAXATONCE];
511 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
512 afs_uint32 victimPtr; /* next free item in victim arrays */
513 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
514 afs_uint32 maxVictimPtr; /* where it is */
518 AFS_STATCNT(afs_GetDownD);
519 if (CheckLock(&afs_xdcache) != -1)
520 osi_Panic("getdownd nolock");
521 /* decrement anumber first for all dudes in free list */
522 /* SHOULD always decrement anumber first, even if aneedSpace >0,
523 * because we should try to free space even if anumber <=0 */
524 if (!aneedSpace || *aneedSpace <= 0) {
525 anumber -= afs_freeDCCount;
527 return; /* enough already free */
529 /* bounds check parameter */
530 if (anumber > MAXATONCE)
531 anumber = MAXATONCE; /* all we can do */
533 /* rewrite so phases include a better eligiblity for gc test*/
535 * The phase variable manages reclaims. Set to 0, the first pass,
536 * we don't reclaim active entries, or other than target bucket.
537 * Set to 1, we reclaim even active ones in target bucket.
538 * Set to 2, we reclaim any inactive one.
539 * Set to 3, we reclaim even active ones.
547 for (i = 0; i < afs_cacheFiles; i++)
548 /* turn off all flags */
549 afs_indexFlags[i] &= ~IFFlag;
551 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
552 /* find oldest entries for reclamation */
553 maxVictimPtr = victimPtr = 0;
554 hzero(maxVictimTime);
555 curbucket = afs_DCWhichBucket(phase, buckethint);
556 /* select victims from access time array */
557 for (i = 0; i < afs_cacheFiles; i++) {
558 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
559 /* skip if dirty or already free */
562 tdc = afs_indexTable[i];
563 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
565 /* Wrong bucket; can't use it! */
568 if (tdc && (tdc->refCount != 0)) {
569 /* Referenced; can't use it! */
572 hset(vtime, afs_indexTimes[i]);
574 /* if we've already looked at this one, skip it */
575 if (afs_indexFlags[i] & IFFlag)
578 if (victimPtr < MAXATONCE) {
579 /* if there's at least one free victim slot left */
580 victims[victimPtr] = i;
581 hset(victimTimes[victimPtr], vtime);
582 if (hcmp(vtime, maxVictimTime) > 0) {
583 hset(maxVictimTime, vtime);
584 maxVictimPtr = victimPtr;
587 } else if (hcmp(vtime, maxVictimTime) < 0) {
589 * We're older than youngest victim, so we replace at
592 /* find youngest (largest LRU) victim */
595 osi_Panic("getdownd local");
597 hset(victimTimes[j], vtime);
598 /* recompute maxVictimTime */
599 hset(maxVictimTime, vtime);
600 for (j = 0; j < victimPtr; j++)
601 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
602 hset(maxVictimTime, victimTimes[j]);
608 /* now really reclaim the victims */
609 j = 0; /* flag to track if we actually got any of the victims */
610 /* first, hold all the victims, since we're going to release the lock
611 * during the truncate operation.
613 for (i = 0; i < victimPtr; i++) {
614 tdc = afs_GetDSlot(victims[i], 0);
615 /* We got tdc->tlock(R) here */
616 if (tdc->refCount == 1)
620 ReleaseReadLock(&tdc->tlock);
624 for (i = 0; i < victimPtr; i++) {
625 /* q is first elt in dcache entry */
627 /* now, since we're dropping the afs_xdcache lock below, we
628 * have to verify, before proceeding, that there are no other
629 * references to this dcache entry, even now. Note that we
630 * compare with 1, since we bumped it above when we called
631 * afs_GetDSlot to preserve the entry's identity.
633 if (tdc && tdc->refCount == 1) {
634 unsigned char chunkFlags;
635 afs_size_t tchunkoffset = 0;
637 /* xdcache is lower than the xvcache lock */
638 MReleaseWriteLock(&afs_xdcache);
639 MObtainReadLock(&afs_xvcache);
640 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
641 MReleaseReadLock(&afs_xvcache);
642 MObtainWriteLock(&afs_xdcache, 527);
644 if (tdc->refCount > 1)
647 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
648 chunkFlags = afs_indexFlags[tdc->index];
649 if (((phase & 1) == 0) && osi_Active(tvc))
651 if (((phase & 1) == 1) && osi_Active(tvc)
652 && (tvc->states & CDCLock)
653 && (chunkFlags & IFAnyPages))
655 if (chunkFlags & IFDataMod)
657 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
658 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
659 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
660 ICL_HANDLE_OFFSET(tchunkoffset));
662 #if defined(AFS_SUN5_ENV)
664 * Now we try to invalidate pages. We do this only for
665 * Solaris. For other platforms, it's OK to recycle a
666 * dcache entry out from under a page, because the strategy
667 * function can call afs_GetDCache().
669 if (!skip && (chunkFlags & IFAnyPages)) {
672 MReleaseWriteLock(&afs_xdcache);
673 MObtainWriteLock(&tvc->vlock, 543);
674 if (tvc->multiPage) {
678 /* block locking pages */
679 tvc->vstates |= VPageCleaning;
680 /* block getting new pages */
682 MReleaseWriteLock(&tvc->vlock);
683 /* One last recheck */
684 MObtainWriteLock(&afs_xdcache, 333);
685 chunkFlags = afs_indexFlags[tdc->index];
686 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
687 || (osi_Active(tvc) && (tvc->states & CDCLock)
688 && (chunkFlags & IFAnyPages))) {
690 MReleaseWriteLock(&afs_xdcache);
693 MReleaseWriteLock(&afs_xdcache);
695 code = osi_VM_GetDownD(tvc, tdc);
697 MObtainWriteLock(&afs_xdcache, 269);
698 /* we actually removed all pages, clean and dirty */
700 afs_indexFlags[tdc->index] &=
701 ~(IFDirtyPages | IFAnyPages);
704 MReleaseWriteLock(&afs_xdcache);
706 MObtainWriteLock(&tvc->vlock, 544);
707 if (--tvc->activeV == 0
708 && (tvc->vstates & VRevokeWait)) {
709 tvc->vstates &= ~VRevokeWait;
710 afs_osi_Wakeup((char *)&tvc->vstates);
713 if (tvc->vstates & VPageCleaning) {
714 tvc->vstates &= ~VPageCleaning;
715 afs_osi_Wakeup((char *)&tvc->vstates);
718 MReleaseWriteLock(&tvc->vlock);
720 #endif /* AFS_SUN5_ENV */
722 MReleaseWriteLock(&afs_xdcache);
726 MObtainWriteLock(&afs_xdcache, 528);
727 if (afs_indexFlags[tdc->index] &
728 (IFDataMod | IFDirtyPages | IFAnyPages))
730 if (tdc->refCount > 1)
733 #if defined(AFS_SUN5_ENV)
735 /* no vnode, so IFDirtyPages is spurious (we don't
736 * sweep dcaches on vnode recycling, so we can have
737 * DIRTYPAGES set even when all pages are gone). Just
739 * Hold vcache lock to prevent vnode from being
740 * created while we're clearing IFDirtyPages.
742 afs_indexFlags[tdc->index] &=
743 ~(IFDirtyPages | IFAnyPages);
747 /* skip this guy and mark him as recently used */
748 afs_indexFlags[tdc->index] |= IFFlag;
749 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
750 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
751 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
752 ICL_HANDLE_OFFSET(tchunkoffset));
754 /* flush this dude from the data cache and reclaim;
755 * first, make sure no one will care that we damage
756 * it, by removing it from all hash tables. Then,
757 * melt it down for parts. Note that any concurrent
758 * (new possibility!) calls to GetDownD won't touch
759 * this guy because his reference count is > 0. */
760 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
761 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
762 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
763 ICL_HANDLE_OFFSET(tchunkoffset));
764 AFS_STATCNT(afs_gget);
765 afs_HashOutDCache(tdc);
766 if (tdc->f.chunkBytes != 0) {
770 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
775 afs_DiscardDCache(tdc);
780 j = 1; /* we reclaimed at least one victim */
787 /* Phase is 0 and no one was found, so try phase 1 (ignore
788 * osi_Active flag) */
791 for (i = 0; i < afs_cacheFiles; i++)
792 /* turn off all flags */
793 afs_indexFlags[i] &= ~IFFlag;
796 /* found no one in phases 0-5, we're hosed */
800 } /* big while loop */
807 * Description: remove adc from any hash tables that would allow it to be located
808 * again by afs_FindDCache or afs_GetDCache.
810 * Parameters: adc -- pointer to dcache entry to remove from hash tables.
812 * Locks: Must have the afs_xdcache lock write-locked to call this function.
815 afs_HashOutDCache(struct dcache *adc)
819 AFS_STATCNT(afs_glink);
820 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
822 /* if this guy is in the hash table, pull him out */
823 if (adc->f.fid.Fid.Volume != 0) {
824 /* remove entry from first hash chains */
825 i = DCHash(&adc->f.fid, adc->f.chunk);
826 us = afs_dchashTbl[i];
827 if (us == adc->index) {
828 /* first dude in the list */
829 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
831 /* somewhere on the chain */
832 while (us != NULLIDX) {
833 if (afs_dcnextTbl[us] == adc->index) {
834 /* found item pointing at the one to delete */
835 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
838 us = afs_dcnextTbl[us];
841 osi_Panic("dcache hc");
843 /* remove entry from *other* hash chain */
844 i = DVHash(&adc->f.fid);
845 us = afs_dvhashTbl[i];
846 if (us == adc->index) {
847 /* first dude in the list */
848 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
850 /* somewhere on the chain */
851 while (us != NULLIDX) {
852 if (afs_dvnextTbl[us] == adc->index) {
853 /* found item pointing at the one to delete */
854 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
857 us = afs_dvnextTbl[us];
860 osi_Panic("dcache hv");
864 /* prevent entry from being found on a reboot (it is already out of
865 * the hash table, but after a crash, we just look at fid fields of
866 * stable (old) entries).
868 adc->f.fid.Fid.Volume = 0; /* invalid */
870 /* mark entry as modified */
871 adc->dflags |= DFEntryMod;
875 } /*afs_HashOutDCache */
882 * Flush the given dcache entry, pulling it from hash chains
883 * and truncating the associated cache file.
886 * adc: Ptr to dcache entry to flush.
889 * This routine must be called with the afs_xdcache lock held
894 afs_FlushDCache(register struct dcache *adc)
896 AFS_STATCNT(afs_FlushDCache);
898 * Bump the number of cache files flushed.
900 afs_stats_cmperf.cacheFlushes++;
902 /* remove from all hash tables */
903 afs_HashOutDCache(adc);
905 /* Free its space; special case null operation, since truncate operation
906 * in UFS is slow even in this case, and this allows us to pre-truncate
907 * these files at more convenient times with fewer locks set
908 * (see afs_GetDownD).
910 if (adc->f.chunkBytes != 0) {
911 afs_DiscardDCache(adc);
912 afs_MaybeWakeupTruncateDaemon();
917 if (afs_WaitForCacheDrain) {
918 if (afs_blocksUsed <=
919 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
920 afs_WaitForCacheDrain = 0;
921 afs_osi_Wakeup(&afs_WaitForCacheDrain);
924 } /*afs_FlushDCache */
930 * Description: put a dcache entry on the free dcache entry list.
932 * Parameters: adc -- dcache entry to free
934 * Environment: called with afs_xdcache lock write-locked.
937 afs_FreeDCache(register struct dcache *adc)
939 /* Thread on free list, update free list count and mark entry as
940 * freed in its indexFlags element. Also, ensure DCache entry gets
941 * written out (set DFEntryMod).
944 afs_dvnextTbl[adc->index] = afs_freeDCList;
945 afs_freeDCList = adc->index;
947 afs_indexFlags[adc->index] |= IFFree;
948 adc->dflags |= DFEntryMod;
950 if (afs_WaitForCacheDrain) {
951 if ((afs_blocksUsed - afs_blocksDiscarded) <=
952 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
953 afs_WaitForCacheDrain = 0;
954 afs_osi_Wakeup(&afs_WaitForCacheDrain);
963 * Discard the cache element by moving it to the discardDCList.
964 * This puts the cache element into a quasi-freed state, where
965 * the space may be reused, but the file has not been truncated.
967 * Major Assumptions Here:
968 * Assumes that frag size is an integral power of two, less one,
969 * and that this is a two's complement machine. I don't
970 * know of any filesystems which violate this assumption...
973 * adc : Ptr to dcache entry.
976 * Must be called with afs_xdcache write-locked.
980 afs_DiscardDCache(register struct dcache *adc)
982 register afs_int32 size;
984 AFS_STATCNT(afs_DiscardDCache);
986 osi_Assert(adc->refCount == 1);
988 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
989 afs_blocksDiscarded += size;
990 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
992 afs_dvnextTbl[adc->index] = afs_discardDCList;
993 afs_discardDCList = adc->index;
994 afs_discardDCCount++;
996 adc->f.fid.Fid.Volume = 0;
997 adc->dflags |= DFEntryMod;
998 afs_indexFlags[adc->index] |= IFDiscarded;
1000 if (afs_WaitForCacheDrain) {
1001 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1002 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1003 afs_WaitForCacheDrain = 0;
1004 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1008 } /*afs_DiscardDCache */
1011 * afs_FreeDiscardedDCache
1014 * Free the next element on the list of discarded cache elements.
1017 afs_FreeDiscardedDCache(void)
1019 register struct dcache *tdc;
1020 register struct osi_file *tfile;
1021 register afs_int32 size;
1023 AFS_STATCNT(afs_FreeDiscardedDCache);
1025 MObtainWriteLock(&afs_xdcache, 510);
1026 if (!afs_blocksDiscarded) {
1027 MReleaseWriteLock(&afs_xdcache);
1032 * Get an entry from the list of discarded cache elements
1034 tdc = afs_GetDSlot(afs_discardDCList, 0);
1035 osi_Assert(tdc->refCount == 1);
1036 ReleaseReadLock(&tdc->tlock);
1038 afs_discardDCList = afs_dvnextTbl[tdc->index];
1039 afs_dvnextTbl[tdc->index] = NULLIDX;
1040 afs_discardDCCount--;
1041 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1042 afs_blocksDiscarded -= size;
1043 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1044 /* We can lock because we just took it off the free list */
1045 ObtainWriteLock(&tdc->lock, 626);
1046 MReleaseWriteLock(&afs_xdcache);
1049 * Truncate the element to reclaim its space
1051 tfile = afs_CFileOpen(tdc->f.inode);
1052 afs_CFileTruncate(tfile, 0);
1053 afs_CFileClose(tfile);
1054 afs_AdjustSize(tdc, 0);
1055 tdc->f.states &= ~(DRO|DBackup|DRW);
1056 afs_DCMoveBucket(tdc, 0, 0);
1059 * Free the element we just truncated
1061 MObtainWriteLock(&afs_xdcache, 511);
1062 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1063 afs_FreeDCache(tdc);
1064 ReleaseWriteLock(&tdc->lock);
1066 MReleaseWriteLock(&afs_xdcache);
1070 * afs_MaybeFreeDiscardedDCache
1073 * Free as many entries from the list of discarded cache elements
1074 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1080 afs_MaybeFreeDiscardedDCache(void)
1083 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1085 while (afs_blocksDiscarded &&
1086 (afs_blocksUsed > PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1087 afs_FreeDiscardedDCache();
1096 * Try to free up a certain number of disk slots.
1099 * anumber : Targeted number of disk slots to free up.
1102 * Must be called with afs_xdcache write-locked.
1105 afs_GetDownDSlot(int anumber)
1107 struct afs_q *tq, *nq;
1112 AFS_STATCNT(afs_GetDownDSlot);
1113 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1114 osi_Panic("diskless getdowndslot");
1116 if (CheckLock(&afs_xdcache) != -1)
1117 osi_Panic("getdowndslot nolock");
1119 /* decrement anumber first for all dudes in free list */
1120 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1123 return; /* enough already free */
1125 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1127 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1128 nq = QPrev(tq); /* in case we remove it */
1129 if (tdc->refCount == 0) {
1130 if ((ix = tdc->index) == NULLIDX)
1131 osi_Panic("getdowndslot");
1132 /* pull the entry out of the lruq and put it on the free list */
1133 QRemove(&tdc->lruq);
1135 /* write-through if modified */
1136 if (tdc->dflags & DFEntryMod) {
1137 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1139 * ask proxy to do this for us - we don't have the stack space
1141 while (tdc->dflags & DFEntryMod) {
1144 s = SPLOCK(afs_sgibklock);
1145 if (afs_sgibklist == NULL) {
1146 /* if slot is free, grab it. */
1147 afs_sgibklist = tdc;
1148 SV_SIGNAL(&afs_sgibksync);
1150 /* wait for daemon to (start, then) finish. */
1151 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1155 tdc->dflags &= ~DFEntryMod;
1156 afs_WriteDCache(tdc, 1);
1160 /* finally put the entry in the free list */
1161 afs_indexTable[ix] = NULL;
1162 afs_indexFlags[ix] &= ~IFEverUsed;
1163 tdc->index = NULLIDX;
1164 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1165 afs_freeDSList = tdc;
1169 } /*afs_GetDownDSlot */
1176 * Increment the reference count on a disk cache entry,
1177 * which already has a non-zero refcount. In order to
1178 * increment the refcount of a zero-reference entry, you
1179 * have to hold afs_xdcache.
1182 * adc : Pointer to the dcache entry to increment.
1185 * Nothing interesting.
1188 afs_RefDCache(struct dcache *adc)
1190 ObtainWriteLock(&adc->tlock, 627);
1191 if (adc->refCount < 0)
1192 osi_Panic("RefDCache: negative refcount");
1194 ReleaseWriteLock(&adc->tlock);
1203 * Decrement the reference count on a disk cache entry.
1206 * ad : Ptr to the dcache entry to decrement.
1209 * Nothing interesting.
1212 afs_PutDCache(register struct dcache *adc)
1214 AFS_STATCNT(afs_PutDCache);
1215 ObtainWriteLock(&adc->tlock, 276);
1216 if (adc->refCount <= 0)
1217 osi_Panic("putdcache");
1219 ReleaseWriteLock(&adc->tlock);
1228 * Try to discard all data associated with this file from the
1232 * avc : Pointer to the cache info for the file.
1235 * Both pvnLock and lock are write held.
1238 afs_TryToSmush(register struct vcache *avc, struct AFS_UCRED *acred, int sync)
1240 register struct dcache *tdc;
1243 AFS_STATCNT(afs_TryToSmush);
1244 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1245 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->m.Length));
1246 sync = 1; /* XX Temp testing XX */
1248 #if defined(AFS_SUN5_ENV)
1249 ObtainWriteLock(&avc->vlock, 573);
1250 avc->activeV++; /* block new getpages */
1251 ReleaseWriteLock(&avc->vlock);
1254 /* Flush VM pages */
1255 osi_VM_TryToSmush(avc, acred, sync);
1258 * Get the hash chain containing all dce's for this fid
1260 i = DVHash(&avc->fid);
1261 MObtainWriteLock(&afs_xdcache, 277);
1262 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1263 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1264 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1265 int releaseTlock = 1;
1266 tdc = afs_GetDSlot(index, NULL);
1267 if (!FidCmp(&tdc->f.fid, &avc->fid)) {
1269 if ((afs_indexFlags[index] & IFDataMod) == 0
1270 && tdc->refCount == 1) {
1271 ReleaseReadLock(&tdc->tlock);
1273 afs_FlushDCache(tdc);
1276 afs_indexTable[index] = 0;
1279 ReleaseReadLock(&tdc->tlock);
1283 #if defined(AFS_SUN5_ENV)
1284 ObtainWriteLock(&avc->vlock, 545);
1285 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1286 avc->vstates &= ~VRevokeWait;
1287 afs_osi_Wakeup((char *)&avc->vstates);
1289 ReleaseWriteLock(&avc->vlock);
1291 MReleaseWriteLock(&afs_xdcache);
1293 * It's treated like a callback so that when we do lookups we'll invalidate the unique bit if any
1294 * trytoSmush occured during the lookup call
1303 * Given the cached info for a file and a byte offset into the
1304 * file, make sure the dcache entry for that file and containing
1305 * the given byte is available, returning it to our caller.
1308 * avc : Pointer to the (held) vcache entry to look in.
1309 * abyte : Which byte we want to get to.
1312 * Pointer to the dcache entry covering the file & desired byte,
1313 * or NULL if not found.
1316 * The vcache entry is held upon entry.
1320 afs_FindDCache(register struct vcache *avc, afs_size_t abyte)
1323 register afs_int32 i, index;
1324 register struct dcache *tdc = NULL;
1326 AFS_STATCNT(afs_FindDCache);
1327 chunk = AFS_CHUNK(abyte);
1330 * Hash on the [fid, chunk] and get the corresponding dcache index
1331 * after write-locking the dcache.
1333 i = DCHash(&avc->fid, chunk);
1334 MObtainWriteLock(&afs_xdcache, 278);
1335 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1336 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1337 tdc = afs_GetDSlot(index, NULL);
1338 ReleaseReadLock(&tdc->tlock);
1339 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1340 break; /* leaving refCount high for caller */
1345 index = afs_dcnextTbl[index];
1347 MReleaseWriteLock(&afs_xdcache);
1348 if (index != NULLIDX) {
1349 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1350 hadd32(afs_indexCounter, 1);
1355 } /*afs_FindDCache */
1359 * afs_UFSCacheStoreProc
1362 * Called upon store.
1365 * acall : Ptr to the Rx call structure involved.
1366 * afile : Ptr to the related file descriptor.
1367 * alen : Size of the file in bytes.
1368 * avc : Ptr to the vcache entry.
1369 * shouldWake : is it "safe" to return early from close() ?
1370 * abytesToXferP : Set to the number of bytes to xfer.
1371 * NOTE: This parameter is only used if AFS_NOSTATS
1373 * abytesXferredP : Set to the number of bytes actually xferred.
1374 * NOTE: This parameter is only used if AFS_NOSTATS
1378 * Nothing interesting.
1381 afs_UFSCacheStoreProc(register struct rx_call *acall, struct osi_file *afile,
1382 register afs_int32 alen, struct vcache *avc,
1383 int *shouldWake, afs_size_t * abytesToXferP,
1384 afs_size_t * abytesXferredP)
1386 afs_int32 code, got;
1387 register char *tbuffer;
1390 AFS_STATCNT(UFS_CacheStoreProc);
1394 * In this case, alen is *always* the amount of data we'll be trying
1397 (*abytesToXferP) = alen;
1398 (*abytesXferredP) = 0;
1399 #endif /* AFS_NOSTATS */
1401 afs_Trace4(afs_iclSetp, CM_TRACE_STOREPROC, ICL_TYPE_POINTER, avc,
1402 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
1403 ICL_HANDLE_OFFSET(avc->m.Length), ICL_TYPE_INT32, alen);
1404 tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1406 tlen = (alen > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : alen);
1407 got = afs_osi_Read(afile, -1, tbuffer, tlen);
1409 #if defined(KERNEL_HAVE_UERROR)
1410 || (got != tlen && getuerror())
1413 osi_FreeLargeSpace(tbuffer);
1416 afs_Trace2(afs_iclSetp, CM_TRACE_STOREPROC2, ICL_TYPE_OFFSET,
1417 ICL_HANDLE_OFFSET(*tbuffer), ICL_TYPE_INT32, got);
1419 code = rx_Write(acall, tbuffer, got); /* writing 0 bytes will
1420 * push a short packet. Is that really what we want, just because the
1421 * data didn't come back from the disk yet? Let's try it and see. */
1424 (*abytesXferredP) += code;
1425 #endif /* AFS_NOSTATS */
1427 code = rx_Error(acall);
1428 osi_FreeLargeSpace(tbuffer);
1429 return code ? code : -33;
1433 * If file has been locked on server, we can allow the store
1436 if (shouldWake && *shouldWake && (rx_GetRemoteStatus(acall) & 1)) {
1437 *shouldWake = 0; /* only do this once */
1441 afs_Trace4(afs_iclSetp, CM_TRACE_STOREPROC, ICL_TYPE_POINTER, avc,
1442 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
1443 ICL_HANDLE_OFFSET(avc->m.Length), ICL_TYPE_INT32, alen);
1444 osi_FreeLargeSpace(tbuffer);
1447 } /* afs_UFSCacheStoreProc */
1451 * afs_UFSCacheFetchProc
1454 * Routine called on fetch; also tells people waiting for data
1455 * that more has arrived.
1458 * acall : Ptr to the Rx call structure.
1459 * afile : File descriptor for the cache file.
1460 * abase : Base offset to fetch.
1461 * adc : Ptr to the dcache entry for the file, write-locked.
1462 * avc : Ptr to the vcache entry for the file.
1463 * abytesToXferP : Set to the number of bytes to xfer.
1464 * NOTE: This parameter is only used if AFS_NOSTATS
1466 * abytesXferredP : Set to the number of bytes actually xferred.
1467 * NOTE: This parameter is only used if AFS_NOSTATS
1471 * Nothing interesting.
1475 afs_UFSCacheFetchProc(register struct rx_call *acall, struct osi_file *afile,
1476 afs_size_t abase, struct dcache *adc,
1477 struct vcache *avc, afs_size_t * abytesToXferP,
1478 afs_size_t * abytesXferredP, afs_int32 lengthFound)
1481 register afs_int32 code;
1482 register char *tbuffer;
1486 AFS_STATCNT(UFS_CacheFetchProc);
1487 osi_Assert(WriteLocked(&adc->lock));
1488 afile->offset = 0; /* Each time start from the beginning */
1489 length = lengthFound;
1491 (*abytesToXferP) = 0;
1492 (*abytesXferredP) = 0;
1493 #endif /* AFS_NOSTATS */
1494 tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1495 adc->validPos = abase;
1499 code = rx_Read(acall, (char *)&length, sizeof(afs_int32));
1501 length = ntohl(length);
1502 if (code != sizeof(afs_int32)) {
1503 osi_FreeLargeSpace(tbuffer);
1504 code = rx_Error(acall);
1505 return (code ? code : -1); /* try to return code, not -1 */
1509 * The fetch protocol is extended for the AFS/DFS translator
1510 * to allow multiple blocks of data, each with its own length,
1511 * to be returned. As long as the top bit is set, there are more
1514 * We do not do this for AFS file servers because they sometimes
1515 * return large negative numbers as the transfer size.
1517 if (avc->states & CForeign) {
1518 moredata = length & 0x80000000;
1519 length &= ~0x80000000;
1524 (*abytesToXferP) += length;
1525 #endif /* AFS_NOSTATS */
1526 while (length > 0) {
1527 tlen = (length > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : length);
1528 #ifdef RX_KERNEL_TRACE
1529 afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
1533 code = rx_Read(acall, tbuffer, tlen);
1535 #ifdef RX_KERNEL_TRACE
1536 afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
1540 (*abytesXferredP) += code;
1541 #endif /* AFS_NOSTATS */
1543 osi_FreeLargeSpace(tbuffer);
1544 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64READ,
1545 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
1546 ICL_TYPE_INT32, length);
1549 code = afs_osi_Write(afile, -1, tbuffer, tlen);
1551 osi_FreeLargeSpace(tbuffer);
1556 adc->validPos = abase;
1557 if (afs_osi_Wakeup(&adc->validPos) == 0)
1558 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
1559 __FILE__, ICL_TYPE_INT32, __LINE__,
1560 ICL_TYPE_POINTER, adc, ICL_TYPE_INT32,
1564 osi_FreeLargeSpace(tbuffer);
1567 } /* afs_UFSCacheFetchProc */
1573 * This function is called to obtain a reference to data stored in
1574 * the disk cache, locating a chunk of data containing the desired
1575 * byte and returning a reference to the disk cache entry, with its
1576 * reference count incremented.
1580 * avc : Ptr to a vcache entry (unlocked)
1581 * abyte : Byte position in the file desired
1582 * areq : Request structure identifying the requesting user.
1583 * aflags : Settings as follows:
1585 * 2 : Return after creating entry.
1586 * 4 : called from afs_vnop_write.c
1587 * *alen contains length of data to be written.
1589 * aoffset : Set to the offset within the chunk where the resident
1591 * alen : Set to the number of bytes of data after the desired
1592 * byte (including the byte itself) which can be read
1596 * The vcache entry pointed to by avc is unlocked upon entry.
1600 struct AFSVolSync tsync;
1601 struct AFSFetchStatus OutStatus;
1602 struct AFSCallBack CallBack;
1606 * Update the vnode-to-dcache hint if we can get the vnode lock
1607 * right away. Assumes dcache entry is at least read-locked.
1610 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1612 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1613 if (hsame(v->m.DataVersion, d->f.versionNo) && v->callback)
1616 ReleaseWriteLock(&v->lock);
1620 /* avc - Write-locked unless aflags & 1 */
1622 afs_GetDCache(register struct vcache *avc, afs_size_t abyte,
1623 register struct vrequest *areq, afs_size_t * aoffset,
1624 afs_size_t * alen, int aflags)
1626 register afs_int32 i, code, code1 = 0, shortcut;
1627 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1628 register afs_int32 adjustsize = 0;
1634 afs_size_t maxGoodLength; /* amount of good data at server */
1635 struct rx_call *tcall;
1636 afs_size_t Position = 0;
1637 #ifdef AFS_64BIT_CLIENT
1639 afs_size_t lengthFound; /* as returned from server */
1640 #endif /* AFS_64BIT_CLIENT */
1641 afs_int32 size, tlen; /* size of segment to transfer */
1642 struct tlocal1 *tsmall = 0;
1643 register struct dcache *tdc;
1644 register struct osi_file *file;
1645 register struct conn *tc;
1647 struct server *newCallback = NULL;
1648 char setNewCallback;
1649 char setVcacheStatus;
1650 char doVcacheUpdate;
1652 int doAdjustSize = 0;
1653 int doReallyAdjustSize = 0;
1654 int overWriteWholeChunk = 0;
1658 struct afs_stats_xferData *xferP; /* Ptr to this op's xfer struct */
1659 osi_timeval_t xferStartTime, /*FS xfer start time */
1660 xferStopTime; /*FS xfer stop time */
1661 afs_size_t bytesToXfer; /* # bytes to xfer */
1662 afs_size_t bytesXferred; /* # bytes actually xferred */
1663 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1664 int fromReplica; /*Are we reading from a replica? */
1665 int numFetchLoops; /*# times around the fetch/analyze loop */
1666 #endif /* AFS_NOSTATS */
1668 AFS_STATCNT(afs_GetDCache);
1673 setLocks = aflags & 1;
1676 * Determine the chunk number and offset within the chunk corresponding
1677 * to the desired byte.
1679 if (avc->fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1682 chunk = AFS_CHUNK(abyte);
1685 /* come back to here if we waited for the cache to drain. */
1688 setNewCallback = setVcacheStatus = 0;
1692 ObtainWriteLock(&avc->lock, 616);
1694 ObtainReadLock(&avc->lock);
1699 * avc->lock(R) if setLocks && !slowPass
1700 * avc->lock(W) if !setLocks || slowPass
1705 /* check hints first! (might could use bcmp or some such...) */
1706 if ((tdc = avc->dchint)) {
1710 * The locking order between afs_xdcache and dcache lock matters.
1711 * The hint dcache entry could be anywhere, even on the free list.
1712 * Locking afs_xdcache ensures that noone is trying to pull dcache
1713 * entries from the free list, and thereby assuming them to be not
1714 * referenced and not locked.
1716 MObtainReadLock(&afs_xdcache);
1717 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1719 if (dcLocked && (tdc->index != NULLIDX)
1720 && !FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk
1721 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1722 /* got the right one. It might not be the right version, and it
1723 * might be fetching, but it's the right dcache entry.
1725 /* All this code should be integrated better with what follows:
1726 * I can save a good bit more time under a write lock if I do..
1728 ObtainWriteLock(&tdc->tlock, 603);
1730 ReleaseWriteLock(&tdc->tlock);
1732 MReleaseReadLock(&afs_xdcache);
1735 if (hsame(tdc->f.versionNo, avc->m.DataVersion)
1736 && !(tdc->dflags & DFFetching)) {
1738 afs_stats_cmperf.dcacheHits++;
1739 MObtainWriteLock(&afs_xdcache, 559);
1740 QRemove(&tdc->lruq);
1741 QAdd(&afs_DLRU, &tdc->lruq);
1742 MReleaseWriteLock(&afs_xdcache);
1745 * avc->lock(R) if setLocks && !slowPass
1746 * avc->lock(W) if !setLocks || slowPass
1753 ReleaseSharedLock(&tdc->lock);
1754 MReleaseReadLock(&afs_xdcache);
1762 * avc->lock(R) if setLocks && !slowPass
1763 * avc->lock(W) if !setLocks || slowPass
1764 * tdc->lock(S) if tdc
1767 if (!tdc) { /* If the hint wasn't the right dcache entry */
1769 * Hash on the [fid, chunk] and get the corresponding dcache index
1770 * after write-locking the dcache.
1775 * avc->lock(R) if setLocks && !slowPass
1776 * avc->lock(W) if !setLocks || slowPass
1779 i = DCHash(&avc->fid, chunk);
1780 /* check to make sure our space is fine */
1781 afs_MaybeWakeupTruncateDaemon();
1783 MObtainWriteLock(&afs_xdcache, 280);
1785 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1786 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1787 tdc = afs_GetDSlot(index, NULL);
1788 ReleaseReadLock(&tdc->tlock);
1791 * avc->lock(R) if setLocks && !slowPass
1792 * avc->lock(W) if !setLocks || slowPass
1795 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1796 /* Move it up in the beginning of the list */
1797 if (afs_dchashTbl[i] != index) {
1798 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1799 afs_dcnextTbl[index] = afs_dchashTbl[i];
1800 afs_dchashTbl[i] = index;
1802 MReleaseWriteLock(&afs_xdcache);
1803 ObtainSharedLock(&tdc->lock, 606);
1804 break; /* leaving refCount high for caller */
1810 index = afs_dcnextTbl[index];
1814 * If we didn't find the entry, we'll create one.
1816 if (index == NULLIDX) {
1819 * avc->lock(R) if setLocks
1820 * avc->lock(W) if !setLocks
1823 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1824 avc, ICL_TYPE_INT32, chunk);
1826 /* Make sure there is a free dcache entry for us to use */
1827 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1830 avc->states |= CDCLock;
1831 /* just need slots */
1832 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1834 avc->states &= ~CDCLock;
1835 if (afs_discardDCList != NULLIDX
1836 || afs_freeDCList != NULLIDX)
1838 /* If we can't get space for 5 mins we give up and panic */
1839 if (++downDCount > 300)
1840 osi_Panic("getdcache");
1841 MReleaseWriteLock(&afs_xdcache);
1844 * avc->lock(R) if setLocks
1845 * avc->lock(W) if !setLocks
1847 afs_osi_Wait(1000, 0, 0);
1852 if (afs_discardDCList == NULLIDX
1853 || ((aflags & 2) && afs_freeDCList != NULLIDX)) {
1855 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1856 tdc = afs_GetDSlot(afs_freeDCList, 0);
1857 osi_Assert(tdc->refCount == 1);
1858 ReleaseReadLock(&tdc->tlock);
1859 ObtainWriteLock(&tdc->lock, 604);
1860 afs_freeDCList = afs_dvnextTbl[tdc->index];
1863 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1864 tdc = afs_GetDSlot(afs_discardDCList, 0);
1865 osi_Assert(tdc->refCount == 1);
1866 ReleaseReadLock(&tdc->tlock);
1867 ObtainWriteLock(&tdc->lock, 605);
1868 afs_discardDCList = afs_dvnextTbl[tdc->index];
1869 afs_discardDCCount--;
1871 ((tdc->f.chunkBytes +
1872 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1873 tdc->f.states &= ~(DRO|DBackup|DRW);
1874 afs_DCMoveBucket(tdc, size, 0);
1875 afs_blocksDiscarded -= size;
1876 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1878 /* Truncate the chunk so zeroes get filled properly */
1879 file = afs_CFileOpen(tdc->f.inode);
1880 afs_CFileTruncate(file, 0);
1881 afs_CFileClose(file);
1882 afs_AdjustSize(tdc, 0);
1888 * avc->lock(R) if setLocks
1889 * avc->lock(W) if !setLocks
1895 * Fill in the newly-allocated dcache record.
1897 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1898 tdc->f.fid = avc->fid;
1899 if (avc->states & CRO)
1900 tdc->f.states = DRO;
1901 else if (avc->states & CBackup)
1902 tdc->f.states = DBackup;
1904 tdc->f.states = DRW;
1905 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1906 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1907 hones(tdc->f.versionNo); /* invalid value */
1908 tdc->f.chunk = chunk;
1909 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1911 if (tdc->lruq.prev == &tdc->lruq)
1912 osi_Panic("lruq 1");
1915 * Now add to the two hash chains - note that i is still set
1916 * from the above DCHash call.
1918 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1919 afs_dchashTbl[i] = tdc->index;
1920 i = DVHash(&avc->fid);
1921 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1922 afs_dvhashTbl[i] = tdc->index;
1923 tdc->dflags = DFEntryMod;
1925 afs_MaybeWakeupTruncateDaemon();
1926 MReleaseWriteLock(&afs_xdcache);
1927 ConvertWToSLock(&tdc->lock);
1932 /* vcache->dcache hint failed */
1935 * avc->lock(R) if setLocks && !slowPass
1936 * avc->lock(W) if !setLocks || slowPass
1939 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1940 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
1941 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
1942 hgetlo(avc->m.DataVersion));
1944 * Here we have the entry in tdc, with its refCount incremented.
1945 * Note: we don't use the S-lock on avc; it costs concurrency when
1946 * storing a file back to the server.
1950 * Not a newly created file so we need to check the file's length and
1951 * compare data versions since someone could have changed the data or we're
1952 * reading a file written elsewhere. We only want to bypass doing no-op
1953 * read rpcs on newly created files (dv of 0) since only then we guarantee
1954 * that this chunk's data hasn't been filled by another client.
1956 size = AFS_CHUNKSIZE(abyte);
1957 if (aflags & 4) /* called from write */
1959 else /* called from read */
1960 tlen = tdc->validPos - abyte;
1961 Position = AFS_CHUNKTOBASE(chunk);
1962 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
1963 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
1964 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
1965 ICL_HANDLE_OFFSET(Position));
1966 if ((aflags & 4) && (hiszero(avc->m.DataVersion)))
1968 if ((AFS_CHUNKTOBASE(chunk) >= avc->m.Length) ||
1969 ((aflags & 4) && (abyte == Position) && (tlen >= size))))
1970 overWriteWholeChunk = 1;
1971 if (doAdjustSize || overWriteWholeChunk) {
1972 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1974 #ifdef AFS_SGI64_ENV
1977 #else /* AFS_SGI64_ENV */
1980 #endif /* AFS_SGI64_ENV */
1981 #else /* AFS_SGI_ENV */
1984 #endif /* AFS_SGI_ENV */
1985 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->m.Length &&
1986 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1987 #if defined(AFS_SUN5_ENV) || defined(AFS_OSF_ENV)
1988 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->m.Length)) &&
1990 if (AFS_CHUNKTOBASE(chunk) >= avc->m.Length &&
1992 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1993 !hsame(avc->m.DataVersion, tdc->f.versionNo))
1994 doReallyAdjustSize = 1;
1996 if (doReallyAdjustSize || overWriteWholeChunk) {
1997 /* no data in file to read at this position */
1998 UpgradeSToWLock(&tdc->lock, 607);
2000 file = afs_CFileOpen(tdc->f.inode);
2001 afs_CFileTruncate(file, 0);
2002 afs_CFileClose(file);
2003 afs_AdjustSize(tdc, 0);
2004 hset(tdc->f.versionNo, avc->m.DataVersion);
2005 tdc->dflags |= DFEntryMod;
2007 ConvertWToSLock(&tdc->lock);
2012 * We must read in the whole chunk if the version number doesn't
2016 /* don't need data, just a unique dcache entry */
2017 ObtainWriteLock(&afs_xdcache, 608);
2018 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2019 hadd32(afs_indexCounter, 1);
2020 ReleaseWriteLock(&afs_xdcache);
2022 updateV2DC(setLocks, avc, tdc, 553);
2023 if (vType(avc) == VDIR)
2026 *aoffset = AFS_CHUNKOFFSET(abyte);
2027 if (tdc->validPos < abyte)
2028 *alen = (afs_size_t) 0;
2030 *alen = tdc->validPos - abyte;
2031 ReleaseSharedLock(&tdc->lock);
2034 ReleaseWriteLock(&avc->lock);
2036 ReleaseReadLock(&avc->lock);
2038 return tdc; /* check if we're done */
2043 * avc->lock(R) if setLocks && !slowPass
2044 * avc->lock(W) if !setLocks || slowPass
2047 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
2049 setNewCallback = setVcacheStatus = 0;
2053 * avc->lock(R) if setLocks && !slowPass
2054 * avc->lock(W) if !setLocks || slowPass
2057 if (!hsame(avc->m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
2059 * Version number mismatch.
2061 UpgradeSToWLock(&tdc->lock, 609);
2064 * If data ever existed for this vnode, and this is a text object,
2065 * do some clearing. Now, you'd think you need only do the flush
2066 * when VTEXT is on, but VTEXT is turned off when the text object
2067 * is freed, while pages are left lying around in memory marked
2068 * with this vnode. If we would reactivate (create a new text
2069 * object from) this vnode, we could easily stumble upon some of
2070 * these old pages in pagein. So, we always flush these guys.
2071 * Sun has a wonderful lack of useful invariants in this system.
2073 * avc->flushDV is the data version # of the file at the last text
2074 * flush. Clearly, at least, we don't have to flush the file more
2075 * often than it changes
2077 if (hcmp(avc->flushDV, avc->m.DataVersion) < 0) {
2079 * By here, the cache entry is always write-locked. We can
2080 * deadlock if we call osi_Flush with the cache entry locked...
2081 * Unlock the dcache too.
2083 ReleaseWriteLock(&tdc->lock);
2084 if (setLocks && !slowPass)
2085 ReleaseReadLock(&avc->lock);
2087 ReleaseWriteLock(&avc->lock);
2091 * Call osi_FlushPages in open, read/write, and map, since it
2092 * is too hard here to figure out if we should lock the
2095 if (setLocks && !slowPass)
2096 ObtainReadLock(&avc->lock);
2098 ObtainWriteLock(&avc->lock, 66);
2099 ObtainWriteLock(&tdc->lock, 610);
2104 * avc->lock(R) if setLocks && !slowPass
2105 * avc->lock(W) if !setLocks || slowPass
2109 /* Watch for standard race condition around osi_FlushText */
2110 if (hsame(avc->m.DataVersion, tdc->f.versionNo)) {
2111 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2112 afs_stats_cmperf.dcacheHits++;
2113 ConvertWToSLock(&tdc->lock);
2117 /* Sleep here when cache needs to be drained. */
2118 if (setLocks && !slowPass &&
2119 (afs_blocksUsed > PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2120 /* Make sure truncate daemon is running */
2121 afs_MaybeWakeupTruncateDaemon();
2122 ObtainWriteLock(&tdc->tlock, 614);
2123 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2124 ReleaseWriteLock(&tdc->tlock);
2125 ReleaseWriteLock(&tdc->lock);
2126 ReleaseReadLock(&avc->lock);
2127 while ((afs_blocksUsed - afs_blocksDiscarded) >
2128 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2129 afs_WaitForCacheDrain = 1;
2130 afs_osi_Sleep(&afs_WaitForCacheDrain);
2132 afs_MaybeFreeDiscardedDCache();
2133 /* need to check if someone else got the chunk first. */
2134 goto RetryGetDCache;
2137 /* Do not fetch data beyond truncPos. */
2138 maxGoodLength = avc->m.Length;
2139 if (avc->truncPos < maxGoodLength)
2140 maxGoodLength = avc->truncPos;
2141 Position = AFS_CHUNKBASE(abyte);
2142 if (vType(avc) == VDIR) {
2143 size = avc->m.Length;
2144 if (size > tdc->f.chunkBytes) {
2145 /* pre-reserve space for file */
2146 afs_AdjustSize(tdc, size);
2148 size = 999999999; /* max size for transfer */
2150 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2151 /* don't read past end of good data on server */
2152 if (Position + size > maxGoodLength)
2153 size = maxGoodLength - Position;
2155 size = 0; /* Handle random races */
2156 if (size > tdc->f.chunkBytes) {
2157 /* pre-reserve space for file */
2158 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2159 /* max size for transfer still in size */
2162 if (afs_mariner && !tdc->f.chunk)
2163 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2165 * Right now, we only have one tool, and it's a hammer. So, we
2166 * fetch the whole file.
2168 DZap(tdc); /* pages in cache may be old */
2169 file = afs_CFileOpen(tdc->f.inode);
2170 afs_RemoveVCB(&avc->fid);
2171 tdc->f.states |= DWriting;
2172 tdc->dflags |= DFFetching;
2173 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2174 if (tdc->mflags & DFFetchReq) {
2175 tdc->mflags &= ~DFFetchReq;
2176 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2177 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2178 __FILE__, ICL_TYPE_INT32, __LINE__,
2179 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2183 (struct tlocal1 *)osi_AllocLargeSpace(sizeof(struct tlocal1));
2184 setVcacheStatus = 0;
2187 * Remember if we are doing the reading from a replicated volume,
2188 * and how many times we've zipped around the fetch/analyze loop.
2190 fromReplica = (avc->states & CRO) ? 1 : 0;
2192 accP = &(afs_stats_cmfullperf.accessinf);
2194 (accP->replicatedRefs)++;
2196 (accP->unreplicatedRefs)++;
2197 #endif /* AFS_NOSTATS */
2198 /* this is a cache miss */
2199 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2200 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
2201 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2204 afs_stats_cmperf.dcacheMisses++;
2207 * Dynamic root support: fetch data from local memory.
2209 if (afs_IsDynroot(avc)) {
2213 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2215 dynrootDir += Position;
2216 dynrootLen -= Position;
2217 if (size > dynrootLen)
2221 code = afs_CFileWrite(file, 0, dynrootDir, size);
2229 tdc->validPos = Position + size;
2230 afs_CFileTruncate(file, size); /* prune it */
2233 * Not a dynamic vnode: do the real fetch.
2238 * avc->lock(R) if setLocks && !slowPass
2239 * avc->lock(W) if !setLocks || slowPass
2243 tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
2245 afs_int32 length_hi, length, bytes;
2249 (accP->numReplicasAccessed)++;
2251 #endif /* AFS_NOSTATS */
2252 if (!setLocks || slowPass) {
2253 avc->callback = tc->srvr->server;
2255 newCallback = tc->srvr->server;
2260 tcall = rx_NewCall(tc->id);
2263 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
2264 #ifdef AFS_64BIT_CLIENT
2265 length_hi = code = 0;
2266 if (!afs_serverHasNo64Bit(tc)) {
2270 StartRXAFS_FetchData64(tcall,
2271 (struct AFSFid *)&avc->fid.
2272 Fid, Position, tsize);
2275 afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2276 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32,
2280 rx_Read(tcall, (char *)&length_hi,
2283 if (bytes == sizeof(afs_int32)) {
2284 length_hi = ntohl(length_hi);
2287 code = rx_Error(tcall);
2289 code1 = rx_EndCall(tcall, code);
2291 tcall = (struct rx_call *)0;
2295 if (code == RXGEN_OPCODE || afs_serverHasNo64Bit(tc)) {
2296 if (Position > 0x7FFFFFFF) {
2303 tcall = rx_NewCall(tc->id);
2305 StartRXAFS_FetchData(tcall, (struct AFSFid *)
2310 afs_serverSetNo64Bit(tc);
2315 rx_Read(tcall, (char *)&length,
2318 if (bytes == sizeof(afs_int32)) {
2319 length = ntohl(length);
2321 code = rx_Error(tcall);
2324 FillInt64(lengthFound, length_hi, length);
2325 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64LENG,
2326 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
2328 ICL_HANDLE_OFFSET(lengthFound));
2329 #else /* AFS_64BIT_CLIENT */
2332 StartRXAFS_FetchData(tcall,
2333 (struct AFSFid *)&avc->fid.Fid,
2339 rx_Read(tcall, (char *)&length,
2342 if (bytes == sizeof(afs_int32)) {
2343 length = ntohl(length);
2345 code = rx_Error(tcall);
2348 #endif /* AFS_64BIT_CLIENT */
2353 &(afs_stats_cmfullperf.rpc.
2354 fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
2355 osi_GetuTime(&xferStartTime);
2358 afs_CacheFetchProc(tcall, file,
2359 (afs_size_t) Position, tdc,
2361 &bytesXferred, length);
2363 osi_GetuTime(&xferStopTime);
2364 (xferP->numXfers)++;
2366 (xferP->numSuccesses)++;
2367 afs_stats_XferSumBytes
2368 [AFS_STATS_FS_XFERIDX_FETCHDATA] +=
2370 (xferP->sumBytes) +=
2371 (afs_stats_XferSumBytes
2372 [AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
2373 afs_stats_XferSumBytes
2374 [AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
2375 if (bytesXferred < xferP->minBytes)
2376 xferP->minBytes = bytesXferred;
2377 if (bytesXferred > xferP->maxBytes)
2378 xferP->maxBytes = bytesXferred;
2381 * Tally the size of the object. Note: we tally the actual size,
2382 * NOT the number of bytes that made it out over the wire.
2384 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
2385 (xferP->count[0])++;
2386 else if (bytesToXfer <=
2387 AFS_STATS_MAXBYTES_BUCKET1)
2388 (xferP->count[1])++;
2389 else if (bytesToXfer <=
2390 AFS_STATS_MAXBYTES_BUCKET2)
2391 (xferP->count[2])++;
2392 else if (bytesToXfer <=
2393 AFS_STATS_MAXBYTES_BUCKET3)
2394 (xferP->count[3])++;
2395 else if (bytesToXfer <=
2396 AFS_STATS_MAXBYTES_BUCKET4)
2397 (xferP->count[4])++;
2398 else if (bytesToXfer <=
2399 AFS_STATS_MAXBYTES_BUCKET5)
2400 (xferP->count[5])++;
2401 else if (bytesToXfer <=
2402 AFS_STATS_MAXBYTES_BUCKET6)
2403 (xferP->count[6])++;
2404 else if (bytesToXfer <=
2405 AFS_STATS_MAXBYTES_BUCKET7)
2406 (xferP->count[7])++;
2408 (xferP->count[8])++;
2410 afs_stats_GetDiff(elapsedTime, xferStartTime,
2412 afs_stats_AddTo((xferP->sumTime), elapsedTime);
2413 afs_stats_SquareAddTo((xferP->sqrTime),
2415 if (afs_stats_TimeLessThan
2416 (elapsedTime, (xferP->minTime))) {
2417 afs_stats_TimeAssign((xferP->minTime),
2420 if (afs_stats_TimeGreaterThan
2421 (elapsedTime, (xferP->maxTime))) {
2422 afs_stats_TimeAssign((xferP->maxTime),
2428 afs_CacheFetchProc(tcall, file, Position, tdc,
2430 #endif /* AFS_NOSTATS */
2435 EndRXAFS_FetchData(tcall, &tsmall->OutStatus,
2443 code1 = rx_EndCall(tcall, code);
2452 /* callback could have been broken (or expired) in a race here,
2453 * but we return the data anyway. It's as good as we knew about
2454 * when we started. */
2456 * validPos is updated by CacheFetchProc, and can only be
2457 * modifed under a dcache write lock, which we've blocked out
2459 size = tdc->validPos - Position; /* actual segment size */
2462 afs_CFileTruncate(file, size); /* prune it */
2464 if (!setLocks || slowPass) {
2465 ObtainWriteLock(&afs_xcbhash, 453);
2466 afs_DequeueCallback(avc);
2467 avc->states &= ~(CStatd | CUnique);
2468 avc->callback = NULL;
2469 ReleaseWriteLock(&afs_xcbhash);
2470 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2471 osi_dnlc_purgedp(avc);
2473 /* Something lost. Forget about performance, and go
2474 * back with a vcache write lock.
2476 afs_CFileTruncate(file, 0);
2477 afs_AdjustSize(tdc, 0);
2478 afs_CFileClose(file);
2479 osi_FreeLargeSpace(tsmall);
2481 ReleaseWriteLock(&tdc->lock);
2484 ReleaseReadLock(&avc->lock);
2486 goto RetryGetDCache;
2490 } while (afs_Analyze
2491 (tc, code, &avc->fid, areq,
2492 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2496 * avc->lock(R) if setLocks && !slowPass
2497 * avc->lock(W) if !setLocks || slowPass
2503 * In the case of replicated access, jot down info on the number of
2504 * attempts it took before we got through or gave up.
2507 if (numFetchLoops <= 1)
2508 (accP->refFirstReplicaOK)++;
2509 if (numFetchLoops > accP->maxReplicasPerRef)
2510 accP->maxReplicasPerRef = numFetchLoops;
2512 #endif /* AFS_NOSTATS */
2514 tdc->dflags &= ~DFFetching;
2515 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2516 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2517 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2518 tdc, ICL_TYPE_INT32, tdc->dflags);
2519 if (avc->execsOrWriters == 0)
2520 tdc->f.states &= ~DWriting;
2522 /* now, if code != 0, we have an error and should punt.
2523 * note that we have the vcache write lock, either because
2524 * !setLocks or slowPass.
2527 afs_CFileTruncate(file, 0);
2528 afs_AdjustSize(tdc, 0);
2529 afs_CFileClose(file);
2530 ZapDCE(tdc); /* sets DFEntryMod */
2531 if (vType(avc) == VDIR) {
2534 tdc->f.states &= ~(DRO|DBackup|DRW);
2535 afs_DCMoveBucket(tdc, 0, 0);
2536 ReleaseWriteLock(&tdc->lock);
2538 ObtainWriteLock(&afs_xcbhash, 454);
2539 afs_DequeueCallback(avc);
2540 avc->states &= ~(CStatd | CUnique);
2541 ReleaseWriteLock(&afs_xcbhash);
2542 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2543 osi_dnlc_purgedp(avc);
2546 * avc->lock(W); assert(!setLocks || slowPass)
2548 osi_Assert(!setLocks || slowPass);
2549 tdc->f.states &= ~(DRO|DBackup|DRW);
2550 afs_DCMoveBucket(tdc, 0, 0);
2555 /* otherwise we copy in the just-fetched info */
2556 afs_CFileClose(file);
2557 afs_AdjustSize(tdc, size); /* new size */
2559 * Copy appropriate fields into vcache. Status is
2560 * copied later where we selectively acquire the
2561 * vcache write lock.
2564 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2566 setVcacheStatus = 1;
2567 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2568 tsmall->OutStatus.DataVersion);
2569 tdc->dflags |= DFEntryMod;
2570 afs_indexFlags[tdc->index] |= IFEverUsed;
2571 ConvertWToSLock(&tdc->lock);
2572 } /*Data version numbers don't match */
2575 * Data version numbers match.
2577 afs_stats_cmperf.dcacheHits++;
2578 } /*Data version numbers match */
2580 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2584 * avc->lock(R) if setLocks && !slowPass
2585 * avc->lock(W) if !setLocks || slowPass
2586 * tdc->lock(S) if tdc
2590 * See if this was a reference to a file in the local cell.
2592 if (afs_IsPrimaryCellNum(avc->fid.Cell))
2593 afs_stats_cmperf.dlocalAccesses++;
2595 afs_stats_cmperf.dremoteAccesses++;
2597 /* Fix up LRU info */
2600 MObtainWriteLock(&afs_xdcache, 602);
2601 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2602 hadd32(afs_indexCounter, 1);
2603 MReleaseWriteLock(&afs_xdcache);
2605 /* return the data */
2606 if (vType(avc) == VDIR)
2609 *aoffset = AFS_CHUNKOFFSET(abyte);
2610 *alen = (tdc->f.chunkBytes - *aoffset);
2611 ReleaseSharedLock(&tdc->lock);
2616 * avc->lock(R) if setLocks && !slowPass
2617 * avc->lock(W) if !setLocks || slowPass
2620 /* Fix up the callback and status values in the vcache */
2622 if (setLocks && !slowPass) {
2625 * This is our dirty little secret to parallel fetches.
2626 * We don't write-lock the vcache while doing the fetch,
2627 * but potentially we'll need to update the vcache after
2628 * the fetch is done.
2630 * Drop the read lock and try to re-obtain the write
2631 * lock. If the vcache still has the same DV, it's
2632 * ok to go ahead and install the new data.
2634 afs_hyper_t currentDV, statusDV;
2636 hset(currentDV, avc->m.DataVersion);
2638 if (setNewCallback && avc->callback != newCallback)
2642 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2643 tsmall->OutStatus.DataVersion);
2645 if (setVcacheStatus && avc->m.Length != tsmall->OutStatus.Length)
2647 if (setVcacheStatus && !hsame(currentDV, statusDV))
2651 ReleaseReadLock(&avc->lock);
2653 if (doVcacheUpdate) {
2654 ObtainWriteLock(&avc->lock, 615);
2655 if (!hsame(avc->m.DataVersion, currentDV)) {
2656 /* We lose. Someone will beat us to it. */
2658 ReleaseWriteLock(&avc->lock);
2663 /* With slow pass, we've already done all the updates */
2665 ReleaseWriteLock(&avc->lock);
2668 /* Check if we need to perform any last-minute fixes with a write-lock */
2669 if (!setLocks || doVcacheUpdate) {
2671 avc->callback = newCallback;
2672 if (tsmall && setVcacheStatus)
2673 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2675 ReleaseWriteLock(&avc->lock);
2679 osi_FreeLargeSpace(tsmall);
2682 } /*afs_GetDCache */
2686 * afs_WriteThroughDSlots
2689 * Sweep through the dcache slots and write out any modified
2690 * in-memory data back on to our caching store.
2696 * The afs_xdcache is write-locked through this whole affair.
2699 afs_WriteThroughDSlots(void)
2701 register struct dcache *tdc;
2702 register afs_int32 i, touchedit = 0;
2704 struct afs_q DirtyQ, *tq;
2706 AFS_STATCNT(afs_WriteThroughDSlots);
2709 * Because of lock ordering, we can't grab dcache locks while
2710 * holding afs_xdcache. So we enter xdcache, get a reference
2711 * for every dcache entry, and exit xdcache.
2713 MObtainWriteLock(&afs_xdcache, 283);
2715 for (i = 0; i < afs_cacheFiles; i++) {
2716 tdc = afs_indexTable[i];
2718 /* Grab tlock in case the existing refcount isn't zero */
2719 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2720 ObtainWriteLock(&tdc->tlock, 623);
2722 ReleaseWriteLock(&tdc->tlock);
2724 QAdd(&DirtyQ, &tdc->dirty);
2727 MReleaseWriteLock(&afs_xdcache);
2730 * Now, for each dcache entry we found, check if it's dirty.
2731 * If so, get write-lock, get afs_xdcache, which protects
2732 * afs_cacheInodep, and flush it. Don't forget to put back
2736 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2738 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2740 if (tdc->dflags & DFEntryMod) {
2743 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2745 /* Now that we have the write lock, double-check */
2746 if (wrLock && (tdc->dflags & DFEntryMod)) {
2747 tdc->dflags &= ~DFEntryMod;
2748 MObtainWriteLock(&afs_xdcache, 620);
2749 afs_WriteDCache(tdc, 1);
2750 MReleaseWriteLock(&afs_xdcache);
2754 ReleaseWriteLock(&tdc->lock);
2760 MObtainWriteLock(&afs_xdcache, 617);
2761 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2762 /* Touch the file to make sure that the mtime on the file is kept
2763 * up-to-date to avoid losing cached files on cold starts because
2764 * their mtime seems old...
2766 struct afs_fheader theader;
2768 theader.magic = AFS_FHMAGIC;
2769 theader.firstCSize = AFS_FIRSTCSIZE;
2770 theader.otherCSize = AFS_OTHERCSIZE;
2771 theader.version = AFS_CI_VERSION;
2772 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2774 MReleaseWriteLock(&afs_xdcache);
2781 * Return a pointer to an freshly initialized dcache entry using
2782 * a memory-based cache. The tlock will be read-locked.
2785 * aslot : Dcache slot to look at.
2786 * tmpdc : Ptr to dcache entry.
2789 * Must be called with afs_xdcache write-locked.
2793 afs_MemGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2795 register struct dcache *tdc;
2798 AFS_STATCNT(afs_MemGetDSlot);
2799 if (CheckLock(&afs_xdcache) != -1)
2800 osi_Panic("getdslot nolock");
2801 if (aslot < 0 || aslot >= afs_cacheFiles)
2802 osi_Panic("getdslot slot");
2803 tdc = afs_indexTable[aslot];
2805 QRemove(&tdc->lruq); /* move to queue head */
2806 QAdd(&afs_DLRU, &tdc->lruq);
2807 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2808 ObtainWriteLock(&tdc->tlock, 624);
2810 ConvertWToRLock(&tdc->tlock);
2813 if (tmpdc == NULL) {
2814 if (!afs_freeDSList)
2815 afs_GetDownDSlot(4);
2816 if (!afs_freeDSList) {
2817 /* none free, making one is better than a panic */
2818 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2819 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2820 #ifdef KERNEL_HAVE_PIN
2821 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2824 tdc = afs_freeDSList;
2825 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2828 tdc->dflags = 0; /* up-to-date, not in free q */
2830 QAdd(&afs_DLRU, &tdc->lruq);
2831 if (tdc->lruq.prev == &tdc->lruq)
2832 osi_Panic("lruq 3");
2838 /* initialize entry */
2839 tdc->f.fid.Cell = 0;
2840 tdc->f.fid.Fid.Volume = 0;
2842 hones(tdc->f.versionNo);
2843 tdc->f.inode = aslot;
2844 tdc->dflags |= DFEntryMod;
2847 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2850 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2851 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2852 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2855 RWLOCK_INIT(&tdc->lock, "dcache lock");
2856 RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2857 RWLOCK_INIT(&tdc->mflock, "dcache flock");
2858 ObtainReadLock(&tdc->tlock);
2861 afs_indexTable[aslot] = tdc;
2864 } /*afs_MemGetDSlot */
2866 unsigned int last_error = 0, lasterrtime = 0;
2872 * Return a pointer to an freshly initialized dcache entry using
2873 * a UFS-based disk cache. The dcache tlock will be read-locked.
2876 * aslot : Dcache slot to look at.
2877 * tmpdc : Ptr to dcache entry.
2880 * afs_xdcache lock write-locked.
2883 afs_UFSGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2885 register afs_int32 code;
2886 register struct dcache *tdc;
2890 AFS_STATCNT(afs_UFSGetDSlot);
2891 if (CheckLock(&afs_xdcache) != -1)
2892 osi_Panic("getdslot nolock");
2893 if (aslot < 0 || aslot >= afs_cacheFiles)
2894 osi_Panic("getdslot slot");
2895 tdc = afs_indexTable[aslot];
2897 QRemove(&tdc->lruq); /* move to queue head */
2898 QAdd(&afs_DLRU, &tdc->lruq);
2899 /* Grab tlock in case refCount != 0 */
2900 ObtainWriteLock(&tdc->tlock, 625);
2902 ConvertWToRLock(&tdc->tlock);
2905 /* otherwise we should read it in from the cache file */
2907 * If we weren't passed an in-memory region to place the file info,
2908 * we have to allocate one.
2910 if (tmpdc == NULL) {
2911 if (!afs_freeDSList)
2912 afs_GetDownDSlot(4);
2913 if (!afs_freeDSList) {
2914 /* none free, making one is better than a panic */
2915 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2916 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2917 #ifdef KERNEL_HAVE_PIN
2918 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2921 tdc = afs_freeDSList;
2922 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2925 tdc->dflags = 0; /* up-to-date, not in free q */
2927 QAdd(&afs_DLRU, &tdc->lruq);
2928 if (tdc->lruq.prev == &tdc->lruq)
2929 osi_Panic("lruq 3");
2936 * Seek to the aslot'th entry and read it in.
2939 afs_osi_Read(afs_cacheInodep,
2940 sizeof(struct fcache) * aslot +
2941 sizeof(struct afs_fheader), (char *)(&tdc->f),
2942 sizeof(struct fcache));
2944 if (code != sizeof(struct fcache))
2946 if (!afs_CellNumValid(tdc->f.fid.Cell))
2950 tdc->f.fid.Cell = 0;
2951 tdc->f.fid.Fid.Volume = 0;
2953 hones(tdc->f.versionNo);
2954 tdc->dflags |= DFEntryMod;
2955 #if defined(KERNEL_HAVE_UERROR)
2956 last_error = getuerror();
2958 lasterrtime = osi_Time();
2959 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2960 tdc->f.states &= ~(DRO|DBackup|DRW);
2961 afs_DCMoveBucket(tdc, 0, 0);
2964 if (tdc->f.states & DRO) {
2965 afs_DCMoveBucket(tdc, 0, 2);
2966 } else if (tdc->f.states & DBackup) {
2967 afs_DCMoveBucket(tdc, 0, 1);
2969 afs_DCMoveBucket(tdc, 0, 1);
2975 if (tdc->f.chunk >= 0)
2976 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
2981 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2982 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2983 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2986 RWLOCK_INIT(&tdc->lock, "dcache lock");
2987 RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2988 RWLOCK_INIT(&tdc->mflock, "dcache flock");
2989 ObtainReadLock(&tdc->tlock);
2992 * If we didn't read into a temporary dcache region, update the
2993 * slot pointer table.
2996 afs_indexTable[aslot] = tdc;
2999 } /*afs_UFSGetDSlot */
3007 * write a particular dcache entry back to its home in the
3011 * adc : Pointer to the dcache entry to write.
3012 * atime : If true, set the modtime on the file to the current time.
3015 * Must be called with the afs_xdcache lock at least read-locked,
3016 * and dcache entry at least read-locked.
3017 * The reference count is not changed.
3021 afs_WriteDCache(register struct dcache *adc, int atime)
3023 register afs_int32 code;
3025 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3027 AFS_STATCNT(afs_WriteDCache);
3029 adc->f.modTime = osi_Time();
3031 * Seek to the right dcache slot and write the in-memory image out to disk.
3033 afs_cellname_write();
3035 afs_osi_Write(afs_cacheInodep,
3036 sizeof(struct fcache) * adc->index +
3037 sizeof(struct afs_fheader), (char *)(&adc->f),
3038 sizeof(struct fcache));
3039 if (code != sizeof(struct fcache))
3050 * Wake up users of a particular file waiting for stores to take
3054 * avc : Ptr to related vcache entry.
3057 * Nothing interesting.
3061 afs_wakeup(register struct vcache *avc)
3064 register struct brequest *tb;
3066 AFS_STATCNT(afs_wakeup);
3067 for (i = 0; i < NBRS; i++, tb++) {
3068 /* if request is valid and for this file, we've found it */
3069 if (tb->refCount > 0 && avc == tb->vc) {
3072 * If CSafeStore is on, then we don't awaken the guy
3073 * waiting for the store until the whole store has finished.
3074 * Otherwise, we do it now. Note that if CSafeStore is on,
3075 * the BStore routine actually wakes up the user, instead
3077 * I think this is redundant now because this sort of thing
3078 * is already being handled by the higher-level code.
3080 if ((avc->states & CSafeStore) == 0) {
3082 tb->flags |= BUVALID;
3083 if (tb->flags & BUWAIT) {
3084 tb->flags &= ~BUWAIT;
3099 * Given a file name and inode, set up that file to be an
3100 * active member in the AFS cache. This also involves checking
3101 * the usability of its data.
3104 * afile : Name of the cache file to initialize.
3105 * ainode : Inode of the file.
3108 * This function is called only during initialization.
3112 afs_InitCacheFile(char *afile, ino_t ainode)
3114 register afs_int32 code;
3115 #if defined(AFS_LINUX22_ENV)
3116 struct dentry *filevp;
3118 struct vnode *filevp;
3122 struct osi_file *tfile;
3123 struct osi_stat tstat;
3124 register struct dcache *tdc;
3126 AFS_STATCNT(afs_InitCacheFile);
3127 index = afs_stats_cmperf.cacheNumEntries;
3128 if (index >= afs_cacheFiles)
3131 MObtainWriteLock(&afs_xdcache, 282);
3132 tdc = afs_GetDSlot(index, NULL);
3133 ReleaseReadLock(&tdc->tlock);
3134 MReleaseWriteLock(&afs_xdcache);
3136 ObtainWriteLock(&tdc->lock, 621);
3137 MObtainWriteLock(&afs_xdcache, 622);
3139 code = gop_lookupname(afile, AFS_UIOSYS, 0, &filevp);
3141 ReleaseWriteLock(&afs_xdcache);
3142 ReleaseWriteLock(&tdc->lock);
3147 * We have a VN_HOLD on filevp. Get the useful info out and
3148 * return. We make use of the fact that the cache is in the
3149 * UFS file system, and just record the inode number.
3151 #ifdef AFS_LINUX22_ENV
3152 tdc->f.inode = VTOI(filevp->d_inode)->i_number;
3155 tdc->f.inode = afs_vnodeToInumber(filevp);
3157 #endif /* AFS_LINUX22_ENV */
3159 tdc->f.inode = ainode;
3162 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3164 tfile = osi_UFSOpen(tdc->f.inode);
3165 code = afs_osi_Stat(tfile, &tstat);
3167 osi_Panic("initcachefile stat");
3170 * If file size doesn't match the cache info file, it's probably bad.
3172 if (tdc->f.chunkBytes != tstat.size)
3174 tdc->f.chunkBytes = 0;
3177 * If file changed within T (120?) seconds of cache info file, it's
3178 * probably bad. In addition, if slot changed within last T seconds,
3179 * the cache info file may be incorrectly identified, and so slot
3182 if (cacheInfoModTime < tstat.mtime + 120)
3184 if (cacheInfoModTime < tdc->f.modTime + 120)
3186 /* In case write through is behind, make sure cache items entry is
3187 * at least as new as the chunk.
3189 if (tdc->f.modTime < tstat.mtime)
3192 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3193 if (tstat.size != 0)
3194 osi_UFSTruncate(tfile, 0);
3195 tdc->f.states &= ~(DRO|DBackup|DRW);
3196 afs_DCMoveBucket(tdc, 0, 0);
3197 /* put entry in free cache slot list */
3198 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3199 afs_freeDCList = index;
3201 afs_indexFlags[index] |= IFFree;
3202 afs_indexUnique[index] = 0;
3205 * We must put this entry in the appropriate hash tables.
3206 * Note that i is still set from the above DCHash call
3208 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3209 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3210 afs_dchashTbl[code] = tdc->index;
3211 code = DVHash(&tdc->f.fid);
3212 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3213 afs_dvhashTbl[code] = tdc->index;
3214 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3216 /* has nontrivial amt of data */
3217 afs_indexFlags[index] |= IFEverUsed;
3218 afs_stats_cmperf.cacheFilesReused++;
3220 * Initialize index times to file's mod times; init indexCounter
3223 hset32(afs_indexTimes[index], tstat.atime);
3224 if (hgetlo(afs_indexCounter) < tstat.atime) {
3225 hset32(afs_indexCounter, tstat.atime);
3227 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3228 } /*File is not bad */
3230 osi_UFSClose(tfile);
3231 tdc->f.states &= ~DWriting;
3232 tdc->dflags &= ~DFEntryMod;
3233 /* don't set f.modTime; we're just cleaning up */
3234 afs_WriteDCache(tdc, 0);
3235 ReleaseWriteLock(&afs_xdcache);
3236 ReleaseWriteLock(&tdc->lock);
3238 afs_stats_cmperf.cacheNumEntries++;
3243 /*Max # of struct dcache's resident at any time*/
3245 * If 'dchint' is enabled then in-memory dcache min is increased because of
3254 * Initialize dcache related variables.
3257 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3259 register struct dcache *tdp;
3263 afs_freeDCList = NULLIDX;
3264 afs_discardDCList = NULLIDX;
3265 afs_freeDCCount = 0;
3266 afs_freeDSList = NULL;
3267 hzero(afs_indexCounter);
3269 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3275 if (achunk < 0 || achunk > 30)
3276 achunk = 13; /* Use default */
3277 AFS_SETCHUNKSIZE(achunk);
3283 if (aflags & AFSCALL_INIT_MEMCACHE) {
3285 * Use a memory cache instead of a disk cache
3287 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3288 afs_cacheType = &afs_MemCacheOps;
3289 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3290 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3291 /* ablocks is reported in 1K blocks */
3292 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3294 printf("afsd: memory cache too large for available memory.\n");
3295 printf("afsd: AFS files cannot be accessed.\n\n");
3297 afiles = ablocks = 0;
3299 printf("Memory cache: Allocating %d dcache entries...",
3302 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3303 afs_cacheType = &afs_UfsCacheOps;
3306 if (aDentries > 512)
3307 afs_dhashsize = 2048;
3308 /* initialize hash tables */
3310 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3312 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3313 for (i = 0; i < afs_dhashsize; i++) {
3314 afs_dvhashTbl[i] = NULLIDX;
3315 afs_dchashTbl[i] = NULLIDX;
3317 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3318 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3319 for (i = 0; i < afiles; i++) {
3320 afs_dvnextTbl[i] = NULLIDX;
3321 afs_dcnextTbl[i] = NULLIDX;
3324 /* Allocate and zero the pointer array to the dcache entries */
3325 afs_indexTable = (struct dcache **)
3326 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3327 memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3329 (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3330 memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3332 (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3333 memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3334 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3335 memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
3337 /* Allocate and thread the struct dcache entries themselves */
3338 tdp = afs_Initial_freeDSList =
3339 (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3340 memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
3341 #ifdef KERNEL_HAVE_PIN
3342 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3343 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3344 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3345 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3346 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3347 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3348 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3349 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3350 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3353 afs_freeDSList = &tdp[0];
3354 for (i = 0; i < aDentries - 1; i++) {
3355 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3356 RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3357 RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3358 RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3360 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3361 RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3362 RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3363 RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3365 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3366 afs_cacheBlocks = ablocks;
3367 afs_ComputeCacheParms(); /* compute parms based on cache size */
3369 afs_dcentries = aDentries;
3371 afs_stats_cmperf.cacheBucket0_Discarded =
3372 afs_stats_cmperf.cacheBucket1_Discarded =
3373 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3383 shutdown_dcache(void)
3387 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3388 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3389 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3390 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3391 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3392 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3393 afs_osi_Free(afs_Initial_freeDSList,
3394 afs_dcentries * sizeof(struct dcache));
3395 #ifdef KERNEL_HAVE_PIN
3396 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3397 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3398 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3399 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3400 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3401 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3402 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3406 for (i = 0; i < afs_dhashsize; i++) {
3407 afs_dvhashTbl[i] = NULLIDX;
3408 afs_dchashTbl[i] = NULLIDX;
3411 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3412 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3414 afs_blocksUsed = afs_dcentries = 0;
3415 afs_stats_cmperf.cacheBucket0_Discarded =
3416 afs_stats_cmperf.cacheBucket1_Discarded =
3417 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3418 hzero(afs_indexCounter);
3420 afs_freeDCCount = 0;
3421 afs_freeDCList = NULLIDX;
3422 afs_discardDCList = NULLIDX;
3423 afs_freeDSList = afs_Initial_freeDSList = 0;
3425 LOCK_INIT(&afs_xdcache, "afs_xdcache");