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);
1854 setLocks = aflags & 1;
1857 * Determine the chunk number and offset within the chunk corresponding
1858 * to the desired byte.
1860 if (avc->fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1863 chunk = AFS_CHUNK(abyte);
1866 /* come back to here if we waited for the cache to drain. */
1869 setNewCallback = setVcacheStatus = 0;
1873 ObtainWriteLock(&avc->lock, 616);
1875 ObtainReadLock(&avc->lock);
1880 * avc->lock(R) if setLocks && !slowPass
1881 * avc->lock(W) if !setLocks || slowPass
1886 /* check hints first! (might could use bcmp or some such...) */
1887 if ((tdc = avc->dchint)) {
1891 * The locking order between afs_xdcache and dcache lock matters.
1892 * The hint dcache entry could be anywhere, even on the free list.
1893 * Locking afs_xdcache ensures that noone is trying to pull dcache
1894 * entries from the free list, and thereby assuming them to be not
1895 * referenced and not locked.
1897 MObtainReadLock(&afs_xdcache);
1898 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1900 if (dcLocked && (tdc->index != NULLIDX)
1901 && !FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk
1902 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1903 /* got the right one. It might not be the right version, and it
1904 * might be fetching, but it's the right dcache entry.
1906 /* All this code should be integrated better with what follows:
1907 * I can save a good bit more time under a write lock if I do..
1909 ObtainWriteLock(&tdc->tlock, 603);
1911 ReleaseWriteLock(&tdc->tlock);
1913 MReleaseReadLock(&afs_xdcache);
1916 if (hsame(tdc->f.versionNo, avc->m.DataVersion)
1917 && !(tdc->dflags & DFFetching)) {
1919 afs_stats_cmperf.dcacheHits++;
1920 MObtainWriteLock(&afs_xdcache, 559);
1921 QRemove(&tdc->lruq);
1922 QAdd(&afs_DLRU, &tdc->lruq);
1923 MReleaseWriteLock(&afs_xdcache);
1926 * avc->lock(R) if setLocks && !slowPass
1927 * avc->lock(W) if !setLocks || slowPass
1934 ReleaseSharedLock(&tdc->lock);
1935 MReleaseReadLock(&afs_xdcache);
1943 * avc->lock(R) if setLocks && !slowPass
1944 * avc->lock(W) if !setLocks || slowPass
1945 * tdc->lock(S) if tdc
1948 if (!tdc) { /* If the hint wasn't the right dcache entry */
1950 * Hash on the [fid, chunk] and get the corresponding dcache index
1951 * after write-locking the dcache.
1956 * avc->lock(R) if setLocks && !slowPass
1957 * avc->lock(W) if !setLocks || slowPass
1960 i = DCHash(&avc->fid, chunk);
1961 /* check to make sure our space is fine */
1962 afs_MaybeWakeupTruncateDaemon();
1964 MObtainWriteLock(&afs_xdcache, 280);
1966 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1967 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
1968 tdc = afs_GetDSlot(index, NULL);
1969 ReleaseReadLock(&tdc->tlock);
1972 * avc->lock(R) if setLocks && !slowPass
1973 * avc->lock(W) if !setLocks || slowPass
1976 if (!FidCmp(&tdc->f.fid, &avc->fid) && chunk == tdc->f.chunk) {
1977 /* Move it up in the beginning of the list */
1978 if (afs_dchashTbl[i] != index) {
1979 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1980 afs_dcnextTbl[index] = afs_dchashTbl[i];
1981 afs_dchashTbl[i] = index;
1983 MReleaseWriteLock(&afs_xdcache);
1984 ObtainSharedLock(&tdc->lock, 606);
1985 break; /* leaving refCount high for caller */
1991 index = afs_dcnextTbl[index];
1995 * If we didn't find the entry, we'll create one.
1997 if (index == NULLIDX) {
2000 * avc->lock(R) if setLocks
2001 * avc->lock(W) if !setLocks
2004 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
2005 avc, ICL_TYPE_INT32, chunk);
2007 /* Make sure there is a free dcache entry for us to use */
2008 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
2011 avc->states |= CDCLock;
2012 /* just need slots */
2013 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
2015 avc->states &= ~CDCLock;
2016 if (afs_discardDCList != NULLIDX
2017 || afs_freeDCList != NULLIDX)
2019 /* If we can't get space for 5 mins we give up and panic */
2020 if (++downDCount > 300)
2021 osi_Panic("getdcache");
2022 MReleaseWriteLock(&afs_xdcache);
2025 * avc->lock(R) if setLocks
2026 * avc->lock(W) if !setLocks
2028 afs_osi_Wait(1000, 0, 0);
2033 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
2036 * Now add to the two hash chains - note that i is still set
2037 * from the above DCHash call.
2039 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
2040 afs_dchashTbl[i] = tdc->index;
2041 i = DVHash(&avc->fid);
2042 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
2043 afs_dvhashTbl[i] = tdc->index;
2044 tdc->dflags = DFEntryMod;
2046 afs_MaybeWakeupTruncateDaemon();
2047 MReleaseWriteLock(&afs_xdcache);
2048 ConvertWToSLock(&tdc->lock);
2053 /* vcache->dcache hint failed */
2056 * avc->lock(R) if setLocks && !slowPass
2057 * avc->lock(W) if !setLocks || slowPass
2060 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
2061 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2062 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
2063 hgetlo(avc->m.DataVersion));
2065 * Here we have the entry in tdc, with its refCount incremented.
2066 * Note: we don't use the S-lock on avc; it costs concurrency when
2067 * storing a file back to the server.
2071 * Not a newly created file so we need to check the file's length and
2072 * compare data versions since someone could have changed the data or we're
2073 * reading a file written elsewhere. We only want to bypass doing no-op
2074 * read rpcs on newly created files (dv of 0) since only then we guarantee
2075 * that this chunk's data hasn't been filled by another client.
2077 size = AFS_CHUNKSIZE(abyte);
2078 if (aflags & 4) /* called from write */
2080 else /* called from read */
2081 tlen = tdc->validPos - abyte;
2082 Position = AFS_CHUNKTOBASE(chunk);
2083 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
2084 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
2085 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
2086 ICL_HANDLE_OFFSET(Position));
2087 if ((aflags & 4) && (hiszero(avc->m.DataVersion)))
2089 if ((AFS_CHUNKTOBASE(chunk) >= avc->m.Length) ||
2090 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
2091 overWriteWholeChunk = 1;
2092 if (doAdjustSize || overWriteWholeChunk) {
2093 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
2095 #ifdef AFS_SGI64_ENV
2098 #else /* AFS_SGI64_ENV */
2101 #endif /* AFS_SGI64_ENV */
2102 #else /* AFS_SGI_ENV */
2105 #endif /* AFS_SGI_ENV */
2106 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->m.Length &&
2107 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2108 #if defined(AFS_SUN5_ENV) || defined(AFS_OSF_ENV)
2109 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->m.Length)) &&
2111 if (AFS_CHUNKTOBASE(chunk) >= avc->m.Length &&
2113 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2114 !hsame(avc->m.DataVersion, tdc->f.versionNo))
2115 doReallyAdjustSize = 1;
2117 if (doReallyAdjustSize || overWriteWholeChunk) {
2118 /* no data in file to read at this position */
2119 UpgradeSToWLock(&tdc->lock, 607);
2121 file = afs_CFileOpen(tdc->f.inode);
2122 afs_CFileTruncate(file, 0);
2123 afs_CFileClose(file);
2124 afs_AdjustSize(tdc, 0);
2125 hset(tdc->f.versionNo, avc->m.DataVersion);
2126 tdc->dflags |= DFEntryMod;
2128 ConvertWToSLock(&tdc->lock);
2133 * We must read in the whole chunk if the version number doesn't
2137 /* don't need data, just a unique dcache entry */
2138 ObtainWriteLock(&afs_xdcache, 608);
2139 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2140 hadd32(afs_indexCounter, 1);
2141 ReleaseWriteLock(&afs_xdcache);
2143 updateV2DC(setLocks, avc, tdc, 553);
2144 if (vType(avc) == VDIR)
2147 *aoffset = AFS_CHUNKOFFSET(abyte);
2148 if (tdc->validPos < abyte)
2149 *alen = (afs_size_t) 0;
2151 *alen = tdc->validPos - abyte;
2152 ReleaseSharedLock(&tdc->lock);
2155 ReleaseWriteLock(&avc->lock);
2157 ReleaseReadLock(&avc->lock);
2159 return tdc; /* check if we're done */
2164 * avc->lock(R) if setLocks && !slowPass
2165 * avc->lock(W) if !setLocks || slowPass
2168 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
2170 setNewCallback = setVcacheStatus = 0;
2174 * avc->lock(R) if setLocks && !slowPass
2175 * avc->lock(W) if !setLocks || slowPass
2178 if (!hsame(avc->m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
2180 * Version number mismatch.
2183 * If we are disconnected, then we can't do much of anything
2184 * because the data doesn't match the file.
2186 if (AFS_IS_DISCONNECTED) {
2187 ReleaseSharedLock(&tdc->lock);
2190 ReleaseWriteLock(&avc->lock);
2192 ReleaseReadLock(&avc->lock);
2194 /* Flush the Dcache */
2199 UpgradeSToWLock(&tdc->lock, 609);
2202 * If data ever existed for this vnode, and this is a text object,
2203 * do some clearing. Now, you'd think you need only do the flush
2204 * when VTEXT is on, but VTEXT is turned off when the text object
2205 * is freed, while pages are left lying around in memory marked
2206 * with this vnode. If we would reactivate (create a new text
2207 * object from) this vnode, we could easily stumble upon some of
2208 * these old pages in pagein. So, we always flush these guys.
2209 * Sun has a wonderful lack of useful invariants in this system.
2211 * avc->flushDV is the data version # of the file at the last text
2212 * flush. Clearly, at least, we don't have to flush the file more
2213 * often than it changes
2215 if (hcmp(avc->flushDV, avc->m.DataVersion) < 0) {
2217 * By here, the cache entry is always write-locked. We can
2218 * deadlock if we call osi_Flush with the cache entry locked...
2219 * Unlock the dcache too.
2221 ReleaseWriteLock(&tdc->lock);
2222 if (setLocks && !slowPass)
2223 ReleaseReadLock(&avc->lock);
2225 ReleaseWriteLock(&avc->lock);
2229 * Call osi_FlushPages in open, read/write, and map, since it
2230 * is too hard here to figure out if we should lock the
2233 if (setLocks && !slowPass)
2234 ObtainReadLock(&avc->lock);
2236 ObtainWriteLock(&avc->lock, 66);
2237 ObtainWriteLock(&tdc->lock, 610);
2242 * avc->lock(R) if setLocks && !slowPass
2243 * avc->lock(W) if !setLocks || slowPass
2247 /* Watch for standard race condition around osi_FlushText */
2248 if (hsame(avc->m.DataVersion, tdc->f.versionNo)) {
2249 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2250 afs_stats_cmperf.dcacheHits++;
2251 ConvertWToSLock(&tdc->lock);
2255 /* Sleep here when cache needs to be drained. */
2256 if (setLocks && !slowPass
2257 && (afs_blocksUsed >
2258 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2259 /* Make sure truncate daemon is running */
2260 afs_MaybeWakeupTruncateDaemon();
2261 ObtainWriteLock(&tdc->tlock, 614);
2262 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2263 ReleaseWriteLock(&tdc->tlock);
2264 ReleaseWriteLock(&tdc->lock);
2265 ReleaseReadLock(&avc->lock);
2266 while ((afs_blocksUsed - afs_blocksDiscarded) >
2267 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2268 afs_WaitForCacheDrain = 1;
2269 afs_osi_Sleep(&afs_WaitForCacheDrain);
2271 afs_MaybeFreeDiscardedDCache();
2272 /* need to check if someone else got the chunk first. */
2273 goto RetryGetDCache;
2276 /* Do not fetch data beyond truncPos. */
2277 maxGoodLength = avc->m.Length;
2278 if (avc->truncPos < maxGoodLength)
2279 maxGoodLength = avc->truncPos;
2280 Position = AFS_CHUNKBASE(abyte);
2281 if (vType(avc) == VDIR) {
2282 size = avc->m.Length;
2283 if (size > tdc->f.chunkBytes) {
2284 /* pre-reserve space for file */
2285 afs_AdjustSize(tdc, size);
2287 size = 999999999; /* max size for transfer */
2289 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2290 /* don't read past end of good data on server */
2291 if (Position + size > maxGoodLength)
2292 size = maxGoodLength - Position;
2294 size = 0; /* Handle random races */
2295 if (size > tdc->f.chunkBytes) {
2296 /* pre-reserve space for file */
2297 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2298 /* max size for transfer still in size */
2301 if (afs_mariner && !tdc->f.chunk)
2302 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2304 * Right now, we only have one tool, and it's a hammer. So, we
2305 * fetch the whole file.
2307 DZap(tdc); /* pages in cache may be old */
2308 file = afs_CFileOpen(tdc->f.inode);
2309 afs_RemoveVCB(&avc->fid);
2310 tdc->f.states |= DWriting;
2311 tdc->dflags |= DFFetching;
2312 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2313 if (tdc->mflags & DFFetchReq) {
2314 tdc->mflags &= ~DFFetchReq;
2315 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2316 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2317 __FILE__, ICL_TYPE_INT32, __LINE__,
2318 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2322 (struct tlocal1 *)osi_AllocLargeSpace(sizeof(struct tlocal1));
2323 setVcacheStatus = 0;
2326 * Remember if we are doing the reading from a replicated volume,
2327 * and how many times we've zipped around the fetch/analyze loop.
2329 fromReplica = (avc->states & CRO) ? 1 : 0;
2331 accP = &(afs_stats_cmfullperf.accessinf);
2333 (accP->replicatedRefs)++;
2335 (accP->unreplicatedRefs)++;
2336 #endif /* AFS_NOSTATS */
2337 /* this is a cache miss */
2338 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2339 ICL_TYPE_FID, &(avc->fid), ICL_TYPE_OFFSET,
2340 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2343 afs_stats_cmperf.dcacheMisses++;
2346 * Dynamic root support: fetch data from local memory.
2348 if (afs_IsDynroot(avc)) {
2352 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2354 dynrootDir += Position;
2355 dynrootLen -= Position;
2356 if (size > dynrootLen)
2360 code = afs_CFileWrite(file, 0, dynrootDir, size);
2368 tdc->validPos = Position + size;
2369 afs_CFileTruncate(file, size); /* prune it */
2370 } else if (afs_IsDynrootMount(avc)) {
2374 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2376 dynrootDir += Position;
2377 dynrootLen -= Position;
2378 if (size > dynrootLen)
2382 code = afs_CFileWrite(file, 0, dynrootDir, size);
2390 tdc->validPos = Position + size;
2391 afs_CFileTruncate(file, size); /* prune it */
2392 } else if (afs_IsDynrootMount(avc)) {
2396 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2398 dynrootDir += Position;
2399 dynrootLen -= Position;
2400 if (size > dynrootLen)
2404 code = afs_CFileWrite(file, 0, dynrootDir, size);
2412 tdc->validPos = Position + size;
2413 afs_CFileTruncate(file, size); /* prune it */
2416 * Not a dynamic vnode: do the real fetch.
2421 * avc->lock(R) if setLocks && !slowPass
2422 * avc->lock(W) if !setLocks || slowPass
2426 tc = afs_Conn(&avc->fid, areq, SHARED_LOCK);
2428 afs_int32 length_hi, length, bytes;
2432 (accP->numReplicasAccessed)++;
2434 #endif /* AFS_NOSTATS */
2435 if (!setLocks || slowPass) {
2436 avc->callback = tc->srvr->server;
2438 newCallback = tc->srvr->server;
2443 tcall = rx_NewCall(tc->id);
2446 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHDATA);
2447 #ifdef AFS_64BIT_CLIENT
2448 length_hi = code = 0;
2449 if (!afs_serverHasNo64Bit(tc)) {
2453 StartRXAFS_FetchData64(tcall,
2454 (struct AFSFid *)&avc->fid.
2455 Fid, Position, tsize);
2458 afs_Trace2(afs_iclSetp, CM_TRACE_FETCH64CODE,
2459 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32,
2463 rx_Read(tcall, (char *)&length_hi,
2466 if (bytes == sizeof(afs_int32)) {
2467 length_hi = ntohl(length_hi);
2470 code = rx_Error(tcall);
2472 code1 = rx_EndCall(tcall, code);
2474 tcall = (struct rx_call *)0;
2478 if (code == RXGEN_OPCODE || afs_serverHasNo64Bit(tc)) {
2479 if (Position > 0x7FFFFFFF) {
2486 tcall = rx_NewCall(tc->id);
2488 StartRXAFS_FetchData(tcall, (struct AFSFid *)
2493 afs_serverSetNo64Bit(tc);
2498 rx_Read(tcall, (char *)&length,
2501 if (bytes == sizeof(afs_int32)) {
2502 length = ntohl(length);
2504 code = rx_Error(tcall);
2507 FillInt64(lengthFound, length_hi, length);
2508 afs_Trace3(afs_iclSetp, CM_TRACE_FETCH64LENG,
2509 ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, code,
2511 ICL_HANDLE_OFFSET(lengthFound));
2512 #else /* AFS_64BIT_CLIENT */
2515 StartRXAFS_FetchData(tcall,
2516 (struct AFSFid *)&avc->fid.Fid,
2522 rx_Read(tcall, (char *)&length,
2525 if (bytes == sizeof(afs_int32)) {
2526 length = ntohl(length);
2528 code = rx_Error(tcall);
2531 #endif /* AFS_64BIT_CLIENT */
2536 &(afs_stats_cmfullperf.rpc.
2537 fsXferTimes[AFS_STATS_FS_XFERIDX_FETCHDATA]);
2538 osi_GetuTime(&xferStartTime);
2541 afs_CacheFetchProc(tcall, file,
2542 (afs_size_t) Position, tdc,
2544 &bytesXferred, length);
2546 osi_GetuTime(&xferStopTime);
2547 (xferP->numXfers)++;
2549 (xferP->numSuccesses)++;
2550 afs_stats_XferSumBytes
2551 [AFS_STATS_FS_XFERIDX_FETCHDATA] +=
2553 (xferP->sumBytes) +=
2554 (afs_stats_XferSumBytes
2555 [AFS_STATS_FS_XFERIDX_FETCHDATA] >> 10);
2556 afs_stats_XferSumBytes
2557 [AFS_STATS_FS_XFERIDX_FETCHDATA] &= 0x3FF;
2558 if (bytesXferred < xferP->minBytes)
2559 xferP->minBytes = bytesXferred;
2560 if (bytesXferred > xferP->maxBytes)
2561 xferP->maxBytes = bytesXferred;
2564 * Tally the size of the object. Note: we tally the actual size,
2565 * NOT the number of bytes that made it out over the wire.
2567 if (bytesToXfer <= AFS_STATS_MAXBYTES_BUCKET0)
2568 (xferP->count[0])++;
2569 else if (bytesToXfer <=
2570 AFS_STATS_MAXBYTES_BUCKET1)
2571 (xferP->count[1])++;
2572 else if (bytesToXfer <=
2573 AFS_STATS_MAXBYTES_BUCKET2)
2574 (xferP->count[2])++;
2575 else if (bytesToXfer <=
2576 AFS_STATS_MAXBYTES_BUCKET3)
2577 (xferP->count[3])++;
2578 else if (bytesToXfer <=
2579 AFS_STATS_MAXBYTES_BUCKET4)
2580 (xferP->count[4])++;
2581 else if (bytesToXfer <=
2582 AFS_STATS_MAXBYTES_BUCKET5)
2583 (xferP->count[5])++;
2584 else if (bytesToXfer <=
2585 AFS_STATS_MAXBYTES_BUCKET6)
2586 (xferP->count[6])++;
2587 else if (bytesToXfer <=
2588 AFS_STATS_MAXBYTES_BUCKET7)
2589 (xferP->count[7])++;
2591 (xferP->count[8])++;
2593 afs_stats_GetDiff(elapsedTime, xferStartTime,
2595 afs_stats_AddTo((xferP->sumTime), elapsedTime);
2596 afs_stats_SquareAddTo((xferP->sqrTime),
2598 if (afs_stats_TimeLessThan
2599 (elapsedTime, (xferP->minTime))) {
2600 afs_stats_TimeAssign((xferP->minTime),
2603 if (afs_stats_TimeGreaterThan
2604 (elapsedTime, (xferP->maxTime))) {
2605 afs_stats_TimeAssign((xferP->maxTime),
2611 afs_CacheFetchProc(tcall, file, Position, tdc,
2613 #endif /* AFS_NOSTATS */
2618 EndRXAFS_FetchData(tcall, &tsmall->OutStatus,
2626 code1 = rx_EndCall(tcall, code);
2635 /* callback could have been broken (or expired) in a race here,
2636 * but we return the data anyway. It's as good as we knew about
2637 * when we started. */
2639 * validPos is updated by CacheFetchProc, and can only be
2640 * modifed under a dcache write lock, which we've blocked out
2642 size = tdc->validPos - Position; /* actual segment size */
2645 afs_CFileTruncate(file, size); /* prune it */
2647 if (!setLocks || slowPass) {
2648 ObtainWriteLock(&afs_xcbhash, 453);
2649 afs_DequeueCallback(avc);
2650 avc->states &= ~(CStatd | CUnique);
2651 avc->callback = NULL;
2652 ReleaseWriteLock(&afs_xcbhash);
2653 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2654 osi_dnlc_purgedp(avc);
2656 /* Something lost. Forget about performance, and go
2657 * back with a vcache write lock.
2659 afs_CFileTruncate(file, 0);
2660 afs_AdjustSize(tdc, 0);
2661 afs_CFileClose(file);
2662 osi_FreeLargeSpace(tsmall);
2664 ReleaseWriteLock(&tdc->lock);
2667 ReleaseReadLock(&avc->lock);
2669 goto RetryGetDCache;
2673 } while (afs_Analyze
2674 (tc, code, &avc->fid, areq,
2675 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2679 * avc->lock(R) if setLocks && !slowPass
2680 * avc->lock(W) if !setLocks || slowPass
2686 * In the case of replicated access, jot down info on the number of
2687 * attempts it took before we got through or gave up.
2690 if (numFetchLoops <= 1)
2691 (accP->refFirstReplicaOK)++;
2692 if (numFetchLoops > accP->maxReplicasPerRef)
2693 accP->maxReplicasPerRef = numFetchLoops;
2695 #endif /* AFS_NOSTATS */
2697 tdc->dflags &= ~DFFetching;
2698 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2699 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2700 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2701 tdc, ICL_TYPE_INT32, tdc->dflags);
2702 if (avc->execsOrWriters == 0)
2703 tdc->f.states &= ~DWriting;
2705 /* now, if code != 0, we have an error and should punt.
2706 * note that we have the vcache write lock, either because
2707 * !setLocks or slowPass.
2710 afs_CFileTruncate(file, 0);
2711 afs_AdjustSize(tdc, 0);
2712 afs_CFileClose(file);
2713 ZapDCE(tdc); /* sets DFEntryMod */
2714 if (vType(avc) == VDIR) {
2717 tdc->f.states &= ~(DRO|DBackup|DRW);
2718 afs_DCMoveBucket(tdc, 0, 0);
2719 ReleaseWriteLock(&tdc->lock);
2721 if (!afs_IsDynroot(avc)) {
2722 ObtainWriteLock(&afs_xcbhash, 454);
2723 afs_DequeueCallback(avc);
2724 avc->states &= ~(CStatd | CUnique);
2725 ReleaseWriteLock(&afs_xcbhash);
2726 if (avc->fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2727 osi_dnlc_purgedp(avc);
2730 * avc->lock(W); assert(!setLocks || slowPass)
2732 osi_Assert(!setLocks || slowPass);
2734 tdc->f.states &= ~(DRO|DBackup|DRW);
2735 afs_DCMoveBucket(tdc, 0, 0);
2740 /* otherwise we copy in the just-fetched info */
2741 afs_CFileClose(file);
2742 afs_AdjustSize(tdc, size); /* new size */
2744 * Copy appropriate fields into vcache. Status is
2745 * copied later where we selectively acquire the
2746 * vcache write lock.
2749 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2751 setVcacheStatus = 1;
2752 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2753 tsmall->OutStatus.DataVersion);
2754 tdc->dflags |= DFEntryMod;
2755 afs_indexFlags[tdc->index] |= IFEverUsed;
2756 ConvertWToSLock(&tdc->lock);
2757 } /*Data version numbers don't match */
2760 * Data version numbers match.
2762 afs_stats_cmperf.dcacheHits++;
2763 } /*Data version numbers match */
2765 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2769 * avc->lock(R) if setLocks && !slowPass
2770 * avc->lock(W) if !setLocks || slowPass
2771 * tdc->lock(S) if tdc
2775 * See if this was a reference to a file in the local cell.
2777 if (afs_IsPrimaryCellNum(avc->fid.Cell))
2778 afs_stats_cmperf.dlocalAccesses++;
2780 afs_stats_cmperf.dremoteAccesses++;
2782 /* Fix up LRU info */
2785 MObtainWriteLock(&afs_xdcache, 602);
2786 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2787 hadd32(afs_indexCounter, 1);
2788 MReleaseWriteLock(&afs_xdcache);
2790 /* return the data */
2791 if (vType(avc) == VDIR)
2794 *aoffset = AFS_CHUNKOFFSET(abyte);
2795 *alen = (tdc->f.chunkBytes - *aoffset);
2796 ReleaseSharedLock(&tdc->lock);
2801 * avc->lock(R) if setLocks && !slowPass
2802 * avc->lock(W) if !setLocks || slowPass
2805 /* Fix up the callback and status values in the vcache */
2807 if (setLocks && !slowPass) {
2810 * This is our dirty little secret to parallel fetches.
2811 * We don't write-lock the vcache while doing the fetch,
2812 * but potentially we'll need to update the vcache after
2813 * the fetch is done.
2815 * Drop the read lock and try to re-obtain the write
2816 * lock. If the vcache still has the same DV, it's
2817 * ok to go ahead and install the new data.
2819 afs_hyper_t currentDV, statusDV;
2821 hset(currentDV, avc->m.DataVersion);
2823 if (setNewCallback && avc->callback != newCallback)
2827 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2828 tsmall->OutStatus.DataVersion);
2830 if (setVcacheStatus && avc->m.Length != tsmall->OutStatus.Length)
2832 if (setVcacheStatus && !hsame(currentDV, statusDV))
2836 ReleaseReadLock(&avc->lock);
2838 if (doVcacheUpdate) {
2839 ObtainWriteLock(&avc->lock, 615);
2840 if (!hsame(avc->m.DataVersion, currentDV)) {
2841 /* We lose. Someone will beat us to it. */
2843 ReleaseWriteLock(&avc->lock);
2848 /* With slow pass, we've already done all the updates */
2850 ReleaseWriteLock(&avc->lock);
2853 /* Check if we need to perform any last-minute fixes with a write-lock */
2854 if (!setLocks || doVcacheUpdate) {
2856 avc->callback = newCallback;
2857 if (tsmall && setVcacheStatus)
2858 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2860 ReleaseWriteLock(&avc->lock);
2864 osi_FreeLargeSpace(tsmall);
2867 } /*afs_GetDCache */
2871 * afs_WriteThroughDSlots
2874 * Sweep through the dcache slots and write out any modified
2875 * in-memory data back on to our caching store.
2881 * The afs_xdcache is write-locked through this whole affair.
2884 afs_WriteThroughDSlots(void)
2886 register struct dcache *tdc;
2887 register afs_int32 i, touchedit = 0;
2889 struct afs_q DirtyQ, *tq;
2891 AFS_STATCNT(afs_WriteThroughDSlots);
2894 * Because of lock ordering, we can't grab dcache locks while
2895 * holding afs_xdcache. So we enter xdcache, get a reference
2896 * for every dcache entry, and exit xdcache.
2898 MObtainWriteLock(&afs_xdcache, 283);
2900 for (i = 0; i < afs_cacheFiles; i++) {
2901 tdc = afs_indexTable[i];
2903 /* Grab tlock in case the existing refcount isn't zero */
2904 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2905 ObtainWriteLock(&tdc->tlock, 623);
2907 ReleaseWriteLock(&tdc->tlock);
2909 QAdd(&DirtyQ, &tdc->dirty);
2912 MReleaseWriteLock(&afs_xdcache);
2915 * Now, for each dcache entry we found, check if it's dirty.
2916 * If so, get write-lock, get afs_xdcache, which protects
2917 * afs_cacheInodep, and flush it. Don't forget to put back
2921 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2923 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2925 if (tdc->dflags & DFEntryMod) {
2928 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2930 /* Now that we have the write lock, double-check */
2931 if (wrLock && (tdc->dflags & DFEntryMod)) {
2932 tdc->dflags &= ~DFEntryMod;
2933 MObtainWriteLock(&afs_xdcache, 620);
2934 afs_WriteDCache(tdc, 1);
2935 MReleaseWriteLock(&afs_xdcache);
2939 ReleaseWriteLock(&tdc->lock);
2945 MObtainWriteLock(&afs_xdcache, 617);
2946 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2947 /* Touch the file to make sure that the mtime on the file is kept
2948 * up-to-date to avoid losing cached files on cold starts because
2949 * their mtime seems old...
2951 struct afs_fheader theader;
2953 theader.magic = AFS_FHMAGIC;
2954 theader.firstCSize = AFS_FIRSTCSIZE;
2955 theader.otherCSize = AFS_OTHERCSIZE;
2956 theader.version = AFS_CI_VERSION;
2957 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2959 MReleaseWriteLock(&afs_xdcache);
2966 * Return a pointer to an freshly initialized dcache entry using
2967 * a memory-based cache. The tlock will be read-locked.
2970 * aslot : Dcache slot to look at.
2971 * tmpdc : Ptr to dcache entry.
2974 * Must be called with afs_xdcache write-locked.
2978 afs_MemGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2980 register struct dcache *tdc;
2983 AFS_STATCNT(afs_MemGetDSlot);
2984 if (CheckLock(&afs_xdcache) != -1)
2985 osi_Panic("getdslot nolock");
2986 if (aslot < 0 || aslot >= afs_cacheFiles)
2987 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2988 tdc = afs_indexTable[aslot];
2990 QRemove(&tdc->lruq); /* move to queue head */
2991 QAdd(&afs_DLRU, &tdc->lruq);
2992 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2993 ObtainWriteLock(&tdc->tlock, 624);
2995 ConvertWToRLock(&tdc->tlock);
2998 if (tmpdc == NULL) {
2999 if (!afs_freeDSList)
3000 afs_GetDownDSlot(4);
3001 if (!afs_freeDSList) {
3002 /* none free, making one is better than a panic */
3003 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
3004 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
3005 #ifdef KERNEL_HAVE_PIN
3006 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
3009 tdc = afs_freeDSList;
3010 afs_freeDSList = (struct dcache *)tdc->lruq.next;
3013 tdc->dflags = 0; /* up-to-date, not in free q */
3015 QAdd(&afs_DLRU, &tdc->lruq);
3016 if (tdc->lruq.prev == &tdc->lruq)
3017 osi_Panic("lruq 3");
3023 /* initialize entry */
3024 tdc->f.fid.Cell = 0;
3025 tdc->f.fid.Fid.Volume = 0;
3027 hones(tdc->f.versionNo);
3028 tdc->f.inode = aslot;
3029 tdc->dflags |= DFEntryMod;
3032 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3035 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3036 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3037 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3040 RWLOCK_INIT(&tdc->lock, "dcache lock");
3041 RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3042 RWLOCK_INIT(&tdc->mflock, "dcache flock");
3043 ObtainReadLock(&tdc->tlock);
3046 afs_indexTable[aslot] = tdc;
3049 } /*afs_MemGetDSlot */
3051 unsigned int last_error = 0, lasterrtime = 0;
3057 * Return a pointer to an freshly initialized dcache entry using
3058 * a UFS-based disk cache. The dcache tlock will be read-locked.
3061 * aslot : Dcache slot to look at.
3062 * tmpdc : Ptr to dcache entry.
3065 * afs_xdcache lock write-locked.
3068 afs_UFSGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
3070 register afs_int32 code;
3071 register struct dcache *tdc;
3075 AFS_STATCNT(afs_UFSGetDSlot);
3076 if (CheckLock(&afs_xdcache) != -1)
3077 osi_Panic("getdslot nolock");
3078 if (aslot < 0 || aslot >= afs_cacheFiles)
3079 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3080 tdc = afs_indexTable[aslot];
3082 QRemove(&tdc->lruq); /* move to queue head */
3083 QAdd(&afs_DLRU, &tdc->lruq);
3084 /* Grab tlock in case refCount != 0 */
3085 ObtainWriteLock(&tdc->tlock, 625);
3087 ConvertWToRLock(&tdc->tlock);
3090 /* otherwise we should read it in from the cache file */
3092 * If we weren't passed an in-memory region to place the file info,
3093 * we have to allocate one.
3095 if (tmpdc == NULL) {
3096 if (!afs_freeDSList)
3097 afs_GetDownDSlot(4);
3098 if (!afs_freeDSList) {
3099 /* none free, making one is better than a panic */
3100 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
3101 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
3102 #ifdef KERNEL_HAVE_PIN
3103 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
3106 tdc = afs_freeDSList;
3107 afs_freeDSList = (struct dcache *)tdc->lruq.next;
3110 tdc->dflags = 0; /* up-to-date, not in free q */
3112 QAdd(&afs_DLRU, &tdc->lruq);
3113 if (tdc->lruq.prev == &tdc->lruq)
3114 osi_Panic("lruq 3");
3121 * Seek to the aslot'th entry and read it in.
3124 afs_osi_Read(afs_cacheInodep,
3125 sizeof(struct fcache) * aslot +
3126 sizeof(struct afs_fheader), (char *)(&tdc->f),
3127 sizeof(struct fcache));
3129 if (code != sizeof(struct fcache))
3131 if (!afs_CellNumValid(tdc->f.fid.Cell))
3135 tdc->f.fid.Cell = 0;
3136 tdc->f.fid.Fid.Volume = 0;
3138 hones(tdc->f.versionNo);
3139 tdc->dflags |= DFEntryMod;
3140 #if defined(KERNEL_HAVE_UERROR)
3141 last_error = getuerror();
3143 lasterrtime = osi_Time();
3144 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3145 tdc->f.states &= ~(DRO|DBackup|DRW);
3146 afs_DCMoveBucket(tdc, 0, 0);
3149 if (tdc->f.states & DRO) {
3150 afs_DCMoveBucket(tdc, 0, 2);
3151 } else if (tdc->f.states & DBackup) {
3152 afs_DCMoveBucket(tdc, 0, 1);
3154 afs_DCMoveBucket(tdc, 0, 1);
3160 if (tdc->f.chunk >= 0)
3161 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
3166 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3167 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3168 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3171 RWLOCK_INIT(&tdc->lock, "dcache lock");
3172 RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3173 RWLOCK_INIT(&tdc->mflock, "dcache flock");
3174 ObtainReadLock(&tdc->tlock);
3177 * If we didn't read into a temporary dcache region, update the
3178 * slot pointer table.
3181 afs_indexTable[aslot] = tdc;
3184 } /*afs_UFSGetDSlot */
3192 * write a particular dcache entry back to its home in the
3196 * adc : Pointer to the dcache entry to write.
3197 * atime : If true, set the modtime on the file to the current time.
3200 * Must be called with the afs_xdcache lock at least read-locked,
3201 * and dcache entry at least read-locked.
3202 * The reference count is not changed.
3206 afs_WriteDCache(register struct dcache *adc, int atime)
3208 register afs_int32 code;
3210 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3212 AFS_STATCNT(afs_WriteDCache);
3213 osi_Assert(WriteLocked(&afs_xdcache));
3215 adc->f.modTime = osi_Time();
3217 * Seek to the right dcache slot and write the in-memory image out to disk.
3219 afs_cellname_write();
3221 afs_osi_Write(afs_cacheInodep,
3222 sizeof(struct fcache) * adc->index +
3223 sizeof(struct afs_fheader), (char *)(&adc->f),
3224 sizeof(struct fcache));
3225 if (code != sizeof(struct fcache))
3236 * Wake up users of a particular file waiting for stores to take
3240 * avc : Ptr to related vcache entry.
3243 * Nothing interesting.
3247 afs_wakeup(register struct vcache *avc)
3250 register struct brequest *tb;
3252 AFS_STATCNT(afs_wakeup);
3253 for (i = 0; i < NBRS; i++, tb++) {
3254 /* if request is valid and for this file, we've found it */
3255 if (tb->refCount > 0 && avc == tb->vc) {
3258 * If CSafeStore is on, then we don't awaken the guy
3259 * waiting for the store until the whole store has finished.
3260 * Otherwise, we do it now. Note that if CSafeStore is on,
3261 * the BStore routine actually wakes up the user, instead
3263 * I think this is redundant now because this sort of thing
3264 * is already being handled by the higher-level code.
3266 if ((avc->states & CSafeStore) == 0) {
3268 tb->flags |= BUVALID;
3269 if (tb->flags & BUWAIT) {
3270 tb->flags &= ~BUWAIT;
3285 * Given a file name and inode, set up that file to be an
3286 * active member in the AFS cache. This also involves checking
3287 * the usability of its data.
3290 * afile : Name of the cache file to initialize.
3291 * ainode : Inode of the file.
3294 * This function is called only during initialization.
3298 afs_InitCacheFile(char *afile, ino_t ainode)
3300 register afs_int32 code;
3301 #if defined(AFS_LINUX22_ENV)
3302 struct dentry *filevp;
3304 struct vnode *filevp;
3308 struct osi_file *tfile;
3309 struct osi_stat tstat;
3310 register struct dcache *tdc;
3312 AFS_STATCNT(afs_InitCacheFile);
3313 index = afs_stats_cmperf.cacheNumEntries;
3314 if (index >= afs_cacheFiles)
3317 MObtainWriteLock(&afs_xdcache, 282);
3318 tdc = afs_GetDSlot(index, NULL);
3319 ReleaseReadLock(&tdc->tlock);
3320 MReleaseWriteLock(&afs_xdcache);
3322 ObtainWriteLock(&tdc->lock, 621);
3323 MObtainWriteLock(&afs_xdcache, 622);
3325 code = gop_lookupname(afile, AFS_UIOSYS, 0, &filevp);
3327 ReleaseWriteLock(&afs_xdcache);
3328 ReleaseWriteLock(&tdc->lock);
3333 * We have a VN_HOLD on filevp. Get the useful info out and
3334 * return. We make use of the fact that the cache is in the
3335 * UFS file system, and just record the inode number.
3337 #ifdef AFS_LINUX22_ENV
3338 tdc->f.inode = VTOI(filevp->d_inode)->i_number;
3341 tdc->f.inode = afs_vnodeToInumber(filevp);
3343 #endif /* AFS_LINUX22_ENV */
3345 tdc->f.inode = ainode;
3348 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3350 tfile = osi_UFSOpen(tdc->f.inode);
3351 code = afs_osi_Stat(tfile, &tstat);
3353 osi_Panic("initcachefile stat");
3356 * If file size doesn't match the cache info file, it's probably bad.
3358 if (tdc->f.chunkBytes != tstat.size)
3360 tdc->f.chunkBytes = 0;
3363 * If file changed within T (120?) seconds of cache info file, it's
3364 * probably bad. In addition, if slot changed within last T seconds,
3365 * the cache info file may be incorrectly identified, and so slot
3368 if (cacheInfoModTime < tstat.mtime + 120)
3370 if (cacheInfoModTime < tdc->f.modTime + 120)
3372 /* In case write through is behind, make sure cache items entry is
3373 * at least as new as the chunk.
3375 if (tdc->f.modTime < tstat.mtime)
3378 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3379 if (tstat.size != 0)
3380 osi_UFSTruncate(tfile, 0);
3381 tdc->f.states &= ~(DRO|DBackup|DRW);
3382 afs_DCMoveBucket(tdc, 0, 0);
3383 /* put entry in free cache slot list */
3384 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3385 afs_freeDCList = index;
3387 afs_indexFlags[index] |= IFFree;
3388 afs_indexUnique[index] = 0;
3391 * We must put this entry in the appropriate hash tables.
3392 * Note that i is still set from the above DCHash call
3394 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3395 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3396 afs_dchashTbl[code] = tdc->index;
3397 code = DVHash(&tdc->f.fid);
3398 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3399 afs_dvhashTbl[code] = tdc->index;
3400 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3402 /* has nontrivial amt of data */
3403 afs_indexFlags[index] |= IFEverUsed;
3404 afs_stats_cmperf.cacheFilesReused++;
3406 * Initialize index times to file's mod times; init indexCounter
3409 hset32(afs_indexTimes[index], tstat.atime);
3410 if (hgetlo(afs_indexCounter) < tstat.atime) {
3411 hset32(afs_indexCounter, tstat.atime);
3413 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3414 } /*File is not bad */
3416 osi_UFSClose(tfile);
3417 tdc->f.states &= ~DWriting;
3418 tdc->dflags &= ~DFEntryMod;
3419 /* don't set f.modTime; we're just cleaning up */
3420 afs_WriteDCache(tdc, 0);
3421 ReleaseWriteLock(&afs_xdcache);
3422 ReleaseWriteLock(&tdc->lock);
3424 afs_stats_cmperf.cacheNumEntries++;
3429 /*Max # of struct dcache's resident at any time*/
3431 * If 'dchint' is enabled then in-memory dcache min is increased because of
3440 * Initialize dcache related variables.
3443 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3445 register struct dcache *tdp;
3449 afs_freeDCList = NULLIDX;
3450 afs_discardDCList = NULLIDX;
3451 afs_freeDCCount = 0;
3452 afs_freeDSList = NULL;
3453 hzero(afs_indexCounter);
3455 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3461 if (achunk < 0 || achunk > 30)
3462 achunk = 13; /* Use default */
3463 AFS_SETCHUNKSIZE(achunk);
3469 if (aflags & AFSCALL_INIT_MEMCACHE) {
3471 * Use a memory cache instead of a disk cache
3473 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3474 afs_cacheType = &afs_MemCacheOps;
3475 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3476 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3477 /* ablocks is reported in 1K blocks */
3478 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3480 printf("afsd: memory cache too large for available memory.\n");
3481 printf("afsd: AFS files cannot be accessed.\n\n");
3483 afiles = ablocks = 0;
3485 printf("Memory cache: Allocating %d dcache entries...",
3488 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3489 afs_cacheType = &afs_UfsCacheOps;
3492 if (aDentries > 512)
3493 afs_dhashsize = 2048;
3494 /* initialize hash tables */
3496 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3498 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3499 for (i = 0; i < afs_dhashsize; i++) {
3500 afs_dvhashTbl[i] = NULLIDX;
3501 afs_dchashTbl[i] = NULLIDX;
3503 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3504 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3505 for (i = 0; i < afiles; i++) {
3506 afs_dvnextTbl[i] = NULLIDX;
3507 afs_dcnextTbl[i] = NULLIDX;
3510 /* Allocate and zero the pointer array to the dcache entries */
3511 afs_indexTable = (struct dcache **)
3512 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3513 memset((char *)afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3515 (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3516 memset((char *)afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3518 (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3519 memset((char *)afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3520 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3521 memset((char *)afs_indexFlags, 0, afiles * sizeof(char));
3523 /* Allocate and thread the struct dcache entries themselves */
3524 tdp = afs_Initial_freeDSList =
3525 (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3526 memset((char *)tdp, 0, aDentries * sizeof(struct dcache));
3527 #ifdef KERNEL_HAVE_PIN
3528 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3529 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3530 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3531 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3532 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3533 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3534 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3535 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3536 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3539 afs_freeDSList = &tdp[0];
3540 for (i = 0; i < aDentries - 1; i++) {
3541 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3542 RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3543 RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3544 RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3546 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3547 RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3548 RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3549 RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3551 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3552 afs_cacheBlocks = ablocks;
3553 afs_ComputeCacheParms(); /* compute parms based on cache size */
3555 afs_dcentries = aDentries;
3557 afs_stats_cmperf.cacheBucket0_Discarded =
3558 afs_stats_cmperf.cacheBucket1_Discarded =
3559 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3569 shutdown_dcache(void)
3573 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3574 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3575 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3576 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3577 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3578 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3579 afs_osi_Free(afs_Initial_freeDSList,
3580 afs_dcentries * sizeof(struct dcache));
3581 #ifdef KERNEL_HAVE_PIN
3582 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3583 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3584 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3585 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3586 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3587 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3588 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3592 for (i = 0; i < afs_dhashsize; i++) {
3593 afs_dvhashTbl[i] = NULLIDX;
3594 afs_dchashTbl[i] = NULLIDX;
3597 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3598 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3600 afs_blocksUsed = afs_dcentries = 0;
3601 afs_stats_cmperf.cacheBucket0_Discarded =
3602 afs_stats_cmperf.cacheBucket1_Discarded =
3603 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3604 hzero(afs_indexCounter);
3606 afs_freeDCCount = 0;
3607 afs_freeDCList = NULLIDX;
3608 afs_discardDCList = NULLIDX;
3609 afs_freeDSList = afs_Initial_freeDSList = 0;
3611 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3616 #if defined(AFS_DISCON_ENV)
3619 * Make a shadow copy of a dir's dcaches. It's used for disconnected
3620 * operations like remove/create/rename to keep the original directory data.
3621 * On reconnection, we can diff the original data with the server and get the
3622 * server changes and with the local data to get the local changes.
3624 * \param avc The dir vnode.
3626 * \return 0 for success.
3628 * \note The only lock allowed to be set is the dir's vcache entry, and it
3629 * must be set in write mode.
3630 * \note The vcache entry must be write locked.
3632 int afs_MakeShadowDir(struct vcache *avc)
3634 int j, i, index, code, ret_code = 0, offset, trans_size, block;
3635 struct dcache *tdc, *new_dc = NULL;
3636 struct osi_file *tfile_src, *tfile_dst;
3637 struct VenusFid shadow_fid;
3641 /* Is this a dir? */
3642 if (vType(avc) != VDIR)
3645 /* Generate a fid for the shadow dir. */
3646 shadow_fid.Cell = avc->fid.Cell;
3647 shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3648 afs_GenShadowFid(&shadow_fid);
3650 /* For each dcache, do copy it into a new fresh one. */
3651 i = DVHash(&avc->fid);
3652 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
3653 /* Making sure that this isn't going to get locked twice. */
3655 /* XXX: Moved it from outside of the loop.
3656 * Maybe it's not quite okay because of the use of
3657 * dvhashTbl (once) in the for statement.
3659 ObtainWriteLock(&afs_xdcache, 716);
3663 i = afs_dvnextTbl[index];
3664 if (afs_indexUnique[index] == avc->fid.Fid.Unique) {
3665 tdc = afs_GetDSlot(index, NULL);
3667 ReleaseReadLock(&tdc->tlock);
3669 if (!FidCmp(&tdc->f.fid, &avc->fid)) {
3671 /* Got a dir's dcache. */
3674 /* Get a fresh dcache. */
3675 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3677 /* Unlock hash for now. Don't need it during operations on the
3678 * dcache. Oh, and we can't use it because of the locking
3681 /* XXX: So much for lock ierarchy, the afs_AllocDCache doesn't
3684 //ReleaseWriteLock(&afs_xdcache);
3686 ObtainReadLock(&tdc->lock);
3688 /* Set up the new fid. */
3689 /* Copy interesting data from original dir dcache. */
3690 new_dc->mflags = tdc->mflags;
3691 new_dc->dflags = tdc->dflags;
3692 new_dc->f.modTime = tdc->f.modTime;
3693 new_dc->f.versionNo = tdc->f.versionNo;
3694 new_dc->f.states = tdc->f.states;
3695 new_dc->f.chunk= tdc->f.chunk;
3696 new_dc->f.chunkBytes = tdc->f.chunkBytes;
3699 * Now add to the two hash chains - note that i is still set
3700 * from the above DCHash call.
3702 //ObtainWriteLock(&afs_xdcache, 713);
3704 j = DCHash(&shadow_fid, 0);
3705 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[j];
3706 afs_dchashTbl[j] = new_dc->index;
3708 j = DVHash(&shadow_fid);
3709 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[j];
3710 afs_dvhashTbl[j] = new_dc->index;
3711 afs_MaybeWakeupTruncateDaemon();
3713 ReleaseWriteLock(&afs_xdcache);
3715 /* Alloc a 4k block. */
3716 data = (char *) afs_osi_Alloc(4096);
3718 printf("afs_MakeShadowDir: could not alloc data\n");
3723 /* Open the files. */
3724 tfile_src = afs_CFileOpen(tdc->f.inode);
3725 tfile_dst = afs_CFileOpen(new_dc->f.inode);
3727 /* Init no of blocks to be read and offset. */
3728 block = (tdc->f.chunkBytes / 4096);
3731 /* And now copy dir dcache data into this dcache,
3734 while (block >= 0) {
3736 /* Last chunk might have less bytes to transfer. */
3739 trans_size = (tdc->f.chunkBytes % 4096);
3741 /* An exact no of 4k blocks. */
3746 /* Read a chunk from the dcache. */
3747 code = afs_CFileRead(tfile_src, offset, data, trans_size);
3748 if (code < trans_size) {
3749 /* Can't access file, stop doing stuff and return error. */
3754 /* Write it to the new dcache. */
3755 code = afs_CFileWrite(tfile_dst, offset, data, trans_size);
3756 if (code < trans_size) {
3763 } /* while (block) */
3765 afs_CFileClose(tfile_dst);
3766 afs_CFileClose(tfile_src);
3768 afs_osi_Free(data, 4096);
3770 ReleaseWriteLock(&new_dc->lock);
3771 ReleaseReadLock(&tdc->lock);
3773 afs_PutDCache(new_dc);
3774 } /* if dcache fid match */
3776 } /* if unuiquifier match */
3780 ReleaseWriteLock(&afs_xdcache);
3783 if (!avc->ddirty_flags) {
3784 ObtainWriteLock(&afs_DDirtyVCListLock, 763);
3785 AFS_DISCON_ADD_DIRTY(avc);
3786 ReleaseWriteLock(&afs_DDirtyVCListLock);
3788 avc->shVnode = shadow_fid.Fid.Vnode;
3789 avc->shUnique = shadow_fid.Fid.Unique;
3790 avc->ddirty_flags |= VDisconShadowed;
3797 * Delete the dcaches of a shadow dir.
3799 * \param avc The vcache containing the shadow fid.
3801 * \note avc must be write locked.
3803 void afs_DeleteShadowDir(struct vcache *avc)
3806 struct VenusFid shadow_fid;
3808 shadow_fid.Cell = avc->fid.Cell;
3809 shadow_fid.Fid.Volume = avc->fid.Fid.Volume;
3810 shadow_fid.Fid.Vnode = avc->shVnode;
3811 shadow_fid.Fid.Unique = avc->shUnique;
3813 tdc = afs_FindDCacheByFid(&shadow_fid);
3815 afs_HashOutDCache(tdc, 1);
3816 afs_DiscardDCache(tdc);
3819 /* Remove shadowed dir flag. */
3820 avc->ddirty_flags &= ~VDisconShadowed;