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 * Keeps the cache clean and free by truncating uneeded files, when used.
404 afs_CacheTruncateDaemon(void)
406 osi_timeval_t CTD_tmpTime;
410 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
412 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
414 osi_GetuTime(&CTD_stats.CTD_afterSleep);
415 afs_TruncateDaemonRunning = 1;
417 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
418 ObtainWriteLock(&afs_xdcache, 266);
419 if (afs_CacheTooFull) {
420 int space_needed, slots_needed;
421 /* if we get woken up, we should try to clean something out */
422 for (counter = 0; counter < 10; counter++) {
424 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
425 if (space_needed < 0)
428 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
429 if (slots_needed < 0)
431 if (slots_needed || space_needed)
432 afs_GetDownD(slots_needed, &space_needed, 0);
433 if ((space_needed <= 0) && (slots_needed <= 0)) {
434 afs_CacheTooFull = 0;
437 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
440 if (!afs_CacheIsTooFull())
441 afs_CacheTooFull = 0;
442 } /* end of cache cleanup */
443 ReleaseWriteLock(&afs_xdcache);
446 * This is a defensive check to try to avoid starving threads
447 * that may need the global lock so thay can help free some
448 * cache space. If this thread won't be sleeping or truncating
449 * any cache files then give up the global lock so other
450 * threads get a chance to run.
452 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
453 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
454 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
458 * This is where we free the discarded cache elements.
460 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
461 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
462 int code = afs_FreeDiscardedDCache();
464 /* If we can't free any discarded dcache entries, that's okay.
465 * We're just doing this in the background; if someone needs
466 * discarded entries freed, they will try it themselves and/or
467 * signal us that the cache is too full. In any case, we'll
468 * try doing this again the next time we run through the loop.
474 /* See if we need to continue to run. Someone may have
475 * signalled us while we were executing.
477 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
478 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
479 /* Collect statistics on truncate daemon. */
480 CTD_stats.CTD_nSleeps++;
481 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
482 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
483 CTD_stats.CTD_beforeSleep);
484 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
486 afs_TruncateDaemonRunning = 0;
487 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
488 afs_TruncateDaemonRunning = 1;
490 osi_GetuTime(&CTD_stats.CTD_afterSleep);
491 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
492 CTD_stats.CTD_afterSleep);
493 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
495 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
496 afs_termState = AFSOP_STOP_AFSDB;
497 afs_osi_Wakeup(&afs_termState);
505 * Make adjustment for the new size in the disk cache entry
507 * \note Major Assumptions Here:
508 * Assumes that frag size is an integral power of two, less one,
509 * and that this is a two's complement machine. I don't
510 * know of any filesystems which violate this assumption...
512 * \param adc Ptr to dcache entry.
513 * \param anewsize New size desired.
518 afs_AdjustSize(struct dcache *adc, afs_int32 newSize)
522 AFS_STATCNT(afs_AdjustSize);
524 adc->dflags |= DFEntryMod;
525 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
526 adc->f.chunkBytes = newSize;
529 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
530 afs_DCAdjustSize(adc, oldSize, newSize);
531 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
533 /* We're growing the file, wakeup the daemon */
534 afs_MaybeWakeupTruncateDaemon();
536 afs_blocksUsed += (newSize - oldSize);
537 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
542 * This routine is responsible for moving at least one entry (but up
543 * to some number of them) from the LRU queue to the free queue.
545 * \param anumber Number of entries that should ideally be moved.
546 * \param aneedSpace How much space we need (1K blocks);
549 * The anumber parameter is just a hint; at least one entry MUST be
550 * moved, or we'll panic. We must be called with afs_xdcache
551 * write-locked. We should try to satisfy both anumber and aneedspace,
552 * whichever is more demanding - need to do several things:
553 * 1. only grab up to anumber victims if aneedSpace <= 0, not
554 * the whole set of MAXATONCE.
555 * 2. dynamically choose MAXATONCE to reflect severity of
556 * demand: something like (*aneedSpace >> (logChunk - 9))
558 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
559 * indicates that the cache is not properly configured/tuned or
560 * something. We should be able to automatically correct that problem.
563 #define MAXATONCE 16 /* max we can obtain at once */
565 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
569 struct VenusFid *afid;
574 afs_uint32 victims[MAXATONCE];
575 struct dcache *victimDCs[MAXATONCE];
576 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
577 afs_uint32 victimPtr; /* next free item in victim arrays */
578 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
579 afs_uint32 maxVictimPtr; /* where it is */
583 AFS_STATCNT(afs_GetDownD);
585 if (CheckLock(&afs_xdcache) != -1)
586 osi_Panic("getdownd nolock");
587 /* decrement anumber first for all dudes in free list */
588 /* SHOULD always decrement anumber first, even if aneedSpace >0,
589 * because we should try to free space even if anumber <=0 */
590 if (!aneedSpace || *aneedSpace <= 0) {
591 anumber -= afs_freeDCCount;
593 return; /* enough already free */
597 /* bounds check parameter */
598 if (anumber > MAXATONCE)
599 anumber = MAXATONCE; /* all we can do */
601 /* rewrite so phases include a better eligiblity for gc test*/
603 * The phase variable manages reclaims. Set to 0, the first pass,
604 * we don't reclaim active entries, or other than target bucket.
605 * Set to 1, we reclaim even active ones in target bucket.
606 * Set to 2, we reclaim any inactive one.
607 * Set to 3, we reclaim even active ones. On Solaris, we also reclaim
608 * entries whose corresponding vcache has a nonempty multiPage list, when
617 for (i = 0; i < afs_cacheFiles; i++)
618 /* turn off all flags */
619 afs_indexFlags[i] &= ~IFFlag;
621 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
622 /* find oldest entries for reclamation */
623 maxVictimPtr = victimPtr = 0;
624 hzero(maxVictimTime);
625 curbucket = afs_DCWhichBucket(phase, buckethint);
626 /* select victims from access time array */
627 for (i = 0; i < afs_cacheFiles; i++) {
628 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
629 /* skip if dirty or already free */
632 tdc = afs_indexTable[i];
633 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
635 /* Wrong bucket; can't use it! */
638 if (tdc && (tdc->refCount != 0)) {
639 /* Referenced; can't use it! */
642 hset(vtime, afs_indexTimes[i]);
644 /* if we've already looked at this one, skip it */
645 if (afs_indexFlags[i] & IFFlag)
648 if (victimPtr < MAXATONCE) {
649 /* if there's at least one free victim slot left */
650 victims[victimPtr] = i;
651 hset(victimTimes[victimPtr], vtime);
652 if (hcmp(vtime, maxVictimTime) > 0) {
653 hset(maxVictimTime, vtime);
654 maxVictimPtr = victimPtr;
657 } else if (hcmp(vtime, maxVictimTime) < 0) {
659 * We're older than youngest victim, so we replace at
662 /* find youngest (largest LRU) victim */
665 osi_Panic("getdownd local");
667 hset(victimTimes[j], vtime);
668 /* recompute maxVictimTime */
669 hset(maxVictimTime, vtime);
670 for (j = 0; j < victimPtr; j++)
671 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
672 hset(maxVictimTime, victimTimes[j]);
678 /* now really reclaim the victims */
679 j = 0; /* flag to track if we actually got any of the victims */
680 /* first, hold all the victims, since we're going to release the lock
681 * during the truncate operation.
683 for (i = 0; i < victimPtr; i++) {
684 tdc = afs_GetValidDSlot(victims[i]);
685 /* We got tdc->tlock(R) here */
686 if (tdc && tdc->refCount == 1)
691 ReleaseReadLock(&tdc->tlock);
696 for (i = 0; i < victimPtr; i++) {
697 /* q is first elt in dcache entry */
699 /* now, since we're dropping the afs_xdcache lock below, we
700 * have to verify, before proceeding, that there are no other
701 * references to this dcache entry, even now. Note that we
702 * compare with 1, since we bumped it above when we called
703 * afs_GetValidDSlot to preserve the entry's identity.
705 if (tdc && tdc->refCount == 1) {
706 unsigned char chunkFlags;
707 afs_size_t tchunkoffset = 0;
709 /* xdcache is lower than the xvcache lock */
710 ReleaseWriteLock(&afs_xdcache);
711 ObtainReadLock(&afs_xvcache);
712 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
713 ReleaseReadLock(&afs_xvcache);
714 ObtainWriteLock(&afs_xdcache, 527);
716 if (tdc->refCount > 1)
719 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
720 chunkFlags = afs_indexFlags[tdc->index];
721 if (((phase & 1) == 0) && osi_Active(tvc))
723 if (((phase & 1) == 1) && osi_Active(tvc)
724 && (tvc->f.states & CDCLock)
725 && (chunkFlags & IFAnyPages))
727 if (chunkFlags & IFDataMod)
729 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
730 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
731 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
732 ICL_HANDLE_OFFSET(tchunkoffset));
734 #if defined(AFS_SUN5_ENV)
736 * Now we try to invalidate pages. We do this only for
737 * Solaris. For other platforms, it's OK to recycle a
738 * dcache entry out from under a page, because the strategy
739 * function can call afs_GetDCache().
741 if (!skip && (chunkFlags & IFAnyPages)) {
744 ReleaseWriteLock(&afs_xdcache);
745 ObtainWriteLock(&tvc->vlock, 543);
746 if (!QEmpty(&tvc->multiPage)) {
747 if (phase < 3 || osi_VM_MultiPageConflict(tvc, tdc)) {
752 /* block locking pages */
753 tvc->vstates |= VPageCleaning;
754 /* block getting new pages */
756 ReleaseWriteLock(&tvc->vlock);
757 /* One last recheck */
758 ObtainWriteLock(&afs_xdcache, 333);
759 chunkFlags = afs_indexFlags[tdc->index];
760 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
761 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
762 && (chunkFlags & IFAnyPages))) {
764 ReleaseWriteLock(&afs_xdcache);
767 ReleaseWriteLock(&afs_xdcache);
769 code = osi_VM_GetDownD(tvc, tdc);
771 ObtainWriteLock(&afs_xdcache, 269);
772 /* we actually removed all pages, clean and dirty */
774 afs_indexFlags[tdc->index] &=
775 ~(IFDirtyPages | IFAnyPages);
778 ReleaseWriteLock(&afs_xdcache);
780 ObtainWriteLock(&tvc->vlock, 544);
781 if (--tvc->activeV == 0
782 && (tvc->vstates & VRevokeWait)) {
783 tvc->vstates &= ~VRevokeWait;
784 afs_osi_Wakeup((char *)&tvc->vstates);
787 if (tvc->vstates & VPageCleaning) {
788 tvc->vstates &= ~VPageCleaning;
789 afs_osi_Wakeup((char *)&tvc->vstates);
792 ReleaseWriteLock(&tvc->vlock);
794 #endif /* AFS_SUN5_ENV */
796 ReleaseWriteLock(&afs_xdcache);
799 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
800 ObtainWriteLock(&afs_xdcache, 528);
801 if (afs_indexFlags[tdc->index] &
802 (IFDataMod | IFDirtyPages | IFAnyPages))
804 if (tdc->refCount > 1)
807 #if defined(AFS_SUN5_ENV)
809 /* no vnode, so IFDirtyPages is spurious (we don't
810 * sweep dcaches on vnode recycling, so we can have
811 * DIRTYPAGES set even when all pages are gone). Just
813 * Hold vcache lock to prevent vnode from being
814 * created while we're clearing IFDirtyPages.
816 afs_indexFlags[tdc->index] &=
817 ~(IFDirtyPages | IFAnyPages);
821 /* skip this guy and mark him as recently used */
822 afs_indexFlags[tdc->index] |= IFFlag;
823 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
824 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
825 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
826 ICL_HANDLE_OFFSET(tchunkoffset));
828 /* flush this dude from the data cache and reclaim;
829 * first, make sure no one will care that we damage
830 * it, by removing it from all hash tables. Then,
831 * melt it down for parts. Note that any concurrent
832 * (new possibility!) calls to GetDownD won't touch
833 * this guy because his reference count is > 0. */
834 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
835 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
836 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
837 ICL_HANDLE_OFFSET(tchunkoffset));
838 AFS_STATCNT(afs_gget);
839 afs_HashOutDCache(tdc, 1);
840 if (tdc->f.chunkBytes != 0) {
844 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
849 afs_DiscardDCache(tdc);
854 j = 1; /* we reclaimed at least one victim */
859 } /* end of for victims loop */
862 /* Phase is 0 and no one was found, so try phase 1 (ignore
863 * osi_Active flag) */
866 for (i = 0; i < afs_cacheFiles; i++)
867 /* turn off all flags */
868 afs_indexFlags[i] &= ~IFFlag;
871 /* found no one in phases 0-5, we're hosed */
875 } /* big while loop */
883 * Remove adc from any hash tables that would allow it to be located
884 * again by afs_FindDCache or afs_GetDCache.
886 * \param adc Pointer to dcache entry to remove from hash tables.
888 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
892 afs_HashOutDCache(struct dcache *adc, int zap)
896 AFS_STATCNT(afs_glink);
898 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
900 /* if this guy is in the hash table, pull him out */
901 if (adc->f.fid.Fid.Volume != 0) {
902 /* remove entry from first hash chains */
903 i = DCHash(&adc->f.fid, adc->f.chunk);
904 us = afs_dchashTbl[i];
905 if (us == adc->index) {
906 /* first dude in the list */
907 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
909 /* somewhere on the chain */
910 while (us != NULLIDX) {
911 if (afs_dcnextTbl[us] == adc->index) {
912 /* found item pointing at the one to delete */
913 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
916 us = afs_dcnextTbl[us];
919 osi_Panic("dcache hc");
921 /* remove entry from *other* hash chain */
922 i = DVHash(&adc->f.fid);
923 us = afs_dvhashTbl[i];
924 if (us == adc->index) {
925 /* first dude in the list */
926 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
928 /* somewhere on the chain */
929 while (us != NULLIDX) {
930 if (afs_dvnextTbl[us] == adc->index) {
931 /* found item pointing at the one to delete */
932 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
935 us = afs_dvnextTbl[us];
938 osi_Panic("dcache hv");
943 /* prevent entry from being found on a reboot (it is already out of
944 * the hash table, but after a crash, we just look at fid fields of
945 * stable (old) entries).
947 adc->f.fid.Fid.Volume = 0; /* invalid */
949 /* mark entry as modified */
950 adc->dflags |= DFEntryMod;
955 } /*afs_HashOutDCache */
958 * Flush the given dcache entry, pulling it from hash chains
959 * and truncating the associated cache file.
961 * \param adc Ptr to dcache entry to flush.
964 * This routine must be called with the afs_xdcache lock held
968 afs_FlushDCache(struct dcache *adc)
970 AFS_STATCNT(afs_FlushDCache);
972 * Bump the number of cache files flushed.
974 afs_stats_cmperf.cacheFlushes++;
976 /* remove from all hash tables */
977 afs_HashOutDCache(adc, 1);
979 /* Free its space; special case null operation, since truncate operation
980 * in UFS is slow even in this case, and this allows us to pre-truncate
981 * these files at more convenient times with fewer locks set
982 * (see afs_GetDownD).
984 if (adc->f.chunkBytes != 0) {
985 afs_DiscardDCache(adc);
986 afs_MaybeWakeupTruncateDaemon();
991 if (afs_WaitForCacheDrain) {
992 if (afs_blocksUsed <=
993 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
994 afs_WaitForCacheDrain = 0;
995 afs_osi_Wakeup(&afs_WaitForCacheDrain);
998 } /*afs_FlushDCache */
1002 * Put a dcache entry on the free dcache entry list.
1004 * \param adc dcache entry to free.
1006 * \note Environment: called with afs_xdcache lock write-locked.
1009 afs_FreeDCache(struct dcache *adc)
1011 /* Thread on free list, update free list count and mark entry as
1012 * freed in its indexFlags element. Also, ensure DCache entry gets
1013 * written out (set DFEntryMod).
1016 afs_dvnextTbl[adc->index] = afs_freeDCList;
1017 afs_freeDCList = adc->index;
1019 afs_indexFlags[adc->index] |= IFFree;
1020 adc->dflags |= DFEntryMod;
1022 if (afs_WaitForCacheDrain) {
1023 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1024 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1025 afs_WaitForCacheDrain = 0;
1026 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1029 } /* afs_FreeDCache */
1032 * Discard the cache element by moving it to the discardDCList.
1033 * This puts the cache element into a quasi-freed state, where
1034 * the space may be reused, but the file has not been truncated.
1036 * \note Major Assumptions Here:
1037 * Assumes that frag size is an integral power of two, less one,
1038 * and that this is a two's complement machine. I don't
1039 * know of any filesystems which violate this assumption...
1041 * \param adr Ptr to dcache entry.
1043 * \note Environment:
1044 * Must be called with afs_xdcache write-locked.
1048 afs_DiscardDCache(struct dcache *adc)
1052 AFS_STATCNT(afs_DiscardDCache);
1054 osi_Assert(adc->refCount == 1);
1056 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1057 afs_blocksDiscarded += size;
1058 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1060 afs_dvnextTbl[adc->index] = afs_discardDCList;
1061 afs_discardDCList = adc->index;
1062 afs_discardDCCount++;
1064 adc->f.fid.Fid.Volume = 0;
1065 adc->dflags |= DFEntryMod;
1066 afs_indexFlags[adc->index] |= IFDiscarded;
1068 if (afs_WaitForCacheDrain) {
1069 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1070 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1071 afs_WaitForCacheDrain = 0;
1072 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1076 } /*afs_DiscardDCache */
1079 * Get a dcache entry from the discard or free list
1081 * @param[in] indexp A pointer to the head of the dcache free list or discard
1082 * list (afs_freeDCList, or afs_discardDCList)
1084 * @return A dcache from that list, or NULL if none could be retrieved.
1086 * @pre afs_xdcache is write-locked
1088 static struct dcache *
1089 afs_GetDSlotFromList(afs_int32 *indexp)
1093 for ( ; *indexp != NULLIDX; indexp = &afs_dvnextTbl[*indexp]) {
1094 tdc = afs_GetUnusedDSlot(*indexp);
1096 osi_Assert(tdc->refCount == 1);
1097 ReleaseReadLock(&tdc->tlock);
1098 *indexp = afs_dvnextTbl[tdc->index];
1099 afs_dvnextTbl[tdc->index] = NULLIDX;
1107 * Free the next element on the list of discarded cache elements.
1109 * Returns -1 if we encountered an error preventing us from freeing a
1110 * discarded dcache, or 0 on success.
1113 afs_FreeDiscardedDCache(void)
1116 struct osi_file *tfile;
1119 AFS_STATCNT(afs_FreeDiscardedDCache);
1121 ObtainWriteLock(&afs_xdcache, 510);
1122 if (!afs_blocksDiscarded) {
1123 ReleaseWriteLock(&afs_xdcache);
1128 * Get an entry from the list of discarded cache elements
1130 tdc = afs_GetDSlotFromList(&afs_discardDCList);
1132 ReleaseWriteLock(&afs_xdcache);
1136 afs_discardDCCount--;
1137 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1138 afs_blocksDiscarded -= size;
1139 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1140 /* We can lock because we just took it off the free list */
1141 ObtainWriteLock(&tdc->lock, 626);
1142 ReleaseWriteLock(&afs_xdcache);
1145 * Truncate the element to reclaim its space
1147 tfile = afs_CFileOpen(&tdc->f.inode);
1148 afs_CFileTruncate(tfile, 0);
1149 afs_CFileClose(tfile);
1150 afs_AdjustSize(tdc, 0);
1151 afs_DCMoveBucket(tdc, 0, 0);
1154 * Free the element we just truncated
1156 ObtainWriteLock(&afs_xdcache, 511);
1157 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1158 afs_FreeDCache(tdc);
1159 tdc->f.states &= ~(DRO|DBackup|DRW);
1160 ReleaseWriteLock(&tdc->lock);
1162 ReleaseWriteLock(&afs_xdcache);
1168 * Free as many entries from the list of discarded cache elements
1169 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1174 afs_MaybeFreeDiscardedDCache(void)
1177 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1179 while (afs_blocksDiscarded
1180 && (afs_blocksUsed >
1181 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1182 int code = afs_FreeDiscardedDCache();
1184 /* Callers depend on us to get the afs_blocksDiscarded count down.
1185 * If we cannot do that, the callers can spin by calling us over
1186 * and over. Panic for now until we can figure out something
1188 osi_Panic("Error freeing discarded dcache");
1195 * Try to free up a certain number of disk slots.
1197 * \param anumber Targeted number of disk slots to free up.
1199 * \note Environment:
1200 * Must be called with afs_xdcache write-locked.
1204 afs_GetDownDSlot(int anumber)
1206 struct afs_q *tq, *nq;
1211 AFS_STATCNT(afs_GetDownDSlot);
1212 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1213 osi_Panic("diskless getdowndslot");
1215 if (CheckLock(&afs_xdcache) != -1)
1216 osi_Panic("getdowndslot nolock");
1218 /* decrement anumber first for all dudes in free list */
1219 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1222 return; /* enough already free */
1224 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1226 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1227 nq = QPrev(tq); /* in case we remove it */
1228 if (tdc->refCount == 0) {
1229 if ((ix = tdc->index) == NULLIDX)
1230 osi_Panic("getdowndslot");
1231 /* pull the entry out of the lruq and put it on the free list */
1232 QRemove(&tdc->lruq);
1234 /* write-through if modified */
1235 if (tdc->dflags & DFEntryMod) {
1236 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1238 * ask proxy to do this for us - we don't have the stack space
1240 while (tdc->dflags & DFEntryMod) {
1243 s = SPLOCK(afs_sgibklock);
1244 if (afs_sgibklist == NULL) {
1245 /* if slot is free, grab it. */
1246 afs_sgibklist = tdc;
1247 SV_SIGNAL(&afs_sgibksync);
1249 /* wait for daemon to (start, then) finish. */
1250 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1254 tdc->dflags &= ~DFEntryMod;
1255 osi_Assert(afs_WriteDCache(tdc, 1) == 0);
1259 /* finally put the entry in the free list */
1260 afs_indexTable[ix] = NULL;
1261 afs_indexFlags[ix] &= ~IFEverUsed;
1262 tdc->index = NULLIDX;
1263 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1264 afs_freeDSList = tdc;
1268 } /*afs_GetDownDSlot */
1275 * Increment the reference count on a disk cache entry,
1276 * which already has a non-zero refcount. In order to
1277 * increment the refcount of a zero-reference entry, you
1278 * have to hold afs_xdcache.
1281 * adc : Pointer to the dcache entry to increment.
1284 * Nothing interesting.
1287 afs_RefDCache(struct dcache *adc)
1289 ObtainWriteLock(&adc->tlock, 627);
1290 if (adc->refCount < 0)
1291 osi_Panic("RefDCache: negative refcount");
1293 ReleaseWriteLock(&adc->tlock);
1302 * Decrement the reference count on a disk cache entry.
1305 * ad : Ptr to the dcache entry to decrement.
1308 * Nothing interesting.
1311 afs_PutDCache(struct dcache *adc)
1313 AFS_STATCNT(afs_PutDCache);
1314 ObtainWriteLock(&adc->tlock, 276);
1315 if (adc->refCount <= 0)
1316 osi_Panic("putdcache");
1318 ReleaseWriteLock(&adc->tlock);
1327 * Try to discard all data associated with this file from the
1331 * avc : Pointer to the cache info for the file.
1334 * Both pvnLock and lock are write held.
1337 afs_TryToSmush(struct vcache *avc, afs_ucred_t *acred, int sync)
1342 AFS_STATCNT(afs_TryToSmush);
1343 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1344 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1345 sync = 1; /* XX Temp testing XX */
1347 #if defined(AFS_SUN5_ENV)
1348 ObtainWriteLock(&avc->vlock, 573);
1349 avc->activeV++; /* block new getpages */
1350 ReleaseWriteLock(&avc->vlock);
1353 /* Flush VM pages */
1354 osi_VM_TryToSmush(avc, acred, sync);
1357 * Get the hash chain containing all dce's for this fid
1359 i = DVHash(&avc->f.fid);
1360 ObtainWriteLock(&afs_xdcache, 277);
1361 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1362 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1363 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1364 int releaseTlock = 1;
1365 tdc = afs_GetValidDSlot(index);
1367 /* afs_TryToSmush is best-effort; we may not actually discard
1368 * everything, so failure to discard a dcache due to an i/o
1372 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1374 if ((afs_indexFlags[index] & IFDataMod) == 0
1375 && tdc->refCount == 1) {
1376 ReleaseReadLock(&tdc->tlock);
1378 afs_FlushDCache(tdc);
1381 afs_indexTable[index] = 0;
1384 ReleaseReadLock(&tdc->tlock);
1388 #if defined(AFS_SUN5_ENV)
1389 ObtainWriteLock(&avc->vlock, 545);
1390 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1391 avc->vstates &= ~VRevokeWait;
1392 afs_osi_Wakeup((char *)&avc->vstates);
1394 ReleaseWriteLock(&avc->vlock);
1396 ReleaseWriteLock(&afs_xdcache);
1398 * It's treated like a callback so that when we do lookups we'll
1399 * invalidate the unique bit if any
1400 * trytoSmush occured during the lookup call
1406 * afs_DCacheMissingChunks
1409 * Given the cached info for a file, return the number of chunks that
1410 * are not available from the dcache.
1413 * avc: Pointer to the (held) vcache entry to look in.
1416 * The number of chunks which are not currently cached.
1419 * The vcache entry is held upon entry.
1423 afs_DCacheMissingChunks(struct vcache *avc)
1426 afs_size_t totalLength = 0;
1427 afs_uint32 totalChunks = 0;
1430 totalLength = avc->f.m.Length;
1431 if (avc->f.truncPos < totalLength)
1432 totalLength = avc->f.truncPos;
1434 /* Length is 0, no chunk missing. */
1435 if (totalLength == 0)
1438 /* If totalLength is a multiple of chunksize, the last byte appears
1439 * as being part of the next chunk, which does not exist.
1440 * Decrementing totalLength by one fixes that.
1443 totalChunks = (AFS_CHUNK(totalLength) + 1);
1445 /* If we're a directory, we only ever have one chunk, regardless of
1446 * the size of the dir.
1448 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1452 printf("Should have %d chunks for %u bytes\n",
1453 totalChunks, (totalLength + 1));
1455 i = DVHash(&avc->f.fid);
1456 ObtainWriteLock(&afs_xdcache, 1001);
1457 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1458 i = afs_dvnextTbl[index];
1459 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1460 tdc = afs_GetValidDSlot(index);
1462 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1465 ReleaseReadLock(&tdc->tlock);
1470 ReleaseWriteLock(&afs_xdcache);
1472 /*printf("Missing %d chunks\n", totalChunks);*/
1474 return (totalChunks);
1481 * Given the cached info for a file and a byte offset into the
1482 * file, make sure the dcache entry for that file and containing
1483 * the given byte is available, returning it to our caller.
1486 * avc : Pointer to the (held) vcache entry to look in.
1487 * abyte : Which byte we want to get to.
1490 * Pointer to the dcache entry covering the file & desired byte,
1491 * or NULL if not found.
1494 * The vcache entry is held upon entry.
1498 afs_FindDCache(struct vcache *avc, afs_size_t abyte)
1502 struct dcache *tdc = NULL;
1504 AFS_STATCNT(afs_FindDCache);
1505 chunk = AFS_CHUNK(abyte);
1508 * Hash on the [fid, chunk] and get the corresponding dcache index
1509 * after write-locking the dcache.
1511 i = DCHash(&avc->f.fid, chunk);
1512 ObtainWriteLock(&afs_xdcache, 278);
1513 for (index = afs_dchashTbl[i]; index != NULLIDX; index = afs_dcnextTbl[index]) {
1514 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1515 tdc = afs_GetValidDSlot(index);
1517 /* afs_FindDCache is best-effort; we may not find the given
1518 * file/offset, so if we cannot find the given dcache due to
1519 * i/o errors, that is okay. */
1522 ReleaseReadLock(&tdc->tlock);
1523 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1524 break; /* leaving refCount high for caller */
1529 if (index != NULLIDX) {
1530 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1531 hadd32(afs_indexCounter, 1);
1532 ReleaseWriteLock(&afs_xdcache);
1535 ReleaseWriteLock(&afs_xdcache);
1537 } /*afs_FindDCache */
1539 /* only call these from afs_AllocDCache() */
1540 static struct dcache *
1541 afs_AllocFreeDSlot(void)
1545 tdc = afs_GetDSlotFromList(&afs_freeDCList);
1549 afs_indexFlags[tdc->index] &= ~IFFree;
1550 ObtainWriteLock(&tdc->lock, 604);
1555 static struct dcache *
1556 afs_AllocDiscardDSlot(afs_int32 lock)
1559 afs_uint32 size = 0;
1560 struct osi_file *file;
1562 tdc = afs_GetDSlotFromList(&afs_discardDCList);
1566 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1567 ObtainWriteLock(&tdc->lock, 605);
1568 afs_discardDCCount--;
1570 ((tdc->f.chunkBytes +
1571 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1572 tdc->f.states &= ~(DRO|DBackup|DRW);
1573 afs_DCMoveBucket(tdc, size, 0);
1574 afs_blocksDiscarded -= size;
1575 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1577 /* Truncate the chunk so zeroes get filled properly */
1578 file = afs_CFileOpen(&tdc->f.inode);
1579 afs_CFileTruncate(file, 0);
1580 afs_CFileClose(file);
1581 afs_AdjustSize(tdc, 0);
1588 * Get a fresh dcache from the free or discarded list.
1590 * \param avc Who's dcache is this going to be?
1591 * \param chunk The position where it will be placed in.
1592 * \param lock How are locks held.
1593 * \param ashFid If this dcache going to be used for a shadow dir,
1596 * \note Required locks:
1598 * - avc (R if (lock & 1) set and W otherwise)
1599 * \note It write locks the new dcache. The caller must unlock it.
1601 * \return The new dcache.
1604 afs_AllocDCache(struct vcache *avc, afs_int32 chunk, afs_int32 lock,
1605 struct VenusFid *ashFid)
1607 struct dcache *tdc = NULL;
1609 /* if (lock & 2), prefer 'free' dcaches; otherwise, prefer 'discard'
1610 * dcaches. In either case, try both if our first choice doesn't work. */
1612 tdc = afs_AllocFreeDSlot();
1614 tdc = afs_AllocDiscardDSlot(lock);
1617 tdc = afs_AllocDiscardDSlot(lock);
1619 tdc = afs_AllocFreeDSlot();
1628 * avc->lock(R) if setLocks
1629 * avc->lock(W) if !setLocks
1635 * Fill in the newly-allocated dcache record.
1637 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1639 /* Use shadow fid if provided. */
1640 tdc->f.fid = *ashFid;
1642 /* Use normal vcache's fid otherwise. */
1643 tdc->f.fid = avc->f.fid;
1644 if (avc->f.states & CRO)
1645 tdc->f.states = DRO;
1646 else if (avc->f.states & CBackup)
1647 tdc->f.states = DBackup;
1649 tdc->f.states = DRW;
1650 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1651 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1653 hones(tdc->f.versionNo); /* invalid value */
1654 tdc->f.chunk = chunk;
1655 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1657 if (tdc->lruq.prev == &tdc->lruq)
1658 osi_Panic("lruq 1");
1667 * This function is called to obtain a reference to data stored in
1668 * the disk cache, locating a chunk of data containing the desired
1669 * byte and returning a reference to the disk cache entry, with its
1670 * reference count incremented.
1674 * avc : Ptr to a vcache entry (unlocked)
1675 * abyte : Byte position in the file desired
1676 * areq : Request structure identifying the requesting user.
1677 * aflags : Settings as follows:
1679 * 2 : Return after creating entry.
1680 * 4 : called from afs_vnop_write.c
1681 * *alen contains length of data to be written.
1683 * aoffset : Set to the offset within the chunk where the resident
1685 * alen : Set to the number of bytes of data after the desired
1686 * byte (including the byte itself) which can be read
1690 * The vcache entry pointed to by avc is unlocked upon entry.
1694 * Update the vnode-to-dcache hint if we can get the vnode lock
1695 * right away. Assumes dcache entry is at least read-locked.
1698 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1700 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1701 if (hsame(v->f.m.DataVersion, d->f.versionNo) && v->callback)
1704 ReleaseWriteLock(&v->lock);
1708 /* avc - Write-locked unless aflags & 1 */
1710 afs_GetDCache(struct vcache *avc, afs_size_t abyte,
1711 struct vrequest *areq, afs_size_t * aoffset,
1712 afs_size_t * alen, int aflags)
1714 afs_int32 i, code, shortcut;
1715 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1716 afs_int32 adjustsize = 0;
1722 afs_size_t Position = 0;
1723 afs_int32 size, tlen; /* size of segment to transfer */
1724 struct afs_FetchOutput *tsmall = 0;
1726 struct osi_file *file;
1727 struct afs_conn *tc;
1729 struct server *newCallback = NULL;
1730 char setNewCallback;
1731 char setVcacheStatus;
1732 char doVcacheUpdate;
1734 int doAdjustSize = 0;
1735 int doReallyAdjustSize = 0;
1736 int overWriteWholeChunk = 0;
1737 struct rx_connection *rxconn;
1740 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1741 int fromReplica; /*Are we reading from a replica? */
1742 int numFetchLoops; /*# times around the fetch/analyze loop */
1743 #endif /* AFS_NOSTATS */
1745 AFS_STATCNT(afs_GetDCache);
1749 setLocks = aflags & 1;
1752 * Determine the chunk number and offset within the chunk corresponding
1753 * to the desired byte.
1755 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1758 chunk = AFS_CHUNK(abyte);
1761 /* come back to here if we waited for the cache to drain. */
1764 setNewCallback = setVcacheStatus = 0;
1768 ObtainWriteLock(&avc->lock, 616);
1770 ObtainReadLock(&avc->lock);
1775 * avc->lock(R) if setLocks && !slowPass
1776 * avc->lock(W) if !setLocks || slowPass
1781 /* check hints first! (might could use bcmp or some such...) */
1782 if ((tdc = avc->dchint)) {
1786 * The locking order between afs_xdcache and dcache lock matters.
1787 * The hint dcache entry could be anywhere, even on the free list.
1788 * Locking afs_xdcache ensures that noone is trying to pull dcache
1789 * entries from the free list, and thereby assuming them to be not
1790 * referenced and not locked.
1792 ObtainReadLock(&afs_xdcache);
1793 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1795 if (dcLocked && (tdc->index != NULLIDX)
1796 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
1797 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1798 /* got the right one. It might not be the right version, and it
1799 * might be fetching, but it's the right dcache entry.
1801 /* All this code should be integrated better with what follows:
1802 * I can save a good bit more time under a write lock if I do..
1804 ObtainWriteLock(&tdc->tlock, 603);
1806 ReleaseWriteLock(&tdc->tlock);
1808 ReleaseReadLock(&afs_xdcache);
1811 if (hsame(tdc->f.versionNo, avc->f.m.DataVersion)
1812 && !(tdc->dflags & DFFetching)) {
1814 afs_stats_cmperf.dcacheHits++;
1815 ObtainWriteLock(&afs_xdcache, 559);
1816 QRemove(&tdc->lruq);
1817 QAdd(&afs_DLRU, &tdc->lruq);
1818 ReleaseWriteLock(&afs_xdcache);
1821 * avc->lock(R) if setLocks && !slowPass
1822 * avc->lock(W) if !setLocks || slowPass
1829 ReleaseSharedLock(&tdc->lock);
1830 ReleaseReadLock(&afs_xdcache);
1838 * avc->lock(R) if setLocks && !slowPass
1839 * avc->lock(W) if !setLocks || slowPass
1840 * tdc->lock(S) if tdc
1843 if (!tdc) { /* If the hint wasn't the right dcache entry */
1844 int dslot_error = 0;
1846 * Hash on the [fid, chunk] and get the corresponding dcache index
1847 * after write-locking the dcache.
1852 * avc->lock(R) if setLocks && !slowPass
1853 * avc->lock(W) if !setLocks || slowPass
1856 i = DCHash(&avc->f.fid, chunk);
1857 /* check to make sure our space is fine */
1858 afs_MaybeWakeupTruncateDaemon();
1860 ObtainWriteLock(&afs_xdcache, 280);
1862 for (index = afs_dchashTbl[i]; index != NULLIDX; us = index, index = afs_dcnextTbl[index]) {
1863 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1864 tdc = afs_GetValidDSlot(index);
1866 /* we got an i/o error when trying to get the given dslot,
1867 * but do not bail out just yet; it is possible the dcache
1868 * we're looking for is elsewhere, so it doesn't matter if
1869 * we can't load this one. */
1873 ReleaseReadLock(&tdc->tlock);
1876 * avc->lock(R) if setLocks && !slowPass
1877 * avc->lock(W) if !setLocks || slowPass
1880 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1881 /* Move it up in the beginning of the list */
1882 if (afs_dchashTbl[i] != index) {
1883 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1884 afs_dcnextTbl[index] = afs_dchashTbl[i];
1885 afs_dchashTbl[i] = index;
1887 ReleaseWriteLock(&afs_xdcache);
1888 ObtainSharedLock(&tdc->lock, 606);
1889 break; /* leaving refCount high for caller */
1897 * If we didn't find the entry, we'll create one.
1899 if (index == NULLIDX) {
1902 * avc->lock(R) if setLocks
1903 * avc->lock(W) if !setLocks
1906 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1907 avc, ICL_TYPE_INT32, chunk);
1910 /* We couldn't find the dcache we want, but we hit some i/o
1911 * errors when trying to find it, so we're not sure if the
1912 * dcache we want is in the cache or not. Error out, so we
1913 * don't try to possibly create 2 separate dcaches for the
1914 * same exact data. */
1915 ReleaseWriteLock(&afs_xdcache);
1919 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1921 avc->f.states |= CDCLock;
1922 /* just need slots */
1923 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1925 avc->f.states &= ~CDCLock;
1927 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
1929 /* If we can't get space for 5 mins we give up and panic */
1930 if (++downDCount > 300)
1931 osi_Panic("getdcache");
1932 ReleaseWriteLock(&afs_xdcache);
1935 * avc->lock(R) if setLocks
1936 * avc->lock(W) if !setLocks
1938 afs_osi_Wait(1000, 0, 0);
1944 * avc->lock(R) if setLocks
1945 * avc->lock(W) if !setLocks
1951 * Now add to the two hash chains - note that i is still set
1952 * from the above DCHash call.
1954 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1955 afs_dchashTbl[i] = tdc->index;
1956 i = DVHash(&avc->f.fid);
1957 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1958 afs_dvhashTbl[i] = tdc->index;
1959 tdc->dflags = DFEntryMod;
1961 afs_MaybeWakeupTruncateDaemon();
1962 ReleaseWriteLock(&afs_xdcache);
1963 ConvertWToSLock(&tdc->lock);
1968 /* vcache->dcache hint failed */
1971 * avc->lock(R) if setLocks && !slowPass
1972 * avc->lock(W) if !setLocks || slowPass
1975 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1976 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
1977 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
1978 hgetlo(avc->f.m.DataVersion));
1980 * Here we have the entry in tdc, with its refCount incremented.
1981 * Note: we don't use the S-lock on avc; it costs concurrency when
1982 * storing a file back to the server.
1986 * Not a newly created file so we need to check the file's length and
1987 * compare data versions since someone could have changed the data or we're
1988 * reading a file written elsewhere. We only want to bypass doing no-op
1989 * read rpcs on newly created files (dv of 0) since only then we guarantee
1990 * that this chunk's data hasn't been filled by another client.
1992 size = AFS_CHUNKSIZE(abyte);
1993 if (aflags & 4) /* called from write */
1995 else /* called from read */
1996 tlen = tdc->validPos - abyte;
1997 Position = AFS_CHUNKTOBASE(chunk);
1998 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
1999 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
2000 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
2001 ICL_HANDLE_OFFSET(Position));
2002 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
2004 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
2005 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
2006 overWriteWholeChunk = 1;
2007 if (doAdjustSize || overWriteWholeChunk) {
2008 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
2010 #ifdef AFS_SGI64_ENV
2013 #else /* AFS_SGI64_ENV */
2016 #endif /* AFS_SGI64_ENV */
2017 #else /* AFS_SGI_ENV */
2020 #endif /* AFS_SGI_ENV */
2021 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
2022 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2023 #if defined(AFS_SUN5_ENV)
2024 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
2026 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
2028 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2029 !hsame(avc->f.m.DataVersion, tdc->f.versionNo))
2030 doReallyAdjustSize = 1;
2032 if (doReallyAdjustSize || overWriteWholeChunk) {
2033 /* no data in file to read at this position */
2034 UpgradeSToWLock(&tdc->lock, 607);
2035 file = afs_CFileOpen(&tdc->f.inode);
2036 afs_CFileTruncate(file, 0);
2037 afs_CFileClose(file);
2038 afs_AdjustSize(tdc, 0);
2039 hset(tdc->f.versionNo, avc->f.m.DataVersion);
2040 tdc->dflags |= DFEntryMod;
2042 ConvertWToSLock(&tdc->lock);
2047 * We must read in the whole chunk if the version number doesn't
2051 /* don't need data, just a unique dcache entry */
2052 ObtainWriteLock(&afs_xdcache, 608);
2053 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2054 hadd32(afs_indexCounter, 1);
2055 ReleaseWriteLock(&afs_xdcache);
2057 updateV2DC(setLocks, avc, tdc, 553);
2058 if (vType(avc) == VDIR)
2061 *aoffset = AFS_CHUNKOFFSET(abyte);
2062 if (tdc->validPos < abyte)
2063 *alen = (afs_size_t) 0;
2065 *alen = tdc->validPos - abyte;
2066 ReleaseSharedLock(&tdc->lock);
2069 ReleaseWriteLock(&avc->lock);
2071 ReleaseReadLock(&avc->lock);
2073 return tdc; /* check if we're done */
2078 * avc->lock(R) if setLocks && !slowPass
2079 * avc->lock(W) if !setLocks || slowPass
2082 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
2084 setNewCallback = setVcacheStatus = 0;
2088 * avc->lock(R) if setLocks && !slowPass
2089 * avc->lock(W) if !setLocks || slowPass
2092 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
2094 * Version number mismatch.
2097 * If we are disconnected, then we can't do much of anything
2098 * because the data doesn't match the file.
2100 if (AFS_IS_DISCONNECTED) {
2101 ReleaseSharedLock(&tdc->lock);
2104 ReleaseWriteLock(&avc->lock);
2106 ReleaseReadLock(&avc->lock);
2108 /* Flush the Dcache */
2113 UpgradeSToWLock(&tdc->lock, 609);
2116 * If data ever existed for this vnode, and this is a text object,
2117 * do some clearing. Now, you'd think you need only do the flush
2118 * when VTEXT is on, but VTEXT is turned off when the text object
2119 * is freed, while pages are left lying around in memory marked
2120 * with this vnode. If we would reactivate (create a new text
2121 * object from) this vnode, we could easily stumble upon some of
2122 * these old pages in pagein. So, we always flush these guys.
2123 * Sun has a wonderful lack of useful invariants in this system.
2125 * avc->flushDV is the data version # of the file at the last text
2126 * flush. Clearly, at least, we don't have to flush the file more
2127 * often than it changes
2129 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2131 * By here, the cache entry is always write-locked. We can
2132 * deadlock if we call osi_Flush with the cache entry locked...
2133 * Unlock the dcache too.
2135 ReleaseWriteLock(&tdc->lock);
2136 if (setLocks && !slowPass)
2137 ReleaseReadLock(&avc->lock);
2139 ReleaseWriteLock(&avc->lock);
2143 * Call osi_FlushPages in open, read/write, and map, since it
2144 * is too hard here to figure out if we should lock the
2147 if (setLocks && !slowPass)
2148 ObtainReadLock(&avc->lock);
2150 ObtainWriteLock(&avc->lock, 66);
2151 ObtainWriteLock(&tdc->lock, 610);
2156 * avc->lock(R) if setLocks && !slowPass
2157 * avc->lock(W) if !setLocks || slowPass
2161 /* Watch for standard race condition around osi_FlushText */
2162 if (hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
2163 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2164 afs_stats_cmperf.dcacheHits++;
2165 ConvertWToSLock(&tdc->lock);
2169 /* Sleep here when cache needs to be drained. */
2170 if (setLocks && !slowPass
2171 && (afs_blocksUsed >
2172 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2173 /* Make sure truncate daemon is running */
2174 afs_MaybeWakeupTruncateDaemon();
2175 ObtainWriteLock(&tdc->tlock, 614);
2176 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2177 ReleaseWriteLock(&tdc->tlock);
2178 ReleaseWriteLock(&tdc->lock);
2179 ReleaseReadLock(&avc->lock);
2180 while ((afs_blocksUsed - afs_blocksDiscarded) >
2181 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2182 afs_WaitForCacheDrain = 1;
2183 afs_osi_Sleep(&afs_WaitForCacheDrain);
2185 afs_MaybeFreeDiscardedDCache();
2186 /* need to check if someone else got the chunk first. */
2187 goto RetryGetDCache;
2190 Position = AFS_CHUNKBASE(abyte);
2191 if (vType(avc) == VDIR) {
2192 size = avc->f.m.Length;
2193 if (size > tdc->f.chunkBytes) {
2194 /* pre-reserve space for file */
2195 afs_AdjustSize(tdc, size);
2197 size = 999999999; /* max size for transfer */
2199 afs_size_t maxGoodLength;
2201 /* estimate how much data we're expecting back from the server,
2202 * and reserve space in the dcache entry for it */
2204 maxGoodLength = avc->f.m.Length;
2205 if (avc->f.truncPos < maxGoodLength)
2206 maxGoodLength = avc->f.truncPos;
2208 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2209 if (Position + size > maxGoodLength)
2210 size = maxGoodLength - Position;
2212 size = 0; /* Handle random races */
2213 if (size > tdc->f.chunkBytes) {
2214 /* pre-reserve estimated space for file */
2215 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2219 /* For the actual fetch, do not limit the request to the
2220 * length of the file. If this results in a read past EOF on
2221 * the server, the server will just reply with less data than
2222 * requested. If we limit ourselves to only requesting data up
2223 * to the avc file length, we open ourselves up to races if the
2224 * file is extended on the server at about the same time.
2226 * However, we must restrict ourselves to the avc->f.truncPos
2227 * length, since this represents an outstanding local
2228 * truncation of the file that will be committed to the
2229 * fileserver when we actually write the fileserver contents.
2230 * If we do not restrict the fetch length based on
2231 * avc->f.truncPos, a different truncate operation extending
2232 * the file length could cause the old data after
2233 * avc->f.truncPos to reappear, instead of extending the file
2234 * with NUL bytes. */
2235 size = AFS_CHUNKSIZE(abyte);
2236 if (Position + size > avc->f.truncPos) {
2237 size = avc->f.truncPos - Position;
2244 if (afs_mariner && !tdc->f.chunk)
2245 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2247 * Right now, we only have one tool, and it's a hammer. So, we
2248 * fetch the whole file.
2250 DZap(tdc); /* pages in cache may be old */
2251 file = afs_CFileOpen(&tdc->f.inode);
2252 afs_RemoveVCB(&avc->f.fid);
2253 tdc->f.states |= DWriting;
2254 tdc->dflags |= DFFetching;
2255 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2256 if (tdc->mflags & DFFetchReq) {
2257 tdc->mflags &= ~DFFetchReq;
2258 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2259 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2260 __FILE__, ICL_TYPE_INT32, __LINE__,
2261 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2264 tsmall = osi_AllocLargeSpace(sizeof(struct afs_FetchOutput));
2265 setVcacheStatus = 0;
2268 * Remember if we are doing the reading from a replicated volume,
2269 * and how many times we've zipped around the fetch/analyze loop.
2271 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2273 accP = &(afs_stats_cmfullperf.accessinf);
2275 (accP->replicatedRefs)++;
2277 (accP->unreplicatedRefs)++;
2278 #endif /* AFS_NOSTATS */
2279 /* this is a cache miss */
2280 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2281 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2282 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2285 afs_stats_cmperf.dcacheMisses++;
2288 * Dynamic root support: fetch data from local memory.
2290 if (afs_IsDynroot(avc)) {
2294 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2296 dynrootDir += Position;
2297 dynrootLen -= Position;
2298 if (size > dynrootLen)
2302 code = afs_CFileWrite(file, 0, dynrootDir, size);
2310 tdc->validPos = Position + size;
2311 afs_CFileTruncate(file, size); /* prune it */
2312 } else if (afs_IsDynrootMount(avc)) {
2316 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2318 dynrootDir += Position;
2319 dynrootLen -= Position;
2320 if (size > dynrootLen)
2324 code = afs_CFileWrite(file, 0, dynrootDir, size);
2332 tdc->validPos = Position + size;
2333 afs_CFileTruncate(file, size); /* prune it */
2336 * Not a dynamic vnode: do the real fetch.
2341 * avc->lock(R) if setLocks && !slowPass
2342 * avc->lock(W) if !setLocks || slowPass
2346 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
2351 (accP->numReplicasAccessed)++;
2353 #endif /* AFS_NOSTATS */
2354 if (!setLocks || slowPass) {
2355 avc->callback = tc->parent->srvr->server;
2357 newCallback = tc->parent->srvr->server;
2361 code = afs_CacheFetchProc(tc, rxconn, file, Position, tdc,
2367 /* callback could have been broken (or expired) in a race here,
2368 * but we return the data anyway. It's as good as we knew about
2369 * when we started. */
2371 * validPos is updated by CacheFetchProc, and can only be
2372 * modifed under a dcache write lock, which we've blocked out
2374 size = tdc->validPos - Position; /* actual segment size */
2377 afs_CFileTruncate(file, size); /* prune it */
2379 if (!setLocks || slowPass) {
2380 ObtainWriteLock(&afs_xcbhash, 453);
2381 afs_DequeueCallback(avc);
2382 avc->f.states &= ~(CStatd | CUnique);
2383 avc->callback = NULL;
2384 ReleaseWriteLock(&afs_xcbhash);
2385 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2386 osi_dnlc_purgedp(avc);
2388 /* Something lost. Forget about performance, and go
2389 * back with a vcache write lock.
2391 afs_CFileTruncate(file, 0);
2392 afs_AdjustSize(tdc, 0);
2393 afs_CFileClose(file);
2394 osi_FreeLargeSpace(tsmall);
2396 ReleaseWriteLock(&tdc->lock);
2399 ReleaseReadLock(&avc->lock);
2401 goto RetryGetDCache;
2405 } while (afs_Analyze
2406 (tc, rxconn, code, &avc->f.fid, areq,
2407 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2411 * avc->lock(R) if setLocks && !slowPass
2412 * avc->lock(W) if !setLocks || slowPass
2418 * In the case of replicated access, jot down info on the number of
2419 * attempts it took before we got through or gave up.
2422 if (numFetchLoops <= 1)
2423 (accP->refFirstReplicaOK)++;
2424 if (numFetchLoops > accP->maxReplicasPerRef)
2425 accP->maxReplicasPerRef = numFetchLoops;
2427 #endif /* AFS_NOSTATS */
2429 tdc->dflags &= ~DFFetching;
2430 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2431 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2432 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2433 tdc, ICL_TYPE_INT32, tdc->dflags);
2434 if (avc->execsOrWriters == 0)
2435 tdc->f.states &= ~DWriting;
2437 /* now, if code != 0, we have an error and should punt.
2438 * note that we have the vcache write lock, either because
2439 * !setLocks or slowPass.
2442 afs_CFileTruncate(file, 0);
2443 afs_AdjustSize(tdc, 0);
2444 afs_CFileClose(file);
2445 ZapDCE(tdc); /* sets DFEntryMod */
2446 if (vType(avc) == VDIR) {
2449 tdc->f.states &= ~(DRO|DBackup|DRW);
2450 afs_DCMoveBucket(tdc, 0, 0);
2451 ReleaseWriteLock(&tdc->lock);
2453 if (!afs_IsDynroot(avc)) {
2454 ObtainWriteLock(&afs_xcbhash, 454);
2455 afs_DequeueCallback(avc);
2456 avc->f.states &= ~(CStatd | CUnique);
2457 ReleaseWriteLock(&afs_xcbhash);
2458 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2459 osi_dnlc_purgedp(avc);
2462 * avc->lock(W); assert(!setLocks || slowPass)
2464 osi_Assert(!setLocks || slowPass);
2470 /* otherwise we copy in the just-fetched info */
2471 afs_CFileClose(file);
2472 afs_AdjustSize(tdc, size); /* new size */
2474 * Copy appropriate fields into vcache. Status is
2475 * copied later where we selectively acquire the
2476 * vcache write lock.
2479 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2481 setVcacheStatus = 1;
2482 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2483 tsmall->OutStatus.DataVersion);
2484 tdc->dflags |= DFEntryMod;
2485 afs_indexFlags[tdc->index] |= IFEverUsed;
2486 ConvertWToSLock(&tdc->lock);
2487 } /*Data version numbers don't match */
2490 * Data version numbers match.
2492 afs_stats_cmperf.dcacheHits++;
2493 } /*Data version numbers match */
2495 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2499 * avc->lock(R) if setLocks && !slowPass
2500 * avc->lock(W) if !setLocks || slowPass
2501 * tdc->lock(S) if tdc
2505 * See if this was a reference to a file in the local cell.
2507 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2508 afs_stats_cmperf.dlocalAccesses++;
2510 afs_stats_cmperf.dremoteAccesses++;
2512 /* Fix up LRU info */
2515 ObtainWriteLock(&afs_xdcache, 602);
2516 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2517 hadd32(afs_indexCounter, 1);
2518 ReleaseWriteLock(&afs_xdcache);
2520 /* return the data */
2521 if (vType(avc) == VDIR)
2524 *aoffset = AFS_CHUNKOFFSET(abyte);
2525 *alen = (tdc->f.chunkBytes - *aoffset);
2526 ReleaseSharedLock(&tdc->lock);
2531 * avc->lock(R) if setLocks && !slowPass
2532 * avc->lock(W) if !setLocks || slowPass
2535 /* Fix up the callback and status values in the vcache */
2537 if (setLocks && !slowPass) {
2540 * This is our dirty little secret to parallel fetches.
2541 * We don't write-lock the vcache while doing the fetch,
2542 * but potentially we'll need to update the vcache after
2543 * the fetch is done.
2545 * Drop the read lock and try to re-obtain the write
2546 * lock. If the vcache still has the same DV, it's
2547 * ok to go ahead and install the new data.
2549 afs_hyper_t currentDV, statusDV;
2551 hset(currentDV, avc->f.m.DataVersion);
2553 if (setNewCallback && avc->callback != newCallback)
2557 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2558 tsmall->OutStatus.DataVersion);
2560 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2562 if (setVcacheStatus && !hsame(currentDV, statusDV))
2566 ReleaseReadLock(&avc->lock);
2568 if (doVcacheUpdate) {
2569 ObtainWriteLock(&avc->lock, 615);
2570 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2571 /* We lose. Someone will beat us to it. */
2573 ReleaseWriteLock(&avc->lock);
2578 /* With slow pass, we've already done all the updates */
2580 ReleaseWriteLock(&avc->lock);
2583 /* Check if we need to perform any last-minute fixes with a write-lock */
2584 if (!setLocks || doVcacheUpdate) {
2586 avc->callback = newCallback;
2587 if (tsmall && setVcacheStatus)
2588 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2590 ReleaseWriteLock(&avc->lock);
2594 osi_FreeLargeSpace(tsmall);
2597 } /*afs_GetDCache */
2601 * afs_WriteThroughDSlots
2604 * Sweep through the dcache slots and write out any modified
2605 * in-memory data back on to our caching store.
2611 * The afs_xdcache is write-locked through this whole affair.
2614 afs_WriteThroughDSlots(void)
2617 afs_int32 i, touchedit = 0;
2619 struct afs_q DirtyQ, *tq;
2621 AFS_STATCNT(afs_WriteThroughDSlots);
2624 * Because of lock ordering, we can't grab dcache locks while
2625 * holding afs_xdcache. So we enter xdcache, get a reference
2626 * for every dcache entry, and exit xdcache.
2628 ObtainWriteLock(&afs_xdcache, 283);
2630 for (i = 0; i < afs_cacheFiles; i++) {
2631 tdc = afs_indexTable[i];
2633 /* Grab tlock in case the existing refcount isn't zero */
2634 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2635 ObtainWriteLock(&tdc->tlock, 623);
2637 ReleaseWriteLock(&tdc->tlock);
2639 QAdd(&DirtyQ, &tdc->dirty);
2642 ReleaseWriteLock(&afs_xdcache);
2645 * Now, for each dcache entry we found, check if it's dirty.
2646 * If so, get write-lock, get afs_xdcache, which protects
2647 * afs_cacheInodep, and flush it. Don't forget to put back
2651 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2653 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2655 if (tdc->dflags & DFEntryMod) {
2658 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2660 /* Now that we have the write lock, double-check */
2661 if (wrLock && (tdc->dflags & DFEntryMod)) {
2662 tdc->dflags &= ~DFEntryMod;
2663 ObtainWriteLock(&afs_xdcache, 620);
2664 osi_Assert(afs_WriteDCache(tdc, 1) == 0);
2665 ReleaseWriteLock(&afs_xdcache);
2669 ReleaseWriteLock(&tdc->lock);
2675 ObtainWriteLock(&afs_xdcache, 617);
2676 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2677 /* Touch the file to make sure that the mtime on the file is kept
2678 * up-to-date to avoid losing cached files on cold starts because
2679 * their mtime seems old...
2681 struct afs_fheader theader;
2683 theader.magic = AFS_FHMAGIC;
2684 theader.firstCSize = AFS_FIRSTCSIZE;
2685 theader.otherCSize = AFS_OTHERCSIZE;
2686 theader.version = AFS_CI_VERSION;
2687 theader.dataSize = sizeof(struct fcache);
2688 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2690 ReleaseWriteLock(&afs_xdcache);
2697 * Return a pointer to an freshly initialized dcache entry using
2698 * a memory-based cache. The tlock will be read-locked.
2701 * aslot : Dcache slot to look at.
2702 * needvalid : Whether the specified slot should already exist
2705 * Must be called with afs_xdcache write-locked.
2709 afs_MemGetDSlot(afs_int32 aslot, int indexvalid, int datavalid)
2714 AFS_STATCNT(afs_MemGetDSlot);
2715 if (CheckLock(&afs_xdcache) != -1)
2716 osi_Panic("getdslot nolock");
2717 if (aslot < 0 || aslot >= afs_cacheFiles)
2718 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2719 tdc = afs_indexTable[aslot];
2721 QRemove(&tdc->lruq); /* move to queue head */
2722 QAdd(&afs_DLRU, &tdc->lruq);
2723 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2724 ObtainWriteLock(&tdc->tlock, 624);
2726 ConvertWToRLock(&tdc->tlock);
2730 /* if 'indexvalid' is true, the slot must already exist and be populated
2731 * somewhere. for memcache, the only place that dcache entries exist is
2732 * in memory, so if we did not find it above, something is very wrong. */
2733 osi_Assert(!indexvalid);
2735 if (!afs_freeDSList)
2736 afs_GetDownDSlot(4);
2737 if (!afs_freeDSList) {
2738 /* none free, making one is better than a panic */
2739 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2740 tdc = afs_osi_Alloc(sizeof(struct dcache));
2741 osi_Assert(tdc != NULL);
2742 #ifdef KERNEL_HAVE_PIN
2743 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2746 tdc = afs_freeDSList;
2747 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2750 tdc->dflags = 0; /* up-to-date, not in free q */
2752 QAdd(&afs_DLRU, &tdc->lruq);
2753 if (tdc->lruq.prev == &tdc->lruq)
2754 osi_Panic("lruq 3");
2756 /* initialize entry */
2757 tdc->f.fid.Cell = 0;
2758 tdc->f.fid.Fid.Volume = 0;
2760 hones(tdc->f.versionNo);
2761 tdc->f.inode.mem = aslot;
2762 tdc->dflags |= DFEntryMod;
2765 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2768 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2769 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2770 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2773 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2774 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2775 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2776 ObtainReadLock(&tdc->tlock);
2778 afs_indexTable[aslot] = tdc;
2781 } /*afs_MemGetDSlot */
2783 unsigned int last_error = 0, lasterrtime = 0;
2789 * Return a pointer to an freshly initialized dcache entry using
2790 * a UFS-based disk cache. The dcache tlock will be read-locked.
2793 * aslot : Dcache slot to look at.
2794 * indexvalid : 1 if we know the slot we're giving is valid, and thus
2795 * reading the dcache from the disk index should succeed. 0
2796 * if we are initializing a new dcache, and so reading from
2797 * the disk index may fail.
2798 * datavalid : 0 if we are loading a dcache entry from the free or
2799 * discard list, so we know the data in the given dcache is
2800 * not valid. 1 if we are loading a known used dcache, so the
2801 * data in the dcache must be valid.
2804 * afs_xdcache lock write-locked.
2807 afs_UFSGetDSlot(afs_int32 aslot, int indexvalid, int datavalid)
2815 AFS_STATCNT(afs_UFSGetDSlot);
2816 if (CheckLock(&afs_xdcache) != -1)
2817 osi_Panic("getdslot nolock");
2818 if (aslot < 0 || aslot >= afs_cacheFiles)
2819 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2820 tdc = afs_indexTable[aslot];
2822 QRemove(&tdc->lruq); /* move to queue head */
2823 QAdd(&afs_DLRU, &tdc->lruq);
2824 /* Grab tlock in case refCount != 0 */
2825 ObtainWriteLock(&tdc->tlock, 625);
2827 ConvertWToRLock(&tdc->tlock);
2831 /* otherwise we should read it in from the cache file */
2832 if (!afs_freeDSList)
2833 afs_GetDownDSlot(4);
2834 if (!afs_freeDSList) {
2835 /* none free, making one is better than a panic */
2836 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2837 tdc = afs_osi_Alloc(sizeof(struct dcache));
2838 osi_Assert(tdc != NULL);
2839 #ifdef KERNEL_HAVE_PIN
2840 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2843 tdc = afs_freeDSList;
2844 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2847 tdc->dflags = 0; /* up-to-date, not in free q */
2849 QAdd(&afs_DLRU, &tdc->lruq);
2850 if (tdc->lruq.prev == &tdc->lruq)
2851 osi_Panic("lruq 3");
2854 * Seek to the aslot'th entry and read it in.
2856 off = sizeof(struct fcache)*aslot + sizeof(struct afs_fheader);
2858 afs_osi_Read(afs_cacheInodep,
2859 off, (char *)(&tdc->f),
2860 sizeof(struct fcache));
2862 if (code != sizeof(struct fcache)) {
2864 #if defined(KERNEL_HAVE_UERROR)
2865 last_error = getuerror();
2869 lasterrtime = osi_Time();
2871 struct osi_stat tstat;
2872 if (afs_osi_Stat(afs_cacheInodep, &tstat)) {
2875 afs_warn("afs: disk cache read error in CacheItems slot %d "
2876 "off %d/%d code %d/%d\n",
2878 off, (int)tstat.size,
2879 (int)code, (int)sizeof(struct fcache));
2880 /* put tdc back on the free dslot list */
2881 QRemove(&tdc->lruq);
2882 tdc->index = NULLIDX;
2883 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
2884 afs_freeDSList = tdc;
2888 if (!afs_CellNumValid(tdc->f.fid.Cell)) {
2891 osi_Panic("afs: needed valid dcache but index %d off %d has "
2892 "invalid cell num %d\n",
2893 (int)aslot, off, (int)tdc->f.fid.Cell);
2897 if (datavalid && tdc->f.fid.Fid.Volume == 0) {
2898 osi_Panic("afs: invalid zero-volume dcache entry at slot %d off %d",
2902 if (!entryok || !datavalid) {
2903 tdc->f.fid.Cell = 0;
2904 tdc->f.fid.Fid.Volume = 0;
2906 hones(tdc->f.versionNo);
2907 tdc->dflags |= DFEntryMod;
2908 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2909 tdc->f.states &= ~(DRO|DBackup|DRW);
2910 afs_DCMoveBucket(tdc, 0, 0);
2913 if (tdc->f.states & DRO) {
2914 afs_DCMoveBucket(tdc, 0, 2);
2915 } else if (tdc->f.states & DBackup) {
2916 afs_DCMoveBucket(tdc, 0, 1);
2918 afs_DCMoveBucket(tdc, 0, 1);
2924 if (tdc->f.chunk >= 0)
2925 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
2930 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2931 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2932 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2935 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2936 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2937 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2938 ObtainReadLock(&tdc->tlock);
2941 * If we didn't read into a temporary dcache region, update the
2942 * slot pointer table.
2944 afs_indexTable[aslot] = tdc;
2947 } /*afs_UFSGetDSlot */
2952 * Write a particular dcache entry back to its home in the
2955 * \param adc Pointer to the dcache entry to write.
2956 * \param atime If true, set the modtime on the file to the current time.
2958 * \note Environment:
2959 * Must be called with the afs_xdcache lock at least read-locked,
2960 * and dcache entry at least read-locked.
2961 * The reference count is not changed.
2965 afs_WriteDCache(struct dcache *adc, int atime)
2969 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2971 AFS_STATCNT(afs_WriteDCache);
2972 osi_Assert(WriteLocked(&afs_xdcache));
2974 adc->f.modTime = osi_Time();
2976 if ((afs_indexFlags[adc->index] & (IFFree | IFDiscarded)) == 0 &&
2977 adc->f.fid.Fid.Volume == 0) {
2978 /* If a dcache slot is not on the free or discard list, it must be
2979 * in the hash table. Thus, the volume must be non-zero, since that
2980 * is how we determine whether or not to unhash the entry when kicking
2981 * it out of the cache. Do this check now, since otherwise this can
2982 * cause hash table corruption and a panic later on after we read the
2984 osi_Panic("afs_WriteDCache zero volume index %d flags 0x%x\n",
2985 adc->index, (unsigned)afs_indexFlags[adc->index]);
2989 * Seek to the right dcache slot and write the in-memory image out to disk.
2991 afs_cellname_write();
2993 afs_osi_Write(afs_cacheInodep,
2994 sizeof(struct fcache) * adc->index +
2995 sizeof(struct afs_fheader), (char *)(&adc->f),
2996 sizeof(struct fcache));
2997 if (code != sizeof(struct fcache)) {
2998 afs_warn("afs: failed to write to CacheItems off %ld code %d/%d\n",
2999 (long)(sizeof(struct fcache) * adc->index + sizeof(struct afs_fheader)),
3000 (int)code, (int)sizeof(struct fcache));
3009 * Wake up users of a particular file waiting for stores to take
3012 * \param avc Ptr to related vcache entry.
3014 * \note Environment:
3015 * Nothing interesting.
3018 afs_wakeup(struct vcache *avc)
3021 struct brequest *tb;
3023 AFS_STATCNT(afs_wakeup);
3024 for (i = 0; i < NBRS; i++, tb++) {
3025 /* if request is valid and for this file, we've found it */
3026 if (tb->refCount > 0 && avc == tb->vc) {
3029 * If CSafeStore is on, then we don't awaken the guy
3030 * waiting for the store until the whole store has finished.
3031 * Otherwise, we do it now. Note that if CSafeStore is on,
3032 * the BStore routine actually wakes up the user, instead
3034 * I think this is redundant now because this sort of thing
3035 * is already being handled by the higher-level code.
3037 if ((avc->f.states & CSafeStore) == 0) {
3039 tb->flags |= BUVALID;
3040 if (tb->flags & BUWAIT) {
3041 tb->flags &= ~BUWAIT;
3052 * Given a file name and inode, set up that file to be an
3053 * active member in the AFS cache. This also involves checking
3054 * the usability of its data.
3056 * \param afile Name of the cache file to initialize.
3057 * \param ainode Inode of the file.
3059 * \note Environment:
3060 * This function is called only during initialization.
3063 afs_InitCacheFile(char *afile, ino_t ainode)
3068 struct osi_file *tfile;
3069 struct osi_stat tstat;
3072 AFS_STATCNT(afs_InitCacheFile);
3073 index = afs_stats_cmperf.cacheNumEntries;
3074 if (index >= afs_cacheFiles)
3077 ObtainWriteLock(&afs_xdcache, 282);
3078 tdc = afs_GetNewDSlot(index);
3079 ReleaseReadLock(&tdc->tlock);
3080 ReleaseWriteLock(&afs_xdcache);
3082 ObtainWriteLock(&tdc->lock, 621);
3083 ObtainWriteLock(&afs_xdcache, 622);
3084 if (!afile && !ainode) {
3089 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
3091 ReleaseWriteLock(&afs_xdcache);
3092 ReleaseWriteLock(&tdc->lock);
3097 /* Add any other 'complex' inode types here ... */
3098 #if !defined(AFS_LINUX26_ENV) && !defined(AFS_CACHE_VNODE_PATH)
3099 tdc->f.inode.ufs = ainode;
3101 osi_Panic("Can't init cache with inode numbers when complex inodes are "
3106 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3108 tfile = osi_UFSOpen(&tdc->f.inode);
3109 code = afs_osi_Stat(tfile, &tstat);
3111 osi_Panic("initcachefile stat");
3114 * If file size doesn't match the cache info file, it's probably bad.
3116 if (tdc->f.chunkBytes != tstat.size)
3119 * If file changed within T (120?) seconds of cache info file, it's
3120 * probably bad. In addition, if slot changed within last T seconds,
3121 * the cache info file may be incorrectly identified, and so slot
3124 if (cacheInfoModTime < tstat.mtime + 120)
3126 if (cacheInfoModTime < tdc->f.modTime + 120)
3128 /* In case write through is behind, make sure cache items entry is
3129 * at least as new as the chunk.
3131 if (tdc->f.modTime < tstat.mtime)
3134 tdc->f.chunkBytes = 0;
3137 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3138 if (tfile && tstat.size != 0)
3139 osi_UFSTruncate(tfile, 0);
3140 tdc->f.states &= ~(DRO|DBackup|DRW);
3141 afs_DCMoveBucket(tdc, 0, 0);
3142 /* put entry in free cache slot list */
3143 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3144 afs_freeDCList = index;
3146 afs_indexFlags[index] |= IFFree;
3147 afs_indexUnique[index] = 0;
3150 * We must put this entry in the appropriate hash tables.
3151 * Note that i is still set from the above DCHash call
3153 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3154 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3155 afs_dchashTbl[code] = tdc->index;
3156 code = DVHash(&tdc->f.fid);
3157 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3158 afs_dvhashTbl[code] = tdc->index;
3159 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3161 /* has nontrivial amt of data */
3162 afs_indexFlags[index] |= IFEverUsed;
3163 afs_stats_cmperf.cacheFilesReused++;
3165 * Initialize index times to file's mod times; init indexCounter
3168 hset32(afs_indexTimes[index], tstat.atime);
3169 if (hgetlo(afs_indexCounter) < tstat.atime) {
3170 hset32(afs_indexCounter, tstat.atime);
3172 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3173 } /*File is not bad */
3176 osi_UFSClose(tfile);
3177 tdc->f.states &= ~DWriting;
3178 tdc->dflags &= ~DFEntryMod;
3179 /* don't set f.modTime; we're just cleaning up */
3180 osi_Assert(afs_WriteDCache(tdc, 0) == 0);
3181 ReleaseWriteLock(&afs_xdcache);
3182 ReleaseWriteLock(&tdc->lock);
3184 afs_stats_cmperf.cacheNumEntries++;
3189 /*Max # of struct dcache's resident at any time*/
3191 * If 'dchint' is enabled then in-memory dcache min is increased because of
3197 * Initialize dcache related variables.
3207 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3213 afs_freeDCList = NULLIDX;
3214 afs_discardDCList = NULLIDX;
3215 afs_freeDCCount = 0;
3216 afs_freeDSList = NULL;
3217 hzero(afs_indexCounter);
3219 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3225 if (achunk < 0 || achunk > 30)
3226 achunk = 13; /* Use default */
3227 AFS_SETCHUNKSIZE(achunk);
3233 if (aDentries > 512)
3234 afs_dhashsize = 2048;
3235 /* initialize hash tables */
3236 afs_dvhashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3237 osi_Assert(afs_dvhashTbl != NULL);
3238 afs_dchashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3239 osi_Assert(afs_dchashTbl != NULL);
3240 for (i = 0; i < afs_dhashsize; i++) {
3241 afs_dvhashTbl[i] = NULLIDX;
3242 afs_dchashTbl[i] = NULLIDX;
3244 afs_dvnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3245 osi_Assert(afs_dvnextTbl != NULL);
3246 afs_dcnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3247 osi_Assert(afs_dcnextTbl != NULL);
3248 for (i = 0; i < afiles; i++) {
3249 afs_dvnextTbl[i] = NULLIDX;
3250 afs_dcnextTbl[i] = NULLIDX;
3253 /* Allocate and zero the pointer array to the dcache entries */
3254 afs_indexTable = afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3255 osi_Assert(afs_indexTable != NULL);
3256 memset(afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3257 afs_indexTimes = afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3258 osi_Assert(afs_indexTimes != NULL);
3259 memset(afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3260 afs_indexUnique = afs_osi_Alloc(afiles * sizeof(afs_uint32));
3261 osi_Assert(afs_indexUnique != NULL);
3262 memset(afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3263 afs_indexFlags = afs_osi_Alloc(afiles * sizeof(u_char));
3264 osi_Assert(afs_indexFlags != NULL);
3265 memset(afs_indexFlags, 0, afiles * sizeof(char));
3267 /* Allocate and thread the struct dcache entries themselves */
3268 tdp = afs_Initial_freeDSList =
3269 afs_osi_Alloc(aDentries * sizeof(struct dcache));
3270 osi_Assert(tdp != NULL);
3271 memset(tdp, 0, aDentries * sizeof(struct dcache));
3272 #ifdef KERNEL_HAVE_PIN
3273 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3274 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3275 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3276 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3277 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3278 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3279 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3280 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3281 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3284 afs_freeDSList = &tdp[0];
3285 for (i = 0; i < aDentries - 1; i++) {
3286 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3287 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3288 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3289 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3291 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3292 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3293 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3294 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3296 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3297 afs_cacheBlocks = ablocks;
3298 afs_ComputeCacheParms(); /* compute parms based on cache size */
3300 afs_dcentries = aDentries;
3302 afs_stats_cmperf.cacheBucket0_Discarded =
3303 afs_stats_cmperf.cacheBucket1_Discarded =
3304 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3308 if (aflags & AFSCALL_INIT_MEMCACHE) {
3310 * Use a memory cache instead of a disk cache
3312 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3313 afs_cacheType = &afs_MemCacheOps;
3314 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3315 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3316 /* ablocks is reported in 1K blocks */
3317 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3319 afs_warn("afsd: memory cache too large for available memory.\n");
3320 afs_warn("afsd: AFS files cannot be accessed.\n\n");
3322 afiles = ablocks = 0;
3324 afs_warn("Memory cache: Allocating %d dcache entries...",
3327 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3328 afs_cacheType = &afs_UfsCacheOps;
3333 * Shuts down the cache.
3337 shutdown_dcache(void)
3341 #ifdef AFS_CACHE_VNODE_PATH
3342 if (cacheDiskType != AFS_FCACHE_TYPE_MEM) {
3344 for (i = 0; i < afs_cacheFiles; i++) {
3345 tdc = afs_indexTable[i];
3347 afs_osi_FreeStr(tdc->f.inode.ufs);
3353 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3354 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3355 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3356 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3357 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3358 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3359 afs_osi_Free(afs_Initial_freeDSList,
3360 afs_dcentries * sizeof(struct dcache));
3361 #ifdef KERNEL_HAVE_PIN
3362 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3363 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3364 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3365 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3366 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3367 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3368 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3372 for (i = 0; i < afs_dhashsize; i++) {
3373 afs_dvhashTbl[i] = NULLIDX;
3374 afs_dchashTbl[i] = NULLIDX;
3377 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3378 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3380 afs_blocksUsed = afs_dcentries = 0;
3381 afs_stats_cmperf.cacheBucket0_Discarded =
3382 afs_stats_cmperf.cacheBucket1_Discarded =
3383 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3384 hzero(afs_indexCounter);
3386 afs_freeDCCount = 0;
3387 afs_freeDCList = NULLIDX;
3388 afs_discardDCList = NULLIDX;
3389 afs_freeDSList = afs_Initial_freeDSList = 0;
3391 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3397 * Get a dcache ready for writing, respecting the current cache size limits
3399 * len is required because afs_GetDCache with flag == 4 expects the length
3400 * field to be filled. It decides from this whether it's necessary to fetch
3401 * data into the chunk before writing or not (when the whole chunk is
3404 * \param avc The vcache to fetch a dcache for
3405 * \param filePos The start of the section to be written
3406 * \param len The length of the section to be written
3410 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3411 * must be released and afs_PutDCache() called to free dcache.
3414 * \note avc->lock must be held on entry. Function may release and reobtain
3415 * avc->lock and GLOCK.
3419 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3420 afs_size_t len, struct vrequest *areq,
3423 struct dcache *tdc = NULL;
3426 /* read the cached info */
3428 tdc = afs_FindDCache(avc, filePos);
3430 ObtainWriteLock(&tdc->lock, 657);
3431 } else if (afs_blocksUsed >
3432 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3433 tdc = afs_FindDCache(avc, filePos);
3435 ObtainWriteLock(&tdc->lock, 658);
3436 if (!hsame(tdc->f.versionNo, avc->f.m.DataVersion)
3437 || (tdc->dflags & DFFetching)) {
3438 ReleaseWriteLock(&tdc->lock);
3444 afs_MaybeWakeupTruncateDaemon();
3445 while (afs_blocksUsed >
3446 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3447 ReleaseWriteLock(&avc->lock);
3448 if (afs_blocksUsed - afs_blocksDiscarded >
3449 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3450 afs_WaitForCacheDrain = 1;
3451 afs_osi_Sleep(&afs_WaitForCacheDrain);
3453 afs_MaybeFreeDiscardedDCache();
3454 afs_MaybeWakeupTruncateDaemon();
3455 ObtainWriteLock(&avc->lock, 509);
3457 avc->f.states |= CDirty;
3458 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3460 ObtainWriteLock(&tdc->lock, 659);
3463 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3465 ObtainWriteLock(&tdc->lock, 660);
3468 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3469 afs_stats_cmperf.cacheCurrDirtyChunks++;
3470 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3472 if (!(tdc->f.states & DWriting)) {
3473 /* don't mark entry as mod if we don't have to */
3474 tdc->f.states |= DWriting;
3475 tdc->dflags |= DFEntryMod;
3482 * Make a shadow copy of a dir's dcache. It's used for disconnected
3483 * operations like remove/create/rename to keep the original directory data.
3484 * On reconnection, we can diff the original data with the server and get the
3485 * server changes and with the local data to get the local changes.
3487 * \param avc The dir vnode.
3488 * \param adc The dir dcache.
3490 * \return 0 for success.
3492 * \note The vcache entry must be write locked.
3493 * \note The dcache entry must be read locked.
3496 afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3498 int i, code, ret_code = 0, written, trans_size;
3499 struct dcache *new_dc = NULL;
3500 struct osi_file *tfile_src, *tfile_dst;
3501 struct VenusFid shadow_fid;
3504 /* Is this a dir? */
3505 if (vType(avc) != VDIR)
3508 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3511 /* Generate a fid for the shadow dir. */
3512 shadow_fid.Cell = avc->f.fid.Cell;
3513 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3514 afs_GenShadowFid(&shadow_fid);
3516 ObtainWriteLock(&afs_xdcache, 716);
3518 /* Get a fresh dcache. */
3519 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3522 ObtainReadLock(&adc->mflock);
3524 /* Set up the new fid. */
3525 /* Copy interesting data from original dir dcache. */
3526 new_dc->mflags = adc->mflags;
3527 new_dc->dflags = adc->dflags;
3528 new_dc->f.modTime = adc->f.modTime;
3529 new_dc->f.versionNo = adc->f.versionNo;
3530 new_dc->f.states = adc->f.states;
3531 new_dc->f.chunk= adc->f.chunk;
3532 new_dc->f.chunkBytes = adc->f.chunkBytes;
3534 ReleaseReadLock(&adc->mflock);
3536 /* Now add to the two hash chains */
3537 i = DCHash(&shadow_fid, 0);
3538 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[i];
3539 afs_dchashTbl[i] = new_dc->index;
3541 i = DVHash(&shadow_fid);
3542 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[i];
3543 afs_dvhashTbl[i] = new_dc->index;
3545 ReleaseWriteLock(&afs_xdcache);
3547 /* Alloc a 4k block. */
3548 data = afs_osi_Alloc(4096);
3550 afs_warn("afs_MakeShadowDir: could not alloc data\n");
3555 /* Open the files. */
3556 tfile_src = afs_CFileOpen(&adc->f.inode);
3557 tfile_dst = afs_CFileOpen(&new_dc->f.inode);
3559 /* And now copy dir dcache data into this dcache,
3563 while (written < adc->f.chunkBytes) {
3564 trans_size = adc->f.chunkBytes - written;
3565 if (trans_size > 4096)
3568 /* Read a chunk from the dcache. */
3569 code = afs_CFileRead(tfile_src, written, data, trans_size);
3570 if (code < trans_size) {
3575 /* Write it to the new dcache. */
3576 code = afs_CFileWrite(tfile_dst, written, data, trans_size);
3577 if (code < trans_size) {
3582 written+=trans_size;
3585 afs_CFileClose(tfile_dst);
3586 afs_CFileClose(tfile_src);
3588 afs_osi_Free(data, 4096);
3590 ReleaseWriteLock(&new_dc->lock);
3591 afs_PutDCache(new_dc);
3594 ObtainWriteLock(&afs_xvcache, 763);
3595 ObtainWriteLock(&afs_disconDirtyLock, 765);
3596 QAdd(&afs_disconShadow, &avc->shadowq);
3597 osi_Assert((afs_RefVCache(avc) == 0));
3598 ReleaseWriteLock(&afs_disconDirtyLock);
3599 ReleaseWriteLock(&afs_xvcache);
3601 avc->f.shadow.vnode = shadow_fid.Fid.Vnode;
3602 avc->f.shadow.unique = shadow_fid.Fid.Unique;
3610 * Delete the dcaches of a shadow dir.
3612 * \param avc The vcache containing the shadow fid.
3614 * \note avc must be write locked.
3617 afs_DeleteShadowDir(struct vcache *avc)
3620 struct VenusFid shadow_fid;
3622 shadow_fid.Cell = avc->f.fid.Cell;
3623 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3624 shadow_fid.Fid.Vnode = avc->f.shadow.vnode;
3625 shadow_fid.Fid.Unique = avc->f.shadow.unique;
3627 tdc = afs_FindDCacheByFid(&shadow_fid);
3629 afs_HashOutDCache(tdc, 1);
3630 afs_DiscardDCache(tdc);
3633 avc->f.shadow.vnode = avc->f.shadow.unique = 0;
3634 ObtainWriteLock(&afs_disconDirtyLock, 708);
3635 QRemove(&avc->shadowq);
3636 ReleaseWriteLock(&afs_disconDirtyLock);
3637 afs_PutVCache(avc); /* Because we held it when we added to the queue */
3641 * Populate a dcache with empty chunks up to a given file size,
3642 * used before extending a file in order to avoid 'holes' which
3643 * we can't access in disconnected mode.
3645 * \param avc The vcache which is being extended (locked)
3646 * \param alen The new length of the file
3650 afs_PopulateDCache(struct vcache *avc, afs_size_t apos, struct vrequest *areq)
3653 afs_size_t len, offset;
3654 afs_int32 start, end;
3656 /* We're doing this to deal with the situation where we extend
3657 * by writing after lseek()ing past the end of the file . If that
3658 * extension skips chunks, then those chunks won't be created, and
3659 * GetDCache will assume that they have to be fetched from the server.
3660 * So, for each chunk between the current file position, and the new
3661 * length we GetDCache for that chunk.
3664 if (AFS_CHUNK(apos) == 0 || apos <= avc->f.m.Length)
3667 if (avc->f.m.Length == 0)
3670 start = AFS_CHUNK(avc->f.m.Length)+1;
3672 end = AFS_CHUNK(apos);
3675 len = AFS_CHUNKTOSIZE(start);
3676 tdc = afs_GetDCache(avc, AFS_CHUNKTOBASE(start), areq, &offset, &len, 4);