2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
13 #include <afsconfig.h>
14 #include "afs/param.h"
17 #include "afs/sysincludes.h" /*Standard vendor system headers */
18 #include "afsincludes.h" /*AFS-based standard headers */
19 #include "afs/afs_stats.h" /* statistics */
20 #include "afs/afs_cbqueue.h"
21 #include "afs/afs_osidnlc.h"
23 /* Forward declarations. */
24 static void afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint);
25 static int afs_FreeDiscardedDCache(void);
26 static void afs_DiscardDCache(struct dcache *);
27 static void afs_FreeDCache(struct dcache *);
29 static afs_int32 afs_DCGetBucket(struct vcache *);
30 static void afs_DCAdjustSize(struct dcache *, afs_int32, afs_int32);
31 static void afs_DCMoveBucket(struct dcache *, afs_int32, afs_int32);
32 static void afs_DCSizeInit(void);
33 static afs_int32 afs_DCWhichBucket(afs_int32, afs_int32);
36 * --------------------- Exported definitions ---------------------
39 afs_int32 afs_blocksUsed_0; /*!< 1K blocks in cache - in theory is zero */
40 afs_int32 afs_blocksUsed_1; /*!< 1K blocks in cache */
41 afs_int32 afs_blocksUsed_2; /*!< 1K blocks in cache */
42 afs_int32 afs_pct1 = -1;
43 afs_int32 afs_pct2 = -1;
44 afs_uint32 afs_tpct1 = 0;
45 afs_uint32 afs_tpct2 = 0;
46 afs_uint32 splitdcache = 0;
48 afs_lock_t afs_xdcache; /*!< Lock: alloc new disk cache entries */
49 afs_int32 afs_freeDCList; /*!< Free list for disk cache entries */
50 afs_int32 afs_freeDCCount; /*!< Count of elts in freeDCList */
51 afs_int32 afs_discardDCList; /*!< Discarded disk cache entries */
52 afs_int32 afs_discardDCCount; /*!< Count of elts in discardDCList */
53 struct dcache *afs_freeDSList; /*!< Free list for disk slots */
54 struct dcache *afs_Initial_freeDSList; /*!< Initial list for above */
55 afs_dcache_id_t cacheInode; /*!< Inode for CacheItems file */
56 struct osi_file *afs_cacheInodep = 0; /*!< file for CacheItems inode */
57 struct afs_q afs_DLRU; /*!< dcache LRU */
58 afs_int32 afs_dhashsize = 1024;
59 afs_int32 *afs_dvhashTbl; /*!< Data cache hash table: hashed by FID + chunk number. */
60 afs_int32 *afs_dchashTbl; /*!< Data cache hash table: hashed by FID. */
61 afs_int32 *afs_dvnextTbl; /*!< Dcache hash table links */
62 afs_int32 *afs_dcnextTbl; /*!< Dcache hash table links */
63 struct dcache **afs_indexTable; /*!< Pointers to dcache entries */
64 afs_hyper_t *afs_indexTimes; /*!< Dcache entry Access times */
65 afs_int32 *afs_indexUnique; /*!< dcache entry Fid.Unique */
66 unsigned char *afs_indexFlags; /*!< (only one) Is there data there? */
67 afs_hyper_t afs_indexCounter; /*!< Fake time for marking index
69 afs_int32 afs_cacheFiles = 0; /*!< Size of afs_indexTable */
70 afs_int32 afs_cacheBlocks; /*!< 1K blocks in cache */
71 afs_int32 afs_cacheStats; /*!< Stat entries in cache */
72 afs_int32 afs_blocksUsed; /*!< Number of blocks in use */
73 afs_int32 afs_blocksDiscarded; /*!<Blocks freed but not truncated */
74 afs_int32 afs_fsfragsize = AFS_MIN_FRAGSIZE; /*!< Underlying Filesystem minimum unit
75 *of disk allocation usually 1K
76 *this value is (truefrag -1 ) to
77 *save a bunch of subtracts... */
78 #ifdef AFS_64BIT_CLIENT
79 #ifdef AFS_VM_RDWR_ENV
80 afs_size_t afs_vmMappingEnd; /* !< For large files (>= 2GB) the VM
81 * mapping an 32bit addressing machines
82 * can only be used below the 2 GB
83 * line. From this point upwards we
84 * must do direct I/O into the cache
85 * files. The value should be on a
87 #endif /* AFS_VM_RDWR_ENV */
88 #endif /* AFS_64BIT_CLIENT */
90 /* The following is used to ensure that new dcache's aren't obtained when
91 * the cache is nearly full.
93 int afs_WaitForCacheDrain = 0;
94 int afs_TruncateDaemonRunning = 0;
95 int afs_CacheTooFull = 0;
97 afs_int32 afs_dcentries; /*!< In-memory dcache entries */
100 int dcacheDisabled = 0;
102 struct afs_cacheOps afs_UfsCacheOps = {
103 #ifndef HAVE_STRUCT_LABEL_SUPPORT
116 .truncate = osi_UFSTruncate,
117 .fread = afs_osi_Read,
118 .fwrite = afs_osi_Write,
119 .close = osi_UFSClose,
120 .vreadUIO = afs_UFSReadUIO,
121 .vwriteUIO = afs_UFSWriteUIO,
122 .GetDSlot = afs_UFSGetDSlot,
123 .GetVolSlot = afs_UFSGetVolSlot,
124 .HandleLink = afs_UFSHandleLink,
128 struct afs_cacheOps afs_MemCacheOps = {
129 #ifndef HAVE_STRUCT_LABEL_SUPPORT
131 afs_MemCacheTruncate,
141 .open = afs_MemCacheOpen,
142 .truncate = afs_MemCacheTruncate,
143 .fread = afs_MemReadBlk,
144 .fwrite = afs_MemWriteBlk,
145 .close = afs_MemCacheClose,
146 .vreadUIO = afs_MemReadUIO,
147 .vwriteUIO = afs_MemWriteUIO,
148 .GetDSlot = afs_MemGetDSlot,
149 .GetVolSlot = afs_MemGetVolSlot,
150 .HandleLink = afs_MemHandleLink,
154 int cacheDiskType; /*Type of backing disk for cache */
155 struct afs_cacheOps *afs_cacheType;
158 * Where is this vcache's entry associated dcache located/
159 * \param avc The vcache entry.
160 * \return Bucket index:
165 afs_DCGetBucket(struct vcache *avc)
170 /* This should be replaced with some sort of user configurable function */
171 if (avc->f.states & CRO) {
173 } else if (avc->f.states & CBackup) {
183 * Readjust a dcache's size.
185 * \param adc The dcache to be adjusted.
186 * \param oldSize Old size for the dcache.
187 * \param newSize The new size to be adjusted to.
191 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
193 afs_int32 adjustSize = newSize - oldSize;
201 afs_blocksUsed_0 += adjustSize;
202 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
205 afs_blocksUsed_1 += adjustSize;
206 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
209 afs_blocksUsed_2 += adjustSize;
210 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
218 * Move a dcache from one bucket to another.
220 * \param adc Operate on this dcache.
221 * \param size Size in bucket (?).
222 * \param newBucket Destination bucket.
226 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
231 /* Substract size from old bucket. */
235 afs_blocksUsed_0 -= size;
238 afs_blocksUsed_1 -= size;
241 afs_blocksUsed_2 -= size;
245 /* Set new bucket and increase destination bucket size. */
246 adc->bucket = newBucket;
251 afs_blocksUsed_0 += size;
254 afs_blocksUsed_1 += size;
257 afs_blocksUsed_2 += size;
265 * Init split caches size.
270 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
279 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
284 afs_pct1 = afs_blocksUsed_1 / (afs_cacheBlocks / 100);
285 afs_pct2 = afs_blocksUsed_2 / (afs_cacheBlocks / 100);
287 /* Short cut: if we don't know about it, try to kill it */
288 if (phase < 2 && afs_blocksUsed_0)
291 if (afs_pct1 > afs_tpct1)
293 if (afs_pct2 > afs_tpct2)
295 return 0; /* unlikely */
300 * Warn about failing to store a file.
302 * \param acode Associated error code.
303 * \param avolume Volume involved.
304 * \param aflags How to handle the output:
305 * aflags & 1: Print out on console
306 * aflags & 2: Print out on controlling tty
308 * \note Environment: Call this from close call when vnodeops is RCS unlocked.
312 afs_StoreWarn(afs_int32 acode, afs_int32 avolume,
315 static char problem_fmt[] =
316 "afs: failed to store file in volume %d (%s)\n";
317 static char problem_fmt_w_error[] =
318 "afs: failed to store file in volume %d (error %d)\n";
319 static char netproblems[] = "network problems";
320 static char partfull[] = "partition full";
321 static char overquota[] = "over quota";
323 AFS_STATCNT(afs_StoreWarn);
329 afs_warn(problem_fmt, avolume, netproblems);
331 afs_warnuser(problem_fmt, avolume, netproblems);
332 } else if (acode == ENOSPC) {
337 afs_warn(problem_fmt, avolume, partfull);
339 afs_warnuser(problem_fmt, avolume, partfull);
342 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
343 * Instead ENOSPC will be sent...
345 if (acode == EDQUOT) {
350 afs_warn(problem_fmt, avolume, overquota);
352 afs_warnuser(problem_fmt, avolume, overquota);
360 afs_warn(problem_fmt_w_error, avolume, acode);
362 afs_warnuser(problem_fmt_w_error, avolume, acode);
367 * Try waking up truncation daemon, if it's worth it.
370 afs_MaybeWakeupTruncateDaemon(void)
372 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
373 afs_CacheTooFull = 1;
374 if (!afs_TruncateDaemonRunning)
375 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
376 } else if (!afs_TruncateDaemonRunning
377 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
378 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
385 * Keep statistics on run time for afs_CacheTruncateDaemon. This is a
386 * struct so we need only export one symbol for AIX.
388 static struct CTD_stats {
389 osi_timeval_t CTD_beforeSleep;
390 osi_timeval_t CTD_afterSleep;
391 osi_timeval_t CTD_sleepTime;
392 osi_timeval_t CTD_runTime;
396 u_int afs_min_cache = 0;
399 * If there are waiters for the cache to drain, wake them if
400 * the number of free or discarded cache blocks reaches the
401 * CM_CACHESIZEDDRAINEDPCT limit.
404 * This routine must be called with the afs_xdcache lock held
408 afs_WakeCacheWaitersIfDrained(void)
410 if (afs_WaitForCacheDrain) {
411 if ((afs_blocksUsed - afs_blocksDiscarded) <=
412 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
413 afs_WaitForCacheDrain = 0;
414 afs_osi_Wakeup(&afs_WaitForCacheDrain);
420 * Keeps the cache clean and free by truncating uneeded files, when used.
425 afs_CacheTruncateDaemon(void)
427 osi_timeval_t CTD_tmpTime;
431 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
433 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
435 osi_GetuTime(&CTD_stats.CTD_afterSleep);
436 afs_TruncateDaemonRunning = 1;
438 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
439 ObtainWriteLock(&afs_xdcache, 266);
440 if (afs_CacheTooFull || afs_WaitForCacheDrain) {
441 int space_needed, slots_needed;
442 /* if we get woken up, we should try to clean something out */
443 for (counter = 0; counter < 10; counter++) {
445 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
446 if (space_needed < 0)
449 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
450 if (slots_needed < 0)
452 if (slots_needed || space_needed)
453 afs_GetDownD(slots_needed, &space_needed, 0);
454 if ((space_needed <= 0) && (slots_needed <= 0)) {
455 afs_CacheTooFull = 0;
458 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
461 if (!afs_CacheIsTooFull()) {
462 afs_CacheTooFull = 0;
463 afs_WakeCacheWaitersIfDrained();
465 } /* end of cache cleanup */
466 ReleaseWriteLock(&afs_xdcache);
469 * This is a defensive check to try to avoid starving threads
470 * that may need the global lock so thay can help free some
471 * cache space. If this thread won't be sleeping or truncating
472 * any cache files then give up the global lock so other
473 * threads get a chance to run.
475 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
476 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
477 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
481 * This is where we free the discarded cache elements.
483 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
484 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
485 int code = afs_FreeDiscardedDCache();
487 /* If we can't free any discarded dcache entries, that's okay.
488 * We're just doing this in the background; if someone needs
489 * discarded entries freed, they will try it themselves and/or
490 * signal us that the cache is too full. In any case, we'll
491 * try doing this again the next time we run through the loop.
497 /* See if we need to continue to run. Someone may have
498 * signalled us while we were executing.
500 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
501 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
502 /* Collect statistics on truncate daemon. */
503 CTD_stats.CTD_nSleeps++;
504 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
505 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
506 CTD_stats.CTD_beforeSleep);
507 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
509 afs_TruncateDaemonRunning = 0;
510 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
511 afs_TruncateDaemonRunning = 1;
513 osi_GetuTime(&CTD_stats.CTD_afterSleep);
514 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
515 CTD_stats.CTD_afterSleep);
516 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
518 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
519 afs_termState = AFSOP_STOP_AFSDB;
520 afs_osi_Wakeup(&afs_termState);
528 * Make adjustment for the new size in the disk cache entry
530 * \note Major Assumptions Here:
531 * Assumes that frag size is an integral power of two, less one,
532 * and that this is a two's complement machine. I don't
533 * know of any filesystems which violate this assumption...
535 * \param adc Ptr to dcache entry.
536 * \param anewsize New size desired.
541 afs_AdjustSize(struct dcache *adc, afs_int32 newSize)
545 AFS_STATCNT(afs_AdjustSize);
547 adc->dflags |= DFEntryMod;
548 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
549 adc->f.chunkBytes = newSize;
552 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
553 afs_DCAdjustSize(adc, oldSize, newSize);
554 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
556 /* We're growing the file, wakeup the daemon */
557 afs_MaybeWakeupTruncateDaemon();
559 afs_blocksUsed += (newSize - oldSize);
560 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
565 * This routine is responsible for moving at least one entry (but up
566 * to some number of them) from the LRU queue to the free queue.
568 * \param anumber Number of entries that should ideally be moved.
569 * \param aneedSpace How much space we need (1K blocks);
572 * The anumber parameter is just a hint; at least one entry MUST be
573 * moved, or we'll panic. We must be called with afs_xdcache
574 * write-locked. We should try to satisfy both anumber and aneedspace,
575 * whichever is more demanding - need to do several things:
576 * 1. only grab up to anumber victims if aneedSpace <= 0, not
577 * the whole set of MAXATONCE.
578 * 2. dynamically choose MAXATONCE to reflect severity of
579 * demand: something like (*aneedSpace >> (logChunk - 9))
581 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
582 * indicates that the cache is not properly configured/tuned or
583 * something. We should be able to automatically correct that problem.
586 #define MAXATONCE 16 /* max we can obtain at once */
588 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
592 struct VenusFid *afid;
597 afs_uint32 victims[MAXATONCE];
598 struct dcache *victimDCs[MAXATONCE];
599 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
600 afs_uint32 victimPtr; /* next free item in victim arrays */
601 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
602 afs_uint32 maxVictimPtr; /* where it is */
606 AFS_STATCNT(afs_GetDownD);
608 if (CheckLock(&afs_xdcache) != -1)
609 osi_Panic("getdownd nolock");
610 /* decrement anumber first for all dudes in free list */
611 /* SHOULD always decrement anumber first, even if aneedSpace >0,
612 * because we should try to free space even if anumber <=0 */
613 if (!aneedSpace || *aneedSpace <= 0) {
614 anumber -= afs_freeDCCount;
616 return; /* enough already free */
620 /* bounds check parameter */
621 if (anumber > MAXATONCE)
622 anumber = MAXATONCE; /* all we can do */
624 /* rewrite so phases include a better eligiblity for gc test*/
626 * The phase variable manages reclaims. Set to 0, the first pass,
627 * we don't reclaim active entries, or other than target bucket.
628 * Set to 1, we reclaim even active ones in target bucket.
629 * Set to 2, we reclaim any inactive one.
630 * Set to 3, we reclaim even active ones. On Solaris, we also reclaim
631 * entries whose corresponding vcache has a nonempty multiPage list, when
640 for (i = 0; i < afs_cacheFiles; i++)
641 /* turn off all flags */
642 afs_indexFlags[i] &= ~IFFlag;
644 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
645 /* find oldest entries for reclamation */
646 maxVictimPtr = victimPtr = 0;
647 hzero(maxVictimTime);
648 curbucket = afs_DCWhichBucket(phase, buckethint);
649 /* select victims from access time array */
650 for (i = 0; i < afs_cacheFiles; i++) {
651 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
652 /* skip if dirty or already free */
655 tdc = afs_indexTable[i];
656 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
658 /* Wrong bucket; can't use it! */
661 if (tdc && (tdc->refCount != 0)) {
662 /* Referenced; can't use it! */
665 hset(vtime, afs_indexTimes[i]);
667 /* if we've already looked at this one, skip it */
668 if (afs_indexFlags[i] & IFFlag)
671 if (victimPtr < MAXATONCE) {
672 /* if there's at least one free victim slot left */
673 victims[victimPtr] = i;
674 hset(victimTimes[victimPtr], vtime);
675 if (hcmp(vtime, maxVictimTime) > 0) {
676 hset(maxVictimTime, vtime);
677 maxVictimPtr = victimPtr;
680 } else if (hcmp(vtime, maxVictimTime) < 0) {
682 * We're older than youngest victim, so we replace at
685 /* find youngest (largest LRU) victim */
688 osi_Panic("getdownd local");
690 hset(victimTimes[j], vtime);
691 /* recompute maxVictimTime */
692 hset(maxVictimTime, vtime);
693 for (j = 0; j < victimPtr; j++)
694 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
695 hset(maxVictimTime, victimTimes[j]);
701 /* now really reclaim the victims */
702 j = 0; /* flag to track if we actually got any of the victims */
703 /* first, hold all the victims, since we're going to release the lock
704 * during the truncate operation.
706 for (i = 0; i < victimPtr; i++) {
707 tdc = afs_GetValidDSlot(victims[i]);
708 /* We got tdc->tlock(R) here */
709 if (tdc && tdc->refCount == 1)
714 ReleaseReadLock(&tdc->tlock);
719 for (i = 0; i < victimPtr; i++) {
720 /* q is first elt in dcache entry */
722 /* now, since we're dropping the afs_xdcache lock below, we
723 * have to verify, before proceeding, that there are no other
724 * references to this dcache entry, even now. Note that we
725 * compare with 1, since we bumped it above when we called
726 * afs_GetValidDSlot to preserve the entry's identity.
728 if (tdc && tdc->refCount == 1) {
729 unsigned char chunkFlags;
730 afs_size_t tchunkoffset = 0;
732 /* xdcache is lower than the xvcache lock */
733 ReleaseWriteLock(&afs_xdcache);
734 ObtainReadLock(&afs_xvcache);
735 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
736 ReleaseReadLock(&afs_xvcache);
737 ObtainWriteLock(&afs_xdcache, 527);
739 if (tdc->refCount > 1)
742 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
743 chunkFlags = afs_indexFlags[tdc->index];
744 if (((phase & 1) == 0) && osi_Active(tvc))
746 if (((phase & 1) == 1) && osi_Active(tvc)
747 && (tvc->f.states & CDCLock)
748 && (chunkFlags & IFAnyPages))
750 if (chunkFlags & IFDataMod)
752 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
753 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
754 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
755 ICL_HANDLE_OFFSET(tchunkoffset));
757 #if defined(AFS_SUN5_ENV)
759 * Now we try to invalidate pages. We do this only for
760 * Solaris. For other platforms, it's OK to recycle a
761 * dcache entry out from under a page, because the strategy
762 * function can call afs_GetDCache().
764 if (!skip && (chunkFlags & IFAnyPages)) {
767 ReleaseWriteLock(&afs_xdcache);
768 ObtainWriteLock(&tvc->vlock, 543);
769 if (!QEmpty(&tvc->multiPage)) {
770 if (phase < 3 || osi_VM_MultiPageConflict(tvc, tdc)) {
775 /* block locking pages */
776 tvc->vstates |= VPageCleaning;
777 /* block getting new pages */
779 ReleaseWriteLock(&tvc->vlock);
780 /* One last recheck */
781 ObtainWriteLock(&afs_xdcache, 333);
782 chunkFlags = afs_indexFlags[tdc->index];
783 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
784 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
785 && (chunkFlags & IFAnyPages))) {
787 ReleaseWriteLock(&afs_xdcache);
790 ReleaseWriteLock(&afs_xdcache);
792 code = osi_VM_GetDownD(tvc, tdc);
794 ObtainWriteLock(&afs_xdcache, 269);
795 /* we actually removed all pages, clean and dirty */
797 afs_indexFlags[tdc->index] &=
798 ~(IFDirtyPages | IFAnyPages);
801 ReleaseWriteLock(&afs_xdcache);
803 ObtainWriteLock(&tvc->vlock, 544);
804 if (--tvc->activeV == 0
805 && (tvc->vstates & VRevokeWait)) {
806 tvc->vstates &= ~VRevokeWait;
807 afs_osi_Wakeup((char *)&tvc->vstates);
810 if (tvc->vstates & VPageCleaning) {
811 tvc->vstates &= ~VPageCleaning;
812 afs_osi_Wakeup((char *)&tvc->vstates);
815 ReleaseWriteLock(&tvc->vlock);
817 #endif /* AFS_SUN5_ENV */
819 ReleaseWriteLock(&afs_xdcache);
822 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
823 ObtainWriteLock(&afs_xdcache, 528);
824 if (afs_indexFlags[tdc->index] &
825 (IFDataMod | IFDirtyPages | IFAnyPages))
827 if (tdc->refCount > 1)
830 #if defined(AFS_SUN5_ENV)
832 /* no vnode, so IFDirtyPages is spurious (we don't
833 * sweep dcaches on vnode recycling, so we can have
834 * DIRTYPAGES set even when all pages are gone). Just
836 * Hold vcache lock to prevent vnode from being
837 * created while we're clearing IFDirtyPages.
839 afs_indexFlags[tdc->index] &=
840 ~(IFDirtyPages | IFAnyPages);
844 /* skip this guy and mark him as recently used */
845 afs_indexFlags[tdc->index] |= IFFlag;
846 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
847 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
848 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
849 ICL_HANDLE_OFFSET(tchunkoffset));
851 /* flush this dude from the data cache and reclaim;
852 * first, make sure no one will care that we damage
853 * it, by removing it from all hash tables. Then,
854 * melt it down for parts. Note that any concurrent
855 * (new possibility!) calls to GetDownD won't touch
856 * this guy because his reference count is > 0. */
857 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
858 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
859 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
860 ICL_HANDLE_OFFSET(tchunkoffset));
861 AFS_STATCNT(afs_gget);
862 afs_HashOutDCache(tdc, 1);
863 if (tdc->f.chunkBytes != 0) {
867 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
872 afs_DiscardDCache(tdc);
877 j = 1; /* we reclaimed at least one victim */
882 } /* end of for victims loop */
885 /* Phase is 0 and no one was found, so try phase 1 (ignore
886 * osi_Active flag) */
889 for (i = 0; i < afs_cacheFiles; i++)
890 /* turn off all flags */
891 afs_indexFlags[i] &= ~IFFlag;
894 /* found no one in phases 0-5, we're hosed */
898 } /* big while loop */
906 * Remove adc from any hash tables that would allow it to be located
907 * again by afs_FindDCache or afs_GetDCache.
909 * \param adc Pointer to dcache entry to remove from hash tables.
911 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
915 afs_HashOutDCache(struct dcache *adc, int zap)
919 AFS_STATCNT(afs_glink);
921 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
923 /* if this guy is in the hash table, pull him out */
924 if (adc->f.fid.Fid.Volume != 0) {
925 /* remove entry from first hash chains */
926 i = DCHash(&adc->f.fid, adc->f.chunk);
927 us = afs_dchashTbl[i];
928 if (us == adc->index) {
929 /* first dude in the list */
930 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
932 /* somewhere on the chain */
933 while (us != NULLIDX) {
934 if (afs_dcnextTbl[us] == adc->index) {
935 /* found item pointing at the one to delete */
936 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
939 us = afs_dcnextTbl[us];
942 osi_Panic("dcache hc");
944 /* remove entry from *other* hash chain */
945 i = DVHash(&adc->f.fid);
946 us = afs_dvhashTbl[i];
947 if (us == adc->index) {
948 /* first dude in the list */
949 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
951 /* somewhere on the chain */
952 while (us != NULLIDX) {
953 if (afs_dvnextTbl[us] == adc->index) {
954 /* found item pointing at the one to delete */
955 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
958 us = afs_dvnextTbl[us];
961 osi_Panic("dcache hv");
966 /* prevent entry from being found on a reboot (it is already out of
967 * the hash table, but after a crash, we just look at fid fields of
968 * stable (old) entries).
970 adc->f.fid.Fid.Volume = 0; /* invalid */
972 /* mark entry as modified */
973 adc->dflags |= DFEntryMod;
978 } /*afs_HashOutDCache */
981 * Flush the given dcache entry, pulling it from hash chains
982 * and truncating the associated cache file.
984 * \param adc Ptr to dcache entry to flush.
987 * This routine must be called with the afs_xdcache lock held
991 afs_FlushDCache(struct dcache *adc)
993 AFS_STATCNT(afs_FlushDCache);
995 * Bump the number of cache files flushed.
997 afs_stats_cmperf.cacheFlushes++;
999 /* remove from all hash tables */
1000 afs_HashOutDCache(adc, 1);
1002 /* Free its space; special case null operation, since truncate operation
1003 * in UFS is slow even in this case, and this allows us to pre-truncate
1004 * these files at more convenient times with fewer locks set
1005 * (see afs_GetDownD).
1007 if (adc->f.chunkBytes != 0) {
1008 afs_DiscardDCache(adc);
1009 afs_MaybeWakeupTruncateDaemon();
1011 afs_FreeDCache(adc);
1013 } /*afs_FlushDCache */
1017 * Put a dcache entry on the free dcache entry list.
1019 * \param adc dcache entry to free.
1021 * \note Environment: called with afs_xdcache lock write-locked.
1024 afs_FreeDCache(struct dcache *adc)
1026 /* Thread on free list, update free list count and mark entry as
1027 * freed in its indexFlags element. Also, ensure DCache entry gets
1028 * written out (set DFEntryMod).
1031 afs_dvnextTbl[adc->index] = afs_freeDCList;
1032 afs_freeDCList = adc->index;
1034 afs_indexFlags[adc->index] |= IFFree;
1035 adc->dflags |= DFEntryMod;
1037 afs_WakeCacheWaitersIfDrained();
1038 } /* afs_FreeDCache */
1041 * Discard the cache element by moving it to the discardDCList.
1042 * This puts the cache element into a quasi-freed state, where
1043 * the space may be reused, but the file has not been truncated.
1045 * \note Major Assumptions Here:
1046 * Assumes that frag size is an integral power of two, less one,
1047 * and that this is a two's complement machine. I don't
1048 * know of any filesystems which violate this assumption...
1050 * \param adr Ptr to dcache entry.
1052 * \note Environment:
1053 * Must be called with afs_xdcache write-locked.
1057 afs_DiscardDCache(struct dcache *adc)
1061 AFS_STATCNT(afs_DiscardDCache);
1063 osi_Assert(adc->refCount == 1);
1065 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1066 afs_blocksDiscarded += size;
1067 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1069 afs_dvnextTbl[adc->index] = afs_discardDCList;
1070 afs_discardDCList = adc->index;
1071 afs_discardDCCount++;
1073 adc->f.fid.Fid.Volume = 0;
1074 adc->dflags |= DFEntryMod;
1075 afs_indexFlags[adc->index] |= IFDiscarded;
1077 afs_WakeCacheWaitersIfDrained();
1078 } /*afs_DiscardDCache */
1081 * Get a dcache entry from the discard or free list
1083 * @param[in] indexp A pointer to the head of the dcache free list or discard
1084 * list (afs_freeDCList, or afs_discardDCList)
1086 * @return A dcache from that list, or NULL if none could be retrieved.
1088 * @pre afs_xdcache is write-locked
1090 static struct dcache *
1091 afs_GetDSlotFromList(afs_int32 *indexp)
1095 for ( ; *indexp != NULLIDX; indexp = &afs_dvnextTbl[*indexp]) {
1096 tdc = afs_GetUnusedDSlot(*indexp);
1098 osi_Assert(tdc->refCount == 1);
1099 ReleaseReadLock(&tdc->tlock);
1100 *indexp = afs_dvnextTbl[tdc->index];
1101 afs_dvnextTbl[tdc->index] = NULLIDX;
1109 * Free the next element on the list of discarded cache elements.
1111 * Returns -1 if we encountered an error preventing us from freeing a
1112 * discarded dcache, or 0 on success.
1115 afs_FreeDiscardedDCache(void)
1118 struct osi_file *tfile;
1121 AFS_STATCNT(afs_FreeDiscardedDCache);
1123 ObtainWriteLock(&afs_xdcache, 510);
1124 if (!afs_blocksDiscarded) {
1125 ReleaseWriteLock(&afs_xdcache);
1130 * Get an entry from the list of discarded cache elements
1132 tdc = afs_GetDSlotFromList(&afs_discardDCList);
1134 ReleaseWriteLock(&afs_xdcache);
1138 afs_discardDCCount--;
1139 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1140 afs_blocksDiscarded -= size;
1141 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1142 /* We can lock because we just took it off the free list */
1143 ObtainWriteLock(&tdc->lock, 626);
1144 ReleaseWriteLock(&afs_xdcache);
1147 * Truncate the element to reclaim its space
1149 tfile = afs_CFileOpen(&tdc->f.inode);
1150 afs_CFileTruncate(tfile, 0);
1151 afs_CFileClose(tfile);
1152 afs_AdjustSize(tdc, 0);
1153 afs_DCMoveBucket(tdc, 0, 0);
1156 * Free the element we just truncated
1158 ObtainWriteLock(&afs_xdcache, 511);
1159 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1160 afs_FreeDCache(tdc);
1161 tdc->f.states &= ~(DRO|DBackup|DRW);
1162 ReleaseWriteLock(&tdc->lock);
1164 ReleaseWriteLock(&afs_xdcache);
1170 * Free as many entries from the list of discarded cache elements
1171 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1176 afs_MaybeFreeDiscardedDCache(void)
1179 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1181 while (afs_blocksDiscarded
1182 && (afs_blocksUsed >
1183 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1184 int code = afs_FreeDiscardedDCache();
1186 /* Callers depend on us to get the afs_blocksDiscarded count down.
1187 * If we cannot do that, the callers can spin by calling us over
1188 * and over. Panic for now until we can figure out something
1190 osi_Panic("Error freeing discarded dcache");
1197 * Try to free up a certain number of disk slots.
1199 * \param anumber Targeted number of disk slots to free up.
1201 * \note Environment:
1202 * Must be called with afs_xdcache write-locked.
1206 afs_GetDownDSlot(int anumber)
1208 struct afs_q *tq, *nq;
1213 AFS_STATCNT(afs_GetDownDSlot);
1214 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1215 osi_Panic("diskless getdowndslot");
1217 if (CheckLock(&afs_xdcache) != -1)
1218 osi_Panic("getdowndslot nolock");
1220 /* decrement anumber first for all dudes in free list */
1221 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1224 return; /* enough already free */
1226 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1228 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1229 nq = QPrev(tq); /* in case we remove it */
1230 if (tdc->refCount == 0) {
1231 if ((ix = tdc->index) == NULLIDX)
1232 osi_Panic("getdowndslot");
1233 /* pull the entry out of the lruq and put it on the free list */
1234 QRemove(&tdc->lruq);
1236 /* write-through if modified */
1237 if (tdc->dflags & DFEntryMod) {
1238 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1240 * ask proxy to do this for us - we don't have the stack space
1242 while (tdc->dflags & DFEntryMod) {
1245 s = SPLOCK(afs_sgibklock);
1246 if (afs_sgibklist == NULL) {
1247 /* if slot is free, grab it. */
1248 afs_sgibklist = tdc;
1249 SV_SIGNAL(&afs_sgibksync);
1251 /* wait for daemon to (start, then) finish. */
1252 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1256 tdc->dflags &= ~DFEntryMod;
1257 osi_Assert(afs_WriteDCache(tdc, 1) == 0);
1261 /* finally put the entry in the free list */
1262 afs_indexTable[ix] = NULL;
1263 afs_indexFlags[ix] &= ~IFEverUsed;
1264 tdc->index = NULLIDX;
1265 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1266 afs_freeDSList = tdc;
1270 } /*afs_GetDownDSlot */
1277 * Increment the reference count on a disk cache entry,
1278 * which already has a non-zero refcount. In order to
1279 * increment the refcount of a zero-reference entry, you
1280 * have to hold afs_xdcache.
1283 * adc : Pointer to the dcache entry to increment.
1286 * Nothing interesting.
1289 afs_RefDCache(struct dcache *adc)
1291 ObtainWriteLock(&adc->tlock, 627);
1292 if (adc->refCount < 0)
1293 osi_Panic("RefDCache: negative refcount");
1295 ReleaseWriteLock(&adc->tlock);
1304 * Decrement the reference count on a disk cache entry.
1307 * ad : Ptr to the dcache entry to decrement.
1310 * Nothing interesting.
1313 afs_PutDCache(struct dcache *adc)
1315 AFS_STATCNT(afs_PutDCache);
1316 ObtainWriteLock(&adc->tlock, 276);
1317 if (adc->refCount <= 0)
1318 osi_Panic("putdcache");
1320 ReleaseWriteLock(&adc->tlock);
1329 * Try to discard all data associated with this file from the
1333 * avc : Pointer to the cache info for the file.
1336 * Both pvnLock and lock are write held.
1339 afs_TryToSmush(struct vcache *avc, afs_ucred_t *acred, int sync)
1344 AFS_STATCNT(afs_TryToSmush);
1345 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1346 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1347 sync = 1; /* XX Temp testing XX */
1349 #if defined(AFS_SUN5_ENV)
1350 ObtainWriteLock(&avc->vlock, 573);
1351 avc->activeV++; /* block new getpages */
1352 ReleaseWriteLock(&avc->vlock);
1355 /* Flush VM pages */
1356 osi_VM_TryToSmush(avc, acred, sync);
1359 * Get the hash chain containing all dce's for this fid
1361 i = DVHash(&avc->f.fid);
1362 ObtainWriteLock(&afs_xdcache, 277);
1363 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1364 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1365 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1366 int releaseTlock = 1;
1367 tdc = afs_GetValidDSlot(index);
1369 /* afs_TryToSmush is best-effort; we may not actually discard
1370 * everything, so failure to discard a dcache due to an i/o
1374 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1376 if ((afs_indexFlags[index] & IFDataMod) == 0
1377 && tdc->refCount == 1) {
1378 ReleaseReadLock(&tdc->tlock);
1380 afs_FlushDCache(tdc);
1383 afs_indexTable[index] = 0;
1386 ReleaseReadLock(&tdc->tlock);
1390 #if defined(AFS_SUN5_ENV)
1391 ObtainWriteLock(&avc->vlock, 545);
1392 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1393 avc->vstates &= ~VRevokeWait;
1394 afs_osi_Wakeup((char *)&avc->vstates);
1396 ReleaseWriteLock(&avc->vlock);
1398 ReleaseWriteLock(&afs_xdcache);
1400 * It's treated like a callback so that when we do lookups we'll
1401 * invalidate the unique bit if any
1402 * trytoSmush occured during the lookup call
1408 * afs_DCacheMissingChunks
1411 * Given the cached info for a file, return the number of chunks that
1412 * are not available from the dcache.
1415 * avc: Pointer to the (held) vcache entry to look in.
1418 * The number of chunks which are not currently cached.
1421 * The vcache entry is held upon entry.
1425 afs_DCacheMissingChunks(struct vcache *avc)
1428 afs_size_t totalLength = 0;
1429 afs_uint32 totalChunks = 0;
1432 totalLength = avc->f.m.Length;
1433 if (avc->f.truncPos < totalLength)
1434 totalLength = avc->f.truncPos;
1436 /* Length is 0, no chunk missing. */
1437 if (totalLength == 0)
1440 /* If totalLength is a multiple of chunksize, the last byte appears
1441 * as being part of the next chunk, which does not exist.
1442 * Decrementing totalLength by one fixes that.
1445 totalChunks = (AFS_CHUNK(totalLength) + 1);
1447 /* If we're a directory, we only ever have one chunk, regardless of
1448 * the size of the dir.
1450 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1454 printf("Should have %d chunks for %u bytes\n",
1455 totalChunks, (totalLength + 1));
1457 i = DVHash(&avc->f.fid);
1458 ObtainWriteLock(&afs_xdcache, 1001);
1459 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1460 i = afs_dvnextTbl[index];
1461 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1462 tdc = afs_GetValidDSlot(index);
1464 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1467 ReleaseReadLock(&tdc->tlock);
1472 ReleaseWriteLock(&afs_xdcache);
1474 /*printf("Missing %d chunks\n", totalChunks);*/
1476 return (totalChunks);
1483 * Given the cached info for a file and a byte offset into the
1484 * file, make sure the dcache entry for that file and containing
1485 * the given byte is available, returning it to our caller.
1488 * avc : Pointer to the (held) vcache entry to look in.
1489 * abyte : Which byte we want to get to.
1492 * Pointer to the dcache entry covering the file & desired byte,
1493 * or NULL if not found.
1496 * The vcache entry is held upon entry.
1500 afs_FindDCache(struct vcache *avc, afs_size_t abyte)
1504 struct dcache *tdc = NULL;
1506 AFS_STATCNT(afs_FindDCache);
1507 chunk = AFS_CHUNK(abyte);
1510 * Hash on the [fid, chunk] and get the corresponding dcache index
1511 * after write-locking the dcache.
1513 i = DCHash(&avc->f.fid, chunk);
1514 ObtainWriteLock(&afs_xdcache, 278);
1515 for (index = afs_dchashTbl[i]; index != NULLIDX; index = afs_dcnextTbl[index]) {
1516 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1517 tdc = afs_GetValidDSlot(index);
1519 /* afs_FindDCache is best-effort; we may not find the given
1520 * file/offset, so if we cannot find the given dcache due to
1521 * i/o errors, that is okay. */
1524 ReleaseReadLock(&tdc->tlock);
1525 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1526 break; /* leaving refCount high for caller */
1531 if (index != NULLIDX) {
1532 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1533 hadd32(afs_indexCounter, 1);
1534 ReleaseWriteLock(&afs_xdcache);
1537 ReleaseWriteLock(&afs_xdcache);
1539 } /*afs_FindDCache */
1541 /* only call these from afs_AllocDCache() */
1542 static struct dcache *
1543 afs_AllocFreeDSlot(void)
1547 tdc = afs_GetDSlotFromList(&afs_freeDCList);
1551 afs_indexFlags[tdc->index] &= ~IFFree;
1552 ObtainWriteLock(&tdc->lock, 604);
1557 static struct dcache *
1558 afs_AllocDiscardDSlot(afs_int32 lock)
1561 afs_uint32 size = 0;
1562 struct osi_file *file;
1564 tdc = afs_GetDSlotFromList(&afs_discardDCList);
1568 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1569 ObtainWriteLock(&tdc->lock, 605);
1570 afs_discardDCCount--;
1572 ((tdc->f.chunkBytes +
1573 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1574 tdc->f.states &= ~(DRO|DBackup|DRW);
1575 afs_DCMoveBucket(tdc, size, 0);
1576 afs_blocksDiscarded -= size;
1577 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1579 /* Truncate the chunk so zeroes get filled properly */
1580 file = afs_CFileOpen(&tdc->f.inode);
1581 afs_CFileTruncate(file, 0);
1582 afs_CFileClose(file);
1583 afs_AdjustSize(tdc, 0);
1590 * Get a fresh dcache from the free or discarded list.
1592 * \param avc Who's dcache is this going to be?
1593 * \param chunk The position where it will be placed in.
1594 * \param lock How are locks held.
1595 * \param ashFid If this dcache going to be used for a shadow dir,
1598 * \note Required locks:
1600 * - avc (R if (lock & 1) set and W otherwise)
1601 * \note It write locks the new dcache. The caller must unlock it.
1603 * \return The new dcache.
1606 afs_AllocDCache(struct vcache *avc, afs_int32 chunk, afs_int32 lock,
1607 struct VenusFid *ashFid)
1609 struct dcache *tdc = NULL;
1611 /* if (lock & 2), prefer 'free' dcaches; otherwise, prefer 'discard'
1612 * dcaches. In either case, try both if our first choice doesn't work. */
1614 tdc = afs_AllocFreeDSlot();
1616 tdc = afs_AllocDiscardDSlot(lock);
1619 tdc = afs_AllocDiscardDSlot(lock);
1621 tdc = afs_AllocFreeDSlot();
1630 * avc->lock(R) if setLocks
1631 * avc->lock(W) if !setLocks
1637 * Fill in the newly-allocated dcache record.
1639 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1641 /* Use shadow fid if provided. */
1642 tdc->f.fid = *ashFid;
1644 /* Use normal vcache's fid otherwise. */
1645 tdc->f.fid = avc->f.fid;
1646 if (avc->f.states & CRO)
1647 tdc->f.states = DRO;
1648 else if (avc->f.states & CBackup)
1649 tdc->f.states = DBackup;
1651 tdc->f.states = DRW;
1652 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1653 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1655 hones(tdc->f.versionNo); /* invalid value */
1656 tdc->f.chunk = chunk;
1657 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1659 if (tdc->lruq.prev == &tdc->lruq)
1660 osi_Panic("lruq 1");
1669 * This function is called to obtain a reference to data stored in
1670 * the disk cache, locating a chunk of data containing the desired
1671 * byte and returning a reference to the disk cache entry, with its
1672 * reference count incremented.
1676 * avc : Ptr to a vcache entry (unlocked)
1677 * abyte : Byte position in the file desired
1678 * areq : Request structure identifying the requesting user.
1679 * aflags : Settings as follows:
1681 * 2 : Return after creating entry.
1682 * 4 : called from afs_vnop_write.c
1683 * *alen contains length of data to be written.
1685 * aoffset : Set to the offset within the chunk where the resident
1687 * alen : Set to the number of bytes of data after the desired
1688 * byte (including the byte itself) which can be read
1692 * The vcache entry pointed to by avc is unlocked upon entry.
1696 * Update the vnode-to-dcache hint if we can get the vnode lock
1697 * right away. Assumes dcache entry is at least read-locked.
1700 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1702 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1703 if (hsame(v->f.m.DataVersion, d->f.versionNo) && v->callback)
1706 ReleaseWriteLock(&v->lock);
1710 /* avc - Write-locked unless aflags & 1 */
1712 afs_GetDCache(struct vcache *avc, afs_size_t abyte,
1713 struct vrequest *areq, afs_size_t * aoffset,
1714 afs_size_t * alen, int aflags)
1716 afs_int32 i, code, shortcut;
1717 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1718 afs_int32 adjustsize = 0;
1724 afs_size_t Position = 0;
1725 afs_int32 size, tlen; /* size of segment to transfer */
1726 struct afs_FetchOutput *tsmall = 0;
1728 struct osi_file *file;
1729 struct afs_conn *tc;
1731 struct server *newCallback = NULL;
1732 char setNewCallback;
1733 char setVcacheStatus;
1734 char doVcacheUpdate;
1736 int doAdjustSize = 0;
1737 int doReallyAdjustSize = 0;
1738 int overWriteWholeChunk = 0;
1739 struct rx_connection *rxconn;
1742 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1743 int fromReplica; /*Are we reading from a replica? */
1744 int numFetchLoops; /*# times around the fetch/analyze loop */
1745 #endif /* AFS_NOSTATS */
1747 AFS_STATCNT(afs_GetDCache);
1751 setLocks = aflags & 1;
1754 * Determine the chunk number and offset within the chunk corresponding
1755 * to the desired byte.
1757 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1760 chunk = AFS_CHUNK(abyte);
1763 /* come back to here if we waited for the cache to drain. */
1766 setNewCallback = setVcacheStatus = 0;
1770 ObtainWriteLock(&avc->lock, 616);
1772 ObtainReadLock(&avc->lock);
1777 * avc->lock(R) if setLocks && !slowPass
1778 * avc->lock(W) if !setLocks || slowPass
1783 /* check hints first! (might could use bcmp or some such...) */
1784 if ((tdc = avc->dchint)) {
1788 * The locking order between afs_xdcache and dcache lock matters.
1789 * The hint dcache entry could be anywhere, even on the free list.
1790 * Locking afs_xdcache ensures that noone is trying to pull dcache
1791 * entries from the free list, and thereby assuming them to be not
1792 * referenced and not locked.
1794 ObtainReadLock(&afs_xdcache);
1795 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1797 if (dcLocked && (tdc->index != NULLIDX)
1798 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
1799 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1800 /* got the right one. It might not be the right version, and it
1801 * might be fetching, but it's the right dcache entry.
1803 /* All this code should be integrated better with what follows:
1804 * I can save a good bit more time under a write lock if I do..
1806 ObtainWriteLock(&tdc->tlock, 603);
1808 ReleaseWriteLock(&tdc->tlock);
1810 ReleaseReadLock(&afs_xdcache);
1813 if (hsame(tdc->f.versionNo, avc->f.m.DataVersion)
1814 && !(tdc->dflags & DFFetching)) {
1816 afs_stats_cmperf.dcacheHits++;
1817 ObtainWriteLock(&afs_xdcache, 559);
1818 QRemove(&tdc->lruq);
1819 QAdd(&afs_DLRU, &tdc->lruq);
1820 ReleaseWriteLock(&afs_xdcache);
1823 * avc->lock(R) if setLocks && !slowPass
1824 * avc->lock(W) if !setLocks || slowPass
1831 ReleaseSharedLock(&tdc->lock);
1832 ReleaseReadLock(&afs_xdcache);
1840 * avc->lock(R) if setLocks && !slowPass
1841 * avc->lock(W) if !setLocks || slowPass
1842 * tdc->lock(S) if tdc
1845 if (!tdc) { /* If the hint wasn't the right dcache entry */
1846 int dslot_error = 0;
1848 * Hash on the [fid, chunk] and get the corresponding dcache index
1849 * after write-locking the dcache.
1854 * avc->lock(R) if setLocks && !slowPass
1855 * avc->lock(W) if !setLocks || slowPass
1858 i = DCHash(&avc->f.fid, chunk);
1859 /* check to make sure our space is fine */
1860 afs_MaybeWakeupTruncateDaemon();
1862 ObtainWriteLock(&afs_xdcache, 280);
1864 for (index = afs_dchashTbl[i]; index != NULLIDX; us = index, index = afs_dcnextTbl[index]) {
1865 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1866 tdc = afs_GetValidDSlot(index);
1868 /* we got an i/o error when trying to get the given dslot,
1869 * but do not bail out just yet; it is possible the dcache
1870 * we're looking for is elsewhere, so it doesn't matter if
1871 * we can't load this one. */
1875 ReleaseReadLock(&tdc->tlock);
1878 * avc->lock(R) if setLocks && !slowPass
1879 * avc->lock(W) if !setLocks || slowPass
1882 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1883 /* Move it up in the beginning of the list */
1884 if (afs_dchashTbl[i] != index) {
1885 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1886 afs_dcnextTbl[index] = afs_dchashTbl[i];
1887 afs_dchashTbl[i] = index;
1889 ReleaseWriteLock(&afs_xdcache);
1890 ObtainSharedLock(&tdc->lock, 606);
1891 break; /* leaving refCount high for caller */
1899 * If we didn't find the entry, we'll create one.
1901 if (index == NULLIDX) {
1904 * avc->lock(R) if setLocks
1905 * avc->lock(W) if !setLocks
1908 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1909 avc, ICL_TYPE_INT32, chunk);
1912 /* We couldn't find the dcache we want, but we hit some i/o
1913 * errors when trying to find it, so we're not sure if the
1914 * dcache we want is in the cache or not. Error out, so we
1915 * don't try to possibly create 2 separate dcaches for the
1916 * same exact data. */
1917 ReleaseWriteLock(&afs_xdcache);
1921 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1923 avc->f.states |= CDCLock;
1924 /* just need slots */
1925 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1927 avc->f.states &= ~CDCLock;
1929 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
1931 /* If we can't get space for 5 mins we give up and panic */
1932 if (++downDCount > 300)
1933 osi_Panic("getdcache");
1934 ReleaseWriteLock(&afs_xdcache);
1937 * avc->lock(R) if setLocks
1938 * avc->lock(W) if !setLocks
1940 afs_osi_Wait(1000, 0, 0);
1946 * avc->lock(R) if setLocks
1947 * avc->lock(W) if !setLocks
1953 * Now add to the two hash chains - note that i is still set
1954 * from the above DCHash call.
1956 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1957 afs_dchashTbl[i] = tdc->index;
1958 i = DVHash(&avc->f.fid);
1959 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1960 afs_dvhashTbl[i] = tdc->index;
1961 tdc->dflags = DFEntryMod;
1963 afs_MaybeWakeupTruncateDaemon();
1964 ReleaseWriteLock(&afs_xdcache);
1965 ConvertWToSLock(&tdc->lock);
1970 /* vcache->dcache hint failed */
1973 * avc->lock(R) if setLocks && !slowPass
1974 * avc->lock(W) if !setLocks || slowPass
1977 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1978 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
1979 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
1980 hgetlo(avc->f.m.DataVersion));
1982 * Here we have the entry in tdc, with its refCount incremented.
1983 * Note: we don't use the S-lock on avc; it costs concurrency when
1984 * storing a file back to the server.
1988 * Not a newly created file so we need to check the file's length and
1989 * compare data versions since someone could have changed the data or we're
1990 * reading a file written elsewhere. We only want to bypass doing no-op
1991 * read rpcs on newly created files (dv of 0) since only then we guarantee
1992 * that this chunk's data hasn't been filled by another client.
1994 size = AFS_CHUNKSIZE(abyte);
1995 if (aflags & 4) /* called from write */
1997 else /* called from read */
1998 tlen = tdc->validPos - abyte;
1999 Position = AFS_CHUNKTOBASE(chunk);
2000 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
2001 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
2002 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
2003 ICL_HANDLE_OFFSET(Position));
2004 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
2006 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
2007 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
2008 overWriteWholeChunk = 1;
2009 if (doAdjustSize || overWriteWholeChunk) {
2010 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
2012 #ifdef AFS_SGI64_ENV
2015 #else /* AFS_SGI64_ENV */
2018 #endif /* AFS_SGI64_ENV */
2019 #else /* AFS_SGI_ENV */
2022 #endif /* AFS_SGI_ENV */
2023 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
2024 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2025 #if defined(AFS_SUN5_ENV)
2026 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
2028 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
2030 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2031 !hsame(avc->f.m.DataVersion, tdc->f.versionNo))
2032 doReallyAdjustSize = 1;
2034 if (doReallyAdjustSize || overWriteWholeChunk) {
2035 /* no data in file to read at this position */
2036 UpgradeSToWLock(&tdc->lock, 607);
2037 file = afs_CFileOpen(&tdc->f.inode);
2038 afs_CFileTruncate(file, 0);
2039 afs_CFileClose(file);
2040 afs_AdjustSize(tdc, 0);
2041 hset(tdc->f.versionNo, avc->f.m.DataVersion);
2042 tdc->dflags |= DFEntryMod;
2044 ConvertWToSLock(&tdc->lock);
2049 * We must read in the whole chunk if the version number doesn't
2053 /* don't need data, just a unique dcache entry */
2054 ObtainWriteLock(&afs_xdcache, 608);
2055 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2056 hadd32(afs_indexCounter, 1);
2057 ReleaseWriteLock(&afs_xdcache);
2059 updateV2DC(setLocks, avc, tdc, 553);
2060 if (vType(avc) == VDIR)
2063 *aoffset = AFS_CHUNKOFFSET(abyte);
2064 if (tdc->validPos < abyte)
2065 *alen = (afs_size_t) 0;
2067 *alen = tdc->validPos - abyte;
2068 ReleaseSharedLock(&tdc->lock);
2071 ReleaseWriteLock(&avc->lock);
2073 ReleaseReadLock(&avc->lock);
2075 return tdc; /* check if we're done */
2080 * avc->lock(R) if setLocks && !slowPass
2081 * avc->lock(W) if !setLocks || slowPass
2084 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
2086 setNewCallback = setVcacheStatus = 0;
2090 * avc->lock(R) if setLocks && !slowPass
2091 * avc->lock(W) if !setLocks || slowPass
2094 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
2096 * Version number mismatch.
2099 * If we are disconnected, then we can't do much of anything
2100 * because the data doesn't match the file.
2102 if (AFS_IS_DISCONNECTED) {
2103 ReleaseSharedLock(&tdc->lock);
2106 ReleaseWriteLock(&avc->lock);
2108 ReleaseReadLock(&avc->lock);
2110 /* Flush the Dcache */
2115 UpgradeSToWLock(&tdc->lock, 609);
2118 * If data ever existed for this vnode, and this is a text object,
2119 * do some clearing. Now, you'd think you need only do the flush
2120 * when VTEXT is on, but VTEXT is turned off when the text object
2121 * is freed, while pages are left lying around in memory marked
2122 * with this vnode. If we would reactivate (create a new text
2123 * object from) this vnode, we could easily stumble upon some of
2124 * these old pages in pagein. So, we always flush these guys.
2125 * Sun has a wonderful lack of useful invariants in this system.
2127 * avc->flushDV is the data version # of the file at the last text
2128 * flush. Clearly, at least, we don't have to flush the file more
2129 * often than it changes
2131 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2133 * By here, the cache entry is always write-locked. We can
2134 * deadlock if we call osi_Flush with the cache entry locked...
2135 * Unlock the dcache too.
2137 ReleaseWriteLock(&tdc->lock);
2138 if (setLocks && !slowPass)
2139 ReleaseReadLock(&avc->lock);
2141 ReleaseWriteLock(&avc->lock);
2145 * Call osi_FlushPages in open, read/write, and map, since it
2146 * is too hard here to figure out if we should lock the
2149 if (setLocks && !slowPass)
2150 ObtainReadLock(&avc->lock);
2152 ObtainWriteLock(&avc->lock, 66);
2153 ObtainWriteLock(&tdc->lock, 610);
2158 * avc->lock(R) if setLocks && !slowPass
2159 * avc->lock(W) if !setLocks || slowPass
2163 /* Watch for standard race condition around osi_FlushText */
2164 if (hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
2165 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2166 afs_stats_cmperf.dcacheHits++;
2167 ConvertWToSLock(&tdc->lock);
2171 /* Sleep here when cache needs to be drained. */
2172 if (setLocks && !slowPass
2173 && (afs_blocksUsed >
2174 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2175 /* Make sure truncate daemon is running */
2176 afs_MaybeWakeupTruncateDaemon();
2177 ObtainWriteLock(&tdc->tlock, 614);
2178 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2179 ReleaseWriteLock(&tdc->tlock);
2180 ReleaseWriteLock(&tdc->lock);
2181 ReleaseReadLock(&avc->lock);
2182 while ((afs_blocksUsed - afs_blocksDiscarded) >
2183 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2184 afs_WaitForCacheDrain = 1;
2185 afs_osi_Sleep(&afs_WaitForCacheDrain);
2187 afs_MaybeFreeDiscardedDCache();
2188 /* need to check if someone else got the chunk first. */
2189 goto RetryGetDCache;
2192 Position = AFS_CHUNKBASE(abyte);
2193 if (vType(avc) == VDIR) {
2194 size = avc->f.m.Length;
2195 if (size > tdc->f.chunkBytes) {
2196 /* pre-reserve space for file */
2197 afs_AdjustSize(tdc, size);
2199 size = 999999999; /* max size for transfer */
2201 afs_size_t maxGoodLength;
2203 /* estimate how much data we're expecting back from the server,
2204 * and reserve space in the dcache entry for it */
2206 maxGoodLength = avc->f.m.Length;
2207 if (avc->f.truncPos < maxGoodLength)
2208 maxGoodLength = avc->f.truncPos;
2210 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2211 if (Position + size > maxGoodLength)
2212 size = maxGoodLength - Position;
2214 size = 0; /* Handle random races */
2215 if (size > tdc->f.chunkBytes) {
2216 /* pre-reserve estimated space for file */
2217 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2221 /* For the actual fetch, do not limit the request to the
2222 * length of the file. If this results in a read past EOF on
2223 * the server, the server will just reply with less data than
2224 * requested. If we limit ourselves to only requesting data up
2225 * to the avc file length, we open ourselves up to races if the
2226 * file is extended on the server at about the same time.
2228 * However, we must restrict ourselves to the avc->f.truncPos
2229 * length, since this represents an outstanding local
2230 * truncation of the file that will be committed to the
2231 * fileserver when we actually write the fileserver contents.
2232 * If we do not restrict the fetch length based on
2233 * avc->f.truncPos, a different truncate operation extending
2234 * the file length could cause the old data after
2235 * avc->f.truncPos to reappear, instead of extending the file
2236 * with NUL bytes. */
2237 size = AFS_CHUNKSIZE(abyte);
2238 if (Position + size > avc->f.truncPos) {
2239 size = avc->f.truncPos - Position;
2246 if (afs_mariner && !tdc->f.chunk)
2247 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2249 * Right now, we only have one tool, and it's a hammer. So, we
2250 * fetch the whole file.
2252 DZap(tdc); /* pages in cache may be old */
2253 file = afs_CFileOpen(&tdc->f.inode);
2254 afs_RemoveVCB(&avc->f.fid);
2255 tdc->f.states |= DWriting;
2256 tdc->dflags |= DFFetching;
2257 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2258 if (tdc->mflags & DFFetchReq) {
2259 tdc->mflags &= ~DFFetchReq;
2260 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2261 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2262 __FILE__, ICL_TYPE_INT32, __LINE__,
2263 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2266 tsmall = osi_AllocLargeSpace(sizeof(struct afs_FetchOutput));
2267 setVcacheStatus = 0;
2270 * Remember if we are doing the reading from a replicated volume,
2271 * and how many times we've zipped around the fetch/analyze loop.
2273 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2275 accP = &(afs_stats_cmfullperf.accessinf);
2277 (accP->replicatedRefs)++;
2279 (accP->unreplicatedRefs)++;
2280 #endif /* AFS_NOSTATS */
2281 /* this is a cache miss */
2282 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2283 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2284 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2287 afs_stats_cmperf.dcacheMisses++;
2290 * Dynamic root support: fetch data from local memory.
2292 if (afs_IsDynroot(avc)) {
2296 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2298 dynrootDir += Position;
2299 dynrootLen -= Position;
2300 if (size > dynrootLen)
2304 code = afs_CFileWrite(file, 0, dynrootDir, size);
2312 tdc->validPos = Position + size;
2313 afs_CFileTruncate(file, size); /* prune it */
2314 } else if (afs_IsDynrootMount(avc)) {
2318 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2320 dynrootDir += Position;
2321 dynrootLen -= Position;
2322 if (size > dynrootLen)
2326 code = afs_CFileWrite(file, 0, dynrootDir, size);
2334 tdc->validPos = Position + size;
2335 afs_CFileTruncate(file, size); /* prune it */
2338 * Not a dynamic vnode: do the real fetch.
2343 * avc->lock(R) if setLocks && !slowPass
2344 * avc->lock(W) if !setLocks || slowPass
2348 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
2353 (accP->numReplicasAccessed)++;
2355 #endif /* AFS_NOSTATS */
2356 if (!setLocks || slowPass) {
2357 avc->callback = tc->parent->srvr->server;
2359 newCallback = tc->parent->srvr->server;
2363 code = afs_CacheFetchProc(tc, rxconn, file, Position, tdc,
2369 /* callback could have been broken (or expired) in a race here,
2370 * but we return the data anyway. It's as good as we knew about
2371 * when we started. */
2373 * validPos is updated by CacheFetchProc, and can only be
2374 * modifed under a dcache write lock, which we've blocked out
2376 size = tdc->validPos - Position; /* actual segment size */
2379 afs_CFileTruncate(file, size); /* prune it */
2381 if (!setLocks || slowPass) {
2382 ObtainWriteLock(&afs_xcbhash, 453);
2383 afs_DequeueCallback(avc);
2384 avc->f.states &= ~(CStatd | CUnique);
2385 avc->callback = NULL;
2386 ReleaseWriteLock(&afs_xcbhash);
2387 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2388 osi_dnlc_purgedp(avc);
2390 /* Something lost. Forget about performance, and go
2391 * back with a vcache write lock.
2393 afs_CFileTruncate(file, 0);
2394 afs_AdjustSize(tdc, 0);
2395 afs_CFileClose(file);
2396 osi_FreeLargeSpace(tsmall);
2398 ReleaseWriteLock(&tdc->lock);
2401 ReleaseReadLock(&avc->lock);
2403 goto RetryGetDCache;
2407 } while (afs_Analyze
2408 (tc, rxconn, code, &avc->f.fid, areq,
2409 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2413 * avc->lock(R) if setLocks && !slowPass
2414 * avc->lock(W) if !setLocks || slowPass
2420 * In the case of replicated access, jot down info on the number of
2421 * attempts it took before we got through or gave up.
2424 if (numFetchLoops <= 1)
2425 (accP->refFirstReplicaOK)++;
2426 if (numFetchLoops > accP->maxReplicasPerRef)
2427 accP->maxReplicasPerRef = numFetchLoops;
2429 #endif /* AFS_NOSTATS */
2431 tdc->dflags &= ~DFFetching;
2432 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2433 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2434 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2435 tdc, ICL_TYPE_INT32, tdc->dflags);
2436 if (avc->execsOrWriters == 0)
2437 tdc->f.states &= ~DWriting;
2439 /* now, if code != 0, we have an error and should punt.
2440 * note that we have the vcache write lock, either because
2441 * !setLocks or slowPass.
2444 afs_CFileTruncate(file, 0);
2445 afs_AdjustSize(tdc, 0);
2446 afs_CFileClose(file);
2447 ZapDCE(tdc); /* sets DFEntryMod */
2448 if (vType(avc) == VDIR) {
2451 tdc->f.states &= ~(DRO|DBackup|DRW);
2452 afs_DCMoveBucket(tdc, 0, 0);
2453 ReleaseWriteLock(&tdc->lock);
2455 if (!afs_IsDynroot(avc)) {
2456 ObtainWriteLock(&afs_xcbhash, 454);
2457 afs_DequeueCallback(avc);
2458 avc->f.states &= ~(CStatd | CUnique);
2459 ReleaseWriteLock(&afs_xcbhash);
2460 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2461 osi_dnlc_purgedp(avc);
2464 * avc->lock(W); assert(!setLocks || slowPass)
2466 osi_Assert(!setLocks || slowPass);
2472 /* otherwise we copy in the just-fetched info */
2473 afs_CFileClose(file);
2474 afs_AdjustSize(tdc, size); /* new size */
2476 * Copy appropriate fields into vcache. Status is
2477 * copied later where we selectively acquire the
2478 * vcache write lock.
2481 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2483 setVcacheStatus = 1;
2484 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2485 tsmall->OutStatus.DataVersion);
2486 tdc->dflags |= DFEntryMod;
2487 afs_indexFlags[tdc->index] |= IFEverUsed;
2488 ConvertWToSLock(&tdc->lock);
2489 } /*Data version numbers don't match */
2492 * Data version numbers match.
2494 afs_stats_cmperf.dcacheHits++;
2495 } /*Data version numbers match */
2497 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2501 * avc->lock(R) if setLocks && !slowPass
2502 * avc->lock(W) if !setLocks || slowPass
2503 * tdc->lock(S) if tdc
2507 * See if this was a reference to a file in the local cell.
2509 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2510 afs_stats_cmperf.dlocalAccesses++;
2512 afs_stats_cmperf.dremoteAccesses++;
2514 /* Fix up LRU info */
2517 ObtainWriteLock(&afs_xdcache, 602);
2518 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2519 hadd32(afs_indexCounter, 1);
2520 ReleaseWriteLock(&afs_xdcache);
2522 /* return the data */
2523 if (vType(avc) == VDIR)
2526 *aoffset = AFS_CHUNKOFFSET(abyte);
2527 *alen = (tdc->f.chunkBytes - *aoffset);
2528 ReleaseSharedLock(&tdc->lock);
2533 * avc->lock(R) if setLocks && !slowPass
2534 * avc->lock(W) if !setLocks || slowPass
2537 /* Fix up the callback and status values in the vcache */
2539 if (setLocks && !slowPass) {
2542 * This is our dirty little secret to parallel fetches.
2543 * We don't write-lock the vcache while doing the fetch,
2544 * but potentially we'll need to update the vcache after
2545 * the fetch is done.
2547 * Drop the read lock and try to re-obtain the write
2548 * lock. If the vcache still has the same DV, it's
2549 * ok to go ahead and install the new data.
2551 afs_hyper_t currentDV, statusDV;
2553 hset(currentDV, avc->f.m.DataVersion);
2555 if (setNewCallback && avc->callback != newCallback)
2559 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2560 tsmall->OutStatus.DataVersion);
2562 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2564 if (setVcacheStatus && !hsame(currentDV, statusDV))
2568 ReleaseReadLock(&avc->lock);
2570 if (doVcacheUpdate) {
2571 ObtainWriteLock(&avc->lock, 615);
2572 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2573 /* We lose. Someone will beat us to it. */
2575 ReleaseWriteLock(&avc->lock);
2580 /* With slow pass, we've already done all the updates */
2582 ReleaseWriteLock(&avc->lock);
2585 /* Check if we need to perform any last-minute fixes with a write-lock */
2586 if (!setLocks || doVcacheUpdate) {
2588 avc->callback = newCallback;
2589 if (tsmall && setVcacheStatus)
2590 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2592 ReleaseWriteLock(&avc->lock);
2596 osi_FreeLargeSpace(tsmall);
2599 } /*afs_GetDCache */
2603 * afs_WriteThroughDSlots
2606 * Sweep through the dcache slots and write out any modified
2607 * in-memory data back on to our caching store.
2613 * The afs_xdcache is write-locked through this whole affair.
2616 afs_WriteThroughDSlots(void)
2619 afs_int32 i, touchedit = 0;
2621 struct afs_q DirtyQ, *tq;
2623 AFS_STATCNT(afs_WriteThroughDSlots);
2626 * Because of lock ordering, we can't grab dcache locks while
2627 * holding afs_xdcache. So we enter xdcache, get a reference
2628 * for every dcache entry, and exit xdcache.
2630 ObtainWriteLock(&afs_xdcache, 283);
2632 for (i = 0; i < afs_cacheFiles; i++) {
2633 tdc = afs_indexTable[i];
2635 /* Grab tlock in case the existing refcount isn't zero */
2636 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2637 ObtainWriteLock(&tdc->tlock, 623);
2639 ReleaseWriteLock(&tdc->tlock);
2641 QAdd(&DirtyQ, &tdc->dirty);
2644 ReleaseWriteLock(&afs_xdcache);
2647 * Now, for each dcache entry we found, check if it's dirty.
2648 * If so, get write-lock, get afs_xdcache, which protects
2649 * afs_cacheInodep, and flush it. Don't forget to put back
2653 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2655 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2657 if (tdc->dflags & DFEntryMod) {
2660 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2662 /* Now that we have the write lock, double-check */
2663 if (wrLock && (tdc->dflags & DFEntryMod)) {
2664 tdc->dflags &= ~DFEntryMod;
2665 ObtainWriteLock(&afs_xdcache, 620);
2666 osi_Assert(afs_WriteDCache(tdc, 1) == 0);
2667 ReleaseWriteLock(&afs_xdcache);
2671 ReleaseWriteLock(&tdc->lock);
2677 ObtainWriteLock(&afs_xdcache, 617);
2678 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2679 /* Touch the file to make sure that the mtime on the file is kept
2680 * up-to-date to avoid losing cached files on cold starts because
2681 * their mtime seems old...
2683 struct afs_fheader theader;
2685 theader.magic = AFS_FHMAGIC;
2686 theader.firstCSize = AFS_FIRSTCSIZE;
2687 theader.otherCSize = AFS_OTHERCSIZE;
2688 theader.version = AFS_CI_VERSION;
2689 theader.dataSize = sizeof(struct fcache);
2690 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2692 ReleaseWriteLock(&afs_xdcache);
2699 * Return a pointer to an freshly initialized dcache entry using
2700 * a memory-based cache. The tlock will be read-locked.
2703 * aslot : Dcache slot to look at.
2704 * needvalid : Whether the specified slot should already exist
2707 * Must be called with afs_xdcache write-locked.
2711 afs_MemGetDSlot(afs_int32 aslot, int indexvalid, int datavalid)
2716 AFS_STATCNT(afs_MemGetDSlot);
2717 if (CheckLock(&afs_xdcache) != -1)
2718 osi_Panic("getdslot nolock");
2719 if (aslot < 0 || aslot >= afs_cacheFiles)
2720 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2721 tdc = afs_indexTable[aslot];
2723 QRemove(&tdc->lruq); /* move to queue head */
2724 QAdd(&afs_DLRU, &tdc->lruq);
2725 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2726 ObtainWriteLock(&tdc->tlock, 624);
2728 ConvertWToRLock(&tdc->tlock);
2732 /* if 'indexvalid' is true, the slot must already exist and be populated
2733 * somewhere. for memcache, the only place that dcache entries exist is
2734 * in memory, so if we did not find it above, something is very wrong. */
2735 osi_Assert(!indexvalid);
2737 if (!afs_freeDSList)
2738 afs_GetDownDSlot(4);
2739 if (!afs_freeDSList) {
2740 /* none free, making one is better than a panic */
2741 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2742 tdc = afs_osi_Alloc(sizeof(struct dcache));
2743 osi_Assert(tdc != NULL);
2744 #ifdef KERNEL_HAVE_PIN
2745 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2748 tdc = afs_freeDSList;
2749 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2752 tdc->dflags = 0; /* up-to-date, not in free q */
2754 QAdd(&afs_DLRU, &tdc->lruq);
2755 if (tdc->lruq.prev == &tdc->lruq)
2756 osi_Panic("lruq 3");
2758 /* initialize entry */
2759 tdc->f.fid.Cell = 0;
2760 tdc->f.fid.Fid.Volume = 0;
2762 hones(tdc->f.versionNo);
2763 tdc->f.inode.mem = aslot;
2764 tdc->dflags |= DFEntryMod;
2767 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2770 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2771 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2772 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2775 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2776 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2777 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2778 ObtainReadLock(&tdc->tlock);
2780 afs_indexTable[aslot] = tdc;
2783 } /*afs_MemGetDSlot */
2785 unsigned int last_error = 0, lasterrtime = 0;
2791 * Return a pointer to an freshly initialized dcache entry using
2792 * a UFS-based disk cache. The dcache tlock will be read-locked.
2795 * aslot : Dcache slot to look at.
2796 * indexvalid : 1 if we know the slot we're giving is valid, and thus
2797 * reading the dcache from the disk index should succeed. 0
2798 * if we are initializing a new dcache, and so reading from
2799 * the disk index may fail.
2800 * datavalid : 0 if we are loading a dcache entry from the free or
2801 * discard list, so we know the data in the given dcache is
2802 * not valid. 1 if we are loading a known used dcache, so the
2803 * data in the dcache must be valid.
2806 * afs_xdcache lock write-locked.
2809 afs_UFSGetDSlot(afs_int32 aslot, int indexvalid, int datavalid)
2817 AFS_STATCNT(afs_UFSGetDSlot);
2818 if (CheckLock(&afs_xdcache) != -1)
2819 osi_Panic("getdslot nolock");
2820 if (aslot < 0 || aslot >= afs_cacheFiles)
2821 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2822 tdc = afs_indexTable[aslot];
2824 QRemove(&tdc->lruq); /* move to queue head */
2825 QAdd(&afs_DLRU, &tdc->lruq);
2826 /* Grab tlock in case refCount != 0 */
2827 ObtainWriteLock(&tdc->tlock, 625);
2829 ConvertWToRLock(&tdc->tlock);
2833 /* otherwise we should read it in from the cache file */
2834 if (!afs_freeDSList)
2835 afs_GetDownDSlot(4);
2836 if (!afs_freeDSList) {
2837 /* none free, making one is better than a panic */
2838 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2839 tdc = afs_osi_Alloc(sizeof(struct dcache));
2840 osi_Assert(tdc != NULL);
2841 #ifdef KERNEL_HAVE_PIN
2842 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2845 tdc = afs_freeDSList;
2846 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2849 tdc->dflags = 0; /* up-to-date, not in free q */
2851 QAdd(&afs_DLRU, &tdc->lruq);
2852 if (tdc->lruq.prev == &tdc->lruq)
2853 osi_Panic("lruq 3");
2856 * Seek to the aslot'th entry and read it in.
2858 off = sizeof(struct fcache)*aslot + sizeof(struct afs_fheader);
2860 afs_osi_Read(afs_cacheInodep,
2861 off, (char *)(&tdc->f),
2862 sizeof(struct fcache));
2864 if (code != sizeof(struct fcache)) {
2866 #if defined(KERNEL_HAVE_UERROR)
2867 last_error = getuerror();
2871 lasterrtime = osi_Time();
2873 struct osi_stat tstat;
2874 if (afs_osi_Stat(afs_cacheInodep, &tstat)) {
2877 afs_warn("afs: disk cache read error in CacheItems slot %d "
2878 "off %d/%d code %d/%d\n",
2880 off, (int)tstat.size,
2881 (int)code, (int)sizeof(struct fcache));
2882 /* put tdc back on the free dslot list */
2883 QRemove(&tdc->lruq);
2884 tdc->index = NULLIDX;
2885 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
2886 afs_freeDSList = tdc;
2890 if (!afs_CellNumValid(tdc->f.fid.Cell)) {
2893 osi_Panic("afs: needed valid dcache but index %d off %d has "
2894 "invalid cell num %d\n",
2895 (int)aslot, off, (int)tdc->f.fid.Cell);
2899 if (datavalid && tdc->f.fid.Fid.Volume == 0) {
2900 osi_Panic("afs: invalid zero-volume dcache entry at slot %d off %d",
2904 if (indexvalid && !datavalid) {
2905 /* we know that the given dslot does exist, but the data in it is not
2906 * valid. this only occurs when we pull a dslot from the free or
2907 * discard list, so be sure not to re-use the data; force invalidation.
2913 tdc->f.fid.Cell = 0;
2914 tdc->f.fid.Fid.Volume = 0;
2916 hones(tdc->f.versionNo);
2917 tdc->dflags |= DFEntryMod;
2918 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2919 tdc->f.states &= ~(DRO|DBackup|DRW);
2920 afs_DCMoveBucket(tdc, 0, 0);
2923 if (tdc->f.states & DRO) {
2924 afs_DCMoveBucket(tdc, 0, 2);
2925 } else if (tdc->f.states & DBackup) {
2926 afs_DCMoveBucket(tdc, 0, 1);
2928 afs_DCMoveBucket(tdc, 0, 1);
2934 if (tdc->f.chunk >= 0)
2935 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
2940 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2941 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2942 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2945 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2946 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2947 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2948 ObtainReadLock(&tdc->tlock);
2951 * If we didn't read into a temporary dcache region, update the
2952 * slot pointer table.
2954 afs_indexTable[aslot] = tdc;
2957 } /*afs_UFSGetDSlot */
2962 * Write a particular dcache entry back to its home in the
2965 * \param adc Pointer to the dcache entry to write.
2966 * \param atime If true, set the modtime on the file to the current time.
2968 * \note Environment:
2969 * Must be called with the afs_xdcache lock at least read-locked,
2970 * and dcache entry at least read-locked.
2971 * The reference count is not changed.
2975 afs_WriteDCache(struct dcache *adc, int atime)
2979 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2981 AFS_STATCNT(afs_WriteDCache);
2982 osi_Assert(WriteLocked(&afs_xdcache));
2984 adc->f.modTime = osi_Time();
2986 if ((afs_indexFlags[adc->index] & (IFFree | IFDiscarded)) == 0 &&
2987 adc->f.fid.Fid.Volume == 0) {
2988 /* If a dcache slot is not on the free or discard list, it must be
2989 * in the hash table. Thus, the volume must be non-zero, since that
2990 * is how we determine whether or not to unhash the entry when kicking
2991 * it out of the cache. Do this check now, since otherwise this can
2992 * cause hash table corruption and a panic later on after we read the
2994 osi_Panic("afs_WriteDCache zero volume index %d flags 0x%x\n",
2995 adc->index, (unsigned)afs_indexFlags[adc->index]);
2999 * Seek to the right dcache slot and write the in-memory image out to disk.
3001 afs_cellname_write();
3003 afs_osi_Write(afs_cacheInodep,
3004 sizeof(struct fcache) * adc->index +
3005 sizeof(struct afs_fheader), (char *)(&adc->f),
3006 sizeof(struct fcache));
3007 if (code != sizeof(struct fcache)) {
3008 afs_warn("afs: failed to write to CacheItems off %ld code %d/%d\n",
3009 (long)(sizeof(struct fcache) * adc->index + sizeof(struct afs_fheader)),
3010 (int)code, (int)sizeof(struct fcache));
3019 * Wake up users of a particular file waiting for stores to take
3022 * \param avc Ptr to related vcache entry.
3024 * \note Environment:
3025 * Nothing interesting.
3028 afs_wakeup(struct vcache *avc)
3031 struct brequest *tb;
3033 AFS_STATCNT(afs_wakeup);
3034 for (i = 0; i < NBRS; i++, tb++) {
3035 /* if request is valid and for this file, we've found it */
3036 if (tb->refCount > 0 && avc == tb->vc) {
3039 * If CSafeStore is on, then we don't awaken the guy
3040 * waiting for the store until the whole store has finished.
3041 * Otherwise, we do it now. Note that if CSafeStore is on,
3042 * the BStore routine actually wakes up the user, instead
3044 * I think this is redundant now because this sort of thing
3045 * is already being handled by the higher-level code.
3047 if ((avc->f.states & CSafeStore) == 0) {
3049 tb->flags |= BUVALID;
3050 if (tb->flags & BUWAIT) {
3051 tb->flags &= ~BUWAIT;
3062 * Given a file name and inode, set up that file to be an
3063 * active member in the AFS cache. This also involves checking
3064 * the usability of its data.
3066 * \param afile Name of the cache file to initialize.
3067 * \param ainode Inode of the file.
3069 * \note Environment:
3070 * This function is called only during initialization.
3073 afs_InitCacheFile(char *afile, ino_t ainode)
3078 struct osi_file *tfile;
3079 struct osi_stat tstat;
3082 AFS_STATCNT(afs_InitCacheFile);
3083 index = afs_stats_cmperf.cacheNumEntries;
3084 if (index >= afs_cacheFiles)
3087 ObtainWriteLock(&afs_xdcache, 282);
3088 tdc = afs_GetNewDSlot(index);
3089 ReleaseReadLock(&tdc->tlock);
3090 ReleaseWriteLock(&afs_xdcache);
3092 ObtainWriteLock(&tdc->lock, 621);
3093 ObtainWriteLock(&afs_xdcache, 622);
3094 if (!afile && !ainode) {
3099 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
3101 ReleaseWriteLock(&afs_xdcache);
3102 ReleaseWriteLock(&tdc->lock);
3107 /* Add any other 'complex' inode types here ... */
3108 #if !defined(AFS_LINUX26_ENV) && !defined(AFS_CACHE_VNODE_PATH)
3109 tdc->f.inode.ufs = ainode;
3111 osi_Panic("Can't init cache with inode numbers when complex inodes are "
3116 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3118 tfile = osi_UFSOpen(&tdc->f.inode);
3119 code = afs_osi_Stat(tfile, &tstat);
3121 osi_Panic("initcachefile stat");
3124 * If file size doesn't match the cache info file, it's probably bad.
3126 if (tdc->f.chunkBytes != tstat.size)
3129 * If file changed within T (120?) seconds of cache info file, it's
3130 * probably bad. In addition, if slot changed within last T seconds,
3131 * the cache info file may be incorrectly identified, and so slot
3134 if (cacheInfoModTime < tstat.mtime + 120)
3136 if (cacheInfoModTime < tdc->f.modTime + 120)
3138 /* In case write through is behind, make sure cache items entry is
3139 * at least as new as the chunk.
3141 if (tdc->f.modTime < tstat.mtime)
3144 tdc->f.chunkBytes = 0;
3147 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3148 if (tfile && tstat.size != 0)
3149 osi_UFSTruncate(tfile, 0);
3150 tdc->f.states &= ~(DRO|DBackup|DRW);
3151 afs_DCMoveBucket(tdc, 0, 0);
3152 /* put entry in free cache slot list */
3153 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3154 afs_freeDCList = index;
3156 afs_indexFlags[index] |= IFFree;
3157 afs_indexUnique[index] = 0;
3160 * We must put this entry in the appropriate hash tables.
3161 * Note that i is still set from the above DCHash call
3163 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3164 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3165 afs_dchashTbl[code] = tdc->index;
3166 code = DVHash(&tdc->f.fid);
3167 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3168 afs_dvhashTbl[code] = tdc->index;
3169 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3171 /* has nontrivial amt of data */
3172 afs_indexFlags[index] |= IFEverUsed;
3173 afs_stats_cmperf.cacheFilesReused++;
3175 * Initialize index times to file's mod times; init indexCounter
3178 hset32(afs_indexTimes[index], tstat.atime);
3179 if (hgetlo(afs_indexCounter) < tstat.atime) {
3180 hset32(afs_indexCounter, tstat.atime);
3182 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3183 } /*File is not bad */
3186 osi_UFSClose(tfile);
3187 tdc->f.states &= ~DWriting;
3188 tdc->dflags &= ~DFEntryMod;
3189 /* don't set f.modTime; we're just cleaning up */
3190 osi_Assert(afs_WriteDCache(tdc, 0) == 0);
3191 ReleaseWriteLock(&afs_xdcache);
3192 ReleaseWriteLock(&tdc->lock);
3194 afs_stats_cmperf.cacheNumEntries++;
3199 /*Max # of struct dcache's resident at any time*/
3201 * If 'dchint' is enabled then in-memory dcache min is increased because of
3207 * Initialize dcache related variables.
3217 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3223 afs_freeDCList = NULLIDX;
3224 afs_discardDCList = NULLIDX;
3225 afs_freeDCCount = 0;
3226 afs_freeDSList = NULL;
3227 hzero(afs_indexCounter);
3229 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3235 if (achunk < 0 || achunk > 30)
3236 achunk = 13; /* Use default */
3237 AFS_SETCHUNKSIZE(achunk);
3243 if (aDentries > 512)
3244 afs_dhashsize = 2048;
3245 /* initialize hash tables */
3246 afs_dvhashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3247 osi_Assert(afs_dvhashTbl != NULL);
3248 afs_dchashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3249 osi_Assert(afs_dchashTbl != NULL);
3250 for (i = 0; i < afs_dhashsize; i++) {
3251 afs_dvhashTbl[i] = NULLIDX;
3252 afs_dchashTbl[i] = NULLIDX;
3254 afs_dvnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3255 osi_Assert(afs_dvnextTbl != NULL);
3256 afs_dcnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3257 osi_Assert(afs_dcnextTbl != NULL);
3258 for (i = 0; i < afiles; i++) {
3259 afs_dvnextTbl[i] = NULLIDX;
3260 afs_dcnextTbl[i] = NULLIDX;
3263 /* Allocate and zero the pointer array to the dcache entries */
3264 afs_indexTable = afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3265 osi_Assert(afs_indexTable != NULL);
3266 memset(afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3267 afs_indexTimes = afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3268 osi_Assert(afs_indexTimes != NULL);
3269 memset(afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3270 afs_indexUnique = afs_osi_Alloc(afiles * sizeof(afs_uint32));
3271 osi_Assert(afs_indexUnique != NULL);
3272 memset(afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3273 afs_indexFlags = afs_osi_Alloc(afiles * sizeof(u_char));
3274 osi_Assert(afs_indexFlags != NULL);
3275 memset(afs_indexFlags, 0, afiles * sizeof(char));
3277 /* Allocate and thread the struct dcache entries themselves */
3278 tdp = afs_Initial_freeDSList =
3279 afs_osi_Alloc(aDentries * sizeof(struct dcache));
3280 osi_Assert(tdp != NULL);
3281 memset(tdp, 0, aDentries * sizeof(struct dcache));
3282 #ifdef KERNEL_HAVE_PIN
3283 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3284 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3285 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3286 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3287 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3288 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3289 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3290 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3291 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3294 afs_freeDSList = &tdp[0];
3295 for (i = 0; i < aDentries - 1; i++) {
3296 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3297 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3298 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3299 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3301 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3302 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3303 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3304 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3306 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3307 afs_cacheBlocks = ablocks;
3308 afs_ComputeCacheParms(); /* compute parms based on cache size */
3310 afs_dcentries = aDentries;
3312 afs_stats_cmperf.cacheBucket0_Discarded =
3313 afs_stats_cmperf.cacheBucket1_Discarded =
3314 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3318 if (aflags & AFSCALL_INIT_MEMCACHE) {
3320 * Use a memory cache instead of a disk cache
3322 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3323 afs_cacheType = &afs_MemCacheOps;
3324 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3325 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3326 /* ablocks is reported in 1K blocks */
3327 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3329 afs_warn("afsd: memory cache too large for available memory.\n");
3330 afs_warn("afsd: AFS files cannot be accessed.\n\n");
3333 afs_warn("Memory cache: Allocating %d dcache entries...",
3336 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3337 afs_cacheType = &afs_UfsCacheOps;
3342 * Shuts down the cache.
3346 shutdown_dcache(void)
3350 #ifdef AFS_CACHE_VNODE_PATH
3351 if (cacheDiskType != AFS_FCACHE_TYPE_MEM) {
3353 for (i = 0; i < afs_cacheFiles; i++) {
3354 tdc = afs_indexTable[i];
3356 afs_osi_FreeStr(tdc->f.inode.ufs);
3362 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3363 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3364 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3365 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3366 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3367 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3368 afs_osi_Free(afs_Initial_freeDSList,
3369 afs_dcentries * sizeof(struct dcache));
3370 #ifdef KERNEL_HAVE_PIN
3371 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3372 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3373 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3374 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3375 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3376 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3377 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3381 for (i = 0; i < afs_dhashsize; i++) {
3382 afs_dvhashTbl[i] = NULLIDX;
3383 afs_dchashTbl[i] = NULLIDX;
3386 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3387 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3389 afs_blocksUsed = afs_dcentries = 0;
3390 afs_stats_cmperf.cacheBucket0_Discarded =
3391 afs_stats_cmperf.cacheBucket1_Discarded =
3392 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3393 hzero(afs_indexCounter);
3395 afs_freeDCCount = 0;
3396 afs_freeDCList = NULLIDX;
3397 afs_discardDCList = NULLIDX;
3398 afs_freeDSList = afs_Initial_freeDSList = 0;
3400 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3406 * Get a dcache ready for writing, respecting the current cache size limits
3408 * len is required because afs_GetDCache with flag == 4 expects the length
3409 * field to be filled. It decides from this whether it's necessary to fetch
3410 * data into the chunk before writing or not (when the whole chunk is
3413 * \param avc The vcache to fetch a dcache for
3414 * \param filePos The start of the section to be written
3415 * \param len The length of the section to be written
3419 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3420 * must be released and afs_PutDCache() called to free dcache.
3423 * \note avc->lock must be held on entry. Function may release and reobtain
3424 * avc->lock and GLOCK.
3428 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3429 afs_size_t len, struct vrequest *areq,
3432 struct dcache *tdc = NULL;
3435 /* read the cached info */
3437 tdc = afs_FindDCache(avc, filePos);
3439 ObtainWriteLock(&tdc->lock, 657);
3440 } else if (afs_blocksUsed >
3441 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3442 tdc = afs_FindDCache(avc, filePos);
3444 ObtainWriteLock(&tdc->lock, 658);
3445 if (!hsame(tdc->f.versionNo, avc->f.m.DataVersion)
3446 || (tdc->dflags & DFFetching)) {
3447 ReleaseWriteLock(&tdc->lock);
3453 afs_MaybeWakeupTruncateDaemon();
3454 while (afs_blocksUsed >
3455 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3456 ReleaseWriteLock(&avc->lock);
3457 if (afs_blocksUsed - afs_blocksDiscarded >
3458 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3459 afs_WaitForCacheDrain = 1;
3460 afs_osi_Sleep(&afs_WaitForCacheDrain);
3462 afs_MaybeFreeDiscardedDCache();
3463 afs_MaybeWakeupTruncateDaemon();
3464 ObtainWriteLock(&avc->lock, 509);
3466 avc->f.states |= CDirty;
3467 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3469 ObtainWriteLock(&tdc->lock, 659);
3472 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3474 ObtainWriteLock(&tdc->lock, 660);
3477 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3478 afs_stats_cmperf.cacheCurrDirtyChunks++;
3479 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3481 if (!(tdc->f.states & DWriting)) {
3482 /* don't mark entry as mod if we don't have to */
3483 tdc->f.states |= DWriting;
3484 tdc->dflags |= DFEntryMod;
3491 * Make a shadow copy of a dir's dcache. It's used for disconnected
3492 * operations like remove/create/rename to keep the original directory data.
3493 * On reconnection, we can diff the original data with the server and get the
3494 * server changes and with the local data to get the local changes.
3496 * \param avc The dir vnode.
3497 * \param adc The dir dcache.
3499 * \return 0 for success.
3501 * \note The vcache entry must be write locked.
3502 * \note The dcache entry must be read locked.
3505 afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3507 int i, code, ret_code = 0, written, trans_size;
3508 struct dcache *new_dc = NULL;
3509 struct osi_file *tfile_src, *tfile_dst;
3510 struct VenusFid shadow_fid;
3513 /* Is this a dir? */
3514 if (vType(avc) != VDIR)
3517 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3520 /* Generate a fid for the shadow dir. */
3521 shadow_fid.Cell = avc->f.fid.Cell;
3522 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3523 afs_GenShadowFid(&shadow_fid);
3525 ObtainWriteLock(&afs_xdcache, 716);
3527 /* Get a fresh dcache. */
3528 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3531 ObtainReadLock(&adc->mflock);
3533 /* Set up the new fid. */
3534 /* Copy interesting data from original dir dcache. */
3535 new_dc->mflags = adc->mflags;
3536 new_dc->dflags = adc->dflags;
3537 new_dc->f.modTime = adc->f.modTime;
3538 new_dc->f.versionNo = adc->f.versionNo;
3539 new_dc->f.states = adc->f.states;
3540 new_dc->f.chunk= adc->f.chunk;
3541 new_dc->f.chunkBytes = adc->f.chunkBytes;
3543 ReleaseReadLock(&adc->mflock);
3545 /* Now add to the two hash chains */
3546 i = DCHash(&shadow_fid, 0);
3547 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[i];
3548 afs_dchashTbl[i] = new_dc->index;
3550 i = DVHash(&shadow_fid);
3551 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[i];
3552 afs_dvhashTbl[i] = new_dc->index;
3554 ReleaseWriteLock(&afs_xdcache);
3556 /* Alloc a 4k block. */
3557 data = afs_osi_Alloc(4096);
3559 afs_warn("afs_MakeShadowDir: could not alloc data\n");
3564 /* Open the files. */
3565 tfile_src = afs_CFileOpen(&adc->f.inode);
3566 tfile_dst = afs_CFileOpen(&new_dc->f.inode);
3568 /* And now copy dir dcache data into this dcache,
3572 while (written < adc->f.chunkBytes) {
3573 trans_size = adc->f.chunkBytes - written;
3574 if (trans_size > 4096)
3577 /* Read a chunk from the dcache. */
3578 code = afs_CFileRead(tfile_src, written, data, trans_size);
3579 if (code < trans_size) {
3584 /* Write it to the new dcache. */
3585 code = afs_CFileWrite(tfile_dst, written, data, trans_size);
3586 if (code < trans_size) {
3591 written+=trans_size;
3594 afs_CFileClose(tfile_dst);
3595 afs_CFileClose(tfile_src);
3597 afs_osi_Free(data, 4096);
3599 ReleaseWriteLock(&new_dc->lock);
3600 afs_PutDCache(new_dc);
3603 ObtainWriteLock(&afs_xvcache, 763);
3604 ObtainWriteLock(&afs_disconDirtyLock, 765);
3605 QAdd(&afs_disconShadow, &avc->shadowq);
3606 osi_Assert((afs_RefVCache(avc) == 0));
3607 ReleaseWriteLock(&afs_disconDirtyLock);
3608 ReleaseWriteLock(&afs_xvcache);
3610 avc->f.shadow.vnode = shadow_fid.Fid.Vnode;
3611 avc->f.shadow.unique = shadow_fid.Fid.Unique;
3619 * Delete the dcaches of a shadow dir.
3621 * \param avc The vcache containing the shadow fid.
3623 * \note avc must be write locked.
3626 afs_DeleteShadowDir(struct vcache *avc)
3629 struct VenusFid shadow_fid;
3631 shadow_fid.Cell = avc->f.fid.Cell;
3632 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3633 shadow_fid.Fid.Vnode = avc->f.shadow.vnode;
3634 shadow_fid.Fid.Unique = avc->f.shadow.unique;
3636 tdc = afs_FindDCacheByFid(&shadow_fid);
3638 afs_HashOutDCache(tdc, 1);
3639 afs_DiscardDCache(tdc);
3642 avc->f.shadow.vnode = avc->f.shadow.unique = 0;
3643 ObtainWriteLock(&afs_disconDirtyLock, 708);
3644 QRemove(&avc->shadowq);
3645 ReleaseWriteLock(&afs_disconDirtyLock);
3646 afs_PutVCache(avc); /* Because we held it when we added to the queue */
3650 * Populate a dcache with empty chunks up to a given file size,
3651 * used before extending a file in order to avoid 'holes' which
3652 * we can't access in disconnected mode.
3654 * \param avc The vcache which is being extended (locked)
3655 * \param alen The new length of the file
3659 afs_PopulateDCache(struct vcache *avc, afs_size_t apos, struct vrequest *areq)
3662 afs_size_t len, offset;
3663 afs_int32 start, end;
3665 /* We're doing this to deal with the situation where we extend
3666 * by writing after lseek()ing past the end of the file . If that
3667 * extension skips chunks, then those chunks won't be created, and
3668 * GetDCache will assume that they have to be fetched from the server.
3669 * So, for each chunk between the current file position, and the new
3670 * length we GetDCache for that chunk.
3673 if (AFS_CHUNK(apos) == 0 || apos <= avc->f.m.Length)
3676 if (avc->f.m.Length == 0)
3679 start = AFS_CHUNK(avc->f.m.Length)+1;
3681 end = AFS_CHUNK(apos);
3684 len = AFS_CHUNKTOSIZE(start);
3685 tdc = afs_GetDCache(avc, AFS_CHUNKTOBASE(start), areq, &offset, &len, 4);