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"
17 #include "afs/sysincludes.h" /*Standard vendor system headers */
18 #include "afsincludes.h" /*AFS-based standard headers */
19 #include "afs/afs_stats.h" /* statistics */
20 #include "afs/afs_cbqueue.h"
21 #include "afs/afs_osidnlc.h"
23 /* Forward declarations. */
24 static void afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint);
25 static void afs_FreeDiscardedDCache(void);
26 static void afs_DiscardDCache(struct dcache *);
27 static void afs_FreeDCache(struct dcache *);
29 static afs_int32 afs_DCGetBucket(struct vcache *);
30 static void afs_DCAdjustSize(struct dcache *, afs_int32, afs_int32);
31 static void afs_DCMoveBucket(struct dcache *, afs_int32, afs_int32);
32 static void afs_DCSizeInit(void);
33 static afs_int32 afs_DCWhichBucket(afs_int32, afs_int32);
36 * --------------------- Exported definitions ---------------------
39 afs_int32 afs_blocksUsed_0; /*!< 1K blocks in cache - in theory is zero */
40 afs_int32 afs_blocksUsed_1; /*!< 1K blocks in cache */
41 afs_int32 afs_blocksUsed_2; /*!< 1K blocks in cache */
42 afs_int32 afs_pct1 = -1;
43 afs_int32 afs_pct2 = -1;
44 afs_uint32 afs_tpct1 = 0;
45 afs_uint32 afs_tpct2 = 0;
46 afs_uint32 splitdcache = 0;
48 afs_lock_t afs_xdcache; /*!< Lock: alloc new disk cache entries */
49 afs_int32 afs_freeDCList; /*!< Free list for disk cache entries */
50 afs_int32 afs_freeDCCount; /*!< Count of elts in freeDCList */
51 afs_int32 afs_discardDCList; /*!< Discarded disk cache entries */
52 afs_int32 afs_discardDCCount; /*!< Count of elts in discardDCList */
53 struct dcache *afs_freeDSList; /*!< Free list for disk slots */
54 struct dcache *afs_Initial_freeDSList; /*!< Initial list for above */
55 afs_dcache_id_t cacheInode; /*!< Inode for CacheItems file */
56 struct osi_file *afs_cacheInodep = 0; /*!< file for CacheItems inode */
57 struct afs_q afs_DLRU; /*!< dcache LRU */
58 afs_int32 afs_dhashsize = 1024;
59 afs_int32 *afs_dvhashTbl; /*!< Data cache hash table: hashed by FID + chunk number. */
60 afs_int32 *afs_dchashTbl; /*!< Data cache hash table: hashed by FID. */
61 afs_int32 *afs_dvnextTbl; /*!< Dcache hash table links */
62 afs_int32 *afs_dcnextTbl; /*!< Dcache hash table links */
63 struct dcache **afs_indexTable; /*!< Pointers to dcache entries */
64 afs_hyper_t *afs_indexTimes; /*!< Dcache entry Access times */
65 afs_int32 *afs_indexUnique; /*!< dcache entry Fid.Unique */
66 unsigned char *afs_indexFlags; /*!< (only one) Is there data there? */
67 afs_hyper_t afs_indexCounter; /*!< Fake time for marking index
69 afs_int32 afs_cacheFiles = 0; /*!< Size of afs_indexTable */
70 afs_int32 afs_cacheBlocks; /*!< 1K blocks in cache */
71 afs_int32 afs_cacheStats; /*!< Stat entries in cache */
72 afs_int32 afs_blocksUsed; /*!< Number of blocks in use */
73 afs_int32 afs_blocksDiscarded; /*!<Blocks freed but not truncated */
74 afs_int32 afs_fsfragsize = 1023; /*!< Underlying Filesystem minimum unit
75 *of disk allocation usually 1K
76 *this value is (truefrag -1 ) to
77 *save a bunch of subtracts... */
78 #ifdef AFS_64BIT_CLIENT
79 #ifdef AFS_VM_RDWR_ENV
80 afs_size_t afs_vmMappingEnd; /* !< For large files (>= 2GB) the VM
81 * mapping an 32bit addressing machines
82 * can only be used below the 2 GB
83 * line. From this point upwards we
84 * must do direct I/O into the cache
85 * files. The value should be on a
87 #endif /* AFS_VM_RDWR_ENV */
88 #endif /* AFS_64BIT_CLIENT */
90 /* The following is used to ensure that new dcache's aren't obtained when
91 * the cache is nearly full.
93 int afs_WaitForCacheDrain = 0;
94 int afs_TruncateDaemonRunning = 0;
95 int afs_CacheTooFull = 0;
97 afs_int32 afs_dcentries; /*!< In-memory dcache entries */
100 int dcacheDisabled = 0;
102 struct afs_cacheOps afs_UfsCacheOps = {
115 struct afs_cacheOps afs_MemCacheOps = {
117 afs_MemCacheTruncate,
128 int cacheDiskType; /*Type of backing disk for cache */
129 struct afs_cacheOps *afs_cacheType;
132 * Where is this vcache's entry associated dcache located/
133 * \param avc The vcache entry.
134 * \return Bucket index:
139 afs_DCGetBucket(struct vcache *avc)
144 /* This should be replaced with some sort of user configurable function */
145 if (avc->f.states & CRO) {
147 } else if (avc->f.states & CBackup) {
157 * Readjust a dcache's size.
159 * \param adc The dcache to be adjusted.
160 * \param oldSize Old size for the dcache.
161 * \param newSize The new size to be adjusted to.
165 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
167 afs_int32 adjustSize = newSize - oldSize;
175 afs_blocksUsed_0 += adjustSize;
176 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
179 afs_blocksUsed_1 += adjustSize;
180 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
183 afs_blocksUsed_2 += adjustSize;
184 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
192 * Move a dcache from one bucket to another.
194 * \param adc Operate on this dcache.
195 * \param size Size in bucket (?).
196 * \param newBucket Destination bucket.
200 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
205 /* Substract size from old bucket. */
209 afs_blocksUsed_0 -= size;
212 afs_blocksUsed_1 -= size;
215 afs_blocksUsed_2 -= size;
219 /* Set new bucket and increase destination bucket size. */
220 adc->bucket = newBucket;
225 afs_blocksUsed_0 += size;
228 afs_blocksUsed_1 += size;
231 afs_blocksUsed_2 += size;
239 * Init split caches size.
244 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
253 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
258 afs_pct1 = afs_blocksUsed_1 / (afs_cacheBlocks / 100);
259 afs_pct2 = afs_blocksUsed_2 / (afs_cacheBlocks / 100);
261 /* Short cut: if we don't know about it, try to kill it */
262 if (phase < 2 && afs_blocksUsed_0)
265 if (afs_pct1 > afs_tpct1)
267 if (afs_pct2 > afs_tpct2)
269 return 0; /* unlikely */
274 * Warn about failing to store a file.
276 * \param acode Associated error code.
277 * \param avolume Volume involved.
278 * \param aflags How to handle the output:
279 * aflags & 1: Print out on console
280 * aflags & 2: Print out on controlling tty
282 * \note Environment: Call this from close call when vnodeops is RCS unlocked.
286 afs_StoreWarn(register afs_int32 acode, afs_int32 avolume,
287 register afs_int32 aflags)
289 static char problem_fmt[] =
290 "afs: failed to store file in volume %d (%s)\n";
291 static char problem_fmt_w_error[] =
292 "afs: failed to store file in volume %d (error %d)\n";
293 static char netproblems[] = "network problems";
294 static char partfull[] = "partition full";
295 static char overquota[] = "over quota";
297 AFS_STATCNT(afs_StoreWarn);
303 afs_warn(problem_fmt, avolume, netproblems);
305 afs_warnuser(problem_fmt, avolume, netproblems);
306 } else if (acode == ENOSPC) {
311 afs_warn(problem_fmt, avolume, partfull);
313 afs_warnuser(problem_fmt, avolume, partfull);
316 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
317 * Instead ENOSPC will be sent...
319 if (acode == EDQUOT) {
324 afs_warn(problem_fmt, avolume, overquota);
326 afs_warnuser(problem_fmt, avolume, overquota);
334 afs_warn(problem_fmt_w_error, avolume, acode);
336 afs_warnuser(problem_fmt_w_error, avolume, acode);
341 * Try waking up truncation daemon, if it's worth it.
344 afs_MaybeWakeupTruncateDaemon(void)
346 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
347 afs_CacheTooFull = 1;
348 if (!afs_TruncateDaemonRunning)
349 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
350 } else if (!afs_TruncateDaemonRunning
351 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
352 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
359 * Keep statistics on run time for afs_CacheTruncateDaemon. This is a
360 * struct so we need only export one symbol for AIX.
362 static struct CTD_stats {
363 osi_timeval_t CTD_beforeSleep;
364 osi_timeval_t CTD_afterSleep;
365 osi_timeval_t CTD_sleepTime;
366 osi_timeval_t CTD_runTime;
370 u_int afs_min_cache = 0;
373 * Keeps the cache clean and free by truncating uneeded files, when used.
378 afs_CacheTruncateDaemon(void)
380 osi_timeval_t CTD_tmpTime;
384 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
386 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
388 osi_GetuTime(&CTD_stats.CTD_afterSleep);
389 afs_TruncateDaemonRunning = 1;
391 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
392 MObtainWriteLock(&afs_xdcache, 266);
393 if (afs_CacheTooFull) {
394 int space_needed, slots_needed;
395 /* if we get woken up, we should try to clean something out */
396 for (counter = 0; counter < 10; counter++) {
398 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
400 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
401 afs_GetDownD(slots_needed, &space_needed, 0);
402 if ((space_needed <= 0) && (slots_needed <= 0)) {
405 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
408 if (!afs_CacheIsTooFull())
409 afs_CacheTooFull = 0;
410 } /* end of cache cleanup */
411 MReleaseWriteLock(&afs_xdcache);
414 * This is a defensive check to try to avoid starving threads
415 * that may need the global lock so thay can help free some
416 * cache space. If this thread won't be sleeping or truncating
417 * any cache files then give up the global lock so other
418 * threads get a chance to run.
420 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
421 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
422 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
426 * This is where we free the discarded cache elements.
428 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
429 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
430 afs_FreeDiscardedDCache();
433 /* See if we need to continue to run. Someone may have
434 * signalled us while we were executing.
436 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
437 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
438 /* Collect statistics on truncate daemon. */
439 CTD_stats.CTD_nSleeps++;
440 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
441 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
442 CTD_stats.CTD_beforeSleep);
443 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
445 afs_TruncateDaemonRunning = 0;
446 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
447 afs_TruncateDaemonRunning = 1;
449 osi_GetuTime(&CTD_stats.CTD_afterSleep);
450 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
451 CTD_stats.CTD_afterSleep);
452 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
454 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
456 afs_termState = AFSOP_STOP_AFSDB;
458 afs_termState = AFSOP_STOP_RXEVENT;
460 afs_osi_Wakeup(&afs_termState);
468 * Make adjustment for the new size in the disk cache entry
470 * \note Major Assumptions Here:
471 * Assumes that frag size is an integral power of two, less one,
472 * and that this is a two's complement machine. I don't
473 * know of any filesystems which violate this assumption...
475 * \param adc Ptr to dcache entry.
476 * \param anewsize New size desired.
481 afs_AdjustSize(register struct dcache *adc, register afs_int32 newSize)
483 register afs_int32 oldSize;
485 AFS_STATCNT(afs_AdjustSize);
487 adc->dflags |= DFEntryMod;
488 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
489 adc->f.chunkBytes = newSize;
492 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
493 afs_DCAdjustSize(adc, oldSize, newSize);
494 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
496 /* We're growing the file, wakeup the daemon */
497 afs_MaybeWakeupTruncateDaemon();
499 afs_blocksUsed += (newSize - oldSize);
500 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
505 * This routine is responsible for moving at least one entry (but up
506 * to some number of them) from the LRU queue to the free queue.
508 * \param anumber Number of entries that should ideally be moved.
509 * \param aneedSpace How much space we need (1K blocks);
512 * The anumber parameter is just a hint; at least one entry MUST be
513 * moved, or we'll panic. We must be called with afs_xdcache
514 * write-locked. We should try to satisfy both anumber and aneedspace,
515 * whichever is more demanding - need to do several things:
516 * 1. only grab up to anumber victims if aneedSpace <= 0, not
517 * the whole set of MAXATONCE.
518 * 2. dynamically choose MAXATONCE to reflect severity of
519 * demand: something like (*aneedSpace >> (logChunk - 9))
521 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
522 * indicates that the cache is not properly configured/tuned or
523 * something. We should be able to automatically correct that problem.
526 #define MAXATONCE 16 /* max we can obtain at once */
528 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
532 struct VenusFid *afid;
536 register struct vcache *tvc;
537 afs_uint32 victims[MAXATONCE];
538 struct dcache *victimDCs[MAXATONCE];
539 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
540 afs_uint32 victimPtr; /* next free item in victim arrays */
541 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
542 afs_uint32 maxVictimPtr; /* where it is */
545 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
549 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
550 vfslocked = VFS_LOCK_GIANT(afs_globalVFS);
553 AFS_STATCNT(afs_GetDownD);
555 if (CheckLock(&afs_xdcache) != -1)
556 osi_Panic("getdownd nolock");
557 /* decrement anumber first for all dudes in free list */
558 /* SHOULD always decrement anumber first, even if aneedSpace >0,
559 * because we should try to free space even if anumber <=0 */
560 if (!aneedSpace || *aneedSpace <= 0) {
561 anumber -= afs_freeDCCount;
563 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
564 VFS_UNLOCK_GIANT(vfslocked);
566 return; /* enough already free */
570 /* bounds check parameter */
571 if (anumber > MAXATONCE)
572 anumber = MAXATONCE; /* all we can do */
574 /* rewrite so phases include a better eligiblity for gc test*/
576 * The phase variable manages reclaims. Set to 0, the first pass,
577 * we don't reclaim active entries, or other than target bucket.
578 * Set to 1, we reclaim even active ones in target bucket.
579 * Set to 2, we reclaim any inactive one.
580 * Set to 3, we reclaim even active ones.
588 for (i = 0; i < afs_cacheFiles; i++)
589 /* turn off all flags */
590 afs_indexFlags[i] &= ~IFFlag;
592 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
593 /* find oldest entries for reclamation */
594 maxVictimPtr = victimPtr = 0;
595 hzero(maxVictimTime);
596 curbucket = afs_DCWhichBucket(phase, buckethint);
597 /* select victims from access time array */
598 for (i = 0; i < afs_cacheFiles; i++) {
599 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
600 /* skip if dirty or already free */
603 tdc = afs_indexTable[i];
604 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
606 /* Wrong bucket; can't use it! */
609 if (tdc && (tdc->refCount != 0)) {
610 /* Referenced; can't use it! */
613 hset(vtime, afs_indexTimes[i]);
615 /* if we've already looked at this one, skip it */
616 if (afs_indexFlags[i] & IFFlag)
619 if (victimPtr < MAXATONCE) {
620 /* if there's at least one free victim slot left */
621 victims[victimPtr] = i;
622 hset(victimTimes[victimPtr], vtime);
623 if (hcmp(vtime, maxVictimTime) > 0) {
624 hset(maxVictimTime, vtime);
625 maxVictimPtr = victimPtr;
628 } else if (hcmp(vtime, maxVictimTime) < 0) {
630 * We're older than youngest victim, so we replace at
633 /* find youngest (largest LRU) victim */
636 osi_Panic("getdownd local");
638 hset(victimTimes[j], vtime);
639 /* recompute maxVictimTime */
640 hset(maxVictimTime, vtime);
641 for (j = 0; j < victimPtr; j++)
642 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
643 hset(maxVictimTime, victimTimes[j]);
649 /* now really reclaim the victims */
650 j = 0; /* flag to track if we actually got any of the victims */
651 /* first, hold all the victims, since we're going to release the lock
652 * during the truncate operation.
654 for (i = 0; i < victimPtr; i++) {
655 tdc = afs_GetDSlot(victims[i], 0);
656 /* We got tdc->tlock(R) here */
657 if (tdc->refCount == 1)
661 ReleaseReadLock(&tdc->tlock);
665 for (i = 0; i < victimPtr; i++) {
666 /* q is first elt in dcache entry */
668 /* now, since we're dropping the afs_xdcache lock below, we
669 * have to verify, before proceeding, that there are no other
670 * references to this dcache entry, even now. Note that we
671 * compare with 1, since we bumped it above when we called
672 * afs_GetDSlot to preserve the entry's identity.
674 if (tdc && tdc->refCount == 1) {
675 unsigned char chunkFlags;
676 afs_size_t tchunkoffset = 0;
678 /* xdcache is lower than the xvcache lock */
679 MReleaseWriteLock(&afs_xdcache);
680 MObtainReadLock(&afs_xvcache);
681 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
682 MReleaseReadLock(&afs_xvcache);
683 MObtainWriteLock(&afs_xdcache, 527);
685 if (tdc->refCount > 1)
688 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
689 chunkFlags = afs_indexFlags[tdc->index];
690 if (((phase & 1) == 0) && osi_Active(tvc))
692 if (((phase & 1) == 1) && osi_Active(tvc)
693 && (tvc->f.states & CDCLock)
694 && (chunkFlags & IFAnyPages))
696 if (chunkFlags & IFDataMod)
698 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
699 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
700 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
701 ICL_HANDLE_OFFSET(tchunkoffset));
703 #if defined(AFS_SUN5_ENV)
705 * Now we try to invalidate pages. We do this only for
706 * Solaris. For other platforms, it's OK to recycle a
707 * dcache entry out from under a page, because the strategy
708 * function can call afs_GetDCache().
710 if (!skip && (chunkFlags & IFAnyPages)) {
713 MReleaseWriteLock(&afs_xdcache);
714 MObtainWriteLock(&tvc->vlock, 543);
715 if (tvc->multiPage) {
719 /* block locking pages */
720 tvc->vstates |= VPageCleaning;
721 /* block getting new pages */
723 MReleaseWriteLock(&tvc->vlock);
724 /* One last recheck */
725 MObtainWriteLock(&afs_xdcache, 333);
726 chunkFlags = afs_indexFlags[tdc->index];
727 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
728 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
729 && (chunkFlags & IFAnyPages))) {
731 MReleaseWriteLock(&afs_xdcache);
734 MReleaseWriteLock(&afs_xdcache);
736 code = osi_VM_GetDownD(tvc, tdc);
738 MObtainWriteLock(&afs_xdcache, 269);
739 /* we actually removed all pages, clean and dirty */
741 afs_indexFlags[tdc->index] &=
742 ~(IFDirtyPages | IFAnyPages);
745 MReleaseWriteLock(&afs_xdcache);
747 MObtainWriteLock(&tvc->vlock, 544);
748 if (--tvc->activeV == 0
749 && (tvc->vstates & VRevokeWait)) {
750 tvc->vstates &= ~VRevokeWait;
751 afs_osi_Wakeup((char *)&tvc->vstates);
754 if (tvc->vstates & VPageCleaning) {
755 tvc->vstates &= ~VPageCleaning;
756 afs_osi_Wakeup((char *)&tvc->vstates);
759 MReleaseWriteLock(&tvc->vlock);
761 #endif /* AFS_SUN5_ENV */
763 MReleaseWriteLock(&afs_xdcache);
766 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
767 MObtainWriteLock(&afs_xdcache, 528);
768 if (afs_indexFlags[tdc->index] &
769 (IFDataMod | IFDirtyPages | IFAnyPages))
771 if (tdc->refCount > 1)
774 #if defined(AFS_SUN5_ENV)
776 /* no vnode, so IFDirtyPages is spurious (we don't
777 * sweep dcaches on vnode recycling, so we can have
778 * DIRTYPAGES set even when all pages are gone). Just
780 * Hold vcache lock to prevent vnode from being
781 * created while we're clearing IFDirtyPages.
783 afs_indexFlags[tdc->index] &=
784 ~(IFDirtyPages | IFAnyPages);
788 /* skip this guy and mark him as recently used */
789 afs_indexFlags[tdc->index] |= IFFlag;
790 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
791 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
792 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
793 ICL_HANDLE_OFFSET(tchunkoffset));
795 /* flush this dude from the data cache and reclaim;
796 * first, make sure no one will care that we damage
797 * it, by removing it from all hash tables. Then,
798 * melt it down for parts. Note that any concurrent
799 * (new possibility!) calls to GetDownD won't touch
800 * this guy because his reference count is > 0. */
801 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
802 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
803 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
804 ICL_HANDLE_OFFSET(tchunkoffset));
805 AFS_STATCNT(afs_gget);
806 afs_HashOutDCache(tdc, 1);
807 if (tdc->f.chunkBytes != 0) {
811 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
816 afs_DiscardDCache(tdc);
821 j = 1; /* we reclaimed at least one victim */
825 } /* end of for victims loop */
828 /* Phase is 0 and no one was found, so try phase 1 (ignore
829 * osi_Active flag) */
832 for (i = 0; i < afs_cacheFiles; i++)
833 /* turn off all flags */
834 afs_indexFlags[i] &= ~IFFlag;
837 /* found no one in phases 0-5, we're hosed */
841 } /* big while loop */
843 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
844 VFS_UNLOCK_GIANT(vfslocked);
853 * Remove adc from any hash tables that would allow it to be located
854 * again by afs_FindDCache or afs_GetDCache.
856 * \param adc Pointer to dcache entry to remove from hash tables.
858 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
862 afs_HashOutDCache(struct dcache *adc, int zap)
866 AFS_STATCNT(afs_glink);
868 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
870 /* if this guy is in the hash table, pull him out */
871 if (adc->f.fid.Fid.Volume != 0) {
872 /* remove entry from first hash chains */
873 i = DCHash(&adc->f.fid, adc->f.chunk);
874 us = afs_dchashTbl[i];
875 if (us == adc->index) {
876 /* first dude in the list */
877 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
879 /* somewhere on the chain */
880 while (us != NULLIDX) {
881 if (afs_dcnextTbl[us] == adc->index) {
882 /* found item pointing at the one to delete */
883 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
886 us = afs_dcnextTbl[us];
889 osi_Panic("dcache hc");
891 /* remove entry from *other* hash chain */
892 i = DVHash(&adc->f.fid);
893 us = afs_dvhashTbl[i];
894 if (us == adc->index) {
895 /* first dude in the list */
896 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
898 /* somewhere on the chain */
899 while (us != NULLIDX) {
900 if (afs_dvnextTbl[us] == adc->index) {
901 /* found item pointing at the one to delete */
902 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
905 us = afs_dvnextTbl[us];
908 osi_Panic("dcache hv");
913 /* prevent entry from being found on a reboot (it is already out of
914 * the hash table, but after a crash, we just look at fid fields of
915 * stable (old) entries).
917 adc->f.fid.Fid.Volume = 0; /* invalid */
919 /* mark entry as modified */
920 adc->dflags |= DFEntryMod;
925 } /*afs_HashOutDCache */
928 * Flush the given dcache entry, pulling it from hash chains
929 * and truncating the associated cache file.
931 * \param adc Ptr to dcache entry to flush.
934 * This routine must be called with the afs_xdcache lock held
938 afs_FlushDCache(register struct dcache *adc)
940 AFS_STATCNT(afs_FlushDCache);
942 * Bump the number of cache files flushed.
944 afs_stats_cmperf.cacheFlushes++;
946 /* remove from all hash tables */
947 afs_HashOutDCache(adc, 1);
949 /* Free its space; special case null operation, since truncate operation
950 * in UFS is slow even in this case, and this allows us to pre-truncate
951 * these files at more convenient times with fewer locks set
952 * (see afs_GetDownD).
954 if (adc->f.chunkBytes != 0) {
955 afs_DiscardDCache(adc);
956 afs_MaybeWakeupTruncateDaemon();
961 if (afs_WaitForCacheDrain) {
962 if (afs_blocksUsed <=
963 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
964 afs_WaitForCacheDrain = 0;
965 afs_osi_Wakeup(&afs_WaitForCacheDrain);
968 } /*afs_FlushDCache */
972 * Put a dcache entry on the free dcache entry list.
974 * \param adc dcache entry to free.
976 * \note Environment: called with afs_xdcache lock write-locked.
979 afs_FreeDCache(register struct dcache *adc)
981 /* Thread on free list, update free list count and mark entry as
982 * freed in its indexFlags element. Also, ensure DCache entry gets
983 * written out (set DFEntryMod).
986 afs_dvnextTbl[adc->index] = afs_freeDCList;
987 afs_freeDCList = adc->index;
989 afs_indexFlags[adc->index] |= IFFree;
990 adc->dflags |= DFEntryMod;
992 if (afs_WaitForCacheDrain) {
993 if ((afs_blocksUsed - afs_blocksDiscarded) <=
994 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
995 afs_WaitForCacheDrain = 0;
996 afs_osi_Wakeup(&afs_WaitForCacheDrain);
999 } /* afs_FreeDCache */
1002 * Discard the cache element by moving it to the discardDCList.
1003 * This puts the cache element into a quasi-freed state, where
1004 * the space may be reused, but the file has not been truncated.
1006 * \note Major Assumptions Here:
1007 * Assumes that frag size is an integral power of two, less one,
1008 * and that this is a two's complement machine. I don't
1009 * know of any filesystems which violate this assumption...
1011 * \param adr Ptr to dcache entry.
1013 * \note Environment:
1014 * Must be called with afs_xdcache write-locked.
1018 afs_DiscardDCache(register struct dcache *adc)
1020 register afs_int32 size;
1022 AFS_STATCNT(afs_DiscardDCache);
1024 osi_Assert(adc->refCount == 1);
1026 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1027 afs_blocksDiscarded += size;
1028 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1030 afs_dvnextTbl[adc->index] = afs_discardDCList;
1031 afs_discardDCList = adc->index;
1032 afs_discardDCCount++;
1034 adc->f.fid.Fid.Volume = 0;
1035 adc->dflags |= DFEntryMod;
1036 afs_indexFlags[adc->index] |= IFDiscarded;
1038 if (afs_WaitForCacheDrain) {
1039 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1040 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1041 afs_WaitForCacheDrain = 0;
1042 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1046 } /*afs_DiscardDCache */
1049 * Free the next element on the list of discarded cache elements.
1052 afs_FreeDiscardedDCache(void)
1054 register struct dcache *tdc;
1055 register struct osi_file *tfile;
1056 register afs_int32 size;
1058 AFS_STATCNT(afs_FreeDiscardedDCache);
1060 MObtainWriteLock(&afs_xdcache, 510);
1061 if (!afs_blocksDiscarded) {
1062 MReleaseWriteLock(&afs_xdcache);
1067 * Get an entry from the list of discarded cache elements
1069 tdc = afs_GetDSlot(afs_discardDCList, 0);
1070 osi_Assert(tdc->refCount == 1);
1071 ReleaseReadLock(&tdc->tlock);
1073 afs_discardDCList = afs_dvnextTbl[tdc->index];
1074 afs_dvnextTbl[tdc->index] = NULLIDX;
1075 afs_discardDCCount--;
1076 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1077 afs_blocksDiscarded -= size;
1078 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1079 /* We can lock because we just took it off the free list */
1080 ObtainWriteLock(&tdc->lock, 626);
1081 MReleaseWriteLock(&afs_xdcache);
1084 * Truncate the element to reclaim its space
1086 tfile = afs_CFileOpen(&tdc->f.inode);
1087 afs_CFileTruncate(tfile, 0);
1088 afs_CFileClose(tfile);
1089 afs_AdjustSize(tdc, 0);
1090 afs_DCMoveBucket(tdc, 0, 0);
1093 * Free the element we just truncated
1095 MObtainWriteLock(&afs_xdcache, 511);
1096 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1097 afs_FreeDCache(tdc);
1098 tdc->f.states &= ~(DRO|DBackup|DRW);
1099 ReleaseWriteLock(&tdc->lock);
1101 MReleaseWriteLock(&afs_xdcache);
1105 * Free as many entries from the list of discarded cache elements
1106 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1111 afs_MaybeFreeDiscardedDCache(void)
1114 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1116 while (afs_blocksDiscarded
1117 && (afs_blocksUsed >
1118 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1119 afs_FreeDiscardedDCache();
1125 * Try to free up a certain number of disk slots.
1127 * \param anumber Targeted number of disk slots to free up.
1129 * \note Environment:
1130 * Must be called with afs_xdcache write-locked.
1134 afs_GetDownDSlot(int anumber)
1136 struct afs_q *tq, *nq;
1141 AFS_STATCNT(afs_GetDownDSlot);
1142 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1143 osi_Panic("diskless getdowndslot");
1145 if (CheckLock(&afs_xdcache) != -1)
1146 osi_Panic("getdowndslot nolock");
1148 /* decrement anumber first for all dudes in free list */
1149 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1152 return; /* enough already free */
1154 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1156 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1157 nq = QPrev(tq); /* in case we remove it */
1158 if (tdc->refCount == 0) {
1159 if ((ix = tdc->index) == NULLIDX)
1160 osi_Panic("getdowndslot");
1161 /* pull the entry out of the lruq and put it on the free list */
1162 QRemove(&tdc->lruq);
1164 /* write-through if modified */
1165 if (tdc->dflags & DFEntryMod) {
1166 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1168 * ask proxy to do this for us - we don't have the stack space
1170 while (tdc->dflags & DFEntryMod) {
1173 s = SPLOCK(afs_sgibklock);
1174 if (afs_sgibklist == NULL) {
1175 /* if slot is free, grab it. */
1176 afs_sgibklist = tdc;
1177 SV_SIGNAL(&afs_sgibksync);
1179 /* wait for daemon to (start, then) finish. */
1180 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1184 tdc->dflags &= ~DFEntryMod;
1185 afs_WriteDCache(tdc, 1);
1189 /* finally put the entry in the free list */
1190 afs_indexTable[ix] = NULL;
1191 afs_indexFlags[ix] &= ~IFEverUsed;
1192 tdc->index = NULLIDX;
1193 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1194 afs_freeDSList = tdc;
1198 } /*afs_GetDownDSlot */
1205 * Increment the reference count on a disk cache entry,
1206 * which already has a non-zero refcount. In order to
1207 * increment the refcount of a zero-reference entry, you
1208 * have to hold afs_xdcache.
1211 * adc : Pointer to the dcache entry to increment.
1214 * Nothing interesting.
1217 afs_RefDCache(struct dcache *adc)
1219 ObtainWriteLock(&adc->tlock, 627);
1220 if (adc->refCount < 0)
1221 osi_Panic("RefDCache: negative refcount");
1223 ReleaseWriteLock(&adc->tlock);
1232 * Decrement the reference count on a disk cache entry.
1235 * ad : Ptr to the dcache entry to decrement.
1238 * Nothing interesting.
1241 afs_PutDCache(register struct dcache *adc)
1243 AFS_STATCNT(afs_PutDCache);
1244 ObtainWriteLock(&adc->tlock, 276);
1245 if (adc->refCount <= 0)
1246 osi_Panic("putdcache");
1248 ReleaseWriteLock(&adc->tlock);
1257 * Try to discard all data associated with this file from the
1261 * avc : Pointer to the cache info for the file.
1264 * Both pvnLock and lock are write held.
1267 afs_TryToSmush(register struct vcache *avc, struct AFS_UCRED *acred, int sync)
1269 register struct dcache *tdc;
1272 AFS_STATCNT(afs_TryToSmush);
1273 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1274 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1275 sync = 1; /* XX Temp testing XX */
1277 #if defined(AFS_SUN5_ENV)
1278 ObtainWriteLock(&avc->vlock, 573);
1279 avc->activeV++; /* block new getpages */
1280 ReleaseWriteLock(&avc->vlock);
1283 /* Flush VM pages */
1284 osi_VM_TryToSmush(avc, acred, sync);
1287 * Get the hash chain containing all dce's for this fid
1289 i = DVHash(&avc->f.fid);
1290 MObtainWriteLock(&afs_xdcache, 277);
1291 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1292 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1293 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1294 int releaseTlock = 1;
1295 tdc = afs_GetDSlot(index, NULL);
1296 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1298 if ((afs_indexFlags[index] & IFDataMod) == 0
1299 && tdc->refCount == 1) {
1300 ReleaseReadLock(&tdc->tlock);
1302 afs_FlushDCache(tdc);
1305 afs_indexTable[index] = 0;
1308 ReleaseReadLock(&tdc->tlock);
1312 #if defined(AFS_SUN5_ENV)
1313 ObtainWriteLock(&avc->vlock, 545);
1314 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1315 avc->vstates &= ~VRevokeWait;
1316 afs_osi_Wakeup((char *)&avc->vstates);
1318 ReleaseWriteLock(&avc->vlock);
1320 MReleaseWriteLock(&afs_xdcache);
1322 * It's treated like a callback so that when we do lookups we'll
1323 * invalidate the unique bit if any
1324 * trytoSmush occured during the lookup call
1330 * afs_DCacheMissingChunks
1333 * Given the cached info for a file, return the number of chunks that
1334 * are not available from the dcache.
1337 * avc: Pointer to the (held) vcache entry to look in.
1340 * The number of chunks which are not currently cached.
1343 * The vcache entry is held upon entry.
1347 afs_DCacheMissingChunks(struct vcache *avc)
1350 afs_size_t totalLength = 0;
1351 afs_uint32 totalChunks = 0;
1354 totalLength = avc->f.m.Length;
1355 if (avc->f.truncPos < totalLength)
1356 totalLength = avc->f.truncPos;
1358 /* Length is 0, no chunk missing. */
1359 if (totalLength == 0)
1362 /* If totalLength is a multiple of chunksize, the last byte appears
1363 * as being part of the next chunk, which does not exist.
1364 * Decrementing totalLength by one fixes that.
1367 totalChunks = (AFS_CHUNK(totalLength) + 1);
1369 /* If we're a directory, we only ever have one chunk, regardless of
1370 * the size of the dir.
1372 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1376 printf("Should have %d chunks for %u bytes\n",
1377 totalChunks, (totalLength + 1));
1379 i = DVHash(&avc->f.fid);
1380 MObtainWriteLock(&afs_xdcache, 1001);
1381 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1382 i = afs_dvnextTbl[index];
1383 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1384 tdc = afs_GetDSlot(index, NULL);
1385 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1388 ReleaseReadLock(&tdc->tlock);
1392 MReleaseWriteLock(&afs_xdcache);
1394 /*printf("Missing %d chunks\n", totalChunks);*/
1396 return (totalChunks);
1403 * Given the cached info for a file and a byte offset into the
1404 * file, make sure the dcache entry for that file and containing
1405 * the given byte is available, returning it to our caller.
1408 * avc : Pointer to the (held) vcache entry to look in.
1409 * abyte : Which byte we want to get to.
1412 * Pointer to the dcache entry covering the file & desired byte,
1413 * or NULL if not found.
1416 * The vcache entry is held upon entry.
1420 afs_FindDCache(register struct vcache *avc, afs_size_t abyte)
1423 register afs_int32 i, index;
1424 register struct dcache *tdc = NULL;
1426 AFS_STATCNT(afs_FindDCache);
1427 chunk = AFS_CHUNK(abyte);
1430 * Hash on the [fid, chunk] and get the corresponding dcache index
1431 * after write-locking the dcache.
1433 i = DCHash(&avc->f.fid, chunk);
1434 MObtainWriteLock(&afs_xdcache, 278);
1435 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1436 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1437 tdc = afs_GetDSlot(index, NULL);
1438 ReleaseReadLock(&tdc->tlock);
1439 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1440 break; /* leaving refCount high for caller */
1444 index = afs_dcnextTbl[index];
1446 if (index != NULLIDX) {
1447 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1448 hadd32(afs_indexCounter, 1);
1449 MReleaseWriteLock(&afs_xdcache);
1452 MReleaseWriteLock(&afs_xdcache);
1454 } /*afs_FindDCache */
1458 * Get a fresh dcache from the free or discarded list.
1460 * \param avc Who's dcache is this going to be?
1461 * \param chunk The position where it will be placed in.
1462 * \param lock How are locks held.
1463 * \param ashFid If this dcache going to be used for a shadow dir,
1466 * \note Required locks:
1468 * - avc (R if (lock & 1) set and W otherwise)
1469 * \note It write locks the new dcache. The caller must unlock it.
1471 * \return The new dcache.
1473 struct dcache *afs_AllocDCache(struct vcache *avc,
1476 struct VenusFid *ashFid)
1478 struct dcache *tdc = NULL;
1479 afs_uint32 size = 0;
1480 struct osi_file *file;
1482 if (afs_discardDCList == NULLIDX
1483 || ((lock & 2) && afs_freeDCList != NULLIDX)) {
1485 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1486 tdc = afs_GetDSlot(afs_freeDCList, 0);
1487 osi_Assert(tdc->refCount == 1);
1488 ReleaseReadLock(&tdc->tlock);
1489 ObtainWriteLock(&tdc->lock, 604);
1490 afs_freeDCList = afs_dvnextTbl[tdc->index];
1493 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1494 tdc = afs_GetDSlot(afs_discardDCList, 0);
1495 osi_Assert(tdc->refCount == 1);
1496 ReleaseReadLock(&tdc->tlock);
1497 ObtainWriteLock(&tdc->lock, 605);
1498 afs_discardDCList = afs_dvnextTbl[tdc->index];
1499 afs_discardDCCount--;
1501 ((tdc->f.chunkBytes +
1502 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1503 tdc->f.states &= ~(DRO|DBackup|DRW);
1504 afs_DCMoveBucket(tdc, size, 0);
1505 afs_blocksDiscarded -= size;
1506 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1508 /* Truncate the chunk so zeroes get filled properly */
1509 file = afs_CFileOpen(&tdc->f.inode);
1510 afs_CFileTruncate(file, 0);
1511 afs_CFileClose(file);
1512 afs_AdjustSize(tdc, 0);
1518 * avc->lock(R) if setLocks
1519 * avc->lock(W) if !setLocks
1525 * Fill in the newly-allocated dcache record.
1527 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1529 /* Use shadow fid if provided. */
1530 tdc->f.fid = *ashFid;
1532 /* Use normal vcache's fid otherwise. */
1533 tdc->f.fid = avc->f.fid;
1534 if (avc->f.states & CRO)
1535 tdc->f.states = DRO;
1536 else if (avc->f.states & CBackup)
1537 tdc->f.states = DBackup;
1539 tdc->f.states = DRW;
1540 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1541 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1543 hones(tdc->f.versionNo); /* invalid value */
1544 tdc->f.chunk = chunk;
1545 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1547 if (tdc->lruq.prev == &tdc->lruq)
1548 osi_Panic("lruq 1");
1557 * This function is called to obtain a reference to data stored in
1558 * the disk cache, locating a chunk of data containing the desired
1559 * byte and returning a reference to the disk cache entry, with its
1560 * reference count incremented.
1564 * avc : Ptr to a vcache entry (unlocked)
1565 * abyte : Byte position in the file desired
1566 * areq : Request structure identifying the requesting user.
1567 * aflags : Settings as follows:
1569 * 2 : Return after creating entry.
1570 * 4 : called from afs_vnop_write.c
1571 * *alen contains length of data to be written.
1573 * aoffset : Set to the offset within the chunk where the resident
1575 * alen : Set to the number of bytes of data after the desired
1576 * byte (including the byte itself) which can be read
1580 * The vcache entry pointed to by avc is unlocked upon entry.
1584 struct AFSVolSync tsync;
1585 struct AFSFetchStatus OutStatus;
1586 struct AFSCallBack CallBack;
1590 * Update the vnode-to-dcache hint if we can get the vnode lock
1591 * right away. Assumes dcache entry is at least read-locked.
1594 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1596 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1597 if (hsame(v->f.m.DataVersion, d->f.versionNo) && v->callback)
1600 ReleaseWriteLock(&v->lock);
1604 /* avc - Write-locked unless aflags & 1 */
1606 afs_GetDCache(register struct vcache *avc, afs_size_t abyte,
1607 register struct vrequest *areq, afs_size_t * aoffset,
1608 afs_size_t * alen, int aflags)
1610 register afs_int32 i, code, code1 = 0, shortcut;
1611 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1612 register afs_int32 adjustsize = 0;
1618 afs_size_t maxGoodLength; /* amount of good data at server */
1619 struct rx_call *tcall;
1620 afs_size_t Position = 0;
1621 #ifdef AFS_64BIT_CLIENT
1623 afs_size_t lengthFound; /* as returned from server */
1624 #endif /* AFS_64BIT_CLIENT */
1625 afs_int32 size, tlen; /* size of segment to transfer */
1626 struct tlocal1 *tsmall = 0;
1627 register struct dcache *tdc;
1628 register struct osi_file *file;
1629 register struct afs_conn *tc;
1631 struct server *newCallback = NULL;
1632 char setNewCallback;
1633 char setVcacheStatus;
1634 char doVcacheUpdate;
1636 int doAdjustSize = 0;
1637 int doReallyAdjustSize = 0;
1638 int overWriteWholeChunk = 0;
1642 struct afs_stats_xferData *xferP; /* Ptr to this op's xfer struct */
1643 osi_timeval_t xferStartTime, /*FS xfer start time */
1644 xferStopTime; /*FS xfer stop time */
1645 afs_size_t bytesToXfer; /* # bytes to xfer */
1646 afs_size_t bytesXferred; /* # bytes actually xferred */
1647 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1648 int fromReplica; /*Are we reading from a replica? */
1649 int numFetchLoops; /*# times around the fetch/analyze loop */
1650 #endif /* AFS_NOSTATS */
1652 AFS_STATCNT(afs_GetDCache);
1656 setLocks = aflags & 1;
1659 * Determine the chunk number and offset within the chunk corresponding
1660 * to the desired byte.
1662 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1665 chunk = AFS_CHUNK(abyte);
1668 /* come back to here if we waited for the cache to drain. */
1671 setNewCallback = setVcacheStatus = 0;
1675 ObtainWriteLock(&avc->lock, 616);
1677 ObtainReadLock(&avc->lock);
1682 * avc->lock(R) if setLocks && !slowPass
1683 * avc->lock(W) if !setLocks || slowPass
1688 /* check hints first! (might could use bcmp or some such...) */
1689 if ((tdc = avc->dchint)) {
1693 * The locking order between afs_xdcache and dcache lock matters.
1694 * The hint dcache entry could be anywhere, even on the free list.
1695 * Locking afs_xdcache ensures that noone is trying to pull dcache
1696 * entries from the free list, and thereby assuming them to be not
1697 * referenced and not locked.
1699 MObtainReadLock(&afs_xdcache);
1700 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1702 if (dcLocked && (tdc->index != NULLIDX)
1703 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
1704 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1705 /* got the right one. It might not be the right version, and it
1706 * might be fetching, but it's the right dcache entry.
1708 /* All this code should be integrated better with what follows:
1709 * I can save a good bit more time under a write lock if I do..
1711 ObtainWriteLock(&tdc->tlock, 603);
1713 ReleaseWriteLock(&tdc->tlock);
1715 MReleaseReadLock(&afs_xdcache);
1718 if (hsame(tdc->f.versionNo, avc->f.m.DataVersion)
1719 && !(tdc->dflags & DFFetching)) {
1721 afs_stats_cmperf.dcacheHits++;
1722 MObtainWriteLock(&afs_xdcache, 559);
1723 QRemove(&tdc->lruq);
1724 QAdd(&afs_DLRU, &tdc->lruq);
1725 MReleaseWriteLock(&afs_xdcache);
1728 * avc->lock(R) if setLocks && !slowPass
1729 * avc->lock(W) if !setLocks || slowPass
1736 ReleaseSharedLock(&tdc->lock);
1737 MReleaseReadLock(&afs_xdcache);
1745 * avc->lock(R) if setLocks && !slowPass
1746 * avc->lock(W) if !setLocks || slowPass
1747 * tdc->lock(S) if tdc
1750 if (!tdc) { /* If the hint wasn't the right dcache entry */
1752 * Hash on the [fid, chunk] and get the corresponding dcache index
1753 * after write-locking the dcache.
1758 * avc->lock(R) if setLocks && !slowPass
1759 * avc->lock(W) if !setLocks || slowPass
1762 i = DCHash(&avc->f.fid, chunk);
1763 /* check to make sure our space is fine */
1764 afs_MaybeWakeupTruncateDaemon();
1766 MObtainWriteLock(&afs_xdcache, 280);
1768 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1769 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1770 tdc = afs_GetDSlot(index, NULL);
1771 ReleaseReadLock(&tdc->tlock);
1774 * avc->lock(R) if setLocks && !slowPass
1775 * avc->lock(W) if !setLocks || slowPass
1778 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1779 /* Move it up in the beginning of the list */
1780 if (afs_dchashTbl[i] != index) {
1781 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1782 afs_dcnextTbl[index] = afs_dchashTbl[i];
1783 afs_dchashTbl[i] = index;
1785 MReleaseWriteLock(&afs_xdcache);
1786 ObtainSharedLock(&tdc->lock, 606);
1787 break; /* leaving refCount high for caller */
1793 index = afs_dcnextTbl[index];
1797 * If we didn't find the entry, we'll create one.
1799 if (index == NULLIDX) {
1802 * avc->lock(R) if setLocks
1803 * avc->lock(W) if !setLocks
1806 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1807 avc, ICL_TYPE_INT32, chunk);
1809 /* Make sure there is a free dcache entry for us to use */
1810 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1813 avc->f.states |= CDCLock;
1814 /* just need slots */
1815 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1817 avc->f.states &= ~CDCLock;
1818 if (afs_discardDCList != NULLIDX
1819 || afs_freeDCList != NULLIDX)
1821 /* If we can't get space for 5 mins we give up and panic */
1822 if (++downDCount > 300) {
1823 #if defined(AFS_CACHE_BYPASS)
1824 afs_warn("GetDCache calling osi_Panic: No space in five minutes.\n downDCount: %d\n aoffset: %d alen: %d\n", downDCount, aoffset, alen);
1826 osi_Panic("getdcache");
1828 MReleaseWriteLock(&afs_xdcache);
1831 * avc->lock(R) if setLocks
1832 * avc->lock(W) if !setLocks
1834 afs_osi_Wait(1000, 0, 0);
1839 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
1842 * Now add to the two hash chains - note that i is still set
1843 * from the above DCHash call.
1845 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1846 afs_dchashTbl[i] = tdc->index;
1847 i = DVHash(&avc->f.fid);
1848 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1849 afs_dvhashTbl[i] = tdc->index;
1850 tdc->dflags = DFEntryMod;
1852 afs_MaybeWakeupTruncateDaemon();
1853 MReleaseWriteLock(&afs_xdcache);
1854 ConvertWToSLock(&tdc->lock);
1859 /* vcache->dcache hint failed */
1862 * avc->lock(R) if setLocks && !slowPass
1863 * avc->lock(W) if !setLocks || slowPass
1866 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1867 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
1868 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
1869 hgetlo(avc->f.m.DataVersion));
1871 * Here we have the entry in tdc, with its refCount incremented.
1872 * Note: we don't use the S-lock on avc; it costs concurrency when
1873 * storing a file back to the server.
1877 * Not a newly created file so we need to check the file's length and
1878 * compare data versions since someone could have changed the data or we're
1879 * reading a file written elsewhere. We only want to bypass doing no-op
1880 * read rpcs on newly created files (dv of 0) since only then we guarantee
1881 * that this chunk's data hasn't been filled by another client.
1883 size = AFS_CHUNKSIZE(abyte);
1884 if (aflags & 4) /* called from write */
1886 else /* called from read */
1887 tlen = tdc->validPos - abyte;
1888 Position = AFS_CHUNKTOBASE(chunk);
1889 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
1890 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
1891 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
1892 ICL_HANDLE_OFFSET(Position));
1893 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
1895 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
1896 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
1897 overWriteWholeChunk = 1;
1898 if (doAdjustSize || overWriteWholeChunk) {
1899 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1901 #ifdef AFS_SGI64_ENV
1904 #else /* AFS_SGI64_ENV */
1907 #endif /* AFS_SGI64_ENV */
1908 #else /* AFS_SGI_ENV */
1911 #endif /* AFS_SGI_ENV */
1912 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
1913 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1914 #if defined(AFS_SUN5_ENV) || defined(AFS_OSF_ENV)
1915 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
1917 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
1919 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1920 !hsame(avc->f.m.DataVersion, tdc->f.versionNo))
1921 doReallyAdjustSize = 1;
1923 if (doReallyAdjustSize || overWriteWholeChunk) {
1924 /* no data in file to read at this position */
1925 UpgradeSToWLock(&tdc->lock, 607);
1926 file = afs_CFileOpen(&tdc->f.inode);
1927 afs_CFileTruncate(file, 0);
1928 afs_CFileClose(file);
1929 afs_AdjustSize(tdc, 0);
1930 hset(tdc->f.versionNo, avc->f.m.DataVersion);
1931 tdc->dflags |= DFEntryMod;
1933 ConvertWToSLock(&tdc->lock);
1938 * We must read in the whole chunk if the version number doesn't
1942 /* don't need data, just a unique dcache entry */
1943 ObtainWriteLock(&afs_xdcache, 608);
1944 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1945 hadd32(afs_indexCounter, 1);
1946 ReleaseWriteLock(&afs_xdcache);
1948 updateV2DC(setLocks, avc, tdc, 553);
1949 if (vType(avc) == VDIR)
1952 *aoffset = AFS_CHUNKOFFSET(abyte);
1953 if (tdc->validPos < abyte)
1954 *alen = (afs_size_t) 0;
1956 *alen = tdc->validPos - abyte;
1957 ReleaseSharedLock(&tdc->lock);
1960 ReleaseWriteLock(&avc->lock);
1962 ReleaseReadLock(&avc->lock);
1964 return tdc; /* check if we're done */
1969 * avc->lock(R) if setLocks && !slowPass
1970 * avc->lock(W) if !setLocks || slowPass
1973 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
1975 setNewCallback = setVcacheStatus = 0;
1979 * avc->lock(R) if setLocks && !slowPass
1980 * avc->lock(W) if !setLocks || slowPass
1983 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
1985 * Version number mismatch.
1988 * If we are disconnected, then we can't do much of anything
1989 * because the data doesn't match the file.
1991 if (AFS_IS_DISCONNECTED) {
1992 ReleaseSharedLock(&tdc->lock);
1995 ReleaseWriteLock(&avc->lock);
1997 ReleaseReadLock(&avc->lock);
1999 /* Flush the Dcache */
2004 UpgradeSToWLock(&tdc->lock, 609);
2007 * If data ever existed for this vnode, and this is a text object,
2008 * do some clearing. Now, you'd think you need only do the flush
2009 * when VTEXT is on, but VTEXT is turned off when the text object
2010 * is freed, while pages are left lying around in memory marked
2011 * with this vnode. If we would reactivate (create a new text
2012 * object from) this vnode, we could easily stumble upon some of
2013 * these old pages in pagein. So, we always flush these guys.
2014 * Sun has a wonderful lack of useful invariants in this system.
2016 * avc->flushDV is the data version # of the file at the last text
2017 * flush. Clearly, at least, we don't have to flush the file more
2018 * often than it changes
2020 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2022 * By here, the cache entry is always write-locked. We can
2023 * deadlock if we call osi_Flush with the cache entry locked...
2024 * Unlock the dcache too.
2026 ReleaseWriteLock(&tdc->lock);
2027 if (setLocks && !slowPass)
2028 ReleaseReadLock(&avc->lock);
2030 ReleaseWriteLock(&avc->lock);
2034 * Call osi_FlushPages in open, read/write, and map, since it
2035 * is too hard here to figure out if we should lock the
2038 if (setLocks && !slowPass)
2039 ObtainReadLock(&avc->lock);
2041 ObtainWriteLock(&avc->lock, 66);
2042 ObtainWriteLock(&tdc->lock, 610);
2047 * avc->lock(R) if setLocks && !slowPass
2048 * avc->lock(W) if !setLocks || slowPass
2052 /* Watch for standard race condition around osi_FlushText */
2053 if (hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
2054 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2055 afs_stats_cmperf.dcacheHits++;
2056 ConvertWToSLock(&tdc->lock);
2060 /* Sleep here when cache needs to be drained. */
2061 if (setLocks && !slowPass
2062 && (afs_blocksUsed >
2063 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2064 /* Make sure truncate daemon is running */
2065 afs_MaybeWakeupTruncateDaemon();
2066 ObtainWriteLock(&tdc->tlock, 614);
2067 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2068 ReleaseWriteLock(&tdc->tlock);
2069 ReleaseWriteLock(&tdc->lock);
2070 ReleaseReadLock(&avc->lock);
2071 while ((afs_blocksUsed - afs_blocksDiscarded) >
2072 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2073 afs_WaitForCacheDrain = 1;
2074 afs_osi_Sleep(&afs_WaitForCacheDrain);
2076 afs_MaybeFreeDiscardedDCache();
2077 /* need to check if someone else got the chunk first. */
2078 goto RetryGetDCache;
2081 /* Do not fetch data beyond truncPos. */
2082 maxGoodLength = avc->f.m.Length;
2083 if (avc->f.truncPos < maxGoodLength)
2084 maxGoodLength = avc->f.truncPos;
2085 Position = AFS_CHUNKBASE(abyte);
2086 if (vType(avc) == VDIR) {
2087 size = avc->f.m.Length;
2088 if (size > tdc->f.chunkBytes) {
2089 /* pre-reserve space for file */
2090 afs_AdjustSize(tdc, size);
2092 size = 999999999; /* max size for transfer */
2094 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2095 /* don't read past end of good data on server */
2096 if (Position + size > maxGoodLength)
2097 size = maxGoodLength - Position;
2099 size = 0; /* Handle random races */
2100 if (size > tdc->f.chunkBytes) {
2101 /* pre-reserve space for file */
2102 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2103 /* max size for transfer still in size */
2106 if (afs_mariner && !tdc->f.chunk)
2107 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2109 * Right now, we only have one tool, and it's a hammer. So, we
2110 * fetch the whole file.
2112 DZap(tdc); /* pages in cache may be old */
2113 file = afs_CFileOpen(&tdc->f.inode);
2114 afs_RemoveVCB(&avc->f.fid);
2115 tdc->f.states |= DWriting;
2116 tdc->dflags |= DFFetching;
2117 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2118 if (tdc->mflags & DFFetchReq) {
2119 tdc->mflags &= ~DFFetchReq;
2120 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2121 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2122 __FILE__, ICL_TYPE_INT32, __LINE__,
2123 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2127 (struct tlocal1 *)osi_AllocLargeSpace(sizeof(struct tlocal1));
2128 setVcacheStatus = 0;
2131 * Remember if we are doing the reading from a replicated volume,
2132 * and how many times we've zipped around the fetch/analyze loop.
2134 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2136 accP = &(afs_stats_cmfullperf.accessinf);
2138 (accP->replicatedRefs)++;
2140 (accP->unreplicatedRefs)++;
2141 #endif /* AFS_NOSTATS */
2142 /* this is a cache miss */
2143 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2144 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2145 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2148 afs_stats_cmperf.dcacheMisses++;
2151 * Dynamic root support: fetch data from local memory.
2153 if (afs_IsDynroot(avc)) {
2157 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2159 dynrootDir += Position;
2160 dynrootLen -= Position;
2161 if (size > dynrootLen)
2165 code = afs_CFileWrite(file, 0, dynrootDir, size);
2173 tdc->validPos = Position + size;
2174 afs_CFileTruncate(file, size); /* prune it */
2175 } else if (afs_IsDynrootMount(avc)) {
2179 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2181 dynrootDir += Position;
2182 dynrootLen -= Position;
2183 if (size > dynrootLen)
2187 code = afs_CFileWrite(file, 0, dynrootDir, size);
2195 tdc->validPos = Position + size;
2196 afs_CFileTruncate(file, size); /* prune it */
2199 * Not a dynamic vnode: do the real fetch.
2204 * avc->lock(R) if setLocks && !slowPass
2205 * avc->lock(W) if !setLocks || slowPass
2209 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
2211 #ifdef AFS_64BIT_CLIENT
2212 afs_int32 length_hi;
2214 afs_int32 length, bytes;
2218 (accP->numReplicasAccessed)++;
2220 #endif /* AFS_NOSTATS */
2221 if (!setLocks || slowPass) {
2222 avc->callback = tc->srvr->server;
2224 newCallback = tc->srvr->server;
2229 tcall = rx_NewCall(tc->id);
2232 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
2233 #ifdef AFS_64BIT_CLIENT
2234 length_hi = code = 0;
2235 if (!afs_serverHasNo64Bit(tc)) {
2239 StartRXAFS_FetchData64(tcall,
2240 (struct AFSFid *)&avc->f.fid.
2241 Fid, Position, tsize);
2244 afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2245 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32,
2249 rx_Read(tcall, (char *)&length_hi,
2252 if (bytes == sizeof(afs_int32)) {
2253 length_hi = ntohl(length_hi);
2256 code = rx_Error(tcall);
2258 code1 = rx_EndCall(tcall, code);
2260 tcall = (struct rx_call *)0;
2264 if (code == RXGEN_OPCODE || afs_serverHasNo64Bit(tc)) {
2265 if (Position > 0x7FFFFFFF) {
2272 tcall = rx_NewCall(tc->id);
2274 StartRXAFS_FetchData(tcall, (struct AFSFid *)
2275 &avc->f.fid.Fid, pos,
2279 afs_serverSetNo64Bit(tc);
2284 rx_Read(tcall, (char *)&length,
2287 if (bytes == sizeof(afs_int32)) {
2288 length = ntohl(length);
2290 code = rx_Error(tcall);
2293 FillInt64(lengthFound, length_hi, length);
2294 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64LENG,
2295 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
2297 ICL_HANDLE_OFFSET(lengthFound));
2298 #else /* AFS_64BIT_CLIENT */
2301 StartRXAFS_FetchData(tcall,
2302 (struct AFSFid *)&avc->f.fid.Fid,
2308 rx_Read(tcall, (char *)&length,
2311 if (bytes == sizeof(afs_int32)) {
2312 length = ntohl(length);
2314 code = rx_Error(tcall);
2317 #endif /* AFS_64BIT_CLIENT */
2322 &(afs_stats_cmfullperf.rpc.
2323 fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
2324 osi_GetuTime(&xferStartTime);
2327 afs_CacheFetchProc(tcall, file,
2328 (afs_size_t) Position, tdc,
2330 &bytesXferred, length);
2332 osi_GetuTime(&xferStopTime);
2333 (xferP->numXfers)++;
2335 (xferP->numSuccesses)++;
2336 afs_stats_XferSumBytes
2337 [AFS_STATS_FS_XFERIDX_FETCHDATA] +=
2339 (xferP->sumBytes) +=
2340 (afs_stats_XferSumBytes
2341 [AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
2342 afs_stats_XferSumBytes
2343 [AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
2344 if (bytesXferred < xferP->minBytes)
2345 xferP->minBytes = bytesXferred;
2346 if (bytesXferred > xferP->maxBytes)
2347 xferP->maxBytes = bytesXferred;
2350 * Tally the size of the object. Note: we tally the actual size,
2351 * NOT the number of bytes that made it out over the wire.
2353 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
2354 (xferP->count[0])++;
2355 else if (bytesToXfer <=
2356 AFS_STATS_MAXBYTES_BUCKET1)
2357 (xferP->count[1])++;
2358 else if (bytesToXfer <=
2359 AFS_STATS_MAXBYTES_BUCKET2)
2360 (xferP->count[2])++;
2361 else if (bytesToXfer <=
2362 AFS_STATS_MAXBYTES_BUCKET3)
2363 (xferP->count[3])++;
2364 else if (bytesToXfer <=
2365 AFS_STATS_MAXBYTES_BUCKET4)
2366 (xferP->count[4])++;
2367 else if (bytesToXfer <=
2368 AFS_STATS_MAXBYTES_BUCKET5)
2369 (xferP->count[5])++;
2370 else if (bytesToXfer <=
2371 AFS_STATS_MAXBYTES_BUCKET6)
2372 (xferP->count[6])++;
2373 else if (bytesToXfer <=
2374 AFS_STATS_MAXBYTES_BUCKET7)
2375 (xferP->count[7])++;
2377 (xferP->count[8])++;
2379 afs_stats_GetDiff(elapsedTime, xferStartTime,
2381 afs_stats_AddTo((xferP->sumTime), elapsedTime);
2382 afs_stats_SquareAddTo((xferP->sqrTime),
2384 if (afs_stats_TimeLessThan
2385 (elapsedTime, (xferP->minTime))) {
2386 afs_stats_TimeAssign((xferP->minTime),
2389 if (afs_stats_TimeGreaterThan
2390 (elapsedTime, (xferP->maxTime))) {
2391 afs_stats_TimeAssign((xferP->maxTime),
2397 afs_CacheFetchProc(tcall, file, Position, tdc,
2399 #endif /* AFS_NOSTATS */
2404 EndRXAFS_FetchData(tcall, &tsmall->OutStatus,
2412 code1 = rx_EndCall(tcall, code);
2421 /* callback could have been broken (or expired) in a race here,
2422 * but we return the data anyway. It's as good as we knew about
2423 * when we started. */
2425 * validPos is updated by CacheFetchProc, and can only be
2426 * modifed under a dcache write lock, which we've blocked out
2428 size = tdc->validPos - Position; /* actual segment size */
2431 afs_CFileTruncate(file, size); /* prune it */
2433 if (!setLocks || slowPass) {
2434 ObtainWriteLock(&afs_xcbhash, 453);
2435 afs_DequeueCallback(avc);
2436 avc->f.states &= ~(CStatd | CUnique);
2437 avc->callback = NULL;
2438 ReleaseWriteLock(&afs_xcbhash);
2439 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2440 osi_dnlc_purgedp(avc);
2442 /* Something lost. Forget about performance, and go
2443 * back with a vcache write lock.
2445 afs_CFileTruncate(file, 0);
2446 afs_AdjustSize(tdc, 0);
2447 afs_CFileClose(file);
2448 osi_FreeLargeSpace(tsmall);
2450 ReleaseWriteLock(&tdc->lock);
2453 ReleaseReadLock(&avc->lock);
2455 goto RetryGetDCache;
2459 } while (afs_Analyze
2460 (tc, code, &avc->f.fid, areq,
2461 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2465 * avc->lock(R) if setLocks && !slowPass
2466 * avc->lock(W) if !setLocks || slowPass
2472 * In the case of replicated access, jot down info on the number of
2473 * attempts it took before we got through or gave up.
2476 if (numFetchLoops <= 1)
2477 (accP->refFirstReplicaOK)++;
2478 if (numFetchLoops > accP->maxReplicasPerRef)
2479 accP->maxReplicasPerRef = numFetchLoops;
2481 #endif /* AFS_NOSTATS */
2483 tdc->dflags &= ~DFFetching;
2484 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2485 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2486 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2487 tdc, ICL_TYPE_INT32, tdc->dflags);
2488 if (avc->execsOrWriters == 0)
2489 tdc->f.states &= ~DWriting;
2491 /* now, if code != 0, we have an error and should punt.
2492 * note that we have the vcache write lock, either because
2493 * !setLocks or slowPass.
2496 afs_CFileTruncate(file, 0);
2497 afs_AdjustSize(tdc, 0);
2498 afs_CFileClose(file);
2499 ZapDCE(tdc); /* sets DFEntryMod */
2500 if (vType(avc) == VDIR) {
2503 tdc->f.states &= ~(DRO|DBackup|DRW);
2504 afs_DCMoveBucket(tdc, 0, 0);
2505 ReleaseWriteLock(&tdc->lock);
2507 if (!afs_IsDynroot(avc)) {
2508 ObtainWriteLock(&afs_xcbhash, 454);
2509 afs_DequeueCallback(avc);
2510 avc->f.states &= ~(CStatd | CUnique);
2511 ReleaseWriteLock(&afs_xcbhash);
2512 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2513 osi_dnlc_purgedp(avc);
2516 * avc->lock(W); assert(!setLocks || slowPass)
2518 osi_Assert(!setLocks || slowPass);
2524 /* otherwise we copy in the just-fetched info */
2525 afs_CFileClose(file);
2526 afs_AdjustSize(tdc, size); /* new size */
2528 * Copy appropriate fields into vcache. Status is
2529 * copied later where we selectively acquire the
2530 * vcache write lock.
2533 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2535 setVcacheStatus = 1;
2536 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2537 tsmall->OutStatus.DataVersion);
2538 tdc->dflags |= DFEntryMod;
2539 afs_indexFlags[tdc->index] |= IFEverUsed;
2540 ConvertWToSLock(&tdc->lock);
2541 } /*Data version numbers don't match */
2544 * Data version numbers match.
2546 afs_stats_cmperf.dcacheHits++;
2547 } /*Data version numbers match */
2549 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2553 * avc->lock(R) if setLocks && !slowPass
2554 * avc->lock(W) if !setLocks || slowPass
2555 * tdc->lock(S) if tdc
2559 * See if this was a reference to a file in the local cell.
2561 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2562 afs_stats_cmperf.dlocalAccesses++;
2564 afs_stats_cmperf.dremoteAccesses++;
2566 /* Fix up LRU info */
2569 MObtainWriteLock(&afs_xdcache, 602);
2570 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2571 hadd32(afs_indexCounter, 1);
2572 MReleaseWriteLock(&afs_xdcache);
2574 /* return the data */
2575 if (vType(avc) == VDIR)
2578 *aoffset = AFS_CHUNKOFFSET(abyte);
2579 *alen = (tdc->f.chunkBytes - *aoffset);
2580 ReleaseSharedLock(&tdc->lock);
2585 * avc->lock(R) if setLocks && !slowPass
2586 * avc->lock(W) if !setLocks || slowPass
2589 /* Fix up the callback and status values in the vcache */
2591 if (setLocks && !slowPass) {
2594 * This is our dirty little secret to parallel fetches.
2595 * We don't write-lock the vcache while doing the fetch,
2596 * but potentially we'll need to update the vcache after
2597 * the fetch is done.
2599 * Drop the read lock and try to re-obtain the write
2600 * lock. If the vcache still has the same DV, it's
2601 * ok to go ahead and install the new data.
2603 afs_hyper_t currentDV, statusDV;
2605 hset(currentDV, avc->f.m.DataVersion);
2607 if (setNewCallback && avc->callback != newCallback)
2611 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2612 tsmall->OutStatus.DataVersion);
2614 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2616 if (setVcacheStatus && !hsame(currentDV, statusDV))
2620 ReleaseReadLock(&avc->lock);
2622 if (doVcacheUpdate) {
2623 ObtainWriteLock(&avc->lock, 615);
2624 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2625 /* We lose. Someone will beat us to it. */
2627 ReleaseWriteLock(&avc->lock);
2632 /* With slow pass, we've already done all the updates */
2634 ReleaseWriteLock(&avc->lock);
2637 /* Check if we need to perform any last-minute fixes with a write-lock */
2638 if (!setLocks || doVcacheUpdate) {
2640 avc->callback = newCallback;
2641 if (tsmall && setVcacheStatus)
2642 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2644 ReleaseWriteLock(&avc->lock);
2648 osi_FreeLargeSpace(tsmall);
2651 } /*afs_GetDCache */
2655 * afs_WriteThroughDSlots
2658 * Sweep through the dcache slots and write out any modified
2659 * in-memory data back on to our caching store.
2665 * The afs_xdcache is write-locked through this whole affair.
2668 afs_WriteThroughDSlots(void)
2670 register struct dcache *tdc;
2671 register afs_int32 i, touchedit = 0;
2673 struct afs_q DirtyQ, *tq;
2675 AFS_STATCNT(afs_WriteThroughDSlots);
2678 * Because of lock ordering, we can't grab dcache locks while
2679 * holding afs_xdcache. So we enter xdcache, get a reference
2680 * for every dcache entry, and exit xdcache.
2682 MObtainWriteLock(&afs_xdcache, 283);
2684 for (i = 0; i < afs_cacheFiles; i++) {
2685 tdc = afs_indexTable[i];
2687 /* Grab tlock in case the existing refcount isn't zero */
2688 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2689 ObtainWriteLock(&tdc->tlock, 623);
2691 ReleaseWriteLock(&tdc->tlock);
2693 QAdd(&DirtyQ, &tdc->dirty);
2696 MReleaseWriteLock(&afs_xdcache);
2699 * Now, for each dcache entry we found, check if it's dirty.
2700 * If so, get write-lock, get afs_xdcache, which protects
2701 * afs_cacheInodep, and flush it. Don't forget to put back
2705 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2707 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2709 if (tdc->dflags & DFEntryMod) {
2712 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2714 /* Now that we have the write lock, double-check */
2715 if (wrLock && (tdc->dflags & DFEntryMod)) {
2716 tdc->dflags &= ~DFEntryMod;
2717 MObtainWriteLock(&afs_xdcache, 620);
2718 afs_WriteDCache(tdc, 1);
2719 MReleaseWriteLock(&afs_xdcache);
2723 ReleaseWriteLock(&tdc->lock);
2729 MObtainWriteLock(&afs_xdcache, 617);
2730 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2731 /* Touch the file to make sure that the mtime on the file is kept
2732 * up-to-date to avoid losing cached files on cold starts because
2733 * their mtime seems old...
2735 struct afs_fheader theader;
2737 theader.magic = AFS_FHMAGIC;
2738 theader.firstCSize = AFS_FIRSTCSIZE;
2739 theader.otherCSize = AFS_OTHERCSIZE;
2740 theader.version = AFS_CI_VERSION;
2741 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2743 MReleaseWriteLock(&afs_xdcache);
2750 * Return a pointer to an freshly initialized dcache entry using
2751 * a memory-based cache. The tlock will be read-locked.
2754 * aslot : Dcache slot to look at.
2755 * tmpdc : Ptr to dcache entry.
2758 * Must be called with afs_xdcache write-locked.
2762 afs_MemGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2764 register struct dcache *tdc;
2767 AFS_STATCNT(afs_MemGetDSlot);
2768 if (CheckLock(&afs_xdcache) != -1)
2769 osi_Panic("getdslot nolock");
2770 if (aslot < 0 || aslot >= afs_cacheFiles)
2771 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2772 tdc = afs_indexTable[aslot];
2774 QRemove(&tdc->lruq); /* move to queue head */
2775 QAdd(&afs_DLRU, &tdc->lruq);
2776 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2777 ObtainWriteLock(&tdc->tlock, 624);
2779 ConvertWToRLock(&tdc->tlock);
2782 if (tmpdc == NULL) {
2783 if (!afs_freeDSList)
2784 afs_GetDownDSlot(4);
2785 if (!afs_freeDSList) {
2786 /* none free, making one is better than a panic */
2787 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2788 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2789 #ifdef KERNEL_HAVE_PIN
2790 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2793 tdc = afs_freeDSList;
2794 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2797 tdc->dflags = 0; /* up-to-date, not in free q */
2799 QAdd(&afs_DLRU, &tdc->lruq);
2800 if (tdc->lruq.prev == &tdc->lruq)
2801 osi_Panic("lruq 3");
2807 /* initialize entry */
2808 tdc->f.fid.Cell = 0;
2809 tdc->f.fid.Fid.Volume = 0;
2811 hones(tdc->f.versionNo);
2812 tdc->f.inode.mem = aslot;
2813 tdc->dflags |= DFEntryMod;
2816 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2819 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2820 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2821 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2824 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2825 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2826 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2827 ObtainReadLock(&tdc->tlock);
2830 afs_indexTable[aslot] = tdc;
2833 } /*afs_MemGetDSlot */
2835 unsigned int last_error = 0, lasterrtime = 0;
2841 * Return a pointer to an freshly initialized dcache entry using
2842 * a UFS-based disk cache. The dcache tlock will be read-locked.
2845 * aslot : Dcache slot to look at.
2846 * tmpdc : Ptr to dcache entry.
2849 * afs_xdcache lock write-locked.
2852 afs_UFSGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2854 register afs_int32 code;
2855 register struct dcache *tdc;
2859 AFS_STATCNT(afs_UFSGetDSlot);
2860 if (CheckLock(&afs_xdcache) != -1)
2861 osi_Panic("getdslot nolock");
2862 if (aslot < 0 || aslot >= afs_cacheFiles)
2863 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2864 tdc = afs_indexTable[aslot];
2866 QRemove(&tdc->lruq); /* move to queue head */
2867 QAdd(&afs_DLRU, &tdc->lruq);
2868 /* Grab tlock in case refCount != 0 */
2869 ObtainWriteLock(&tdc->tlock, 625);
2871 ConvertWToRLock(&tdc->tlock);
2874 /* otherwise we should read it in from the cache file */
2876 * If we weren't passed an in-memory region to place the file info,
2877 * we have to allocate one.
2879 if (tmpdc == NULL) {
2880 if (!afs_freeDSList)
2881 afs_GetDownDSlot(4);
2882 if (!afs_freeDSList) {
2883 /* none free, making one is better than a panic */
2884 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2885 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2886 #ifdef KERNEL_HAVE_PIN
2887 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2890 tdc = afs_freeDSList;
2891 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2894 tdc->dflags = 0; /* up-to-date, not in free q */
2896 QAdd(&afs_DLRU, &tdc->lruq);
2897 if (tdc->lruq.prev == &tdc->lruq)
2898 osi_Panic("lruq 3");
2905 * Seek to the aslot'th entry and read it in.
2908 afs_osi_Read(afs_cacheInodep,
2909 sizeof(struct fcache) * aslot +
2910 sizeof(struct afs_fheader), (char *)(&tdc->f),
2911 sizeof(struct fcache));
2913 if (code != sizeof(struct fcache))
2915 if (!afs_CellNumValid(tdc->f.fid.Cell))
2919 tdc->f.fid.Cell = 0;
2920 tdc->f.fid.Fid.Volume = 0;
2922 hones(tdc->f.versionNo);
2923 tdc->dflags |= DFEntryMod;
2924 #if defined(KERNEL_HAVE_UERROR)
2925 last_error = getuerror();
2927 lasterrtime = osi_Time();
2928 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2929 tdc->f.states &= ~(DRO|DBackup|DRW);
2930 afs_DCMoveBucket(tdc, 0, 0);
2933 if (tdc->f.states & DRO) {
2934 afs_DCMoveBucket(tdc, 0, 2);
2935 } else if (tdc->f.states & DBackup) {
2936 afs_DCMoveBucket(tdc, 0, 1);
2938 afs_DCMoveBucket(tdc, 0, 1);
2944 if (tdc->f.chunk >= 0)
2945 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
2950 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2951 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2952 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2955 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2956 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2957 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2958 ObtainReadLock(&tdc->tlock);
2961 * If we didn't read into a temporary dcache region, update the
2962 * slot pointer table.
2965 afs_indexTable[aslot] = tdc;
2968 } /*afs_UFSGetDSlot */
2973 * Write a particular dcache entry back to its home in the
2976 * \param adc Pointer to the dcache entry to write.
2977 * \param atime If true, set the modtime on the file to the current time.
2979 * \note Environment:
2980 * Must be called with the afs_xdcache lock at least read-locked,
2981 * and dcache entry at least read-locked.
2982 * The reference count is not changed.
2986 afs_WriteDCache(register struct dcache *adc, int atime)
2988 register afs_int32 code;
2990 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2992 AFS_STATCNT(afs_WriteDCache);
2993 osi_Assert(WriteLocked(&afs_xdcache));
2995 adc->f.modTime = osi_Time();
2997 * Seek to the right dcache slot and write the in-memory image out to disk.
2999 afs_cellname_write();
3001 afs_osi_Write(afs_cacheInodep,
3002 sizeof(struct fcache) * adc->index +
3003 sizeof(struct afs_fheader), (char *)(&adc->f),
3004 sizeof(struct fcache));
3005 if (code != sizeof(struct fcache))
3013 * Wake up users of a particular file waiting for stores to take
3016 * \param avc Ptr to related vcache entry.
3018 * \note Environment:
3019 * Nothing interesting.
3022 afs_wakeup(register struct vcache *avc)
3025 register struct brequest *tb;
3027 AFS_STATCNT(afs_wakeup);
3028 for (i = 0; i < NBRS; i++, tb++) {
3029 /* if request is valid and for this file, we've found it */
3030 if (tb->refCount > 0 && avc == tb->vc) {
3033 * If CSafeStore is on, then we don't awaken the guy
3034 * waiting for the store until the whole store has finished.
3035 * Otherwise, we do it now. Note that if CSafeStore is on,
3036 * the BStore routine actually wakes up the user, instead
3038 * I think this is redundant now because this sort of thing
3039 * is already being handled by the higher-level code.
3041 if ((avc->f.states & CSafeStore) == 0) {
3043 tb->flags |= BUVALID;
3044 if (tb->flags & BUWAIT) {
3045 tb->flags &= ~BUWAIT;
3057 * Given a file name and inode, set up that file to be an
3058 * active member in the AFS cache. This also involves checking
3059 * the usability of its data.
3061 * \param afile Name of the cache file to initialize.
3062 * \param ainode Inode of the file.
3064 * \note Environment:
3065 * This function is called only during initialization.
3068 afs_InitCacheFile(char *afile, ino_t ainode)
3070 register afs_int32 code;
3073 struct osi_file *tfile;
3074 struct osi_stat tstat;
3075 register struct dcache *tdc;
3077 AFS_STATCNT(afs_InitCacheFile);
3078 index = afs_stats_cmperf.cacheNumEntries;
3079 if (index >= afs_cacheFiles)
3082 MObtainWriteLock(&afs_xdcache, 282);
3083 tdc = afs_GetDSlot(index, NULL);
3084 ReleaseReadLock(&tdc->tlock);
3085 MReleaseWriteLock(&afs_xdcache);
3087 ObtainWriteLock(&tdc->lock, 621);
3088 MObtainWriteLock(&afs_xdcache, 622);
3090 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
3092 ReleaseWriteLock(&afs_xdcache);
3093 ReleaseWriteLock(&tdc->lock);
3098 /* Add any other 'complex' inode types here ... */
3099 #if defined(UKERNEL) || !defined(LINUX_USE_FH)
3100 tdc->f.inode.ufs = ainode;
3102 osi_Panic("Can't init cache with inode numbers when complex inodes are "
3107 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3109 tfile = osi_UFSOpen(&tdc->f.inode);
3110 code = afs_osi_Stat(tfile, &tstat);
3112 osi_Panic("initcachefile stat");
3115 * If file size doesn't match the cache info file, it's probably bad.
3117 if (tdc->f.chunkBytes != tstat.size)
3119 tdc->f.chunkBytes = 0;
3122 * If file changed within T (120?) seconds of cache info file, it's
3123 * probably bad. In addition, if slot changed within last T seconds,
3124 * the cache info file may be incorrectly identified, and so slot
3127 if (cacheInfoModTime < tstat.mtime + 120)
3129 if (cacheInfoModTime < tdc->f.modTime + 120)
3131 /* In case write through is behind, make sure cache items entry is
3132 * at least as new as the chunk.
3134 if (tdc->f.modTime < tstat.mtime)
3137 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3138 if (tstat.size != 0)
3139 osi_UFSTruncate(tfile, 0);
3140 tdc->f.states &= ~(DRO|DBackup|DRW);
3141 afs_DCMoveBucket(tdc, 0, 0);
3142 /* put entry in free cache slot list */
3143 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3144 afs_freeDCList = index;
3146 afs_indexFlags[index] |= IFFree;
3147 afs_indexUnique[index] = 0;
3150 * We must put this entry in the appropriate hash tables.
3151 * Note that i is still set from the above DCHash call
3153 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3154 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3155 afs_dchashTbl[code] = tdc->index;
3156 code = DVHash(&tdc->f.fid);
3157 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3158 afs_dvhashTbl[code] = tdc->index;
3159 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3161 /* has nontrivial amt of data */
3162 afs_indexFlags[index] |= IFEverUsed;
3163 afs_stats_cmperf.cacheFilesReused++;
3165 * Initialize index times to file's mod times; init indexCounter
3168 hset32(afs_indexTimes[index], tstat.atime);
3169 if (hgetlo(afs_indexCounter) < tstat.atime) {
3170 hset32(afs_indexCounter, tstat.atime);
3172 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3173 } /*File is not bad */
3175 osi_UFSClose(tfile);
3176 tdc->f.states &= ~DWriting;
3177 tdc->dflags &= ~DFEntryMod;
3178 /* don't set f.modTime; we're just cleaning up */
3179 afs_WriteDCache(tdc, 0);
3180 ReleaseWriteLock(&afs_xdcache);
3181 ReleaseWriteLock(&tdc->lock);
3183 afs_stats_cmperf.cacheNumEntries++;
3188 /*Max # of struct dcache's resident at any time*/
3190 * If 'dchint' is enabled then in-memory dcache min is increased because of
3196 * Initialize dcache related variables.
3206 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3208 register struct dcache *tdp;
3212 afs_freeDCList = NULLIDX;
3213 afs_discardDCList = NULLIDX;
3214 afs_freeDCCount = 0;
3215 afs_freeDSList = NULL;
3216 hzero(afs_indexCounter);
3218 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3224 if (achunk < 0 || achunk > 30)
3225 achunk = 13; /* Use default */
3226 AFS_SETCHUNKSIZE(achunk);
3232 if (aflags & AFSCALL_INIT_MEMCACHE) {
3234 * Use a memory cache instead of a disk cache
3236 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3237 afs_cacheType = &afs_MemCacheOps;
3238 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3239 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3240 /* ablocks is reported in 1K blocks */
3241 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3243 printf("afsd: memory cache too large for available memory.\n");
3244 printf("afsd: AFS files cannot be accessed.\n\n");
3246 afiles = ablocks = 0;
3248 printf("Memory cache: Allocating %d dcache entries...",
3251 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3252 afs_cacheType = &afs_UfsCacheOps;
3255 if (aDentries > 512)
3256 afs_dhashsize = 2048;
3257 /* initialize hash tables */
3259 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3261 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3262 for (i = 0; i < afs_dhashsize; i++) {
3263 afs_dvhashTbl[i] = NULLIDX;
3264 afs_dchashTbl[i] = NULLIDX;
3266 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3267 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3268 for (i = 0; i < afiles; i++) {
3269 afs_dvnextTbl[i] = NULLIDX;
3270 afs_dcnextTbl[i] = NULLIDX;
3273 /* Allocate and zero the pointer array to the dcache entries */
3274 afs_indexTable = (struct dcache **)
3275 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3276 memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3278 (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3279 memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3281 (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3282 memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3283 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3284 memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
3286 /* Allocate and thread the struct dcache entries themselves */
3287 tdp = afs_Initial_freeDSList =
3288 (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3289 memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
3290 #ifdef KERNEL_HAVE_PIN
3291 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3292 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3293 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3294 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3295 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3296 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3297 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3298 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3299 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3302 afs_freeDSList = &tdp[0];
3303 for (i = 0; i < aDentries - 1; i++) {
3304 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3305 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3306 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3307 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3309 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3310 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3311 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3312 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3314 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3315 afs_cacheBlocks = ablocks;
3316 afs_ComputeCacheParms(); /* compute parms based on cache size */
3318 afs_dcentries = aDentries;
3320 afs_stats_cmperf.cacheBucket0_Discarded =
3321 afs_stats_cmperf.cacheBucket1_Discarded =
3322 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3328 * Shuts down the cache.
3332 shutdown_dcache(void)
3336 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3337 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3338 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3339 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3340 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3341 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3342 afs_osi_Free(afs_Initial_freeDSList,
3343 afs_dcentries * sizeof(struct dcache));
3344 #ifdef KERNEL_HAVE_PIN
3345 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3346 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3347 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3348 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3349 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3350 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3351 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3355 for (i = 0; i < afs_dhashsize; i++) {
3356 afs_dvhashTbl[i] = NULLIDX;
3357 afs_dchashTbl[i] = NULLIDX;
3360 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3361 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3363 afs_blocksUsed = afs_dcentries = 0;
3364 afs_stats_cmperf.cacheBucket0_Discarded =
3365 afs_stats_cmperf.cacheBucket1_Discarded =
3366 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3367 hzero(afs_indexCounter);
3369 afs_freeDCCount = 0;
3370 afs_freeDCList = NULLIDX;
3371 afs_discardDCList = NULLIDX;
3372 afs_freeDSList = afs_Initial_freeDSList = 0;
3374 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3380 * Get a dcache ready for writing, respecting the current cache size limits
3382 * len is required because afs_GetDCache with flag == 4 expects the length
3383 * field to be filled. It decides from this whether it's necessary to fetch
3384 * data into the chunk before writing or not (when the whole chunk is
3387 * \param avc The vcache to fetch a dcache for
3388 * \param filePos The start of the section to be written
3389 * \param len The length of the section to be written
3393 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3394 * must be released and afs_PutDCache() called to free dcache.
3397 * \note avc->lock must be held on entry. Function may release and reobtain
3398 * avc->lock and GLOCK.
3402 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3403 afs_size_t len, struct vrequest *areq,
3405 struct dcache *tdc = NULL;
3408 /* read the cached info */
3410 tdc = afs_FindDCache(avc, filePos);
3412 ObtainWriteLock(&tdc->lock, 657);
3413 } else if (afs_blocksUsed >
3414 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3415 tdc = afs_FindDCache(avc, filePos);
3417 ObtainWriteLock(&tdc->lock, 658);
3418 if (!hsame(tdc->f.versionNo, avc->f.m.DataVersion)
3419 || (tdc->dflags & DFFetching)) {
3420 ReleaseWriteLock(&tdc->lock);
3426 afs_MaybeWakeupTruncateDaemon();
3427 while (afs_blocksUsed >
3428 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3429 ReleaseWriteLock(&avc->lock);
3430 if (afs_blocksUsed - afs_blocksDiscarded >
3431 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3432 afs_WaitForCacheDrain = 1;
3433 afs_osi_Sleep(&afs_WaitForCacheDrain);
3435 afs_MaybeFreeDiscardedDCache();
3436 afs_MaybeWakeupTruncateDaemon();
3437 ObtainWriteLock(&avc->lock, 509);
3439 avc->f.states |= CDirty;
3440 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3442 ObtainWriteLock(&tdc->lock, 659);
3445 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3447 ObtainWriteLock(&tdc->lock, 660);
3450 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3451 afs_stats_cmperf.cacheCurrDirtyChunks++;
3452 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3454 if (!(tdc->f.states & DWriting)) {
3455 /* don't mark entry as mod if we don't have to */
3456 tdc->f.states |= DWriting;
3457 tdc->dflags |= DFEntryMod;
3463 #if defined(AFS_DISCON_ENV)
3466 * Make a shadow copy of a dir's dcache. It's used for disconnected
3467 * operations like remove/create/rename to keep the original directory data.
3468 * On reconnection, we can diff the original data with the server and get the
3469 * server changes and with the local data to get the local changes.
3471 * \param avc The dir vnode.
3472 * \param adc The dir dcache.
3474 * \return 0 for success.
3476 * \note The vcache entry must be write locked.
3477 * \note The dcache entry must be read locked.
3479 int afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3481 int i, code, ret_code = 0, written, trans_size;
3482 struct dcache *new_dc = NULL;
3483 struct osi_file *tfile_src, *tfile_dst;
3484 struct VenusFid shadow_fid;
3487 /* Is this a dir? */
3488 if (vType(avc) != VDIR)
3491 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3494 /* Generate a fid for the shadow dir. */
3495 shadow_fid.Cell = avc->f.fid.Cell;
3496 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3497 afs_GenShadowFid(&shadow_fid);
3499 ObtainWriteLock(&afs_xdcache, 716);