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 */
2410 * Not a dynamic vnode: do the real fetch.
2415 * avc->lock(R) if setLocks && !slowPass
2416 * avc->lock(W) if !setLocks || slowPass
2420 tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
2422 afs_int32 length_hi, length, bytes;
2426 (accP->numReplicasAccessed)++;
2428 #endif /* AFS_NOSTATS */
2429 if (!setLocks || slowPass) {
2430 avc->callback = tc->srvr->server;
2432 newCallback = tc->srvr->server;
2437 tcall = rx_NewCall(tc->id);
2440 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
2441 #ifdef AFS_64BIT_CLIENT
2442 length_hi = code = 0;
2443 if (!afs_serverHasNo64Bit(tc)) {
2447 StartRXAFS_FetchData64(tcall,
2448 (struct AFSFid *)&avc->fid.
2449 Fid, Position, tsize);
2452 afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2453 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32,
2457 rx_Read(tcall, (char *)&length_hi,
2460 if (bytes == sizeof(afs_int32)) {
2461 length_hi = ntohl(length_hi);
2464 code = rx_Error(tcall);
2466 code1 = rx_EndCall(tcall, code);
2468 tcall = (struct rx_call *)0;
2472 if (code == RXGEN_OPCODE || afs_serverHasNo64Bit(tc)) {
2473 if (Position > 0x7FFFFFFF) {
2480 tcall = rx_NewCall(tc->id);
2482 StartRXAFS_FetchData(tcall, (struct AFSFid *)
2487 afs_serverSetNo64Bit(tc);
2492 rx_Read(tcall, (char *)&length,
2495 if (bytes == sizeof(afs_int32)) {
2496 length = ntohl(length);
2498 code = rx_Error(tcall);
2501 FillInt64(lengthFound, length_hi, length);
2502 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64LENG,
2503 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
2505 ICL_HANDLE_OFFSET(lengthFound));
2506 #else /* AFS_64BIT_CLIENT */
2509 StartRXAFS_FetchData(tcall,
2510 (struct AFSFid *)&avc->fid.Fid,
2516 rx_Read(tcall, (char *)&length,
2519 if (bytes == sizeof(afs_int32)) {
2520 length = ntohl(length);
2522 code = rx_Error(tcall);
2525 #endif /* AFS_64BIT_CLIENT */
2530 &(afs_stats_cmfullperf.rpc.
2531 fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
2532 osi_GetuTime(&xferStartTime);
2535 afs_CacheFetchProc(tcall, file,
2536 (afs_size_t) Position, tdc,
2538 &bytesXferred, length);
2540 osi_GetuTime(&xferStopTime);
2541 (xferP->numXfers)++;
2543 (xferP->numSuccesses)++;
2544 afs_stats_XferSumBytes
2545 [AFS_STATS_FS_XFERIDX_FETCHDATA] +=
2547 (xferP->sumBytes) +=
2548 (afs_stats_XferSumBytes
2549 [AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
2550 afs_stats_XferSumBytes
2551 [AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
2552 if (bytesXferred < xferP->minBytes)
2553 xferP->minBytes = bytesXferred;
2554 if (bytesXferred > xferP->maxBytes)
2555 xferP->maxBytes = bytesXferred;
2558 * Tally the size of the object. Note: we tally the actual size,
2559 * NOT the number of bytes that made it out over the wire.
2561 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
2562 (xferP->count[0])++;
2563 else if (bytesToXfer <=
2564 AFS_STATS_MAXBYTES_BUCKET1)
2565 (xferP->count[1])++;
2566 else if (bytesToXfer <=
2567 AFS_STATS_MAXBYTES_BUCKET2)
2568 (xferP->count[2])++;
2569 else if (bytesToXfer <=
2570 AFS_STATS_MAXBYTES_BUCKET3)
2571 (xferP->count[3])++;
2572 else if (bytesToXfer <=
2573 AFS_STATS_MAXBYTES_BUCKET4)
2574 (xferP->count[4])++;
2575 else if (bytesToXfer <=
2576 AFS_STATS_MAXBYTES_BUCKET5)
2577 (xferP->count[5])++;
2578 else if (bytesToXfer <=
2579 AFS_STATS_MAXBYTES_BUCKET6)
2580 (xferP->count[6])++;
2581 else if (bytesToXfer <=
2582 AFS_STATS_MAXBYTES_BUCKET7)
2583 (xferP->count[7])++;
2585 (xferP->count[8])++;
2587 afs_stats_GetDiff(elapsedTime, xferStartTime,
2589 afs_stats_AddTo((xferP->sumTime), elapsedTime);
2590 afs_stats_SquareAddTo((xferP->sqrTime),
2592 if (afs_stats_TimeLessThan
2593 (elapsedTime, (xferP->minTime))) {
2594 afs_stats_TimeAssign((xferP->minTime),
2597 if (afs_stats_TimeGreaterThan
2598 (elapsedTime, (xferP->maxTime))) {
2599 afs_stats_TimeAssign((xferP->maxTime),
2605 afs_CacheFetchProc(tcall, file, Position, tdc,
2607 #endif /* AFS_NOSTATS */
2612 EndRXAFS_FetchData(tcall, &tsmall->OutStatus,
2620 code1 = rx_EndCall(tcall, code);
2629 /* callback could have been broken (or expired) in a race here,
2630 * but we return the data anyway. It's as good as we knew about
2631 * when we started. */
2633 * validPos is updated by CacheFetchProc, and can only be
2634 * modifed under a dcache write lock, which we've blocked out
2636 size = tdc->validPos - Position; /* actual segment size */
2639 afs_CFileTruncate(file, size); /* prune it */
2641 if (!setLocks || slowPass) {
2642 ObtainWriteLock(&afs_xcbhash, 453);
2643 afs_DequeueCallback(avc);
2644 avc->states &= ~(CStatd | CUnique);
2645 avc->callback = NULL;
2646 ReleaseWriteLock(&afs_xcbhash);
2647 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2648 osi_dnlc_purgedp(avc);
2650 /* Something lost. Forget about performance, and go
2651 * back with a vcache write lock.
2653 afs_CFileTruncate(file, 0);
2654 afs_AdjustSize(tdc, 0);
2655 afs_CFileClose(file);
2656 osi_FreeLargeSpace(tsmall);
2658 ReleaseWriteLock(&tdc->lock);
2661 ReleaseReadLock(&avc->lock);
2663 goto RetryGetDCache;
2667 } while (afs_Analyze
2668 (tc, code, &avc->fid, areq,
2669 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2673 * avc->lock(R) if setLocks && !slowPass
2674 * avc->lock(W) if !setLocks || slowPass
2680 * In the case of replicated access, jot down info on the number of
2681 * attempts it took before we got through or gave up.
2684 if (numFetchLoops <= 1)
2685 (accP->refFirstReplicaOK)++;
2686 if (numFetchLoops > accP->maxReplicasPerRef)
2687 accP->maxReplicasPerRef = numFetchLoops;
2689 #endif /* AFS_NOSTATS */
2691 tdc->dflags &= ~DFFetching;
2692 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2693 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2694 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2695 tdc, ICL_TYPE_INT32, tdc->dflags);
2696 if (avc->execsOrWriters == 0)
2697 tdc->f.states &= ~DWriting;
2699 /* now, if code != 0, we have an error and should punt.
2700 * note that we have the vcache write lock, either because
2701 * !setLocks or slowPass.
2704 afs_CFileTruncate(file, 0);
2705 afs_AdjustSize(tdc, 0);
2706 afs_CFileClose(file);
2707 ZapDCE(tdc); /* sets DFEntryMod */
2708 if (vType(avc) == VDIR) {
2711 tdc->f.states &= ~(DRO|DBackup|DRW);
2712 afs_DCMoveBucket(tdc, 0, 0);
2713 ReleaseWriteLock(&tdc->lock);
2715 if (!afs_IsDynroot(avc)) {
2716 ObtainWriteLock(&afs_xcbhash, 454);
2717 afs_DequeueCallback(avc);
2718 avc->states &= ~(CStatd | CUnique);
2719 ReleaseWriteLock(&afs_xcbhash);
2720 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2721 osi_dnlc_purgedp(avc);
2724 * avc->lock(W); assert(!setLocks || slowPass)
2726 osi_Assert(!setLocks || slowPass);
2728 tdc->f.states &= ~(DRO|DBackup|DRW);
2729 afs_DCMoveBucket(tdc, 0, 0);
2734 /* otherwise we copy in the just-fetched info */
2735 afs_CFileClose(file);
2736 afs_AdjustSize(tdc, size); /* new size */
2738 * Copy appropriate fields into vcache. Status is
2739 * copied later where we selectively acquire the
2740 * vcache write lock.
2743 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2745 setVcacheStatus = 1;
2746 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2747 tsmall->OutStatus.DataVersion);
2748 tdc->dflags |= DFEntryMod;
2749 afs_indexFlags[tdc->index] |= IFEverUsed;
2750 ConvertWToSLock(&tdc->lock);
2751 } /*Data version numbers don't match */
2754 * Data version numbers match.
2756 afs_stats_cmperf.dcacheHits++;
2757 } /*Data version numbers match */
2759 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2763 * avc->lock(R) if setLocks && !slowPass
2764 * avc->lock(W) if !setLocks || slowPass
2765 * tdc->lock(S) if tdc
2769 * See if this was a reference to a file in the local cell.
2771 if (afs_IsPrimaryCellNum(avc->fid.Cell))
2772 afs_stats_cmperf.dlocalAccesses++;
2774 afs_stats_cmperf.dremoteAccesses++;
2776 /* Fix up LRU info */
2779 MObtainWriteLock(&afs_xdcache, 602);
2780 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2781 hadd32(afs_indexCounter, 1);
2782 MReleaseWriteLock(&afs_xdcache);
2784 /* return the data */
2785 if (vType(avc) == VDIR)
2788 *aoffset = AFS_CHUNKOFFSET(abyte);
2789 *alen = (tdc->f.chunkBytes - *aoffset);
2790 ReleaseSharedLock(&tdc->lock);
2795 * avc->lock(R) if setLocks && !slowPass
2796 * avc->lock(W) if !setLocks || slowPass
2799 /* Fix up the callback and status values in the vcache */
2801 if (setLocks && !slowPass) {
2804 * This is our dirty little secret to parallel fetches.
2805 * We don't write-lock the vcache while doing the fetch,
2806 * but potentially we'll need to update the vcache after
2807 * the fetch is done.
2809 * Drop the read lock and try to re-obtain the write
2810 * lock. If the vcache still has the same DV, it's
2811 * ok to go ahead and install the new data.
2813 afs_hyper_t currentDV, statusDV;
2815 hset(currentDV, avc->m.DataVersion);
2817 if (setNewCallback && avc->callback != newCallback)
2821 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2822 tsmall->OutStatus.DataVersion);
2824 if (setVcacheStatus && avc->m.Length != tsmall->OutStatus.Length)
2826 if (setVcacheStatus && !hsame(currentDV, statusDV))
2830 ReleaseReadLock(&avc->lock);
2832 if (doVcacheUpdate) {
2833 ObtainWriteLock(&avc->lock, 615);
2834 if (!hsame(avc->m.DataVersion, currentDV)) {
2835 /* We lose. Someone will beat us to it. */
2837 ReleaseWriteLock(&avc->lock);
2842 /* With slow pass, we've already done all the updates */
2844 ReleaseWriteLock(&avc->lock);
2847 /* Check if we need to perform any last-minute fixes with a write-lock */
2848 if (!setLocks || doVcacheUpdate) {
2850 avc->callback = newCallback;
2851 if (tsmall && setVcacheStatus)
2852 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2854 ReleaseWriteLock(&avc->lock);
2858 osi_FreeLargeSpace(tsmall);
2861 } /*afs_GetDCache */
2865 * afs_WriteThroughDSlots
2868 * Sweep through the dcache slots and write out any modified
2869 * in-memory data back on to our caching store.
2875 * The afs_xdcache is write-locked through this whole affair.
2878 afs_WriteThroughDSlots(void)
2880 register struct dcache *tdc;
2881 register afs_int32 i, touchedit = 0;
2883 struct afs_q DirtyQ, *tq;
2885 AFS_STATCNT(afs_WriteThroughDSlots);
2888 * Because of lock ordering, we can't grab dcache locks while
2889 * holding afs_xdcache. So we enter xdcache, get a reference
2890 * for every dcache entry, and exit xdcache.
2892 MObtainWriteLock(&afs_xdcache, 283);
2894 for (i = 0; i < afs_cacheFiles; i++) {
2895 tdc = afs_indexTable[i];
2897 /* Grab tlock in case the existing refcount isn't zero */
2898 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2899 ObtainWriteLock(&tdc->tlock, 623);
2901 ReleaseWriteLock(&tdc->tlock);
2903 QAdd(&DirtyQ, &tdc->dirty);
2906 MReleaseWriteLock(&afs_xdcache);
2909 * Now, for each dcache entry we found, check if it's dirty.
2910 * If so, get write-lock, get afs_xdcache, which protects
2911 * afs_cacheInodep, and flush it. Don't forget to put back
2915 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2917 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2919 if (tdc->dflags & DFEntryMod) {
2922 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2924 /* Now that we have the write lock, double-check */
2925 if (wrLock && (tdc->dflags & DFEntryMod)) {
2926 tdc->dflags &= ~DFEntryMod;
2927 MObtainWriteLock(&afs_xdcache, 620);
2928 afs_WriteDCache(tdc, 1);
2929 MReleaseWriteLock(&afs_xdcache);
2933 ReleaseWriteLock(&tdc->lock);
2939 MObtainWriteLock(&afs_xdcache, 617);
2940 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2941 /* Touch the file to make sure that the mtime on the file is kept
2942 * up-to-date to avoid losing cached files on cold starts because
2943 * their mtime seems old...
2945 struct afs_fheader theader;
2947 theader.magic = AFS_FHMAGIC;
2948 theader.firstCSize = AFS_FIRSTCSIZE;
2949 theader.otherCSize = AFS_OTHERCSIZE;
2950 theader.version = AFS_CI_VERSION;
2951 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2953 MReleaseWriteLock(&afs_xdcache);
2960 * Return a pointer to an freshly initialized dcache entry using
2961 * a memory-based cache. The tlock will be read-locked.
2964 * aslot : Dcache slot to look at.
2965 * tmpdc : Ptr to dcache entry.
2968 * Must be called with afs_xdcache write-locked.
2972 afs_MemGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2974 register struct dcache *tdc;
2977 AFS_STATCNT(afs_MemGetDSlot);
2978 if (CheckLock(&afs_xdcache) != -1)
2979 osi_Panic("getdslot nolock");
2980 if (aslot < 0 || aslot >= afs_cacheFiles)
2981 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2982 tdc = afs_indexTable[aslot];
2984 QRemove(&tdc->lruq); /* move to queue head */
2985 QAdd(&afs_DLRU, &tdc->lruq);
2986 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2987 ObtainWriteLock(&tdc->tlock, 624);
2989 ConvertWToRLock(&tdc->tlock);
2992 if (tmpdc == NULL) {
2993 if (!afs_freeDSList)
2994 afs_GetDownDSlot(4);
2995 if (!afs_freeDSList) {
2996 /* none free, making one is better than a panic */
2997 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2998 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2999 #ifdef KERNEL_HAVE_PIN
3000 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
3003 tdc = afs_freeDSList;
3004 afs_freeDSList = (struct dcache *)tdc->lruq.next;
3007 tdc->dflags = 0; /* up-to-date, not in free q */
3009 QAdd(&afs_DLRU, &tdc->lruq);
3010 if (tdc->lruq.prev == &tdc->lruq)
3011 osi_Panic("lruq 3");
3017 /* initialize entry */
3018 tdc->f.fid.Cell = 0;
3019 tdc->f.fid.Fid.Volume = 0;
3021 hones(tdc->f.versionNo);
3022 tdc->f.inode = aslot;
3023 tdc->dflags |= DFEntryMod;
3026 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3029 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3030 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3031 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3034 RWLOCK_INIT(&tdc->lock, "dcache lock");
3035 RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3036 RWLOCK_INIT(&tdc->mflock, "dcache flock");
3037 ObtainReadLock(&tdc->tlock);
3040 afs_indexTable[aslot] = tdc;
3043 } /*afs_MemGetDSlot */
3045 unsigned int last_error = 0, lasterrtime = 0;
3051 * Return a pointer to an freshly initialized dcache entry using
3052 * a UFS-based disk cache. The dcache tlock will be read-locked.
3055 * aslot : Dcache slot to look at.
3056 * tmpdc : Ptr to dcache entry.
3059 * afs_xdcache lock write-locked.
3062 afs_UFSGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
3064 register afs_int32 code;
3065 register struct dcache *tdc;
3069 AFS_STATCNT(afs_UFSGetDSlot);
3070 if (CheckLock(&afs_xdcache) != -1)
3071 osi_Panic("getdslot nolock");
3072 if (aslot < 0 || aslot >= afs_cacheFiles)
3073 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3074 tdc = afs_indexTable[aslot];
3076 QRemove(&tdc->lruq); /* move to queue head */
3077 QAdd(&afs_DLRU, &tdc->lruq);
3078 /* Grab tlock in case refCount != 0 */
3079 ObtainWriteLock(&tdc->tlock, 625);
3081 ConvertWToRLock(&tdc->tlock);
3084 /* otherwise we should read it in from the cache file */
3086 * If we weren't passed an in-memory region to place the file info,
3087 * we have to allocate one.
3089 if (tmpdc == NULL) {
3090 if (!afs_freeDSList)
3091 afs_GetDownDSlot(4);
3092 if (!afs_freeDSList) {
3093 /* none free, making one is better than a panic */
3094 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
3095 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
3096 #ifdef KERNEL_HAVE_PIN
3097 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
3100 tdc = afs_freeDSList;
3101 afs_freeDSList = (struct dcache *)tdc->lruq.next;
3104 tdc->dflags = 0; /* up-to-date, not in free q */
3106 QAdd(&afs_DLRU, &tdc->lruq);
3107 if (tdc->lruq.prev == &tdc->lruq)
3108 osi_Panic("lruq 3");
3115 * Seek to the aslot'th entry and read it in.
3118 afs_osi_Read(afs_cacheInodep,
3119 sizeof(struct fcache) * aslot +
3120 sizeof(struct afs_fheader), (char *)(&tdc->f),
3121 sizeof(struct fcache));
3123 if (code != sizeof(struct fcache))
3125 if (!afs_CellNumValid(tdc->f.fid.Cell))
3129 tdc->f.fid.Cell = 0;
3130 tdc->f.fid.Fid.Volume = 0;
3132 hones(tdc->f.versionNo);
3133 tdc->dflags |= DFEntryMod;
3134 #if defined(KERNEL_HAVE_UERROR)
3135 last_error = getuerror();
3137 lasterrtime = osi_Time();
3138 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3139 tdc->f.states &= ~(DRO|DBackup|DRW);
3140 afs_DCMoveBucket(tdc, 0, 0);
3143 if (tdc->f.states & DRO) {
3144 afs_DCMoveBucket(tdc, 0, 2);
3145 } else if (tdc->f.states & DBackup) {
3146 afs_DCMoveBucket(tdc, 0, 1);
3148 afs_DCMoveBucket(tdc, 0, 1);
3154 if (tdc->f.chunk >= 0)
3155 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
3160 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3161 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3162 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3165 RWLOCK_INIT(&tdc->lock, "dcache lock");
3166 RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3167 RWLOCK_INIT(&tdc->mflock, "dcache flock");
3168 ObtainReadLock(&tdc->tlock);
3171 * If we didn't read into a temporary dcache region, update the
3172 * slot pointer table.
3175 afs_indexTable[aslot] = tdc;
3178 } /*afs_UFSGetDSlot */
3183 * Write a particular dcache entry back to its home in the
3186 * \param adc Pointer to the dcache entry to write.
3187 * \param atime If true, set the modtime on the file to the current time.
3189 * \note Environment:
3190 * Must be called with the afs_xdcache lock at least read-locked,
3191 * and dcache entry at least read-locked.
3192 * The reference count is not changed.
3196 afs_WriteDCache(register struct dcache *adc, int atime)
3198 register afs_int32 code;
3200 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3202 AFS_STATCNT(afs_WriteDCache);
3203 osi_Assert(WriteLocked(&afs_xdcache));
3205 adc->f.modTime = osi_Time();
3207 * Seek to the right dcache slot and write the in-memory image out to disk.
3209 afs_cellname_write();
3211 afs_osi_Write(afs_cacheInodep,
3212 sizeof(struct fcache) * adc->index +
3213 sizeof(struct afs_fheader), (char *)(&adc->f),
3214 sizeof(struct fcache));
3215 if (code != sizeof(struct fcache))
3223 * Wake up users of a particular file waiting for stores to take
3226 * \param avc Ptr to related vcache entry.
3228 * \note Environment:
3229 * Nothing interesting.
3232 afs_wakeup(register struct vcache *avc)
3235 register struct brequest *tb;
3237 AFS_STATCNT(afs_wakeup);
3238 for (i = 0; i < NBRS; i++, tb++) {
3239 /* if request is valid and for this file, we've found it */
3240 if (tb->refCount > 0 && avc == tb->vc) {
3243 * If CSafeStore is on, then we don't awaken the guy
3244 * waiting for the store until the whole store has finished.
3245 * Otherwise, we do it now. Note that if CSafeStore is on,
3246 * the BStore routine actually wakes up the user, instead
3248 * I think this is redundant now because this sort of thing
3249 * is already being handled by the higher-level code.
3251 if ((avc->states & CSafeStore) == 0) {
3253 tb->flags |= BUVALID;
3254 if (tb->flags & BUWAIT) {
3255 tb->flags &= ~BUWAIT;
3267 * Given a file name and inode, set up that file to be an
3268 * active member in the AFS cache. This also involves checking
3269 * the usability of its data.
3271 * \param afile Name of the cache file to initialize.
3272 * \param ainode Inode of the file.
3274 * \note Environment:
3275 * This function is called only during initialization.
3278 afs_InitCacheFile(char *afile, ino_t ainode)
3280 register afs_int32 code;
3281 #if defined(AFS_LINUX22_ENV)
3282 struct dentry *filevp;
3284 struct vnode *filevp;
3288 struct osi_file *tfile;
3289 struct osi_stat tstat;
3290 register struct dcache *tdc;
3292 AFS_STATCNT(afs_InitCacheFile);
3293 index = afs_stats_cmperf.cacheNumEntries;
3294 if (index >= afs_cacheFiles)
3297 MObtainWriteLock(&afs_xdcache, 282);
3298 tdc = afs_GetDSlot(index, NULL);
3299 ReleaseReadLock(&tdc->tlock);
3300 MReleaseWriteLock(&afs_xdcache);
3302 ObtainWriteLock(&tdc->lock, 621);
3303 MObtainWriteLock(&afs_xdcache, 622);
3305 code = gop_lookupname(afile, AFS_UIOSYS, 0, &filevp);
3307 ReleaseWriteLock(&afs_xdcache);
3308 ReleaseWriteLock(&tdc->lock);
3313 * We have a VN_HOLD on filevp. Get the useful info out and
3314 * return. We make use of the fact that the cache is in the
3315 * UFS file system, and just record the inode number.
3317 #ifdef AFS_LINUX22_ENV
3318 tdc->f.inode = VTOI(filevp->d_inode)->i_number;
3321 tdc->f.inode = afs_vnodeToInumber(filevp);
3323 #endif /* AFS_LINUX22_ENV */
3325 tdc->f.inode = ainode;
3328 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3330 tfile = osi_UFSOpen(tdc->f.inode);
3331 code = afs_osi_Stat(tfile, &tstat);
3333 osi_Panic("initcachefile stat");
3336 * If file size doesn't match the cache info file, it's probably bad.
3338 if (tdc->f.chunkBytes != tstat.size)
3340 tdc->f.chunkBytes = 0;
3343 * If file changed within T (120?) seconds of cache info file, it's
3344 * probably bad. In addition, if slot changed within last T seconds,
3345 * the cache info file may be incorrectly identified, and so slot
3348 if (cacheInfoModTime < tstat.mtime + 120)
3350 if (cacheInfoModTime < tdc->f.modTime + 120)
3352 /* In case write through is behind, make sure cache items entry is
3353 * at least as new as the chunk.
3355 if (tdc->f.modTime < tstat.mtime)
3358 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3359 if (tstat.size != 0)
3360 osi_UFSTruncate(tfile, 0);
3361 tdc->f.states &= ~(DRO|DBackup|DRW);
3362 afs_DCMoveBucket(tdc, 0, 0);
3363 /* put entry in free cache slot list */
3364 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3365 afs_freeDCList = index;
3367 afs_indexFlags[index] |= IFFree;
3368 afs_indexUnique[index] = 0;
3371 * We must put this entry in the appropriate hash tables.
3372 * Note that i is still set from the above DCHash call
3374 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3375 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3376 afs_dchashTbl[code] = tdc->index;
3377 code = DVHash(&tdc->f.fid);
3378 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3379 afs_dvhashTbl[code] = tdc->index;
3380 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3382 /* has nontrivial amt of data */
3383 afs_indexFlags[index] |= IFEverUsed;
3384 afs_stats_cmperf.cacheFilesReused++;
3386 * Initialize index times to file's mod times; init indexCounter
3389 hset32(afs_indexTimes[index], tstat.atime);
3390 if (hgetlo(afs_indexCounter) < tstat.atime) {
3391 hset32(afs_indexCounter, tstat.atime);
3393 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3394 } /*File is not bad */
3396 osi_UFSClose(tfile);
3397 tdc->f.states &= ~DWriting;
3398 tdc->dflags &= ~DFEntryMod;
3399 /* don't set f.modTime; we're just cleaning up */
3400 afs_WriteDCache(tdc, 0);
3401 ReleaseWriteLock(&afs_xdcache);
3402 ReleaseWriteLock(&tdc->lock);
3404 afs_stats_cmperf.cacheNumEntries++;
3409 /*Max # of struct dcache's resident at any time*/
3411 * If 'dchint' is enabled then in-memory dcache min is increased because of
3417 * Initialize dcache related variables.
3427 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3429 register struct dcache *tdp;
3433 afs_freeDCList = NULLIDX;
3434 afs_discardDCList = NULLIDX;
3435 afs_freeDCCount = 0;
3436 afs_freeDSList = NULL;
3437 hzero(afs_indexCounter);
3439 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3445 if (achunk < 0 || achunk > 30)
3446 achunk = 13; /* Use default */
3447 AFS_SETCHUNKSIZE(achunk);
3453 if (aflags & AFSCALL_INIT_MEMCACHE) {
3455 * Use a memory cache instead of a disk cache
3457 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3458 afs_cacheType = &afs_MemCacheOps;
3459 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3460 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3461 /* ablocks is reported in 1K blocks */
3462 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3464 printf("afsd: memory cache too large for available memory.\n");
3465 printf("afsd: AFS files cannot be accessed.\n\n");
3467 afiles = ablocks = 0;
3469 printf("Memory cache: Allocating %d dcache entries...",
3472 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3473 afs_cacheType = &afs_UfsCacheOps;
3476 if (aDentries > 512)
3477 afs_dhashsize = 2048;
3478 /* initialize hash tables */
3480 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3482 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3483 for (i = 0; i < afs_dhashsize; i++) {
3484 afs_dvhashTbl[i] = NULLIDX;
3485 afs_dchashTbl[i] = NULLIDX;
3487 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3488 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3489 for (i = 0; i < afiles; i++) {
3490 afs_dvnextTbl[i] = NULLIDX;
3491 afs_dcnextTbl[i] = NULLIDX;
3494 /* Allocate and zero the pointer array to the dcache entries */
3495 afs_indexTable = (struct dcache **)
3496 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3497 memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3499 (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3500 memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3502 (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3503 memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3504 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3505 memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
3507 /* Allocate and thread the struct dcache entries themselves */
3508 tdp = afs_Initial_freeDSList =
3509 (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3510 memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
3511 #ifdef KERNEL_HAVE_PIN
3512 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3513 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3514 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3515 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3516 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3517 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3518 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3519 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3520 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3523 afs_freeDSList = &tdp[0];
3524 for (i = 0; i < aDentries - 1; i++) {
3525 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3526 RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3527 RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3528 RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3530 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3531 RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3532 RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3533 RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3535 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3536 afs_cacheBlocks = ablocks;
3537 afs_ComputeCacheParms(); /* compute parms based on cache size */
3539 afs_dcentries = aDentries;
3541 afs_stats_cmperf.cacheBucket0_Discarded =
3542 afs_stats_cmperf.cacheBucket1_Discarded =
3543 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3549 * Shuts down the cache.
3553 shutdown_dcache(void)
3557 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3558 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3559 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3560 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3561 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3562 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3563 afs_osi_Free(afs_Initial_freeDSList,
3564 afs_dcentries * sizeof(struct dcache));
3565 #ifdef KERNEL_HAVE_PIN
3566 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3567 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3568 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3569 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3570 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3571 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3572 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3576 for (i = 0; i < afs_dhashsize; i++) {
3577 afs_dvhashTbl[i] = NULLIDX;
3578 afs_dchashTbl[i] = NULLIDX;
3581 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3582 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3584 afs_blocksUsed = afs_dcentries = 0;
3585 afs_stats_cmperf.cacheBucket0_Discarded =
3586 afs_stats_cmperf.cacheBucket1_Discarded =
3587 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3588 hzero(afs_indexCounter);
3590 afs_freeDCCount = 0;
3591 afs_freeDCList = NULLIDX;
3592 afs_discardDCList = NULLIDX;
3593 afs_freeDSList = afs_Initial_freeDSList = 0;
3595 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3600 #if defined(AFS_DISCON_ENV)
3603 * Make a shadow copy of a dir's dcaches. It's used for disconnected
3604 * operations like remove/create/rename to keep the original directory data.
3605 * On reconnection, we can diff the original data with the server and get the
3606 * server changes and with the local data to get the local changes.
3608 * \param avc The dir vnode.
3610 * \return 0 for success.
3612 * \note The only lock allowed to be set is the dir's vcache entry, and it
3613 * must be set in write mode.
3614 * \note The vcache entry must be write locked.
3616 int afs_MakeShadowDir(struct vcache *avc)
3618 int j, i, index, code, ret_code = 0, offset, trans_size, block;
3619 struct dcache *tdc, *new_dc = NULL;
3620 struct osi_file *tfile_src, *tfile_dst;
3621 struct VenusFid shadow_fid;
3625 /* Is this a dir? */
3626 if (vType(avc) != VDIR)
3629 /* Generate a fid for the shadow dir. */
3630 shadow_fid.Cell = avc->fid.Cell;
3631 shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3632 afs_GenShadowFid(&shadow_fid);
3634 /* For each dcache, do copy it into a new fresh one. */
3635 i = DVHash(&avc->fid);
3636 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
3637 /* Making sure that this isn't going to get locked twice. */
3639 /* XXX: Moved it from outside of the loop.
3640 * Maybe it's not quite okay because of the use of
3641 * dvhashTbl (once) in the for statement.
3643 ObtainWriteLock(&afs_xdcache, 716);
3647 i = afs_dvnextTbl[index];
3648 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
3649 tdc = afs_GetDSlot(index, NULL);
3651 ReleaseReadLock(&tdc->tlock);
3653 if (!FidCmp(&tdc->f.fid, &avc->fid)) {
3655 /* Got a dir's dcache. */
3658 /* Get a fresh dcache. */
3659 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3661 /* Unlock hash for now. Don't need it during operations on the
3662 * dcache. Oh, and we can't use it because of the locking
3665 /* XXX: So much for lock ierarchy, the afs_AllocDCache doesn't
3668 //ReleaseWriteLock(&afs_xdcache);
3670 ObtainReadLock(&tdc->lock);
3672 /* Set up the new fid. */
3673 /* Copy interesting data from original dir dcache. */
3674 new_dc->mflags = tdc->mflags;
3675 new_dc->dflags = tdc->dflags;
3676 new_dc->f.modTime = tdc->f.modTime;
3677 new_dc->f.versionNo = tdc->f.versionNo;
3678 new_dc->f.states = tdc->f.states;
3679 new_dc->f.chunk= tdc->f.chunk;
3680 new_dc->f.chunkBytes = tdc->f.chunkBytes;
3683 * Now add to the two hash chains - note that i is still set
3684 * from the above DCHash call.
3686 //ObtainWriteLock(&afs_xdcache, 713);
3688 j = DCHash(&shadow_fid, 0);
3689 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[j];
3690 afs_dchashTbl[j] = new_dc->index;
3692 j = DVHash(&shadow_fid);
3693 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[j];
3694 afs_dvhashTbl[j] = new_dc->index;
3695 afs_MaybeWakeupTruncateDaemon();
3697 ReleaseWriteLock(&afs_xdcache);
3699 /* Alloc a 4k block. */
3700 data = (char *) afs_osi_Alloc(4096);
3702 printf("afs_MakeShadowDir: could not alloc data\n");
3707 /* Open the files. */
3708 tfile_src = afs_CFileOpen(tdc->f.inode);
3709 tfile_dst = afs_CFileOpen(new_dc->f.inode);
3711 /* Init no of blocks to be read and offset. */
3712 block = (tdc->f.chunkBytes / 4096);
3715 /* And now copy dir dcache data into this dcache,
3718 while (block >= 0) {
3720 /* Last chunk might have less bytes to transfer. */
3723 trans_size = (tdc->f.chunkBytes % 4096);
3725 /* An exact no of 4k blocks. */
3730 /* Read a chunk from the dcache. */
3731 code = afs_CFileRead(tfile_src, offset, data, trans_size);
3732 if (code < trans_size) {
3733 /* Can't access file, stop doing stuff and return error. */
3738 /* Write it to the new dcache. */
3739 code = afs_CFileWrite(tfile_dst, offset, data, trans_size);
3740 if (code < trans_size) {
3747 } /* while (block) */
3749 afs_CFileClose(tfile_dst);
3750 afs_CFileClose(tfile_src);
3752 afs_osi_Free(data, 4096);
3754 ReleaseWriteLock(&new_dc->lock);
3755 ReleaseReadLock(&tdc->lock);
3757 afs_PutDCache(new_dc);
3758 } /* if dcache fid match */
3760 } /* if unuiquifier match */
3764 ReleaseWriteLock(&afs_xdcache);
3767 if (!avc->ddirty_flags) {
3768 ObtainWriteLock(&afs_DDirtyVCListLock, 763);
3769 AFS_DISCON_ADD_DIRTY(avc);
3770 ReleaseWriteLock(&afs_DDirtyVCListLock);
3772 avc->shVnode = shadow_fid.Fid.Vnode;
3773 avc->shUnique = shadow_fid.Fid.Unique;
3774 avc->ddirty_flags |= VDisconShadowed;
3781 * Delete the dcaches of a shadow dir.
3783 * \param avc The vcache containing the shadow fid.
3785 * \note avc must be write locked.
3787 void afs_DeleteShadowDir(struct vcache *avc)
3790 struct VenusFid shadow_fid;
3792 shadow_fid.Cell = avc->fid.Cell;
3793 shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3794 shadow_fid.Fid.Vnode = avc->shVnode;
3795 shadow_fid.Fid.Unique = avc->shUnique;
3797 tdc = afs_FindDCacheByFid(&shadow_fid);
3799 afs_HashOutDCache(tdc, 1);
3800 afs_DiscardDCache(tdc);
3803 /* Remove shadowed dir flag. */
3804 avc->ddirty_flags &= ~VDisconShadowed;