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"
25 /* Forward declarations. */
26 static void afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint);
27 static int 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 afs_dcache_id_t cacheInode; /*!< Inode for CacheItems file */
58 struct osi_file *afs_cacheInodep = 0; /*!< file for CacheItems inode */
59 struct afs_q afs_DLRU; /*!< dcache LRU */
60 afs_int32 afs_dhashsize = 1024;
61 afs_int32 *afs_dvhashTbl; /*!< Data cache hash table: hashed by FID + chunk number. */
62 afs_int32 *afs_dchashTbl; /*!< Data cache hash table: hashed by FID. */
63 afs_int32 *afs_dvnextTbl; /*!< Dcache hash table links */
64 afs_int32 *afs_dcnextTbl; /*!< Dcache hash table links */
65 struct dcache **afs_indexTable; /*!< Pointers to dcache entries */
66 afs_hyper_t *afs_indexTimes; /*!< Dcache entry Access times */
67 afs_int32 *afs_indexUnique; /*!< dcache entry Fid.Unique */
68 unsigned char *afs_indexFlags; /*!< (only one) Is there data there? */
69 afs_hyper_t afs_indexCounter; /*!< Fake time for marking index
71 afs_int32 afs_cacheFiles = 0; /*!< Size of afs_indexTable */
72 afs_int32 afs_cacheBlocks; /*!< 1K blocks in cache */
73 afs_int32 afs_cacheStats; /*!< Stat entries in cache */
74 afs_int32 afs_blocksUsed; /*!< Number of blocks in use */
75 afs_int32 afs_blocksDiscarded; /*!<Blocks freed but not truncated */
76 afs_int32 afs_fsfragsize = AFS_MIN_FRAGSIZE; /*!< 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 struct afs_cacheOps afs_UfsCacheOps = {
105 #ifndef HAVE_STRUCT_LABEL_SUPPORT
118 .truncate = osi_UFSTruncate,
119 .fread = afs_osi_Read,
120 .fwrite = afs_osi_Write,
121 .close = osi_UFSClose,
122 .vreadUIO = afs_UFSReadUIO,
123 .vwriteUIO = afs_UFSWriteUIO,
124 .GetDSlot = afs_UFSGetDSlot,
125 .GetVolSlot = afs_UFSGetVolSlot,
126 .HandleLink = afs_UFSHandleLink,
130 struct afs_cacheOps afs_MemCacheOps = {
131 #ifndef HAVE_STRUCT_LABEL_SUPPORT
133 afs_MemCacheTruncate,
143 .open = afs_MemCacheOpen,
144 .truncate = afs_MemCacheTruncate,
145 .fread = afs_MemReadBlk,
146 .fwrite = afs_MemWriteBlk,
147 .close = afs_MemCacheClose,
148 .vreadUIO = afs_MemReadUIO,
149 .vwriteUIO = afs_MemWriteUIO,
150 .GetDSlot = afs_MemGetDSlot,
151 .GetVolSlot = afs_MemGetVolSlot,
152 .HandleLink = afs_MemHandleLink,
156 int cacheDiskType; /*Type of backing disk for cache */
157 struct afs_cacheOps *afs_cacheType;
161 * The PFlush algorithm makes use of the fact that Fid.Unique is not used in
162 * below hash algorithms. Change it if need be so that flushing algorithm
163 * doesn't move things from one hash chain to another.
165 /*Vnode, Chunk -> Hash table index */
166 int DCHash(struct VenusFid *fid, afs_int32 chunk)
170 buf[0] = fid->Fid.Volume;
171 buf[1] = fid->Fid.Vnode;
173 return opr_jhash(buf, 3, 0) & (afs_dhashsize - 1);
175 /*Vnode -> Other hash table index */
176 int DVHash(struct VenusFid *fid)
178 return opr_jhash_int2(fid->Fid.Volume, fid->Fid.Vnode, 0) &
183 * Where is this vcache's entry associated dcache located/
184 * \param avc The vcache entry.
185 * \return Bucket index:
190 afs_DCGetBucket(struct vcache *avc)
195 /* This should be replaced with some sort of user configurable function */
196 if (avc->f.states & CRO) {
198 } else if (avc->f.states & CBackup) {
208 * Readjust a dcache's size.
210 * \param adc The dcache to be adjusted.
211 * \param oldSize Old size for the dcache.
212 * \param newSize The new size to be adjusted to.
216 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
218 afs_int32 adjustSize = newSize - oldSize;
226 afs_blocksUsed_0 += adjustSize;
227 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
230 afs_blocksUsed_1 += adjustSize;
231 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
234 afs_blocksUsed_2 += adjustSize;
235 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
243 * Move a dcache from one bucket to another.
245 * \param adc Operate on this dcache.
246 * \param size Size in bucket (?).
247 * \param newBucket Destination bucket.
251 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
256 /* Substract size from old bucket. */
260 afs_blocksUsed_0 -= size;
263 afs_blocksUsed_1 -= size;
266 afs_blocksUsed_2 -= size;
270 /* Set new bucket and increase destination bucket size. */
271 adc->bucket = newBucket;
276 afs_blocksUsed_0 += size;
279 afs_blocksUsed_1 += size;
282 afs_blocksUsed_2 += size;
290 * Init split caches size.
295 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
304 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
309 afs_pct1 = afs_blocksUsed_1 / (afs_cacheBlocks / 100);
310 afs_pct2 = afs_blocksUsed_2 / (afs_cacheBlocks / 100);
312 /* Short cut: if we don't know about it, try to kill it */
313 if (phase < 2 && afs_blocksUsed_0)
316 if (afs_pct1 > afs_tpct1)
318 if (afs_pct2 > afs_tpct2)
320 return 0; /* unlikely */
325 * Warn about failing to store a file.
327 * \param acode Associated error code.
328 * \param avolume Volume involved.
329 * \param aflags How to handle the output:
330 * aflags & 1: Print out on console
331 * aflags & 2: Print out on controlling tty
333 * \note Environment: Call this from close call when vnodeops is RCS unlocked.
337 afs_StoreWarn(afs_int32 acode, afs_int32 avolume,
340 static char problem_fmt[] =
341 "afs: failed to store file in volume %d (%s)\n";
342 static char problem_fmt_w_error[] =
343 "afs: failed to store file in volume %d (error %d)\n";
344 static char netproblems[] = "network problems";
345 static char partfull[] = "partition full";
346 static char overquota[] = "over quota";
348 AFS_STATCNT(afs_StoreWarn);
354 afs_warn(problem_fmt, avolume, netproblems);
356 afs_warnuser(problem_fmt, avolume, netproblems);
357 } else if (acode == ENOSPC) {
362 afs_warn(problem_fmt, avolume, partfull);
364 afs_warnuser(problem_fmt, avolume, partfull);
367 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
368 * Instead ENOSPC will be sent...
370 if (acode == EDQUOT) {
375 afs_warn(problem_fmt, avolume, overquota);
377 afs_warnuser(problem_fmt, avolume, overquota);
385 afs_warn(problem_fmt_w_error, avolume, acode);
387 afs_warnuser(problem_fmt_w_error, avolume, acode);
392 * Try waking up truncation daemon, if it's worth it.
395 afs_MaybeWakeupTruncateDaemon(void)
397 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
398 afs_CacheTooFull = 1;
399 if (!afs_TruncateDaemonRunning)
400 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
401 } else if (!afs_TruncateDaemonRunning
402 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
403 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
410 * Keep statistics on run time for afs_CacheTruncateDaemon. This is a
411 * struct so we need only export one symbol for AIX.
413 static struct CTD_stats {
414 osi_timeval_t CTD_beforeSleep;
415 osi_timeval_t CTD_afterSleep;
416 osi_timeval_t CTD_sleepTime;
417 osi_timeval_t CTD_runTime;
421 u_int afs_min_cache = 0;
424 * If there are waiters for the cache to drain, wake them if
425 * the number of free or discarded cache blocks reaches the
426 * CM_CACHESIZEDDRAINEDPCT limit.
429 * This routine must be called with the afs_xdcache lock held
433 afs_WakeCacheWaitersIfDrained(void)
435 if (afs_WaitForCacheDrain) {
436 if ((afs_blocksUsed - afs_blocksDiscarded) <=
437 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
438 afs_WaitForCacheDrain = 0;
439 afs_osi_Wakeup(&afs_WaitForCacheDrain);
445 * Keeps the cache clean and free by truncating uneeded files, when used.
450 afs_CacheTruncateDaemon(void)
452 osi_timeval_t CTD_tmpTime;
456 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
458 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
460 osi_GetuTime(&CTD_stats.CTD_afterSleep);
461 afs_TruncateDaemonRunning = 1;
463 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
464 ObtainWriteLock(&afs_xdcache, 266);
465 if (afs_CacheTooFull || afs_WaitForCacheDrain) {
466 int space_needed, slots_needed;
467 /* if we get woken up, we should try to clean something out */
468 for (counter = 0; counter < 10; counter++) {
470 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
471 if (space_needed < 0)
474 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
475 if (slots_needed < 0)
477 if (slots_needed || space_needed)
478 afs_GetDownD(slots_needed, &space_needed, 0);
479 if ((space_needed <= 0) && (slots_needed <= 0)) {
482 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
485 if (!afs_CacheIsTooFull()) {
486 afs_CacheTooFull = 0;
487 afs_WakeCacheWaitersIfDrained();
489 } /* end of cache cleanup */
490 ReleaseWriteLock(&afs_xdcache);
493 * This is a defensive check to try to avoid starving threads
494 * that may need the global lock so thay can help free some
495 * cache space. If this thread won't be sleeping or truncating
496 * any cache files then give up the global lock so other
497 * threads get a chance to run.
499 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
500 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
501 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
505 * This is where we free the discarded cache elements.
507 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
508 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
509 int code = afs_FreeDiscardedDCache();
511 /* If we can't free any discarded dcache entries, that's okay.
512 * We're just doing this in the background; if someone needs
513 * discarded entries freed, they will try it themselves and/or
514 * signal us that the cache is too full. In any case, we'll
515 * try doing this again the next time we run through the loop.
521 /* See if we need to continue to run. Someone may have
522 * signalled us while we were executing.
524 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
525 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
526 /* Collect statistics on truncate daemon. */
527 CTD_stats.CTD_nSleeps++;
528 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
529 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
530 CTD_stats.CTD_beforeSleep);
531 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
533 afs_TruncateDaemonRunning = 0;
534 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
535 afs_TruncateDaemonRunning = 1;
537 osi_GetuTime(&CTD_stats.CTD_afterSleep);
538 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
539 CTD_stats.CTD_afterSleep);
540 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
542 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
543 afs_termState = AFSOP_STOP_AFSDB;
544 afs_osi_Wakeup(&afs_termState);
552 * Make adjustment for the new size in the disk cache entry
554 * \note Major Assumptions Here:
555 * Assumes that frag size is an integral power of two, less one,
556 * and that this is a two's complement machine. I don't
557 * know of any filesystems which violate this assumption...
559 * \param adc Ptr to dcache entry.
560 * \param anewsize New size desired.
565 afs_AdjustSize(struct dcache *adc, afs_int32 newSize)
569 AFS_STATCNT(afs_AdjustSize);
571 adc->dflags |= DFEntryMod;
572 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
573 adc->f.chunkBytes = newSize;
576 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
577 afs_DCAdjustSize(adc, oldSize, newSize);
578 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
580 /* We're growing the file, wakeup the daemon */
581 afs_MaybeWakeupTruncateDaemon();
583 afs_blocksUsed += (newSize - oldSize);
584 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
589 * This routine is responsible for moving at least one entry (but up
590 * to some number of them) from the LRU queue to the free queue.
592 * \param anumber Number of entries that should ideally be moved.
593 * \param aneedSpace How much space we need (1K blocks);
596 * The anumber parameter is just a hint; at least one entry MUST be
597 * moved, or we'll panic. We must be called with afs_xdcache
598 * write-locked. We should try to satisfy both anumber and aneedspace,
599 * whichever is more demanding - need to do several things:
600 * 1. only grab up to anumber victims if aneedSpace <= 0, not
601 * the whole set of MAXATONCE.
602 * 2. dynamically choose MAXATONCE to reflect severity of
603 * demand: something like (*aneedSpace >> (logChunk - 9))
605 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
606 * indicates that the cache is not properly configured/tuned or
607 * something. We should be able to automatically correct that problem.
610 #define MAXATONCE 16 /* max we can obtain at once */
612 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
616 struct VenusFid *afid;
621 afs_uint32 victims[MAXATONCE];
622 struct dcache *victimDCs[MAXATONCE];
623 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
624 afs_uint32 victimPtr; /* next free item in victim arrays */
625 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
626 afs_uint32 maxVictimPtr; /* where it is */
630 AFS_STATCNT(afs_GetDownD);
632 if (CheckLock(&afs_xdcache) != -1)
633 osi_Panic("getdownd nolock");
634 /* decrement anumber first for all dudes in free list */
635 /* SHOULD always decrement anumber first, even if aneedSpace >0,
636 * because we should try to free space even if anumber <=0 */
637 if (!aneedSpace || *aneedSpace <= 0) {
638 anumber -= afs_freeDCCount;
640 return; /* enough already free */
644 /* bounds check parameter */
645 if (anumber > MAXATONCE)
646 anumber = MAXATONCE; /* all we can do */
648 /* rewrite so phases include a better eligiblity for gc test*/
650 * The phase variable manages reclaims. Set to 0, the first pass,
651 * we don't reclaim active entries, or other than target bucket.
652 * Set to 1, we reclaim even active ones in target bucket.
653 * Set to 2, we reclaim any inactive one.
654 * Set to 3, we reclaim even active ones. On Solaris, we also reclaim
655 * entries whose corresponding vcache has a nonempty multiPage list, when
664 for (i = 0; i < afs_cacheFiles; i++)
665 /* turn off all flags */
666 afs_indexFlags[i] &= ~IFFlag;
668 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
669 /* find oldest entries for reclamation */
670 maxVictimPtr = victimPtr = 0;
671 hzero(maxVictimTime);
672 curbucket = afs_DCWhichBucket(phase, buckethint);
673 /* select victims from access time array */
674 for (i = 0; i < afs_cacheFiles; i++) {
675 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
676 /* skip if dirty or already free */
679 tdc = afs_indexTable[i];
680 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
682 /* Wrong bucket; can't use it! */
685 if (tdc && (tdc->refCount != 0)) {
686 /* Referenced; can't use it! */
689 hset(vtime, afs_indexTimes[i]);
691 /* if we've already looked at this one, skip it */
692 if (afs_indexFlags[i] & IFFlag)
695 if (victimPtr < MAXATONCE) {
696 /* if there's at least one free victim slot left */
697 victims[victimPtr] = i;
698 hset(victimTimes[victimPtr], vtime);
699 if (hcmp(vtime, maxVictimTime) > 0) {
700 hset(maxVictimTime, vtime);
701 maxVictimPtr = victimPtr;
704 } else if (hcmp(vtime, maxVictimTime) < 0) {
706 * We're older than youngest victim, so we replace at
709 /* find youngest (largest LRU) victim */
712 osi_Panic("getdownd local");
714 hset(victimTimes[j], vtime);
715 /* recompute maxVictimTime */
716 hset(maxVictimTime, vtime);
717 for (j = 0; j < victimPtr; j++)
718 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
719 hset(maxVictimTime, victimTimes[j]);
725 /* now really reclaim the victims */
726 j = 0; /* flag to track if we actually got any of the victims */
727 /* first, hold all the victims, since we're going to release the lock
728 * during the truncate operation.
730 for (i = 0; i < victimPtr; i++) {
731 tdc = afs_GetValidDSlot(victims[i]);
732 /* We got tdc->tlock(R) here */
733 if (tdc && tdc->refCount == 1)
738 ReleaseReadLock(&tdc->tlock);
743 for (i = 0; i < victimPtr; i++) {
744 /* q is first elt in dcache entry */
746 /* now, since we're dropping the afs_xdcache lock below, we
747 * have to verify, before proceeding, that there are no other
748 * references to this dcache entry, even now. Note that we
749 * compare with 1, since we bumped it above when we called
750 * afs_GetValidDSlot to preserve the entry's identity.
752 if (tdc && tdc->refCount == 1) {
753 unsigned char chunkFlags;
754 afs_size_t tchunkoffset = 0;
756 /* xdcache is lower than the xvcache lock */
757 ReleaseWriteLock(&afs_xdcache);
758 ObtainReadLock(&afs_xvcache);
759 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
760 ReleaseReadLock(&afs_xvcache);
761 ObtainWriteLock(&afs_xdcache, 527);
763 if (tdc->refCount > 1)
766 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
767 chunkFlags = afs_indexFlags[tdc->index];
768 if (((phase & 1) == 0) && osi_Active(tvc))
770 if (((phase & 1) == 1) && osi_Active(tvc)
771 && (tvc->f.states & CDCLock)
772 && (chunkFlags & IFAnyPages))
774 if (chunkFlags & IFDataMod)
776 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
777 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
778 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
779 ICL_HANDLE_OFFSET(tchunkoffset));
781 #if defined(AFS_SUN5_ENV)
783 * Now we try to invalidate pages. We do this only for
784 * Solaris. For other platforms, it's OK to recycle a
785 * dcache entry out from under a page, because the strategy
786 * function can call afs_GetDCache().
788 if (!skip && (chunkFlags & IFAnyPages)) {
791 ReleaseWriteLock(&afs_xdcache);
792 ObtainWriteLock(&tvc->vlock, 543);
793 if (!QEmpty(&tvc->multiPage)) {
794 if (phase < 3 || osi_VM_MultiPageConflict(tvc, tdc)) {
799 /* block locking pages */
800 tvc->vstates |= VPageCleaning;
801 /* block getting new pages */
803 ReleaseWriteLock(&tvc->vlock);
804 /* One last recheck */
805 ObtainWriteLock(&afs_xdcache, 333);
806 chunkFlags = afs_indexFlags[tdc->index];
807 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
808 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
809 && (chunkFlags & IFAnyPages))) {
811 ReleaseWriteLock(&afs_xdcache);
814 ReleaseWriteLock(&afs_xdcache);
816 code = osi_VM_GetDownD(tvc, tdc);
818 ObtainWriteLock(&afs_xdcache, 269);
819 /* we actually removed all pages, clean and dirty */
821 afs_indexFlags[tdc->index] &=
822 ~(IFDirtyPages | IFAnyPages);
825 ReleaseWriteLock(&afs_xdcache);
827 ObtainWriteLock(&tvc->vlock, 544);
828 if (--tvc->activeV == 0
829 && (tvc->vstates & VRevokeWait)) {
830 tvc->vstates &= ~VRevokeWait;
831 afs_osi_Wakeup((char *)&tvc->vstates);
834 if (tvc->vstates & VPageCleaning) {
835 tvc->vstates &= ~VPageCleaning;
836 afs_osi_Wakeup((char *)&tvc->vstates);
839 ReleaseWriteLock(&tvc->vlock);
841 #endif /* AFS_SUN5_ENV */
843 ReleaseWriteLock(&afs_xdcache);
846 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
847 ObtainWriteLock(&afs_xdcache, 528);
848 if (afs_indexFlags[tdc->index] &
849 (IFDataMod | IFDirtyPages | IFAnyPages))
851 if (tdc->refCount > 1)
854 #if defined(AFS_SUN5_ENV)
856 /* no vnode, so IFDirtyPages is spurious (we don't
857 * sweep dcaches on vnode recycling, so we can have
858 * DIRTYPAGES set even when all pages are gone). Just
860 * Hold vcache lock to prevent vnode from being
861 * created while we're clearing IFDirtyPages.
863 afs_indexFlags[tdc->index] &=
864 ~(IFDirtyPages | IFAnyPages);
868 /* skip this guy and mark him as recently used */
869 afs_indexFlags[tdc->index] |= IFFlag;
870 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
871 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
872 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
873 ICL_HANDLE_OFFSET(tchunkoffset));
875 /* flush this dude from the data cache and reclaim;
876 * first, make sure no one will care that we damage
877 * it, by removing it from all hash tables. Then,
878 * melt it down for parts. Note that any concurrent
879 * (new possibility!) calls to GetDownD won't touch
880 * this guy because his reference count is > 0. */
881 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
882 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
883 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
884 ICL_HANDLE_OFFSET(tchunkoffset));
885 AFS_STATCNT(afs_gget);
886 afs_HashOutDCache(tdc, 1);
887 if (tdc->f.chunkBytes != 0) {
891 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
896 afs_DiscardDCache(tdc);
901 j = 1; /* we reclaimed at least one victim */
906 } /* end of for victims loop */
909 /* Phase is 0 and no one was found, so try phase 1 (ignore
910 * osi_Active flag) */
913 for (i = 0; i < afs_cacheFiles; i++)
914 /* turn off all flags */
915 afs_indexFlags[i] &= ~IFFlag;
918 /* found no one in phases 0-5, we're hosed */
922 } /* big while loop */
930 * Remove adc from any hash tables that would allow it to be located
931 * again by afs_FindDCache or afs_GetDCache.
933 * \param adc Pointer to dcache entry to remove from hash tables.
935 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
939 afs_HashOutDCache(struct dcache *adc, int zap)
943 AFS_STATCNT(afs_glink);
945 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
947 /* if this guy is in the hash table, pull him out */
948 if (adc->f.fid.Fid.Volume != 0) {
949 /* remove entry from first hash chains */
950 i = DCHash(&adc->f.fid, adc->f.chunk);
951 us = afs_dchashTbl[i];
952 if (us == adc->index) {
953 /* first dude in the list */
954 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
956 /* somewhere on the chain */
957 while (us != NULLIDX) {
958 if (afs_dcnextTbl[us] == adc->index) {
959 /* found item pointing at the one to delete */
960 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
963 us = afs_dcnextTbl[us];
966 osi_Panic("dcache hc");
968 /* remove entry from *other* hash chain */
969 i = DVHash(&adc->f.fid);
970 us = afs_dvhashTbl[i];
971 if (us == adc->index) {
972 /* first dude in the list */
973 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
975 /* somewhere on the chain */
976 while (us != NULLIDX) {
977 if (afs_dvnextTbl[us] == adc->index) {
978 /* found item pointing at the one to delete */
979 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
982 us = afs_dvnextTbl[us];
985 osi_Panic("dcache hv");
990 /* prevent entry from being found on a reboot (it is already out of
991 * the hash table, but after a crash, we just look at fid fields of
992 * stable (old) entries).
994 adc->f.fid.Fid.Volume = 0; /* invalid */
996 /* mark entry as modified */
997 adc->dflags |= DFEntryMod;
1002 } /*afs_HashOutDCache */
1005 * Flush the given dcache entry, pulling it from hash chains
1006 * and truncating the associated cache file.
1008 * \param adc Ptr to dcache entry to flush.
1010 * \note Environment:
1011 * This routine must be called with the afs_xdcache lock held
1015 afs_FlushDCache(struct dcache *adc)
1017 AFS_STATCNT(afs_FlushDCache);
1019 * Bump the number of cache files flushed.
1021 afs_stats_cmperf.cacheFlushes++;
1023 /* remove from all hash tables */
1024 afs_HashOutDCache(adc, 1);
1026 /* Free its space; special case null operation, since truncate operation
1027 * in UFS is slow even in this case, and this allows us to pre-truncate
1028 * these files at more convenient times with fewer locks set
1029 * (see afs_GetDownD).
1031 if (adc->f.chunkBytes != 0) {
1032 afs_DiscardDCache(adc);
1033 afs_MaybeWakeupTruncateDaemon();
1035 afs_FreeDCache(adc);
1037 } /*afs_FlushDCache */
1041 * Put a dcache entry on the free dcache entry list.
1043 * \param adc dcache entry to free.
1045 * \note Environment: called with afs_xdcache lock write-locked.
1048 afs_FreeDCache(struct dcache *adc)
1050 /* Thread on free list, update free list count and mark entry as
1051 * freed in its indexFlags element. Also, ensure DCache entry gets
1052 * written out (set DFEntryMod).
1055 afs_dvnextTbl[adc->index] = afs_freeDCList;
1056 afs_freeDCList = adc->index;
1058 afs_indexFlags[adc->index] |= IFFree;
1059 adc->dflags |= DFEntryMod;
1061 afs_WakeCacheWaitersIfDrained();
1062 } /* afs_FreeDCache */
1065 * Discard the cache element by moving it to the discardDCList.
1066 * This puts the cache element into a quasi-freed state, where
1067 * the space may be reused, but the file has not been truncated.
1069 * \note Major Assumptions Here:
1070 * Assumes that frag size is an integral power of two, less one,
1071 * and that this is a two's complement machine. I don't
1072 * know of any filesystems which violate this assumption...
1074 * \param adr Ptr to dcache entry.
1076 * \note Environment:
1077 * Must be called with afs_xdcache write-locked.
1081 afs_DiscardDCache(struct dcache *adc)
1085 AFS_STATCNT(afs_DiscardDCache);
1087 osi_Assert(adc->refCount == 1);
1089 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1090 afs_blocksDiscarded += size;
1091 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1093 afs_dvnextTbl[adc->index] = afs_discardDCList;
1094 afs_discardDCList = adc->index;
1095 afs_discardDCCount++;
1097 adc->f.fid.Fid.Volume = 0;
1098 adc->dflags |= DFEntryMod;
1099 afs_indexFlags[adc->index] |= IFDiscarded;
1101 afs_WakeCacheWaitersIfDrained();
1102 } /*afs_DiscardDCache */
1105 * Get a dcache entry from the discard or free list
1107 * @param[in] indexp A pointer to the head of the dcache free list or discard
1108 * list (afs_freeDCList, or afs_discardDCList)
1110 * @return A dcache from that list, or NULL if none could be retrieved.
1112 * @pre afs_xdcache is write-locked
1114 static struct dcache *
1115 afs_GetDSlotFromList(afs_int32 *indexp)
1119 for ( ; *indexp != NULLIDX; indexp = &afs_dvnextTbl[*indexp]) {
1120 tdc = afs_GetUnusedDSlot(*indexp);
1122 osi_Assert(tdc->refCount == 1);
1123 ReleaseReadLock(&tdc->tlock);
1124 *indexp = afs_dvnextTbl[tdc->index];
1125 afs_dvnextTbl[tdc->index] = NULLIDX;
1133 * Free the next element on the list of discarded cache elements.
1135 * Returns -1 if we encountered an error preventing us from freeing a
1136 * discarded dcache, or 0 on success.
1139 afs_FreeDiscardedDCache(void)
1142 struct osi_file *tfile;
1145 AFS_STATCNT(afs_FreeDiscardedDCache);
1147 ObtainWriteLock(&afs_xdcache, 510);
1148 if (!afs_blocksDiscarded) {
1149 ReleaseWriteLock(&afs_xdcache);
1154 * Get an entry from the list of discarded cache elements
1156 tdc = afs_GetDSlotFromList(&afs_discardDCList);
1158 ReleaseWriteLock(&afs_xdcache);
1162 afs_discardDCCount--;
1163 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1164 afs_blocksDiscarded -= size;
1165 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1166 /* We can lock because we just took it off the free list */
1167 ObtainWriteLock(&tdc->lock, 626);
1168 ReleaseWriteLock(&afs_xdcache);
1171 * Truncate the element to reclaim its space
1173 tfile = afs_CFileOpen(&tdc->f.inode);
1174 afs_CFileTruncate(tfile, 0);
1175 afs_CFileClose(tfile);
1176 afs_AdjustSize(tdc, 0);
1177 afs_DCMoveBucket(tdc, 0, 0);
1180 * Free the element we just truncated
1182 ObtainWriteLock(&afs_xdcache, 511);
1183 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1184 afs_FreeDCache(tdc);
1185 tdc->f.states &= ~(DRO|DBackup|DRW);
1186 ReleaseWriteLock(&tdc->lock);
1188 ReleaseWriteLock(&afs_xdcache);
1194 * Free as many entries from the list of discarded cache elements
1195 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1200 afs_MaybeFreeDiscardedDCache(void)
1203 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1205 while (afs_blocksDiscarded
1206 && (afs_blocksUsed >
1207 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1208 int code = afs_FreeDiscardedDCache();
1210 /* Callers depend on us to get the afs_blocksDiscarded count down.
1211 * If we cannot do that, the callers can spin by calling us over
1212 * and over. Panic for now until we can figure out something
1214 osi_Panic("Error freeing discarded dcache");
1221 * Try to free up a certain number of disk slots.
1223 * \param anumber Targeted number of disk slots to free up.
1225 * \note Environment:
1226 * Must be called with afs_xdcache write-locked.
1230 afs_GetDownDSlot(int anumber)
1232 struct afs_q *tq, *nq;
1237 AFS_STATCNT(afs_GetDownDSlot);
1238 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1239 osi_Panic("diskless getdowndslot");
1241 if (CheckLock(&afs_xdcache) != -1)
1242 osi_Panic("getdowndslot nolock");
1244 /* decrement anumber first for all dudes in free list */
1245 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1248 return; /* enough already free */
1250 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1252 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1253 nq = QPrev(tq); /* in case we remove it */
1254 if (tdc->refCount == 0) {
1255 if ((ix = tdc->index) == NULLIDX)
1256 osi_Panic("getdowndslot");
1257 /* pull the entry out of the lruq and put it on the free list */
1258 QRemove(&tdc->lruq);
1260 /* write-through if modified */
1261 if (tdc->dflags & DFEntryMod) {
1262 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1264 * ask proxy to do this for us - we don't have the stack space
1266 while (tdc->dflags & DFEntryMod) {
1269 s = SPLOCK(afs_sgibklock);
1270 if (afs_sgibklist == NULL) {
1271 /* if slot is free, grab it. */
1272 afs_sgibklist = tdc;
1273 SV_SIGNAL(&afs_sgibksync);
1275 /* wait for daemon to (start, then) finish. */
1276 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1280 tdc->dflags &= ~DFEntryMod;
1281 osi_Assert(afs_WriteDCache(tdc, 1) == 0);
1285 /* finally put the entry in the free list */
1286 afs_indexTable[ix] = NULL;
1287 afs_indexFlags[ix] &= ~IFEverUsed;
1288 tdc->index = NULLIDX;
1289 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1290 afs_freeDSList = tdc;
1294 } /*afs_GetDownDSlot */
1301 * Increment the reference count on a disk cache entry,
1302 * which already has a non-zero refcount. In order to
1303 * increment the refcount of a zero-reference entry, you
1304 * have to hold afs_xdcache.
1307 * adc : Pointer to the dcache entry to increment.
1310 * Nothing interesting.
1313 afs_RefDCache(struct dcache *adc)
1315 ObtainWriteLock(&adc->tlock, 627);
1316 if (adc->refCount < 0)
1317 osi_Panic("RefDCache: negative refcount");
1319 ReleaseWriteLock(&adc->tlock);
1328 * Decrement the reference count on a disk cache entry.
1331 * ad : Ptr to the dcache entry to decrement.
1334 * Nothing interesting.
1337 afs_PutDCache(struct dcache *adc)
1339 AFS_STATCNT(afs_PutDCache);
1340 ObtainWriteLock(&adc->tlock, 276);
1341 if (adc->refCount <= 0)
1342 osi_Panic("putdcache");
1344 ReleaseWriteLock(&adc->tlock);
1353 * Try to discard all data associated with this file from the
1357 * avc : Pointer to the cache info for the file.
1360 * Both pvnLock and lock are write held.
1363 afs_TryToSmush(struct vcache *avc, afs_ucred_t *acred, int sync)
1368 AFS_STATCNT(afs_TryToSmush);
1369 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1370 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1371 sync = 1; /* XX Temp testing XX */
1373 #if defined(AFS_SUN5_ENV)
1374 ObtainWriteLock(&avc->vlock, 573);
1375 avc->activeV++; /* block new getpages */
1376 ReleaseWriteLock(&avc->vlock);
1379 /* Flush VM pages */
1380 osi_VM_TryToSmush(avc, acred, sync);
1383 * Get the hash chain containing all dce's for this fid
1385 i = DVHash(&avc->f.fid);
1386 ObtainWriteLock(&afs_xdcache, 277);
1387 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1388 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1389 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1390 int releaseTlock = 1;
1391 tdc = afs_GetValidDSlot(index);
1393 /* afs_TryToSmush is best-effort; we may not actually discard
1394 * everything, so failure to discard a dcache due to an i/o
1398 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1400 if ((afs_indexFlags[index] & IFDataMod) == 0
1401 && tdc->refCount == 1) {
1402 ReleaseReadLock(&tdc->tlock);
1404 afs_FlushDCache(tdc);
1407 afs_indexTable[index] = 0;
1410 ReleaseReadLock(&tdc->tlock);
1414 #if defined(AFS_SUN5_ENV)
1415 ObtainWriteLock(&avc->vlock, 545);
1416 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1417 avc->vstates &= ~VRevokeWait;
1418 afs_osi_Wakeup((char *)&avc->vstates);
1420 ReleaseWriteLock(&avc->vlock);
1422 ReleaseWriteLock(&afs_xdcache);
1424 * It's treated like a callback so that when we do lookups we'll
1425 * invalidate the unique bit if any
1426 * trytoSmush occured during the lookup call
1432 * afs_DCacheMissingChunks
1435 * Given the cached info for a file, return the number of chunks that
1436 * are not available from the dcache.
1439 * avc: Pointer to the (held) vcache entry to look in.
1442 * The number of chunks which are not currently cached.
1445 * The vcache entry is held upon entry.
1449 afs_DCacheMissingChunks(struct vcache *avc)
1452 afs_size_t totalLength = 0;
1453 afs_uint32 totalChunks = 0;
1456 totalLength = avc->f.m.Length;
1457 if (avc->f.truncPos < totalLength)
1458 totalLength = avc->f.truncPos;
1460 /* Length is 0, no chunk missing. */
1461 if (totalLength == 0)
1464 /* If totalLength is a multiple of chunksize, the last byte appears
1465 * as being part of the next chunk, which does not exist.
1466 * Decrementing totalLength by one fixes that.
1469 totalChunks = (AFS_CHUNK(totalLength) + 1);
1471 /* If we're a directory, we only ever have one chunk, regardless of
1472 * the size of the dir.
1474 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1478 printf("Should have %d chunks for %u bytes\n",
1479 totalChunks, (totalLength + 1));
1481 i = DVHash(&avc->f.fid);
1482 ObtainWriteLock(&afs_xdcache, 1001);
1483 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1484 i = afs_dvnextTbl[index];
1485 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1486 tdc = afs_GetValidDSlot(index);
1488 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1491 ReleaseReadLock(&tdc->tlock);
1496 ReleaseWriteLock(&afs_xdcache);
1498 /*printf("Missing %d chunks\n", totalChunks);*/
1500 return (totalChunks);
1507 * Given the cached info for a file and a byte offset into the
1508 * file, make sure the dcache entry for that file and containing
1509 * the given byte is available, returning it to our caller.
1512 * avc : Pointer to the (held) vcache entry to look in.
1513 * abyte : Which byte we want to get to.
1516 * Pointer to the dcache entry covering the file & desired byte,
1517 * or NULL if not found.
1520 * The vcache entry is held upon entry.
1524 afs_FindDCache(struct vcache *avc, afs_size_t abyte)
1528 struct dcache *tdc = NULL;
1530 AFS_STATCNT(afs_FindDCache);
1531 chunk = AFS_CHUNK(abyte);
1534 * Hash on the [fid, chunk] and get the corresponding dcache index
1535 * after write-locking the dcache.
1537 i = DCHash(&avc->f.fid, chunk);
1538 ObtainWriteLock(&afs_xdcache, 278);
1539 for (index = afs_dchashTbl[i]; index != NULLIDX; index = afs_dcnextTbl[index]) {
1540 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1541 tdc = afs_GetValidDSlot(index);
1543 /* afs_FindDCache is best-effort; we may not find the given
1544 * file/offset, so if we cannot find the given dcache due to
1545 * i/o errors, that is okay. */
1548 ReleaseReadLock(&tdc->tlock);
1549 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1550 break; /* leaving refCount high for caller */
1555 if (index != NULLIDX) {
1556 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1557 hadd32(afs_indexCounter, 1);
1558 ReleaseWriteLock(&afs_xdcache);
1561 ReleaseWriteLock(&afs_xdcache);
1563 } /*afs_FindDCache */
1565 /* only call these from afs_AllocDCache() */
1566 static struct dcache *
1567 afs_AllocFreeDSlot(void)
1571 tdc = afs_GetDSlotFromList(&afs_freeDCList);
1575 afs_indexFlags[tdc->index] &= ~IFFree;
1576 ObtainWriteLock(&tdc->lock, 604);
1581 static struct dcache *
1582 afs_AllocDiscardDSlot(afs_int32 lock)
1585 afs_uint32 size = 0;
1586 struct osi_file *file;
1588 tdc = afs_GetDSlotFromList(&afs_discardDCList);
1592 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1593 ObtainWriteLock(&tdc->lock, 605);
1594 afs_discardDCCount--;
1596 ((tdc->f.chunkBytes +
1597 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1598 tdc->f.states &= ~(DRO|DBackup|DRW);
1599 afs_DCMoveBucket(tdc, size, 0);
1600 afs_blocksDiscarded -= size;
1601 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1603 /* Truncate the chunk so zeroes get filled properly */
1604 file = afs_CFileOpen(&tdc->f.inode);
1605 afs_CFileTruncate(file, 0);
1606 afs_CFileClose(file);
1607 afs_AdjustSize(tdc, 0);
1614 * Get a fresh dcache from the free or discarded list.
1616 * \param avc Who's dcache is this going to be?
1617 * \param chunk The position where it will be placed in.
1618 * \param lock How are locks held.
1619 * \param ashFid If this dcache going to be used for a shadow dir,
1622 * \note Required locks:
1624 * - avc (R if (lock & 1) set and W otherwise)
1625 * \note It write locks the new dcache. The caller must unlock it.
1627 * \return The new dcache.
1630 afs_AllocDCache(struct vcache *avc, afs_int32 chunk, afs_int32 lock,
1631 struct VenusFid *ashFid)
1633 struct dcache *tdc = NULL;
1635 /* if (lock & 2), prefer 'free' dcaches; otherwise, prefer 'discard'
1636 * dcaches. In either case, try both if our first choice doesn't work. */
1638 tdc = afs_AllocFreeDSlot();
1640 tdc = afs_AllocDiscardDSlot(lock);
1643 tdc = afs_AllocDiscardDSlot(lock);
1645 tdc = afs_AllocFreeDSlot();
1654 * avc->lock(R) if setLocks
1655 * avc->lock(W) if !setLocks
1661 * Fill in the newly-allocated dcache record.
1663 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1665 /* Use shadow fid if provided. */
1666 tdc->f.fid = *ashFid;
1668 /* Use normal vcache's fid otherwise. */
1669 tdc->f.fid = avc->f.fid;
1670 if (avc->f.states & CRO)
1671 tdc->f.states = DRO;
1672 else if (avc->f.states & CBackup)
1673 tdc->f.states = DBackup;
1675 tdc->f.states = DRW;
1676 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1677 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1679 hones(tdc->f.versionNo); /* invalid value */
1680 tdc->f.chunk = chunk;
1681 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1683 if (tdc->lruq.prev == &tdc->lruq)
1684 osi_Panic("lruq 1");
1693 * This function is called to obtain a reference to data stored in
1694 * the disk cache, locating a chunk of data containing the desired
1695 * byte and returning a reference to the disk cache entry, with its
1696 * reference count incremented.
1700 * avc : Ptr to a vcache entry (unlocked)
1701 * abyte : Byte position in the file desired
1702 * areq : Request structure identifying the requesting user.
1703 * aflags : Settings as follows:
1705 * 2 : Return after creating entry.
1706 * 4 : called from afs_vnop_write.c
1707 * *alen contains length of data to be written.
1709 * aoffset : Set to the offset within the chunk where the resident
1711 * alen : Set to the number of bytes of data after the desired
1712 * byte (including the byte itself) which can be read
1716 * The vcache entry pointed to by avc is unlocked upon entry.
1720 * Update the vnode-to-dcache hint if we can get the vnode lock
1721 * right away. Assumes dcache entry is at least read-locked.
1724 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1726 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1727 if (hsame(v->f.m.DataVersion, d->f.versionNo) && v->callback)
1730 ReleaseWriteLock(&v->lock);
1734 /* avc - Write-locked unless aflags & 1 */
1736 afs_GetDCache(struct vcache *avc, afs_size_t abyte,
1737 struct vrequest *areq, afs_size_t * aoffset,
1738 afs_size_t * alen, int aflags)
1740 afs_int32 i, code, shortcut;
1741 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1742 afs_int32 adjustsize = 0;
1748 afs_size_t Position = 0;
1749 afs_int32 size, tlen; /* size of segment to transfer */
1750 struct afs_FetchOutput *tsmall = 0;
1752 struct osi_file *file;
1753 struct afs_conn *tc;
1755 struct server *newCallback = NULL;
1756 char setNewCallback;
1757 char setVcacheStatus;
1758 char doVcacheUpdate;
1760 int doAdjustSize = 0;
1761 int doReallyAdjustSize = 0;
1762 int overWriteWholeChunk = 0;
1763 struct rx_connection *rxconn;
1766 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1767 int fromReplica; /*Are we reading from a replica? */
1768 int numFetchLoops; /*# times around the fetch/analyze loop */
1769 #endif /* AFS_NOSTATS */
1771 AFS_STATCNT(afs_GetDCache);
1775 setLocks = aflags & 1;
1778 * Determine the chunk number and offset within the chunk corresponding
1779 * to the desired byte.
1781 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1784 chunk = AFS_CHUNK(abyte);
1787 /* come back to here if we waited for the cache to drain. */
1790 setNewCallback = setVcacheStatus = 0;
1794 ObtainWriteLock(&avc->lock, 616);
1796 ObtainReadLock(&avc->lock);
1801 * avc->lock(R) if setLocks && !slowPass
1802 * avc->lock(W) if !setLocks || slowPass
1807 /* check hints first! (might could use bcmp or some such...) */
1808 if ((tdc = avc->dchint)) {
1812 * The locking order between afs_xdcache and dcache lock matters.
1813 * The hint dcache entry could be anywhere, even on the free list.
1814 * Locking afs_xdcache ensures that noone is trying to pull dcache
1815 * entries from the free list, and thereby assuming them to be not
1816 * referenced and not locked.
1818 ObtainReadLock(&afs_xdcache);
1819 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1821 if (dcLocked && (tdc->index != NULLIDX)
1822 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
1823 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1824 /* got the right one. It might not be the right version, and it
1825 * might be fetching, but it's the right dcache entry.
1827 /* All this code should be integrated better with what follows:
1828 * I can save a good bit more time under a write lock if I do..
1830 ObtainWriteLock(&tdc->tlock, 603);
1832 ReleaseWriteLock(&tdc->tlock);
1834 ReleaseReadLock(&afs_xdcache);
1837 if (hsame(tdc->f.versionNo, avc->f.m.DataVersion)
1838 && !(tdc->dflags & DFFetching)) {
1840 afs_stats_cmperf.dcacheHits++;
1841 ObtainWriteLock(&afs_xdcache, 559);
1842 QRemove(&tdc->lruq);
1843 QAdd(&afs_DLRU, &tdc->lruq);
1844 ReleaseWriteLock(&afs_xdcache);
1847 * avc->lock(R) if setLocks && !slowPass
1848 * avc->lock(W) if !setLocks || slowPass
1855 ReleaseSharedLock(&tdc->lock);
1856 ReleaseReadLock(&afs_xdcache);
1864 * avc->lock(R) if setLocks && !slowPass
1865 * avc->lock(W) if !setLocks || slowPass
1866 * tdc->lock(S) if tdc
1869 if (!tdc) { /* If the hint wasn't the right dcache entry */
1870 int dslot_error = 0;
1872 * Hash on the [fid, chunk] and get the corresponding dcache index
1873 * after write-locking the dcache.
1878 * avc->lock(R) if setLocks && !slowPass
1879 * avc->lock(W) if !setLocks || slowPass
1882 i = DCHash(&avc->f.fid, chunk);
1883 /* check to make sure our space is fine */
1884 afs_MaybeWakeupTruncateDaemon();
1886 ObtainWriteLock(&afs_xdcache, 280);
1888 for (index = afs_dchashTbl[i]; index != NULLIDX; us = index, index = afs_dcnextTbl[index]) {
1889 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1890 tdc = afs_GetValidDSlot(index);
1892 /* we got an i/o error when trying to get the given dslot,
1893 * but do not bail out just yet; it is possible the dcache
1894 * we're looking for is elsewhere, so it doesn't matter if
1895 * we can't load this one. */
1899 ReleaseReadLock(&tdc->tlock);
1902 * avc->lock(R) if setLocks && !slowPass
1903 * avc->lock(W) if !setLocks || slowPass
1906 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1907 /* Move it up in the beginning of the list */
1908 if (afs_dchashTbl[i] != index) {
1909 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1910 afs_dcnextTbl[index] = afs_dchashTbl[i];
1911 afs_dchashTbl[i] = index;
1913 ReleaseWriteLock(&afs_xdcache);
1914 ObtainSharedLock(&tdc->lock, 606);
1915 break; /* leaving refCount high for caller */
1923 * If we didn't find the entry, we'll create one.
1925 if (index == NULLIDX) {
1928 * avc->lock(R) if setLocks
1929 * avc->lock(W) if !setLocks
1932 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1933 avc, ICL_TYPE_INT32, chunk);
1936 /* We couldn't find the dcache we want, but we hit some i/o
1937 * errors when trying to find it, so we're not sure if the
1938 * dcache we want is in the cache or not. Error out, so we
1939 * don't try to possibly create 2 separate dcaches for the
1940 * same exact data. */
1941 ReleaseWriteLock(&afs_xdcache);
1945 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1947 avc->f.states |= CDCLock;
1948 /* just need slots */
1949 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1951 avc->f.states &= ~CDCLock;
1953 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
1955 /* If we can't get space for 5 mins we give up and panic */
1956 if (++downDCount > 300)
1957 osi_Panic("getdcache");
1958 ReleaseWriteLock(&afs_xdcache);
1961 * avc->lock(R) if setLocks
1962 * avc->lock(W) if !setLocks
1964 afs_osi_Wait(1000, 0, 0);
1970 * avc->lock(R) if setLocks
1971 * avc->lock(W) if !setLocks
1977 * Now add to the two hash chains - note that i is still set
1978 * from the above DCHash call.
1980 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1981 afs_dchashTbl[i] = tdc->index;
1982 i = DVHash(&avc->f.fid);
1983 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1984 afs_dvhashTbl[i] = tdc->index;
1985 tdc->dflags = DFEntryMod;
1987 afs_MaybeWakeupTruncateDaemon();
1988 ReleaseWriteLock(&afs_xdcache);
1989 ConvertWToSLock(&tdc->lock);
1994 /* vcache->dcache hint failed */
1997 * avc->lock(R) if setLocks && !slowPass
1998 * avc->lock(W) if !setLocks || slowPass
2001 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
2002 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2003 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
2004 hgetlo(avc->f.m.DataVersion));
2006 * Here we have the entry in tdc, with its refCount incremented.
2007 * Note: we don't use the S-lock on avc; it costs concurrency when
2008 * storing a file back to the server.
2012 * Not a newly created file so we need to check the file's length and
2013 * compare data versions since someone could have changed the data or we're
2014 * reading a file written elsewhere. We only want to bypass doing no-op
2015 * read rpcs on newly created files (dv of 0) since only then we guarantee
2016 * that this chunk's data hasn't been filled by another client.
2018 size = AFS_CHUNKSIZE(abyte);
2019 if (aflags & 4) /* called from write */
2021 else /* called from read */
2022 tlen = tdc->validPos - abyte;
2023 Position = AFS_CHUNKTOBASE(chunk);
2024 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
2025 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
2026 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
2027 ICL_HANDLE_OFFSET(Position));
2028 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
2030 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
2031 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
2032 overWriteWholeChunk = 1;
2033 if (doAdjustSize || overWriteWholeChunk) {
2034 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
2036 #ifdef AFS_SGI64_ENV
2039 #else /* AFS_SGI64_ENV */
2042 #endif /* AFS_SGI64_ENV */
2043 #else /* AFS_SGI_ENV */
2046 #endif /* AFS_SGI_ENV */
2047 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
2048 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2049 #if defined(AFS_SUN5_ENV)
2050 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
2052 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
2054 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2055 !hsame(avc->f.m.DataVersion, tdc->f.versionNo))
2056 doReallyAdjustSize = 1;
2058 if (doReallyAdjustSize || overWriteWholeChunk) {
2059 /* no data in file to read at this position */
2060 UpgradeSToWLock(&tdc->lock, 607);
2061 file = afs_CFileOpen(&tdc->f.inode);
2062 afs_CFileTruncate(file, 0);
2063 afs_CFileClose(file);
2064 afs_AdjustSize(tdc, 0);
2065 hset(tdc->f.versionNo, avc->f.m.DataVersion);
2066 tdc->dflags |= DFEntryMod;
2068 ConvertWToSLock(&tdc->lock);
2073 * We must read in the whole chunk if the version number doesn't
2077 /* don't need data, just a unique dcache entry */
2078 ObtainWriteLock(&afs_xdcache, 608);
2079 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2080 hadd32(afs_indexCounter, 1);
2081 ReleaseWriteLock(&afs_xdcache);
2083 updateV2DC(setLocks, avc, tdc, 553);
2084 if (vType(avc) == VDIR)
2087 *aoffset = AFS_CHUNKOFFSET(abyte);
2088 if (tdc->validPos < abyte)
2089 *alen = (afs_size_t) 0;
2091 *alen = tdc->validPos - abyte;
2092 ReleaseSharedLock(&tdc->lock);
2095 ReleaseWriteLock(&avc->lock);
2097 ReleaseReadLock(&avc->lock);
2099 return tdc; /* check if we're done */
2104 * avc->lock(R) if setLocks && !slowPass
2105 * avc->lock(W) if !setLocks || slowPass
2108 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
2110 setNewCallback = setVcacheStatus = 0;
2114 * avc->lock(R) if setLocks && !slowPass
2115 * avc->lock(W) if !setLocks || slowPass
2118 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
2120 * Version number mismatch.
2123 * If we are disconnected, then we can't do much of anything
2124 * because the data doesn't match the file.
2126 if (AFS_IS_DISCONNECTED) {
2127 ReleaseSharedLock(&tdc->lock);
2130 ReleaseWriteLock(&avc->lock);
2132 ReleaseReadLock(&avc->lock);
2134 /* Flush the Dcache */
2139 UpgradeSToWLock(&tdc->lock, 609);
2142 * If data ever existed for this vnode, and this is a text object,
2143 * do some clearing. Now, you'd think you need only do the flush
2144 * when VTEXT is on, but VTEXT is turned off when the text object
2145 * is freed, while pages are left lying around in memory marked
2146 * with this vnode. If we would reactivate (create a new text
2147 * object from) this vnode, we could easily stumble upon some of
2148 * these old pages in pagein. So, we always flush these guys.
2149 * Sun has a wonderful lack of useful invariants in this system.
2151 * avc->flushDV is the data version # of the file at the last text
2152 * flush. Clearly, at least, we don't have to flush the file more
2153 * often than it changes
2155 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2157 * By here, the cache entry is always write-locked. We can
2158 * deadlock if we call osi_Flush with the cache entry locked...
2159 * Unlock the dcache too.
2161 ReleaseWriteLock(&tdc->lock);
2162 if (setLocks && !slowPass)
2163 ReleaseReadLock(&avc->lock);
2165 ReleaseWriteLock(&avc->lock);
2169 * Call osi_FlushPages in open, read/write, and map, since it
2170 * is too hard here to figure out if we should lock the
2173 if (setLocks && !slowPass)
2174 ObtainReadLock(&avc->lock);
2176 ObtainWriteLock(&avc->lock, 66);
2177 ObtainWriteLock(&tdc->lock, 610);
2182 * avc->lock(R) if setLocks && !slowPass
2183 * avc->lock(W) if !setLocks || slowPass
2187 /* Watch for standard race condition around osi_FlushText */
2188 if (hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
2189 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2190 afs_stats_cmperf.dcacheHits++;
2191 ConvertWToSLock(&tdc->lock);
2195 /* Sleep here when cache needs to be drained. */
2196 if (setLocks && !slowPass
2197 && (afs_blocksUsed >
2198 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2199 /* Make sure truncate daemon is running */
2200 afs_MaybeWakeupTruncateDaemon();
2201 ObtainWriteLock(&tdc->tlock, 614);
2202 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2203 ReleaseWriteLock(&tdc->tlock);
2204 ReleaseWriteLock(&tdc->lock);
2205 ReleaseReadLock(&avc->lock);
2206 while ((afs_blocksUsed - afs_blocksDiscarded) >
2207 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2208 afs_WaitForCacheDrain = 1;
2209 afs_osi_Sleep(&afs_WaitForCacheDrain);
2211 afs_MaybeFreeDiscardedDCache();
2212 /* need to check if someone else got the chunk first. */
2213 goto RetryGetDCache;
2216 Position = AFS_CHUNKBASE(abyte);
2217 if (vType(avc) == VDIR) {
2218 size = avc->f.m.Length;
2219 if (size > tdc->f.chunkBytes) {
2220 /* pre-reserve space for file */
2221 afs_AdjustSize(tdc, size);
2223 size = 999999999; /* max size for transfer */
2225 afs_size_t maxGoodLength;
2227 /* estimate how much data we're expecting back from the server,
2228 * and reserve space in the dcache entry for it */
2230 maxGoodLength = avc->f.m.Length;
2231 if (avc->f.truncPos < maxGoodLength)
2232 maxGoodLength = avc->f.truncPos;
2234 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2235 if (Position > maxGoodLength) { /* If we're beyond EOF */
2237 } else if (Position + size > maxGoodLength) {
2238 size = maxGoodLength - Position;
2240 osi_Assert(size >= 0);
2242 if (size > tdc->f.chunkBytes) {
2243 /* pre-reserve estimated space for file */
2244 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2248 /* For the actual fetch, do not limit the request to the
2249 * length of the file. If this results in a read past EOF on
2250 * the server, the server will just reply with less data than
2251 * requested. If we limit ourselves to only requesting data up
2252 * to the avc file length, we open ourselves up to races if the
2253 * file is extended on the server at about the same time.
2255 * However, we must restrict ourselves to the avc->f.truncPos
2256 * length, since this represents an outstanding local
2257 * truncation of the file that will be committed to the
2258 * fileserver when we actually write the fileserver contents.
2259 * If we do not restrict the fetch length based on
2260 * avc->f.truncPos, a different truncate operation extending
2261 * the file length could cause the old data after
2262 * avc->f.truncPos to reappear, instead of extending the file
2263 * with NUL bytes. */
2264 size = AFS_CHUNKSIZE(abyte);
2265 if (Position > avc->f.truncPos) {
2267 } else if (Position + size > avc->f.truncPos) {
2268 size = avc->f.truncPos - Position;
2270 osi_Assert(size >= 0);
2273 if (afs_mariner && !tdc->f.chunk)
2274 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2276 * Right now, we only have one tool, and it's a hammer. So, we
2277 * fetch the whole file.
2279 DZap(tdc); /* pages in cache may be old */
2280 file = afs_CFileOpen(&tdc->f.inode);
2281 afs_RemoveVCB(&avc->f.fid);
2282 tdc->f.states |= DWriting;
2283 tdc->dflags |= DFFetching;
2284 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2285 if (tdc->mflags & DFFetchReq) {
2286 tdc->mflags &= ~DFFetchReq;
2287 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2288 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2289 __FILE__, ICL_TYPE_INT32, __LINE__,
2290 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2293 tsmall = osi_AllocLargeSpace(sizeof(struct afs_FetchOutput));
2294 setVcacheStatus = 0;
2297 * Remember if we are doing the reading from a replicated volume,
2298 * and how many times we've zipped around the fetch/analyze loop.
2300 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2302 accP = &(afs_stats_cmfullperf.accessinf);
2304 (accP->replicatedRefs)++;
2306 (accP->unreplicatedRefs)++;
2307 #endif /* AFS_NOSTATS */
2308 /* this is a cache miss */
2309 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2310 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2311 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2314 afs_stats_cmperf.dcacheMisses++;
2317 * Dynamic root support: fetch data from local memory.
2319 if (afs_IsDynroot(avc)) {
2323 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2325 dynrootDir += Position;
2326 dynrootLen -= Position;
2327 if (size > dynrootLen)
2331 code = afs_CFileWrite(file, 0, dynrootDir, size);
2339 tdc->validPos = Position + size;
2340 afs_CFileTruncate(file, size); /* prune it */
2341 } else if (afs_IsDynrootMount(avc)) {
2345 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2347 dynrootDir += Position;
2348 dynrootLen -= Position;
2349 if (size > dynrootLen)
2353 code = afs_CFileWrite(file, 0, dynrootDir, size);
2361 tdc->validPos = Position + size;
2362 afs_CFileTruncate(file, size); /* prune it */
2365 * Not a dynamic vnode: do the real fetch.
2370 * avc->lock(R) if setLocks && !slowPass
2371 * avc->lock(W) if !setLocks || slowPass
2375 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
2380 (accP->numReplicasAccessed)++;
2382 #endif /* AFS_NOSTATS */
2383 if (!setLocks || slowPass) {
2384 avc->callback = tc->parent->srvr->server;
2386 newCallback = tc->parent->srvr->server;
2390 code = afs_CacheFetchProc(tc, rxconn, file, Position, tdc,
2396 /* callback could have been broken (or expired) in a race here,
2397 * but we return the data anyway. It's as good as we knew about
2398 * when we started. */
2400 * validPos is updated by CacheFetchProc, and can only be
2401 * modifed under a dcache write lock, which we've blocked out
2403 size = tdc->validPos - Position; /* actual segment size */
2406 afs_CFileTruncate(file, size); /* prune it */
2408 if (!setLocks || slowPass) {
2409 ObtainWriteLock(&afs_xcbhash, 453);
2410 afs_DequeueCallback(avc);
2411 avc->f.states &= ~(CStatd | CUnique);
2412 avc->callback = NULL;
2413 ReleaseWriteLock(&afs_xcbhash);
2414 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2415 osi_dnlc_purgedp(avc);
2417 /* Something lost. Forget about performance, and go
2418 * back with a vcache write lock.
2420 afs_CFileTruncate(file, 0);
2421 afs_AdjustSize(tdc, 0);
2422 afs_CFileClose(file);
2423 osi_FreeLargeSpace(tsmall);
2425 ReleaseWriteLock(&tdc->lock);
2428 ReleaseReadLock(&avc->lock);
2431 /* If we have a connection, we must put it back,
2432 * since afs_Analyze will not be called here. */
2433 afs_PutConn(tc, rxconn, SHARED_LOCK);
2437 goto RetryGetDCache;
2441 } while (afs_Analyze
2442 (tc, rxconn, code, &avc->f.fid, areq,
2443 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2447 * avc->lock(R) if setLocks && !slowPass
2448 * avc->lock(W) if !setLocks || slowPass
2454 * In the case of replicated access, jot down info on the number of
2455 * attempts it took before we got through or gave up.
2458 if (numFetchLoops <= 1)
2459 (accP->refFirstReplicaOK)++;
2460 if (numFetchLoops > accP->maxReplicasPerRef)
2461 accP->maxReplicasPerRef = numFetchLoops;
2463 #endif /* AFS_NOSTATS */
2465 tdc->dflags &= ~DFFetching;
2466 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2467 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2468 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2469 tdc, ICL_TYPE_INT32, tdc->dflags);
2470 if (avc->execsOrWriters == 0)
2471 tdc->f.states &= ~DWriting;
2473 /* now, if code != 0, we have an error and should punt.
2474 * note that we have the vcache write lock, either because
2475 * !setLocks or slowPass.
2478 afs_CFileTruncate(file, 0);
2479 afs_AdjustSize(tdc, 0);
2480 afs_CFileClose(file);
2481 ZapDCE(tdc); /* sets DFEntryMod */
2482 if (vType(avc) == VDIR) {
2485 tdc->f.states &= ~(DRO|DBackup|DRW);
2486 afs_DCMoveBucket(tdc, 0, 0);
2487 ReleaseWriteLock(&tdc->lock);
2489 if (!afs_IsDynroot(avc)) {
2490 ObtainWriteLock(&afs_xcbhash, 454);
2491 afs_DequeueCallback(avc);
2492 avc->f.states &= ~(CStatd | CUnique);
2493 ReleaseWriteLock(&afs_xcbhash);
2494 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2495 osi_dnlc_purgedp(avc);
2498 * avc->lock(W); assert(!setLocks || slowPass)
2500 osi_Assert(!setLocks || slowPass);
2506 /* otherwise we copy in the just-fetched info */
2507 afs_CFileClose(file);
2508 afs_AdjustSize(tdc, size); /* new size */
2510 * Copy appropriate fields into vcache. Status is
2511 * copied later where we selectively acquire the
2512 * vcache write lock.
2515 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2517 setVcacheStatus = 1;
2518 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2519 tsmall->OutStatus.DataVersion);
2520 tdc->dflags |= DFEntryMod;
2521 afs_indexFlags[tdc->index] |= IFEverUsed;
2522 ConvertWToSLock(&tdc->lock);
2523 } /*Data version numbers don't match */
2526 * Data version numbers match.
2528 afs_stats_cmperf.dcacheHits++;
2529 } /*Data version numbers match */
2531 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2535 * avc->lock(R) if setLocks && !slowPass
2536 * avc->lock(W) if !setLocks || slowPass
2537 * tdc->lock(S) if tdc
2541 * See if this was a reference to a file in the local cell.
2543 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2544 afs_stats_cmperf.dlocalAccesses++;
2546 afs_stats_cmperf.dremoteAccesses++;
2548 /* Fix up LRU info */
2551 ObtainWriteLock(&afs_xdcache, 602);
2552 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2553 hadd32(afs_indexCounter, 1);
2554 ReleaseWriteLock(&afs_xdcache);
2556 /* return the data */
2557 if (vType(avc) == VDIR)
2560 *aoffset = AFS_CHUNKOFFSET(abyte);
2561 *alen = (tdc->f.chunkBytes - *aoffset);
2562 ReleaseSharedLock(&tdc->lock);
2567 * avc->lock(R) if setLocks && !slowPass
2568 * avc->lock(W) if !setLocks || slowPass
2571 /* Fix up the callback and status values in the vcache */
2573 if (setLocks && !slowPass) {
2576 * This is our dirty little secret to parallel fetches.
2577 * We don't write-lock the vcache while doing the fetch,
2578 * but potentially we'll need to update the vcache after
2579 * the fetch is done.
2581 * Drop the read lock and try to re-obtain the write
2582 * lock. If the vcache still has the same DV, it's
2583 * ok to go ahead and install the new data.
2585 afs_hyper_t currentDV, statusDV;
2587 hset(currentDV, avc->f.m.DataVersion);
2589 if (setNewCallback && avc->callback != newCallback)
2593 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2594 tsmall->OutStatus.DataVersion);
2596 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2598 if (setVcacheStatus && !hsame(currentDV, statusDV))
2602 ReleaseReadLock(&avc->lock);
2604 if (doVcacheUpdate) {
2605 ObtainWriteLock(&avc->lock, 615);
2606 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2607 /* We lose. Someone will beat us to it. */
2609 ReleaseWriteLock(&avc->lock);
2614 /* With slow pass, we've already done all the updates */
2616 ReleaseWriteLock(&avc->lock);
2619 /* Check if we need to perform any last-minute fixes with a write-lock */
2620 if (!setLocks || doVcacheUpdate) {
2622 avc->callback = newCallback;
2623 if (tsmall && setVcacheStatus)
2624 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2626 ReleaseWriteLock(&avc->lock);
2630 osi_FreeLargeSpace(tsmall);
2633 } /*afs_GetDCache */
2637 * afs_WriteThroughDSlots
2640 * Sweep through the dcache slots and write out any modified
2641 * in-memory data back on to our caching store.
2647 * The afs_xdcache is write-locked through this whole affair.
2650 afs_WriteThroughDSlots(void)
2653 afs_int32 i, touchedit = 0;
2655 struct afs_q DirtyQ, *tq;
2657 AFS_STATCNT(afs_WriteThroughDSlots);
2660 * Because of lock ordering, we can't grab dcache locks while
2661 * holding afs_xdcache. So we enter xdcache, get a reference
2662 * for every dcache entry, and exit xdcache.
2664 ObtainWriteLock(&afs_xdcache, 283);
2666 for (i = 0; i < afs_cacheFiles; i++) {
2667 tdc = afs_indexTable[i];
2669 /* Grab tlock in case the existing refcount isn't zero */
2670 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2671 ObtainWriteLock(&tdc->tlock, 623);
2673 ReleaseWriteLock(&tdc->tlock);
2675 QAdd(&DirtyQ, &tdc->dirty);
2678 ReleaseWriteLock(&afs_xdcache);
2681 * Now, for each dcache entry we found, check if it's dirty.
2682 * If so, get write-lock, get afs_xdcache, which protects
2683 * afs_cacheInodep, and flush it. Don't forget to put back
2687 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2689 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2691 if (tdc->dflags & DFEntryMod) {
2694 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2696 /* Now that we have the write lock, double-check */
2697 if (wrLock && (tdc->dflags & DFEntryMod)) {
2698 tdc->dflags &= ~DFEntryMod;
2699 ObtainWriteLock(&afs_xdcache, 620);
2700 osi_Assert(afs_WriteDCache(tdc, 1) == 0);
2701 ReleaseWriteLock(&afs_xdcache);
2705 ReleaseWriteLock(&tdc->lock);
2711 ObtainWriteLock(&afs_xdcache, 617);
2712 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2713 /* Touch the file to make sure that the mtime on the file is kept
2714 * up-to-date to avoid losing cached files on cold starts because
2715 * their mtime seems old...
2717 struct afs_fheader theader;
2719 afs_InitFHeader(&theader);
2720 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2722 ReleaseWriteLock(&afs_xdcache);
2729 * Return a pointer to an freshly initialized dcache entry using
2730 * a memory-based cache. The tlock will be read-locked.
2733 * aslot : Dcache slot to look at.
2734 * type : What 'type' of dslot to get; see the dslot_state enum
2737 * Must be called with afs_xdcache write-locked.
2741 afs_MemGetDSlot(afs_int32 aslot, dslot_state type)
2746 AFS_STATCNT(afs_MemGetDSlot);
2747 if (CheckLock(&afs_xdcache) != -1)
2748 osi_Panic("getdslot nolock");
2749 if (aslot < 0 || aslot >= afs_cacheFiles)
2750 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2751 tdc = afs_indexTable[aslot];
2753 QRemove(&tdc->lruq); /* move to queue head */
2754 QAdd(&afs_DLRU, &tdc->lruq);
2755 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2756 ObtainWriteLock(&tdc->tlock, 624);
2758 ConvertWToRLock(&tdc->tlock);
2762 /* if we got here, the given slot is not in memory in our list of known
2763 * slots. for memcache, the only place a dslot can exist is in memory, so
2764 * if the caller is expecting to get back a known dslot, and we've reached
2765 * here, something is very wrong. DSLOT_NEW is the only type of dslot that
2766 * may not exist; for all others, the caller assumes the given dslot
2767 * already exists. so, 'type' had better be DSLOT_NEW here, or something is
2769 osi_Assert(type == DSLOT_NEW);
2771 if (!afs_freeDSList)
2772 afs_GetDownDSlot(4);
2773 if (!afs_freeDSList) {
2774 /* none free, making one is better than a panic */
2775 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2776 tdc = afs_osi_Alloc(sizeof(struct dcache));
2777 osi_Assert(tdc != NULL);
2778 #ifdef KERNEL_HAVE_PIN
2779 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2782 tdc = afs_freeDSList;
2783 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2786 tdc->dflags = 0; /* up-to-date, not in free q */
2788 QAdd(&afs_DLRU, &tdc->lruq);
2789 if (tdc->lruq.prev == &tdc->lruq)
2790 osi_Panic("lruq 3");
2792 /* initialize entry */
2793 tdc->f.fid.Cell = 0;
2794 tdc->f.fid.Fid.Volume = 0;
2796 hones(tdc->f.versionNo);
2797 tdc->f.inode.mem = aslot;
2798 tdc->dflags |= DFEntryMod;
2801 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2804 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2805 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2806 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2809 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2810 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2811 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2812 ObtainReadLock(&tdc->tlock);
2814 afs_indexTable[aslot] = tdc;
2817 } /*afs_MemGetDSlot */
2819 unsigned int last_error = 0, lasterrtime = 0;
2825 * Return a pointer to an freshly initialized dcache entry using
2826 * a UFS-based disk cache. The dcache tlock will be read-locked.
2829 * aslot : Dcache slot to look at.
2830 * type : What 'type' of dslot to get; see the dslot_state enum
2833 * afs_xdcache lock write-locked.
2836 afs_UFSGetDSlot(afs_int32 aslot, dslot_state type)
2844 AFS_STATCNT(afs_UFSGetDSlot);
2845 if (CheckLock(&afs_xdcache) != -1)
2846 osi_Panic("getdslot nolock");
2847 if (aslot < 0 || aslot >= afs_cacheFiles)
2848 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2849 tdc = afs_indexTable[aslot];
2851 QRemove(&tdc->lruq); /* move to queue head */
2852 QAdd(&afs_DLRU, &tdc->lruq);
2853 /* Grab tlock in case refCount != 0 */
2854 ObtainWriteLock(&tdc->tlock, 625);
2856 ConvertWToRLock(&tdc->tlock);
2860 /* otherwise we should read it in from the cache file */
2861 if (!afs_freeDSList)
2862 afs_GetDownDSlot(4);
2863 if (!afs_freeDSList) {
2864 /* none free, making one is better than a panic */
2865 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2866 tdc = afs_osi_Alloc(sizeof(struct dcache));
2867 osi_Assert(tdc != NULL);
2868 #ifdef KERNEL_HAVE_PIN
2869 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2872 tdc = afs_freeDSList;
2873 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2876 tdc->dflags = 0; /* up-to-date, not in free q */
2878 QAdd(&afs_DLRU, &tdc->lruq);
2879 if (tdc->lruq.prev == &tdc->lruq)
2880 osi_Panic("lruq 3");
2883 * Seek to the aslot'th entry and read it in.
2885 off = sizeof(struct fcache)*aslot + sizeof(struct afs_fheader);
2887 afs_osi_Read(afs_cacheInodep,
2888 off, (char *)(&tdc->f),
2889 sizeof(struct fcache));
2891 if (code != sizeof(struct fcache)) {
2893 #if defined(KERNEL_HAVE_UERROR)
2894 last_error = getuerror();
2898 lasterrtime = osi_Time();
2899 if (type != DSLOT_NEW) {
2900 /* If we are requesting a non-DSLOT_NEW slot, this is an error.
2901 * non-DSLOT_NEW slots are supposed to already exist, so if we
2902 * failed to read in the slot, something is wrong. */
2903 struct osi_stat tstat;
2904 if (afs_osi_Stat(afs_cacheInodep, &tstat)) {
2907 afs_warn("afs: disk cache read error in CacheItems slot %d "
2908 "off %d/%d code %d/%d\n",
2910 off, (int)tstat.size,
2911 (int)code, (int)sizeof(struct fcache));
2912 /* put tdc back on the free dslot list */
2913 QRemove(&tdc->lruq);
2914 tdc->index = NULLIDX;
2915 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
2916 afs_freeDSList = tdc;
2920 if (!afs_CellNumValid(tdc->f.fid.Cell)) {
2922 if (type == DSLOT_VALID) {
2923 osi_Panic("afs: needed valid dcache but index %d off %d has "
2924 "invalid cell num %d\n",
2925 (int)aslot, off, (int)tdc->f.fid.Cell);
2929 if (type == DSLOT_VALID && tdc->f.fid.Fid.Volume == 0) {
2930 osi_Panic("afs: invalid zero-volume dcache entry at slot %d off %d",
2934 if (type == DSLOT_UNUSED) {
2935 /* the requested dslot is known to exist, but contain invalid data
2936 * (this happens when we're using a dslot from the free or discard
2937 * list). be sure not to re-use the data in it, so force invalidation.
2943 tdc->f.fid.Cell = 0;
2944 tdc->f.fid.Fid.Volume = 0;
2946 hones(tdc->f.versionNo);
2947 tdc->dflags |= DFEntryMod;
2948 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2949 tdc->f.states &= ~(DRO|DBackup|DRW);
2950 afs_DCMoveBucket(tdc, 0, 0);
2952 if (tdc->f.states & DRO) {
2953 afs_DCMoveBucket(tdc, 0, 2);
2954 } else if (tdc->f.states & DBackup) {
2955 afs_DCMoveBucket(tdc, 0, 1);
2957 afs_DCMoveBucket(tdc, 0, 1);
2962 if (tdc->f.chunk >= 0)
2963 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
2968 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2969 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2970 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2973 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2974 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2975 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2976 ObtainReadLock(&tdc->tlock);
2979 * If we didn't read into a temporary dcache region, update the
2980 * slot pointer table.
2982 afs_indexTable[aslot] = tdc;
2985 } /*afs_UFSGetDSlot */
2990 * Write a particular dcache entry back to its home in the
2993 * \param adc Pointer to the dcache entry to write.
2994 * \param atime If true, set the modtime on the file to the current time.
2996 * \note Environment:
2997 * Must be called with the afs_xdcache lock at least read-locked,
2998 * and dcache entry at least read-locked.
2999 * The reference count is not changed.
3003 afs_WriteDCache(struct dcache *adc, int atime)
3007 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3009 AFS_STATCNT(afs_WriteDCache);
3010 osi_Assert(WriteLocked(&afs_xdcache));
3012 adc->f.modTime = osi_Time();
3014 if ((afs_indexFlags[adc->index] & (IFFree | IFDiscarded)) == 0 &&
3015 adc->f.fid.Fid.Volume == 0) {
3016 /* If a dcache slot is not on the free or discard list, it must be
3017 * in the hash table. Thus, the volume must be non-zero, since that
3018 * is how we determine whether or not to unhash the entry when kicking
3019 * it out of the cache. Do this check now, since otherwise this can
3020 * cause hash table corruption and a panic later on after we read the
3022 osi_Panic("afs_WriteDCache zero volume index %d flags 0x%x\n",
3023 adc->index, (unsigned)afs_indexFlags[adc->index]);
3027 * Seek to the right dcache slot and write the in-memory image out to disk.
3029 afs_cellname_write();
3031 afs_osi_Write(afs_cacheInodep,
3032 sizeof(struct fcache) * adc->index +
3033 sizeof(struct afs_fheader), (char *)(&adc->f),
3034 sizeof(struct fcache));
3035 if (code != sizeof(struct fcache)) {
3036 afs_warn("afs: failed to write to CacheItems off %ld code %d/%d\n",
3037 (long)(sizeof(struct fcache) * adc->index + sizeof(struct afs_fheader)),
3038 (int)code, (int)sizeof(struct fcache));
3047 * Wake up users of a particular file waiting for stores to take
3050 * \param avc Ptr to related vcache entry.
3052 * \note Environment:
3053 * Nothing interesting.
3056 afs_wakeup(struct vcache *avc)
3059 struct brequest *tb;
3061 AFS_STATCNT(afs_wakeup);
3062 for (i = 0; i < NBRS; i++, tb++) {
3063 /* if request is valid and for this file, we've found it */
3064 if (tb->refCount > 0 && avc == tb->vc) {
3067 * If CSafeStore is on, then we don't awaken the guy
3068 * waiting for the store until the whole store has finished.
3069 * Otherwise, we do it now. Note that if CSafeStore is on,
3070 * the BStore routine actually wakes up the user, instead
3072 * I think this is redundant now because this sort of thing
3073 * is already being handled by the higher-level code.
3075 if ((avc->f.states & CSafeStore) == 0) {
3076 tb->code_raw = tb->code_checkcode = 0;
3077 tb->flags |= BUVALID;
3078 if (tb->flags & BUWAIT) {
3079 tb->flags &= ~BUWAIT;
3090 * Given a file name and inode, set up that file to be an
3091 * active member in the AFS cache. This also involves checking
3092 * the usability of its data.
3094 * \param afile Name of the cache file to initialize.
3095 * \param ainode Inode of the file.
3097 * \note Environment:
3098 * This function is called only during initialization.
3101 afs_InitCacheFile(char *afile, ino_t ainode)
3106 struct osi_file *tfile;
3107 struct osi_stat tstat;
3110 AFS_STATCNT(afs_InitCacheFile);
3111 index = afs_stats_cmperf.cacheNumEntries;
3112 if (index >= afs_cacheFiles)
3115 ObtainWriteLock(&afs_xdcache, 282);
3116 tdc = afs_GetNewDSlot(index);
3117 ReleaseReadLock(&tdc->tlock);
3118 ReleaseWriteLock(&afs_xdcache);
3120 ObtainWriteLock(&tdc->lock, 621);
3121 ObtainWriteLock(&afs_xdcache, 622);
3122 if (!afile && !ainode) {
3127 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
3129 ReleaseWriteLock(&afs_xdcache);
3130 ReleaseWriteLock(&tdc->lock);
3135 /* Add any other 'complex' inode types here ... */
3136 #if !defined(AFS_LINUX26_ENV) && !defined(AFS_CACHE_VNODE_PATH)
3137 tdc->f.inode.ufs = ainode;
3139 osi_Panic("Can't init cache with inode numbers when complex inodes are "
3144 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3146 tfile = osi_UFSOpen(&tdc->f.inode);
3148 ReleaseWriteLock(&afs_xdcache);
3149 ReleaseWriteLock(&tdc->lock);
3154 code = afs_osi_Stat(tfile, &tstat);
3156 osi_Panic("initcachefile stat");
3159 * If file size doesn't match the cache info file, it's probably bad.
3161 if (tdc->f.chunkBytes != tstat.size)
3164 * If file changed within T (120?) seconds of cache info file, it's
3165 * probably bad. In addition, if slot changed within last T seconds,
3166 * the cache info file may be incorrectly identified, and so slot
3169 if (cacheInfoModTime < tstat.mtime + 120)
3171 if (cacheInfoModTime < tdc->f.modTime + 120)
3173 /* In case write through is behind, make sure cache items entry is
3174 * at least as new as the chunk.
3176 if (tdc->f.modTime < tstat.mtime)
3179 tdc->f.chunkBytes = 0;
3182 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3183 if (tfile && tstat.size != 0)
3184 osi_UFSTruncate(tfile, 0);
3185 tdc->f.states &= ~(DRO|DBackup|DRW);
3186 afs_DCMoveBucket(tdc, 0, 0);
3187 /* put entry in free cache slot list */
3188 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3189 afs_freeDCList = index;
3191 afs_indexFlags[index] |= IFFree;
3192 afs_indexUnique[index] = 0;
3195 * We must put this entry in the appropriate hash tables.
3196 * Note that i is still set from the above DCHash call
3198 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3199 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3200 afs_dchashTbl[code] = tdc->index;
3201 code = DVHash(&tdc->f.fid);
3202 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3203 afs_dvhashTbl[code] = tdc->index;
3204 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3206 /* has nontrivial amt of data */
3207 afs_indexFlags[index] |= IFEverUsed;
3208 afs_stats_cmperf.cacheFilesReused++;
3210 * Initialize index times to file's mod times; init indexCounter
3213 hset32(afs_indexTimes[index], tstat.atime);
3214 if (hgetlo(afs_indexCounter) < tstat.atime) {
3215 hset32(afs_indexCounter, tstat.atime);
3217 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3218 } /*File is not bad */
3221 osi_UFSClose(tfile);
3222 tdc->f.states &= ~DWriting;
3223 tdc->dflags &= ~DFEntryMod;
3224 /* don't set f.modTime; we're just cleaning up */
3225 osi_Assert(afs_WriteDCache(tdc, 0) == 0);
3226 ReleaseWriteLock(&afs_xdcache);
3227 ReleaseWriteLock(&tdc->lock);
3229 afs_stats_cmperf.cacheNumEntries++;
3234 /*Max # of struct dcache's resident at any time*/
3236 * If 'dchint' is enabled then in-memory dcache min is increased because of
3242 * Initialize dcache related variables.
3252 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3259 afs_freeDCList = NULLIDX;
3260 afs_discardDCList = NULLIDX;
3261 afs_freeDCCount = 0;
3262 afs_freeDSList = NULL;
3263 hzero(afs_indexCounter);
3265 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3271 if (achunk < 0 || achunk > 30)
3272 achunk = 13; /* Use default */
3273 AFS_SETCHUNKSIZE(achunk);
3279 /* afs_dhashsize defaults to 1024 */
3280 if (aDentries > 512)
3281 afs_dhashsize = 2048;
3282 /* Try to keep the average chain length around two unless the table
3283 * would be ridiculously big. */
3284 if (aDentries > 4096) {
3285 afs_dhashbits = opr_fls(aDentries) - 3;
3286 /* Cap the hash tables to 32k entries. */
3287 if (afs_dhashbits > 15)
3289 afs_dhashsize = opr_jhash_size(afs_dhashbits);
3291 /* initialize hash tables */
3292 afs_dvhashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3293 osi_Assert(afs_dvhashTbl != NULL);
3294 afs_dchashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3295 osi_Assert(afs_dchashTbl != NULL);
3296 for (i = 0; i < afs_dhashsize; i++) {
3297 afs_dvhashTbl[i] = NULLIDX;
3298 afs_dchashTbl[i] = NULLIDX;
3300 afs_dvnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3301 osi_Assert(afs_dvnextTbl != NULL);
3302 afs_dcnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3303 osi_Assert(afs_dcnextTbl != NULL);
3304 for (i = 0; i < afiles; i++) {
3305 afs_dvnextTbl[i] = NULLIDX;
3306 afs_dcnextTbl[i] = NULLIDX;
3309 /* Allocate and zero the pointer array to the dcache entries */
3310 afs_indexTable = afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3311 osi_Assert(afs_indexTable != NULL);
3312 memset(afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3313 afs_indexTimes = afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3314 osi_Assert(afs_indexTimes != NULL);
3315 memset(afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3316 afs_indexUnique = afs_osi_Alloc(afiles * sizeof(afs_uint32));
3317 osi_Assert(afs_indexUnique != NULL);
3318 memset(afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3319 afs_indexFlags = afs_osi_Alloc(afiles * sizeof(u_char));
3320 osi_Assert(afs_indexFlags != NULL);
3321 memset(afs_indexFlags, 0, afiles * sizeof(char));
3323 /* Allocate and thread the struct dcache entries themselves */
3324 tdp = afs_Initial_freeDSList =
3325 afs_osi_Alloc(aDentries * sizeof(struct dcache));
3326 osi_Assert(tdp != NULL);
3327 memset(tdp, 0, aDentries * sizeof(struct dcache));
3328 #ifdef KERNEL_HAVE_PIN
3329 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3330 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3331 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3332 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3333 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3334 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3335 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3336 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3337 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3340 afs_freeDSList = &tdp[0];
3341 for (i = 0; i < aDentries - 1; i++) {
3342 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3343 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3344 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3345 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3347 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3348 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3349 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3350 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3352 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3353 afs_cacheBlocks = ablocks;
3354 afs_ComputeCacheParms(); /* compute parms based on cache size */
3356 afs_dcentries = aDentries;
3358 afs_stats_cmperf.cacheBucket0_Discarded =
3359 afs_stats_cmperf.cacheBucket1_Discarded =
3360 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3364 if (aflags & AFSCALL_INIT_MEMCACHE) {
3366 * Use a memory cache instead of a disk cache
3368 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3369 afs_cacheType = &afs_MemCacheOps;
3370 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3371 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3372 /* ablocks is reported in 1K blocks */
3373 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3375 afs_warn("afsd: memory cache too large for available memory.\n");
3376 afs_warn("afsd: AFS files cannot be accessed.\n\n");
3379 afs_warn("Memory cache: Allocating %d dcache entries...",
3382 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3383 afs_cacheType = &afs_UfsCacheOps;
3388 * Shuts down the cache.
3392 shutdown_dcache(void)
3396 #ifdef AFS_CACHE_VNODE_PATH
3397 if (cacheDiskType != AFS_FCACHE_TYPE_MEM) {
3399 for (i = 0; i < afs_cacheFiles; i++) {
3400 tdc = afs_indexTable[i];
3402 afs_osi_FreeStr(tdc->f.inode.ufs);
3408 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3409 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3410 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3411 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3412 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3413 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3414 afs_osi_Free(afs_Initial_freeDSList,
3415 afs_dcentries * sizeof(struct dcache));
3416 #ifdef KERNEL_HAVE_PIN
3417 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3418 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3419 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3420 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3421 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3422 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3423 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3427 for (i = 0; i < afs_dhashsize; i++) {
3428 afs_dvhashTbl[i] = NULLIDX;
3429 afs_dchashTbl[i] = NULLIDX;
3432 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3433 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3435 afs_blocksUsed = afs_dcentries = 0;
3436 afs_stats_cmperf.cacheBucket0_Discarded =
3437 afs_stats_cmperf.cacheBucket1_Discarded =
3438 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3439 hzero(afs_indexCounter);
3441 afs_freeDCCount = 0;
3442 afs_freeDCList = NULLIDX;
3443 afs_discardDCList = NULLIDX;
3444 afs_freeDSList = afs_Initial_freeDSList = 0;
3446 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3452 * Get a dcache ready for writing, respecting the current cache size limits
3454 * len is required because afs_GetDCache with flag == 4 expects the length
3455 * field to be filled. It decides from this whether it's necessary to fetch
3456 * data into the chunk before writing or not (when the whole chunk is
3459 * \param avc The vcache to fetch a dcache for
3460 * \param filePos The start of the section to be written
3461 * \param len The length of the section to be written
3465 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3466 * must be released and afs_PutDCache() called to free dcache.
3469 * \note avc->lock must be held on entry. Function may release and reobtain
3470 * avc->lock and GLOCK.
3474 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3475 afs_size_t len, struct vrequest *areq,
3478 struct dcache *tdc = NULL;
3481 /* read the cached info */
3483 tdc = afs_FindDCache(avc, filePos);
3485 ObtainWriteLock(&tdc->lock, 657);
3486 } else if (afs_blocksUsed >
3487 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3488 tdc = afs_FindDCache(avc, filePos);
3490 ObtainWriteLock(&tdc->lock, 658);
3491 if (!hsame(tdc->f.versionNo, avc->f.m.DataVersion)
3492 || (tdc->dflags & DFFetching)) {
3493 ReleaseWriteLock(&tdc->lock);
3499 afs_MaybeWakeupTruncateDaemon();
3500 while (afs_blocksUsed >
3501 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3502 ReleaseWriteLock(&avc->lock);
3503 if (afs_blocksUsed - afs_blocksDiscarded >
3504 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3505 afs_WaitForCacheDrain = 1;
3506 afs_osi_Sleep(&afs_WaitForCacheDrain);
3508 afs_MaybeFreeDiscardedDCache();
3509 afs_MaybeWakeupTruncateDaemon();
3510 ObtainWriteLock(&avc->lock, 509);
3512 avc->f.states |= CDirty;
3513 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3515 ObtainWriteLock(&tdc->lock, 659);
3518 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3520 ObtainWriteLock(&tdc->lock, 660);
3523 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3524 afs_stats_cmperf.cacheCurrDirtyChunks++;
3525 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3527 if (!(tdc->f.states & DWriting)) {
3528 /* don't mark entry as mod if we don't have to */
3529 tdc->f.states |= DWriting;
3530 tdc->dflags |= DFEntryMod;
3537 * Make a shadow copy of a dir's dcache. It's used for disconnected
3538 * operations like remove/create/rename to keep the original directory data.
3539 * On reconnection, we can diff the original data with the server and get the
3540 * server changes and with the local data to get the local changes.
3542 * \param avc The dir vnode.
3543 * \param adc The dir dcache.
3545 * \return 0 for success.
3547 * \note The vcache entry must be write locked.
3548 * \note The dcache entry must be read locked.
3551 afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3553 int i, code, ret_code = 0, written, trans_size;
3554 struct dcache *new_dc = NULL;
3555 struct osi_file *tfile_src, *tfile_dst;
3556 struct VenusFid shadow_fid;
3559 /* Is this a dir? */
3560 if (vType(avc) != VDIR)
3563 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3566 /* Generate a fid for the shadow dir. */
3567 shadow_fid.Cell = avc->f.fid.Cell;
3568 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3569 afs_GenShadowFid(&shadow_fid);
3571 ObtainWriteLock(&afs_xdcache, 716);
3573 /* Get a fresh dcache. */
3574 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3577 ObtainReadLock(&adc->mflock);
3579 /* Set up the new fid. */
3580 /* Copy interesting data from original dir dcache. */
3581 new_dc->mflags = adc->mflags;
3582 new_dc->dflags = adc->dflags;
3583 new_dc->f.modTime = adc->f.modTime;
3584 new_dc->f.versionNo = adc->f.versionNo;
3585 new_dc->f.states = adc->f.states;
3586 new_dc->f.chunk= adc->f.chunk;
3587 new_dc->f.chunkBytes = adc->f.chunkBytes;
3589 ReleaseReadLock(&adc->mflock);
3591 /* Now add to the two hash chains */
3592 i = DCHash(&shadow_fid, 0);
3593 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[i];
3594 afs_dchashTbl[i] = new_dc->index;
3596 i = DVHash(&shadow_fid);
3597 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[i];
3598 afs_dvhashTbl[i] = new_dc->index;
3600 ReleaseWriteLock(&afs_xdcache);
3602 /* Alloc a 4k block. */
3603 data = afs_osi_Alloc(4096);
3605 afs_warn("afs_MakeShadowDir: could not alloc data\n");
3610 /* Open the files. */
3611 tfile_src = afs_CFileOpen(&adc->f.inode);
3612 tfile_dst = afs_CFileOpen(&new_dc->f.inode);
3614 /* And now copy dir dcache data into this dcache,
3618 while (written < adc->f.chunkBytes) {
3619 trans_size = adc->f.chunkBytes - written;
3620 if (trans_size > 4096)
3623 /* Read a chunk from the dcache. */
3624 code = afs_CFileRead(tfile_src, written, data, trans_size);
3625 if (code < trans_size) {
3630 /* Write it to the new dcache. */
3631 code = afs_CFileWrite(tfile_dst, written, data, trans_size);
3632 if (code < trans_size) {
3637 written+=trans_size;
3640 afs_CFileClose(tfile_dst);
3641 afs_CFileClose(tfile_src);
3643 afs_osi_Free(data, 4096);
3645 ReleaseWriteLock(&new_dc->lock);
3646 afs_PutDCache(new_dc);
3649 ObtainWriteLock(&afs_xvcache, 763);
3650 ObtainWriteLock(&afs_disconDirtyLock, 765);
3651 QAdd(&afs_disconShadow, &avc->shadowq);
3652 osi_Assert((afs_RefVCache(avc) == 0));
3653 ReleaseWriteLock(&afs_disconDirtyLock);
3654 ReleaseWriteLock(&afs_xvcache);
3656 avc->f.shadow.vnode = shadow_fid.Fid.Vnode;
3657 avc->f.shadow.unique = shadow_fid.Fid.Unique;
3665 * Delete the dcaches of a shadow dir.
3667 * \param avc The vcache containing the shadow fid.
3669 * \note avc must be write locked.
3672 afs_DeleteShadowDir(struct vcache *avc)
3675 struct VenusFid shadow_fid;
3677 shadow_fid.Cell = avc->f.fid.Cell;
3678 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3679 shadow_fid.Fid.Vnode = avc->f.shadow.vnode;
3680 shadow_fid.Fid.Unique = avc->f.shadow.unique;
3682 tdc = afs_FindDCacheByFid(&shadow_fid);
3684 afs_HashOutDCache(tdc, 1);
3685 afs_DiscardDCache(tdc);
3688 avc->f.shadow.vnode = avc->f.shadow.unique = 0;
3689 ObtainWriteLock(&afs_disconDirtyLock, 708);
3690 QRemove(&avc->shadowq);
3691 ReleaseWriteLock(&afs_disconDirtyLock);
3692 afs_PutVCache(avc); /* Because we held it when we added to the queue */
3696 * Populate a dcache with empty chunks up to a given file size,
3697 * used before extending a file in order to avoid 'holes' which
3698 * we can't access in disconnected mode.
3700 * \param avc The vcache which is being extended (locked)
3701 * \param alen The new length of the file
3705 afs_PopulateDCache(struct vcache *avc, afs_size_t apos, struct vrequest *areq)
3708 afs_size_t len, offset;
3709 afs_int32 start, end;
3711 /* We're doing this to deal with the situation where we extend
3712 * by writing after lseek()ing past the end of the file . If that
3713 * extension skips chunks, then those chunks won't be created, and
3714 * GetDCache will assume that they have to be fetched from the server.
3715 * So, for each chunk between the current file position, and the new
3716 * length we GetDCache for that chunk.
3719 if (AFS_CHUNK(apos) == 0 || apos <= avc->f.m.Length)
3722 if (avc->f.m.Length == 0)
3725 start = AFS_CHUNK(avc->f.m.Length)+1;
3727 end = AFS_CHUNK(apos);
3730 len = AFS_CHUNKTOSIZE(start);
3731 tdc = afs_GetDCache(avc, AFS_CHUNKTOBASE(start), areq, &offset, &len, 4);