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"
17 #include "afs/sysincludes.h" /*Standard vendor system headers */
18 #include "afsincludes.h" /*AFS-based standard headers */
19 #include "afs/afs_stats.h" /* statistics */
20 #include "afs/afs_cbqueue.h"
21 #include "afs/afs_osidnlc.h"
23 /* Forward declarations. */
24 static void afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint);
25 static void afs_FreeDiscardedDCache(void);
26 static void afs_DiscardDCache(struct dcache *);
27 static void afs_FreeDCache(struct dcache *);
29 static afs_int32 afs_DCGetBucket(struct vcache *);
30 static void afs_DCAdjustSize(struct dcache *, afs_int32, afs_int32);
31 static void afs_DCMoveBucket(struct dcache *, afs_int32, afs_int32);
32 static void afs_DCSizeInit(void);
33 static afs_int32 afs_DCWhichBucket(afs_int32, afs_int32);
36 * --------------------- Exported definitions ---------------------
39 afs_int32 afs_blocksUsed_0; /*!< 1K blocks in cache - in theory is zero */
40 afs_int32 afs_blocksUsed_1; /*!< 1K blocks in cache */
41 afs_int32 afs_blocksUsed_2; /*!< 1K blocks in cache */
42 afs_int32 afs_pct1 = -1;
43 afs_int32 afs_pct2 = -1;
44 afs_uint32 afs_tpct1 = 0;
45 afs_uint32 afs_tpct2 = 0;
46 afs_uint32 splitdcache = 0;
48 afs_lock_t afs_xdcache; /*!< Lock: alloc new disk cache entries */
49 afs_int32 afs_freeDCList; /*!< Free list for disk cache entries */
50 afs_int32 afs_freeDCCount; /*!< Count of elts in freeDCList */
51 afs_int32 afs_discardDCList; /*!< Discarded disk cache entries */
52 afs_int32 afs_discardDCCount; /*!< Count of elts in discardDCList */
53 struct dcache *afs_freeDSList; /*!< Free list for disk slots */
54 struct dcache *afs_Initial_freeDSList; /*!< Initial list for above */
55 afs_dcache_id_t cacheInode; /*!< Inode for CacheItems file */
56 struct osi_file *afs_cacheInodep = 0; /*!< file for CacheItems inode */
57 struct afs_q afs_DLRU; /*!< dcache LRU */
58 afs_int32 afs_dhashsize = 1024;
59 afs_int32 *afs_dvhashTbl; /*!< Data cache hash table: hashed by FID + chunk number. */
60 afs_int32 *afs_dchashTbl; /*!< Data cache hash table: hashed by FID. */
61 afs_int32 *afs_dvnextTbl; /*!< Dcache hash table links */
62 afs_int32 *afs_dcnextTbl; /*!< Dcache hash table links */
63 struct dcache **afs_indexTable; /*!< Pointers to dcache entries */
64 afs_hyper_t *afs_indexTimes; /*!< Dcache entry Access times */
65 afs_int32 *afs_indexUnique; /*!< dcache entry Fid.Unique */
66 unsigned char *afs_indexFlags; /*!< (only one) Is there data there? */
67 afs_hyper_t afs_indexCounter; /*!< Fake time for marking index
69 afs_int32 afs_cacheFiles = 0; /*!< Size of afs_indexTable */
70 afs_int32 afs_cacheBlocks; /*!< 1K blocks in cache */
71 afs_int32 afs_cacheStats; /*!< Stat entries in cache */
72 afs_int32 afs_blocksUsed; /*!< Number of blocks in use */
73 afs_int32 afs_blocksDiscarded; /*!<Blocks freed but not truncated */
74 afs_int32 afs_fsfragsize = AFS_MIN_FRAGSIZE; /*!< Underlying Filesystem minimum unit
75 *of disk allocation usually 1K
76 *this value is (truefrag -1 ) to
77 *save a bunch of subtracts... */
78 #ifdef AFS_64BIT_CLIENT
79 #ifdef AFS_VM_RDWR_ENV
80 afs_size_t afs_vmMappingEnd; /* !< For large files (>= 2GB) the VM
81 * mapping an 32bit addressing machines
82 * can only be used below the 2 GB
83 * line. From this point upwards we
84 * must do direct I/O into the cache
85 * files. The value should be on a
87 #endif /* AFS_VM_RDWR_ENV */
88 #endif /* AFS_64BIT_CLIENT */
90 /* The following is used to ensure that new dcache's aren't obtained when
91 * the cache is nearly full.
93 int afs_WaitForCacheDrain = 0;
94 int afs_TruncateDaemonRunning = 0;
95 int afs_CacheTooFull = 0;
97 afs_int32 afs_dcentries; /*!< In-memory dcache entries */
100 int dcacheDisabled = 0;
102 struct afs_cacheOps afs_UfsCacheOps = {
103 #ifndef HAVE_STRUCT_LABEL_SUPPORT
116 .truncate = osi_UFSTruncate,
117 .fread = afs_osi_Read,
118 .fwrite = afs_osi_Write,
119 .close = osi_UFSClose,
120 .vread = afs_UFSRead,
121 .vwrite = afs_UFSWrite,
122 .GetDSlot = afs_UFSGetDSlot,
123 .GetVolSlot = afs_UFSGetVolSlot,
124 .HandleLink = afs_UFSHandleLink,
128 struct afs_cacheOps afs_MemCacheOps = {
129 #ifndef HAVE_STRUCT_LABEL_SUPPORT
131 afs_MemCacheTruncate,
141 .open = afs_MemCacheOpen,
142 .truncate = afs_MemCacheTruncate,
143 .fread = afs_MemReadBlk,
144 .fwrite = afs_MemWriteBlk,
145 .close = afs_MemCacheClose,
146 .vread = afs_MemRead,
147 .vwrite = afs_MemWrite,
148 .GetDSlot = afs_MemGetDSlot,
149 .GetVolSlot = afs_MemGetVolSlot,
150 .HandleLink = afs_MemHandleLink,
154 int cacheDiskType; /*Type of backing disk for cache */
155 struct afs_cacheOps *afs_cacheType;
158 * Where is this vcache's entry associated dcache located/
159 * \param avc The vcache entry.
160 * \return Bucket index:
165 afs_DCGetBucket(struct vcache *avc)
170 /* This should be replaced with some sort of user configurable function */
171 if (avc->f.states & CRO) {
173 } else if (avc->f.states & CBackup) {
183 * Readjust a dcache's size.
185 * \param adc The dcache to be adjusted.
186 * \param oldSize Old size for the dcache.
187 * \param newSize The new size to be adjusted to.
191 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
193 afs_int32 adjustSize = newSize - oldSize;
201 afs_blocksUsed_0 += adjustSize;
202 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
205 afs_blocksUsed_1 += adjustSize;
206 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
209 afs_blocksUsed_2 += adjustSize;
210 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
218 * Move a dcache from one bucket to another.
220 * \param adc Operate on this dcache.
221 * \param size Size in bucket (?).
222 * \param newBucket Destination bucket.
226 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
231 /* Substract size from old bucket. */
235 afs_blocksUsed_0 -= size;
238 afs_blocksUsed_1 -= size;
241 afs_blocksUsed_2 -= size;
245 /* Set new bucket and increase destination bucket size. */
246 adc->bucket = newBucket;
251 afs_blocksUsed_0 += size;
254 afs_blocksUsed_1 += size;
257 afs_blocksUsed_2 += size;
265 * Init split caches size.
270 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
279 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
284 afs_pct1 = afs_blocksUsed_1 / (afs_cacheBlocks / 100);
285 afs_pct2 = afs_blocksUsed_2 / (afs_cacheBlocks / 100);
287 /* Short cut: if we don't know about it, try to kill it */
288 if (phase < 2 && afs_blocksUsed_0)
291 if (afs_pct1 > afs_tpct1)
293 if (afs_pct2 > afs_tpct2)
295 return 0; /* unlikely */
300 * Warn about failing to store a file.
302 * \param acode Associated error code.
303 * \param avolume Volume involved.
304 * \param aflags How to handle the output:
305 * aflags & 1: Print out on console
306 * aflags & 2: Print out on controlling tty
308 * \note Environment: Call this from close call when vnodeops is RCS unlocked.
312 afs_StoreWarn(afs_int32 acode, afs_int32 avolume,
315 static char problem_fmt[] =
316 "afs: failed to store file in volume %d (%s)\n";
317 static char problem_fmt_w_error[] =
318 "afs: failed to store file in volume %d (error %d)\n";
319 static char netproblems[] = "network problems";
320 static char partfull[] = "partition full";
321 static char overquota[] = "over quota";
323 AFS_STATCNT(afs_StoreWarn);
329 afs_warn(problem_fmt, avolume, netproblems);
331 afs_warnuser(problem_fmt, avolume, netproblems);
332 } else if (acode == ENOSPC) {
337 afs_warn(problem_fmt, avolume, partfull);
339 afs_warnuser(problem_fmt, avolume, partfull);
342 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
343 * Instead ENOSPC will be sent...
345 if (acode == EDQUOT) {
350 afs_warn(problem_fmt, avolume, overquota);
352 afs_warnuser(problem_fmt, avolume, overquota);
360 afs_warn(problem_fmt_w_error, avolume, acode);
362 afs_warnuser(problem_fmt_w_error, avolume, acode);
367 * Try waking up truncation daemon, if it's worth it.
370 afs_MaybeWakeupTruncateDaemon(void)
372 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
373 afs_CacheTooFull = 1;
374 if (!afs_TruncateDaemonRunning)
375 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
376 } else if (!afs_TruncateDaemonRunning
377 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
378 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
385 * Keep statistics on run time for afs_CacheTruncateDaemon. This is a
386 * struct so we need only export one symbol for AIX.
388 static struct CTD_stats {
389 osi_timeval_t CTD_beforeSleep;
390 osi_timeval_t CTD_afterSleep;
391 osi_timeval_t CTD_sleepTime;
392 osi_timeval_t CTD_runTime;
396 u_int afs_min_cache = 0;
399 * Keeps the cache clean and free by truncating uneeded files, when used.
404 afs_CacheTruncateDaemon(void)
406 osi_timeval_t CTD_tmpTime;
410 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
412 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
414 osi_GetuTime(&CTD_stats.CTD_afterSleep);
415 afs_TruncateDaemonRunning = 1;
417 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
418 ObtainWriteLock(&afs_xdcache, 266);
419 if (afs_CacheTooFull) {
420 int space_needed, slots_needed;
421 /* if we get woken up, we should try to clean something out */
422 for (counter = 0; counter < 10; counter++) {
424 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
426 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
427 afs_GetDownD(slots_needed, &space_needed, 0);
428 if ((space_needed <= 0) && (slots_needed <= 0)) {
431 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
434 if (!afs_CacheIsTooFull())
435 afs_CacheTooFull = 0;
436 } /* end of cache cleanup */
437 ReleaseWriteLock(&afs_xdcache);
440 * This is a defensive check to try to avoid starving threads
441 * that may need the global lock so thay can help free some
442 * cache space. If this thread won't be sleeping or truncating
443 * any cache files then give up the global lock so other
444 * threads get a chance to run.
446 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
447 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
448 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
452 * This is where we free the discarded cache elements.
454 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
455 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
456 afs_FreeDiscardedDCache();
459 /* See if we need to continue to run. Someone may have
460 * signalled us while we were executing.
462 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
463 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
464 /* Collect statistics on truncate daemon. */
465 CTD_stats.CTD_nSleeps++;
466 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
467 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
468 CTD_stats.CTD_beforeSleep);
469 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
471 afs_TruncateDaemonRunning = 0;
472 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
473 afs_TruncateDaemonRunning = 1;
475 osi_GetuTime(&CTD_stats.CTD_afterSleep);
476 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
477 CTD_stats.CTD_afterSleep);
478 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
480 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
481 afs_termState = AFSOP_STOP_AFSDB;
482 afs_osi_Wakeup(&afs_termState);
490 * Make adjustment for the new size in the disk cache entry
492 * \note Major Assumptions Here:
493 * Assumes that frag size is an integral power of two, less one,
494 * and that this is a two's complement machine. I don't
495 * know of any filesystems which violate this assumption...
497 * \param adc Ptr to dcache entry.
498 * \param anewsize New size desired.
503 afs_AdjustSize(struct dcache *adc, afs_int32 newSize)
507 AFS_STATCNT(afs_AdjustSize);
509 adc->dflags |= DFEntryMod;
510 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
511 adc->f.chunkBytes = newSize;
514 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
515 afs_DCAdjustSize(adc, oldSize, newSize);
516 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
518 /* We're growing the file, wakeup the daemon */
519 afs_MaybeWakeupTruncateDaemon();
521 afs_blocksUsed += (newSize - oldSize);
522 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
527 * This routine is responsible for moving at least one entry (but up
528 * to some number of them) from the LRU queue to the free queue.
530 * \param anumber Number of entries that should ideally be moved.
531 * \param aneedSpace How much space we need (1K blocks);
534 * The anumber parameter is just a hint; at least one entry MUST be
535 * moved, or we'll panic. We must be called with afs_xdcache
536 * write-locked. We should try to satisfy both anumber and aneedspace,
537 * whichever is more demanding - need to do several things:
538 * 1. only grab up to anumber victims if aneedSpace <= 0, not
539 * the whole set of MAXATONCE.
540 * 2. dynamically choose MAXATONCE to reflect severity of
541 * demand: something like (*aneedSpace >> (logChunk - 9))
543 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
544 * indicates that the cache is not properly configured/tuned or
545 * something. We should be able to automatically correct that problem.
548 #define MAXATONCE 16 /* max we can obtain at once */
550 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
554 struct VenusFid *afid;
559 afs_uint32 victims[MAXATONCE];
560 struct dcache *victimDCs[MAXATONCE];
561 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
562 afs_uint32 victimPtr; /* next free item in victim arrays */
563 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
564 afs_uint32 maxVictimPtr; /* where it is */
567 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
571 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
572 vfslocked = VFS_LOCK_GIANT(afs_globalVFS);
575 AFS_STATCNT(afs_GetDownD);
577 if (CheckLock(&afs_xdcache) != -1)
578 osi_Panic("getdownd nolock");
579 /* decrement anumber first for all dudes in free list */
580 /* SHOULD always decrement anumber first, even if aneedSpace >0,
581 * because we should try to free space even if anumber <=0 */
582 if (!aneedSpace || *aneedSpace <= 0) {
583 anumber -= afs_freeDCCount;
585 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
586 VFS_UNLOCK_GIANT(vfslocked);
588 return; /* enough already free */
592 /* bounds check parameter */
593 if (anumber > MAXATONCE)
594 anumber = MAXATONCE; /* all we can do */
596 /* rewrite so phases include a better eligiblity for gc test*/
598 * The phase variable manages reclaims. Set to 0, the first pass,
599 * we don't reclaim active entries, or other than target bucket.
600 * Set to 1, we reclaim even active ones in target bucket.
601 * Set to 2, we reclaim any inactive one.
602 * Set to 3, we reclaim even active ones.
610 for (i = 0; i < afs_cacheFiles; i++)
611 /* turn off all flags */
612 afs_indexFlags[i] &= ~IFFlag;
614 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
615 /* find oldest entries for reclamation */
616 maxVictimPtr = victimPtr = 0;
617 hzero(maxVictimTime);
618 curbucket = afs_DCWhichBucket(phase, buckethint);
619 /* select victims from access time array */
620 for (i = 0; i < afs_cacheFiles; i++) {
621 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
622 /* skip if dirty or already free */
625 tdc = afs_indexTable[i];
626 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
628 /* Wrong bucket; can't use it! */
631 if (tdc && (tdc->refCount != 0)) {
632 /* Referenced; can't use it! */
635 hset(vtime, afs_indexTimes[i]);
637 /* if we've already looked at this one, skip it */
638 if (afs_indexFlags[i] & IFFlag)
641 if (victimPtr < MAXATONCE) {
642 /* if there's at least one free victim slot left */
643 victims[victimPtr] = i;
644 hset(victimTimes[victimPtr], vtime);
645 if (hcmp(vtime, maxVictimTime) > 0) {
646 hset(maxVictimTime, vtime);
647 maxVictimPtr = victimPtr;
650 } else if (hcmp(vtime, maxVictimTime) < 0) {
652 * We're older than youngest victim, so we replace at
655 /* find youngest (largest LRU) victim */
658 osi_Panic("getdownd local");
660 hset(victimTimes[j], vtime);
661 /* recompute maxVictimTime */
662 hset(maxVictimTime, vtime);
663 for (j = 0; j < victimPtr; j++)
664 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
665 hset(maxVictimTime, victimTimes[j]);
671 /* now really reclaim the victims */
672 j = 0; /* flag to track if we actually got any of the victims */
673 /* first, hold all the victims, since we're going to release the lock
674 * during the truncate operation.
676 for (i = 0; i < victimPtr; i++) {
677 tdc = afs_GetDSlot(victims[i], 0);
678 /* We got tdc->tlock(R) here */
679 if (tdc->refCount == 1)
683 ReleaseReadLock(&tdc->tlock);
687 for (i = 0; i < victimPtr; i++) {
688 /* q is first elt in dcache entry */
690 /* now, since we're dropping the afs_xdcache lock below, we
691 * have to verify, before proceeding, that there are no other
692 * references to this dcache entry, even now. Note that we
693 * compare with 1, since we bumped it above when we called
694 * afs_GetDSlot to preserve the entry's identity.
696 if (tdc && tdc->refCount == 1) {
697 unsigned char chunkFlags;
698 afs_size_t tchunkoffset = 0;
700 /* xdcache is lower than the xvcache lock */
701 ReleaseWriteLock(&afs_xdcache);
702 ObtainReadLock(&afs_xvcache);
703 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
704 ReleaseReadLock(&afs_xvcache);
705 ObtainWriteLock(&afs_xdcache, 527);
707 if (tdc->refCount > 1)
710 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
711 chunkFlags = afs_indexFlags[tdc->index];
712 if (((phase & 1) == 0) && osi_Active(tvc))
714 if (((phase & 1) == 1) && osi_Active(tvc)
715 && (tvc->f.states & CDCLock)
716 && (chunkFlags & IFAnyPages))
718 if (chunkFlags & IFDataMod)
720 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
721 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
722 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
723 ICL_HANDLE_OFFSET(tchunkoffset));
725 #if defined(AFS_SUN5_ENV)
727 * Now we try to invalidate pages. We do this only for
728 * Solaris. For other platforms, it's OK to recycle a
729 * dcache entry out from under a page, because the strategy
730 * function can call afs_GetDCache().
732 if (!skip && (chunkFlags & IFAnyPages)) {
735 ReleaseWriteLock(&afs_xdcache);
736 ObtainWriteLock(&tvc->vlock, 543);
737 if (tvc->multiPage) {
741 /* block locking pages */
742 tvc->vstates |= VPageCleaning;
743 /* block getting new pages */
745 ReleaseWriteLock(&tvc->vlock);
746 /* One last recheck */
747 ObtainWriteLock(&afs_xdcache, 333);
748 chunkFlags = afs_indexFlags[tdc->index];
749 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
750 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
751 && (chunkFlags & IFAnyPages))) {
753 ReleaseWriteLock(&afs_xdcache);
756 ReleaseWriteLock(&afs_xdcache);
758 code = osi_VM_GetDownD(tvc, tdc);
760 ObtainWriteLock(&afs_xdcache, 269);
761 /* we actually removed all pages, clean and dirty */
763 afs_indexFlags[tdc->index] &=
764 ~(IFDirtyPages | IFAnyPages);
767 ReleaseWriteLock(&afs_xdcache);
769 ObtainWriteLock(&tvc->vlock, 544);
770 if (--tvc->activeV == 0
771 && (tvc->vstates & VRevokeWait)) {
772 tvc->vstates &= ~VRevokeWait;
773 afs_osi_Wakeup((char *)&tvc->vstates);
776 if (tvc->vstates & VPageCleaning) {
777 tvc->vstates &= ~VPageCleaning;
778 afs_osi_Wakeup((char *)&tvc->vstates);
781 ReleaseWriteLock(&tvc->vlock);
783 #endif /* AFS_SUN5_ENV */
785 ReleaseWriteLock(&afs_xdcache);
788 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
789 ObtainWriteLock(&afs_xdcache, 528);
790 if (afs_indexFlags[tdc->index] &
791 (IFDataMod | IFDirtyPages | IFAnyPages))
793 if (tdc->refCount > 1)
796 #if defined(AFS_SUN5_ENV)
798 /* no vnode, so IFDirtyPages is spurious (we don't
799 * sweep dcaches on vnode recycling, so we can have
800 * DIRTYPAGES set even when all pages are gone). Just
802 * Hold vcache lock to prevent vnode from being
803 * created while we're clearing IFDirtyPages.
805 afs_indexFlags[tdc->index] &=
806 ~(IFDirtyPages | IFAnyPages);
810 /* skip this guy and mark him as recently used */
811 afs_indexFlags[tdc->index] |= IFFlag;
812 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
813 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
814 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
815 ICL_HANDLE_OFFSET(tchunkoffset));
817 /* flush this dude from the data cache and reclaim;
818 * first, make sure no one will care that we damage
819 * it, by removing it from all hash tables. Then,
820 * melt it down for parts. Note that any concurrent
821 * (new possibility!) calls to GetDownD won't touch
822 * this guy because his reference count is > 0. */
823 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
824 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
825 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
826 ICL_HANDLE_OFFSET(tchunkoffset));
827 AFS_STATCNT(afs_gget);
828 afs_HashOutDCache(tdc, 1);
829 if (tdc->f.chunkBytes != 0) {
833 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
838 afs_DiscardDCache(tdc);
843 j = 1; /* we reclaimed at least one victim */
847 } /* end of for victims loop */
850 /* Phase is 0 and no one was found, so try phase 1 (ignore
851 * osi_Active flag) */
854 for (i = 0; i < afs_cacheFiles; i++)
855 /* turn off all flags */
856 afs_indexFlags[i] &= ~IFFlag;
859 /* found no one in phases 0-5, we're hosed */
863 } /* big while loop */
865 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
866 VFS_UNLOCK_GIANT(vfslocked);
875 * Remove adc from any hash tables that would allow it to be located
876 * again by afs_FindDCache or afs_GetDCache.
878 * \param adc Pointer to dcache entry to remove from hash tables.
880 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
884 afs_HashOutDCache(struct dcache *adc, int zap)
888 AFS_STATCNT(afs_glink);
890 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
892 /* if this guy is in the hash table, pull him out */
893 if (adc->f.fid.Fid.Volume != 0) {
894 /* remove entry from first hash chains */
895 i = DCHash(&adc->f.fid, adc->f.chunk);
896 us = afs_dchashTbl[i];
897 if (us == adc->index) {
898 /* first dude in the list */
899 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
901 /* somewhere on the chain */
902 while (us != NULLIDX) {
903 if (afs_dcnextTbl[us] == adc->index) {
904 /* found item pointing at the one to delete */
905 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
908 us = afs_dcnextTbl[us];
911 osi_Panic("dcache hc");
913 /* remove entry from *other* hash chain */
914 i = DVHash(&adc->f.fid);
915 us = afs_dvhashTbl[i];
916 if (us == adc->index) {
917 /* first dude in the list */
918 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
920 /* somewhere on the chain */
921 while (us != NULLIDX) {
922 if (afs_dvnextTbl[us] == adc->index) {
923 /* found item pointing at the one to delete */
924 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
927 us = afs_dvnextTbl[us];
930 osi_Panic("dcache hv");
935 /* prevent entry from being found on a reboot (it is already out of
936 * the hash table, but after a crash, we just look at fid fields of
937 * stable (old) entries).
939 adc->f.fid.Fid.Volume = 0; /* invalid */
941 /* mark entry as modified */
942 adc->dflags |= DFEntryMod;
947 } /*afs_HashOutDCache */
950 * Flush the given dcache entry, pulling it from hash chains
951 * and truncating the associated cache file.
953 * \param adc Ptr to dcache entry to flush.
956 * This routine must be called with the afs_xdcache lock held
960 afs_FlushDCache(struct dcache *adc)
962 AFS_STATCNT(afs_FlushDCache);
964 * Bump the number of cache files flushed.
966 afs_stats_cmperf.cacheFlushes++;
968 /* remove from all hash tables */
969 afs_HashOutDCache(adc, 1);
971 /* Free its space; special case null operation, since truncate operation
972 * in UFS is slow even in this case, and this allows us to pre-truncate
973 * these files at more convenient times with fewer locks set
974 * (see afs_GetDownD).
976 if (adc->f.chunkBytes != 0) {
977 afs_DiscardDCache(adc);
978 afs_MaybeWakeupTruncateDaemon();
983 if (afs_WaitForCacheDrain) {
984 if (afs_blocksUsed <=
985 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
986 afs_WaitForCacheDrain = 0;
987 afs_osi_Wakeup(&afs_WaitForCacheDrain);
990 } /*afs_FlushDCache */
994 * Put a dcache entry on the free dcache entry list.
996 * \param adc dcache entry to free.
998 * \note Environment: called with afs_xdcache lock write-locked.
1001 afs_FreeDCache(struct dcache *adc)
1003 /* Thread on free list, update free list count and mark entry as
1004 * freed in its indexFlags element. Also, ensure DCache entry gets
1005 * written out (set DFEntryMod).
1008 afs_dvnextTbl[adc->index] = afs_freeDCList;
1009 afs_freeDCList = adc->index;
1011 afs_indexFlags[adc->index] |= IFFree;
1012 adc->dflags |= DFEntryMod;
1014 if (afs_WaitForCacheDrain) {
1015 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1016 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1017 afs_WaitForCacheDrain = 0;
1018 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1021 } /* afs_FreeDCache */
1024 * Discard the cache element by moving it to the discardDCList.
1025 * This puts the cache element into a quasi-freed state, where
1026 * the space may be reused, but the file has not been truncated.
1028 * \note Major Assumptions Here:
1029 * Assumes that frag size is an integral power of two, less one,
1030 * and that this is a two's complement machine. I don't
1031 * know of any filesystems which violate this assumption...
1033 * \param adr Ptr to dcache entry.
1035 * \note Environment:
1036 * Must be called with afs_xdcache write-locked.
1040 afs_DiscardDCache(struct dcache *adc)
1044 AFS_STATCNT(afs_DiscardDCache);
1046 osi_Assert(adc->refCount == 1);
1048 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1049 afs_blocksDiscarded += size;
1050 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1052 afs_dvnextTbl[adc->index] = afs_discardDCList;
1053 afs_discardDCList = adc->index;
1054 afs_discardDCCount++;
1056 adc->f.fid.Fid.Volume = 0;
1057 adc->dflags |= DFEntryMod;
1058 afs_indexFlags[adc->index] |= IFDiscarded;
1060 if (afs_WaitForCacheDrain) {
1061 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1062 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1063 afs_WaitForCacheDrain = 0;
1064 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1068 } /*afs_DiscardDCache */
1071 * Free the next element on the list of discarded cache elements.
1074 afs_FreeDiscardedDCache(void)
1077 struct osi_file *tfile;
1080 AFS_STATCNT(afs_FreeDiscardedDCache);
1082 ObtainWriteLock(&afs_xdcache, 510);
1083 if (!afs_blocksDiscarded) {
1084 ReleaseWriteLock(&afs_xdcache);
1089 * Get an entry from the list of discarded cache elements
1091 tdc = afs_GetDSlot(afs_discardDCList, 0);
1092 osi_Assert(tdc->refCount == 1);
1093 ReleaseReadLock(&tdc->tlock);
1095 afs_discardDCList = afs_dvnextTbl[tdc->index];
1096 afs_dvnextTbl[tdc->index] = NULLIDX;
1097 afs_discardDCCount--;
1098 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1099 afs_blocksDiscarded -= size;
1100 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1101 /* We can lock because we just took it off the free list */
1102 ObtainWriteLock(&tdc->lock, 626);
1103 ReleaseWriteLock(&afs_xdcache);
1106 * Truncate the element to reclaim its space
1108 tfile = afs_CFileOpen(&tdc->f.inode);
1109 afs_CFileTruncate(tfile, 0);
1110 afs_CFileClose(tfile);
1111 afs_AdjustSize(tdc, 0);
1112 afs_DCMoveBucket(tdc, 0, 0);
1115 * Free the element we just truncated
1117 ObtainWriteLock(&afs_xdcache, 511);
1118 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1119 afs_FreeDCache(tdc);
1120 tdc->f.states &= ~(DRO|DBackup|DRW);
1121 ReleaseWriteLock(&tdc->lock);
1123 ReleaseWriteLock(&afs_xdcache);
1127 * Free as many entries from the list of discarded cache elements
1128 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1133 afs_MaybeFreeDiscardedDCache(void)
1136 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1138 while (afs_blocksDiscarded
1139 && (afs_blocksUsed >
1140 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1141 afs_FreeDiscardedDCache();
1147 * Try to free up a certain number of disk slots.
1149 * \param anumber Targeted number of disk slots to free up.
1151 * \note Environment:
1152 * Must be called with afs_xdcache write-locked.
1156 afs_GetDownDSlot(int anumber)
1158 struct afs_q *tq, *nq;
1163 AFS_STATCNT(afs_GetDownDSlot);
1164 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1165 osi_Panic("diskless getdowndslot");
1167 if (CheckLock(&afs_xdcache) != -1)
1168 osi_Panic("getdowndslot nolock");
1170 /* decrement anumber first for all dudes in free list */
1171 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1174 return; /* enough already free */
1176 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1178 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1179 nq = QPrev(tq); /* in case we remove it */
1180 if (tdc->refCount == 0) {
1181 if ((ix = tdc->index) == NULLIDX)
1182 osi_Panic("getdowndslot");
1183 /* pull the entry out of the lruq and put it on the free list */
1184 QRemove(&tdc->lruq);
1186 /* write-through if modified */
1187 if (tdc->dflags & DFEntryMod) {
1188 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1190 * ask proxy to do this for us - we don't have the stack space
1192 while (tdc->dflags & DFEntryMod) {
1195 s = SPLOCK(afs_sgibklock);
1196 if (afs_sgibklist == NULL) {
1197 /* if slot is free, grab it. */
1198 afs_sgibklist = tdc;
1199 SV_SIGNAL(&afs_sgibksync);
1201 /* wait for daemon to (start, then) finish. */
1202 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1206 tdc->dflags &= ~DFEntryMod;
1207 afs_WriteDCache(tdc, 1);
1211 /* finally put the entry in the free list */
1212 afs_indexTable[ix] = NULL;
1213 afs_indexFlags[ix] &= ~IFEverUsed;
1214 tdc->index = NULLIDX;
1215 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1216 afs_freeDSList = tdc;
1220 } /*afs_GetDownDSlot */
1227 * Increment the reference count on a disk cache entry,
1228 * which already has a non-zero refcount. In order to
1229 * increment the refcount of a zero-reference entry, you
1230 * have to hold afs_xdcache.
1233 * adc : Pointer to the dcache entry to increment.
1236 * Nothing interesting.
1239 afs_RefDCache(struct dcache *adc)
1241 ObtainWriteLock(&adc->tlock, 627);
1242 if (adc->refCount < 0)
1243 osi_Panic("RefDCache: negative refcount");
1245 ReleaseWriteLock(&adc->tlock);
1254 * Decrement the reference count on a disk cache entry.
1257 * ad : Ptr to the dcache entry to decrement.
1260 * Nothing interesting.
1263 afs_PutDCache(struct dcache *adc)
1265 AFS_STATCNT(afs_PutDCache);
1266 ObtainWriteLock(&adc->tlock, 276);
1267 if (adc->refCount <= 0)
1268 osi_Panic("putdcache");
1270 ReleaseWriteLock(&adc->tlock);
1279 * Try to discard all data associated with this file from the
1283 * avc : Pointer to the cache info for the file.
1286 * Both pvnLock and lock are write held.
1289 afs_TryToSmush(struct vcache *avc, afs_ucred_t *acred, int sync)
1294 AFS_STATCNT(afs_TryToSmush);
1295 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1296 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1297 sync = 1; /* XX Temp testing XX */
1299 #if defined(AFS_SUN5_ENV)
1300 ObtainWriteLock(&avc->vlock, 573);
1301 avc->activeV++; /* block new getpages */
1302 ReleaseWriteLock(&avc->vlock);
1305 /* Flush VM pages */
1306 osi_VM_TryToSmush(avc, acred, sync);
1309 * Get the hash chain containing all dce's for this fid
1311 i = DVHash(&avc->f.fid);
1312 ObtainWriteLock(&afs_xdcache, 277);
1313 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1314 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1315 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1316 int releaseTlock = 1;
1317 tdc = afs_GetDSlot(index, NULL);
1318 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1320 if ((afs_indexFlags[index] & IFDataMod) == 0
1321 && tdc->refCount == 1) {
1322 ReleaseReadLock(&tdc->tlock);
1324 afs_FlushDCache(tdc);
1327 afs_indexTable[index] = 0;
1330 ReleaseReadLock(&tdc->tlock);
1334 #if defined(AFS_SUN5_ENV)
1335 ObtainWriteLock(&avc->vlock, 545);
1336 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1337 avc->vstates &= ~VRevokeWait;
1338 afs_osi_Wakeup((char *)&avc->vstates);
1340 ReleaseWriteLock(&avc->vlock);
1342 ReleaseWriteLock(&afs_xdcache);
1344 * It's treated like a callback so that when we do lookups we'll
1345 * invalidate the unique bit if any
1346 * trytoSmush occured during the lookup call
1352 * afs_DCacheMissingChunks
1355 * Given the cached info for a file, return the number of chunks that
1356 * are not available from the dcache.
1359 * avc: Pointer to the (held) vcache entry to look in.
1362 * The number of chunks which are not currently cached.
1365 * The vcache entry is held upon entry.
1369 afs_DCacheMissingChunks(struct vcache *avc)
1372 afs_size_t totalLength = 0;
1373 afs_uint32 totalChunks = 0;
1376 totalLength = avc->f.m.Length;
1377 if (avc->f.truncPos < totalLength)
1378 totalLength = avc->f.truncPos;
1380 /* Length is 0, no chunk missing. */
1381 if (totalLength == 0)
1384 /* If totalLength is a multiple of chunksize, the last byte appears
1385 * as being part of the next chunk, which does not exist.
1386 * Decrementing totalLength by one fixes that.
1389 totalChunks = (AFS_CHUNK(totalLength) + 1);
1391 /* If we're a directory, we only ever have one chunk, regardless of
1392 * the size of the dir.
1394 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1398 printf("Should have %d chunks for %u bytes\n",
1399 totalChunks, (totalLength + 1));
1401 i = DVHash(&avc->f.fid);
1402 ObtainWriteLock(&afs_xdcache, 1001);
1403 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1404 i = afs_dvnextTbl[index];
1405 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1406 tdc = afs_GetDSlot(index, NULL);
1407 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1410 ReleaseReadLock(&tdc->tlock);
1414 ReleaseWriteLock(&afs_xdcache);
1416 /*printf("Missing %d chunks\n", totalChunks);*/
1418 return (totalChunks);
1425 * Given the cached info for a file and a byte offset into the
1426 * file, make sure the dcache entry for that file and containing
1427 * the given byte is available, returning it to our caller.
1430 * avc : Pointer to the (held) vcache entry to look in.
1431 * abyte : Which byte we want to get to.
1434 * Pointer to the dcache entry covering the file & desired byte,
1435 * or NULL if not found.
1438 * The vcache entry is held upon entry.
1442 afs_FindDCache(struct vcache *avc, afs_size_t abyte)
1446 struct dcache *tdc = NULL;
1448 AFS_STATCNT(afs_FindDCache);
1449 chunk = AFS_CHUNK(abyte);
1452 * Hash on the [fid, chunk] and get the corresponding dcache index
1453 * after write-locking the dcache.
1455 i = DCHash(&avc->f.fid, chunk);
1456 ObtainWriteLock(&afs_xdcache, 278);
1457 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1458 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1459 tdc = afs_GetDSlot(index, NULL);
1460 ReleaseReadLock(&tdc->tlock);
1461 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1462 break; /* leaving refCount high for caller */
1466 index = afs_dcnextTbl[index];
1468 if (index != NULLIDX) {
1469 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1470 hadd32(afs_indexCounter, 1);
1471 ReleaseWriteLock(&afs_xdcache);
1474 ReleaseWriteLock(&afs_xdcache);
1476 } /*afs_FindDCache */
1480 * Get a fresh dcache from the free or discarded list.
1482 * \param avc Who's dcache is this going to be?
1483 * \param chunk The position where it will be placed in.
1484 * \param lock How are locks held.
1485 * \param ashFid If this dcache going to be used for a shadow dir,
1488 * \note Required locks:
1490 * - avc (R if (lock & 1) set and W otherwise)
1491 * \note It write locks the new dcache. The caller must unlock it.
1493 * \return The new dcache.
1496 afs_AllocDCache(struct vcache *avc, afs_int32 chunk, afs_int32 lock,
1497 struct VenusFid *ashFid)
1499 struct dcache *tdc = NULL;
1500 afs_uint32 size = 0;
1501 struct osi_file *file;
1503 if (afs_discardDCList == NULLIDX
1504 || ((lock & 2) && afs_freeDCList != NULLIDX)) {
1506 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1507 tdc = afs_GetDSlot(afs_freeDCList, 0);
1508 osi_Assert(tdc->refCount == 1);
1509 ReleaseReadLock(&tdc->tlock);
1510 ObtainWriteLock(&tdc->lock, 604);
1511 afs_freeDCList = afs_dvnextTbl[tdc->index];
1514 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1515 tdc = afs_GetDSlot(afs_discardDCList, 0);
1516 osi_Assert(tdc->refCount == 1);
1517 ReleaseReadLock(&tdc->tlock);
1518 ObtainWriteLock(&tdc->lock, 605);
1519 afs_discardDCList = afs_dvnextTbl[tdc->index];
1520 afs_discardDCCount--;
1522 ((tdc->f.chunkBytes +
1523 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1524 tdc->f.states &= ~(DRO|DBackup|DRW);
1525 afs_DCMoveBucket(tdc, size, 0);
1526 afs_blocksDiscarded -= size;
1527 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1529 /* Truncate the chunk so zeroes get filled properly */
1530 file = afs_CFileOpen(&tdc->f.inode);
1531 afs_CFileTruncate(file, 0);
1532 afs_CFileClose(file);
1533 afs_AdjustSize(tdc, 0);
1539 * avc->lock(R) if setLocks
1540 * avc->lock(W) if !setLocks
1546 * Fill in the newly-allocated dcache record.
1548 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1550 /* Use shadow fid if provided. */
1551 tdc->f.fid = *ashFid;
1553 /* Use normal vcache's fid otherwise. */
1554 tdc->f.fid = avc->f.fid;
1555 if (avc->f.states & CRO)
1556 tdc->f.states = DRO;
1557 else if (avc->f.states & CBackup)
1558 tdc->f.states = DBackup;
1560 tdc->f.states = DRW;
1561 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1562 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1564 hones(tdc->f.versionNo); /* invalid value */
1565 tdc->f.chunk = chunk;
1566 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1568 if (tdc->lruq.prev == &tdc->lruq)
1569 osi_Panic("lruq 1");
1578 * This function is called to obtain a reference to data stored in
1579 * the disk cache, locating a chunk of data containing the desired
1580 * byte and returning a reference to the disk cache entry, with its
1581 * reference count incremented.
1585 * avc : Ptr to a vcache entry (unlocked)
1586 * abyte : Byte position in the file desired
1587 * areq : Request structure identifying the requesting user.
1588 * aflags : Settings as follows:
1590 * 2 : Return after creating entry.
1591 * 4 : called from afs_vnop_write.c
1592 * *alen contains length of data to be written.
1594 * aoffset : Set to the offset within the chunk where the resident
1596 * alen : Set to the number of bytes of data after the desired
1597 * byte (including the byte itself) which can be read
1601 * The vcache entry pointed to by avc is unlocked upon entry.
1605 * Update the vnode-to-dcache hint if we can get the vnode lock
1606 * right away. Assumes dcache entry is at least read-locked.
1609 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1611 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1612 if (hsame(v->f.m.DataVersion, d->f.versionNo) && v->callback)
1615 ReleaseWriteLock(&v->lock);
1619 /* avc - Write-locked unless aflags & 1 */
1621 afs_GetDCache(struct vcache *avc, afs_size_t abyte,
1622 struct vrequest *areq, afs_size_t * aoffset,
1623 afs_size_t * alen, int aflags)
1625 afs_int32 i, code, shortcut;
1626 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1627 afs_int32 adjustsize = 0;
1633 afs_size_t maxGoodLength; /* amount of good data at server */
1634 afs_size_t Position = 0;
1635 afs_int32 size, tlen; /* size of segment to transfer */
1636 struct afs_FetchOutput *tsmall = 0;
1638 struct osi_file *file;
1639 struct afs_conn *tc;
1641 struct server *newCallback = NULL;
1642 char setNewCallback;
1643 char setVcacheStatus;
1644 char doVcacheUpdate;
1646 int doAdjustSize = 0;
1647 int doReallyAdjustSize = 0;
1648 int overWriteWholeChunk = 0;
1651 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1652 int fromReplica; /*Are we reading from a replica? */
1653 int numFetchLoops; /*# times around the fetch/analyze loop */
1654 #endif /* AFS_NOSTATS */
1656 AFS_STATCNT(afs_GetDCache);
1660 setLocks = aflags & 1;
1663 * Determine the chunk number and offset within the chunk corresponding
1664 * to the desired byte.
1666 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1669 chunk = AFS_CHUNK(abyte);
1672 /* come back to here if we waited for the cache to drain. */
1675 setNewCallback = setVcacheStatus = 0;
1679 ObtainWriteLock(&avc->lock, 616);
1681 ObtainReadLock(&avc->lock);
1686 * avc->lock(R) if setLocks && !slowPass
1687 * avc->lock(W) if !setLocks || slowPass
1692 /* check hints first! (might could use bcmp or some such...) */
1693 if ((tdc = avc->dchint)) {
1697 * The locking order between afs_xdcache and dcache lock matters.
1698 * The hint dcache entry could be anywhere, even on the free list.
1699 * Locking afs_xdcache ensures that noone is trying to pull dcache
1700 * entries from the free list, and thereby assuming them to be not
1701 * referenced and not locked.
1703 ObtainReadLock(&afs_xdcache);
1704 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1706 if (dcLocked && (tdc->index != NULLIDX)
1707 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
1708 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1709 /* got the right one. It might not be the right version, and it
1710 * might be fetching, but it's the right dcache entry.
1712 /* All this code should be integrated better with what follows:
1713 * I can save a good bit more time under a write lock if I do..
1715 ObtainWriteLock(&tdc->tlock, 603);
1717 ReleaseWriteLock(&tdc->tlock);
1719 ReleaseReadLock(&afs_xdcache);
1722 if (hsame(tdc->f.versionNo, avc->f.m.DataVersion)
1723 && !(tdc->dflags & DFFetching)) {
1725 afs_stats_cmperf.dcacheHits++;
1726 ObtainWriteLock(&afs_xdcache, 559);
1727 QRemove(&tdc->lruq);
1728 QAdd(&afs_DLRU, &tdc->lruq);
1729 ReleaseWriteLock(&afs_xdcache);
1732 * avc->lock(R) if setLocks && !slowPass
1733 * avc->lock(W) if !setLocks || slowPass
1740 ReleaseSharedLock(&tdc->lock);
1741 ReleaseReadLock(&afs_xdcache);
1749 * avc->lock(R) if setLocks && !slowPass
1750 * avc->lock(W) if !setLocks || slowPass
1751 * tdc->lock(S) if tdc
1754 if (!tdc) { /* If the hint wasn't the right dcache entry */
1756 * Hash on the [fid, chunk] and get the corresponding dcache index
1757 * after write-locking the dcache.
1762 * avc->lock(R) if setLocks && !slowPass
1763 * avc->lock(W) if !setLocks || slowPass
1766 i = DCHash(&avc->f.fid, chunk);
1767 /* check to make sure our space is fine */
1768 afs_MaybeWakeupTruncateDaemon();
1770 ObtainWriteLock(&afs_xdcache, 280);
1772 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1773 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1774 tdc = afs_GetDSlot(index, NULL);
1775 ReleaseReadLock(&tdc->tlock);
1778 * avc->lock(R) if setLocks && !slowPass
1779 * avc->lock(W) if !setLocks || slowPass
1782 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1783 /* Move it up in the beginning of the list */
1784 if (afs_dchashTbl[i] != index) {
1785 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1786 afs_dcnextTbl[index] = afs_dchashTbl[i];
1787 afs_dchashTbl[i] = index;
1789 ReleaseWriteLock(&afs_xdcache);
1790 ObtainSharedLock(&tdc->lock, 606);
1791 break; /* leaving refCount high for caller */
1797 index = afs_dcnextTbl[index];
1801 * If we didn't find the entry, we'll create one.
1803 if (index == NULLIDX) {
1806 * avc->lock(R) if setLocks
1807 * avc->lock(W) if !setLocks
1810 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1811 avc, ICL_TYPE_INT32, chunk);
1813 /* Make sure there is a free dcache entry for us to use */
1814 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1817 avc->f.states |= CDCLock;
1818 /* just need slots */
1819 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1821 avc->f.states &= ~CDCLock;
1822 if (afs_discardDCList != NULLIDX
1823 || afs_freeDCList != NULLIDX)
1825 /* If we can't get space for 5 mins we give up and panic */
1826 if (++downDCount > 300) {
1827 osi_Panic("getdcache");
1829 ReleaseWriteLock(&afs_xdcache);
1832 * avc->lock(R) if setLocks
1833 * avc->lock(W) if !setLocks
1835 afs_osi_Wait(1000, 0, 0);
1840 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
1843 * Now add to the two hash chains - note that i is still set
1844 * from the above DCHash call.
1846 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1847 afs_dchashTbl[i] = tdc->index;
1848 i = DVHash(&avc->f.fid);
1849 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1850 afs_dvhashTbl[i] = tdc->index;
1851 tdc->dflags = DFEntryMod;
1853 afs_MaybeWakeupTruncateDaemon();
1854 ReleaseWriteLock(&afs_xdcache);
1855 ConvertWToSLock(&tdc->lock);
1860 /* vcache->dcache hint failed */
1863 * avc->lock(R) if setLocks && !slowPass
1864 * avc->lock(W) if !setLocks || slowPass
1867 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1868 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
1869 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
1870 hgetlo(avc->f.m.DataVersion));
1872 * Here we have the entry in tdc, with its refCount incremented.
1873 * Note: we don't use the S-lock on avc; it costs concurrency when
1874 * storing a file back to the server.
1878 * Not a newly created file so we need to check the file's length and
1879 * compare data versions since someone could have changed the data or we're
1880 * reading a file written elsewhere. We only want to bypass doing no-op
1881 * read rpcs on newly created files (dv of 0) since only then we guarantee
1882 * that this chunk's data hasn't been filled by another client.
1884 size = AFS_CHUNKSIZE(abyte);
1885 if (aflags & 4) /* called from write */
1887 else /* called from read */
1888 tlen = tdc->validPos - abyte;
1889 Position = AFS_CHUNKTOBASE(chunk);
1890 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
1891 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
1892 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
1893 ICL_HANDLE_OFFSET(Position));
1894 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
1896 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
1897 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
1898 overWriteWholeChunk = 1;
1899 if (doAdjustSize || overWriteWholeChunk) {
1900 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1902 #ifdef AFS_SGI64_ENV
1905 #else /* AFS_SGI64_ENV */
1908 #endif /* AFS_SGI64_ENV */
1909 #else /* AFS_SGI_ENV */
1912 #endif /* AFS_SGI_ENV */
1913 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
1914 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1915 #if defined(AFS_SUN5_ENV)
1916 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
1918 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
1920 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1921 !hsame(avc->f.m.DataVersion, tdc->f.versionNo))
1922 doReallyAdjustSize = 1;
1924 if (doReallyAdjustSize || overWriteWholeChunk) {
1925 /* no data in file to read at this position */
1926 UpgradeSToWLock(&tdc->lock, 607);
1927 file = afs_CFileOpen(&tdc->f.inode);
1928 afs_CFileTruncate(file, 0);
1929 afs_CFileClose(file);
1930 afs_AdjustSize(tdc, 0);
1931 hset(tdc->f.versionNo, avc->f.m.DataVersion);
1932 tdc->dflags |= DFEntryMod;
1934 ConvertWToSLock(&tdc->lock);
1939 * We must read in the whole chunk if the version number doesn't
1943 /* don't need data, just a unique dcache entry */
1944 ObtainWriteLock(&afs_xdcache, 608);
1945 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1946 hadd32(afs_indexCounter, 1);
1947 ReleaseWriteLock(&afs_xdcache);
1949 updateV2DC(setLocks, avc, tdc, 553);
1950 if (vType(avc) == VDIR)
1953 *aoffset = AFS_CHUNKOFFSET(abyte);
1954 if (tdc->validPos < abyte)
1955 *alen = (afs_size_t) 0;
1957 *alen = tdc->validPos - abyte;
1958 ReleaseSharedLock(&tdc->lock);
1961 ReleaseWriteLock(&avc->lock);
1963 ReleaseReadLock(&avc->lock);
1965 return tdc; /* check if we're done */
1970 * avc->lock(R) if setLocks && !slowPass
1971 * avc->lock(W) if !setLocks || slowPass
1974 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
1976 setNewCallback = setVcacheStatus = 0;
1980 * avc->lock(R) if setLocks && !slowPass
1981 * avc->lock(W) if !setLocks || slowPass
1984 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
1986 * Version number mismatch.
1989 * If we are disconnected, then we can't do much of anything
1990 * because the data doesn't match the file.
1992 if (AFS_IS_DISCONNECTED) {
1993 ReleaseSharedLock(&tdc->lock);
1996 ReleaseWriteLock(&avc->lock);
1998 ReleaseReadLock(&avc->lock);
2000 /* Flush the Dcache */
2005 UpgradeSToWLock(&tdc->lock, 609);
2008 * If data ever existed for this vnode, and this is a text object,
2009 * do some clearing. Now, you'd think you need only do the flush
2010 * when VTEXT is on, but VTEXT is turned off when the text object
2011 * is freed, while pages are left lying around in memory marked
2012 * with this vnode. If we would reactivate (create a new text
2013 * object from) this vnode, we could easily stumble upon some of
2014 * these old pages in pagein. So, we always flush these guys.
2015 * Sun has a wonderful lack of useful invariants in this system.
2017 * avc->flushDV is the data version # of the file at the last text
2018 * flush. Clearly, at least, we don't have to flush the file more
2019 * often than it changes
2021 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2023 * By here, the cache entry is always write-locked. We can
2024 * deadlock if we call osi_Flush with the cache entry locked...
2025 * Unlock the dcache too.
2027 ReleaseWriteLock(&tdc->lock);
2028 if (setLocks && !slowPass)
2029 ReleaseReadLock(&avc->lock);
2031 ReleaseWriteLock(&avc->lock);
2035 * Call osi_FlushPages in open, read/write, and map, since it
2036 * is too hard here to figure out if we should lock the
2039 if (setLocks && !slowPass)
2040 ObtainReadLock(&avc->lock);
2042 ObtainWriteLock(&avc->lock, 66);
2043 ObtainWriteLock(&tdc->lock, 610);
2048 * avc->lock(R) if setLocks && !slowPass
2049 * avc->lock(W) if !setLocks || slowPass
2053 /* Watch for standard race condition around osi_FlushText */
2054 if (hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
2055 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2056 afs_stats_cmperf.dcacheHits++;
2057 ConvertWToSLock(&tdc->lock);
2061 /* Sleep here when cache needs to be drained. */
2062 if (setLocks && !slowPass
2063 && (afs_blocksUsed >
2064 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2065 /* Make sure truncate daemon is running */
2066 afs_MaybeWakeupTruncateDaemon();
2067 ObtainWriteLock(&tdc->tlock, 614);
2068 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2069 ReleaseWriteLock(&tdc->tlock);
2070 ReleaseWriteLock(&tdc->lock);
2071 ReleaseReadLock(&avc->lock);
2072 while ((afs_blocksUsed - afs_blocksDiscarded) >
2073 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2074 afs_WaitForCacheDrain = 1;
2075 afs_osi_Sleep(&afs_WaitForCacheDrain);
2077 afs_MaybeFreeDiscardedDCache();
2078 /* need to check if someone else got the chunk first. */
2079 goto RetryGetDCache;
2082 /* Do not fetch data beyond truncPos. */
2083 maxGoodLength = avc->f.m.Length;
2084 if (avc->f.truncPos < maxGoodLength)
2085 maxGoodLength = avc->f.truncPos;
2086 Position = AFS_CHUNKBASE(abyte);
2087 if (vType(avc) == VDIR) {
2088 size = avc->f.m.Length;
2089 if (size > tdc->f.chunkBytes) {
2090 /* pre-reserve space for file */
2091 afs_AdjustSize(tdc, size);
2093 size = 999999999; /* max size for transfer */
2095 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2096 /* don't read past end of good data on server */
2097 if (Position + size > maxGoodLength)
2098 size = maxGoodLength - Position;
2100 size = 0; /* Handle random races */
2101 if (size > tdc->f.chunkBytes) {
2102 /* pre-reserve space for file */
2103 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2104 /* max size for transfer still in size */
2107 if (afs_mariner && !tdc->f.chunk)
2108 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2110 * Right now, we only have one tool, and it's a hammer. So, we
2111 * fetch the whole file.
2113 DZap(tdc); /* pages in cache may be old */
2114 file = afs_CFileOpen(&tdc->f.inode);
2115 afs_RemoveVCB(&avc->f.fid);
2116 tdc->f.states |= DWriting;
2117 tdc->dflags |= DFFetching;
2118 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2119 if (tdc->mflags & DFFetchReq) {
2120 tdc->mflags &= ~DFFetchReq;
2121 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2122 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2123 __FILE__, ICL_TYPE_INT32, __LINE__,
2124 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2128 (struct afs_FetchOutput *)osi_AllocLargeSpace(sizeof(struct afs_FetchOutput));
2129 setVcacheStatus = 0;
2132 * Remember if we are doing the reading from a replicated volume,
2133 * and how many times we've zipped around the fetch/analyze loop.
2135 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2137 accP = &(afs_stats_cmfullperf.accessinf);
2139 (accP->replicatedRefs)++;
2141 (accP->unreplicatedRefs)++;
2142 #endif /* AFS_NOSTATS */
2143 /* this is a cache miss */
2144 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2145 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2146 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2149 afs_stats_cmperf.dcacheMisses++;
2152 * Dynamic root support: fetch data from local memory.
2154 if (afs_IsDynroot(avc)) {
2158 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2160 dynrootDir += Position;
2161 dynrootLen -= Position;
2162 if (size > dynrootLen)
2166 code = afs_CFileWrite(file, 0, dynrootDir, size);
2174 tdc->validPos = Position + size;
2175 afs_CFileTruncate(file, size); /* prune it */
2176 } else if (afs_IsDynrootMount(avc)) {
2180 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2182 dynrootDir += Position;
2183 dynrootLen -= Position;
2184 if (size > dynrootLen)
2188 code = afs_CFileWrite(file, 0, dynrootDir, size);
2196 tdc->validPos = Position + size;
2197 afs_CFileTruncate(file, size); /* prune it */
2200 * Not a dynamic vnode: do the real fetch.
2205 * avc->lock(R) if setLocks && !slowPass
2206 * avc->lock(W) if !setLocks || slowPass
2210 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
2215 (accP->numReplicasAccessed)++;
2217 #endif /* AFS_NOSTATS */
2218 if (!setLocks || slowPass) {
2219 avc->callback = tc->srvr->server;
2221 newCallback = tc->srvr->server;
2225 code = afs_CacheFetchProc(tc, file, Position, tdc,
2231 /* callback could have been broken (or expired) in a race here,
2232 * but we return the data anyway. It's as good as we knew about
2233 * when we started. */
2235 * validPos is updated by CacheFetchProc, and can only be
2236 * modifed under a dcache write lock, which we've blocked out
2238 size = tdc->validPos - Position; /* actual segment size */
2241 afs_CFileTruncate(file, size); /* prune it */
2243 if (!setLocks || slowPass) {
2244 ObtainWriteLock(&afs_xcbhash, 453);
2245 afs_DequeueCallback(avc);
2246 avc->f.states &= ~(CStatd | CUnique);
2247 avc->callback = NULL;
2248 ReleaseWriteLock(&afs_xcbhash);
2249 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2250 osi_dnlc_purgedp(avc);
2252 /* Something lost. Forget about performance, and go
2253 * back with a vcache write lock.
2255 afs_CFileTruncate(file, 0);
2256 afs_AdjustSize(tdc, 0);
2257 afs_CFileClose(file);
2258 osi_FreeLargeSpace(tsmall);
2260 ReleaseWriteLock(&tdc->lock);
2263 ReleaseReadLock(&avc->lock);
2265 goto RetryGetDCache;
2269 } while (afs_Analyze
2270 (tc, code, &avc->f.fid, areq,
2271 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2275 * avc->lock(R) if setLocks && !slowPass
2276 * avc->lock(W) if !setLocks || slowPass
2282 * In the case of replicated access, jot down info on the number of
2283 * attempts it took before we got through or gave up.
2286 if (numFetchLoops <= 1)
2287 (accP->refFirstReplicaOK)++;
2288 if (numFetchLoops > accP->maxReplicasPerRef)
2289 accP->maxReplicasPerRef = numFetchLoops;
2291 #endif /* AFS_NOSTATS */
2293 tdc->dflags &= ~DFFetching;
2294 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2295 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2296 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2297 tdc, ICL_TYPE_INT32, tdc->dflags);
2298 if (avc->execsOrWriters == 0)
2299 tdc->f.states &= ~DWriting;
2301 /* now, if code != 0, we have an error and should punt.
2302 * note that we have the vcache write lock, either because
2303 * !setLocks or slowPass.
2306 afs_CFileTruncate(file, 0);
2307 afs_AdjustSize(tdc, 0);
2308 afs_CFileClose(file);
2309 ZapDCE(tdc); /* sets DFEntryMod */
2310 if (vType(avc) == VDIR) {
2313 tdc->f.states &= ~(DRO|DBackup|DRW);
2314 afs_DCMoveBucket(tdc, 0, 0);
2315 ReleaseWriteLock(&tdc->lock);
2317 if (!afs_IsDynroot(avc)) {
2318 ObtainWriteLock(&afs_xcbhash, 454);
2319 afs_DequeueCallback(avc);
2320 avc->f.states &= ~(CStatd | CUnique);
2321 ReleaseWriteLock(&afs_xcbhash);
2322 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2323 osi_dnlc_purgedp(avc);
2326 * avc->lock(W); assert(!setLocks || slowPass)
2328 osi_Assert(!setLocks || slowPass);
2334 /* otherwise we copy in the just-fetched info */
2335 afs_CFileClose(file);
2336 afs_AdjustSize(tdc, size); /* new size */
2338 * Copy appropriate fields into vcache. Status is
2339 * copied later where we selectively acquire the
2340 * vcache write lock.
2343 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2345 setVcacheStatus = 1;
2346 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2347 tsmall->OutStatus.DataVersion);
2348 tdc->dflags |= DFEntryMod;
2349 afs_indexFlags[tdc->index] |= IFEverUsed;
2350 ConvertWToSLock(&tdc->lock);
2351 } /*Data version numbers don't match */
2354 * Data version numbers match.
2356 afs_stats_cmperf.dcacheHits++;
2357 } /*Data version numbers match */
2359 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2363 * avc->lock(R) if setLocks && !slowPass
2364 * avc->lock(W) if !setLocks || slowPass
2365 * tdc->lock(S) if tdc
2369 * See if this was a reference to a file in the local cell.
2371 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2372 afs_stats_cmperf.dlocalAccesses++;
2374 afs_stats_cmperf.dremoteAccesses++;
2376 /* Fix up LRU info */
2379 ObtainWriteLock(&afs_xdcache, 602);
2380 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2381 hadd32(afs_indexCounter, 1);
2382 ReleaseWriteLock(&afs_xdcache);
2384 /* return the data */
2385 if (vType(avc) == VDIR)
2388 *aoffset = AFS_CHUNKOFFSET(abyte);
2389 *alen = (tdc->f.chunkBytes - *aoffset);
2390 ReleaseSharedLock(&tdc->lock);
2395 * avc->lock(R) if setLocks && !slowPass
2396 * avc->lock(W) if !setLocks || slowPass
2399 /* Fix up the callback and status values in the vcache */
2401 if (setLocks && !slowPass) {
2404 * This is our dirty little secret to parallel fetches.
2405 * We don't write-lock the vcache while doing the fetch,
2406 * but potentially we'll need to update the vcache after
2407 * the fetch is done.
2409 * Drop the read lock and try to re-obtain the write
2410 * lock. If the vcache still has the same DV, it's
2411 * ok to go ahead and install the new data.
2413 afs_hyper_t currentDV, statusDV;
2415 hset(currentDV, avc->f.m.DataVersion);
2417 if (setNewCallback && avc->callback != newCallback)
2421 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2422 tsmall->OutStatus.DataVersion);
2424 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2426 if (setVcacheStatus && !hsame(currentDV, statusDV))
2430 ReleaseReadLock(&avc->lock);
2432 if (doVcacheUpdate) {
2433 ObtainWriteLock(&avc->lock, 615);
2434 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2435 /* We lose. Someone will beat us to it. */
2437 ReleaseWriteLock(&avc->lock);
2442 /* With slow pass, we've already done all the updates */
2444 ReleaseWriteLock(&avc->lock);
2447 /* Check if we need to perform any last-minute fixes with a write-lock */
2448 if (!setLocks || doVcacheUpdate) {
2450 avc->callback = newCallback;
2451 if (tsmall && setVcacheStatus)
2452 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2454 ReleaseWriteLock(&avc->lock);
2458 osi_FreeLargeSpace(tsmall);
2461 } /*afs_GetDCache */
2465 * afs_WriteThroughDSlots
2468 * Sweep through the dcache slots and write out any modified
2469 * in-memory data back on to our caching store.
2475 * The afs_xdcache is write-locked through this whole affair.
2478 afs_WriteThroughDSlots(void)
2481 afs_int32 i, touchedit = 0;
2483 struct afs_q DirtyQ, *tq;
2485 AFS_STATCNT(afs_WriteThroughDSlots);
2488 * Because of lock ordering, we can't grab dcache locks while
2489 * holding afs_xdcache. So we enter xdcache, get a reference
2490 * for every dcache entry, and exit xdcache.
2492 ObtainWriteLock(&afs_xdcache, 283);
2494 for (i = 0; i < afs_cacheFiles; i++) {
2495 tdc = afs_indexTable[i];
2497 /* Grab tlock in case the existing refcount isn't zero */
2498 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2499 ObtainWriteLock(&tdc->tlock, 623);
2501 ReleaseWriteLock(&tdc->tlock);
2503 QAdd(&DirtyQ, &tdc->dirty);
2506 ReleaseWriteLock(&afs_xdcache);
2509 * Now, for each dcache entry we found, check if it's dirty.
2510 * If so, get write-lock, get afs_xdcache, which protects
2511 * afs_cacheInodep, and flush it. Don't forget to put back
2515 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2517 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2519 if (tdc->dflags & DFEntryMod) {
2522 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2524 /* Now that we have the write lock, double-check */
2525 if (wrLock && (tdc->dflags & DFEntryMod)) {
2526 tdc->dflags &= ~DFEntryMod;
2527 ObtainWriteLock(&afs_xdcache, 620);
2528 afs_WriteDCache(tdc, 1);
2529 ReleaseWriteLock(&afs_xdcache);
2533 ReleaseWriteLock(&tdc->lock);
2539 ObtainWriteLock(&afs_xdcache, 617);
2540 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2541 /* Touch the file to make sure that the mtime on the file is kept
2542 * up-to-date to avoid losing cached files on cold starts because
2543 * their mtime seems old...
2545 struct afs_fheader theader;
2547 theader.magic = AFS_FHMAGIC;
2548 theader.firstCSize = AFS_FIRSTCSIZE;
2549 theader.otherCSize = AFS_OTHERCSIZE;
2550 theader.version = AFS_CI_VERSION;
2551 theader.dataSize = sizeof(struct fcache);
2552 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2554 ReleaseWriteLock(&afs_xdcache);
2561 * Return a pointer to an freshly initialized dcache entry using
2562 * a memory-based cache. The tlock will be read-locked.
2565 * aslot : Dcache slot to look at.
2566 * tmpdc : Ptr to dcache entry.
2569 * Must be called with afs_xdcache write-locked.
2573 afs_MemGetDSlot(afs_int32 aslot, struct dcache *tmpdc)
2578 AFS_STATCNT(afs_MemGetDSlot);
2579 if (CheckLock(&afs_xdcache) != -1)
2580 osi_Panic("getdslot nolock");
2581 if (aslot < 0 || aslot >= afs_cacheFiles)
2582 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2583 tdc = afs_indexTable[aslot];
2585 QRemove(&tdc->lruq); /* move to queue head */
2586 QAdd(&afs_DLRU, &tdc->lruq);
2587 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2588 ObtainWriteLock(&tdc->tlock, 624);
2590 ConvertWToRLock(&tdc->tlock);
2593 if (tmpdc == NULL) {
2594 if (!afs_freeDSList)
2595 afs_GetDownDSlot(4);
2596 if (!afs_freeDSList) {
2597 /* none free, making one is better than a panic */
2598 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2599 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2600 #ifdef KERNEL_HAVE_PIN
2601 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2604 tdc = afs_freeDSList;
2605 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2608 tdc->dflags = 0; /* up-to-date, not in free q */
2610 QAdd(&afs_DLRU, &tdc->lruq);
2611 if (tdc->lruq.prev == &tdc->lruq)
2612 osi_Panic("lruq 3");
2618 /* initialize entry */
2619 tdc->f.fid.Cell = 0;
2620 tdc->f.fid.Fid.Volume = 0;
2622 hones(tdc->f.versionNo);
2623 tdc->f.inode.mem = aslot;
2624 tdc->dflags |= DFEntryMod;
2627 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2630 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2631 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2632 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2635 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2636 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2637 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2638 ObtainReadLock(&tdc->tlock);
2641 afs_indexTable[aslot] = tdc;
2644 } /*afs_MemGetDSlot */
2646 unsigned int last_error = 0, lasterrtime = 0;
2652 * Return a pointer to an freshly initialized dcache entry using
2653 * a UFS-based disk cache. The dcache tlock will be read-locked.
2656 * aslot : Dcache slot to look at.
2657 * tmpdc : Ptr to dcache entry.
2660 * afs_xdcache lock write-locked.
2663 afs_UFSGetDSlot(afs_int32 aslot, struct dcache *tmpdc)
2670 AFS_STATCNT(afs_UFSGetDSlot);
2671 if (CheckLock(&afs_xdcache) != -1)
2672 osi_Panic("getdslot nolock");
2673 if (aslot < 0 || aslot >= afs_cacheFiles)
2674 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2675 tdc = afs_indexTable[aslot];
2677 QRemove(&tdc->lruq); /* move to queue head */
2678 QAdd(&afs_DLRU, &tdc->lruq);
2679 /* Grab tlock in case refCount != 0 */
2680 ObtainWriteLock(&tdc->tlock, 625);
2682 ConvertWToRLock(&tdc->tlock);
2685 /* otherwise we should read it in from the cache file */
2687 * If we weren't passed an in-memory region to place the file info,
2688 * we have to allocate one.
2690 if (tmpdc == NULL) {
2691 if (!afs_freeDSList)
2692 afs_GetDownDSlot(4);
2693 if (!afs_freeDSList) {
2694 /* none free, making one is better than a panic */
2695 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2696 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2697 #ifdef KERNEL_HAVE_PIN
2698 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2701 tdc = afs_freeDSList;
2702 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2705 tdc->dflags = 0; /* up-to-date, not in free q */
2707 QAdd(&afs_DLRU, &tdc->lruq);
2708 if (tdc->lruq.prev == &tdc->lruq)
2709 osi_Panic("lruq 3");
2716 * Seek to the aslot'th entry and read it in.
2719 afs_osi_Read(afs_cacheInodep,
2720 sizeof(struct fcache) * aslot +
2721 sizeof(struct afs_fheader), (char *)(&tdc->f),
2722 sizeof(struct fcache));
2724 if (code != sizeof(struct fcache))
2726 if (!afs_CellNumValid(tdc->f.fid.Cell))
2730 tdc->f.fid.Cell = 0;
2731 tdc->f.fid.Fid.Volume = 0;
2733 hones(tdc->f.versionNo);
2734 tdc->dflags |= DFEntryMod;
2735 #if defined(KERNEL_HAVE_UERROR)
2736 last_error = getuerror();
2738 lasterrtime = osi_Time();
2739 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2740 tdc->f.states &= ~(DRO|DBackup|DRW);
2741 afs_DCMoveBucket(tdc, 0, 0);
2744 if (tdc->f.states & DRO) {
2745 afs_DCMoveBucket(tdc, 0, 2);
2746 } else if (tdc->f.states & DBackup) {
2747 afs_DCMoveBucket(tdc, 0, 1);
2749 afs_DCMoveBucket(tdc, 0, 1);
2755 if (tdc->f.chunk >= 0)
2756 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
2761 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2762 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2763 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2766 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2767 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2768 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2769 ObtainReadLock(&tdc->tlock);
2772 * If we didn't read into a temporary dcache region, update the
2773 * slot pointer table.
2776 afs_indexTable[aslot] = tdc;
2779 } /*afs_UFSGetDSlot */
2784 * Write a particular dcache entry back to its home in the
2787 * \param adc Pointer to the dcache entry to write.
2788 * \param atime If true, set the modtime on the file to the current time.
2790 * \note Environment:
2791 * Must be called with the afs_xdcache lock at least read-locked,
2792 * and dcache entry at least read-locked.
2793 * The reference count is not changed.
2797 afs_WriteDCache(struct dcache *adc, int atime)
2801 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2803 AFS_STATCNT(afs_WriteDCache);
2804 osi_Assert(WriteLocked(&afs_xdcache));
2806 adc->f.modTime = osi_Time();
2808 * Seek to the right dcache slot and write the in-memory image out to disk.
2810 afs_cellname_write();
2812 afs_osi_Write(afs_cacheInodep,
2813 sizeof(struct fcache) * adc->index +
2814 sizeof(struct afs_fheader), (char *)(&adc->f),
2815 sizeof(struct fcache));
2816 if (code != sizeof(struct fcache))
2824 * Wake up users of a particular file waiting for stores to take
2827 * \param avc Ptr to related vcache entry.
2829 * \note Environment:
2830 * Nothing interesting.
2833 afs_wakeup(struct vcache *avc)
2836 struct brequest *tb;
2838 AFS_STATCNT(afs_wakeup);
2839 for (i = 0; i < NBRS; i++, tb++) {
2840 /* if request is valid and for this file, we've found it */
2841 if (tb->refCount > 0 && avc == tb->vc) {
2844 * If CSafeStore is on, then we don't awaken the guy
2845 * waiting for the store until the whole store has finished.
2846 * Otherwise, we do it now. Note that if CSafeStore is on,
2847 * the BStore routine actually wakes up the user, instead
2849 * I think this is redundant now because this sort of thing
2850 * is already being handled by the higher-level code.
2852 if ((avc->f.states & CSafeStore) == 0) {
2854 tb->flags |= BUVALID;
2855 if (tb->flags & BUWAIT) {
2856 tb->flags &= ~BUWAIT;
2868 * Given a file name and inode, set up that file to be an
2869 * active member in the AFS cache. This also involves checking
2870 * the usability of its data.
2872 * \param afile Name of the cache file to initialize.
2873 * \param ainode Inode of the file.
2875 * \note Environment:
2876 * This function is called only during initialization.
2879 afs_InitCacheFile(char *afile, ino_t ainode)
2884 struct osi_file *tfile;
2885 struct osi_stat tstat;
2888 AFS_STATCNT(afs_InitCacheFile);
2889 index = afs_stats_cmperf.cacheNumEntries;
2890 if (index >= afs_cacheFiles)
2893 ObtainWriteLock(&afs_xdcache, 282);
2894 tdc = afs_GetDSlot(index, NULL);
2895 ReleaseReadLock(&tdc->tlock);
2896 ReleaseWriteLock(&afs_xdcache);
2898 ObtainWriteLock(&tdc->lock, 621);
2899 ObtainWriteLock(&afs_xdcache, 622);
2901 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
2903 ReleaseWriteLock(&afs_xdcache);
2904 ReleaseWriteLock(&tdc->lock);
2909 /* Add any other 'complex' inode types here ... */
2910 #if !defined(AFS_LINUX26_ENV) && !defined(AFS_CACHE_VNODE_PATH)
2911 tdc->f.inode.ufs = ainode;
2913 osi_Panic("Can't init cache with inode numbers when complex inodes are "
2918 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
2920 tfile = osi_UFSOpen(&tdc->f.inode);
2921 code = afs_osi_Stat(tfile, &tstat);
2923 osi_Panic("initcachefile stat");
2926 * If file size doesn't match the cache info file, it's probably bad.
2928 if (tdc->f.chunkBytes != tstat.size)
2930 tdc->f.chunkBytes = 0;
2933 * If file changed within T (120?) seconds of cache info file, it's
2934 * probably bad. In addition, if slot changed within last T seconds,
2935 * the cache info file may be incorrectly identified, and so slot
2938 if (cacheInfoModTime < tstat.mtime + 120)
2940 if (cacheInfoModTime < tdc->f.modTime + 120)
2942 /* In case write through is behind, make sure cache items entry is
2943 * at least as new as the chunk.
2945 if (tdc->f.modTime < tstat.mtime)
2948 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
2949 if (tstat.size != 0)
2950 osi_UFSTruncate(tfile, 0);
2951 tdc->f.states &= ~(DRO|DBackup|DRW);
2952 afs_DCMoveBucket(tdc, 0, 0);
2953 /* put entry in free cache slot list */
2954 afs_dvnextTbl[tdc->index] = afs_freeDCList;
2955 afs_freeDCList = index;
2957 afs_indexFlags[index] |= IFFree;
2958 afs_indexUnique[index] = 0;
2961 * We must put this entry in the appropriate hash tables.
2962 * Note that i is still set from the above DCHash call
2964 code = DCHash(&tdc->f.fid, tdc->f.chunk);
2965 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
2966 afs_dchashTbl[code] = tdc->index;
2967 code = DVHash(&tdc->f.fid);
2968 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
2969 afs_dvhashTbl[code] = tdc->index;
2970 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
2972 /* has nontrivial amt of data */
2973 afs_indexFlags[index] |= IFEverUsed;
2974 afs_stats_cmperf.cacheFilesReused++;
2976 * Initialize index times to file's mod times; init indexCounter
2979 hset32(afs_indexTimes[index], tstat.atime);
2980 if (hgetlo(afs_indexCounter) < tstat.atime) {
2981 hset32(afs_indexCounter, tstat.atime);
2983 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
2984 } /*File is not bad */
2986 osi_UFSClose(tfile);
2987 tdc->f.states &= ~DWriting;
2988 tdc->dflags &= ~DFEntryMod;
2989 /* don't set f.modTime; we're just cleaning up */
2990 afs_WriteDCache(tdc, 0);
2991 ReleaseWriteLock(&afs_xdcache);
2992 ReleaseWriteLock(&tdc->lock);
2994 afs_stats_cmperf.cacheNumEntries++;
2999 /*Max # of struct dcache's resident at any time*/
3001 * If 'dchint' is enabled then in-memory dcache min is increased because of
3007 * Initialize dcache related variables.
3017 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3023 afs_freeDCList = NULLIDX;
3024 afs_discardDCList = NULLIDX;
3025 afs_freeDCCount = 0;
3026 afs_freeDSList = NULL;
3027 hzero(afs_indexCounter);
3029 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3035 if (achunk < 0 || achunk > 30)
3036 achunk = 13; /* Use default */
3037 AFS_SETCHUNKSIZE(achunk);
3043 if (aflags & AFSCALL_INIT_MEMCACHE) {
3045 * Use a memory cache instead of a disk cache
3047 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3048 afs_cacheType = &afs_MemCacheOps;
3049 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3050 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3051 /* ablocks is reported in 1K blocks */
3052 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3054 afs_warn("afsd: memory cache too large for available memory.\n");
3055 afs_warn("afsd: AFS files cannot be accessed.\n\n");
3057 afiles = ablocks = 0;
3059 afs_warn("Memory cache: Allocating %d dcache entries...",
3062 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3063 afs_cacheType = &afs_UfsCacheOps;
3066 if (aDentries > 512)
3067 afs_dhashsize = 2048;
3068 /* initialize hash tables */
3070 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3072 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3073 for (i = 0; i < afs_dhashsize; i++) {
3074 afs_dvhashTbl[i] = NULLIDX;
3075 afs_dchashTbl[i] = NULLIDX;
3077 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3078 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3079 for (i = 0; i < afiles; i++) {
3080 afs_dvnextTbl[i] = NULLIDX;
3081 afs_dcnextTbl[i] = NULLIDX;
3084 /* Allocate and zero the pointer array to the dcache entries */
3085 afs_indexTable = (struct dcache **)
3086 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3087 memset(afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3089 (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3090 memset(afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3092 (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3093 memset(afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3094 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3095 memset(afs_indexFlags, 0, afiles * sizeof(char));
3097 /* Allocate and thread the struct dcache entries themselves */
3098 tdp = afs_Initial_freeDSList =
3099 (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3100 memset(tdp, 0, aDentries * sizeof(struct dcache));
3101 #ifdef KERNEL_HAVE_PIN
3102 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3103 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3104 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3105 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3106 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3107 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3108 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3109 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3110 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3113 afs_freeDSList = &tdp[0];
3114 for (i = 0; i < aDentries - 1; i++) {
3115 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3116 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3117 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3118 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3120 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3121 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3122 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3123 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3125 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3126 afs_cacheBlocks = ablocks;
3127 afs_ComputeCacheParms(); /* compute parms based on cache size */
3129 afs_dcentries = aDentries;
3131 afs_stats_cmperf.cacheBucket0_Discarded =
3132 afs_stats_cmperf.cacheBucket1_Discarded =
3133 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3139 * Shuts down the cache.
3143 shutdown_dcache(void)
3147 #ifdef AFS_CACHE_VNODE_PATH
3148 if (cacheDiskType != AFS_FCACHE_TYPE_MEM) {
3150 for (i = 0; i < afs_cacheFiles; i++) {
3151 tdc = afs_indexTable[i];
3153 afs_osi_FreeStr(tdc->f.inode.ufs);
3159 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3160 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3161 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3162 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3163 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3164 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3165 afs_osi_Free(afs_Initial_freeDSList,
3166 afs_dcentries * sizeof(struct dcache));
3167 #ifdef KERNEL_HAVE_PIN
3168 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3169 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3170 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3171 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3172 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3173 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3174 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3178 for (i = 0; i < afs_dhashsize; i++) {
3179 afs_dvhashTbl[i] = NULLIDX;
3180 afs_dchashTbl[i] = NULLIDX;
3183 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3184 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3186 afs_blocksUsed = afs_dcentries = 0;
3187 afs_stats_cmperf.cacheBucket0_Discarded =
3188 afs_stats_cmperf.cacheBucket1_Discarded =
3189 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3190 hzero(afs_indexCounter);
3192 afs_freeDCCount = 0;
3193 afs_freeDCList = NULLIDX;
3194 afs_discardDCList = NULLIDX;
3195 afs_freeDSList = afs_Initial_freeDSList = 0;
3197 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3203 * Get a dcache ready for writing, respecting the current cache size limits
3205 * len is required because afs_GetDCache with flag == 4 expects the length
3206 * field to be filled. It decides from this whether it's necessary to fetch
3207 * data into the chunk before writing or not (when the whole chunk is
3210 * \param avc The vcache to fetch a dcache for
3211 * \param filePos The start of the section to be written
3212 * \param len The length of the section to be written
3216 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3217 * must be released and afs_PutDCache() called to free dcache.
3220 * \note avc->lock must be held on entry. Function may release and reobtain
3221 * avc->lock and GLOCK.
3225 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3226 afs_size_t len, struct vrequest *areq,
3229 struct dcache *tdc = NULL;
3232 /* read the cached info */
3234 tdc = afs_FindDCache(avc, filePos);
3236 ObtainWriteLock(&tdc->lock, 657);
3237 } else if (afs_blocksUsed >
3238 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3239 tdc = afs_FindDCache(avc, filePos);
3241 ObtainWriteLock(&tdc->lock, 658);
3242 if (!hsame(tdc->f.versionNo, avc->f.m.DataVersion)
3243 || (tdc->dflags & DFFetching)) {
3244 ReleaseWriteLock(&tdc->lock);
3250 afs_MaybeWakeupTruncateDaemon();
3251 while (afs_blocksUsed >
3252 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3253 ReleaseWriteLock(&avc->lock);
3254 if (afs_blocksUsed - afs_blocksDiscarded >
3255 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3256 afs_WaitForCacheDrain = 1;
3257 afs_osi_Sleep(&afs_WaitForCacheDrain);
3259 afs_MaybeFreeDiscardedDCache();
3260 afs_MaybeWakeupTruncateDaemon();
3261 ObtainWriteLock(&avc->lock, 509);
3263 avc->f.states |= CDirty;
3264 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3266 ObtainWriteLock(&tdc->lock, 659);
3269 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3271 ObtainWriteLock(&tdc->lock, 660);
3274 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3275 afs_stats_cmperf.cacheCurrDirtyChunks++;
3276 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3278 if (!(tdc->f.states & DWriting)) {
3279 /* don't mark entry as mod if we don't have to */
3280 tdc->f.states |= DWriting;
3281 tdc->dflags |= DFEntryMod;
3288 * Make a shadow copy of a dir's dcache. It's used for disconnected
3289 * operations like remove/create/rename to keep the original directory data.
3290 * On reconnection, we can diff the original data with the server and get the
3291 * server changes and with the local data to get the local changes.
3293 * \param avc The dir vnode.
3294 * \param adc The dir dcache.
3296 * \return 0 for success.
3298 * \note The vcache entry must be write locked.
3299 * \note The dcache entry must be read locked.
3302 afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3304 int i, code, ret_code = 0, written, trans_size;
3305 struct dcache *new_dc = NULL;
3306 struct osi_file *tfile_src, *tfile_dst;
3307 struct VenusFid shadow_fid;
3310 /* Is this a dir? */
3311 if (vType(avc) != VDIR)
3314 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3317 /* Generate a fid for the shadow dir. */
3318 shadow_fid.Cell = avc->f.fid.Cell;
3319 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3320 afs_GenShadowFid(&shadow_fid);
3322 ObtainWriteLock(&afs_xdcache, 716);
3324 /* Get a fresh dcache. */
3325 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3327 ObtainReadLock(&adc->mflock);
3329 /* Set up the new fid. */
3330 /* Copy interesting data from original dir dcache. */
3331 new_dc->mflags = adc->mflags;
3332 new_dc->dflags = adc->dflags;
3333 new_dc->f.modTime = adc->f.modTime;
3334 new_dc->f.versionNo = adc->f.versionNo;
3335 new_dc->f.states = adc->f.states;
3336 new_dc->f.chunk= adc->f.chunk;
3337 new_dc->f.chunkBytes = adc->f.chunkBytes;
3339 ReleaseReadLock(&adc->mflock);
3341 /* Now add to the two hash chains */
3342 i = DCHash(&shadow_fid, 0);
3343 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[i];
3344 afs_dchashTbl[i] = new_dc->index;
3346 i = DVHash(&shadow_fid);
3347 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[i];
3348 afs_dvhashTbl[i] = new_dc->index;
3350 ReleaseWriteLock(&afs_xdcache);
3352 /* Alloc a 4k block. */
3353 data = (char *) afs_osi_Alloc(4096);
3355 afs_warn("afs_MakeShadowDir: could not alloc data\n");
3360 /* Open the files. */
3361 tfile_src = afs_CFileOpen(&adc->f.inode);
3362 tfile_dst = afs_CFileOpen(&new_dc->f.inode);
3364 /* And now copy dir dcache data into this dcache,
3368 while (written < adc->f.chunkBytes) {
3369 trans_size = adc->f.chunkBytes - written;
3370 if (trans_size > 4096)
3373 /* Read a chunk from the dcache. */
3374 code = afs_CFileRead(tfile_src, written, data, trans_size);
3375 if (code < trans_size) {
3380 /* Write it to the new dcache. */
3381 code = afs_CFileWrite(tfile_dst, written, data, trans_size);
3382 if (code < trans_size) {
3387 written+=trans_size;
3390 afs_CFileClose(tfile_dst);
3391 afs_CFileClose(tfile_src);
3393 afs_osi_Free(data, 4096);
3395 ReleaseWriteLock(&new_dc->lock);
3396 afs_PutDCache(new_dc);
3399 ObtainWriteLock(&afs_xvcache, 763);
3400 ObtainWriteLock(&afs_disconDirtyLock, 765);
3401 QAdd(&afs_disconShadow, &avc->shadowq);
3402 osi_Assert((afs_RefVCache(avc) == 0));
3403 ReleaseWriteLock(&afs_disconDirtyLock);
3404 ReleaseWriteLock(&afs_xvcache);
3406 avc->f.shadow.vnode = shadow_fid.Fid.Vnode;
3407 avc->f.shadow.unique = shadow_fid.Fid.Unique;
3415 * Delete the dcaches of a shadow dir.
3417 * \param avc The vcache containing the shadow fid.
3419 * \note avc must be write locked.
3422 afs_DeleteShadowDir(struct vcache *avc)
3425 struct VenusFid shadow_fid;
3427 shadow_fid.Cell = avc->f.fid.Cell;
3428 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3429 shadow_fid.Fid.Vnode = avc->f.shadow.vnode;
3430 shadow_fid.Fid.Unique = avc->f.shadow.unique;
3432 tdc = afs_FindDCacheByFid(&shadow_fid);
3434 afs_HashOutDCache(tdc, 1);
3435 afs_DiscardDCache(tdc);
3438 avc->f.shadow.vnode = avc->f.shadow.unique = 0;
3439 ObtainWriteLock(&afs_disconDirtyLock, 708);
3440 QRemove(&avc->shadowq);
3441 ReleaseWriteLock(&afs_disconDirtyLock);
3442 afs_PutVCache(avc); /* Because we held it when we added to the queue */
3446 * Populate a dcache with empty chunks up to a given file size,
3447 * used before extending a file in order to avoid 'holes' which
3448 * we can't access in disconnected mode.
3450 * \param avc The vcache which is being extended (locked)
3451 * \param alen The new length of the file
3455 afs_PopulateDCache(struct vcache *avc, afs_size_t apos, struct vrequest *areq)
3458 afs_size_t len, offset;
3459 afs_int32 start, end;
3461 /* We're doing this to deal with the situation where we extend
3462 * by writing after lseek()ing past the end of the file . If that
3463 * extension skips chunks, then those chunks won't be created, and
3464 * GetDCache will assume that they have to be fetched from the server.
3465 * So, for each chunk between the current file position, and the new
3466 * length we GetDCache for that chunk.
3469 if (AFS_CHUNK(apos) == 0 || apos <= avc->f.m.Length)
3472 if (avc->f.m.Length == 0)
3475 start = AFS_CHUNK(avc->f.m.Length)+1;
3477 end = AFS_CHUNK(apos);
3480 len = AFS_CHUNKTOSIZE(start);
3481 tdc = afs_GetDCache(avc, AFS_CHUNKTOBASE(start), areq, &offset, &len, 4);