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(int anumber, int *aneedSpace, afs_int32 buckethint);
27 static void afs_FreeDiscardedDCache(void);
28 static void afs_DiscardDCache(struct dcache *);
29 static void afs_FreeDCache(struct dcache *);
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);
38 * --------------------- Exported definitions ---------------------
41 afs_int32 afs_blocksUsed_0; /*!< 1K blocks in cache - in theory is zero */
42 afs_int32 afs_blocksUsed_1; /*!< 1K blocks in cache */
43 afs_int32 afs_blocksUsed_2; /*!< 1K blocks in cache */
44 afs_int32 afs_pct1 = -1;
45 afs_int32 afs_pct2 = -1;
46 afs_uint32 afs_tpct1 = 0;
47 afs_uint32 afs_tpct2 = 0;
48 afs_uint32 splitdcache = 0;
50 afs_lock_t afs_xdcache; /*!< Lock: alloc new disk cache entries */
51 afs_int32 afs_freeDCList; /*!< Free list for disk cache entries */
52 afs_int32 afs_freeDCCount; /*!< Count of elts in freeDCList */
53 afs_int32 afs_discardDCList; /*!< Discarded disk cache entries */
54 afs_int32 afs_discardDCCount; /*!< Count of elts in discardDCList */
55 struct dcache *afs_freeDSList; /*!< Free list for disk slots */
56 struct dcache *afs_Initial_freeDSList; /*!< Initial list for above */
57 ino_t cacheInode; /*!< Inode for CacheItems file */
58 struct osi_file *afs_cacheInodep = 0; /*!< file for CacheItems inode */
59 struct afs_q afs_DLRU; /*!< dcache LRU */
60 afs_int32 afs_dhashsize = 1024;
61 afs_int32 *afs_dvhashTbl; /*!< Data cache hash table: hashed by FID + chunk number. */
62 afs_int32 *afs_dchashTbl; /*!< Data cache hash table: hashed by FID. */
63 afs_int32 *afs_dvnextTbl; /*!< Dcache hash table links */
64 afs_int32 *afs_dcnextTbl; /*!< Dcache hash table links */
65 struct dcache **afs_indexTable; /*!< Pointers to dcache entries */
66 afs_hyper_t *afs_indexTimes; /*!< Dcache entry Access times */
67 afs_int32 *afs_indexUnique; /*!< dcache entry Fid.Unique */
68 unsigned char *afs_indexFlags; /*!< (only one) Is there data there? */
69 afs_hyper_t afs_indexCounter; /*!< Fake time for marking index
71 afs_int32 afs_cacheFiles = 0; /*!< Size of afs_indexTable */
72 afs_int32 afs_cacheBlocks; /*!< 1K blocks in cache */
73 afs_int32 afs_cacheStats; /*!< Stat entries in cache */
74 afs_int32 afs_blocksUsed; /*!< Number of blocks in use */
75 afs_int32 afs_blocksDiscarded; /*!<Blocks freed but not truncated */
76 afs_int32 afs_fsfragsize = 1023; /*!< Underlying Filesystem minimum unit
77 *of disk allocation usually 1K
78 *this value is (truefrag -1 ) to
79 *save a bunch of subtracts... */
80 #ifdef AFS_64BIT_CLIENT
81 #ifdef AFS_VM_RDWR_ENV
82 afs_size_t afs_vmMappingEnd; /* !< For large files (>= 2GB) the VM
83 * mapping an 32bit addressing machines
84 * can only be used below the 2 GB
85 * line. From this point upwards we
86 * must do direct I/O into the cache
87 * files. The value should be on a
89 #endif /* AFS_VM_RDWR_ENV */
90 #endif /* AFS_64BIT_CLIENT */
92 /* The following is used to ensure that new dcache's aren't obtained when
93 * the cache is nearly full.
95 int afs_WaitForCacheDrain = 0;
96 int afs_TruncateDaemonRunning = 0;
97 int afs_CacheTooFull = 0;
99 afs_int32 afs_dcentries; /*!< In-memory dcache entries */
102 int dcacheDisabled = 0;
104 static int afs_UFSCacheFetchProc(), afs_UFSCacheStoreProc();
105 struct afs_cacheOps afs_UfsCacheOps = {
113 afs_UFSCacheFetchProc,
114 afs_UFSCacheStoreProc,
120 struct afs_cacheOps afs_MemCacheOps = {
122 afs_MemCacheTruncate,
128 afs_MemCacheFetchProc,
129 afs_MemCacheStoreProc,
135 int cacheDiskType; /*Type of backing disk for cache */
136 struct afs_cacheOps *afs_cacheType;
139 * Where is this vcache's entry associated dcache located/
140 * \param avc The vcache entry.
141 * \return Bucket index:
146 afs_DCGetBucket(struct vcache *avc)
151 /* This should be replaced with some sort of user configurable function */
152 if (avc->states & CRO) {
154 } else if (avc->states & CBackup) {
164 * Readjust a dcache's size.
166 * \param adc The dcache to be adjusted.
167 * \param oldSize Old size for the dcache.
168 * \param newSize The new size to be adjusted to.
172 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
174 afs_int32 adjustSize = newSize - oldSize;
182 afs_blocksUsed_0 += adjustSize;
183 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
186 afs_blocksUsed_1 += adjustSize;
187 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
190 afs_blocksUsed_2 += adjustSize;
191 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
199 * Move a dcache from one bucket to another.
201 * \param adc Operate on this dcache.
202 * \param size Size in bucket (?).
203 * \param newBucket Destination bucket.
207 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
212 /* Substract size from old bucket. */
216 afs_blocksUsed_0 -= size;
219 afs_blocksUsed_1 -= size;
222 afs_blocksUsed_2 -= size;
226 /* Set new bucket and increase destination bucket size. */
227 adc->bucket = newBucket;
232 afs_blocksUsed_0 += size;
235 afs_blocksUsed_1 += size;
238 afs_blocksUsed_2 += size;
246 * Init split caches size.
251 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
260 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
265 afs_pct1 = afs_blocksUsed_1 / (afs_cacheBlocks / 100);
266 afs_pct2 = afs_blocksUsed_2 / (afs_cacheBlocks / 100);
268 /* Short cut: if we don't know about it, try to kill it */
269 if (phase < 2 && afs_blocksUsed_0)
272 if (afs_pct1 > afs_tpct1)
274 if (afs_pct2 > afs_tpct2)
276 return 0; /* unlikely */
281 * Warn about failing to store a file.
283 * \param acode Associated error code.
284 * \param avolume Volume involved.
285 * \param aflags How to handle the output:
286 * aflags & 1: Print out on console
287 * aflags & 2: Print out on controlling tty
289 * \note Environment: Call this from close call when vnodeops is RCS unlocked.
293 afs_StoreWarn(register afs_int32 acode, afs_int32 avolume,
294 register afs_int32 aflags)
296 static char problem_fmt[] =
297 "afs: failed to store file in volume %d (%s)\n";
298 static char problem_fmt_w_error[] =
299 "afs: failed to store file in volume %d (error %d)\n";
300 static char netproblems[] = "network problems";
301 static char partfull[] = "partition full";
302 static char overquota[] = "over quota";
304 AFS_STATCNT(afs_StoreWarn);
310 afs_warn(problem_fmt, avolume, netproblems);
312 afs_warnuser(problem_fmt, avolume, netproblems);
313 } else if (acode == ENOSPC) {
318 afs_warn(problem_fmt, avolume, partfull);
320 afs_warnuser(problem_fmt, avolume, partfull);
323 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
324 * Instead ENOSPC will be sent...
326 if (acode == EDQUOT) {
331 afs_warn(problem_fmt, avolume, overquota);
333 afs_warnuser(problem_fmt, avolume, overquota);
341 afs_warn(problem_fmt_w_error, avolume, acode);
343 afs_warnuser(problem_fmt_w_error, avolume, acode);
348 * Try waking up truncation daemon, if it's worth it.
351 afs_MaybeWakeupTruncateDaemon(void)
353 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
354 afs_CacheTooFull = 1;
355 if (!afs_TruncateDaemonRunning)
356 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
357 } else if (!afs_TruncateDaemonRunning
358 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
359 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
366 * Keep statistics on run time for afs_CacheTruncateDaemon. This is a
367 * struct so we need only export one symbol for AIX.
369 static struct CTD_stats {
370 osi_timeval_t CTD_beforeSleep;
371 osi_timeval_t CTD_afterSleep;
372 osi_timeval_t CTD_sleepTime;
373 osi_timeval_t CTD_runTime;
377 u_int afs_min_cache = 0;
380 * Keeps the cache clean and free by truncating uneeded files, when used.
385 afs_CacheTruncateDaemon(void)
387 osi_timeval_t CTD_tmpTime;
391 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
393 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
395 osi_GetuTime(&CTD_stats.CTD_afterSleep);
396 afs_TruncateDaemonRunning = 1;
398 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
399 MObtainWriteLock(&afs_xdcache, 266);
400 if (afs_CacheTooFull) {
401 int space_needed, slots_needed;
402 /* if we get woken up, we should try to clean something out */
403 for (counter = 0; counter < 10; counter++) {
405 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
407 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
408 afs_GetDownD(slots_needed, &space_needed, 0);
409 if ((space_needed <= 0) && (slots_needed <= 0)) {
412 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
415 if (!afs_CacheIsTooFull())
416 afs_CacheTooFull = 0;
417 } /* end of cache cleanup */
418 MReleaseWriteLock(&afs_xdcache);
421 * This is a defensive check to try to avoid starving threads
422 * that may need the global lock so thay can help free some
423 * cache space. If this thread won't be sleeping or truncating
424 * any cache files then give up the global lock so other
425 * threads get a chance to run.
427 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
428 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
429 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
433 * This is where we free the discarded cache elements.
435 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
436 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
437 afs_FreeDiscardedDCache();
440 /* See if we need to continue to run. Someone may have
441 * signalled us while we were executing.
443 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
444 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
445 /* Collect statistics on truncate daemon. */
446 CTD_stats.CTD_nSleeps++;
447 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
448 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
449 CTD_stats.CTD_beforeSleep);
450 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
452 afs_TruncateDaemonRunning = 0;
453 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
454 afs_TruncateDaemonRunning = 1;
456 osi_GetuTime(&CTD_stats.CTD_afterSleep);
457 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
458 CTD_stats.CTD_afterSleep);
459 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
461 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
463 afs_termState = AFSOP_STOP_AFSDB;
465 afs_termState = AFSOP_STOP_RXEVENT;
467 afs_osi_Wakeup(&afs_termState);
475 * Make adjustment for the new size in the disk cache entry
477 * \note Major Assumptions Here:
478 * Assumes that frag size is an integral power of two, less one,
479 * and that this is a two's complement machine. I don't
480 * know of any filesystems which violate this assumption...
482 * \param adc Ptr to dcache entry.
483 * \param anewsize New size desired.
488 afs_AdjustSize(register struct dcache *adc, register afs_int32 newSize)
490 register afs_int32 oldSize;
492 AFS_STATCNT(afs_AdjustSize);
494 adc->dflags |= DFEntryMod;
495 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
496 adc->f.chunkBytes = newSize;
499 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
500 afs_DCAdjustSize(adc, oldSize, newSize);
501 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
503 /* We're growing the file, wakeup the daemon */
504 afs_MaybeWakeupTruncateDaemon();
506 afs_blocksUsed += (newSize - oldSize);
507 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
512 * This routine is responsible for moving at least one entry (but up
513 * to some number of them) from the LRU queue to the free queue.
515 * \param anumber Number of entries that should ideally be moved.
516 * \param aneedSpace How much space we need (1K blocks);
519 * The anumber parameter is just a hint; at least one entry MUST be
520 * moved, or we'll panic. We must be called with afs_xdcache
521 * write-locked. We should try to satisfy both anumber and aneedspace,
522 * whichever is more demanding - need to do several things:
523 * 1. only grab up to anumber victims if aneedSpace <= 0, not
524 * the whole set of MAXATONCE.
525 * 2. dynamically choose MAXATONCE to reflect severity of
526 * demand: something like (*aneedSpace >> (logChunk - 9))
528 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
529 * indicates that the cache is not properly configured/tuned or
530 * something. We should be able to automatically correct that problem.
533 #define MAXATONCE 16 /* max we can obtain at once */
535 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
539 struct VenusFid *afid;
543 register struct vcache *tvc;
544 afs_uint32 victims[MAXATONCE];
545 struct dcache *victimDCs[MAXATONCE];
546 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
547 afs_uint32 victimPtr; /* next free item in victim arrays */
548 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
549 afs_uint32 maxVictimPtr; /* where it is */
554 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
555 vfslocked = VFS_LOCK_GIANT(afs_globalVFS);
558 AFS_STATCNT(afs_GetDownD);
560 if (CheckLock(&afs_xdcache) != -1)
561 osi_Panic("getdownd nolock");
562 /* decrement anumber first for all dudes in free list */
563 /* SHOULD always decrement anumber first, even if aneedSpace >0,
564 * because we should try to free space even if anumber <=0 */
565 if (!aneedSpace || *aneedSpace <= 0) {
566 anumber -= afs_freeDCCount;
568 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
569 VFS_UNLOCK_GIANT(vfslocked);
571 return; /* enough already free */
575 /* bounds check parameter */
576 if (anumber > MAXATONCE)
577 anumber = MAXATONCE; /* all we can do */
579 /* rewrite so phases include a better eligiblity for gc test*/
581 * The phase variable manages reclaims. Set to 0, the first pass,
582 * we don't reclaim active entries, or other than target bucket.
583 * Set to 1, we reclaim even active ones in target bucket.
584 * Set to 2, we reclaim any inactive one.
585 * Set to 3, we reclaim even active ones.
593 for (i = 0; i < afs_cacheFiles; i++)
594 /* turn off all flags */
595 afs_indexFlags[i] &= ~IFFlag;
597 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
598 /* find oldest entries for reclamation */
599 maxVictimPtr = victimPtr = 0;
600 hzero(maxVictimTime);
601 curbucket = afs_DCWhichBucket(phase, buckethint);
602 /* select victims from access time array */
603 for (i = 0; i < afs_cacheFiles; i++) {
604 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
605 /* skip if dirty or already free */
608 tdc = afs_indexTable[i];
609 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
611 /* Wrong bucket; can't use it! */
614 if (tdc && (tdc->refCount != 0)) {
615 /* Referenced; can't use it! */
618 hset(vtime, afs_indexTimes[i]);
620 /* if we've already looked at this one, skip it */
621 if (afs_indexFlags[i] & IFFlag)
624 if (victimPtr < MAXATONCE) {
625 /* if there's at least one free victim slot left */
626 victims[victimPtr] = i;
627 hset(victimTimes[victimPtr], vtime);
628 if (hcmp(vtime, maxVictimTime) > 0) {
629 hset(maxVictimTime, vtime);
630 maxVictimPtr = victimPtr;
633 } else if (hcmp(vtime, maxVictimTime) < 0) {
635 * We're older than youngest victim, so we replace at
638 /* find youngest (largest LRU) victim */
641 osi_Panic("getdownd local");
643 hset(victimTimes[j], vtime);
644 /* recompute maxVictimTime */
645 hset(maxVictimTime, vtime);
646 for (j = 0; j < victimPtr; j++)
647 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
648 hset(maxVictimTime, victimTimes[j]);
654 /* now really reclaim the victims */
655 j = 0; /* flag to track if we actually got any of the victims */
656 /* first, hold all the victims, since we're going to release the lock
657 * during the truncate operation.
659 for (i = 0; i < victimPtr; i++) {
660 tdc = afs_GetDSlot(victims[i], 0);
661 /* We got tdc->tlock(R) here */
662 if (tdc->refCount == 1)
666 ReleaseReadLock(&tdc->tlock);
670 for (i = 0; i < victimPtr; i++) {
671 /* q is first elt in dcache entry */
673 /* now, since we're dropping the afs_xdcache lock below, we
674 * have to verify, before proceeding, that there are no other
675 * references to this dcache entry, even now. Note that we
676 * compare with 1, since we bumped it above when we called
677 * afs_GetDSlot to preserve the entry's identity.
679 if (tdc && tdc->refCount == 1) {
680 unsigned char chunkFlags;
681 afs_size_t tchunkoffset = 0;
683 /* xdcache is lower than the xvcache lock */
684 MReleaseWriteLock(&afs_xdcache);
685 MObtainReadLock(&afs_xvcache);
686 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
687 MReleaseReadLock(&afs_xvcache);
688 MObtainWriteLock(&afs_xdcache, 527);
690 if (tdc->refCount > 1)
693 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
694 chunkFlags = afs_indexFlags[tdc->index];
695 if (((phase & 1) == 0) && osi_Active(tvc))
697 if (((phase & 1) == 1) && osi_Active(tvc)
698 && (tvc->states & CDCLock)
699 && (chunkFlags & IFAnyPages))
701 if (chunkFlags & IFDataMod)
703 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
704 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
705 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
706 ICL_HANDLE_OFFSET(tchunkoffset));
708 #if defined(AFS_SUN5_ENV)
710 * Now we try to invalidate pages. We do this only for
711 * Solaris. For other platforms, it's OK to recycle a
712 * dcache entry out from under a page, because the strategy
713 * function can call afs_GetDCache().
715 if (!skip && (chunkFlags & IFAnyPages)) {
718 MReleaseWriteLock(&afs_xdcache);
719 MObtainWriteLock(&tvc->vlock, 543);
720 if (tvc->multiPage) {
724 /* block locking pages */
725 tvc->vstates |= VPageCleaning;
726 /* block getting new pages */
728 MReleaseWriteLock(&tvc->vlock);
729 /* One last recheck */
730 MObtainWriteLock(&afs_xdcache, 333);
731 chunkFlags = afs_indexFlags[tdc->index];
732 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
733 || (osi_Active(tvc) && (tvc->states & CDCLock)
734 && (chunkFlags & IFAnyPages))) {
736 MReleaseWriteLock(&afs_xdcache);
739 MReleaseWriteLock(&afs_xdcache);
741 code = osi_VM_GetDownD(tvc, tdc);
743 MObtainWriteLock(&afs_xdcache, 269);
744 /* we actually removed all pages, clean and dirty */
746 afs_indexFlags[tdc->index] &=
747 ~(IFDirtyPages | IFAnyPages);
750 MReleaseWriteLock(&afs_xdcache);
752 MObtainWriteLock(&tvc->vlock, 544);
753 if (--tvc->activeV == 0
754 && (tvc->vstates & VRevokeWait)) {
755 tvc->vstates &= ~VRevokeWait;
756 afs_osi_Wakeup((char *)&tvc->vstates);
759 if (tvc->vstates & VPageCleaning) {
760 tvc->vstates &= ~VPageCleaning;
761 afs_osi_Wakeup((char *)&tvc->vstates);
764 MReleaseWriteLock(&tvc->vlock);
766 #endif /* AFS_SUN5_ENV */
768 MReleaseWriteLock(&afs_xdcache);
771 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
772 MObtainWriteLock(&afs_xdcache, 528);
773 if (afs_indexFlags[tdc->index] &
774 (IFDataMod | IFDirtyPages | IFAnyPages))
776 if (tdc->refCount > 1)
779 #if defined(AFS_SUN5_ENV)
781 /* no vnode, so IFDirtyPages is spurious (we don't
782 * sweep dcaches on vnode recycling, so we can have
783 * DIRTYPAGES set even when all pages are gone). Just
785 * Hold vcache lock to prevent vnode from being
786 * created while we're clearing IFDirtyPages.
788 afs_indexFlags[tdc->index] &=
789 ~(IFDirtyPages | IFAnyPages);
793 /* skip this guy and mark him as recently used */
794 afs_indexFlags[tdc->index] |= IFFlag;
795 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
796 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
797 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
798 ICL_HANDLE_OFFSET(tchunkoffset));
800 /* flush this dude from the data cache and reclaim;
801 * first, make sure no one will care that we damage
802 * it, by removing it from all hash tables. Then,
803 * melt it down for parts. Note that any concurrent
804 * (new possibility!) calls to GetDownD won't touch
805 * this guy because his reference count is > 0. */
806 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
807 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
808 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
809 ICL_HANDLE_OFFSET(tchunkoffset));
810 AFS_STATCNT(afs_gget);
811 afs_HashOutDCache(tdc, 1);
812 if (tdc->f.chunkBytes != 0) {
816 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
821 afs_DiscardDCache(tdc);
826 j = 1; /* we reclaimed at least one victim */
830 } /* end of for victims loop */
833 /* Phase is 0 and no one was found, so try phase 1 (ignore
834 * osi_Active flag) */
837 for (i = 0; i < afs_cacheFiles; i++)
838 /* turn off all flags */
839 afs_indexFlags[i] &= ~IFFlag;
842 /* found no one in phases 0-5, we're hosed */
846 } /* big while loop */
848 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
849 VFS_UNLOCK_GIANT(vfslocked);
858 * Remove adc from any hash tables that would allow it to be located
859 * again by afs_FindDCache or afs_GetDCache.
861 * \param adc Pointer to dcache entry to remove from hash tables.
863 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
867 afs_HashOutDCache(struct dcache *adc, int zap)
871 AFS_STATCNT(afs_glink);
873 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
875 /* if this guy is in the hash table, pull him out */
876 if (adc->f.fid.Fid.Volume != 0) {
877 /* remove entry from first hash chains */
878 i = DCHash(&adc->f.fid, adc->f.chunk);
879 us = afs_dchashTbl[i];
880 if (us == adc->index) {
881 /* first dude in the list */
882 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
884 /* somewhere on the chain */
885 while (us != NULLIDX) {
886 if (afs_dcnextTbl[us] == adc->index) {
887 /* found item pointing at the one to delete */
888 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
891 us = afs_dcnextTbl[us];
894 osi_Panic("dcache hc");
896 /* remove entry from *other* hash chain */
897 i = DVHash(&adc->f.fid);
898 us = afs_dvhashTbl[i];
899 if (us == adc->index) {
900 /* first dude in the list */
901 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
903 /* somewhere on the chain */
904 while (us != NULLIDX) {
905 if (afs_dvnextTbl[us] == adc->index) {
906 /* found item pointing at the one to delete */
907 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
910 us = afs_dvnextTbl[us];
913 osi_Panic("dcache hv");
918 /* prevent entry from being found on a reboot (it is already out of
919 * the hash table, but after a crash, we just look at fid fields of
920 * stable (old) entries).
922 adc->f.fid.Fid.Volume = 0; /* invalid */
924 /* mark entry as modified */
925 adc->dflags |= DFEntryMod;
930 } /*afs_HashOutDCache */
933 * Flush the given dcache entry, pulling it from hash chains
934 * and truncating the associated cache file.
936 * \param adc Ptr to dcache entry to flush.
939 * This routine must be called with the afs_xdcache lock held
943 afs_FlushDCache(register struct dcache *adc)
945 AFS_STATCNT(afs_FlushDCache);
947 * Bump the number of cache files flushed.
949 afs_stats_cmperf.cacheFlushes++;
951 /* remove from all hash tables */
952 afs_HashOutDCache(adc, 1);
954 /* Free its space; special case null operation, since truncate operation
955 * in UFS is slow even in this case, and this allows us to pre-truncate
956 * these files at more convenient times with fewer locks set
957 * (see afs_GetDownD).
959 if (adc->f.chunkBytes != 0) {
960 afs_DiscardDCache(adc);
961 afs_MaybeWakeupTruncateDaemon();
966 if (afs_WaitForCacheDrain) {
967 if (afs_blocksUsed <=
968 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
969 afs_WaitForCacheDrain = 0;
970 afs_osi_Wakeup(&afs_WaitForCacheDrain);
973 } /*afs_FlushDCache */
977 * Put a dcache entry on the free dcache entry list.
979 * \param adc dcache entry to free.
981 * \note Environment: called with afs_xdcache lock write-locked.
984 afs_FreeDCache(register struct dcache *adc)
986 /* Thread on free list, update free list count and mark entry as
987 * freed in its indexFlags element. Also, ensure DCache entry gets
988 * written out (set DFEntryMod).
991 afs_dvnextTbl[adc->index] = afs_freeDCList;
992 afs_freeDCList = adc->index;
994 afs_indexFlags[adc->index] |= IFFree;
995 adc->dflags |= DFEntryMod;
997 if (afs_WaitForCacheDrain) {
998 if ((afs_blocksUsed - afs_blocksDiscarded) <=
999 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1000 afs_WaitForCacheDrain = 0;
1001 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1004 } /* afs_FreeDCache */
1007 * Discard the cache element by moving it to the discardDCList.
1008 * This puts the cache element into a quasi-freed state, where
1009 * the space may be reused, but the file has not been truncated.
1011 * \note Major Assumptions Here:
1012 * Assumes that frag size is an integral power of two, less one,
1013 * and that this is a two's complement machine. I don't
1014 * know of any filesystems which violate this assumption...
1016 * \param adr Ptr to dcache entry.
1018 * \note Environment:
1019 * Must be called with afs_xdcache write-locked.
1023 afs_DiscardDCache(register struct dcache *adc)
1025 register afs_int32 size;
1027 AFS_STATCNT(afs_DiscardDCache);
1029 osi_Assert(adc->refCount == 1);
1031 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1032 afs_blocksDiscarded += size;
1033 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1035 afs_dvnextTbl[adc->index] = afs_discardDCList;
1036 afs_discardDCList = adc->index;
1037 afs_discardDCCount++;
1039 adc->f.fid.Fid.Volume = 0;
1040 adc->dflags |= DFEntryMod;
1041 afs_indexFlags[adc->index] |= IFDiscarded;
1043 if (afs_WaitForCacheDrain) {
1044 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1045 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1046 afs_WaitForCacheDrain = 0;
1047 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1051 } /*afs_DiscardDCache */
1054 * Free the next element on the list of discarded cache elements.
1057 afs_FreeDiscardedDCache(void)
1059 register struct dcache *tdc;
1060 register struct osi_file *tfile;
1061 register afs_int32 size;
1063 AFS_STATCNT(afs_FreeDiscardedDCache);
1065 MObtainWriteLock(&afs_xdcache, 510);
1066 if (!afs_blocksDiscarded) {
1067 MReleaseWriteLock(&afs_xdcache);
1072 * Get an entry from the list of discarded cache elements
1074 tdc = afs_GetDSlot(afs_discardDCList, 0);
1075 osi_Assert(tdc->refCount == 1);
1076 ReleaseReadLock(&tdc->tlock);
1078 afs_discardDCList = afs_dvnextTbl[tdc->index];
1079 afs_dvnextTbl[tdc->index] = NULLIDX;
1080 afs_discardDCCount--;
1081 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1082 afs_blocksDiscarded -= size;
1083 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1084 /* We can lock because we just took it off the free list */
1085 ObtainWriteLock(&tdc->lock, 626);
1086 MReleaseWriteLock(&afs_xdcache);
1089 * Truncate the element to reclaim its space
1091 tfile = afs_CFileOpen(tdc->f.inode);
1092 afs_CFileTruncate(tfile, 0);
1093 afs_CFileClose(tfile);
1094 afs_AdjustSize(tdc, 0);
1095 afs_DCMoveBucket(tdc, 0, 0);
1098 * Free the element we just truncated
1100 MObtainWriteLock(&afs_xdcache, 511);
1101 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1102 afs_FreeDCache(tdc);
1103 tdc->f.states &= ~(DRO|DBackup|DRW);
1104 ReleaseWriteLock(&tdc->lock);
1106 MReleaseWriteLock(&afs_xdcache);
1110 * Free as many entries from the list of discarded cache elements
1111 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1116 afs_MaybeFreeDiscardedDCache(void)
1119 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1121 while (afs_blocksDiscarded
1122 && (afs_blocksUsed >
1123 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1124 afs_FreeDiscardedDCache();
1130 * Try to free up a certain number of disk slots.
1132 * \param anumber Targeted number of disk slots to free up.
1134 * \note Environment:
1135 * Must be called with afs_xdcache write-locked.
1139 afs_GetDownDSlot(int anumber)
1141 struct afs_q *tq, *nq;
1146 AFS_STATCNT(afs_GetDownDSlot);
1147 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1148 osi_Panic("diskless getdowndslot");
1150 if (CheckLock(&afs_xdcache) != -1)
1151 osi_Panic("getdowndslot nolock");
1153 /* decrement anumber first for all dudes in free list */
1154 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1157 return; /* enough already free */
1159 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1161 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1162 nq = QPrev(tq); /* in case we remove it */
1163 if (tdc->refCount == 0) {
1164 if ((ix = tdc->index) == NULLIDX)
1165 osi_Panic("getdowndslot");
1166 /* pull the entry out of the lruq and put it on the free list */
1167 QRemove(&tdc->lruq);
1169 /* write-through if modified */
1170 if (tdc->dflags & DFEntryMod) {
1171 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1173 * ask proxy to do this for us - we don't have the stack space
1175 while (tdc->dflags & DFEntryMod) {
1178 s = SPLOCK(afs_sgibklock);
1179 if (afs_sgibklist == NULL) {
1180 /* if slot is free, grab it. */
1181 afs_sgibklist = tdc;
1182 SV_SIGNAL(&afs_sgibksync);
1184 /* wait for daemon to (start, then) finish. */
1185 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1189 tdc->dflags &= ~DFEntryMod;
1190 afs_WriteDCache(tdc, 1);
1194 /* finally put the entry in the free list */
1195 afs_indexTable[ix] = NULL;
1196 afs_indexFlags[ix] &= ~IFEverUsed;
1197 tdc->index = NULLIDX;
1198 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1199 afs_freeDSList = tdc;
1203 } /*afs_GetDownDSlot */
1210 * Increment the reference count on a disk cache entry,
1211 * which already has a non-zero refcount. In order to
1212 * increment the refcount of a zero-reference entry, you
1213 * have to hold afs_xdcache.
1216 * adc : Pointer to the dcache entry to increment.
1219 * Nothing interesting.
1222 afs_RefDCache(struct dcache *adc)
1224 ObtainWriteLock(&adc->tlock, 627);
1225 if (adc->refCount < 0)
1226 osi_Panic("RefDCache: negative refcount");
1228 ReleaseWriteLock(&adc->tlock);
1237 * Decrement the reference count on a disk cache entry.
1240 * ad : Ptr to the dcache entry to decrement.
1243 * Nothing interesting.
1246 afs_PutDCache(register struct dcache *adc)
1248 AFS_STATCNT(afs_PutDCache);
1249 ObtainWriteLock(&adc->tlock, 276);
1250 if (adc->refCount <= 0)
1251 osi_Panic("putdcache");
1253 ReleaseWriteLock(&adc->tlock);
1262 * Try to discard all data associated with this file from the
1266 * avc : Pointer to the cache info for the file.
1269 * Both pvnLock and lock are write held.
1272 afs_TryToSmush(register struct vcache *avc, struct AFS_UCRED *acred, int sync)
1274 register struct dcache *tdc;
1277 AFS_STATCNT(afs_TryToSmush);
1278 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1279 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->m.Length));
1280 sync = 1; /* XX Temp testing XX */
1282 #if defined(AFS_SUN5_ENV)
1283 ObtainWriteLock(&avc->vlock, 573);
1284 avc->activeV++; /* block new getpages */
1285 ReleaseWriteLock(&avc->vlock);
1288 /* Flush VM pages */
1289 osi_VM_TryToSmush(avc, acred, sync);
1292 * Get the hash chain containing all dce's for this fid
1294 i = DVHash(&avc->fid);
1295 MObtainWriteLock(&afs_xdcache, 277);
1296 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1297 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1298 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1299 int releaseTlock = 1;
1300 tdc = afs_GetDSlot(index, NULL);
1301 if (!FidCmp(&tdc->f.fid, &avc->fid)) {
1303 if ((afs_indexFlags[index] & IFDataMod) == 0
1304 && tdc->refCount == 1) {
1305 ReleaseReadLock(&tdc->tlock);
1307 afs_FlushDCache(tdc);
1310 afs_indexTable[index] = 0;
1313 ReleaseReadLock(&tdc->tlock);
1317 #if defined(AFS_SUN5_ENV)
1318 ObtainWriteLock(&avc->vlock, 545);
1319 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1320 avc->vstates &= ~VRevokeWait;
1321 afs_osi_Wakeup((char *)&avc->vstates);
1323 ReleaseWriteLock(&avc->vlock);
1325 MReleaseWriteLock(&afs_xdcache);
1327 * It's treated like a callback so that when we do lookups we'll
1328 * invalidate the unique bit if any
1329 * trytoSmush occured during the lookup call
1335 * afs_DCacheMissingChunks
1338 * Given the cached info for a file, return the number of chunks that
1339 * are not available from the dcache.
1342 * avc: Pointer to the (held) vcache entry to look in.
1345 * The number of chunks which are not currently cached.
1348 * The vcache entry is held upon entry.
1352 afs_DCacheMissingChunks(struct vcache *avc)
1355 afs_size_t totalLength = 0;
1356 afs_uint32 totalChunks = 0;
1359 totalLength = avc->m.Length;
1360 if (avc->truncPos < totalLength)
1361 totalLength = avc->truncPos;
1363 /* Length is 0, no chunk missing. */
1364 if (totalLength == 0)
1367 /* If totalLength is a multiple of chunksize, the last byte appears
1368 * as being part of the next chunk, which does not exist.
1369 * Decrementing totalLength by one fixes that.
1372 totalChunks = (AFS_CHUNK(totalLength) + 1);
1375 printf("Should have %d chunks for %u bytes\n",
1376 totalChunks, (totalLength + 1));
1378 i = DVHash(&avc->fid);
1379 MObtainWriteLock(&afs_xdcache, 1001);
1380 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1381 i = afs_dvnextTbl[index];
1382 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1383 tdc = afs_GetDSlot(index, NULL);
1384 if (!FidCmp(&tdc->f.fid, &avc->fid)) {
1387 ReleaseReadLock(&tdc->tlock);
1391 MReleaseWriteLock(&afs_xdcache);
1393 /*printf("Missing %d chunks\n", totalChunks);*/
1395 return (totalChunks);
1402 * Given the cached info for a file and a byte offset into the
1403 * file, make sure the dcache entry for that file and containing
1404 * the given byte is available, returning it to our caller.
1407 * avc : Pointer to the (held) vcache entry to look in.
1408 * abyte : Which byte we want to get to.
1411 * Pointer to the dcache entry covering the file & desired byte,
1412 * or NULL if not found.
1415 * The vcache entry is held upon entry.
1419 afs_FindDCache(register struct vcache *avc, afs_size_t abyte)
1422 register afs_int32 i, index;
1423 register struct dcache *tdc = NULL;
1425 AFS_STATCNT(afs_FindDCache);
1426 chunk = AFS_CHUNK(abyte);
1429 * Hash on the [fid, chunk] and get the corresponding dcache index
1430 * after write-locking the dcache.
1432 i = DCHash(&avc->fid, chunk);
1433 MObtainWriteLock(&afs_xdcache, 278);
1434 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1435 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1436 tdc = afs_GetDSlot(index, NULL);
1437 ReleaseReadLock(&tdc->tlock);
1438 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1439 break; /* leaving refCount high for caller */
1443 index = afs_dcnextTbl[index];
1445 if (index != NULLIDX) {
1446 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1447 hadd32(afs_indexCounter, 1);
1448 MReleaseWriteLock(&afs_xdcache);
1451 MReleaseWriteLock(&afs_xdcache);
1453 } /*afs_FindDCache */
1457 * afs_UFSCacheStoreProc
1460 * Called upon store.
1463 * acall : Ptr to the Rx call structure involved.
1464 * afile : Ptr to the related file descriptor.
1465 * alen : Size of the file in bytes.
1466 * avc : Ptr to the vcache entry.
1467 * shouldWake : is it "safe" to return early from close() ?
1468 * abytesToXferP : Set to the number of bytes to xfer.
1469 * NOTE: This parameter is only used if AFS_NOSTATS
1471 * abytesXferredP : Set to the number of bytes actually xferred.
1472 * NOTE: This parameter is only used if AFS_NOSTATS
1476 * Nothing interesting.
1479 afs_UFSCacheStoreProc(register struct rx_call *acall, struct osi_file *afile,
1480 register afs_int32 alen, struct vcache *avc,
1481 int *shouldWake, afs_size_t * abytesToXferP,
1482 afs_size_t * abytesXferredP)
1484 afs_int32 code, got;
1485 register char *tbuffer;
1488 AFS_STATCNT(UFS_CacheStoreProc);
1492 * In this case, alen is *always* the amount of data we'll be trying
1495 (*abytesToXferP) = alen;
1496 (*abytesXferredP) = 0;
1497 #endif /* AFS_NOSTATS */
1499 afs_Trace4(afs_iclSetp, CM_TRACE_STOREPROC, ICL_TYPE_POINTER, avc,
1500 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
1501 ICL_HANDLE_OFFSET(avc->m.Length), ICL_TYPE_INT32, alen);
1502 tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1504 tlen = (alen > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : alen);
1505 got = afs_osi_Read(afile, -1, tbuffer, tlen);
1507 #if defined(KERNEL_HAVE_UERROR)
1508 || (got != tlen && getuerror())
1511 osi_FreeLargeSpace(tbuffer);
1514 afs_Trace2(afs_iclSetp, CM_TRACE_STOREPROC2, ICL_TYPE_OFFSET,
1515 ICL_HANDLE_OFFSET(*tbuffer), ICL_TYPE_INT32, got);
1517 code = rx_Write(acall, tbuffer, got); /* writing 0 bytes will
1518 * push a short packet. Is that really what we want, just because the
1519 * data didn't come back from the disk yet? Let's try it and see. */
1522 (*abytesXferredP) += code;
1523 #endif /* AFS_NOSTATS */
1525 code = rx_Error(acall);
1526 osi_FreeLargeSpace(tbuffer);
1527 return code ? code : -33;
1531 * If file has been locked on server, we can allow the store
1534 if (shouldWake && *shouldWake && (rx_GetRemoteStatus(acall) & 1)) {
1535 *shouldWake = 0; /* only do this once */
1539 afs_Trace4(afs_iclSetp, CM_TRACE_STOREPROC, ICL_TYPE_POINTER, avc,
1540 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
1541 ICL_HANDLE_OFFSET(avc->m.Length), ICL_TYPE_INT32, alen);
1542 osi_FreeLargeSpace(tbuffer);
1545 } /* afs_UFSCacheStoreProc */
1549 * afs_UFSCacheFetchProc
1552 * Routine called on fetch; also tells people waiting for data
1553 * that more has arrived.
1556 * acall : Ptr to the Rx call structure.
1557 * afile : File descriptor for the cache file.
1558 * abase : Base offset to fetch.
1559 * adc : Ptr to the dcache entry for the file, write-locked.
1560 * avc : Ptr to the vcache entry for the file.
1561 * abytesToXferP : Set to the number of bytes to xfer.
1562 * NOTE: This parameter is only used if AFS_NOSTATS
1564 * abytesXferredP : Set to the number of bytes actually xferred.
1565 * NOTE: This parameter is only used if AFS_NOSTATS
1569 * Nothing interesting.
1573 afs_UFSCacheFetchProc(register struct rx_call *acall, struct osi_file *afile,
1574 afs_size_t abase, struct dcache *adc,
1575 struct vcache *avc, afs_size_t * abytesToXferP,
1576 afs_size_t * abytesXferredP, afs_int32 lengthFound)
1579 register afs_int32 code;
1580 register char *tbuffer;
1584 AFS_STATCNT(UFS_CacheFetchProc);
1585 osi_Assert(WriteLocked(&adc->lock));
1586 afile->offset = 0; /* Each time start from the beginning */
1587 length = lengthFound;
1589 (*abytesToXferP) = 0;
1590 (*abytesXferredP) = 0;
1591 #endif /* AFS_NOSTATS */
1592 tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1593 adc->validPos = abase;
1597 code = rx_Read(acall, (char *)&length, sizeof(afs_int32));
1599 length = ntohl(length);
1600 if (code != sizeof(afs_int32)) {
1601 osi_FreeLargeSpace(tbuffer);
1602 code = rx_Error(acall);
1603 return (code ? code : -1); /* try to return code, not -1 */
1607 * The fetch protocol is extended for the AFS/DFS translator
1608 * to allow multiple blocks of data, each with its own length,
1609 * to be returned. As long as the top bit is set, there are more
1612 * We do not do this for AFS file servers because they sometimes
1613 * return large negative numbers as the transfer size.
1615 if (avc->states & CForeign) {
1616 moredata = length & 0x80000000;
1617 length &= ~0x80000000;
1622 (*abytesToXferP) += length;
1623 #endif /* AFS_NOSTATS */
1624 while (length > 0) {
1625 tlen = (length > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : length);
1626 #ifdef RX_KERNEL_TRACE
1627 afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
1631 code = rx_Read(acall, tbuffer, tlen);
1633 #ifdef RX_KERNEL_TRACE
1634 afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
1638 (*abytesXferredP) += code;
1639 #endif /* AFS_NOSTATS */
1641 osi_FreeLargeSpace(tbuffer);
1642 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64READ,
1643 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
1644 ICL_TYPE_INT32, length);
1647 code = afs_osi_Write(afile, -1, tbuffer, tlen);
1649 osi_FreeLargeSpace(tbuffer);
1654 adc->validPos = abase;
1655 if (afs_osi_Wakeup(&adc->validPos) == 0)
1656 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
1657 __FILE__, ICL_TYPE_INT32, __LINE__,
1658 ICL_TYPE_POINTER, adc, ICL_TYPE_INT32,
1662 osi_FreeLargeSpace(tbuffer);
1665 } /* afs_UFSCacheFetchProc */
1668 * Get a fresh dcache from the free or discarded list.
1670 * \param avc Who's dcache is this going to be?
1671 * \param chunk The position where it will be placed in.
1672 * \param lock How are locks held.
1673 * \param ashFid If this dcache going to be used for a shadow dir,
1676 * \note Required locks:
1678 * - avc (R if (lock & 1) set and W otherwise)
1679 * \note It write locks the new dcache. The caller must unlock it.
1681 * \return The new dcache.
1683 struct dcache *afs_AllocDCache(struct vcache *avc,
1686 struct VenusFid *ashFid)
1688 struct dcache *tdc = NULL;
1689 afs_uint32 size = 0;
1690 struct osi_file *file;
1692 if (afs_discardDCList == NULLIDX
1693 || ((lock & 2) && afs_freeDCList != NULLIDX)) {
1695 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1696 tdc = afs_GetDSlot(afs_freeDCList, 0);
1697 osi_Assert(tdc->refCount == 1);
1698 ReleaseReadLock(&tdc->tlock);
1699 ObtainWriteLock(&tdc->lock, 604);
1700 afs_freeDCList = afs_dvnextTbl[tdc->index];
1703 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1704 tdc = afs_GetDSlot(afs_discardDCList, 0);
1705 osi_Assert(tdc->refCount == 1);
1706 ReleaseReadLock(&tdc->tlock);
1707 ObtainWriteLock(&tdc->lock, 605);
1708 afs_discardDCList = afs_dvnextTbl[tdc->index];
1709 afs_discardDCCount--;
1711 ((tdc->f.chunkBytes +
1712 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1713 tdc->f.states &= ~(DRO|DBackup|DRW);
1714 afs_DCMoveBucket(tdc, size, 0);
1715 afs_blocksDiscarded -= size;
1716 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1718 /* Truncate the chunk so zeroes get filled properly */
1719 file = afs_CFileOpen(tdc->f.inode);
1720 afs_CFileTruncate(file, 0);
1721 afs_CFileClose(file);
1722 afs_AdjustSize(tdc, 0);
1728 * avc->lock(R) if setLocks
1729 * avc->lock(W) if !setLocks
1735 * Fill in the newly-allocated dcache record.
1737 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1739 /* Use shadow fid if provided. */
1740 tdc->f.fid = *ashFid;
1742 /* Use normal vcache's fid otherwise. */
1743 tdc->f.fid = avc->fid;
1744 if (avc->states & CRO)
1745 tdc->f.states = DRO;
1746 else if (avc->states & CBackup)
1747 tdc->f.states = DBackup;
1749 tdc->f.states = DRW;
1750 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1751 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1753 hones(tdc->f.versionNo); /* invalid value */
1754 tdc->f.chunk = chunk;
1755 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1757 if (tdc->lruq.prev == &tdc->lruq)
1758 osi_Panic("lruq 1");
1767 * This function is called to obtain a reference to data stored in
1768 * the disk cache, locating a chunk of data containing the desired
1769 * byte and returning a reference to the disk cache entry, with its
1770 * reference count incremented.
1774 * avc : Ptr to a vcache entry (unlocked)
1775 * abyte : Byte position in the file desired
1776 * areq : Request structure identifying the requesting user.
1777 * aflags : Settings as follows:
1779 * 2 : Return after creating entry.
1780 * 4 : called from afs_vnop_write.c
1781 * *alen contains length of data to be written.
1783 * aoffset : Set to the offset within the chunk where the resident
1785 * alen : Set to the number of bytes of data after the desired
1786 * byte (including the byte itself) which can be read
1790 * The vcache entry pointed to by avc is unlocked upon entry.
1794 struct AFSVolSync tsync;
1795 struct AFSFetchStatus OutStatus;
1796 struct AFSCallBack CallBack;
1800 * Update the vnode-to-dcache hint if we can get the vnode lock
1801 * right away. Assumes dcache entry is at least read-locked.
1804 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1806 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1807 if (hsame(v->m.DataVersion, d->f.versionNo) && v->callback)
1810 ReleaseWriteLock(&v->lock);
1814 /* avc - Write-locked unless aflags & 1 */
1816 afs_GetDCache(register struct vcache *avc, afs_size_t abyte,
1817 register struct vrequest *areq, afs_size_t * aoffset,
1818 afs_size_t * alen, int aflags)
1820 register afs_int32 i, code, code1 = 0, shortcut;
1821 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1822 register afs_int32 adjustsize = 0;
1828 afs_size_t maxGoodLength; /* amount of good data at server */
1829 struct rx_call *tcall;
1830 afs_size_t Position = 0;
1831 #ifdef AFS_64BIT_CLIENT
1833 afs_size_t lengthFound; /* as returned from server */
1834 #endif /* AFS_64BIT_CLIENT */
1835 afs_int32 size, tlen; /* size of segment to transfer */
1836 struct tlocal1 *tsmall = 0;
1837 register struct dcache *tdc;
1838 register struct osi_file *file;
1839 register struct conn *tc;
1841 struct server *newCallback = NULL;
1842 char setNewCallback;
1843 char setVcacheStatus;
1844 char doVcacheUpdate;
1846 int doAdjustSize = 0;
1847 int doReallyAdjustSize = 0;
1848 int overWriteWholeChunk = 0;
1852 struct afs_stats_xferData *xferP; /* Ptr to this op's xfer struct */
1853 osi_timeval_t xferStartTime, /*FS xfer start time */
1854 xferStopTime; /*FS xfer stop time */
1855 afs_size_t bytesToXfer; /* # bytes to xfer */
1856 afs_size_t bytesXferred; /* # bytes actually xferred */
1857 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1858 int fromReplica; /*Are we reading from a replica? */
1859 int numFetchLoops; /*# times around the fetch/analyze loop */
1860 #endif /* AFS_NOSTATS */
1862 AFS_STATCNT(afs_GetDCache);
1866 setLocks = aflags & 1;
1869 * Determine the chunk number and offset within the chunk corresponding
1870 * to the desired byte.
1872 if (avc->fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1875 chunk = AFS_CHUNK(abyte);
1878 /* come back to here if we waited for the cache to drain. */
1881 setNewCallback = setVcacheStatus = 0;
1885 ObtainWriteLock(&avc->lock, 616);
1887 ObtainReadLock(&avc->lock);
1892 * avc->lock(R) if setLocks && !slowPass
1893 * avc->lock(W) if !setLocks || slowPass
1898 /* check hints first! (might could use bcmp or some such...) */
1899 if ((tdc = avc->dchint)) {
1903 * The locking order between afs_xdcache and dcache lock matters.
1904 * The hint dcache entry could be anywhere, even on the free list.
1905 * Locking afs_xdcache ensures that noone is trying to pull dcache
1906 * entries from the free list, and thereby assuming them to be not
1907 * referenced and not locked.
1909 MObtainReadLock(&afs_xdcache);
1910 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1912 if (dcLocked && (tdc->index != NULLIDX)
1913 && !FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk
1914 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1915 /* got the right one. It might not be the right version, and it
1916 * might be fetching, but it's the right dcache entry.
1918 /* All this code should be integrated better with what follows:
1919 * I can save a good bit more time under a write lock if I do..
1921 ObtainWriteLock(&tdc->tlock, 603);
1923 ReleaseWriteLock(&tdc->tlock);
1925 MReleaseReadLock(&afs_xdcache);
1928 if (hsame(tdc->f.versionNo, avc->m.DataVersion)
1929 && !(tdc->dflags & DFFetching)) {
1931 afs_stats_cmperf.dcacheHits++;
1932 MObtainWriteLock(&afs_xdcache, 559);
1933 QRemove(&tdc->lruq);
1934 QAdd(&afs_DLRU, &tdc->lruq);
1935 MReleaseWriteLock(&afs_xdcache);
1938 * avc->lock(R) if setLocks && !slowPass
1939 * avc->lock(W) if !setLocks || slowPass
1946 ReleaseSharedLock(&tdc->lock);
1947 MReleaseReadLock(&afs_xdcache);
1955 * avc->lock(R) if setLocks && !slowPass
1956 * avc->lock(W) if !setLocks || slowPass
1957 * tdc->lock(S) if tdc
1960 if (!tdc) { /* If the hint wasn't the right dcache entry */
1962 * Hash on the [fid, chunk] and get the corresponding dcache index
1963 * after write-locking the dcache.
1968 * avc->lock(R) if setLocks && !slowPass
1969 * avc->lock(W) if !setLocks || slowPass
1972 i = DCHash(&avc->fid, chunk);
1973 /* check to make sure our space is fine */
1974 afs_MaybeWakeupTruncateDaemon();
1976 MObtainWriteLock(&afs_xdcache, 280);
1978 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1979 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1980 tdc = afs_GetDSlot(index, NULL);
1981 ReleaseReadLock(&tdc->tlock);
1984 * avc->lock(R) if setLocks && !slowPass
1985 * avc->lock(W) if !setLocks || slowPass
1988 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1989 /* Move it up in the beginning of the list */
1990 if (afs_dchashTbl[i] != index) {
1991 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1992 afs_dcnextTbl[index] = afs_dchashTbl[i];
1993 afs_dchashTbl[i] = index;
1995 MReleaseWriteLock(&afs_xdcache);
1996 ObtainSharedLock(&tdc->lock, 606);
1997 break; /* leaving refCount high for caller */
2003 index = afs_dcnextTbl[index];
2007 * If we didn't find the entry, we'll create one.
2009 if (index == NULLIDX) {
2012 * avc->lock(R) if setLocks
2013 * avc->lock(W) if !setLocks
2016 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
2017 avc, ICL_TYPE_INT32, chunk);
2019 /* Make sure there is a free dcache entry for us to use */
2020 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
2023 avc->states |= CDCLock;
2024 /* just need slots */
2025 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
2027 avc->states &= ~CDCLock;
2028 if (afs_discardDCList != NULLIDX
2029 || afs_freeDCList != NULLIDX)
2031 /* If we can't get space for 5 mins we give up and panic */
2032 if (++downDCount > 300) {
2033 #if defined(AFS_CACHE_BYPASS)
2034 afs_warn("GetDCache calling osi_Panic: No space in five minutes.\n downDCount: %d\n aoffset: %d alen: %d\n", downDCount, aoffset, alen);
2036 osi_Panic("getdcache");
2038 MReleaseWriteLock(&afs_xdcache);
2041 * avc->lock(R) if setLocks
2042 * avc->lock(W) if !setLocks
2044 afs_osi_Wait(1000, 0, 0);
2049 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
2052 * Now add to the two hash chains - note that i is still set
2053 * from the above DCHash call.
2055 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
2056 afs_dchashTbl[i] = tdc->index;
2057 i = DVHash(&avc->fid);
2058 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
2059 afs_dvhashTbl[i] = tdc->index;
2060 tdc->dflags = DFEntryMod;
2062 afs_MaybeWakeupTruncateDaemon();
2063 MReleaseWriteLock(&afs_xdcache);
2064 ConvertWToSLock(&tdc->lock);
2069 /* vcache->dcache hint failed */
2072 * avc->lock(R) if setLocks && !slowPass
2073 * avc->lock(W) if !setLocks || slowPass
2076 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
2077 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2078 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
2079 hgetlo(avc->m.DataVersion));
2081 * Here we have the entry in tdc, with its refCount incremented.
2082 * Note: we don't use the S-lock on avc; it costs concurrency when
2083 * storing a file back to the server.
2087 * Not a newly created file so we need to check the file's length and
2088 * compare data versions since someone could have changed the data or we're
2089 * reading a file written elsewhere. We only want to bypass doing no-op
2090 * read rpcs on newly created files (dv of 0) since only then we guarantee
2091 * that this chunk's data hasn't been filled by another client.
2093 size = AFS_CHUNKSIZE(abyte);
2094 if (aflags & 4) /* called from write */
2096 else /* called from read */
2097 tlen = tdc->validPos - abyte;
2098 Position = AFS_CHUNKTOBASE(chunk);
2099 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
2100 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
2101 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
2102 ICL_HANDLE_OFFSET(Position));
2103 if ((aflags & 4) && (hiszero(avc->m.DataVersion)))
2105 if ((AFS_CHUNKTOBASE(chunk) >= avc->m.Length) ||
2106 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
2107 overWriteWholeChunk = 1;
2108 if (doAdjustSize || overWriteWholeChunk) {
2109 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
2111 #ifdef AFS_SGI64_ENV
2114 #else /* AFS_SGI64_ENV */
2117 #endif /* AFS_SGI64_ENV */
2118 #else /* AFS_SGI_ENV */
2121 #endif /* AFS_SGI_ENV */
2122 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->m.Length &&
2123 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2124 #if defined(AFS_SUN5_ENV) || defined(AFS_OSF_ENV)
2125 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->m.Length)) &&
2127 if (AFS_CHUNKTOBASE(chunk) >= avc->m.Length &&
2129 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2130 !hsame(avc->m.DataVersion, tdc->f.versionNo))
2131 doReallyAdjustSize = 1;
2133 if (doReallyAdjustSize || overWriteWholeChunk) {
2134 /* no data in file to read at this position */
2135 UpgradeSToWLock(&tdc->lock, 607);
2137 file = afs_CFileOpen(tdc->f.inode);
2138 afs_CFileTruncate(file, 0);
2139 afs_CFileClose(file);
2140 afs_AdjustSize(tdc, 0);
2141 hset(tdc->f.versionNo, avc->m.DataVersion);
2142 tdc->dflags |= DFEntryMod;
2144 ConvertWToSLock(&tdc->lock);
2149 * We must read in the whole chunk if the version number doesn't
2153 /* don't need data, just a unique dcache entry */
2154 ObtainWriteLock(&afs_xdcache, 608);
2155 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2156 hadd32(afs_indexCounter, 1);
2157 ReleaseWriteLock(&afs_xdcache);
2159 updateV2DC(setLocks, avc, tdc, 553);
2160 if (vType(avc) == VDIR)
2163 *aoffset = AFS_CHUNKOFFSET(abyte);
2164 if (tdc->validPos < abyte)
2165 *alen = (afs_size_t) 0;
2167 *alen = tdc->validPos - abyte;
2168 ReleaseSharedLock(&tdc->lock);
2171 ReleaseWriteLock(&avc->lock);
2173 ReleaseReadLock(&avc->lock);
2175 return tdc; /* check if we're done */
2180 * avc->lock(R) if setLocks && !slowPass
2181 * avc->lock(W) if !setLocks || slowPass
2184 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
2186 setNewCallback = setVcacheStatus = 0;
2190 * avc->lock(R) if setLocks && !slowPass
2191 * avc->lock(W) if !setLocks || slowPass
2194 if (!hsame(avc->m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
2196 * Version number mismatch.
2199 * If we are disconnected, then we can't do much of anything
2200 * because the data doesn't match the file.
2202 if (AFS_IS_DISCONNECTED) {
2203 ReleaseSharedLock(&tdc->lock);
2206 ReleaseWriteLock(&avc->lock);
2208 ReleaseReadLock(&avc->lock);
2210 /* Flush the Dcache */
2215 UpgradeSToWLock(&tdc->lock, 609);
2218 * If data ever existed for this vnode, and this is a text object,
2219 * do some clearing. Now, you'd think you need only do the flush
2220 * when VTEXT is on, but VTEXT is turned off when the text object
2221 * is freed, while pages are left lying around in memory marked
2222 * with this vnode. If we would reactivate (create a new text
2223 * object from) this vnode, we could easily stumble upon some of
2224 * these old pages in pagein. So, we always flush these guys.
2225 * Sun has a wonderful lack of useful invariants in this system.
2227 * avc->flushDV is the data version # of the file at the last text
2228 * flush. Clearly, at least, we don't have to flush the file more
2229 * often than it changes
2231 if (hcmp(avc->flushDV, avc->m.DataVersion) < 0) {
2233 * By here, the cache entry is always write-locked. We can
2234 * deadlock if we call osi_Flush with the cache entry locked...
2235 * Unlock the dcache too.
2237 ReleaseWriteLock(&tdc->lock);
2238 if (setLocks && !slowPass)
2239 ReleaseReadLock(&avc->lock);
2241 ReleaseWriteLock(&avc->lock);
2245 * Call osi_FlushPages in open, read/write, and map, since it
2246 * is too hard here to figure out if we should lock the
2249 if (setLocks && !slowPass)
2250 ObtainReadLock(&avc->lock);
2252 ObtainWriteLock(&avc->lock, 66);
2253 ObtainWriteLock(&tdc->lock, 610);
2258 * avc->lock(R) if setLocks && !slowPass
2259 * avc->lock(W) if !setLocks || slowPass
2263 /* Watch for standard race condition around osi_FlushText */
2264 if (hsame(avc->m.DataVersion, tdc->f.versionNo)) {
2265 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2266 afs_stats_cmperf.dcacheHits++;
2267 ConvertWToSLock(&tdc->lock);
2271 /* Sleep here when cache needs to be drained. */
2272 if (setLocks && !slowPass
2273 && (afs_blocksUsed >
2274 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2275 /* Make sure truncate daemon is running */
2276 afs_MaybeWakeupTruncateDaemon();
2277 ObtainWriteLock(&tdc->tlock, 614);
2278 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2279 ReleaseWriteLock(&tdc->tlock);
2280 ReleaseWriteLock(&tdc->lock);
2281 ReleaseReadLock(&avc->lock);
2282 while ((afs_blocksUsed - afs_blocksDiscarded) >
2283 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2284 afs_WaitForCacheDrain = 1;
2285 afs_osi_Sleep(&afs_WaitForCacheDrain);
2287 afs_MaybeFreeDiscardedDCache();
2288 /* need to check if someone else got the chunk first. */
2289 goto RetryGetDCache;
2292 /* Do not fetch data beyond truncPos. */
2293 maxGoodLength = avc->m.Length;
2294 if (avc->truncPos < maxGoodLength)
2295 maxGoodLength = avc->truncPos;
2296 Position = AFS_CHUNKBASE(abyte);
2297 if (vType(avc) == VDIR) {
2298 size = avc->m.Length;
2299 if (size > tdc->f.chunkBytes) {
2300 /* pre-reserve space for file */
2301 afs_AdjustSize(tdc, size);
2303 size = 999999999; /* max size for transfer */
2305 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2306 /* don't read past end of good data on server */
2307 if (Position + size > maxGoodLength)
2308 size = maxGoodLength - Position;
2310 size = 0; /* Handle random races */
2311 if (size > tdc->f.chunkBytes) {
2312 /* pre-reserve space for file */
2313 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2314 /* max size for transfer still in size */
2317 if (afs_mariner && !tdc->f.chunk)
2318 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2320 * Right now, we only have one tool, and it's a hammer. So, we
2321 * fetch the whole file.
2323 DZap(tdc); /* pages in cache may be old */
2324 file = afs_CFileOpen(tdc->f.inode);
2325 afs_RemoveVCB(&avc->fid);
2326 tdc->f.states |= DWriting;
2327 tdc->dflags |= DFFetching;
2328 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2329 if (tdc->mflags & DFFetchReq) {
2330 tdc->mflags &= ~DFFetchReq;
2331 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2332 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2333 __FILE__, ICL_TYPE_INT32, __LINE__,
2334 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2338 (struct tlocal1 *)osi_AllocLargeSpace(sizeof(struct tlocal1));
2339 setVcacheStatus = 0;
2342 * Remember if we are doing the reading from a replicated volume,
2343 * and how many times we've zipped around the fetch/analyze loop.
2345 fromReplica = (avc->states & CRO) ? 1 : 0;
2347 accP = &(afs_stats_cmfullperf.accessinf);
2349 (accP->replicatedRefs)++;
2351 (accP->unreplicatedRefs)++;
2352 #endif /* AFS_NOSTATS */
2353 /* this is a cache miss */
2354 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2355 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
2356 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2359 afs_stats_cmperf.dcacheMisses++;
2362 * Dynamic root support: fetch data from local memory.
2364 if (afs_IsDynroot(avc)) {
2368 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2370 dynrootDir += Position;
2371 dynrootLen -= Position;
2372 if (size > dynrootLen)
2376 code = afs_CFileWrite(file, 0, dynrootDir, size);
2384 tdc->validPos = Position + size;
2385 afs_CFileTruncate(file, size); /* prune it */
2386 } else if (afs_IsDynrootMount(avc)) {
2390 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2392 dynrootDir += Position;
2393 dynrootLen -= Position;
2394 if (size > dynrootLen)
2398 code = afs_CFileWrite(file, 0, dynrootDir, size);
2406 tdc->validPos = Position + size;
2407 afs_CFileTruncate(file, size); /* prune it */
2408 } else if (afs_IsDynrootMount(avc)) {
2412 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2414 dynrootDir += Position;
2415 dynrootLen -= Position;
2416 if (size > dynrootLen)
2420 code = afs_CFileWrite(file, 0, dynrootDir, size);
2428 tdc->validPos = Position + size;
2429 afs_CFileTruncate(file, size); /* prune it */
2432 * Not a dynamic vnode: do the real fetch.
2437 * avc->lock(R) if setLocks && !slowPass
2438 * avc->lock(W) if !setLocks || slowPass
2442 tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
2444 afs_int32 length_hi, length, bytes;
2448 (accP->numReplicasAccessed)++;
2450 #endif /* AFS_NOSTATS */
2451 if (!setLocks || slowPass) {
2452 avc->callback = tc->srvr->server;
2454 newCallback = tc->srvr->server;
2459 tcall = rx_NewCall(tc->id);
2462 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
2463 #ifdef AFS_64BIT_CLIENT
2464 length_hi = code = 0;
2465 if (!afs_serverHasNo64Bit(tc)) {
2469 StartRXAFS_FetchData64(tcall,
2470 (struct AFSFid *)&avc->fid.
2471 Fid, Position, tsize);
2474 afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2475 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32,
2479 rx_Read(tcall, (char *)&length_hi,
2482 if (bytes == sizeof(afs_int32)) {
2483 length_hi = ntohl(length_hi);
2486 code = rx_Error(tcall);
2488 code1 = rx_EndCall(tcall, code);
2490 tcall = (struct rx_call *)0;
2494 if (code == RXGEN_OPCODE || afs_serverHasNo64Bit(tc)) {
2495 if (Position > 0x7FFFFFFF) {
2502 tcall = rx_NewCall(tc->id);
2504 StartRXAFS_FetchData(tcall, (struct AFSFid *)
2509 afs_serverSetNo64Bit(tc);
2514 rx_Read(tcall, (char *)&length,
2517 if (bytes == sizeof(afs_int32)) {
2518 length = ntohl(length);
2520 code = rx_Error(tcall);
2523 FillInt64(lengthFound, length_hi, length);
2524 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64LENG,
2525 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
2527 ICL_HANDLE_OFFSET(lengthFound));
2528 #else /* AFS_64BIT_CLIENT */
2531 StartRXAFS_FetchData(tcall,
2532 (struct AFSFid *)&avc->fid.Fid,
2538 rx_Read(tcall, (char *)&length,
2541 if (bytes == sizeof(afs_int32)) {
2542 length = ntohl(length);
2544 code = rx_Error(tcall);
2547 #endif /* AFS_64BIT_CLIENT */
2552 &(afs_stats_cmfullperf.rpc.
2553 fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
2554 osi_GetuTime(&xferStartTime);
2557 afs_CacheFetchProc(tcall, file,
2558 (afs_size_t) Position, tdc,
2560 &bytesXferred, length);
2562 osi_GetuTime(&xferStopTime);
2563 (xferP->numXfers)++;
2565 (xferP->numSuccesses)++;
2566 afs_stats_XferSumBytes
2567 [AFS_STATS_FS_XFERIDX_FETCHDATA] +=
2569 (xferP->sumBytes) +=
2570 (afs_stats_XferSumBytes
2571 [AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
2572 afs_stats_XferSumBytes
2573 [AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
2574 if (bytesXferred < xferP->minBytes)
2575 xferP->minBytes = bytesXferred;
2576 if (bytesXferred > xferP->maxBytes)
2577 xferP->maxBytes = bytesXferred;
2580 * Tally the size of the object. Note: we tally the actual size,
2581 * NOT the number of bytes that made it out over the wire.
2583 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
2584 (xferP->count[0])++;
2585 else if (bytesToXfer <=
2586 AFS_STATS_MAXBYTES_BUCKET1)
2587 (xferP->count[1])++;
2588 else if (bytesToXfer <=
2589 AFS_STATS_MAXBYTES_BUCKET2)
2590 (xferP->count[2])++;
2591 else if (bytesToXfer <=
2592 AFS_STATS_MAXBYTES_BUCKET3)
2593 (xferP->count[3])++;
2594 else if (bytesToXfer <=
2595 AFS_STATS_MAXBYTES_BUCKET4)
2596 (xferP->count[4])++;
2597 else if (bytesToXfer <=
2598 AFS_STATS_MAXBYTES_BUCKET5)
2599 (xferP->count[5])++;
2600 else if (bytesToXfer <=
2601 AFS_STATS_MAXBYTES_BUCKET6)
2602 (xferP->count[6])++;
2603 else if (bytesToXfer <=
2604 AFS_STATS_MAXBYTES_BUCKET7)
2605 (xferP->count[7])++;
2607 (xferP->count[8])++;
2609 afs_stats_GetDiff(elapsedTime, xferStartTime,
2611 afs_stats_AddTo((xferP->sumTime), elapsedTime);
2612 afs_stats_SquareAddTo((xferP->sqrTime),
2614 if (afs_stats_TimeLessThan
2615 (elapsedTime, (xferP->minTime))) {
2616 afs_stats_TimeAssign((xferP->minTime),
2619 if (afs_stats_TimeGreaterThan
2620 (elapsedTime, (xferP->maxTime))) {
2621 afs_stats_TimeAssign((xferP->maxTime),
2627 afs_CacheFetchProc(tcall, file, Position, tdc,
2629 #endif /* AFS_NOSTATS */
2634 EndRXAFS_FetchData(tcall, &tsmall->OutStatus,
2642 code1 = rx_EndCall(tcall, code);
2651 /* callback could have been broken (or expired) in a race here,
2652 * but we return the data anyway. It's as good as we knew about
2653 * when we started. */
2655 * validPos is updated by CacheFetchProc, and can only be
2656 * modifed under a dcache write lock, which we've blocked out
2658 size = tdc->validPos - Position; /* actual segment size */
2661 afs_CFileTruncate(file, size); /* prune it */
2663 if (!setLocks || slowPass) {
2664 ObtainWriteLock(&afs_xcbhash, 453);
2665 afs_DequeueCallback(avc);
2666 avc->states &= ~(CStatd | CUnique);
2667 avc->callback = NULL;
2668 ReleaseWriteLock(&afs_xcbhash);
2669 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2670 osi_dnlc_purgedp(avc);
2672 /* Something lost. Forget about performance, and go
2673 * back with a vcache write lock.
2675 afs_CFileTruncate(file, 0);
2676 afs_AdjustSize(tdc, 0);
2677 afs_CFileClose(file);
2678 osi_FreeLargeSpace(tsmall);
2680 ReleaseWriteLock(&tdc->lock);
2683 ReleaseReadLock(&avc->lock);
2685 goto RetryGetDCache;
2689 } while (afs_Analyze
2690 (tc, code, &avc->fid, areq,
2691 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2695 * avc->lock(R) if setLocks && !slowPass
2696 * avc->lock(W) if !setLocks || slowPass
2702 * In the case of replicated access, jot down info on the number of
2703 * attempts it took before we got through or gave up.
2706 if (numFetchLoops <= 1)
2707 (accP->refFirstReplicaOK)++;
2708 if (numFetchLoops > accP->maxReplicasPerRef)
2709 accP->maxReplicasPerRef = numFetchLoops;
2711 #endif /* AFS_NOSTATS */
2713 tdc->dflags &= ~DFFetching;
2714 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2715 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2716 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2717 tdc, ICL_TYPE_INT32, tdc->dflags);
2718 if (avc->execsOrWriters == 0)
2719 tdc->f.states &= ~DWriting;
2721 /* now, if code != 0, we have an error and should punt.
2722 * note that we have the vcache write lock, either because
2723 * !setLocks or slowPass.
2726 afs_CFileTruncate(file, 0);
2727 afs_AdjustSize(tdc, 0);
2728 afs_CFileClose(file);
2729 ZapDCE(tdc); /* sets DFEntryMod */
2730 if (vType(avc) == VDIR) {
2733 tdc->f.states &= ~(DRO|DBackup|DRW);
2734 afs_DCMoveBucket(tdc, 0, 0);
2735 ReleaseWriteLock(&tdc->lock);
2737 if (!afs_IsDynroot(avc)) {
2738 ObtainWriteLock(&afs_xcbhash, 454);
2739 afs_DequeueCallback(avc);
2740 avc->states &= ~(CStatd | CUnique);
2741 ReleaseWriteLock(&afs_xcbhash);
2742 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2743 osi_dnlc_purgedp(avc);
2746 * avc->lock(W); assert(!setLocks || slowPass)
2748 osi_Assert(!setLocks || slowPass);
2750 tdc->f.states &= ~(DRO|DBackup|DRW);
2751 afs_DCMoveBucket(tdc, 0, 0);
2756 /* otherwise we copy in the just-fetched info */
2757 afs_CFileClose(file);
2758 afs_AdjustSize(tdc, size); /* new size */
2760 * Copy appropriate fields into vcache. Status is
2761 * copied later where we selectively acquire the
2762 * vcache write lock.
2765 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2767 setVcacheStatus = 1;
2768 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2769 tsmall->OutStatus.DataVersion);
2770 tdc->dflags |= DFEntryMod;
2771 afs_indexFlags[tdc->index] |= IFEverUsed;
2772 ConvertWToSLock(&tdc->lock);
2773 } /*Data version numbers don't match */
2776 * Data version numbers match.
2778 afs_stats_cmperf.dcacheHits++;
2779 } /*Data version numbers match */
2781 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2785 * avc->lock(R) if setLocks && !slowPass
2786 * avc->lock(W) if !setLocks || slowPass
2787 * tdc->lock(S) if tdc
2791 * See if this was a reference to a file in the local cell.
2793 if (afs_IsPrimaryCellNum(avc->fid.Cell))
2794 afs_stats_cmperf.dlocalAccesses++;
2796 afs_stats_cmperf.dremoteAccesses++;
2798 /* Fix up LRU info */
2801 MObtainWriteLock(&afs_xdcache, 602);
2802 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2803 hadd32(afs_indexCounter, 1);
2804 MReleaseWriteLock(&afs_xdcache);
2806 /* return the data */
2807 if (vType(avc) == VDIR)
2810 *aoffset = AFS_CHUNKOFFSET(abyte);
2811 *alen = (tdc->f.chunkBytes - *aoffset);
2812 ReleaseSharedLock(&tdc->lock);
2817 * avc->lock(R) if setLocks && !slowPass
2818 * avc->lock(W) if !setLocks || slowPass
2821 /* Fix up the callback and status values in the vcache */
2823 if (setLocks && !slowPass) {
2826 * This is our dirty little secret to parallel fetches.
2827 * We don't write-lock the vcache while doing the fetch,
2828 * but potentially we'll need to update the vcache after
2829 * the fetch is done.
2831 * Drop the read lock and try to re-obtain the write
2832 * lock. If the vcache still has the same DV, it's
2833 * ok to go ahead and install the new data.
2835 afs_hyper_t currentDV, statusDV;
2837 hset(currentDV, avc->m.DataVersion);
2839 if (setNewCallback && avc->callback != newCallback)
2843 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2844 tsmall->OutStatus.DataVersion);
2846 if (setVcacheStatus && avc->m.Length != tsmall->OutStatus.Length)
2848 if (setVcacheStatus && !hsame(currentDV, statusDV))
2852 ReleaseReadLock(&avc->lock);
2854 if (doVcacheUpdate) {
2855 ObtainWriteLock(&avc->lock, 615);
2856 if (!hsame(avc->m.DataVersion, currentDV)) {
2857 /* We lose. Someone will beat us to it. */
2859 ReleaseWriteLock(&avc->lock);
2864 /* With slow pass, we've already done all the updates */
2866 ReleaseWriteLock(&avc->lock);
2869 /* Check if we need to perform any last-minute fixes with a write-lock */
2870 if (!setLocks || doVcacheUpdate) {
2872 avc->callback = newCallback;
2873 if (tsmall && setVcacheStatus)
2874 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2876 ReleaseWriteLock(&avc->lock);
2880 osi_FreeLargeSpace(tsmall);
2883 } /*afs_GetDCache */
2887 * afs_WriteThroughDSlots
2890 * Sweep through the dcache slots and write out any modified
2891 * in-memory data back on to our caching store.
2897 * The afs_xdcache is write-locked through this whole affair.
2900 afs_WriteThroughDSlots(void)
2902 register struct dcache *tdc;
2903 register afs_int32 i, touchedit = 0;
2905 struct afs_q DirtyQ, *tq;
2907 AFS_STATCNT(afs_WriteThroughDSlots);
2910 * Because of lock ordering, we can't grab dcache locks while
2911 * holding afs_xdcache. So we enter xdcache, get a reference
2912 * for every dcache entry, and exit xdcache.
2914 MObtainWriteLock(&afs_xdcache, 283);
2916 for (i = 0; i < afs_cacheFiles; i++) {
2917 tdc = afs_indexTable[i];
2919 /* Grab tlock in case the existing refcount isn't zero */
2920 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2921 ObtainWriteLock(&tdc->tlock, 623);
2923 ReleaseWriteLock(&tdc->tlock);
2925 QAdd(&DirtyQ, &tdc->dirty);
2928 MReleaseWriteLock(&afs_xdcache);
2931 * Now, for each dcache entry we found, check if it's dirty.
2932 * If so, get write-lock, get afs_xdcache, which protects
2933 * afs_cacheInodep, and flush it. Don't forget to put back
2937 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2939 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2941 if (tdc->dflags & DFEntryMod) {
2944 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2946 /* Now that we have the write lock, double-check */
2947 if (wrLock && (tdc->dflags & DFEntryMod)) {
2948 tdc->dflags &= ~DFEntryMod;
2949 MObtainWriteLock(&afs_xdcache, 620);
2950 afs_WriteDCache(tdc, 1);
2951 MReleaseWriteLock(&afs_xdcache);
2955 ReleaseWriteLock(&tdc->lock);
2961 MObtainWriteLock(&afs_xdcache, 617);
2962 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2963 /* Touch the file to make sure that the mtime on the file is kept
2964 * up-to-date to avoid losing cached files on cold starts because
2965 * their mtime seems old...
2967 struct afs_fheader theader;
2969 theader.magic = AFS_FHMAGIC;
2970 theader.firstCSize = AFS_FIRSTCSIZE;
2971 theader.otherCSize = AFS_OTHERCSIZE;
2972 theader.version = AFS_CI_VERSION;
2973 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2975 MReleaseWriteLock(&afs_xdcache);
2982 * Return a pointer to an freshly initialized dcache entry using
2983 * a memory-based cache. The tlock will be read-locked.
2986 * aslot : Dcache slot to look at.
2987 * tmpdc : Ptr to dcache entry.
2990 * Must be called with afs_xdcache write-locked.
2994 afs_MemGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2996 register struct dcache *tdc;
2999 AFS_STATCNT(afs_MemGetDSlot);
3000 if (CheckLock(&afs_xdcache) != -1)
3001 osi_Panic("getdslot nolock");
3002 if (aslot < 0 || aslot >= afs_cacheFiles)
3003 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3004 tdc = afs_indexTable[aslot];
3006 QRemove(&tdc->lruq); /* move to queue head */
3007 QAdd(&afs_DLRU, &tdc->lruq);
3008 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
3009 ObtainWriteLock(&tdc->tlock, 624);
3011 ConvertWToRLock(&tdc->tlock);
3014 if (tmpdc == NULL) {
3015 if (!afs_freeDSList)
3016 afs_GetDownDSlot(4);
3017 if (!afs_freeDSList) {
3018 /* none free, making one is better than a panic */
3019 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
3020 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
3021 #ifdef KERNEL_HAVE_PIN
3022 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
3025 tdc = afs_freeDSList;
3026 afs_freeDSList = (struct dcache *)tdc->lruq.next;
3029 tdc->dflags = 0; /* up-to-date, not in free q */
3031 QAdd(&afs_DLRU, &tdc->lruq);
3032 if (tdc->lruq.prev == &tdc->lruq)
3033 osi_Panic("lruq 3");
3039 /* initialize entry */
3040 tdc->f.fid.Cell = 0;
3041 tdc->f.fid.Fid.Volume = 0;
3043 hones(tdc->f.versionNo);
3044 tdc->f.inode = aslot;
3045 tdc->dflags |= DFEntryMod;
3048 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3051 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3052 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3053 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3056 RWLOCK_INIT(&tdc->lock, "dcache lock");
3057 RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3058 RWLOCK_INIT(&tdc->mflock, "dcache flock");
3059 ObtainReadLock(&tdc->tlock);
3062 afs_indexTable[aslot] = tdc;
3065 } /*afs_MemGetDSlot */
3067 unsigned int last_error = 0, lasterrtime = 0;
3073 * Return a pointer to an freshly initialized dcache entry using
3074 * a UFS-based disk cache. The dcache tlock will be read-locked.
3077 * aslot : Dcache slot to look at.
3078 * tmpdc : Ptr to dcache entry.
3081 * afs_xdcache lock write-locked.
3084 afs_UFSGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
3086 register afs_int32 code;
3087 register struct dcache *tdc;
3091 AFS_STATCNT(afs_UFSGetDSlot);
3092 if (CheckLock(&afs_xdcache) != -1)
3093 osi_Panic("getdslot nolock");
3094 if (aslot < 0 || aslot >= afs_cacheFiles)
3095 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3096 tdc = afs_indexTable[aslot];
3098 QRemove(&tdc->lruq); /* move to queue head */
3099 QAdd(&afs_DLRU, &tdc->lruq);
3100 /* Grab tlock in case refCount != 0 */
3101 ObtainWriteLock(&tdc->tlock, 625);
3103 ConvertWToRLock(&tdc->tlock);
3106 /* otherwise we should read it in from the cache file */
3108 * If we weren't passed an in-memory region to place the file info,
3109 * we have to allocate one.
3111 if (tmpdc == NULL) {
3112 if (!afs_freeDSList)
3113 afs_GetDownDSlot(4);
3114 if (!afs_freeDSList) {
3115 /* none free, making one is better than a panic */
3116 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
3117 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
3118 #ifdef KERNEL_HAVE_PIN
3119 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
3122 tdc = afs_freeDSList;
3123 afs_freeDSList = (struct dcache *)tdc->lruq.next;
3126 tdc->dflags = 0; /* up-to-date, not in free q */
3128 QAdd(&afs_DLRU, &tdc->lruq);
3129 if (tdc->lruq.prev == &tdc->lruq)
3130 osi_Panic("lruq 3");
3137 * Seek to the aslot'th entry and read it in.
3140 afs_osi_Read(afs_cacheInodep,
3141 sizeof(struct fcache) * aslot +
3142 sizeof(struct afs_fheader), (char *)(&tdc->f),
3143 sizeof(struct fcache));
3145 if (code != sizeof(struct fcache))
3147 if (!afs_CellNumValid(tdc->f.fid.Cell))
3151 tdc->f.fid.Cell = 0;
3152 tdc->f.fid.Fid.Volume = 0;
3154 hones(tdc->f.versionNo);
3155 tdc->dflags |= DFEntryMod;
3156 #if defined(KERNEL_HAVE_UERROR)
3157 last_error = getuerror();
3159 lasterrtime = osi_Time();
3160 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3161 tdc->f.states &= ~(DRO|DBackup|DRW);
3162 afs_DCMoveBucket(tdc, 0, 0);
3165 if (tdc->f.states & DRO) {
3166 afs_DCMoveBucket(tdc, 0, 2);
3167 } else if (tdc->f.states & DBackup) {
3168 afs_DCMoveBucket(tdc, 0, 1);
3170 afs_DCMoveBucket(tdc, 0, 1);
3176 if (tdc->f.chunk >= 0)
3177 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
3182 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3183 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3184 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3187 RWLOCK_INIT(&tdc->lock, "dcache lock");
3188 RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3189 RWLOCK_INIT(&tdc->mflock, "dcache flock");
3190 ObtainReadLock(&tdc->tlock);
3193 * If we didn't read into a temporary dcache region, update the
3194 * slot pointer table.
3197 afs_indexTable[aslot] = tdc;
3200 } /*afs_UFSGetDSlot */
3205 * Write a particular dcache entry back to its home in the
3208 * \param adc Pointer to the dcache entry to write.
3209 * \param atime If true, set the modtime on the file to the current time.
3211 * \note Environment:
3212 * Must be called with the afs_xdcache lock at least read-locked,
3213 * and dcache entry at least read-locked.
3214 * The reference count is not changed.
3218 afs_WriteDCache(register struct dcache *adc, int atime)
3220 register afs_int32 code;
3222 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3224 AFS_STATCNT(afs_WriteDCache);
3225 osi_Assert(WriteLocked(&afs_xdcache));
3227 adc->f.modTime = osi_Time();
3229 * Seek to the right dcache slot and write the in-memory image out to disk.
3231 afs_cellname_write();
3233 afs_osi_Write(afs_cacheInodep,
3234 sizeof(struct fcache) * adc->index +
3235 sizeof(struct afs_fheader), (char *)(&adc->f),
3236 sizeof(struct fcache));
3237 if (code != sizeof(struct fcache))
3245 * Wake up users of a particular file waiting for stores to take
3248 * \param avc Ptr to related vcache entry.
3250 * \note Environment:
3251 * Nothing interesting.
3254 afs_wakeup(register struct vcache *avc)
3257 register struct brequest *tb;
3259 AFS_STATCNT(afs_wakeup);
3260 for (i = 0; i < NBRS; i++, tb++) {
3261 /* if request is valid and for this file, we've found it */
3262 if (tb->refCount > 0 && avc == tb->vc) {
3265 * If CSafeStore is on, then we don't awaken the guy
3266 * waiting for the store until the whole store has finished.
3267 * Otherwise, we do it now. Note that if CSafeStore is on,
3268 * the BStore routine actually wakes up the user, instead
3270 * I think this is redundant now because this sort of thing
3271 * is already being handled by the higher-level code.
3273 if ((avc->states & CSafeStore) == 0) {
3275 tb->flags |= BUVALID;
3276 if (tb->flags & BUWAIT) {
3277 tb->flags &= ~BUWAIT;
3289 * Given a file name and inode, set up that file to be an
3290 * active member in the AFS cache. This also involves checking
3291 * the usability of its data.
3293 * \param afile Name of the cache file to initialize.
3294 * \param ainode Inode of the file.
3296 * \note Environment:
3297 * This function is called only during initialization.
3300 afs_InitCacheFile(char *afile, ino_t ainode)
3302 register afs_int32 code;
3303 #if defined(AFS_LINUX22_ENV)
3304 struct dentry *filevp;
3306 struct vnode *filevp;
3310 struct osi_file *tfile;
3311 struct osi_stat tstat;
3312 register struct dcache *tdc;
3314 AFS_STATCNT(afs_InitCacheFile);
3315 index = afs_stats_cmperf.cacheNumEntries;
3316 if (index >= afs_cacheFiles)
3319 MObtainWriteLock(&afs_xdcache, 282);
3320 tdc = afs_GetDSlot(index, NULL);
3321 ReleaseReadLock(&tdc->tlock);
3322 MReleaseWriteLock(&afs_xdcache);
3324 ObtainWriteLock(&tdc->lock, 621);
3325 MObtainWriteLock(&afs_xdcache, 622);
3327 code = gop_lookupname(afile, AFS_UIOSYS, 0, &filevp);
3329 ReleaseWriteLock(&afs_xdcache);
3330 ReleaseWriteLock(&tdc->lock);
3335 * We have a VN_HOLD on filevp. Get the useful info out and
3336 * return. We make use of the fact that the cache is in the
3337 * UFS file system, and just record the inode number.
3339 #ifdef AFS_LINUX22_ENV
3340 tdc->f.inode = VTOI(filevp->d_inode)->i_number;
3343 tdc->f.inode = afs_vnodeToInumber(filevp);
3345 #endif /* AFS_LINUX22_ENV */
3347 tdc->f.inode = ainode;
3350 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3352 tfile = osi_UFSOpen(tdc->f.inode);
3353 code = afs_osi_Stat(tfile, &tstat);
3355 osi_Panic("initcachefile stat");
3358 * If file size doesn't match the cache info file, it's probably bad.
3360 if (tdc->f.chunkBytes != tstat.size)
3362 tdc->f.chunkBytes = 0;
3365 * If file changed within T (120?) seconds of cache info file, it's
3366 * probably bad. In addition, if slot changed within last T seconds,
3367 * the cache info file may be incorrectly identified, and so slot
3370 if (cacheInfoModTime < tstat.mtime + 120)
3372 if (cacheInfoModTime < tdc->f.modTime + 120)
3374 /* In case write through is behind, make sure cache items entry is
3375 * at least as new as the chunk.
3377 if (tdc->f.modTime < tstat.mtime)
3380 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3381 if (tstat.size != 0)
3382 osi_UFSTruncate(tfile, 0);
3383 tdc->f.states &= ~(DRO|DBackup|DRW);
3384 afs_DCMoveBucket(tdc, 0, 0);
3385 /* put entry in free cache slot list */
3386 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3387 afs_freeDCList = index;
3389 afs_indexFlags[index] |= IFFree;
3390 afs_indexUnique[index] = 0;
3393 * We must put this entry in the appropriate hash tables.
3394 * Note that i is still set from the above DCHash call
3396 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3397 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3398 afs_dchashTbl[code] = tdc->index;
3399 code = DVHash(&tdc->f.fid);
3400 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3401 afs_dvhashTbl[code] = tdc->index;
3402 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3404 /* has nontrivial amt of data */
3405 afs_indexFlags[index] |= IFEverUsed;
3406 afs_stats_cmperf.cacheFilesReused++;
3408 * Initialize index times to file's mod times; init indexCounter
3411 hset32(afs_indexTimes[index], tstat.atime);
3412 if (hgetlo(afs_indexCounter) < tstat.atime) {
3413 hset32(afs_indexCounter, tstat.atime);
3415 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3416 } /*File is not bad */
3418 osi_UFSClose(tfile);
3419 tdc->f.states &= ~DWriting;
3420 tdc->dflags &= ~DFEntryMod;
3421 /* don't set f.modTime; we're just cleaning up */
3422 afs_WriteDCache(tdc, 0);
3423 ReleaseWriteLock(&afs_xdcache);
3424 ReleaseWriteLock(&tdc->lock);
3426 afs_stats_cmperf.cacheNumEntries++;
3431 /*Max # of struct dcache's resident at any time*/
3433 * If 'dchint' is enabled then in-memory dcache min is increased because of
3439 * Initialize dcache related variables.
3449 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3451 register struct dcache *tdp;
3455 afs_freeDCList = NULLIDX;
3456 afs_discardDCList = NULLIDX;
3457 afs_freeDCCount = 0;
3458 afs_freeDSList = NULL;
3459 hzero(afs_indexCounter);
3461 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3467 if (achunk < 0 || achunk > 30)
3468 achunk = 13; /* Use default */
3469 AFS_SETCHUNKSIZE(achunk);
3475 if (aflags & AFSCALL_INIT_MEMCACHE) {
3477 * Use a memory cache instead of a disk cache
3479 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3480 afs_cacheType = &afs_MemCacheOps;
3481 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3482 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3483 /* ablocks is reported in 1K blocks */
3484 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3486 printf("afsd: memory cache too large for available memory.\n");
3487 printf("afsd: AFS files cannot be accessed.\n\n");
3489 afiles = ablocks = 0;
3491 printf("Memory cache: Allocating %d dcache entries...",
3494 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3495 afs_cacheType = &afs_UfsCacheOps;
3498 if (aDentries > 512)
3499 afs_dhashsize = 2048;
3500 /* initialize hash tables */
3502 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3504 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3505 for (i = 0; i < afs_dhashsize; i++) {
3506 afs_dvhashTbl[i] = NULLIDX;
3507 afs_dchashTbl[i] = NULLIDX;
3509 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3510 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3511 for (i = 0; i < afiles; i++) {
3512 afs_dvnextTbl[i] = NULLIDX;
3513 afs_dcnextTbl[i] = NULLIDX;
3516 /* Allocate and zero the pointer array to the dcache entries */
3517 afs_indexTable = (struct dcache **)
3518 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3519 memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3521 (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3522 memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3524 (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3525 memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3526 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3527 memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
3529 /* Allocate and thread the struct dcache entries themselves */
3530 tdp = afs_Initial_freeDSList =
3531 (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3532 memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
3533 #ifdef KERNEL_HAVE_PIN
3534 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3535 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3536 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3537 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3538 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3539 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3540 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3541 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3542 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3545 afs_freeDSList = &tdp[0];
3546 for (i = 0; i < aDentries - 1; i++) {
3547 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3548 RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3549 RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3550 RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3552 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3553 RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3554 RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3555 RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3557 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3558 afs_cacheBlocks = ablocks;
3559 afs_ComputeCacheParms(); /* compute parms based on cache size */
3561 afs_dcentries = aDentries;
3563 afs_stats_cmperf.cacheBucket0_Discarded =
3564 afs_stats_cmperf.cacheBucket1_Discarded =
3565 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3571 * Shuts down the cache.
3575 shutdown_dcache(void)
3579 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3580 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3581 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3582 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3583 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3584 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3585 afs_osi_Free(afs_Initial_freeDSList,
3586 afs_dcentries * sizeof(struct dcache));
3587 #ifdef KERNEL_HAVE_PIN
3588 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3589 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3590 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3591 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3592 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3593 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3594 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3598 for (i = 0; i < afs_dhashsize; i++) {
3599 afs_dvhashTbl[i] = NULLIDX;
3600 afs_dchashTbl[i] = NULLIDX;
3603 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3604 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3606 afs_blocksUsed = afs_dcentries = 0;
3607 afs_stats_cmperf.cacheBucket0_Discarded =
3608 afs_stats_cmperf.cacheBucket1_Discarded =
3609 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3610 hzero(afs_indexCounter);
3612 afs_freeDCCount = 0;
3613 afs_freeDCList = NULLIDX;
3614 afs_discardDCList = NULLIDX;
3615 afs_freeDSList = afs_Initial_freeDSList = 0;
3617 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3622 #if defined(AFS_DISCON_ENV)
3625 * Make a shadow copy of a dir's dcaches. It's used for disconnected
3626 * operations like remove/create/rename to keep the original directory data.
3627 * On reconnection, we can diff the original data with the server and get the
3628 * server changes and with the local data to get the local changes.
3630 * \param avc The dir vnode.
3632 * \return 0 for success.
3634 * \note The only lock allowed to be set is the dir's vcache entry, and it
3635 * must be set in write mode.
3636 * \note The vcache entry must be write locked.
3638 int afs_MakeShadowDir(struct vcache *avc)
3640 int j, i, index, code, ret_code = 0, offset, trans_size, block;
3641 struct dcache *tdc, *new_dc = NULL;
3642 struct osi_file *tfile_src, *tfile_dst;
3643 struct VenusFid shadow_fid;
3647 /* Is this a dir? */
3648 if (vType(avc) != VDIR)
3651 /* Generate a fid for the shadow dir. */
3652 shadow_fid.Cell = avc->fid.Cell;
3653 shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3654 afs_GenShadowFid(&shadow_fid);
3656 /* For each dcache, do copy it into a new fresh one. */
3657 i = DVHash(&avc->fid);
3658 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
3659 /* Making sure that this isn't going to get locked twice. */
3661 /* XXX: Moved it from outside of the loop.
3662 * Maybe it's not quite okay because of the use of
3663 * dvhashTbl (once) in the for statement.
3665 ObtainWriteLock(&afs_xdcache, 716);
3669 i = afs_dvnextTbl[index];
3670 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
3671 tdc = afs_GetDSlot(index, NULL);
3673 ReleaseReadLock(&tdc->tlock);
3675 if (!FidCmp(&tdc->f.fid, &avc->fid)) {
3677 /* Got a dir's dcache. */
3680 /* Get a fresh dcache. */
3681 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3683 /* Unlock hash for now. Don't need it during operations on the
3684 * dcache. Oh, and we can't use it because of the locking
3687 /* XXX: So much for lock ierarchy, the afs_AllocDCache doesn't
3690 //ReleaseWriteLock(&afs_xdcache);
3692 ObtainReadLock(&tdc->lock);
3694 /* Set up the new fid. */
3695 /* Copy interesting data from original dir dcache. */
3696 new_dc->mflags = tdc->mflags;
3697 new_dc->dflags = tdc->dflags;
3698 new_dc->f.modTime = tdc->f.modTime;
3699 new_dc->f.versionNo = tdc->f.versionNo;
3700 new_dc->f.states = tdc->f.states;
3701 new_dc->f.chunk= tdc->f.chunk;
3702 new_dc->f.chunkBytes = tdc->f.chunkBytes;
3705 * Now add to the two hash chains - note that i is still set
3706 * from the above DCHash call.
3708 //ObtainWriteLock(&afs_xdcache, 713);
3710 j = DCHash(&shadow_fid, 0);
3711 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[j];
3712 afs_dchashTbl[j] = new_dc->index;
3714 j = DVHash(&shadow_fid);
3715 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[j];
3716 afs_dvhashTbl[j] = new_dc->index;
3717 afs_MaybeWakeupTruncateDaemon();
3719 ReleaseWriteLock(&afs_xdcache);
3721 /* Alloc a 4k block. */
3722 data = (char *) afs_osi_Alloc(4096);
3724 printf("afs_MakeShadowDir: could not alloc data\n");
3729 /* Open the files. */
3730 tfile_src = afs_CFileOpen(tdc->f.inode);
3731 tfile_dst = afs_CFileOpen(new_dc->f.inode);
3733 /* Init no of blocks to be read and offset. */
3734 block = (tdc->f.chunkBytes / 4096);
3737 /* And now copy dir dcache data into this dcache,
3740 while (block >= 0) {
3742 /* Last chunk might have less bytes to transfer. */
3745 trans_size = (tdc->f.chunkBytes % 4096);
3747 /* An exact no of 4k blocks. */
3752 /* Read a chunk from the dcache. */
3753 code = afs_CFileRead(tfile_src, offset, data, trans_size);
3754 if (code < trans_size) {
3755 /* Can't access file, stop doing stuff and return error. */
3760 /* Write it to the new dcache. */
3761 code = afs_CFileWrite(tfile_dst, offset, data, trans_size);
3762 if (code < trans_size) {
3769 } /* while (block) */
3771 afs_CFileClose(tfile_dst);
3772 afs_CFileClose(tfile_src);
3774 afs_osi_Free(data, 4096);
3776 ReleaseWriteLock(&new_dc->lock);
3777 ReleaseReadLock(&tdc->lock);
3779 afs_PutDCache(new_dc);
3780 } /* if dcache fid match */
3782 } /* if unuiquifier match */
3786 ReleaseWriteLock(&afs_xdcache);
3789 if (!avc->ddirty_flags) {
3790 ObtainWriteLock(&afs_DDirtyVCListLock, 763);
3791 AFS_DISCON_ADD_DIRTY(avc);
3792 ReleaseWriteLock(&afs_DDirtyVCListLock);
3794 avc->shVnode = shadow_fid.Fid.Vnode;
3795 avc->shUnique = shadow_fid.Fid.Unique;
3796 avc->ddirty_flags |= VDisconShadowed;
3803 * Delete the dcaches of a shadow dir.
3805 * \param avc The vcache containing the shadow fid.
3807 * \note avc must be write locked.
3809 void afs_DeleteShadowDir(struct vcache *avc)
3812 struct VenusFid shadow_fid;
3814 shadow_fid.Cell = avc->fid.Cell;
3815 shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3816 shadow_fid.Fid.Vnode = avc->shVnode;
3817 shadow_fid.Fid.Unique = avc->shUnique;
3819 tdc = afs_FindDCacheByFid(&shadow_fid);
3821 afs_HashOutDCache(tdc, 1);
3822 afs_DiscardDCache(tdc);
3825 /* Remove shadowed dir flag. */
3826 avc->ddirty_flags &= ~VDisconShadowed;