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);
39 * --------------------- Exported definitions ---------------------
42 afs_int32 afs_blocksUsed_0; /*1K blocks in cache - in theory is zero */
43 afs_int32 afs_blocksUsed_1; /*1K blocks in cache */
44 afs_int32 afs_blocksUsed_2; /*1K blocks in cache */
45 afs_int32 afs_pct1 = -1;
46 afs_int32 afs_pct2 = -1;
47 afs_uint32 afs_tpct1 = 0;
48 afs_uint32 afs_tpct2 = 0;
49 afs_uint32 splitdcache = 0;
51 afs_lock_t afs_xdcache; /*Lock: alloc new disk cache entries */
52 afs_int32 afs_freeDCList; /*Free list for disk cache entries */
53 afs_int32 afs_freeDCCount; /*Count of elts in freeDCList */
54 afs_int32 afs_discardDCList; /*Discarded disk cache entries */
55 afs_int32 afs_discardDCCount; /*Count of elts in discardDCList */
56 struct dcache *afs_freeDSList; /*Free list for disk slots */
57 struct dcache *afs_Initial_freeDSList; /*Initial list for above */
58 ino_t cacheInode; /*Inode for CacheItems file */
59 struct osi_file *afs_cacheInodep = 0; /* file for CacheItems inode */
60 struct afs_q afs_DLRU; /*dcache LRU */
61 afs_int32 afs_dhashsize = 1024;
62 afs_int32 *afs_dvhashTbl; /*Data cache hash table */
63 afs_int32 *afs_dchashTbl; /*Data cache hash table */
64 afs_int32 *afs_dvnextTbl; /*Dcache hash table links */
65 afs_int32 *afs_dcnextTbl; /*Dcache hash table links */
66 struct dcache **afs_indexTable; /*Pointers to dcache entries */
67 afs_hyper_t *afs_indexTimes; /*Dcache entry Access times */
68 afs_int32 *afs_indexUnique; /*dcache entry Fid.Unique */
69 unsigned char *afs_indexFlags; /*(only one) Is there data there? */
70 afs_hyper_t afs_indexCounter; /*Fake time for marking index
72 afs_int32 afs_cacheFiles = 0; /*Size of afs_indexTable */
73 afs_int32 afs_cacheBlocks; /*1K blocks in cache */
74 afs_int32 afs_cacheStats; /*Stat entries in cache */
75 afs_int32 afs_blocksUsed; /*Number of blocks in use */
76 afs_int32 afs_blocksDiscarded; /*Blocks freed but not truncated */
77 afs_int32 afs_fsfragsize = 1023; /*Underlying Filesystem minimum unit
78 *of disk allocation usually 1K
79 *this value is (truefrag -1 ) to
80 *save a bunch of subtracts... */
81 #ifdef AFS_64BIT_CLIENT
82 #ifdef AFS_VM_RDWR_ENV
83 afs_size_t afs_vmMappingEnd; /* for large files (>= 2GB) the VM
84 * mapping an 32bit addressing machines
85 * can only be used below the 2 GB
86 * line. From this point upwards we
87 * must do direct I/O into the cache
88 * files. The value should be on a
90 #endif /* AFS_VM_RDWR_ENV */
91 #endif /* AFS_64BIT_CLIENT */
93 /* The following is used to ensure that new dcache's aren't obtained when
94 * the cache is nearly full.
96 int afs_WaitForCacheDrain = 0;
97 int afs_TruncateDaemonRunning = 0;
98 int afs_CacheTooFull = 0;
100 afs_int32 afs_dcentries; /* In-memory dcache entries */
103 int dcacheDisabled = 0;
105 static int afs_UFSCacheFetchProc(), afs_UFSCacheStoreProc();
106 struct afs_cacheOps afs_UfsCacheOps = {
114 afs_UFSCacheFetchProc,
115 afs_UFSCacheStoreProc,
121 struct afs_cacheOps afs_MemCacheOps = {
123 afs_MemCacheTruncate,
129 afs_MemCacheFetchProc,
130 afs_MemCacheStoreProc,
136 int cacheDiskType; /*Type of backing disk for cache */
137 struct afs_cacheOps *afs_cacheType;
140 afs_DCGetBucket(struct vcache *avc)
145 /* This should be replaced with some sort of user configurable function */
146 if (avc->states & CRO) {
148 } else if (avc->states & CBackup) {
158 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
160 afs_int32 adjustSize = newSize - oldSize;
168 afs_blocksUsed_0 += adjustSize;
169 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
172 afs_blocksUsed_1 += adjustSize;
173 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
176 afs_blocksUsed_2 += adjustSize;
177 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
185 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
193 afs_blocksUsed_0 -= size;
196 afs_blocksUsed_1 -= size;
199 afs_blocksUsed_2 -= size;
203 adc->bucket = newBucket;
208 afs_blocksUsed_0 += size;
211 afs_blocksUsed_1 += size;
214 afs_blocksUsed_2 += size;
224 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
228 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
233 afs_pct1 = afs_blocksUsed_1 / (afs_cacheBlocks / 100);
234 afs_pct2 = afs_blocksUsed_2 / (afs_cacheBlocks / 100);
236 /* Short cut: if we don't know about it, try to kill it */
237 if (phase < 2 && afs_blocksUsed_0)
240 if (afs_pct1 > afs_tpct1)
242 if (afs_pct2 > afs_tpct2)
244 return 0; /* unlikely */
252 * Warn about failing to store a file.
255 * acode : Associated error code.
256 * avolume : Volume involved.
257 * aflags : How to handle the output:
258 * aflags & 1: Print out on console
259 * aflags & 2: Print out on controlling tty
262 * Call this from close call when vnodeops is RCS unlocked.
266 afs_StoreWarn(register afs_int32 acode, afs_int32 avolume,
267 register afs_int32 aflags)
269 static char problem_fmt[] =
270 "afs: failed to store file in volume %d (%s)\n";
271 static char problem_fmt_w_error[] =
272 "afs: failed to store file in volume %d (error %d)\n";
273 static char netproblems[] = "network problems";
274 static char partfull[] = "partition full";
275 static char overquota[] = "over quota";
277 AFS_STATCNT(afs_StoreWarn);
283 afs_warn(problem_fmt, avolume, netproblems);
285 afs_warnuser(problem_fmt, avolume, netproblems);
286 } else if (acode == ENOSPC) {
291 afs_warn(problem_fmt, avolume, partfull);
293 afs_warnuser(problem_fmt, avolume, partfull);
296 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
297 * Instead ENOSPC will be sent...
299 if (acode == EDQUOT) {
304 afs_warn(problem_fmt, avolume, overquota);
306 afs_warnuser(problem_fmt, avolume, overquota);
314 afs_warn(problem_fmt_w_error, avolume, acode);
316 afs_warnuser(problem_fmt_w_error, avolume, acode);
321 afs_MaybeWakeupTruncateDaemon(void)
323 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
324 afs_CacheTooFull = 1;
325 if (!afs_TruncateDaemonRunning)
326 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
327 } else if (!afs_TruncateDaemonRunning
328 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
329 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
333 /* Keep statistics on run time for afs_CacheTruncateDaemon. This is a
334 * struct so we need only export one symbol for AIX.
336 static struct CTD_stats {
337 osi_timeval_t CTD_beforeSleep;
338 osi_timeval_t CTD_afterSleep;
339 osi_timeval_t CTD_sleepTime;
340 osi_timeval_t CTD_runTime;
344 u_int afs_min_cache = 0;
346 afs_CacheTruncateDaemon(void)
348 osi_timeval_t CTD_tmpTime;
352 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
354 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
356 osi_GetuTime(&CTD_stats.CTD_afterSleep);
357 afs_TruncateDaemonRunning = 1;
359 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
360 MObtainWriteLock(&afs_xdcache, 266);
361 if (afs_CacheTooFull) {
362 int space_needed, slots_needed;
363 /* if we get woken up, we should try to clean something out */
364 for (counter = 0; counter < 10; counter++) {
366 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
368 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
369 afs_GetDownD(slots_needed, &space_needed, 0);
370 if ((space_needed <= 0) && (slots_needed <= 0)) {
373 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
376 if (!afs_CacheIsTooFull())
377 afs_CacheTooFull = 0;
379 MReleaseWriteLock(&afs_xdcache);
382 * This is a defensive check to try to avoid starving threads
383 * that may need the global lock so thay can help free some
384 * cache space. If this thread won't be sleeping or truncating
385 * any cache files then give up the global lock so other
386 * threads get a chance to run.
388 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
389 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
390 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
394 * This is where we free the discarded cache elements.
396 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
397 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
398 afs_FreeDiscardedDCache();
401 /* See if we need to continue to run. Someone may have
402 * signalled us while we were executing.
404 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
405 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
406 /* Collect statistics on truncate daemon. */
407 CTD_stats.CTD_nSleeps++;
408 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
409 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
410 CTD_stats.CTD_beforeSleep);
411 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
413 afs_TruncateDaemonRunning = 0;
414 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
415 afs_TruncateDaemonRunning = 1;
417 osi_GetuTime(&CTD_stats.CTD_afterSleep);
418 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
419 CTD_stats.CTD_afterSleep);
420 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
422 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
424 afs_termState = AFSOP_STOP_AFSDB;
426 afs_termState = AFSOP_STOP_RXEVENT;
428 afs_osi_Wakeup(&afs_termState);
439 * Make adjustment for the new size in the disk cache entry
441 * Major Assumptions Here:
442 * Assumes that frag size is an integral power of two, less one,
443 * and that this is a two's complement machine. I don't
444 * know of any filesystems which violate this assumption...
447 * adc : Ptr to dcache entry.
448 * anewsize : New size desired.
452 afs_AdjustSize(register struct dcache *adc, register afs_int32 newSize)
454 register afs_int32 oldSize;
456 AFS_STATCNT(afs_AdjustSize);
458 adc->dflags |= DFEntryMod;
459 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
460 adc->f.chunkBytes = newSize;
463 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
464 afs_DCAdjustSize(adc, oldSize, newSize);
465 if (newSize > oldSize) {
466 /* We're growing the file, wakeup the daemon */
467 afs_MaybeWakeupTruncateDaemon();
469 afs_blocksUsed += (newSize - oldSize);
470 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
478 * This routine is responsible for moving at least one entry (but up
479 * to some number of them) from the LRU queue to the free queue.
482 * anumber : Number of entries that should ideally be moved.
483 * aneedSpace : How much space we need (1K blocks);
486 * The anumber parameter is just a hint; at least one entry MUST be
487 * moved, or we'll panic. We must be called with afs_xdcache
488 * write-locked. We should try to satisfy both anumber and aneedspace,
489 * whichever is more demanding - need to do several things:
490 * 1. only grab up to anumber victims if aneedSpace <= 0, not
491 * the whole set of MAXATONCE.
492 * 2. dynamically choose MAXATONCE to reflect severity of
493 * demand: something like (*aneedSpace >> (logChunk - 9))
494 * N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
495 * indicates that the cache is not properly configured/tuned or
496 * something. We should be able to automatically correct that problem.
499 #define MAXATONCE 16 /* max we can obtain at once */
501 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
505 struct VenusFid *afid;
509 register struct vcache *tvc;
510 afs_uint32 victims[MAXATONCE];
511 struct dcache *victimDCs[MAXATONCE];
512 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
513 afs_uint32 victimPtr; /* next free item in victim arrays */
514 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
515 afs_uint32 maxVictimPtr; /* where it is */
519 AFS_STATCNT(afs_GetDownD);
520 if (CheckLock(&afs_xdcache) != -1)
521 osi_Panic("getdownd nolock");
522 /* decrement anumber first for all dudes in free list */
523 /* SHOULD always decrement anumber first, even if aneedSpace >0,
524 * because we should try to free space even if anumber <=0 */
525 if (!aneedSpace || *aneedSpace <= 0) {
526 anumber -= afs_freeDCCount;
528 return; /* enough already free */
530 /* bounds check parameter */
531 if (anumber > MAXATONCE)
532 anumber = MAXATONCE; /* all we can do */
534 /* rewrite so phases include a better eligiblity for gc test*/
536 * The phase variable manages reclaims. Set to 0, the first pass,
537 * we don't reclaim active entries, or other than target bucket.
538 * Set to 1, we reclaim even active ones in target bucket.
539 * Set to 2, we reclaim any inactive one.
540 * Set to 3, we reclaim even active ones.
548 for (i = 0; i < afs_cacheFiles; i++)
549 /* turn off all flags */
550 afs_indexFlags[i] &= ~IFFlag;
552 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
553 /* find oldest entries for reclamation */
554 maxVictimPtr = victimPtr = 0;
555 hzero(maxVictimTime);
556 curbucket = afs_DCWhichBucket(phase, buckethint);
557 /* select victims from access time array */
558 for (i = 0; i < afs_cacheFiles; i++) {
559 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
560 /* skip if dirty or already free */
563 tdc = afs_indexTable[i];
564 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
566 /* Wrong bucket; can't use it! */
569 if (tdc && (tdc->refCount != 0)) {
570 /* Referenced; can't use it! */
573 hset(vtime, afs_indexTimes[i]);
575 /* if we've already looked at this one, skip it */
576 if (afs_indexFlags[i] & IFFlag)
579 if (victimPtr < MAXATONCE) {
580 /* if there's at least one free victim slot left */
581 victims[victimPtr] = i;
582 hset(victimTimes[victimPtr], vtime);
583 if (hcmp(vtime, maxVictimTime) > 0) {
584 hset(maxVictimTime, vtime);
585 maxVictimPtr = victimPtr;
588 } else if (hcmp(vtime, maxVictimTime) < 0) {
590 * We're older than youngest victim, so we replace at
593 /* find youngest (largest LRU) victim */
596 osi_Panic("getdownd local");
598 hset(victimTimes[j], vtime);
599 /* recompute maxVictimTime */
600 hset(maxVictimTime, vtime);
601 for (j = 0; j < victimPtr; j++)
602 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
603 hset(maxVictimTime, victimTimes[j]);
609 /* now really reclaim the victims */
610 j = 0; /* flag to track if we actually got any of the victims */
611 /* first, hold all the victims, since we're going to release the lock
612 * during the truncate operation.
614 for (i = 0; i < victimPtr; i++) {
615 tdc = afs_GetDSlot(victims[i], 0);
616 /* We got tdc->tlock(R) here */
617 if (tdc->refCount == 1)
621 ReleaseReadLock(&tdc->tlock);
625 for (i = 0; i < victimPtr; i++) {
626 /* q is first elt in dcache entry */
628 /* now, since we're dropping the afs_xdcache lock below, we
629 * have to verify, before proceeding, that there are no other
630 * references to this dcache entry, even now. Note that we
631 * compare with 1, since we bumped it above when we called
632 * afs_GetDSlot to preserve the entry's identity.
634 if (tdc && tdc->refCount == 1) {
635 unsigned char chunkFlags;
636 afs_size_t tchunkoffset = 0;
638 /* xdcache is lower than the xvcache lock */
639 MReleaseWriteLock(&afs_xdcache);
640 MObtainReadLock(&afs_xvcache);
641 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
642 MReleaseReadLock(&afs_xvcache);
643 MObtainWriteLock(&afs_xdcache, 527);
645 if (tdc->refCount > 1)
648 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
649 chunkFlags = afs_indexFlags[tdc->index];
650 if (((phase & 1) == 0) && osi_Active(tvc))
652 if (((phase & 1) == 1) && osi_Active(tvc)
653 && (tvc->states & CDCLock)
654 && (chunkFlags & IFAnyPages))
656 if (chunkFlags & IFDataMod)
658 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
659 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
660 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
661 ICL_HANDLE_OFFSET(tchunkoffset));
663 #if defined(AFS_SUN5_ENV)
665 * Now we try to invalidate pages. We do this only for
666 * Solaris. For other platforms, it's OK to recycle a
667 * dcache entry out from under a page, because the strategy
668 * function can call afs_GetDCache().
670 if (!skip && (chunkFlags & IFAnyPages)) {
673 MReleaseWriteLock(&afs_xdcache);
674 MObtainWriteLock(&tvc->vlock, 543);
675 if (tvc->multiPage) {
679 /* block locking pages */
680 tvc->vstates |= VPageCleaning;
681 /* block getting new pages */
683 MReleaseWriteLock(&tvc->vlock);
684 /* One last recheck */
685 MObtainWriteLock(&afs_xdcache, 333);
686 chunkFlags = afs_indexFlags[tdc->index];
687 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
688 || (osi_Active(tvc) && (tvc->states & CDCLock)
689 && (chunkFlags & IFAnyPages))) {
691 MReleaseWriteLock(&afs_xdcache);
694 MReleaseWriteLock(&afs_xdcache);
696 code = osi_VM_GetDownD(tvc, tdc);
698 MObtainWriteLock(&afs_xdcache, 269);
699 /* we actually removed all pages, clean and dirty */
701 afs_indexFlags[tdc->index] &=
702 ~(IFDirtyPages | IFAnyPages);
705 MReleaseWriteLock(&afs_xdcache);
707 MObtainWriteLock(&tvc->vlock, 544);
708 if (--tvc->activeV == 0
709 && (tvc->vstates & VRevokeWait)) {
710 tvc->vstates &= ~VRevokeWait;
711 afs_osi_Wakeup((char *)&tvc->vstates);
714 if (tvc->vstates & VPageCleaning) {
715 tvc->vstates &= ~VPageCleaning;
716 afs_osi_Wakeup((char *)&tvc->vstates);
719 MReleaseWriteLock(&tvc->vlock);
721 #endif /* AFS_SUN5_ENV */
723 MReleaseWriteLock(&afs_xdcache);
726 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
727 MObtainWriteLock(&afs_xdcache, 528);
728 if (afs_indexFlags[tdc->index] &
729 (IFDataMod | IFDirtyPages | IFAnyPages))
731 if (tdc->refCount > 1)
734 #if defined(AFS_SUN5_ENV)
736 /* no vnode, so IFDirtyPages is spurious (we don't
737 * sweep dcaches on vnode recycling, so we can have
738 * DIRTYPAGES set even when all pages are gone). Just
740 * Hold vcache lock to prevent vnode from being
741 * created while we're clearing IFDirtyPages.
743 afs_indexFlags[tdc->index] &=
744 ~(IFDirtyPages | IFAnyPages);
748 /* skip this guy and mark him as recently used */
749 afs_indexFlags[tdc->index] |= IFFlag;
750 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
751 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
752 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
753 ICL_HANDLE_OFFSET(tchunkoffset));
755 /* flush this dude from the data cache and reclaim;
756 * first, make sure no one will care that we damage
757 * it, by removing it from all hash tables. Then,
758 * melt it down for parts. Note that any concurrent
759 * (new possibility!) calls to GetDownD won't touch
760 * this guy because his reference count is > 0. */
761 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
762 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
763 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
764 ICL_HANDLE_OFFSET(tchunkoffset));
765 AFS_STATCNT(afs_gget);
766 afs_HashOutDCache(tdc);
767 if (tdc->f.chunkBytes != 0) {
771 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
776 afs_DiscardDCache(tdc);
781 j = 1; /* we reclaimed at least one victim */
788 /* Phase is 0 and no one was found, so try phase 1 (ignore
789 * osi_Active flag) */
792 for (i = 0; i < afs_cacheFiles; i++)
793 /* turn off all flags */
794 afs_indexFlags[i] &= ~IFFlag;
797 /* found no one in phases 0-5, we're hosed */
801 } /* big while loop */
808 * Description: remove adc from any hash tables that would allow it to be located
809 * again by afs_FindDCache or afs_GetDCache.
811 * Parameters: adc -- pointer to dcache entry to remove from hash tables.
813 * Locks: Must have the afs_xdcache lock write-locked to call this function.
816 afs_HashOutDCache(struct dcache *adc)
820 AFS_STATCNT(afs_glink);
821 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
823 /* if this guy is in the hash table, pull him out */
824 if (adc->f.fid.Fid.Volume != 0) {
825 /* remove entry from first hash chains */
826 i = DCHash(&adc->f.fid, adc->f.chunk);
827 us = afs_dchashTbl[i];
828 if (us == adc->index) {
829 /* first dude in the list */
830 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
832 /* somewhere on the chain */
833 while (us != NULLIDX) {
834 if (afs_dcnextTbl[us] == adc->index) {
835 /* found item pointing at the one to delete */
836 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
839 us = afs_dcnextTbl[us];
842 osi_Panic("dcache hc");
844 /* remove entry from *other* hash chain */
845 i = DVHash(&adc->f.fid);
846 us = afs_dvhashTbl[i];
847 if (us == adc->index) {
848 /* first dude in the list */
849 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
851 /* somewhere on the chain */
852 while (us != NULLIDX) {
853 if (afs_dvnextTbl[us] == adc->index) {
854 /* found item pointing at the one to delete */
855 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
858 us = afs_dvnextTbl[us];
861 osi_Panic("dcache hv");
865 /* prevent entry from being found on a reboot (it is already out of
866 * the hash table, but after a crash, we just look at fid fields of
867 * stable (old) entries).
869 adc->f.fid.Fid.Volume = 0; /* invalid */
871 /* mark entry as modified */
872 adc->dflags |= DFEntryMod;
876 } /*afs_HashOutDCache */
883 * Flush the given dcache entry, pulling it from hash chains
884 * and truncating the associated cache file.
887 * adc: Ptr to dcache entry to flush.
890 * This routine must be called with the afs_xdcache lock held
895 afs_FlushDCache(register struct dcache *adc)
897 AFS_STATCNT(afs_FlushDCache);
899 * Bump the number of cache files flushed.
901 afs_stats_cmperf.cacheFlushes++;
903 /* remove from all hash tables */
904 afs_HashOutDCache(adc);
906 /* Free its space; special case null operation, since truncate operation
907 * in UFS is slow even in this case, and this allows us to pre-truncate
908 * these files at more convenient times with fewer locks set
909 * (see afs_GetDownD).
911 if (adc->f.chunkBytes != 0) {
912 afs_DiscardDCache(adc);
913 afs_MaybeWakeupTruncateDaemon();
918 if (afs_WaitForCacheDrain) {
919 if (afs_blocksUsed <=
920 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
921 afs_WaitForCacheDrain = 0;
922 afs_osi_Wakeup(&afs_WaitForCacheDrain);
925 } /*afs_FlushDCache */
931 * Description: put a dcache entry on the free dcache entry list.
933 * Parameters: adc -- dcache entry to free
935 * Environment: called with afs_xdcache lock write-locked.
938 afs_FreeDCache(register struct dcache *adc)
940 /* Thread on free list, update free list count and mark entry as
941 * freed in its indexFlags element. Also, ensure DCache entry gets
942 * written out (set DFEntryMod).
945 afs_dvnextTbl[adc->index] = afs_freeDCList;
946 afs_freeDCList = adc->index;
948 afs_indexFlags[adc->index] |= IFFree;
949 adc->dflags |= DFEntryMod;
951 if (afs_WaitForCacheDrain) {
952 if ((afs_blocksUsed - afs_blocksDiscarded) <=
953 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
954 afs_WaitForCacheDrain = 0;
955 afs_osi_Wakeup(&afs_WaitForCacheDrain);
964 * Discard the cache element by moving it to the discardDCList.
965 * This puts the cache element into a quasi-freed state, where
966 * the space may be reused, but the file has not been truncated.
968 * Major Assumptions Here:
969 * Assumes that frag size is an integral power of two, less one,
970 * and that this is a two's complement machine. I don't
971 * know of any filesystems which violate this assumption...
974 * adc : Ptr to dcache entry.
977 * Must be called with afs_xdcache write-locked.
981 afs_DiscardDCache(register struct dcache *adc)
983 register afs_int32 size;
985 AFS_STATCNT(afs_DiscardDCache);
987 osi_Assert(adc->refCount == 1);
989 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
990 afs_blocksDiscarded += size;
991 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
993 afs_dvnextTbl[adc->index] = afs_discardDCList;
994 afs_discardDCList = adc->index;
995 afs_discardDCCount++;
997 adc->f.fid.Fid.Volume = 0;
998 adc->dflags |= DFEntryMod;
999 afs_indexFlags[adc->index] |= IFDiscarded;
1001 if (afs_WaitForCacheDrain) {
1002 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1003 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1004 afs_WaitForCacheDrain = 0;
1005 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1009 } /*afs_DiscardDCache */
1012 * afs_FreeDiscardedDCache
1015 * Free the next element on the list of discarded cache elements.
1018 afs_FreeDiscardedDCache(void)
1020 register struct dcache *tdc;
1021 register struct osi_file *tfile;
1022 register afs_int32 size;
1024 AFS_STATCNT(afs_FreeDiscardedDCache);
1026 MObtainWriteLock(&afs_xdcache, 510);
1027 if (!afs_blocksDiscarded) {
1028 MReleaseWriteLock(&afs_xdcache);
1033 * Get an entry from the list of discarded cache elements
1035 tdc = afs_GetDSlot(afs_discardDCList, 0);
1036 osi_Assert(tdc->refCount == 1);
1037 ReleaseReadLock(&tdc->tlock);
1039 afs_discardDCList = afs_dvnextTbl[tdc->index];
1040 afs_dvnextTbl[tdc->index] = NULLIDX;
1041 afs_discardDCCount--;
1042 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1043 afs_blocksDiscarded -= size;
1044 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1045 /* We can lock because we just took it off the free list */
1046 ObtainWriteLock(&tdc->lock, 626);
1047 MReleaseWriteLock(&afs_xdcache);
1050 * Truncate the element to reclaim its space
1052 tfile = afs_CFileOpen(tdc->f.inode);
1053 afs_CFileTruncate(tfile, 0);
1054 afs_CFileClose(tfile);
1055 afs_AdjustSize(tdc, 0);
1056 afs_DCMoveBucket(tdc, 0, 0);
1059 * Free the element we just truncated
1061 MObtainWriteLock(&afs_xdcache, 511);
1062 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1063 afs_FreeDCache(tdc);
1064 tdc->f.states &= ~(DRO|DBackup|DRW);
1065 ReleaseWriteLock(&tdc->lock);
1067 MReleaseWriteLock(&afs_xdcache);
1071 * afs_MaybeFreeDiscardedDCache
1074 * Free as many entries from the list of discarded cache elements
1075 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1081 afs_MaybeFreeDiscardedDCache(void)
1084 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1086 while (afs_blocksDiscarded
1087 && (afs_blocksUsed >
1088 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1089 afs_FreeDiscardedDCache();
1098 * Try to free up a certain number of disk slots.
1101 * anumber : Targeted number of disk slots to free up.
1104 * Must be called with afs_xdcache write-locked.
1107 afs_GetDownDSlot(int anumber)
1109 struct afs_q *tq, *nq;
1114 AFS_STATCNT(afs_GetDownDSlot);
1115 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1116 osi_Panic("diskless getdowndslot");
1118 if (CheckLock(&afs_xdcache) != -1)
1119 osi_Panic("getdowndslot nolock");
1121 /* decrement anumber first for all dudes in free list */
1122 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1125 return; /* enough already free */
1127 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1129 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1130 nq = QPrev(tq); /* in case we remove it */
1131 if (tdc->refCount == 0) {
1132 if ((ix = tdc->index) == NULLIDX)
1133 osi_Panic("getdowndslot");
1134 /* pull the entry out of the lruq and put it on the free list */
1135 QRemove(&tdc->lruq);
1137 /* write-through if modified */
1138 if (tdc->dflags & DFEntryMod) {
1139 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1141 * ask proxy to do this for us - we don't have the stack space
1143 while (tdc->dflags & DFEntryMod) {
1146 s = SPLOCK(afs_sgibklock);
1147 if (afs_sgibklist == NULL) {
1148 /* if slot is free, grab it. */
1149 afs_sgibklist = tdc;
1150 SV_SIGNAL(&afs_sgibksync);
1152 /* wait for daemon to (start, then) finish. */
1153 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1157 tdc->dflags &= ~DFEntryMod;
1158 afs_WriteDCache(tdc, 1);
1162 /* finally put the entry in the free list */
1163 afs_indexTable[ix] = NULL;
1164 afs_indexFlags[ix] &= ~IFEverUsed;
1165 tdc->index = NULLIDX;
1166 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1167 afs_freeDSList = tdc;
1171 } /*afs_GetDownDSlot */
1178 * Increment the reference count on a disk cache entry,
1179 * which already has a non-zero refcount. In order to
1180 * increment the refcount of a zero-reference entry, you
1181 * have to hold afs_xdcache.
1184 * adc : Pointer to the dcache entry to increment.
1187 * Nothing interesting.
1190 afs_RefDCache(struct dcache *adc)
1192 ObtainWriteLock(&adc->tlock, 627);
1193 if (adc->refCount < 0)
1194 osi_Panic("RefDCache: negative refcount");
1196 ReleaseWriteLock(&adc->tlock);
1205 * Decrement the reference count on a disk cache entry.
1208 * ad : Ptr to the dcache entry to decrement.
1211 * Nothing interesting.
1214 afs_PutDCache(register struct dcache *adc)
1216 AFS_STATCNT(afs_PutDCache);
1217 ObtainWriteLock(&adc->tlock, 276);
1218 if (adc->refCount <= 0)
1219 osi_Panic("putdcache");
1221 ReleaseWriteLock(&adc->tlock);
1230 * Try to discard all data associated with this file from the
1234 * avc : Pointer to the cache info for the file.
1237 * Both pvnLock and lock are write held.
1240 afs_TryToSmush(register struct vcache *avc, struct AFS_UCRED *acred, int sync)
1242 register struct dcache *tdc;
1245 AFS_STATCNT(afs_TryToSmush);
1246 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1247 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->m.Length));
1248 sync = 1; /* XX Temp testing XX */
1250 #if defined(AFS_SUN5_ENV)
1251 ObtainWriteLock(&avc->vlock, 573);
1252 avc->activeV++; /* block new getpages */
1253 ReleaseWriteLock(&avc->vlock);
1256 /* Flush VM pages */
1257 osi_VM_TryToSmush(avc, acred, sync);
1260 * Get the hash chain containing all dce's for this fid
1262 i = DVHash(&avc->fid);
1263 MObtainWriteLock(&afs_xdcache, 277);
1264 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1265 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1266 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1267 int releaseTlock = 1;
1268 tdc = afs_GetDSlot(index, NULL);
1269 if (!FidCmp(&tdc->f.fid, &avc->fid)) {
1271 if ((afs_indexFlags[index] & IFDataMod) == 0
1272 && tdc->refCount == 1) {
1273 ReleaseReadLock(&tdc->tlock);
1275 afs_FlushDCache(tdc);
1278 afs_indexTable[index] = 0;
1281 ReleaseReadLock(&tdc->tlock);
1285 #if defined(AFS_SUN5_ENV)
1286 ObtainWriteLock(&avc->vlock, 545);
1287 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1288 avc->vstates &= ~VRevokeWait;
1289 afs_osi_Wakeup((char *)&avc->vstates);
1291 ReleaseWriteLock(&avc->vlock);
1293 MReleaseWriteLock(&afs_xdcache);
1295 * It's treated like a callback so that when we do lookups we'll invalidate the unique bit if any
1296 * trytoSmush occured during the lookup call
1305 * Given the cached info for a file and a byte offset into the
1306 * file, make sure the dcache entry for that file and containing
1307 * the given byte is available, returning it to our caller.
1310 * avc : Pointer to the (held) vcache entry to look in.
1311 * abyte : Which byte we want to get to.
1314 * Pointer to the dcache entry covering the file & desired byte,
1315 * or NULL if not found.
1318 * The vcache entry is held upon entry.
1322 afs_FindDCache(register struct vcache *avc, afs_size_t abyte)
1325 register afs_int32 i, index;
1326 register struct dcache *tdc = NULL;
1328 AFS_STATCNT(afs_FindDCache);
1329 chunk = AFS_CHUNK(abyte);
1332 * Hash on the [fid, chunk] and get the corresponding dcache index
1333 * after write-locking the dcache.
1335 i = DCHash(&avc->fid, chunk);
1336 MObtainWriteLock(&afs_xdcache, 278);
1337 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1338 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1339 tdc = afs_GetDSlot(index, NULL);
1340 ReleaseReadLock(&tdc->tlock);
1341 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1342 break; /* leaving refCount high for caller */
1346 index = afs_dcnextTbl[index];
1348 if (index != NULLIDX) {
1349 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1350 hadd32(afs_indexCounter, 1);
1351 MReleaseWriteLock(&afs_xdcache);
1354 MReleaseWriteLock(&afs_xdcache);
1356 } /*afs_FindDCache */
1360 * afs_UFSCacheStoreProc
1363 * Called upon store.
1366 * acall : Ptr to the Rx call structure involved.
1367 * afile : Ptr to the related file descriptor.
1368 * alen : Size of the file in bytes.
1369 * avc : Ptr to the vcache entry.
1370 * shouldWake : is it "safe" to return early from close() ?
1371 * abytesToXferP : Set to the number of bytes to xfer.
1372 * NOTE: This parameter is only used if AFS_NOSTATS
1374 * abytesXferredP : Set to the number of bytes actually xferred.
1375 * NOTE: This parameter is only used if AFS_NOSTATS
1379 * Nothing interesting.
1382 afs_UFSCacheStoreProc(register struct rx_call *acall, struct osi_file *afile,
1383 register afs_int32 alen, struct vcache *avc,
1384 int *shouldWake, afs_size_t * abytesToXferP,
1385 afs_size_t * abytesXferredP)
1387 afs_int32 code, got;
1388 register char *tbuffer;
1391 AFS_STATCNT(UFS_CacheStoreProc);
1395 * In this case, alen is *always* the amount of data we'll be trying
1398 (*abytesToXferP) = alen;
1399 (*abytesXferredP) = 0;
1400 #endif /* AFS_NOSTATS */
1402 afs_Trace4(afs_iclSetp, CM_TRACE_STOREPROC, ICL_TYPE_POINTER, avc,
1403 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
1404 ICL_HANDLE_OFFSET(avc->m.Length), ICL_TYPE_INT32, alen);
1405 tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1407 tlen = (alen > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : alen);
1408 got = afs_osi_Read(afile, -1, tbuffer, tlen);
1410 #if defined(KERNEL_HAVE_UERROR)
1411 || (got != tlen && getuerror())
1414 osi_FreeLargeSpace(tbuffer);
1417 afs_Trace2(afs_iclSetp, CM_TRACE_STOREPROC2, ICL_TYPE_OFFSET,
1418 ICL_HANDLE_OFFSET(*tbuffer), ICL_TYPE_INT32, got);
1420 code = rx_Write(acall, tbuffer, got); /* writing 0 bytes will
1421 * push a short packet. Is that really what we want, just because the
1422 * data didn't come back from the disk yet? Let's try it and see. */
1425 (*abytesXferredP) += code;
1426 #endif /* AFS_NOSTATS */
1428 code = rx_Error(acall);
1429 osi_FreeLargeSpace(tbuffer);
1430 return code ? code : -33;
1434 * If file has been locked on server, we can allow the store
1437 if (shouldWake && *shouldWake && (rx_GetRemoteStatus(acall) & 1)) {
1438 *shouldWake = 0; /* only do this once */
1442 afs_Trace4(afs_iclSetp, CM_TRACE_STOREPROC, ICL_TYPE_POINTER, avc,
1443 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
1444 ICL_HANDLE_OFFSET(avc->m.Length), ICL_TYPE_INT32, alen);
1445 osi_FreeLargeSpace(tbuffer);
1448 } /* afs_UFSCacheStoreProc */
1452 * afs_UFSCacheFetchProc
1455 * Routine called on fetch; also tells people waiting for data
1456 * that more has arrived.
1459 * acall : Ptr to the Rx call structure.
1460 * afile : File descriptor for the cache file.
1461 * abase : Base offset to fetch.
1462 * adc : Ptr to the dcache entry for the file, write-locked.
1463 * avc : Ptr to the vcache entry for the file.
1464 * abytesToXferP : Set to the number of bytes to xfer.
1465 * NOTE: This parameter is only used if AFS_NOSTATS
1467 * abytesXferredP : Set to the number of bytes actually xferred.
1468 * NOTE: This parameter is only used if AFS_NOSTATS
1472 * Nothing interesting.
1476 afs_UFSCacheFetchProc(register struct rx_call *acall, struct osi_file *afile,
1477 afs_size_t abase, struct dcache *adc,
1478 struct vcache *avc, afs_size_t * abytesToXferP,
1479 afs_size_t * abytesXferredP, afs_int32 lengthFound)
1482 register afs_int32 code;
1483 register char *tbuffer;
1487 AFS_STATCNT(UFS_CacheFetchProc);
1488 osi_Assert(WriteLocked(&adc->lock));
1489 afile->offset = 0; /* Each time start from the beginning */
1490 length = lengthFound;
1492 (*abytesToXferP) = 0;
1493 (*abytesXferredP) = 0;
1494 #endif /* AFS_NOSTATS */
1495 tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1496 adc->validPos = abase;
1500 code = rx_Read(acall, (char *)&length, sizeof(afs_int32));
1502 length = ntohl(length);
1503 if (code != sizeof(afs_int32)) {
1504 osi_FreeLargeSpace(tbuffer);
1505 code = rx_Error(acall);
1506 return (code ? code : -1); /* try to return code, not -1 */
1510 * The fetch protocol is extended for the AFS/DFS translator
1511 * to allow multiple blocks of data, each with its own length,
1512 * to be returned. As long as the top bit is set, there are more
1515 * We do not do this for AFS file servers because they sometimes
1516 * return large negative numbers as the transfer size.
1518 if (avc->states & CForeign) {
1519 moredata = length & 0x80000000;
1520 length &= ~0x80000000;
1525 (*abytesToXferP) += length;
1526 #endif /* AFS_NOSTATS */
1527 while (length > 0) {
1528 tlen = (length > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : length);
1529 #ifdef RX_KERNEL_TRACE
1530 afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
1534 code = rx_Read(acall, tbuffer, tlen);
1536 #ifdef RX_KERNEL_TRACE
1537 afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
1541 (*abytesXferredP) += code;
1542 #endif /* AFS_NOSTATS */
1544 osi_FreeLargeSpace(tbuffer);
1545 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64READ,
1546 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
1547 ICL_TYPE_INT32, length);
1550 code = afs_osi_Write(afile, -1, tbuffer, tlen);
1552 osi_FreeLargeSpace(tbuffer);
1557 adc->validPos = abase;
1558 if (afs_osi_Wakeup(&adc->validPos) == 0)
1559 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
1560 __FILE__, ICL_TYPE_INT32, __LINE__,
1561 ICL_TYPE_POINTER, adc, ICL_TYPE_INT32,
1565 osi_FreeLargeSpace(tbuffer);
1568 } /* afs_UFSCacheFetchProc */
1574 * This function is called to obtain a reference to data stored in
1575 * the disk cache, locating a chunk of data containing the desired
1576 * byte and returning a reference to the disk cache entry, with its
1577 * reference count incremented.
1581 * avc : Ptr to a vcache entry (unlocked)
1582 * abyte : Byte position in the file desired
1583 * areq : Request structure identifying the requesting user.
1584 * aflags : Settings as follows:
1586 * 2 : Return after creating entry.
1587 * 4 : called from afs_vnop_write.c
1588 * *alen contains length of data to be written.
1590 * aoffset : Set to the offset within the chunk where the resident
1592 * alen : Set to the number of bytes of data after the desired
1593 * byte (including the byte itself) which can be read
1597 * The vcache entry pointed to by avc is unlocked upon entry.
1601 struct AFSVolSync tsync;
1602 struct AFSFetchStatus OutStatus;
1603 struct AFSCallBack CallBack;
1607 * Update the vnode-to-dcache hint if we can get the vnode lock
1608 * right away. Assumes dcache entry is at least read-locked.
1611 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1613 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1614 if (hsame(v->m.DataVersion, d->f.versionNo) && v->callback)
1617 ReleaseWriteLock(&v->lock);
1621 /* avc - Write-locked unless aflags & 1 */
1623 afs_GetDCache(register struct vcache *avc, afs_size_t abyte,
1624 register struct vrequest *areq, afs_size_t * aoffset,
1625 afs_size_t * alen, int aflags)
1627 register afs_int32 i, code, code1 = 0, shortcut;
1628 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1629 register afs_int32 adjustsize = 0;
1635 afs_size_t maxGoodLength; /* amount of good data at server */
1636 struct rx_call *tcall;
1637 afs_size_t Position = 0;
1638 #ifdef AFS_64BIT_CLIENT
1640 afs_size_t lengthFound; /* as returned from server */
1641 #endif /* AFS_64BIT_CLIENT */
1642 afs_int32 size, tlen; /* size of segment to transfer */
1643 struct tlocal1 *tsmall = 0;
1644 register struct dcache *tdc;
1645 register struct osi_file *file;
1646 register struct conn *tc;
1648 struct server *newCallback = NULL;
1649 char setNewCallback;
1650 char setVcacheStatus;
1651 char doVcacheUpdate;
1653 int doAdjustSize = 0;
1654 int doReallyAdjustSize = 0;
1655 int overWriteWholeChunk = 0;
1659 struct afs_stats_xferData *xferP; /* Ptr to this op's xfer struct */
1660 osi_timeval_t xferStartTime, /*FS xfer start time */
1661 xferStopTime; /*FS xfer stop time */
1662 afs_size_t bytesToXfer; /* # bytes to xfer */
1663 afs_size_t bytesXferred; /* # bytes actually xferred */
1664 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1665 int fromReplica; /*Are we reading from a replica? */
1666 int numFetchLoops; /*# times around the fetch/analyze loop */
1667 #endif /* AFS_NOSTATS */
1669 AFS_STATCNT(afs_GetDCache);
1674 setLocks = aflags & 1;
1677 * Determine the chunk number and offset within the chunk corresponding
1678 * to the desired byte.
1680 if (avc->fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1683 chunk = AFS_CHUNK(abyte);
1686 /* come back to here if we waited for the cache to drain. */
1689 setNewCallback = setVcacheStatus = 0;
1693 ObtainWriteLock(&avc->lock, 616);
1695 ObtainReadLock(&avc->lock);
1700 * avc->lock(R) if setLocks && !slowPass
1701 * avc->lock(W) if !setLocks || slowPass
1706 /* check hints first! (might could use bcmp or some such...) */
1707 if ((tdc = avc->dchint)) {
1711 * The locking order between afs_xdcache and dcache lock matters.
1712 * The hint dcache entry could be anywhere, even on the free list.
1713 * Locking afs_xdcache ensures that noone is trying to pull dcache
1714 * entries from the free list, and thereby assuming them to be not
1715 * referenced and not locked.
1717 MObtainReadLock(&afs_xdcache);
1718 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1720 if (dcLocked && (tdc->index != NULLIDX)
1721 && !FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk
1722 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1723 /* got the right one. It might not be the right version, and it
1724 * might be fetching, but it's the right dcache entry.
1726 /* All this code should be integrated better with what follows:
1727 * I can save a good bit more time under a write lock if I do..
1729 ObtainWriteLock(&tdc->tlock, 603);
1731 ReleaseWriteLock(&tdc->tlock);
1733 MReleaseReadLock(&afs_xdcache);
1736 if (hsame(tdc->f.versionNo, avc->m.DataVersion)
1737 && !(tdc->dflags & DFFetching)) {
1739 afs_stats_cmperf.dcacheHits++;
1740 MObtainWriteLock(&afs_xdcache, 559);
1741 QRemove(&tdc->lruq);
1742 QAdd(&afs_DLRU, &tdc->lruq);
1743 MReleaseWriteLock(&afs_xdcache);
1746 * avc->lock(R) if setLocks && !slowPass
1747 * avc->lock(W) if !setLocks || slowPass
1754 ReleaseSharedLock(&tdc->lock);
1755 MReleaseReadLock(&afs_xdcache);
1763 * avc->lock(R) if setLocks && !slowPass
1764 * avc->lock(W) if !setLocks || slowPass
1765 * tdc->lock(S) if tdc
1768 if (!tdc) { /* If the hint wasn't the right dcache entry */
1770 * Hash on the [fid, chunk] and get the corresponding dcache index
1771 * after write-locking the dcache.
1776 * avc->lock(R) if setLocks && !slowPass
1777 * avc->lock(W) if !setLocks || slowPass
1780 i = DCHash(&avc->fid, chunk);
1781 /* check to make sure our space is fine */
1782 afs_MaybeWakeupTruncateDaemon();
1784 MObtainWriteLock(&afs_xdcache, 280);
1786 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1787 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1788 tdc = afs_GetDSlot(index, NULL);
1789 ReleaseReadLock(&tdc->tlock);
1792 * avc->lock(R) if setLocks && !slowPass
1793 * avc->lock(W) if !setLocks || slowPass
1796 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1797 /* Move it up in the beginning of the list */
1798 if (afs_dchashTbl[i] != index) {
1799 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1800 afs_dcnextTbl[index] = afs_dchashTbl[i];
1801 afs_dchashTbl[i] = index;
1803 MReleaseWriteLock(&afs_xdcache);
1804 ObtainSharedLock(&tdc->lock, 606);
1805 break; /* leaving refCount high for caller */
1811 index = afs_dcnextTbl[index];
1815 * If we didn't find the entry, we'll create one.
1817 if (index == NULLIDX) {
1820 * avc->lock(R) if setLocks
1821 * avc->lock(W) if !setLocks
1824 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1825 avc, ICL_TYPE_INT32, chunk);
1827 /* Make sure there is a free dcache entry for us to use */
1828 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1831 avc->states |= CDCLock;
1832 /* just need slots */
1833 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1835 avc->states &= ~CDCLock;
1836 if (afs_discardDCList != NULLIDX
1837 || afs_freeDCList != NULLIDX)
1839 /* If we can't get space for 5 mins we give up and panic */
1840 if (++downDCount > 300)
1841 osi_Panic("getdcache");
1842 MReleaseWriteLock(&afs_xdcache);
1845 * avc->lock(R) if setLocks
1846 * avc->lock(W) if !setLocks
1848 afs_osi_Wait(1000, 0, 0);
1853 if (afs_discardDCList == NULLIDX
1854 || ((aflags & 2) && afs_freeDCList != NULLIDX)) {
1856 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1857 tdc = afs_GetDSlot(afs_freeDCList, 0);
1858 osi_Assert(tdc->refCount == 1);
1859 ReleaseReadLock(&tdc->tlock);
1860 ObtainWriteLock(&tdc->lock, 604);
1861 afs_freeDCList = afs_dvnextTbl[tdc->index];
1864 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1865 tdc = afs_GetDSlot(afs_discardDCList, 0);
1866 osi_Assert(tdc->refCount == 1);
1867 ReleaseReadLock(&tdc->tlock);
1868 ObtainWriteLock(&tdc->lock, 605);
1869 afs_discardDCList = afs_dvnextTbl[tdc->index];
1870 afs_discardDCCount--;
1872 ((tdc->f.chunkBytes +
1873 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1874 tdc->f.states &= ~(DRO|DBackup|DRW);
1875 afs_DCMoveBucket(tdc, size, 0);
1876 afs_blocksDiscarded -= size;
1877 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1879 /* Truncate the chunk so zeroes get filled properly */
1880 file = afs_CFileOpen(tdc->f.inode);
1881 afs_CFileTruncate(file, 0);
1882 afs_CFileClose(file);
1883 afs_AdjustSize(tdc, 0);
1889 * avc->lock(R) if setLocks
1890 * avc->lock(W) if !setLocks
1896 * Fill in the newly-allocated dcache record.
1898 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1899 tdc->f.fid = avc->fid;
1900 if (avc->states & CRO)
1901 tdc->f.states = DRO;
1902 else if (avc->states & CBackup)
1903 tdc->f.states = DBackup;
1905 tdc->f.states = DRW;
1906 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1907 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1908 hones(tdc->f.versionNo); /* invalid value */
1909 tdc->f.chunk = chunk;
1910 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1912 if (tdc->lruq.prev == &tdc->lruq)
1913 osi_Panic("lruq 1");
1916 * Now add to the two hash chains - note that i is still set
1917 * from the above DCHash call.
1919 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1920 afs_dchashTbl[i] = tdc->index;
1921 i = DVHash(&avc->fid);
1922 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1923 afs_dvhashTbl[i] = tdc->index;
1924 tdc->dflags = DFEntryMod;
1926 afs_MaybeWakeupTruncateDaemon();
1927 MReleaseWriteLock(&afs_xdcache);
1928 ConvertWToSLock(&tdc->lock);
1933 /* vcache->dcache hint failed */
1936 * avc->lock(R) if setLocks && !slowPass
1937 * avc->lock(W) if !setLocks || slowPass
1940 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1941 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
1942 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
1943 hgetlo(avc->m.DataVersion));
1945 * Here we have the entry in tdc, with its refCount incremented.
1946 * Note: we don't use the S-lock on avc; it costs concurrency when
1947 * storing a file back to the server.
1951 * Not a newly created file so we need to check the file's length and
1952 * compare data versions since someone could have changed the data or we're
1953 * reading a file written elsewhere. We only want to bypass doing no-op
1954 * read rpcs on newly created files (dv of 0) since only then we guarantee
1955 * that this chunk's data hasn't been filled by another client.
1957 size = AFS_CHUNKSIZE(abyte);
1958 if (aflags & 4) /* called from write */
1960 else /* called from read */
1961 tlen = tdc->validPos - abyte;
1962 Position = AFS_CHUNKTOBASE(chunk);
1963 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
1964 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
1965 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
1966 ICL_HANDLE_OFFSET(Position));
1967 if ((aflags & 4) && (hiszero(avc->m.DataVersion)))
1969 if ((AFS_CHUNKTOBASE(chunk) >= avc->m.Length) ||
1970 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
1971 overWriteWholeChunk = 1;
1972 if (doAdjustSize || overWriteWholeChunk) {
1973 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1975 #ifdef AFS_SGI64_ENV
1978 #else /* AFS_SGI64_ENV */
1981 #endif /* AFS_SGI64_ENV */
1982 #else /* AFS_SGI_ENV */
1985 #endif /* AFS_SGI_ENV */
1986 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->m.Length &&
1987 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1988 #if defined(AFS_SUN5_ENV) || defined(AFS_OSF_ENV)
1989 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->m.Length)) &&
1991 if (AFS_CHUNKTOBASE(chunk) >= avc->m.Length &&
1993 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1994 !hsame(avc->m.DataVersion, tdc->f.versionNo))
1995 doReallyAdjustSize = 1;
1997 if (doReallyAdjustSize || overWriteWholeChunk) {
1998 /* no data in file to read at this position */
1999 UpgradeSToWLock(&tdc->lock, 607);
2001 file = afs_CFileOpen(tdc->f.inode);
2002 afs_CFileTruncate(file, 0);
2003 afs_CFileClose(file);
2004 afs_AdjustSize(tdc, 0);
2005 hset(tdc->f.versionNo, avc->m.DataVersion);
2006 tdc->dflags |= DFEntryMod;
2008 ConvertWToSLock(&tdc->lock);
2013 * We must read in the whole chunk if the version number doesn't
2017 /* don't need data, just a unique dcache entry */
2018 ObtainWriteLock(&afs_xdcache, 608);
2019 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2020 hadd32(afs_indexCounter, 1);
2021 ReleaseWriteLock(&afs_xdcache);
2023 updateV2DC(setLocks, avc, tdc, 553);
2024 if (vType(avc) == VDIR)
2027 *aoffset = AFS_CHUNKOFFSET(abyte);
2028 if (tdc->validPos < abyte)
2029 *alen = (afs_size_t) 0;
2031 *alen = tdc->validPos - abyte;
2032 ReleaseSharedLock(&tdc->lock);
2035 ReleaseWriteLock(&avc->lock);
2037 ReleaseReadLock(&avc->lock);
2039 return tdc; /* check if we're done */
2044 * avc->lock(R) if setLocks && !slowPass
2045 * avc->lock(W) if !setLocks || slowPass
2048 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
2050 setNewCallback = setVcacheStatus = 0;
2054 * avc->lock(R) if setLocks && !slowPass
2055 * avc->lock(W) if !setLocks || slowPass
2058 if (!hsame(avc->m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
2060 * Version number mismatch.
2062 UpgradeSToWLock(&tdc->lock, 609);
2065 * If data ever existed for this vnode, and this is a text object,
2066 * do some clearing. Now, you'd think you need only do the flush
2067 * when VTEXT is on, but VTEXT is turned off when the text object
2068 * is freed, while pages are left lying around in memory marked
2069 * with this vnode. If we would reactivate (create a new text
2070 * object from) this vnode, we could easily stumble upon some of
2071 * these old pages in pagein. So, we always flush these guys.
2072 * Sun has a wonderful lack of useful invariants in this system.
2074 * avc->flushDV is the data version # of the file at the last text
2075 * flush. Clearly, at least, we don't have to flush the file more
2076 * often than it changes
2078 if (hcmp(avc->flushDV, avc->m.DataVersion) < 0) {
2080 * By here, the cache entry is always write-locked. We can
2081 * deadlock if we call osi_Flush with the cache entry locked...
2082 * Unlock the dcache too.
2084 ReleaseWriteLock(&tdc->lock);
2085 if (setLocks && !slowPass)
2086 ReleaseReadLock(&avc->lock);
2088 ReleaseWriteLock(&avc->lock);
2092 * Call osi_FlushPages in open, read/write, and map, since it
2093 * is too hard here to figure out if we should lock the
2096 if (setLocks && !slowPass)
2097 ObtainReadLock(&avc->lock);
2099 ObtainWriteLock(&avc->lock, 66);
2100 ObtainWriteLock(&tdc->lock, 610);
2105 * avc->lock(R) if setLocks && !slowPass
2106 * avc->lock(W) if !setLocks || slowPass
2110 /* Watch for standard race condition around osi_FlushText */
2111 if (hsame(avc->m.DataVersion, tdc->f.versionNo)) {
2112 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2113 afs_stats_cmperf.dcacheHits++;
2114 ConvertWToSLock(&tdc->lock);
2118 /* Sleep here when cache needs to be drained. */
2119 if (setLocks && !slowPass
2120 && (afs_blocksUsed >
2121 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2122 /* Make sure truncate daemon is running */
2123 afs_MaybeWakeupTruncateDaemon();
2124 ObtainWriteLock(&tdc->tlock, 614);
2125 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2126 ReleaseWriteLock(&tdc->tlock);
2127 ReleaseWriteLock(&tdc->lock);
2128 ReleaseReadLock(&avc->lock);
2129 while ((afs_blocksUsed - afs_blocksDiscarded) >
2130 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2131 afs_WaitForCacheDrain = 1;
2132 afs_osi_Sleep(&afs_WaitForCacheDrain);
2134 afs_MaybeFreeDiscardedDCache();
2135 /* need to check if someone else got the chunk first. */
2136 goto RetryGetDCache;
2139 /* Do not fetch data beyond truncPos. */
2140 maxGoodLength = avc->m.Length;
2141 if (avc->truncPos < maxGoodLength)
2142 maxGoodLength = avc->truncPos;
2143 Position = AFS_CHUNKBASE(abyte);
2144 if (vType(avc) == VDIR) {
2145 size = avc->m.Length;
2146 if (size > tdc->f.chunkBytes) {
2147 /* pre-reserve space for file */
2148 afs_AdjustSize(tdc, size);
2150 size = 999999999; /* max size for transfer */
2152 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2153 /* don't read past end of good data on server */
2154 if (Position + size > maxGoodLength)
2155 size = maxGoodLength - Position;
2157 size = 0; /* Handle random races */
2158 if (size > tdc->f.chunkBytes) {
2159 /* pre-reserve space for file */
2160 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2161 /* max size for transfer still in size */
2164 if (afs_mariner && !tdc->f.chunk)
2165 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2167 * Right now, we only have one tool, and it's a hammer. So, we
2168 * fetch the whole file.
2170 DZap(tdc); /* pages in cache may be old */
2171 file = afs_CFileOpen(tdc->f.inode);
2172 afs_RemoveVCB(&avc->fid);
2173 tdc->f.states |= DWriting;
2174 tdc->dflags |= DFFetching;
2175 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2176 if (tdc->mflags & DFFetchReq) {
2177 tdc->mflags &= ~DFFetchReq;
2178 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2179 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2180 __FILE__, ICL_TYPE_INT32, __LINE__,
2181 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2185 (struct tlocal1 *)osi_AllocLargeSpace(sizeof(struct tlocal1));
2186 setVcacheStatus = 0;
2189 * Remember if we are doing the reading from a replicated volume,
2190 * and how many times we've zipped around the fetch/analyze loop.
2192 fromReplica = (avc->states & CRO) ? 1 : 0;
2194 accP = &(afs_stats_cmfullperf.accessinf);
2196 (accP->replicatedRefs)++;
2198 (accP->unreplicatedRefs)++;
2199 #endif /* AFS_NOSTATS */
2200 /* this is a cache miss */
2201 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2202 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
2203 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2206 afs_stats_cmperf.dcacheMisses++;
2209 * Dynamic root support: fetch data from local memory.
2211 if (afs_IsDynroot(avc)) {
2215 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2217 dynrootDir += Position;
2218 dynrootLen -= Position;
2219 if (size > dynrootLen)
2223 code = afs_CFileWrite(file, 0, dynrootDir, size);
2231 tdc->validPos = Position + size;
2232 afs_CFileTruncate(file, size); /* prune it */
2233 } else if (afs_IsDynrootMount(avc)) {
2237 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2239 dynrootDir += Position;
2240 dynrootLen -= Position;
2241 if (size > dynrootLen)
2245 code = afs_CFileWrite(file, 0, dynrootDir, size);
2253 tdc->validPos = Position + size;
2254 afs_CFileTruncate(file, size); /* prune it */
2255 } else if (afs_IsDynrootMount(avc)) {
2259 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2261 dynrootDir += Position;
2262 dynrootLen -= Position;
2263 if (size > dynrootLen)
2267 code = afs_CFileWrite(file, 0, dynrootDir, size);
2275 tdc->validPos = Position + size;
2276 afs_CFileTruncate(file, size); /* prune it */
2279 * Not a dynamic vnode: do the real fetch.
2284 * avc->lock(R) if setLocks && !slowPass
2285 * avc->lock(W) if !setLocks || slowPass
2289 tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
2291 afs_int32 length_hi, length, bytes;
2295 (accP->numReplicasAccessed)++;
2297 #endif /* AFS_NOSTATS */
2298 if (!setLocks || slowPass) {
2299 avc->callback = tc->srvr->server;
2301 newCallback = tc->srvr->server;
2306 tcall = rx_NewCall(tc->id);
2309 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
2310 #ifdef AFS_64BIT_CLIENT
2311 length_hi = code = 0;
2312 if (!afs_serverHasNo64Bit(tc)) {
2316 StartRXAFS_FetchData64(tcall,
2317 (struct AFSFid *)&avc->fid.
2318 Fid, Position, tsize);
2321 afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2322 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32,
2326 rx_Read(tcall, (char *)&length_hi,
2329 if (bytes == sizeof(afs_int32)) {
2330 length_hi = ntohl(length_hi);
2333 code = rx_Error(tcall);
2335 code1 = rx_EndCall(tcall, code);
2337 tcall = (struct rx_call *)0;
2341 if (code == RXGEN_OPCODE || afs_serverHasNo64Bit(tc)) {
2342 if (Position > 0x7FFFFFFF) {
2349 tcall = rx_NewCall(tc->id);
2351 StartRXAFS_FetchData(tcall, (struct AFSFid *)
2356 afs_serverSetNo64Bit(tc);
2361 rx_Read(tcall, (char *)&length,
2364 if (bytes == sizeof(afs_int32)) {
2365 length = ntohl(length);
2367 code = rx_Error(tcall);
2370 FillInt64(lengthFound, length_hi, length);
2371 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64LENG,
2372 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
2374 ICL_HANDLE_OFFSET(lengthFound));
2375 #else /* AFS_64BIT_CLIENT */
2378 StartRXAFS_FetchData(tcall,
2379 (struct AFSFid *)&avc->fid.Fid,
2385 rx_Read(tcall, (char *)&length,
2388 if (bytes == sizeof(afs_int32)) {
2389 length = ntohl(length);
2391 code = rx_Error(tcall);
2394 #endif /* AFS_64BIT_CLIENT */
2399 &(afs_stats_cmfullperf.rpc.
2400 fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
2401 osi_GetuTime(&xferStartTime);
2404 afs_CacheFetchProc(tcall, file,
2405 (afs_size_t) Position, tdc,
2407 &bytesXferred, length);
2409 osi_GetuTime(&xferStopTime);
2410 (xferP->numXfers)++;
2412 (xferP->numSuccesses)++;
2413 afs_stats_XferSumBytes
2414 [AFS_STATS_FS_XFERIDX_FETCHDATA] +=
2416 (xferP->sumBytes) +=
2417 (afs_stats_XferSumBytes
2418 [AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
2419 afs_stats_XferSumBytes
2420 [AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
2421 if (bytesXferred < xferP->minBytes)
2422 xferP->minBytes = bytesXferred;
2423 if (bytesXferred > xferP->maxBytes)
2424 xferP->maxBytes = bytesXferred;
2427 * Tally the size of the object. Note: we tally the actual size,
2428 * NOT the number of bytes that made it out over the wire.
2430 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
2431 (xferP->count[0])++;
2432 else if (bytesToXfer <=
2433 AFS_STATS_MAXBYTES_BUCKET1)
2434 (xferP->count[1])++;
2435 else if (bytesToXfer <=
2436 AFS_STATS_MAXBYTES_BUCKET2)
2437 (xferP->count[2])++;
2438 else if (bytesToXfer <=
2439 AFS_STATS_MAXBYTES_BUCKET3)
2440 (xferP->count[3])++;
2441 else if (bytesToXfer <=
2442 AFS_STATS_MAXBYTES_BUCKET4)
2443 (xferP->count[4])++;
2444 else if (bytesToXfer <=
2445 AFS_STATS_MAXBYTES_BUCKET5)
2446 (xferP->count[5])++;
2447 else if (bytesToXfer <=
2448 AFS_STATS_MAXBYTES_BUCKET6)
2449 (xferP->count[6])++;
2450 else if (bytesToXfer <=
2451 AFS_STATS_MAXBYTES_BUCKET7)
2452 (xferP->count[7])++;
2454 (xferP->count[8])++;
2456 afs_stats_GetDiff(elapsedTime, xferStartTime,
2458 afs_stats_AddTo((xferP->sumTime), elapsedTime);
2459 afs_stats_SquareAddTo((xferP->sqrTime),
2461 if (afs_stats_TimeLessThan
2462 (elapsedTime, (xferP->minTime))) {
2463 afs_stats_TimeAssign((xferP->minTime),
2466 if (afs_stats_TimeGreaterThan
2467 (elapsedTime, (xferP->maxTime))) {
2468 afs_stats_TimeAssign((xferP->maxTime),
2474 afs_CacheFetchProc(tcall, file, Position, tdc,
2476 #endif /* AFS_NOSTATS */
2481 EndRXAFS_FetchData(tcall, &tsmall->OutStatus,
2489 code1 = rx_EndCall(tcall, code);
2498 /* callback could have been broken (or expired) in a race here,
2499 * but we return the data anyway. It's as good as we knew about
2500 * when we started. */
2502 * validPos is updated by CacheFetchProc, and can only be
2503 * modifed under a dcache write lock, which we've blocked out
2505 size = tdc->validPos - Position; /* actual segment size */
2508 afs_CFileTruncate(file, size); /* prune it */
2510 if (!setLocks || slowPass) {
2511 ObtainWriteLock(&afs_xcbhash, 453);
2512 afs_DequeueCallback(avc);
2513 avc->states &= ~(CStatd | CUnique);
2514 avc->callback = NULL;
2515 ReleaseWriteLock(&afs_xcbhash);
2516 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2517 osi_dnlc_purgedp(avc);
2519 /* Something lost. Forget about performance, and go
2520 * back with a vcache write lock.
2522 afs_CFileTruncate(file, 0);
2523 afs_AdjustSize(tdc, 0);
2524 afs_CFileClose(file);
2525 osi_FreeLargeSpace(tsmall);
2527 ReleaseWriteLock(&tdc->lock);
2530 ReleaseReadLock(&avc->lock);
2532 goto RetryGetDCache;
2536 } while (afs_Analyze
2537 (tc, code, &avc->fid, areq,
2538 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2542 * avc->lock(R) if setLocks && !slowPass
2543 * avc->lock(W) if !setLocks || slowPass
2549 * In the case of replicated access, jot down info on the number of
2550 * attempts it took before we got through or gave up.
2553 if (numFetchLoops <= 1)
2554 (accP->refFirstReplicaOK)++;
2555 if (numFetchLoops > accP->maxReplicasPerRef)
2556 accP->maxReplicasPerRef = numFetchLoops;
2558 #endif /* AFS_NOSTATS */
2560 tdc->dflags &= ~DFFetching;
2561 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2562 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2563 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2564 tdc, ICL_TYPE_INT32, tdc->dflags);
2565 if (avc->execsOrWriters == 0)
2566 tdc->f.states &= ~DWriting;
2568 /* now, if code != 0, we have an error and should punt.
2569 * note that we have the vcache write lock, either because
2570 * !setLocks or slowPass.
2573 afs_CFileTruncate(file, 0);
2574 afs_AdjustSize(tdc, 0);
2575 afs_CFileClose(file);
2576 ZapDCE(tdc); /* sets DFEntryMod */
2577 if (vType(avc) == VDIR) {
2580 tdc->f.states &= ~(DRO|DBackup|DRW);
2581 afs_DCMoveBucket(tdc, 0, 0);
2582 ReleaseWriteLock(&tdc->lock);
2584 if (!afs_IsDynroot(avc)) {
2585 ObtainWriteLock(&afs_xcbhash, 454);
2586 afs_DequeueCallback(avc);
2587 avc->states &= ~(CStatd | CUnique);
2588 ReleaseWriteLock(&afs_xcbhash);
2589 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2590 osi_dnlc_purgedp(avc);
2593 * avc->lock(W); assert(!setLocks || slowPass)
2595 osi_Assert(!setLocks || slowPass);
2597 tdc->f.states &= ~(DRO|DBackup|DRW);
2598 afs_DCMoveBucket(tdc, 0, 0);
2603 /* otherwise we copy in the just-fetched info */
2604 afs_CFileClose(file);
2605 afs_AdjustSize(tdc, size); /* new size */
2607 * Copy appropriate fields into vcache. Status is
2608 * copied later where we selectively acquire the
2609 * vcache write lock.
2612 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2614 setVcacheStatus = 1;
2615 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2616 tsmall->OutStatus.DataVersion);
2617 tdc->dflags |= DFEntryMod;
2618 afs_indexFlags[tdc->index] |= IFEverUsed;
2619 ConvertWToSLock(&tdc->lock);
2620 } /*Data version numbers don't match */
2623 * Data version numbers match.
2625 afs_stats_cmperf.dcacheHits++;
2626 } /*Data version numbers match */
2628 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2632 * avc->lock(R) if setLocks && !slowPass
2633 * avc->lock(W) if !setLocks || slowPass
2634 * tdc->lock(S) if tdc
2638 * See if this was a reference to a file in the local cell.
2640 if (afs_IsPrimaryCellNum(avc->fid.Cell))
2641 afs_stats_cmperf.dlocalAccesses++;
2643 afs_stats_cmperf.dremoteAccesses++;
2645 /* Fix up LRU info */
2648 MObtainWriteLock(&afs_xdcache, 602);
2649 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2650 hadd32(afs_indexCounter, 1);
2651 MReleaseWriteLock(&afs_xdcache);
2653 /* return the data */
2654 if (vType(avc) == VDIR)
2657 *aoffset = AFS_CHUNKOFFSET(abyte);
2658 *alen = (tdc->f.chunkBytes - *aoffset);
2659 ReleaseSharedLock(&tdc->lock);
2664 * avc->lock(R) if setLocks && !slowPass
2665 * avc->lock(W) if !setLocks || slowPass
2668 /* Fix up the callback and status values in the vcache */
2670 if (setLocks && !slowPass) {
2673 * This is our dirty little secret to parallel fetches.
2674 * We don't write-lock the vcache while doing the fetch,
2675 * but potentially we'll need to update the vcache after
2676 * the fetch is done.
2678 * Drop the read lock and try to re-obtain the write
2679 * lock. If the vcache still has the same DV, it's
2680 * ok to go ahead and install the new data.
2682 afs_hyper_t currentDV, statusDV;
2684 hset(currentDV, avc->m.DataVersion);
2686 if (setNewCallback && avc->callback != newCallback)
2690 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2691 tsmall->OutStatus.DataVersion);
2693 if (setVcacheStatus && avc->m.Length != tsmall->OutStatus.Length)
2695 if (setVcacheStatus && !hsame(currentDV, statusDV))
2699 ReleaseReadLock(&avc->lock);
2701 if (doVcacheUpdate) {
2702 ObtainWriteLock(&avc->lock, 615);
2703 if (!hsame(avc->m.DataVersion, currentDV)) {
2704 /* We lose. Someone will beat us to it. */
2706 ReleaseWriteLock(&avc->lock);
2711 /* With slow pass, we've already done all the updates */
2713 ReleaseWriteLock(&avc->lock);
2716 /* Check if we need to perform any last-minute fixes with a write-lock */
2717 if (!setLocks || doVcacheUpdate) {
2719 avc->callback = newCallback;
2720 if (tsmall && setVcacheStatus)
2721 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2723 ReleaseWriteLock(&avc->lock);
2727 osi_FreeLargeSpace(tsmall);
2730 } /*afs_GetDCache */
2734 * afs_WriteThroughDSlots
2737 * Sweep through the dcache slots and write out any modified
2738 * in-memory data back on to our caching store.
2744 * The afs_xdcache is write-locked through this whole affair.
2747 afs_WriteThroughDSlots(void)
2749 register struct dcache *tdc;
2750 register afs_int32 i, touchedit = 0;
2752 struct afs_q DirtyQ, *tq;
2754 AFS_STATCNT(afs_WriteThroughDSlots);
2757 * Because of lock ordering, we can't grab dcache locks while
2758 * holding afs_xdcache. So we enter xdcache, get a reference
2759 * for every dcache entry, and exit xdcache.
2761 MObtainWriteLock(&afs_xdcache, 283);
2763 for (i = 0; i < afs_cacheFiles; i++) {
2764 tdc = afs_indexTable[i];
2766 /* Grab tlock in case the existing refcount isn't zero */
2767 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2768 ObtainWriteLock(&tdc->tlock, 623);
2770 ReleaseWriteLock(&tdc->tlock);
2772 QAdd(&DirtyQ, &tdc->dirty);
2775 MReleaseWriteLock(&afs_xdcache);
2778 * Now, for each dcache entry we found, check if it's dirty.
2779 * If so, get write-lock, get afs_xdcache, which protects
2780 * afs_cacheInodep, and flush it. Don't forget to put back
2784 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2786 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2788 if (tdc->dflags & DFEntryMod) {
2791 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2793 /* Now that we have the write lock, double-check */
2794 if (wrLock && (tdc->dflags & DFEntryMod)) {
2795 tdc->dflags &= ~DFEntryMod;
2796 MObtainWriteLock(&afs_xdcache, 620);
2797 afs_WriteDCache(tdc, 1);
2798 MReleaseWriteLock(&afs_xdcache);
2802 ReleaseWriteLock(&tdc->lock);
2808 MObtainWriteLock(&afs_xdcache, 617);
2809 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2810 /* Touch the file to make sure that the mtime on the file is kept
2811 * up-to-date to avoid losing cached files on cold starts because
2812 * their mtime seems old...
2814 struct afs_fheader theader;
2816 theader.magic = AFS_FHMAGIC;
2817 theader.firstCSize = AFS_FIRSTCSIZE;
2818 theader.otherCSize = AFS_OTHERCSIZE;
2819 theader.version = AFS_CI_VERSION;
2820 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2822 MReleaseWriteLock(&afs_xdcache);
2829 * Return a pointer to an freshly initialized dcache entry using
2830 * a memory-based cache. The tlock will be read-locked.
2833 * aslot : Dcache slot to look at.
2834 * tmpdc : Ptr to dcache entry.
2837 * Must be called with afs_xdcache write-locked.
2841 afs_MemGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2843 register struct dcache *tdc;
2846 AFS_STATCNT(afs_MemGetDSlot);
2847 if (CheckLock(&afs_xdcache) != -1)
2848 osi_Panic("getdslot nolock");
2849 if (aslot < 0 || aslot >= afs_cacheFiles)
2850 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2851 tdc = afs_indexTable[aslot];
2853 QRemove(&tdc->lruq); /* move to queue head */
2854 QAdd(&afs_DLRU, &tdc->lruq);
2855 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2856 ObtainWriteLock(&tdc->tlock, 624);
2858 ConvertWToRLock(&tdc->tlock);
2861 if (tmpdc == NULL) {
2862 if (!afs_freeDSList)
2863 afs_GetDownDSlot(4);
2864 if (!afs_freeDSList) {
2865 /* none free, making one is better than a panic */
2866 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2867 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2868 #ifdef KERNEL_HAVE_PIN
2869 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2872 tdc = afs_freeDSList;
2873 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2876 tdc->dflags = 0; /* up-to-date, not in free q */
2878 QAdd(&afs_DLRU, &tdc->lruq);
2879 if (tdc->lruq.prev == &tdc->lruq)
2880 osi_Panic("lruq 3");
2886 /* initialize entry */
2887 tdc->f.fid.Cell = 0;
2888 tdc->f.fid.Fid.Volume = 0;
2890 hones(tdc->f.versionNo);
2891 tdc->f.inode = aslot;
2892 tdc->dflags |= DFEntryMod;
2895 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2898 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2899 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2900 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2903 RWLOCK_INIT(&tdc->lock, "dcache lock");
2904 RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2905 RWLOCK_INIT(&tdc->mflock, "dcache flock");
2906 ObtainReadLock(&tdc->tlock);
2909 afs_indexTable[aslot] = tdc;
2912 } /*afs_MemGetDSlot */
2914 unsigned int last_error = 0, lasterrtime = 0;
2920 * Return a pointer to an freshly initialized dcache entry using
2921 * a UFS-based disk cache. The dcache tlock will be read-locked.
2924 * aslot : Dcache slot to look at.
2925 * tmpdc : Ptr to dcache entry.
2928 * afs_xdcache lock write-locked.
2931 afs_UFSGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2933 register afs_int32 code;
2934 register struct dcache *tdc;
2938 AFS_STATCNT(afs_UFSGetDSlot);
2939 if (CheckLock(&afs_xdcache) != -1)
2940 osi_Panic("getdslot nolock");
2941 if (aslot < 0 || aslot >= afs_cacheFiles)
2942 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2943 tdc = afs_indexTable[aslot];
2945 QRemove(&tdc->lruq); /* move to queue head */
2946 QAdd(&afs_DLRU, &tdc->lruq);
2947 /* Grab tlock in case refCount != 0 */
2948 ObtainWriteLock(&tdc->tlock, 625);
2950 ConvertWToRLock(&tdc->tlock);
2953 /* otherwise we should read it in from the cache file */
2955 * If we weren't passed an in-memory region to place the file info,
2956 * we have to allocate one.
2958 if (tmpdc == NULL) {
2959 if (!afs_freeDSList)
2960 afs_GetDownDSlot(4);
2961 if (!afs_freeDSList) {
2962 /* none free, making one is better than a panic */
2963 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2964 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2965 #ifdef KERNEL_HAVE_PIN
2966 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2969 tdc = afs_freeDSList;
2970 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2973 tdc->dflags = 0; /* up-to-date, not in free q */
2975 QAdd(&afs_DLRU, &tdc->lruq);
2976 if (tdc->lruq.prev == &tdc->lruq)
2977 osi_Panic("lruq 3");
2984 * Seek to the aslot'th entry and read it in.
2987 afs_osi_Read(afs_cacheInodep,
2988 sizeof(struct fcache) * aslot +
2989 sizeof(struct afs_fheader), (char *)(&tdc->f),
2990 sizeof(struct fcache));
2992 if (code != sizeof(struct fcache))
2994 if (!afs_CellNumValid(tdc->f.fid.Cell))
2998 tdc->f.fid.Cell = 0;
2999 tdc->f.fid.Fid.Volume = 0;
3001 hones(tdc->f.versionNo);
3002 tdc->dflags |= DFEntryMod;
3003 #if defined(KERNEL_HAVE_UERROR)
3004 last_error = getuerror();
3006 lasterrtime = osi_Time();
3007 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3008 tdc->f.states &= ~(DRO|DBackup|DRW);
3009 afs_DCMoveBucket(tdc, 0, 0);
3012 if (tdc->f.states & DRO) {
3013 afs_DCMoveBucket(tdc, 0, 2);
3014 } else if (tdc->f.states & DBackup) {
3015 afs_DCMoveBucket(tdc, 0, 1);
3017 afs_DCMoveBucket(tdc, 0, 1);
3023 if (tdc->f.chunk >= 0)
3024 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
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 * If we didn't read into a temporary dcache region, update the
3041 * slot pointer table.
3044 afs_indexTable[aslot] = tdc;
3047 } /*afs_UFSGetDSlot */
3055 * write a particular dcache entry back to its home in the
3059 * adc : Pointer to the dcache entry to write.
3060 * atime : If true, set the modtime on the file to the current time.
3063 * Must be called with the afs_xdcache lock at least read-locked,
3064 * and dcache entry at least read-locked.
3065 * The reference count is not changed.
3069 afs_WriteDCache(register struct dcache *adc, int atime)
3071 register afs_int32 code;
3073 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3075 AFS_STATCNT(afs_WriteDCache);
3076 osi_Assert(WriteLocked(&afs_xdcache));
3078 adc->f.modTime = osi_Time();
3080 * Seek to the right dcache slot and write the in-memory image out to disk.
3082 afs_cellname_write();
3084 afs_osi_Write(afs_cacheInodep,
3085 sizeof(struct fcache) * adc->index +
3086 sizeof(struct afs_fheader), (char *)(&adc->f),
3087 sizeof(struct fcache));
3088 if (code != sizeof(struct fcache))
3099 * Wake up users of a particular file waiting for stores to take
3103 * avc : Ptr to related vcache entry.
3106 * Nothing interesting.
3110 afs_wakeup(register struct vcache *avc)
3113 register struct brequest *tb;
3115 AFS_STATCNT(afs_wakeup);
3116 for (i = 0; i < NBRS; i++, tb++) {
3117 /* if request is valid and for this file, we've found it */
3118 if (tb->refCount > 0 && avc == tb->vc) {
3121 * If CSafeStore is on, then we don't awaken the guy
3122 * waiting for the store until the whole store has finished.
3123 * Otherwise, we do it now. Note that if CSafeStore is on,
3124 * the BStore routine actually wakes up the user, instead
3126 * I think this is redundant now because this sort of thing
3127 * is already being handled by the higher-level code.
3129 if ((avc->states & CSafeStore) == 0) {
3131 tb->flags |= BUVALID;
3132 if (tb->flags & BUWAIT) {
3133 tb->flags &= ~BUWAIT;
3148 * Given a file name and inode, set up that file to be an
3149 * active member in the AFS cache. This also involves checking
3150 * the usability of its data.
3153 * afile : Name of the cache file to initialize.
3154 * ainode : Inode of the file.
3157 * This function is called only during initialization.
3161 afs_InitCacheFile(char *afile, ino_t ainode)
3163 register afs_int32 code;
3164 #if defined(AFS_LINUX22_ENV)
3165 struct dentry *filevp;
3167 struct vnode *filevp;
3171 struct osi_file *tfile;
3172 struct osi_stat tstat;
3173 register struct dcache *tdc;
3175 AFS_STATCNT(afs_InitCacheFile);
3176 index = afs_stats_cmperf.cacheNumEntries;
3177 if (index >= afs_cacheFiles)
3180 MObtainWriteLock(&afs_xdcache, 282);
3181 tdc = afs_GetDSlot(index, NULL);
3182 ReleaseReadLock(&tdc->tlock);
3183 MReleaseWriteLock(&afs_xdcache);
3185 ObtainWriteLock(&tdc->lock, 621);
3186 MObtainWriteLock(&afs_xdcache, 622);
3188 code = gop_lookupname(afile, AFS_UIOSYS, 0, &filevp);
3190 ReleaseWriteLock(&afs_xdcache);
3191 ReleaseWriteLock(&tdc->lock);
3196 * We have a VN_HOLD on filevp. Get the useful info out and
3197 * return. We make use of the fact that the cache is in the
3198 * UFS file system, and just record the inode number.
3200 #ifdef AFS_LINUX22_ENV
3201 tdc->f.inode = VTOI(filevp->d_inode)->i_number;
3204 tdc->f.inode = afs_vnodeToInumber(filevp);
3206 #endif /* AFS_LINUX22_ENV */
3208 tdc->f.inode = ainode;
3211 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3213 tfile = osi_UFSOpen(tdc->f.inode);
3214 code = afs_osi_Stat(tfile, &tstat);
3216 osi_Panic("initcachefile stat");
3219 * If file size doesn't match the cache info file, it's probably bad.
3221 if (tdc->f.chunkBytes != tstat.size)
3223 tdc->f.chunkBytes = 0;
3226 * If file changed within T (120?) seconds of cache info file, it's
3227 * probably bad. In addition, if slot changed within last T seconds,
3228 * the cache info file may be incorrectly identified, and so slot
3231 if (cacheInfoModTime < tstat.mtime + 120)
3233 if (cacheInfoModTime < tdc->f.modTime + 120)
3235 /* In case write through is behind, make sure cache items entry is
3236 * at least as new as the chunk.
3238 if (tdc->f.modTime < tstat.mtime)
3241 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3242 if (tstat.size != 0)
3243 osi_UFSTruncate(tfile, 0);
3244 tdc->f.states &= ~(DRO|DBackup|DRW);
3245 afs_DCMoveBucket(tdc, 0, 0);
3246 /* put entry in free cache slot list */
3247 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3248 afs_freeDCList = index;
3250 afs_indexFlags[index] |= IFFree;
3251 afs_indexUnique[index] = 0;
3254 * We must put this entry in the appropriate hash tables.
3255 * Note that i is still set from the above DCHash call
3257 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3258 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3259 afs_dchashTbl[code] = tdc->index;
3260 code = DVHash(&tdc->f.fid);
3261 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3262 afs_dvhashTbl[code] = tdc->index;
3263 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3265 /* has nontrivial amt of data */
3266 afs_indexFlags[index] |= IFEverUsed;
3267 afs_stats_cmperf.cacheFilesReused++;
3269 * Initialize index times to file's mod times; init indexCounter
3272 hset32(afs_indexTimes[index], tstat.atime);
3273 if (hgetlo(afs_indexCounter) < tstat.atime) {
3274 hset32(afs_indexCounter, tstat.atime);
3276 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3277 } /*File is not bad */
3279 osi_UFSClose(tfile);
3280 tdc->f.states &= ~DWriting;
3281 tdc->dflags &= ~DFEntryMod;
3282 /* don't set f.modTime; we're just cleaning up */
3283 afs_WriteDCache(tdc, 0);
3284 ReleaseWriteLock(&afs_xdcache);
3285 ReleaseWriteLock(&tdc->lock);
3287 afs_stats_cmperf.cacheNumEntries++;
3292 /*Max # of struct dcache's resident at any time*/
3294 * If 'dchint' is enabled then in-memory dcache min is increased because of
3303 * Initialize dcache related variables.
3306 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3308 register struct dcache *tdp;
3312 afs_freeDCList = NULLIDX;
3313 afs_discardDCList = NULLIDX;
3314 afs_freeDCCount = 0;
3315 afs_freeDSList = NULL;
3316 hzero(afs_indexCounter);
3318 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3324 if (achunk < 0 || achunk > 30)
3325 achunk = 13; /* Use default */
3326 AFS_SETCHUNKSIZE(achunk);
3332 if (aflags & AFSCALL_INIT_MEMCACHE) {
3334 * Use a memory cache instead of a disk cache
3336 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3337 afs_cacheType = &afs_MemCacheOps;
3338 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3339 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3340 /* ablocks is reported in 1K blocks */
3341 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3343 printf("afsd: memory cache too large for available memory.\n");
3344 printf("afsd: AFS files cannot be accessed.\n\n");
3346 afiles = ablocks = 0;
3348 printf("Memory cache: Allocating %d dcache entries...",
3351 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3352 afs_cacheType = &afs_UfsCacheOps;
3355 if (aDentries > 512)
3356 afs_dhashsize = 2048;
3357 /* initialize hash tables */
3359 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3361 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3362 for (i = 0; i < afs_dhashsize; i++) {
3363 afs_dvhashTbl[i] = NULLIDX;
3364 afs_dchashTbl[i] = NULLIDX;
3366 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3367 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3368 for (i = 0; i < afiles; i++) {
3369 afs_dvnextTbl[i] = NULLIDX;
3370 afs_dcnextTbl[i] = NULLIDX;
3373 /* Allocate and zero the pointer array to the dcache entries */
3374 afs_indexTable = (struct dcache **)
3375 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3376 memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3378 (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3379 memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3381 (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3382 memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3383 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3384 memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
3386 /* Allocate and thread the struct dcache entries themselves */
3387 tdp = afs_Initial_freeDSList =
3388 (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3389 memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
3390 #ifdef KERNEL_HAVE_PIN
3391 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3392 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3393 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3394 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3395 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3396 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3397 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3398 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3399 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3402 afs_freeDSList = &tdp[0];
3403 for (i = 0; i < aDentries - 1; i++) {
3404 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3405 RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3406 RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3407 RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3409 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3410 RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3411 RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3412 RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3414 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3415 afs_cacheBlocks = ablocks;
3416 afs_ComputeCacheParms(); /* compute parms based on cache size */
3418 afs_dcentries = aDentries;
3420 afs_stats_cmperf.cacheBucket0_Discarded =
3421 afs_stats_cmperf.cacheBucket1_Discarded =
3422 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3432 shutdown_dcache(void)
3436 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3437 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3438 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3439 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3440 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3441 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3442 afs_osi_Free(afs_Initial_freeDSList,
3443 afs_dcentries * sizeof(struct dcache));
3444 #ifdef KERNEL_HAVE_PIN
3445 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3446 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3447 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3448 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3449 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3450 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3451 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3455 for (i = 0; i < afs_dhashsize; i++) {
3456 afs_dvhashTbl[i] = NULLIDX;
3457 afs_dchashTbl[i] = NULLIDX;
3460 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3461 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3463 afs_blocksUsed = afs_dcentries = 0;
3464 afs_stats_cmperf.cacheBucket0_Discarded =
3465 afs_stats_cmperf.cacheBucket1_Discarded =
3466 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3467 hzero(afs_indexCounter);
3469 afs_freeDCCount = 0;
3470 afs_freeDCList = NULLIDX;
3471 afs_discardDCList = NULLIDX;
3472 afs_freeDSList = afs_Initial_freeDSList = 0;
3474 LOCK_INIT(&afs_xdcache, "afs_xdcache");