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 */
62 afs_int32 *afs_dchashTbl; /*Data cache hash table */
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 afs_DCGetBucket(struct vcache *avc)
144 /* This should be replaced with some sort of user configurable function */
145 if (avc->states & CRO) {
147 } else if (avc->states & CBackup) {
157 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
159 afs_int32 adjustSize = newSize - oldSize;
167 afs_blocksUsed_0 += adjustSize;
168 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
171 afs_blocksUsed_1 += adjustSize;
172 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
175 afs_blocksUsed_2 += adjustSize;
176 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
184 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
192 afs_blocksUsed_0 -= size;
195 afs_blocksUsed_1 -= size;
198 afs_blocksUsed_2 -= size;
202 adc->bucket = newBucket;
207 afs_blocksUsed_0 += size;
210 afs_blocksUsed_1 += size;
213 afs_blocksUsed_2 += size;
223 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
227 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
232 afs_pct1 = afs_blocksUsed_1 / (afs_cacheBlocks / 100);
233 afs_pct2 = afs_blocksUsed_2 / (afs_cacheBlocks / 100);
235 /* Short cut: if we don't know about it, try to kill it */
236 if (phase < 2 && afs_blocksUsed_0)
239 if (afs_pct1 > afs_tpct1)
241 if (afs_pct2 > afs_tpct2)
243 return 0; /* unlikely */
251 * Warn about failing to store a file.
254 * acode : Associated error code.
255 * avolume : Volume involved.
256 * aflags : How to handle the output:
257 * aflags & 1: Print out on console
258 * aflags & 2: Print out on controlling tty
261 * Call this from close call when vnodeops is RCS unlocked.
265 afs_StoreWarn(register afs_int32 acode, afs_int32 avolume,
266 register afs_int32 aflags)
268 static char problem_fmt[] =
269 "afs: failed to store file in volume %d (%s)\n";
270 static char problem_fmt_w_error[] =
271 "afs: failed to store file in volume %d (error %d)\n";
272 static char netproblems[] = "network problems";
273 static char partfull[] = "partition full";
274 static char overquota[] = "over quota";
276 AFS_STATCNT(afs_StoreWarn);
282 afs_warn(problem_fmt, avolume, netproblems);
284 afs_warnuser(problem_fmt, avolume, netproblems);
285 } else if (acode == ENOSPC) {
290 afs_warn(problem_fmt, avolume, partfull);
292 afs_warnuser(problem_fmt, avolume, partfull);
295 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
296 * Instead ENOSPC will be sent...
298 if (acode == EDQUOT) {
303 afs_warn(problem_fmt, avolume, overquota);
305 afs_warnuser(problem_fmt, avolume, overquota);
313 afs_warn(problem_fmt_w_error, avolume, acode);
315 afs_warnuser(problem_fmt_w_error, avolume, acode);
320 afs_MaybeWakeupTruncateDaemon(void)
322 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
323 afs_CacheTooFull = 1;
324 if (!afs_TruncateDaemonRunning)
325 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
326 } else if (!afs_TruncateDaemonRunning
327 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
328 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
332 /* Keep statistics on run time for afs_CacheTruncateDaemon. This is a
333 * struct so we need only export one symbol for AIX.
335 static struct CTD_stats {
336 osi_timeval_t CTD_beforeSleep;
337 osi_timeval_t CTD_afterSleep;
338 osi_timeval_t CTD_sleepTime;
339 osi_timeval_t CTD_runTime;
343 u_int afs_min_cache = 0;
345 afs_CacheTruncateDaemon(void)
347 osi_timeval_t CTD_tmpTime;
351 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
353 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
355 osi_GetuTime(&CTD_stats.CTD_afterSleep);
356 afs_TruncateDaemonRunning = 1;
358 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
359 MObtainWriteLock(&afs_xdcache, 266);
360 if (afs_CacheTooFull) {
361 int space_needed, slots_needed;
362 /* if we get woken up, we should try to clean something out */
363 for (counter = 0; counter < 10; counter++) {
365 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
367 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
368 afs_GetDownD(slots_needed, &space_needed, 0);
369 if ((space_needed <= 0) && (slots_needed <= 0)) {
372 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
375 if (!afs_CacheIsTooFull())
376 afs_CacheTooFull = 0;
378 MReleaseWriteLock(&afs_xdcache);
381 * This is a defensive check to try to avoid starving threads
382 * that may need the global lock so thay can help free some
383 * cache space. If this thread won't be sleeping or truncating
384 * any cache files then give up the global lock so other
385 * threads get a chance to run.
387 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
388 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
389 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
393 * This is where we free the discarded cache elements.
395 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
396 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
397 afs_FreeDiscardedDCache();
400 /* See if we need to continue to run. Someone may have
401 * signalled us while we were executing.
403 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
404 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
405 /* Collect statistics on truncate daemon. */
406 CTD_stats.CTD_nSleeps++;
407 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
408 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
409 CTD_stats.CTD_beforeSleep);
410 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
412 afs_TruncateDaemonRunning = 0;
413 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
414 afs_TruncateDaemonRunning = 1;
416 osi_GetuTime(&CTD_stats.CTD_afterSleep);
417 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
418 CTD_stats.CTD_afterSleep);
419 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
421 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
423 afs_termState = AFSOP_STOP_AFSDB;
425 afs_termState = AFSOP_STOP_RXEVENT;
427 afs_osi_Wakeup(&afs_termState);
438 * Make adjustment for the new size in the disk cache entry
440 * Major Assumptions Here:
441 * Assumes that frag size is an integral power of two, less one,
442 * and that this is a two's complement machine. I don't
443 * know of any filesystems which violate this assumption...
446 * adc : Ptr to dcache entry.
447 * anewsize : New size desired.
451 afs_AdjustSize(register struct dcache *adc, register afs_int32 newSize)
453 register afs_int32 oldSize;
455 AFS_STATCNT(afs_AdjustSize);
457 adc->dflags |= DFEntryMod;
458 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
459 adc->f.chunkBytes = newSize;
462 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
463 afs_DCAdjustSize(adc, oldSize, newSize);
464 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
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 */
520 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
521 vfslocked = VFS_LOCK_GIANT(afs_globalVFS);
524 AFS_STATCNT(afs_GetDownD);
526 if (CheckLock(&afs_xdcache) != -1)
527 osi_Panic("getdownd nolock");
528 /* decrement anumber first for all dudes in free list */
529 /* SHOULD always decrement anumber first, even if aneedSpace >0,
530 * because we should try to free space even if anumber <=0 */
531 if (!aneedSpace || *aneedSpace <= 0) {
532 anumber -= afs_freeDCCount;
534 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
535 VFS_UNLOCK_GIANT(vfslocked);
537 return; /* enough already free */
541 /* bounds check parameter */
542 if (anumber > MAXATONCE)
543 anumber = MAXATONCE; /* all we can do */
545 /* rewrite so phases include a better eligiblity for gc test*/
547 * The phase variable manages reclaims. Set to 0, the first pass,
548 * we don't reclaim active entries, or other than target bucket.
549 * Set to 1, we reclaim even active ones in target bucket.
550 * Set to 2, we reclaim any inactive one.
551 * Set to 3, we reclaim even active ones.
559 for (i = 0; i < afs_cacheFiles; i++)
560 /* turn off all flags */
561 afs_indexFlags[i] &= ~IFFlag;
563 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
564 /* find oldest entries for reclamation */
565 maxVictimPtr = victimPtr = 0;
566 hzero(maxVictimTime);
567 curbucket = afs_DCWhichBucket(phase, buckethint);
568 /* select victims from access time array */
569 for (i = 0; i < afs_cacheFiles; i++) {
570 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
571 /* skip if dirty or already free */
574 tdc = afs_indexTable[i];
575 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
577 /* Wrong bucket; can't use it! */
580 if (tdc && (tdc->refCount != 0)) {
581 /* Referenced; can't use it! */
584 hset(vtime, afs_indexTimes[i]);
586 /* if we've already looked at this one, skip it */
587 if (afs_indexFlags[i] & IFFlag)
590 if (victimPtr < MAXATONCE) {
591 /* if there's at least one free victim slot left */
592 victims[victimPtr] = i;
593 hset(victimTimes[victimPtr], vtime);
594 if (hcmp(vtime, maxVictimTime) > 0) {
595 hset(maxVictimTime, vtime);
596 maxVictimPtr = victimPtr;
599 } else if (hcmp(vtime, maxVictimTime) < 0) {
601 * We're older than youngest victim, so we replace at
604 /* find youngest (largest LRU) victim */
607 osi_Panic("getdownd local");
609 hset(victimTimes[j], vtime);
610 /* recompute maxVictimTime */
611 hset(maxVictimTime, vtime);
612 for (j = 0; j < victimPtr; j++)
613 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
614 hset(maxVictimTime, victimTimes[j]);
620 /* now really reclaim the victims */
621 j = 0; /* flag to track if we actually got any of the victims */
622 /* first, hold all the victims, since we're going to release the lock
623 * during the truncate operation.
625 for (i = 0; i < victimPtr; i++) {
626 tdc = afs_GetDSlot(victims[i], 0);
627 /* We got tdc->tlock(R) here */
628 if (tdc->refCount == 1)
632 ReleaseReadLock(&tdc->tlock);
636 for (i = 0; i < victimPtr; i++) {
637 /* q is first elt in dcache entry */
639 /* now, since we're dropping the afs_xdcache lock below, we
640 * have to verify, before proceeding, that there are no other
641 * references to this dcache entry, even now. Note that we
642 * compare with 1, since we bumped it above when we called
643 * afs_GetDSlot to preserve the entry's identity.
645 if (tdc && tdc->refCount == 1) {
646 unsigned char chunkFlags;
647 afs_size_t tchunkoffset = 0;
649 /* xdcache is lower than the xvcache lock */
650 MReleaseWriteLock(&afs_xdcache);
651 MObtainReadLock(&afs_xvcache);
652 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
653 MReleaseReadLock(&afs_xvcache);
654 MObtainWriteLock(&afs_xdcache, 527);
656 if (tdc->refCount > 1)
659 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
660 chunkFlags = afs_indexFlags[tdc->index];
661 if (((phase & 1) == 0) && osi_Active(tvc))
663 if (((phase & 1) == 1) && osi_Active(tvc)
664 && (tvc->states & CDCLock)
665 && (chunkFlags & IFAnyPages))
667 if (chunkFlags & IFDataMod)
669 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
670 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
671 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
672 ICL_HANDLE_OFFSET(tchunkoffset));
674 #if defined(AFS_SUN5_ENV)
676 * Now we try to invalidate pages. We do this only for
677 * Solaris. For other platforms, it's OK to recycle a
678 * dcache entry out from under a page, because the strategy
679 * function can call afs_GetDCache().
681 if (!skip && (chunkFlags & IFAnyPages)) {
684 MReleaseWriteLock(&afs_xdcache);
685 MObtainWriteLock(&tvc->vlock, 543);
686 if (tvc->multiPage) {
690 /* block locking pages */
691 tvc->vstates |= VPageCleaning;
692 /* block getting new pages */
694 MReleaseWriteLock(&tvc->vlock);
695 /* One last recheck */
696 MObtainWriteLock(&afs_xdcache, 333);
697 chunkFlags = afs_indexFlags[tdc->index];
698 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
699 || (osi_Active(tvc) && (tvc->states & CDCLock)
700 && (chunkFlags & IFAnyPages))) {
702 MReleaseWriteLock(&afs_xdcache);
705 MReleaseWriteLock(&afs_xdcache);
707 code = osi_VM_GetDownD(tvc, tdc);
709 MObtainWriteLock(&afs_xdcache, 269);
710 /* we actually removed all pages, clean and dirty */
712 afs_indexFlags[tdc->index] &=
713 ~(IFDirtyPages | IFAnyPages);
716 MReleaseWriteLock(&afs_xdcache);
718 MObtainWriteLock(&tvc->vlock, 544);
719 if (--tvc->activeV == 0
720 && (tvc->vstates & VRevokeWait)) {
721 tvc->vstates &= ~VRevokeWait;
722 afs_osi_Wakeup((char *)&tvc->vstates);
725 if (tvc->vstates & VPageCleaning) {
726 tvc->vstates &= ~VPageCleaning;
727 afs_osi_Wakeup((char *)&tvc->vstates);
730 MReleaseWriteLock(&tvc->vlock);
732 #endif /* AFS_SUN5_ENV */
734 MReleaseWriteLock(&afs_xdcache);
737 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
738 MObtainWriteLock(&afs_xdcache, 528);
739 if (afs_indexFlags[tdc->index] &
740 (IFDataMod | IFDirtyPages | IFAnyPages))
742 if (tdc->refCount > 1)
745 #if defined(AFS_SUN5_ENV)
747 /* no vnode, so IFDirtyPages is spurious (we don't
748 * sweep dcaches on vnode recycling, so we can have
749 * DIRTYPAGES set even when all pages are gone). Just
751 * Hold vcache lock to prevent vnode from being
752 * created while we're clearing IFDirtyPages.
754 afs_indexFlags[tdc->index] &=
755 ~(IFDirtyPages | IFAnyPages);
759 /* skip this guy and mark him as recently used */
760 afs_indexFlags[tdc->index] |= IFFlag;
761 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
762 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
763 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
764 ICL_HANDLE_OFFSET(tchunkoffset));
766 /* flush this dude from the data cache and reclaim;
767 * first, make sure no one will care that we damage
768 * it, by removing it from all hash tables. Then,
769 * melt it down for parts. Note that any concurrent
770 * (new possibility!) calls to GetDownD won't touch
771 * this guy because his reference count is > 0. */
772 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
773 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
774 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
775 ICL_HANDLE_OFFSET(tchunkoffset));
776 AFS_STATCNT(afs_gget);
777 afs_HashOutDCache(tdc, 1);
778 if (tdc->f.chunkBytes != 0) {
782 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
787 afs_DiscardDCache(tdc);
792 j = 1; /* we reclaimed at least one victim */
799 /* Phase is 0 and no one was found, so try phase 1 (ignore
800 * osi_Active flag) */
803 for (i = 0; i < afs_cacheFiles; i++)
804 /* turn off all flags */
805 afs_indexFlags[i] &= ~IFFlag;
808 /* found no one in phases 0-5, we're hosed */
812 } /* big while loop */
814 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
815 VFS_UNLOCK_GIANT(vfslocked);
824 * Description: remove adc from any hash tables that would allow it to be located
825 * again by afs_FindDCache or afs_GetDCache.
827 * Parameters: adc -- pointer to dcache entry to remove from hash tables.
828 * zap -- zap the given dcache ?
830 * Locks: Must have the afs_xdcache lock write-locked to call this function.
833 afs_HashOutDCache(struct dcache *adc, int zap)
837 AFS_STATCNT(afs_glink);
839 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
841 /* if this guy is in the hash table, pull him out */
842 if (adc->f.fid.Fid.Volume != 0) {
843 /* remove entry from first hash chains */
844 i = DCHash(&adc->f.fid, adc->f.chunk);
845 us = afs_dchashTbl[i];
846 if (us == adc->index) {
847 /* first dude in the list */
848 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
850 /* somewhere on the chain */
851 while (us != NULLIDX) {
852 if (afs_dcnextTbl[us] == adc->index) {
853 /* found item pointing at the one to delete */
854 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
857 us = afs_dcnextTbl[us];
860 osi_Panic("dcache hc");
862 /* remove entry from *other* hash chain */
863 i = DVHash(&adc->f.fid);
864 us = afs_dvhashTbl[i];
865 if (us == adc->index) {
866 /* first dude in the list */
867 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
869 /* somewhere on the chain */
870 while (us != NULLIDX) {
871 if (afs_dvnextTbl[us] == adc->index) {
872 /* found item pointing at the one to delete */
873 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
876 us = afs_dvnextTbl[us];
879 osi_Panic("dcache hv");
884 /* prevent entry from being found on a reboot (it is already out of
885 * the hash table, but after a crash, we just look at fid fields of
886 * stable (old) entries).
888 adc->f.fid.Fid.Volume = 0; /* invalid */
890 /* mark entry as modified */
891 adc->dflags |= DFEntryMod;
896 } /*afs_HashOutDCache */
902 * Flush the given dcache entry, pulling it from hash chains
903 * and truncating the associated cache file.
906 * adc: Ptr to dcache entry to flush.
909 * This routine must be called with the afs_xdcache lock held
914 afs_FlushDCache(register struct dcache *adc)
916 AFS_STATCNT(afs_FlushDCache);
918 * Bump the number of cache files flushed.
920 afs_stats_cmperf.cacheFlushes++;
922 /* remove from all hash tables */
923 afs_HashOutDCache(adc, 1);
925 /* Free its space; special case null operation, since truncate operation
926 * in UFS is slow even in this case, and this allows us to pre-truncate
927 * these files at more convenient times with fewer locks set
928 * (see afs_GetDownD).
930 if (adc->f.chunkBytes != 0) {
931 afs_DiscardDCache(adc);
932 afs_MaybeWakeupTruncateDaemon();
937 if (afs_WaitForCacheDrain) {
938 if (afs_blocksUsed <=
939 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
940 afs_WaitForCacheDrain = 0;
941 afs_osi_Wakeup(&afs_WaitForCacheDrain);
944 } /*afs_FlushDCache */
950 * Description: put a dcache entry on the free dcache entry list.
952 * Parameters: adc -- dcache entry to free
954 * Environment: called with afs_xdcache lock write-locked.
957 afs_FreeDCache(register struct dcache *adc)
959 /* Thread on free list, update free list count and mark entry as
960 * freed in its indexFlags element. Also, ensure DCache entry gets
961 * written out (set DFEntryMod).
964 afs_dvnextTbl[adc->index] = afs_freeDCList;
965 afs_freeDCList = adc->index;
967 afs_indexFlags[adc->index] |= IFFree;
968 adc->dflags |= DFEntryMod;
970 if (afs_WaitForCacheDrain) {
971 if ((afs_blocksUsed - afs_blocksDiscarded) <=
972 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
973 afs_WaitForCacheDrain = 0;
974 afs_osi_Wakeup(&afs_WaitForCacheDrain);
983 * Discard the cache element by moving it to the discardDCList.
984 * This puts the cache element into a quasi-freed state, where
985 * the space may be reused, but the file has not been truncated.
987 * Major Assumptions Here:
988 * Assumes that frag size is an integral power of two, less one,
989 * and that this is a two's complement machine. I don't
990 * know of any filesystems which violate this assumption...
993 * adc : Ptr to dcache entry.
996 * Must be called with afs_xdcache write-locked.
1000 afs_DiscardDCache(register struct dcache *adc)
1002 register afs_int32 size;
1004 AFS_STATCNT(afs_DiscardDCache);
1006 osi_Assert(adc->refCount == 1);
1008 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1009 afs_blocksDiscarded += size;
1010 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1012 afs_dvnextTbl[adc->index] = afs_discardDCList;
1013 afs_discardDCList = adc->index;
1014 afs_discardDCCount++;
1016 adc->f.fid.Fid.Volume = 0;
1017 adc->dflags |= DFEntryMod;
1018 afs_indexFlags[adc->index] |= IFDiscarded;
1020 if (afs_WaitForCacheDrain) {
1021 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1022 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1023 afs_WaitForCacheDrain = 0;
1024 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1028 } /*afs_DiscardDCache */
1031 * afs_FreeDiscardedDCache
1034 * Free the next element on the list of discarded cache elements.
1037 afs_FreeDiscardedDCache(void)
1039 register struct dcache *tdc;
1040 register struct osi_file *tfile;
1041 register afs_int32 size;
1043 AFS_STATCNT(afs_FreeDiscardedDCache);
1045 MObtainWriteLock(&afs_xdcache, 510);
1046 if (!afs_blocksDiscarded) {
1047 MReleaseWriteLock(&afs_xdcache);
1052 * Get an entry from the list of discarded cache elements
1054 tdc = afs_GetDSlot(afs_discardDCList, 0);
1055 osi_Assert(tdc->refCount == 1);
1056 ReleaseReadLock(&tdc->tlock);
1058 afs_discardDCList = afs_dvnextTbl[tdc->index];
1059 afs_dvnextTbl[tdc->index] = NULLIDX;
1060 afs_discardDCCount--;
1061 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1062 afs_blocksDiscarded -= size;
1063 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1064 /* We can lock because we just took it off the free list */
1065 ObtainWriteLock(&tdc->lock, 626);
1066 MReleaseWriteLock(&afs_xdcache);
1069 * Truncate the element to reclaim its space
1071 tfile = afs_CFileOpen(tdc->f.inode);
1072 afs_CFileTruncate(tfile, 0);
1073 afs_CFileClose(tfile);
1074 afs_AdjustSize(tdc, 0);
1075 afs_DCMoveBucket(tdc, 0, 0);
1078 * Free the element we just truncated
1080 MObtainWriteLock(&afs_xdcache, 511);
1081 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1082 afs_FreeDCache(tdc);
1083 tdc->f.states &= ~(DRO|DBackup|DRW);
1084 ReleaseWriteLock(&tdc->lock);
1086 MReleaseWriteLock(&afs_xdcache);
1090 * afs_MaybeFreeDiscardedDCache
1093 * Free as many entries from the list of discarded cache elements
1094 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1100 afs_MaybeFreeDiscardedDCache(void)
1103 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1105 while (afs_blocksDiscarded
1106 && (afs_blocksUsed >
1107 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1108 afs_FreeDiscardedDCache();
1117 * Try to free up a certain number of disk slots.
1120 * anumber : Targeted number of disk slots to free up.
1123 * Must be called with afs_xdcache write-locked.
1126 afs_GetDownDSlot(int anumber)
1128 struct afs_q *tq, *nq;
1133 AFS_STATCNT(afs_GetDownDSlot);
1134 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1135 osi_Panic("diskless getdowndslot");
1137 if (CheckLock(&afs_xdcache) != -1)
1138 osi_Panic("getdowndslot nolock");
1140 /* decrement anumber first for all dudes in free list */
1141 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1144 return; /* enough already free */
1146 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1148 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1149 nq = QPrev(tq); /* in case we remove it */
1150 if (tdc->refCount == 0) {
1151 if ((ix = tdc->index) == NULLIDX)
1152 osi_Panic("getdowndslot");
1153 /* pull the entry out of the lruq and put it on the free list */
1154 QRemove(&tdc->lruq);
1156 /* write-through if modified */
1157 if (tdc->dflags & DFEntryMod) {
1158 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1160 * ask proxy to do this for us - we don't have the stack space
1162 while (tdc->dflags & DFEntryMod) {
1165 s = SPLOCK(afs_sgibklock);
1166 if (afs_sgibklist == NULL) {
1167 /* if slot is free, grab it. */
1168 afs_sgibklist = tdc;
1169 SV_SIGNAL(&afs_sgibksync);
1171 /* wait for daemon to (start, then) finish. */
1172 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1176 tdc->dflags &= ~DFEntryMod;
1177 afs_WriteDCache(tdc, 1);
1181 /* finally put the entry in the free list */
1182 afs_indexTable[ix] = NULL;
1183 afs_indexFlags[ix] &= ~IFEverUsed;
1184 tdc->index = NULLIDX;
1185 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1186 afs_freeDSList = tdc;
1190 } /*afs_GetDownDSlot */
1197 * Increment the reference count on a disk cache entry,
1198 * which already has a non-zero refcount. In order to
1199 * increment the refcount of a zero-reference entry, you
1200 * have to hold afs_xdcache.
1203 * adc : Pointer to the dcache entry to increment.
1206 * Nothing interesting.
1209 afs_RefDCache(struct dcache *adc)
1211 ObtainWriteLock(&adc->tlock, 627);
1212 if (adc->refCount < 0)
1213 osi_Panic("RefDCache: negative refcount");
1215 ReleaseWriteLock(&adc->tlock);
1224 * Decrement the reference count on a disk cache entry.
1227 * ad : Ptr to the dcache entry to decrement.
1230 * Nothing interesting.
1233 afs_PutDCache(register struct dcache *adc)
1235 AFS_STATCNT(afs_PutDCache);
1236 ObtainWriteLock(&adc->tlock, 276);
1237 if (adc->refCount <= 0)
1238 osi_Panic("putdcache");
1240 ReleaseWriteLock(&adc->tlock);
1249 * Try to discard all data associated with this file from the
1253 * avc : Pointer to the cache info for the file.
1256 * Both pvnLock and lock are write held.
1259 afs_TryToSmush(register struct vcache *avc, struct AFS_UCRED *acred, int sync)
1261 register struct dcache *tdc;
1264 AFS_STATCNT(afs_TryToSmush);
1265 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1266 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->m.Length));
1267 sync = 1; /* XX Temp testing XX */
1269 #if defined(AFS_SUN5_ENV)
1270 ObtainWriteLock(&avc->vlock, 573);
1271 avc->activeV++; /* block new getpages */
1272 ReleaseWriteLock(&avc->vlock);
1275 /* Flush VM pages */
1276 osi_VM_TryToSmush(avc, acred, sync);
1279 * Get the hash chain containing all dce's for this fid
1281 i = DVHash(&avc->fid);
1282 MObtainWriteLock(&afs_xdcache, 277);
1283 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1284 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1285 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1286 int releaseTlock = 1;
1287 tdc = afs_GetDSlot(index, NULL);
1288 if (!FidCmp(&tdc->f.fid, &avc->fid)) {
1290 if ((afs_indexFlags[index] & IFDataMod) == 0
1291 && tdc->refCount == 1) {
1292 ReleaseReadLock(&tdc->tlock);
1294 afs_FlushDCache(tdc);
1297 afs_indexTable[index] = 0;
1300 ReleaseReadLock(&tdc->tlock);
1304 #if defined(AFS_SUN5_ENV)
1305 ObtainWriteLock(&avc->vlock, 545);
1306 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1307 avc->vstates &= ~VRevokeWait;
1308 afs_osi_Wakeup((char *)&avc->vstates);
1310 ReleaseWriteLock(&avc->vlock);
1312 MReleaseWriteLock(&afs_xdcache);
1314 * It's treated like a callback so that when we do lookups we'll
1315 * invalidate the unique bit if any
1316 * trytoSmush occured during the lookup call
1322 * afs_DCacheMissingChunks
1325 * Given the cached info for a file, return the number of chunks that
1326 * are not available from the dcache.
1329 * avc: Pointer to the (held) vcache entry to look in.
1332 * The number of chunks which are not currently cached.
1335 * The vcache entry is held upon entry.
1339 afs_DCacheMissingChunks(struct vcache *avc)
1342 afs_size_t totalLength = 0;
1343 afs_uint32 totalChunks = 0;
1346 totalLength = avc->m.Length;
1347 if (avc->truncPos < totalLength)
1348 totalLength = avc->truncPos;
1350 /* Length is 0, no chunk missing. */
1351 if (totalLength == 0)
1354 /* If totalLength is a multiple of chunksize, the last byte appears
1355 * as being part of the next chunk, which does not exist.
1356 * Decrementing totalLength by one fixes that.
1359 totalChunks = (AFS_CHUNK(totalLength) + 1);
1362 printf("Should have %d chunks for %u bytes\n",
1363 totalChunks, (totalLength + 1));
1365 i = DVHash(&avc->fid);
1366 MObtainWriteLock(&afs_xdcache, 1001);
1367 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1368 i = afs_dvnextTbl[index];
1369 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1370 tdc = afs_GetDSlot(index, NULL);
1371 if (!FidCmp(&tdc->f.fid, &avc->fid)) {
1374 ReleaseReadLock(&tdc->tlock);
1378 MReleaseWriteLock(&afs_xdcache);
1380 /*printf("Missing %d chunks\n", totalChunks);*/
1382 return (totalChunks);
1389 * Given the cached info for a file and a byte offset into the
1390 * file, make sure the dcache entry for that file and containing
1391 * the given byte is available, returning it to our caller.
1394 * avc : Pointer to the (held) vcache entry to look in.
1395 * abyte : Which byte we want to get to.
1398 * Pointer to the dcache entry covering the file & desired byte,
1399 * or NULL if not found.
1402 * The vcache entry is held upon entry.
1406 afs_FindDCache(register struct vcache *avc, afs_size_t abyte)
1409 register afs_int32 i, index;
1410 register struct dcache *tdc = NULL;
1412 AFS_STATCNT(afs_FindDCache);
1413 chunk = AFS_CHUNK(abyte);
1416 * Hash on the [fid, chunk] and get the corresponding dcache index
1417 * after write-locking the dcache.
1419 i = DCHash(&avc->fid, chunk);
1420 MObtainWriteLock(&afs_xdcache, 278);
1421 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1422 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1423 tdc = afs_GetDSlot(index, NULL);
1424 ReleaseReadLock(&tdc->tlock);
1425 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1426 break; /* leaving refCount high for caller */
1430 index = afs_dcnextTbl[index];
1432 if (index != NULLIDX) {
1433 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1434 hadd32(afs_indexCounter, 1);
1435 MReleaseWriteLock(&afs_xdcache);
1438 MReleaseWriteLock(&afs_xdcache);
1440 } /*afs_FindDCache */
1444 * afs_UFSCacheStoreProc
1447 * Called upon store.
1450 * acall : Ptr to the Rx call structure involved.
1451 * afile : Ptr to the related file descriptor.
1452 * alen : Size of the file in bytes.
1453 * avc : Ptr to the vcache entry.
1454 * shouldWake : is it "safe" to return early from close() ?
1455 * abytesToXferP : Set to the number of bytes to xfer.
1456 * NOTE: This parameter is only used if AFS_NOSTATS
1458 * abytesXferredP : Set to the number of bytes actually xferred.
1459 * NOTE: This parameter is only used if AFS_NOSTATS
1463 * Nothing interesting.
1466 afs_UFSCacheStoreProc(register struct rx_call *acall, struct osi_file *afile,
1467 register afs_int32 alen, struct vcache *avc,
1468 int *shouldWake, afs_size_t * abytesToXferP,
1469 afs_size_t * abytesXferredP)
1471 afs_int32 code, got;
1472 register char *tbuffer;
1475 AFS_STATCNT(UFS_CacheStoreProc);
1479 * In this case, alen is *always* the amount of data we'll be trying
1482 (*abytesToXferP) = alen;
1483 (*abytesXferredP) = 0;
1484 #endif /* AFS_NOSTATS */
1486 afs_Trace4(afs_iclSetp, CM_TRACE_STOREPROC, ICL_TYPE_POINTER, avc,
1487 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
1488 ICL_HANDLE_OFFSET(avc->m.Length), ICL_TYPE_INT32, alen);
1489 tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1491 tlen = (alen > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : alen);
1492 got = afs_osi_Read(afile, -1, tbuffer, tlen);
1494 #if defined(KERNEL_HAVE_UERROR)
1495 || (got != tlen && getuerror())
1498 osi_FreeLargeSpace(tbuffer);
1501 afs_Trace2(afs_iclSetp, CM_TRACE_STOREPROC2, ICL_TYPE_OFFSET,
1502 ICL_HANDLE_OFFSET(*tbuffer), ICL_TYPE_INT32, got);
1504 code = rx_Write(acall, tbuffer, got); /* writing 0 bytes will
1505 * push a short packet. Is that really what we want, just because the
1506 * data didn't come back from the disk yet? Let's try it and see. */
1509 (*abytesXferredP) += code;
1510 #endif /* AFS_NOSTATS */
1512 code = rx_Error(acall);
1513 osi_FreeLargeSpace(tbuffer);
1514 return code ? code : -33;
1518 * If file has been locked on server, we can allow the store
1521 if (shouldWake && *shouldWake && (rx_GetRemoteStatus(acall) & 1)) {
1522 *shouldWake = 0; /* only do this once */
1526 afs_Trace4(afs_iclSetp, CM_TRACE_STOREPROC, ICL_TYPE_POINTER, avc,
1527 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
1528 ICL_HANDLE_OFFSET(avc->m.Length), ICL_TYPE_INT32, alen);
1529 osi_FreeLargeSpace(tbuffer);
1532 } /* afs_UFSCacheStoreProc */
1536 * afs_UFSCacheFetchProc
1539 * Routine called on fetch; also tells people waiting for data
1540 * that more has arrived.
1543 * acall : Ptr to the Rx call structure.
1544 * afile : File descriptor for the cache file.
1545 * abase : Base offset to fetch.
1546 * adc : Ptr to the dcache entry for the file, write-locked.
1547 * avc : Ptr to the vcache entry for the file.
1548 * abytesToXferP : Set to the number of bytes to xfer.
1549 * NOTE: This parameter is only used if AFS_NOSTATS
1551 * abytesXferredP : Set to the number of bytes actually xferred.
1552 * NOTE: This parameter is only used if AFS_NOSTATS
1556 * Nothing interesting.
1560 afs_UFSCacheFetchProc(register struct rx_call *acall, struct osi_file *afile,
1561 afs_size_t abase, struct dcache *adc,
1562 struct vcache *avc, afs_size_t * abytesToXferP,
1563 afs_size_t * abytesXferredP, afs_int32 lengthFound)
1566 register afs_int32 code;
1567 register char *tbuffer;
1571 AFS_STATCNT(UFS_CacheFetchProc);
1572 osi_Assert(WriteLocked(&adc->lock));
1573 afile->offset = 0; /* Each time start from the beginning */
1574 length = lengthFound;
1576 (*abytesToXferP) = 0;
1577 (*abytesXferredP) = 0;
1578 #endif /* AFS_NOSTATS */
1579 tbuffer = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
1580 adc->validPos = abase;
1584 code = rx_Read(acall, (char *)&length, sizeof(afs_int32));
1586 length = ntohl(length);
1587 if (code != sizeof(afs_int32)) {
1588 osi_FreeLargeSpace(tbuffer);
1589 code = rx_Error(acall);
1590 return (code ? code : -1); /* try to return code, not -1 */
1594 * The fetch protocol is extended for the AFS/DFS translator
1595 * to allow multiple blocks of data, each with its own length,
1596 * to be returned. As long as the top bit is set, there are more
1599 * We do not do this for AFS file servers because they sometimes
1600 * return large negative numbers as the transfer size.
1602 if (avc->states & CForeign) {
1603 moredata = length & 0x80000000;
1604 length &= ~0x80000000;
1609 (*abytesToXferP) += length;
1610 #endif /* AFS_NOSTATS */
1611 while (length > 0) {
1612 tlen = (length > AFS_LRALLOCSIZ ? AFS_LRALLOCSIZ : length);
1613 #ifdef RX_KERNEL_TRACE
1614 afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
1618 code = rx_Read(acall, tbuffer, tlen);
1620 #ifdef RX_KERNEL_TRACE
1621 afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
1625 (*abytesXferredP) += code;
1626 #endif /* AFS_NOSTATS */
1628 osi_FreeLargeSpace(tbuffer);
1629 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64READ,
1630 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
1631 ICL_TYPE_INT32, length);
1634 code = afs_osi_Write(afile, -1, tbuffer, tlen);
1636 osi_FreeLargeSpace(tbuffer);
1641 adc->validPos = abase;
1642 if (afs_osi_Wakeup(&adc->validPos) == 0)
1643 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
1644 __FILE__, ICL_TYPE_INT32, __LINE__,
1645 ICL_TYPE_POINTER, adc, ICL_TYPE_INT32,
1649 osi_FreeLargeSpace(tbuffer);
1652 } /* afs_UFSCacheFetchProc */
1655 * Get a fresh dcache from the free or discarded list.
1657 * \param avc Who's dcache is this going to be?
1658 * \param chunk The position where it will be placed in.
1659 * \param lock How are locks held.
1660 * \param ashFid If this dcache going to be used for a shadow dir,
1663 * \note Required locks:
1665 * - avc (R if (lock & 1) set and W otherwise)
1666 * \note It write locks the new dcache. The caller must unlock it.
1668 * \return The new dcache.
1670 struct dcache *afs_AllocDCache(struct vcache *avc,
1673 struct VenusFid *ashFid)
1675 struct dcache *tdc = NULL;
1676 afs_uint32 size = 0;
1677 struct osi_file *file;
1679 if (afs_discardDCList == NULLIDX
1680 || ((lock & 2) && afs_freeDCList != NULLIDX)) {
1682 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1683 tdc = afs_GetDSlot(afs_freeDCList, 0);
1684 osi_Assert(tdc->refCount == 1);
1685 ReleaseReadLock(&tdc->tlock);
1686 ObtainWriteLock(&tdc->lock, 604);
1687 afs_freeDCList = afs_dvnextTbl[tdc->index];
1690 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1691 tdc = afs_GetDSlot(afs_discardDCList, 0);
1692 osi_Assert(tdc->refCount == 1);
1693 ReleaseReadLock(&tdc->tlock);
1694 ObtainWriteLock(&tdc->lock, 605);
1695 afs_discardDCList = afs_dvnextTbl[tdc->index];
1696 afs_discardDCCount--;
1698 ((tdc->f.chunkBytes +
1699 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1700 tdc->f.states &= ~(DRO|DBackup|DRW);
1701 afs_DCMoveBucket(tdc, size, 0);
1702 afs_blocksDiscarded -= size;
1703 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1705 /* Truncate the chunk so zeroes get filled properly */
1706 file = afs_CFileOpen(tdc->f.inode);
1707 afs_CFileTruncate(file, 0);
1708 afs_CFileClose(file);
1709 afs_AdjustSize(tdc, 0);
1715 * avc->lock(R) if setLocks
1716 * avc->lock(W) if !setLocks
1722 * Fill in the newly-allocated dcache record.
1724 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1726 /* Use shadow fid if provided. */
1727 tdc->f.fid = *ashFid;
1729 /* Use normal vcache's fid otherwise. */
1730 tdc->f.fid = avc->fid;
1731 if (avc->states & CRO)
1732 tdc->f.states = DRO;
1733 else if (avc->states & CBackup)
1734 tdc->f.states = DBackup;
1736 tdc->f.states = DRW;
1737 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1738 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1740 hones(tdc->f.versionNo); /* invalid value */
1741 tdc->f.chunk = chunk;
1742 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1744 if (tdc->lruq.prev == &tdc->lruq)
1745 osi_Panic("lruq 1");
1754 * This function is called to obtain a reference to data stored in
1755 * the disk cache, locating a chunk of data containing the desired
1756 * byte and returning a reference to the disk cache entry, with its
1757 * reference count incremented.
1761 * avc : Ptr to a vcache entry (unlocked)
1762 * abyte : Byte position in the file desired
1763 * areq : Request structure identifying the requesting user.
1764 * aflags : Settings as follows:
1766 * 2 : Return after creating entry.
1767 * 4 : called from afs_vnop_write.c
1768 * *alen contains length of data to be written.
1770 * aoffset : Set to the offset within the chunk where the resident
1772 * alen : Set to the number of bytes of data after the desired
1773 * byte (including the byte itself) which can be read
1777 * The vcache entry pointed to by avc is unlocked upon entry.
1781 struct AFSVolSync tsync;
1782 struct AFSFetchStatus OutStatus;
1783 struct AFSCallBack CallBack;
1787 * Update the vnode-to-dcache hint if we can get the vnode lock
1788 * right away. Assumes dcache entry is at least read-locked.
1791 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1793 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1794 if (hsame(v->m.DataVersion, d->f.versionNo) && v->callback)
1797 ReleaseWriteLock(&v->lock);
1801 /* avc - Write-locked unless aflags & 1 */
1803 afs_GetDCache(register struct vcache *avc, afs_size_t abyte,
1804 register struct vrequest *areq, afs_size_t * aoffset,
1805 afs_size_t * alen, int aflags)
1807 register afs_int32 i, code, code1 = 0, shortcut;
1808 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1809 register afs_int32 adjustsize = 0;
1815 afs_size_t maxGoodLength; /* amount of good data at server */
1816 struct rx_call *tcall;
1817 afs_size_t Position = 0;
1818 #ifdef AFS_64BIT_CLIENT
1820 afs_size_t lengthFound; /* as returned from server */
1821 #endif /* AFS_64BIT_CLIENT */
1822 afs_int32 size, tlen; /* size of segment to transfer */
1823 struct tlocal1 *tsmall = 0;
1824 register struct dcache *tdc;
1825 register struct osi_file *file;
1826 register struct conn *tc;
1828 struct server *newCallback = NULL;
1829 char setNewCallback;
1830 char setVcacheStatus;
1831 char doVcacheUpdate;
1833 int doAdjustSize = 0;
1834 int doReallyAdjustSize = 0;
1835 int overWriteWholeChunk = 0;
1839 struct afs_stats_xferData *xferP; /* Ptr to this op's xfer struct */
1840 osi_timeval_t xferStartTime, /*FS xfer start time */
1841 xferStopTime; /*FS xfer stop time */
1842 afs_size_t bytesToXfer; /* # bytes to xfer */
1843 afs_size_t bytesXferred; /* # bytes actually xferred */
1844 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1845 int fromReplica; /*Are we reading from a replica? */
1846 int numFetchLoops; /*# times around the fetch/analyze loop */
1847 #endif /* AFS_NOSTATS */
1849 AFS_STATCNT(afs_GetDCache);
1853 setLocks = aflags & 1;
1856 * Determine the chunk number and offset within the chunk corresponding
1857 * to the desired byte.
1859 if (avc->fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1862 chunk = AFS_CHUNK(abyte);
1865 /* come back to here if we waited for the cache to drain. */
1868 setNewCallback = setVcacheStatus = 0;
1872 ObtainWriteLock(&avc->lock, 616);
1874 ObtainReadLock(&avc->lock);
1879 * avc->lock(R) if setLocks && !slowPass
1880 * avc->lock(W) if !setLocks || slowPass
1885 /* check hints first! (might could use bcmp or some such...) */
1886 if ((tdc = avc->dchint)) {
1890 * The locking order between afs_xdcache and dcache lock matters.
1891 * The hint dcache entry could be anywhere, even on the free list.
1892 * Locking afs_xdcache ensures that noone is trying to pull dcache
1893 * entries from the free list, and thereby assuming them to be not
1894 * referenced and not locked.
1896 MObtainReadLock(&afs_xdcache);
1897 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1899 if (dcLocked && (tdc->index != NULLIDX)
1900 && !FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk
1901 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1902 /* got the right one. It might not be the right version, and it
1903 * might be fetching, but it's the right dcache entry.
1905 /* All this code should be integrated better with what follows:
1906 * I can save a good bit more time under a write lock if I do..
1908 ObtainWriteLock(&tdc->tlock, 603);
1910 ReleaseWriteLock(&tdc->tlock);
1912 MReleaseReadLock(&afs_xdcache);
1915 if (hsame(tdc->f.versionNo, avc->m.DataVersion)
1916 && !(tdc->dflags & DFFetching)) {
1918 afs_stats_cmperf.dcacheHits++;
1919 MObtainWriteLock(&afs_xdcache, 559);
1920 QRemove(&tdc->lruq);
1921 QAdd(&afs_DLRU, &tdc->lruq);
1922 MReleaseWriteLock(&afs_xdcache);
1925 * avc->lock(R) if setLocks && !slowPass
1926 * avc->lock(W) if !setLocks || slowPass
1933 ReleaseSharedLock(&tdc->lock);
1934 MReleaseReadLock(&afs_xdcache);
1942 * avc->lock(R) if setLocks && !slowPass
1943 * avc->lock(W) if !setLocks || slowPass
1944 * tdc->lock(S) if tdc
1947 if (!tdc) { /* If the hint wasn't the right dcache entry */
1949 * Hash on the [fid, chunk] and get the corresponding dcache index
1950 * after write-locking the dcache.
1955 * avc->lock(R) if setLocks && !slowPass
1956 * avc->lock(W) if !setLocks || slowPass
1959 i = DCHash(&avc->fid, chunk);
1960 /* check to make sure our space is fine */
1961 afs_MaybeWakeupTruncateDaemon();
1963 MObtainWriteLock(&afs_xdcache, 280);
1965 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1966 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1967 tdc = afs_GetDSlot(index, NULL);
1968 ReleaseReadLock(&tdc->tlock);
1971 * avc->lock(R) if setLocks && !slowPass
1972 * avc->lock(W) if !setLocks || slowPass
1975 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1976 /* Move it up in the beginning of the list */
1977 if (afs_dchashTbl[i] != index) {
1978 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1979 afs_dcnextTbl[index] = afs_dchashTbl[i];
1980 afs_dchashTbl[i] = index;
1982 MReleaseWriteLock(&afs_xdcache);
1983 ObtainSharedLock(&tdc->lock, 606);
1984 break; /* leaving refCount high for caller */
1990 index = afs_dcnextTbl[index];
1994 * If we didn't find the entry, we'll create one.
1996 if (index == NULLIDX) {
1999 * avc->lock(R) if setLocks
2000 * avc->lock(W) if !setLocks
2003 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
2004 avc, ICL_TYPE_INT32, chunk);
2006 /* Make sure there is a free dcache entry for us to use */
2007 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
2010 avc->states |= CDCLock;
2011 /* just need slots */
2012 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
2014 avc->states &= ~CDCLock;
2015 if (afs_discardDCList != NULLIDX
2016 || afs_freeDCList != NULLIDX)
2018 /* If we can't get space for 5 mins we give up and panic */
2019 if (++downDCount > 300) {
2020 #if defined(AFS_CACHE_BYPASS)
2021 afs_warn("GetDCache calling osi_Panic: No space in five minutes.\n downDCount: %d\n aoffset: %d alen: %d\n", downDCount, aoffset, alen);
2023 osi_Panic("getdcache");
2025 MReleaseWriteLock(&afs_xdcache);
2028 * avc->lock(R) if setLocks
2029 * avc->lock(W) if !setLocks
2031 afs_osi_Wait(1000, 0, 0);
2036 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
2039 * Now add to the two hash chains - note that i is still set
2040 * from the above DCHash call.
2042 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
2043 afs_dchashTbl[i] = tdc->index;
2044 i = DVHash(&avc->fid);
2045 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
2046 afs_dvhashTbl[i] = tdc->index;
2047 tdc->dflags = DFEntryMod;
2049 afs_MaybeWakeupTruncateDaemon();
2050 MReleaseWriteLock(&afs_xdcache);
2051 ConvertWToSLock(&tdc->lock);
2056 /* vcache->dcache hint failed */
2059 * avc->lock(R) if setLocks && !slowPass
2060 * avc->lock(W) if !setLocks || slowPass
2063 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
2064 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2065 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
2066 hgetlo(avc->m.DataVersion));
2068 * Here we have the entry in tdc, with its refCount incremented.
2069 * Note: we don't use the S-lock on avc; it costs concurrency when
2070 * storing a file back to the server.
2074 * Not a newly created file so we need to check the file's length and
2075 * compare data versions since someone could have changed the data or we're
2076 * reading a file written elsewhere. We only want to bypass doing no-op
2077 * read rpcs on newly created files (dv of 0) since only then we guarantee
2078 * that this chunk's data hasn't been filled by another client.
2080 size = AFS_CHUNKSIZE(abyte);
2081 if (aflags & 4) /* called from write */
2083 else /* called from read */
2084 tlen = tdc->validPos - abyte;
2085 Position = AFS_CHUNKTOBASE(chunk);
2086 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
2087 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
2088 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
2089 ICL_HANDLE_OFFSET(Position));
2090 if ((aflags & 4) && (hiszero(avc->m.DataVersion)))
2092 if ((AFS_CHUNKTOBASE(chunk) >= avc->m.Length) ||
2093 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
2094 overWriteWholeChunk = 1;
2095 if (doAdjustSize || overWriteWholeChunk) {
2096 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
2098 #ifdef AFS_SGI64_ENV
2101 #else /* AFS_SGI64_ENV */
2104 #endif /* AFS_SGI64_ENV */
2105 #else /* AFS_SGI_ENV */
2108 #endif /* AFS_SGI_ENV */
2109 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->m.Length &&
2110 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2111 #if defined(AFS_SUN5_ENV) || defined(AFS_OSF_ENV)
2112 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->m.Length)) &&
2114 if (AFS_CHUNKTOBASE(chunk) >= avc->m.Length &&
2116 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2117 !hsame(avc->m.DataVersion, tdc->f.versionNo))
2118 doReallyAdjustSize = 1;
2120 if (doReallyAdjustSize || overWriteWholeChunk) {
2121 /* no data in file to read at this position */
2122 UpgradeSToWLock(&tdc->lock, 607);
2124 file = afs_CFileOpen(tdc->f.inode);
2125 afs_CFileTruncate(file, 0);
2126 afs_CFileClose(file);
2127 afs_AdjustSize(tdc, 0);
2128 hset(tdc->f.versionNo, avc->m.DataVersion);
2129 tdc->dflags |= DFEntryMod;
2131 ConvertWToSLock(&tdc->lock);
2136 * We must read in the whole chunk if the version number doesn't
2140 /* don't need data, just a unique dcache entry */
2141 ObtainWriteLock(&afs_xdcache, 608);
2142 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2143 hadd32(afs_indexCounter, 1);
2144 ReleaseWriteLock(&afs_xdcache);
2146 updateV2DC(setLocks, avc, tdc, 553);
2147 if (vType(avc) == VDIR)
2150 *aoffset = AFS_CHUNKOFFSET(abyte);
2151 if (tdc->validPos < abyte)
2152 *alen = (afs_size_t) 0;
2154 *alen = tdc->validPos - abyte;
2155 ReleaseSharedLock(&tdc->lock);
2158 ReleaseWriteLock(&avc->lock);
2160 ReleaseReadLock(&avc->lock);
2162 return tdc; /* check if we're done */
2167 * avc->lock(R) if setLocks && !slowPass
2168 * avc->lock(W) if !setLocks || slowPass
2171 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
2173 setNewCallback = setVcacheStatus = 0;
2177 * avc->lock(R) if setLocks && !slowPass
2178 * avc->lock(W) if !setLocks || slowPass
2181 if (!hsame(avc->m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
2183 * Version number mismatch.
2186 * If we are disconnected, then we can't do much of anything
2187 * because the data doesn't match the file.
2189 if (AFS_IS_DISCONNECTED) {
2190 ReleaseSharedLock(&tdc->lock);
2193 ReleaseWriteLock(&avc->lock);
2195 ReleaseReadLock(&avc->lock);
2197 /* Flush the Dcache */
2202 UpgradeSToWLock(&tdc->lock, 609);
2205 * If data ever existed for this vnode, and this is a text object,
2206 * do some clearing. Now, you'd think you need only do the flush
2207 * when VTEXT is on, but VTEXT is turned off when the text object
2208 * is freed, while pages are left lying around in memory marked
2209 * with this vnode. If we would reactivate (create a new text
2210 * object from) this vnode, we could easily stumble upon some of
2211 * these old pages in pagein. So, we always flush these guys.
2212 * Sun has a wonderful lack of useful invariants in this system.
2214 * avc->flushDV is the data version # of the file at the last text
2215 * flush. Clearly, at least, we don't have to flush the file more
2216 * often than it changes
2218 if (hcmp(avc->flushDV, avc->m.DataVersion) < 0) {
2220 * By here, the cache entry is always write-locked. We can
2221 * deadlock if we call osi_Flush with the cache entry locked...
2222 * Unlock the dcache too.
2224 ReleaseWriteLock(&tdc->lock);
2225 if (setLocks && !slowPass)
2226 ReleaseReadLock(&avc->lock);
2228 ReleaseWriteLock(&avc->lock);
2232 * Call osi_FlushPages in open, read/write, and map, since it
2233 * is too hard here to figure out if we should lock the
2236 if (setLocks && !slowPass)
2237 ObtainReadLock(&avc->lock);
2239 ObtainWriteLock(&avc->lock, 66);
2240 ObtainWriteLock(&tdc->lock, 610);
2245 * avc->lock(R) if setLocks && !slowPass
2246 * avc->lock(W) if !setLocks || slowPass
2250 /* Watch for standard race condition around osi_FlushText */
2251 if (hsame(avc->m.DataVersion, tdc->f.versionNo)) {
2252 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2253 afs_stats_cmperf.dcacheHits++;
2254 ConvertWToSLock(&tdc->lock);
2258 /* Sleep here when cache needs to be drained. */
2259 if (setLocks && !slowPass
2260 && (afs_blocksUsed >
2261 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2262 /* Make sure truncate daemon is running */
2263 afs_MaybeWakeupTruncateDaemon();
2264 ObtainWriteLock(&tdc->tlock, 614);
2265 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2266 ReleaseWriteLock(&tdc->tlock);
2267 ReleaseWriteLock(&tdc->lock);
2268 ReleaseReadLock(&avc->lock);
2269 while ((afs_blocksUsed - afs_blocksDiscarded) >
2270 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2271 afs_WaitForCacheDrain = 1;
2272 afs_osi_Sleep(&afs_WaitForCacheDrain);
2274 afs_MaybeFreeDiscardedDCache();
2275 /* need to check if someone else got the chunk first. */
2276 goto RetryGetDCache;
2279 /* Do not fetch data beyond truncPos. */
2280 maxGoodLength = avc->m.Length;
2281 if (avc->truncPos < maxGoodLength)
2282 maxGoodLength = avc->truncPos;
2283 Position = AFS_CHUNKBASE(abyte);
2284 if (vType(avc) == VDIR) {
2285 size = avc->m.Length;
2286 if (size > tdc->f.chunkBytes) {
2287 /* pre-reserve space for file */
2288 afs_AdjustSize(tdc, size);
2290 size = 999999999; /* max size for transfer */
2292 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2293 /* don't read past end of good data on server */
2294 if (Position + size > maxGoodLength)
2295 size = maxGoodLength - Position;
2297 size = 0; /* Handle random races */
2298 if (size > tdc->f.chunkBytes) {
2299 /* pre-reserve space for file */
2300 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2301 /* max size for transfer still in size */
2304 if (afs_mariner && !tdc->f.chunk)
2305 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2307 * Right now, we only have one tool, and it's a hammer. So, we
2308 * fetch the whole file.
2310 DZap(tdc); /* pages in cache may be old */
2311 file = afs_CFileOpen(tdc->f.inode);
2312 afs_RemoveVCB(&avc->fid);
2313 tdc->f.states |= DWriting;
2314 tdc->dflags |= DFFetching;
2315 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2316 if (tdc->mflags & DFFetchReq) {
2317 tdc->mflags &= ~DFFetchReq;
2318 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2319 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2320 __FILE__, ICL_TYPE_INT32, __LINE__,
2321 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2325 (struct tlocal1 *)osi_AllocLargeSpace(sizeof(struct tlocal1));
2326 setVcacheStatus = 0;
2329 * Remember if we are doing the reading from a replicated volume,
2330 * and how many times we've zipped around the fetch/analyze loop.
2332 fromReplica = (avc->states & CRO) ? 1 : 0;
2334 accP = &(afs_stats_cmfullperf.accessinf);
2336 (accP->replicatedRefs)++;
2338 (accP->unreplicatedRefs)++;
2339 #endif /* AFS_NOSTATS */
2340 /* this is a cache miss */
2341 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2342 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
2343 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2346 afs_stats_cmperf.dcacheMisses++;
2349 * Dynamic root support: fetch data from local memory.
2351 if (afs_IsDynroot(avc)) {
2355 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2357 dynrootDir += Position;
2358 dynrootLen -= Position;
2359 if (size > dynrootLen)
2363 code = afs_CFileWrite(file, 0, dynrootDir, size);
2371 tdc->validPos = Position + size;
2372 afs_CFileTruncate(file, size); /* prune it */
2373 } else if (afs_IsDynrootMount(avc)) {
2377 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2379 dynrootDir += Position;
2380 dynrootLen -= Position;
2381 if (size > dynrootLen)
2385 code = afs_CFileWrite(file, 0, dynrootDir, size);
2393 tdc->validPos = Position + size;
2394 afs_CFileTruncate(file, size); /* prune it */
2397 * Not a dynamic vnode: do the real fetch.
2402 * avc->lock(R) if setLocks && !slowPass
2403 * avc->lock(W) if !setLocks || slowPass
2407 tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
2409 afs_int32 length_hi, length, bytes;
2413 (accP->numReplicasAccessed)++;
2415 #endif /* AFS_NOSTATS */
2416 if (!setLocks || slowPass) {
2417 avc->callback = tc->srvr->server;
2419 newCallback = tc->srvr->server;
2424 tcall = rx_NewCall(tc->id);
2427 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
2428 #ifdef AFS_64BIT_CLIENT
2429 length_hi = code = 0;
2430 if (!afs_serverHasNo64Bit(tc)) {
2434 StartRXAFS_FetchData64(tcall,
2435 (struct AFSFid *)&avc->fid.
2436 Fid, Position, tsize);
2439 afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2440 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32,
2444 rx_Read(tcall, (char *)&length_hi,
2447 if (bytes == sizeof(afs_int32)) {
2448 length_hi = ntohl(length_hi);
2451 code = rx_Error(tcall);
2453 code1 = rx_EndCall(tcall, code);
2455 tcall = (struct rx_call *)0;
2459 if (code == RXGEN_OPCODE || afs_serverHasNo64Bit(tc)) {
2460 if (Position > 0x7FFFFFFF) {
2467 tcall = rx_NewCall(tc->id);
2469 StartRXAFS_FetchData(tcall, (struct AFSFid *)
2474 afs_serverSetNo64Bit(tc);
2479 rx_Read(tcall, (char *)&length,
2482 if (bytes == sizeof(afs_int32)) {
2483 length = ntohl(length);
2485 code = rx_Error(tcall);
2488 FillInt64(lengthFound, length_hi, length);
2489 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64LENG,
2490 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
2492 ICL_HANDLE_OFFSET(lengthFound));
2493 #else /* AFS_64BIT_CLIENT */
2496 StartRXAFS_FetchData(tcall,
2497 (struct AFSFid *)&avc->fid.Fid,
2503 rx_Read(tcall, (char *)&length,
2506 if (bytes == sizeof(afs_int32)) {
2507 length = ntohl(length);
2509 code = rx_Error(tcall);
2512 #endif /* AFS_64BIT_CLIENT */
2517 &(afs_stats_cmfullperf.rpc.
2518 fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
2519 osi_GetuTime(&xferStartTime);
2522 afs_CacheFetchProc(tcall, file,
2523 (afs_size_t) Position, tdc,
2525 &bytesXferred, length);
2527 osi_GetuTime(&xferStopTime);
2528 (xferP->numXfers)++;
2530 (xferP->numSuccesses)++;
2531 afs_stats_XferSumBytes
2532 [AFS_STATS_FS_XFERIDX_FETCHDATA] +=
2534 (xferP->sumBytes) +=
2535 (afs_stats_XferSumBytes
2536 [AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
2537 afs_stats_XferSumBytes
2538 [AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
2539 if (bytesXferred < xferP->minBytes)
2540 xferP->minBytes = bytesXferred;
2541 if (bytesXferred > xferP->maxBytes)
2542 xferP->maxBytes = bytesXferred;
2545 * Tally the size of the object. Note: we tally the actual size,
2546 * NOT the number of bytes that made it out over the wire.
2548 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
2549 (xferP->count[0])++;
2550 else if (bytesToXfer <=
2551 AFS_STATS_MAXBYTES_BUCKET1)
2552 (xferP->count[1])++;
2553 else if (bytesToXfer <=
2554 AFS_STATS_MAXBYTES_BUCKET2)
2555 (xferP->count[2])++;
2556 else if (bytesToXfer <=
2557 AFS_STATS_MAXBYTES_BUCKET3)
2558 (xferP->count[3])++;
2559 else if (bytesToXfer <=
2560 AFS_STATS_MAXBYTES_BUCKET4)
2561 (xferP->count[4])++;
2562 else if (bytesToXfer <=
2563 AFS_STATS_MAXBYTES_BUCKET5)
2564 (xferP->count[5])++;
2565 else if (bytesToXfer <=
2566 AFS_STATS_MAXBYTES_BUCKET6)
2567 (xferP->count[6])++;
2568 else if (bytesToXfer <=
2569 AFS_STATS_MAXBYTES_BUCKET7)
2570 (xferP->count[7])++;
2572 (xferP->count[8])++;
2574 afs_stats_GetDiff(elapsedTime, xferStartTime,
2576 afs_stats_AddTo((xferP->sumTime), elapsedTime);
2577 afs_stats_SquareAddTo((xferP->sqrTime),
2579 if (afs_stats_TimeLessThan
2580 (elapsedTime, (xferP->minTime))) {
2581 afs_stats_TimeAssign((xferP->minTime),
2584 if (afs_stats_TimeGreaterThan
2585 (elapsedTime, (xferP->maxTime))) {
2586 afs_stats_TimeAssign((xferP->maxTime),
2592 afs_CacheFetchProc(tcall, file, Position, tdc,
2594 #endif /* AFS_NOSTATS */
2599 EndRXAFS_FetchData(tcall, &tsmall->OutStatus,
2607 code1 = rx_EndCall(tcall, code);
2616 /* callback could have been broken (or expired) in a race here,
2617 * but we return the data anyway. It's as good as we knew about
2618 * when we started. */
2620 * validPos is updated by CacheFetchProc, and can only be
2621 * modifed under a dcache write lock, which we've blocked out
2623 size = tdc->validPos - Position; /* actual segment size */
2626 afs_CFileTruncate(file, size); /* prune it */
2628 if (!setLocks || slowPass) {
2629 ObtainWriteLock(&afs_xcbhash, 453);
2630 afs_DequeueCallback(avc);
2631 avc->states &= ~(CStatd | CUnique);
2632 avc->callback = NULL;
2633 ReleaseWriteLock(&afs_xcbhash);
2634 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2635 osi_dnlc_purgedp(avc);
2637 /* Something lost. Forget about performance, and go
2638 * back with a vcache write lock.
2640 afs_CFileTruncate(file, 0);
2641 afs_AdjustSize(tdc, 0);
2642 afs_CFileClose(file);
2643 osi_FreeLargeSpace(tsmall);
2645 ReleaseWriteLock(&tdc->lock);
2648 ReleaseReadLock(&avc->lock);
2650 goto RetryGetDCache;
2654 } while (afs_Analyze
2655 (tc, code, &avc->fid, areq,
2656 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2660 * avc->lock(R) if setLocks && !slowPass
2661 * avc->lock(W) if !setLocks || slowPass
2667 * In the case of replicated access, jot down info on the number of
2668 * attempts it took before we got through or gave up.
2671 if (numFetchLoops <= 1)
2672 (accP->refFirstReplicaOK)++;
2673 if (numFetchLoops > accP->maxReplicasPerRef)
2674 accP->maxReplicasPerRef = numFetchLoops;
2676 #endif /* AFS_NOSTATS */
2678 tdc->dflags &= ~DFFetching;
2679 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2680 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2681 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2682 tdc, ICL_TYPE_INT32, tdc->dflags);
2683 if (avc->execsOrWriters == 0)
2684 tdc->f.states &= ~DWriting;
2686 /* now, if code != 0, we have an error and should punt.
2687 * note that we have the vcache write lock, either because
2688 * !setLocks or slowPass.
2691 afs_CFileTruncate(file, 0);
2692 afs_AdjustSize(tdc, 0);
2693 afs_CFileClose(file);
2694 ZapDCE(tdc); /* sets DFEntryMod */
2695 if (vType(avc) == VDIR) {
2698 tdc->f.states &= ~(DRO|DBackup|DRW);
2699 afs_DCMoveBucket(tdc, 0, 0);
2700 ReleaseWriteLock(&tdc->lock);
2702 if (!afs_IsDynroot(avc)) {
2703 ObtainWriteLock(&afs_xcbhash, 454);
2704 afs_DequeueCallback(avc);
2705 avc->states &= ~(CStatd | CUnique);
2706 ReleaseWriteLock(&afs_xcbhash);
2707 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2708 osi_dnlc_purgedp(avc);
2711 * avc->lock(W); assert(!setLocks || slowPass)
2713 osi_Assert(!setLocks || slowPass);
2715 tdc->f.states &= ~(DRO|DBackup|DRW);
2716 afs_DCMoveBucket(tdc, 0, 0);
2721 /* otherwise we copy in the just-fetched info */
2722 afs_CFileClose(file);
2723 afs_AdjustSize(tdc, size); /* new size */
2725 * Copy appropriate fields into vcache. Status is
2726 * copied later where we selectively acquire the
2727 * vcache write lock.
2730 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2732 setVcacheStatus = 1;
2733 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2734 tsmall->OutStatus.DataVersion);
2735 tdc->dflags |= DFEntryMod;
2736 afs_indexFlags[tdc->index] |= IFEverUsed;
2737 ConvertWToSLock(&tdc->lock);
2738 } /*Data version numbers don't match */
2741 * Data version numbers match.
2743 afs_stats_cmperf.dcacheHits++;
2744 } /*Data version numbers match */
2746 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2750 * avc->lock(R) if setLocks && !slowPass
2751 * avc->lock(W) if !setLocks || slowPass
2752 * tdc->lock(S) if tdc
2756 * See if this was a reference to a file in the local cell.
2758 if (afs_IsPrimaryCellNum(avc->fid.Cell))
2759 afs_stats_cmperf.dlocalAccesses++;
2761 afs_stats_cmperf.dremoteAccesses++;
2763 /* Fix up LRU info */
2766 MObtainWriteLock(&afs_xdcache, 602);
2767 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2768 hadd32(afs_indexCounter, 1);
2769 MReleaseWriteLock(&afs_xdcache);
2771 /* return the data */
2772 if (vType(avc) == VDIR)
2775 *aoffset = AFS_CHUNKOFFSET(abyte);
2776 *alen = (tdc->f.chunkBytes - *aoffset);
2777 ReleaseSharedLock(&tdc->lock);
2782 * avc->lock(R) if setLocks && !slowPass
2783 * avc->lock(W) if !setLocks || slowPass
2786 /* Fix up the callback and status values in the vcache */
2788 if (setLocks && !slowPass) {
2791 * This is our dirty little secret to parallel fetches.
2792 * We don't write-lock the vcache while doing the fetch,
2793 * but potentially we'll need to update the vcache after
2794 * the fetch is done.
2796 * Drop the read lock and try to re-obtain the write
2797 * lock. If the vcache still has the same DV, it's
2798 * ok to go ahead and install the new data.
2800 afs_hyper_t currentDV, statusDV;
2802 hset(currentDV, avc->m.DataVersion);
2804 if (setNewCallback && avc->callback != newCallback)
2808 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2809 tsmall->OutStatus.DataVersion);
2811 if (setVcacheStatus && avc->m.Length != tsmall->OutStatus.Length)
2813 if (setVcacheStatus && !hsame(currentDV, statusDV))
2817 ReleaseReadLock(&avc->lock);
2819 if (doVcacheUpdate) {
2820 ObtainWriteLock(&avc->lock, 615);
2821 if (!hsame(avc->m.DataVersion, currentDV)) {
2822 /* We lose. Someone will beat us to it. */
2824 ReleaseWriteLock(&avc->lock);
2829 /* With slow pass, we've already done all the updates */
2831 ReleaseWriteLock(&avc->lock);
2834 /* Check if we need to perform any last-minute fixes with a write-lock */
2835 if (!setLocks || doVcacheUpdate) {
2837 avc->callback = newCallback;
2838 if (tsmall && setVcacheStatus)
2839 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2841 ReleaseWriteLock(&avc->lock);
2845 osi_FreeLargeSpace(tsmall);
2848 } /*afs_GetDCache */
2852 * afs_WriteThroughDSlots
2855 * Sweep through the dcache slots and write out any modified
2856 * in-memory data back on to our caching store.
2862 * The afs_xdcache is write-locked through this whole affair.
2865 afs_WriteThroughDSlots(void)
2867 register struct dcache *tdc;
2868 register afs_int32 i, touchedit = 0;
2870 struct afs_q DirtyQ, *tq;
2872 AFS_STATCNT(afs_WriteThroughDSlots);
2875 * Because of lock ordering, we can't grab dcache locks while
2876 * holding afs_xdcache. So we enter xdcache, get a reference
2877 * for every dcache entry, and exit xdcache.
2879 MObtainWriteLock(&afs_xdcache, 283);
2881 for (i = 0; i < afs_cacheFiles; i++) {
2882 tdc = afs_indexTable[i];
2884 /* Grab tlock in case the existing refcount isn't zero */
2885 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2886 ObtainWriteLock(&tdc->tlock, 623);
2888 ReleaseWriteLock(&tdc->tlock);
2890 QAdd(&DirtyQ, &tdc->dirty);
2893 MReleaseWriteLock(&afs_xdcache);
2896 * Now, for each dcache entry we found, check if it's dirty.
2897 * If so, get write-lock, get afs_xdcache, which protects
2898 * afs_cacheInodep, and flush it. Don't forget to put back
2902 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2904 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2906 if (tdc->dflags & DFEntryMod) {
2909 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2911 /* Now that we have the write lock, double-check */
2912 if (wrLock && (tdc->dflags & DFEntryMod)) {
2913 tdc->dflags &= ~DFEntryMod;
2914 MObtainWriteLock(&afs_xdcache, 620);
2915 afs_WriteDCache(tdc, 1);
2916 MReleaseWriteLock(&afs_xdcache);
2920 ReleaseWriteLock(&tdc->lock);
2926 MObtainWriteLock(&afs_xdcache, 617);
2927 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2928 /* Touch the file to make sure that the mtime on the file is kept
2929 * up-to-date to avoid losing cached files on cold starts because
2930 * their mtime seems old...
2932 struct afs_fheader theader;
2934 theader.magic = AFS_FHMAGIC;
2935 theader.firstCSize = AFS_FIRSTCSIZE;
2936 theader.otherCSize = AFS_OTHERCSIZE;
2937 theader.version = AFS_CI_VERSION;
2938 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2940 MReleaseWriteLock(&afs_xdcache);
2947 * Return a pointer to an freshly initialized dcache entry using
2948 * a memory-based cache. The tlock will be read-locked.
2951 * aslot : Dcache slot to look at.
2952 * tmpdc : Ptr to dcache entry.
2955 * Must be called with afs_xdcache write-locked.
2959 afs_MemGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2961 register struct dcache *tdc;
2964 AFS_STATCNT(afs_MemGetDSlot);
2965 if (CheckLock(&afs_xdcache) != -1)
2966 osi_Panic("getdslot nolock");
2967 if (aslot < 0 || aslot >= afs_cacheFiles)
2968 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2969 tdc = afs_indexTable[aslot];
2971 QRemove(&tdc->lruq); /* move to queue head */
2972 QAdd(&afs_DLRU, &tdc->lruq);
2973 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2974 ObtainWriteLock(&tdc->tlock, 624);
2976 ConvertWToRLock(&tdc->tlock);
2979 if (tmpdc == NULL) {
2980 if (!afs_freeDSList)
2981 afs_GetDownDSlot(4);
2982 if (!afs_freeDSList) {
2983 /* none free, making one is better than a panic */
2984 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2985 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2986 #ifdef KERNEL_HAVE_PIN
2987 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2990 tdc = afs_freeDSList;
2991 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2994 tdc->dflags = 0; /* up-to-date, not in free q */
2996 QAdd(&afs_DLRU, &tdc->lruq);
2997 if (tdc->lruq.prev == &tdc->lruq)
2998 osi_Panic("lruq 3");
3004 /* initialize entry */
3005 tdc->f.fid.Cell = 0;
3006 tdc->f.fid.Fid.Volume = 0;
3008 hones(tdc->f.versionNo);
3009 tdc->f.inode = aslot;
3010 tdc->dflags |= DFEntryMod;
3013 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3016 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3017 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3018 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3021 RWLOCK_INIT(&tdc->lock, "dcache lock");
3022 RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3023 RWLOCK_INIT(&tdc->mflock, "dcache flock");
3024 ObtainReadLock(&tdc->tlock);
3027 afs_indexTable[aslot] = tdc;
3030 } /*afs_MemGetDSlot */
3032 unsigned int last_error = 0, lasterrtime = 0;
3038 * Return a pointer to an freshly initialized dcache entry using
3039 * a UFS-based disk cache. The dcache tlock will be read-locked.
3042 * aslot : Dcache slot to look at.
3043 * tmpdc : Ptr to dcache entry.
3046 * afs_xdcache lock write-locked.
3049 afs_UFSGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
3051 register afs_int32 code;
3052 register struct dcache *tdc;
3056 AFS_STATCNT(afs_UFSGetDSlot);
3057 if (CheckLock(&afs_xdcache) != -1)
3058 osi_Panic("getdslot nolock");
3059 if (aslot < 0 || aslot >= afs_cacheFiles)
3060 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3061 tdc = afs_indexTable[aslot];
3063 QRemove(&tdc->lruq); /* move to queue head */
3064 QAdd(&afs_DLRU, &tdc->lruq);
3065 /* Grab tlock in case refCount != 0 */
3066 ObtainWriteLock(&tdc->tlock, 625);
3068 ConvertWToRLock(&tdc->tlock);
3071 /* otherwise we should read it in from the cache file */
3073 * If we weren't passed an in-memory region to place the file info,
3074 * we have to allocate one.
3076 if (tmpdc == NULL) {
3077 if (!afs_freeDSList)
3078 afs_GetDownDSlot(4);
3079 if (!afs_freeDSList) {
3080 /* none free, making one is better than a panic */
3081 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
3082 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
3083 #ifdef KERNEL_HAVE_PIN
3084 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
3087 tdc = afs_freeDSList;
3088 afs_freeDSList = (struct dcache *)tdc->lruq.next;
3091 tdc->dflags = 0; /* up-to-date, not in free q */
3093 QAdd(&afs_DLRU, &tdc->lruq);
3094 if (tdc->lruq.prev == &tdc->lruq)
3095 osi_Panic("lruq 3");
3102 * Seek to the aslot'th entry and read it in.
3105 afs_osi_Read(afs_cacheInodep,
3106 sizeof(struct fcache) * aslot +
3107 sizeof(struct afs_fheader), (char *)(&tdc->f),
3108 sizeof(struct fcache));
3110 if (code != sizeof(struct fcache))
3112 if (!afs_CellNumValid(tdc->f.fid.Cell))
3116 tdc->f.fid.Cell = 0;
3117 tdc->f.fid.Fid.Volume = 0;
3119 hones(tdc->f.versionNo);
3120 tdc->dflags |= DFEntryMod;
3121 #if defined(KERNEL_HAVE_UERROR)
3122 last_error = getuerror();
3124 lasterrtime = osi_Time();
3125 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3126 tdc->f.states &= ~(DRO|DBackup|DRW);
3127 afs_DCMoveBucket(tdc, 0, 0);
3130 if (tdc->f.states & DRO) {
3131 afs_DCMoveBucket(tdc, 0, 2);
3132 } else if (tdc->f.states & DBackup) {
3133 afs_DCMoveBucket(tdc, 0, 1);
3135 afs_DCMoveBucket(tdc, 0, 1);
3141 if (tdc->f.chunk >= 0)
3142 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
3147 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3148 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3149 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3152 RWLOCK_INIT(&tdc->lock, "dcache lock");
3153 RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3154 RWLOCK_INIT(&tdc->mflock, "dcache flock");
3155 ObtainReadLock(&tdc->tlock);
3158 * If we didn't read into a temporary dcache region, update the
3159 * slot pointer table.
3162 afs_indexTable[aslot] = tdc;
3165 } /*afs_UFSGetDSlot */
3173 * write a particular dcache entry back to its home in the
3177 * adc : Pointer to the dcache entry to write.
3178 * atime : If true, set the modtime on the file to the current time.
3181 * Must be called with the afs_xdcache lock at least read-locked,
3182 * and dcache entry at least read-locked.
3183 * The reference count is not changed.
3187 afs_WriteDCache(register struct dcache *adc, int atime)
3189 register afs_int32 code;
3191 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3193 AFS_STATCNT(afs_WriteDCache);
3194 osi_Assert(WriteLocked(&afs_xdcache));
3196 adc->f.modTime = osi_Time();
3198 * Seek to the right dcache slot and write the in-memory image out to disk.
3200 afs_cellname_write();
3202 afs_osi_Write(afs_cacheInodep,
3203 sizeof(struct fcache) * adc->index +
3204 sizeof(struct afs_fheader), (char *)(&adc->f),
3205 sizeof(struct fcache));
3206 if (code != sizeof(struct fcache))
3217 * Wake up users of a particular file waiting for stores to take
3221 * avc : Ptr to related vcache entry.
3224 * Nothing interesting.
3228 afs_wakeup(register struct vcache *avc)
3231 register struct brequest *tb;
3233 AFS_STATCNT(afs_wakeup);
3234 for (i = 0; i < NBRS; i++, tb++) {
3235 /* if request is valid and for this file, we've found it */
3236 if (tb->refCount > 0 && avc == tb->vc) {
3239 * If CSafeStore is on, then we don't awaken the guy
3240 * waiting for the store until the whole store has finished.
3241 * Otherwise, we do it now. Note that if CSafeStore is on,
3242 * the BStore routine actually wakes up the user, instead
3244 * I think this is redundant now because this sort of thing
3245 * is already being handled by the higher-level code.
3247 if ((avc->states & CSafeStore) == 0) {
3249 tb->flags |= BUVALID;
3250 if (tb->flags & BUWAIT) {
3251 tb->flags &= ~BUWAIT;
3266 * Given a file name and inode, set up that file to be an
3267 * active member in the AFS cache. This also involves checking
3268 * the usability of its data.
3271 * afile : Name of the cache file to initialize.
3272 * ainode : Inode of the file.
3275 * This function is called only during initialization.
3279 afs_InitCacheFile(char *afile, ino_t ainode)
3281 register afs_int32 code;
3282 #if defined(AFS_LINUX22_ENV)
3283 struct dentry *filevp;
3285 struct vnode *filevp;
3289 struct osi_file *tfile;
3290 struct osi_stat tstat;
3291 register struct dcache *tdc;
3293 AFS_STATCNT(afs_InitCacheFile);
3294 index = afs_stats_cmperf.cacheNumEntries;
3295 if (index >= afs_cacheFiles)
3298 MObtainWriteLock(&afs_xdcache, 282);
3299 tdc = afs_GetDSlot(index, NULL);
3300 ReleaseReadLock(&tdc->tlock);
3301 MReleaseWriteLock(&afs_xdcache);
3303 ObtainWriteLock(&tdc->lock, 621);
3304 MObtainWriteLock(&afs_xdcache, 622);
3306 code = gop_lookupname(afile, AFS_UIOSYS, 0, &filevp);
3308 ReleaseWriteLock(&afs_xdcache);
3309 ReleaseWriteLock(&tdc->lock);
3314 * We have a VN_HOLD on filevp. Get the useful info out and
3315 * return. We make use of the fact that the cache is in the
3316 * UFS file system, and just record the inode number.
3318 #ifdef AFS_LINUX22_ENV
3319 tdc->f.inode = VTOI(filevp->d_inode)->i_number;
3322 tdc->f.inode = afs_vnodeToInumber(filevp);
3324 #endif /* AFS_LINUX22_ENV */
3326 tdc->f.inode = ainode;
3329 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3331 tfile = osi_UFSOpen(tdc->f.inode);
3332 code = afs_osi_Stat(tfile, &tstat);
3334 osi_Panic("initcachefile stat");
3337 * If file size doesn't match the cache info file, it's probably bad.
3339 if (tdc->f.chunkBytes != tstat.size)
3341 tdc->f.chunkBytes = 0;
3344 * If file changed within T (120?) seconds of cache info file, it's
3345 * probably bad. In addition, if slot changed within last T seconds,
3346 * the cache info file may be incorrectly identified, and so slot
3349 if (cacheInfoModTime < tstat.mtime + 120)
3351 if (cacheInfoModTime < tdc->f.modTime + 120)
3353 /* In case write through is behind, make sure cache items entry is
3354 * at least as new as the chunk.
3356 if (tdc->f.modTime < tstat.mtime)
3359 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3360 if (tstat.size != 0)
3361 osi_UFSTruncate(tfile, 0);
3362 tdc->f.states &= ~(DRO|DBackup|DRW);
3363 afs_DCMoveBucket(tdc, 0, 0);
3364 /* put entry in free cache slot list */
3365 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3366 afs_freeDCList = index;
3368 afs_indexFlags[index] |= IFFree;
3369 afs_indexUnique[index] = 0;
3372 * We must put this entry in the appropriate hash tables.
3373 * Note that i is still set from the above DCHash call
3375 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3376 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3377 afs_dchashTbl[code] = tdc->index;
3378 code = DVHash(&tdc->f.fid);
3379 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3380 afs_dvhashTbl[code] = tdc->index;
3381 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3383 /* has nontrivial amt of data */
3384 afs_indexFlags[index] |= IFEverUsed;
3385 afs_stats_cmperf.cacheFilesReused++;
3387 * Initialize index times to file's mod times; init indexCounter
3390 hset32(afs_indexTimes[index], tstat.atime);
3391 if (hgetlo(afs_indexCounter) < tstat.atime) {
3392 hset32(afs_indexCounter, tstat.atime);
3394 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3395 } /*File is not bad */
3397 osi_UFSClose(tfile);
3398 tdc->f.states &= ~DWriting;
3399 tdc->dflags &= ~DFEntryMod;
3400 /* don't set f.modTime; we're just cleaning up */
3401 afs_WriteDCache(tdc, 0);
3402 ReleaseWriteLock(&afs_xdcache);
3403 ReleaseWriteLock(&tdc->lock);
3405 afs_stats_cmperf.cacheNumEntries++;
3410 /*Max # of struct dcache's resident at any time*/
3412 * If 'dchint' is enabled then in-memory dcache min is increased because of
3421 * Initialize dcache related variables.
3424 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3426 register struct dcache *tdp;
3430 afs_freeDCList = NULLIDX;
3431 afs_discardDCList = NULLIDX;
3432 afs_freeDCCount = 0;
3433 afs_freeDSList = NULL;
3434 hzero(afs_indexCounter);
3436 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3442 if (achunk < 0 || achunk > 30)
3443 achunk = 13; /* Use default */
3444 AFS_SETCHUNKSIZE(achunk);
3450 if (aflags & AFSCALL_INIT_MEMCACHE) {
3452 * Use a memory cache instead of a disk cache
3454 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3455 afs_cacheType = &afs_MemCacheOps;
3456 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3457 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3458 /* ablocks is reported in 1K blocks */
3459 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3461 printf("afsd: memory cache too large for available memory.\n");
3462 printf("afsd: AFS files cannot be accessed.\n\n");
3464 afiles = ablocks = 0;
3466 printf("Memory cache: Allocating %d dcache entries...",
3469 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3470 afs_cacheType = &afs_UfsCacheOps;
3473 if (aDentries > 512)
3474 afs_dhashsize = 2048;
3475 /* initialize hash tables */
3477 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3479 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3480 for (i = 0; i < afs_dhashsize; i++) {
3481 afs_dvhashTbl[i] = NULLIDX;
3482 afs_dchashTbl[i] = NULLIDX;
3484 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3485 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3486 for (i = 0; i < afiles; i++) {
3487 afs_dvnextTbl[i] = NULLIDX;
3488 afs_dcnextTbl[i] = NULLIDX;
3491 /* Allocate and zero the pointer array to the dcache entries */
3492 afs_indexTable = (struct dcache **)
3493 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3494 memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3496 (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3497 memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3499 (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3500 memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3501 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3502 memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
3504 /* Allocate and thread the struct dcache entries themselves */
3505 tdp = afs_Initial_freeDSList =
3506 (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3507 memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
3508 #ifdef KERNEL_HAVE_PIN
3509 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3510 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3511 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3512 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3513 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3514 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3515 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3516 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3517 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3520 afs_freeDSList = &tdp[0];
3521 for (i = 0; i < aDentries - 1; i++) {
3522 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3523 RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3524 RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3525 RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3527 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3528 RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3529 RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3530 RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3532 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3533 afs_cacheBlocks = ablocks;
3534 afs_ComputeCacheParms(); /* compute parms based on cache size */
3536 afs_dcentries = aDentries;
3538 afs_stats_cmperf.cacheBucket0_Discarded =
3539 afs_stats_cmperf.cacheBucket1_Discarded =
3540 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3550 shutdown_dcache(void)
3554 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3555 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3556 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3557 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3558 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3559 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3560 afs_osi_Free(afs_Initial_freeDSList,
3561 afs_dcentries * sizeof(struct dcache));
3562 #ifdef KERNEL_HAVE_PIN
3563 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3564 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3565 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3566 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3567 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3568 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3569 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3573 for (i = 0; i < afs_dhashsize; i++) {
3574 afs_dvhashTbl[i] = NULLIDX;
3575 afs_dchashTbl[i] = NULLIDX;
3578 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3579 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3581 afs_blocksUsed = afs_dcentries = 0;
3582 afs_stats_cmperf.cacheBucket0_Discarded =
3583 afs_stats_cmperf.cacheBucket1_Discarded =
3584 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3585 hzero(afs_indexCounter);
3587 afs_freeDCCount = 0;
3588 afs_freeDCList = NULLIDX;
3589 afs_discardDCList = NULLIDX;
3590 afs_freeDSList = afs_Initial_freeDSList = 0;
3592 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3597 #if defined(AFS_DISCON_ENV)
3600 * Make a shadow copy of a dir's dcaches. It's used for disconnected
3601 * operations like remove/create/rename to keep the original directory data.
3602 * On reconnection, we can diff the original data with the server and get the
3603 * server changes and with the local data to get the local changes.
3605 * \param avc The dir vnode.
3607 * \return 0 for success.
3609 * \note The only lock allowed to be set is the dir's vcache entry, and it
3610 * must be set in write mode.
3611 * \note The vcache entry must be write locked.
3613 int afs_MakeShadowDir(struct vcache *avc)
3615 int j, i, index, code, ret_code = 0, offset, trans_size, block;
3616 struct dcache *tdc, *new_dc = NULL;
3617 struct osi_file *tfile_src, *tfile_dst;
3618 struct VenusFid shadow_fid;
3622 /* Is this a dir? */
3623 if (vType(avc) != VDIR)
3626 /* Generate a fid for the shadow dir. */
3627 shadow_fid.Cell = avc->fid.Cell;
3628 shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3629 afs_GenShadowFid(&shadow_fid);
3631 /* For each dcache, do copy it into a new fresh one. */
3632 i = DVHash(&avc->fid);
3633 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
3634 /* Making sure that this isn't going to get locked twice. */
3636 /* XXX: Moved it from outside of the loop.
3637 * Maybe it's not quite okay because of the use of
3638 * dvhashTbl (once) in the for statement.
3640 ObtainWriteLock(&afs_xdcache, 716);
3644 i = afs_dvnextTbl[index];
3645 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
3646 tdc = afs_GetDSlot(index, NULL);
3648 ReleaseReadLock(&tdc->tlock);
3650 if (!FidCmp(&tdc->f.fid, &avc->fid)) {
3652 /* Got a dir's dcache. */
3655 /* Get a fresh dcache. */
3656 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3658 /* Unlock hash for now. Don't need it during operations on the
3659 * dcache. Oh, and we can't use it because of the locking
3662 /* XXX: So much for lock ierarchy, the afs_AllocDCache doesn't
3665 //ReleaseWriteLock(&afs_xdcache);
3667 ObtainReadLock(&tdc->lock);
3669 /* Set up the new fid. */
3670 /* Copy interesting data from original dir dcache. */
3671 new_dc->mflags = tdc->mflags;
3672 new_dc->dflags = tdc->dflags;
3673 new_dc->f.modTime = tdc->f.modTime;
3674 new_dc->f.versionNo = tdc->f.versionNo;
3675 new_dc->f.states = tdc->f.states;
3676 new_dc->f.chunk= tdc->f.chunk;
3677 new_dc->f.chunkBytes = tdc->f.chunkBytes;
3680 * Now add to the two hash chains - note that i is still set
3681 * from the above DCHash call.
3683 //ObtainWriteLock(&afs_xdcache, 713);
3685 j = DCHash(&shadow_fid, 0);
3686 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[j];
3687 afs_dchashTbl[j] = new_dc->index;
3689 j = DVHash(&shadow_fid);
3690 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[j];
3691 afs_dvhashTbl[j] = new_dc->index;
3692 afs_MaybeWakeupTruncateDaemon();
3694 ReleaseWriteLock(&afs_xdcache);
3696 /* Alloc a 4k block. */
3697 data = (char *) afs_osi_Alloc(4096);
3699 printf("afs_MakeShadowDir: could not alloc data\n");
3704 /* Open the files. */
3705 tfile_src = afs_CFileOpen(tdc->f.inode);
3706 tfile_dst = afs_CFileOpen(new_dc->f.inode);
3708 /* Init no of blocks to be read and offset. */
3709 block = (tdc->f.chunkBytes / 4096);
3712 /* And now copy dir dcache data into this dcache,
3715 while (block >= 0) {
3717 /* Last chunk might have less bytes to transfer. */
3720 trans_size = (tdc->f.chunkBytes % 4096);
3722 /* An exact no of 4k blocks. */
3727 /* Read a chunk from the dcache. */
3728 code = afs_CFileRead(tfile_src, offset, data, trans_size);
3729 if (code < trans_size) {
3730 /* Can't access file, stop doing stuff and return error. */
3735 /* Write it to the new dcache. */
3736 code = afs_CFileWrite(tfile_dst, offset, data, trans_size);
3737 if (code < trans_size) {
3744 } /* while (block) */
3746 afs_CFileClose(tfile_dst);
3747 afs_CFileClose(tfile_src);
3749 afs_osi_Free(data, 4096);
3751 ReleaseWriteLock(&new_dc->lock);
3752 ReleaseReadLock(&tdc->lock);
3754 afs_PutDCache(new_dc);
3755 } /* if dcache fid match */
3757 } /* if unuiquifier match */
3761 ReleaseWriteLock(&afs_xdcache);
3764 if (!avc->ddirty_flags) {
3765 ObtainWriteLock(&afs_DDirtyVCListLock, 763);
3766 AFS_DISCON_ADD_DIRTY(avc);
3767 ReleaseWriteLock(&afs_DDirtyVCListLock);
3769 avc->shVnode = shadow_fid.Fid.Vnode;
3770 avc->shUnique = shadow_fid.Fid.Unique;
3771 avc->ddirty_flags |= VDisconShadowed;
3778 * Delete the dcaches of a shadow dir.
3780 * \param avc The vcache containing the shadow fid.
3782 * \note avc must be write locked.
3784 void afs_DeleteShadowDir(struct vcache *avc)
3787 struct VenusFid shadow_fid;
3789 shadow_fid.Cell = avc->fid.Cell;
3790 shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3791 shadow_fid.Fid.Vnode = avc->shVnode;
3792 shadow_fid.Fid.Unique = avc->shUnique;
3794 tdc = afs_FindDCacheByFid(&shadow_fid);
3796 afs_HashOutDCache(tdc, 1);
3797 afs_DiscardDCache(tdc);
3800 /* Remove shadowed dir flag. */
3801 avc->ddirty_flags &= ~VDisconShadowed;