2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
13 #include <afsconfig.h>
14 #include "afs/param.h"
17 #include "afs/sysincludes.h" /*Standard vendor system headers */
18 #include "afsincludes.h" /*AFS-based standard headers */
19 #include "afs/afs_stats.h" /* statistics */
20 #include "afs/afs_cbqueue.h"
21 #include "afs/afs_osidnlc.h"
23 /* Forward declarations. */
24 static void afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint);
25 static void afs_FreeDiscardedDCache(void);
26 static void afs_DiscardDCache(struct dcache *);
27 static void afs_FreeDCache(struct dcache *);
29 static afs_int32 afs_DCGetBucket(struct vcache *);
30 static void afs_DCAdjustSize(struct dcache *, afs_int32, afs_int32);
31 static void afs_DCMoveBucket(struct dcache *, afs_int32, afs_int32);
32 static void afs_DCSizeInit(void);
33 static afs_int32 afs_DCWhichBucket(afs_int32, afs_int32);
36 * --------------------- Exported definitions ---------------------
39 afs_int32 afs_blocksUsed_0; /*!< 1K blocks in cache - in theory is zero */
40 afs_int32 afs_blocksUsed_1; /*!< 1K blocks in cache */
41 afs_int32 afs_blocksUsed_2; /*!< 1K blocks in cache */
42 afs_int32 afs_pct1 = -1;
43 afs_int32 afs_pct2 = -1;
44 afs_uint32 afs_tpct1 = 0;
45 afs_uint32 afs_tpct2 = 0;
46 afs_uint32 splitdcache = 0;
48 afs_lock_t afs_xdcache; /*!< Lock: alloc new disk cache entries */
49 afs_int32 afs_freeDCList; /*!< Free list for disk cache entries */
50 afs_int32 afs_freeDCCount; /*!< Count of elts in freeDCList */
51 afs_int32 afs_discardDCList; /*!< Discarded disk cache entries */
52 afs_int32 afs_discardDCCount; /*!< Count of elts in discardDCList */
53 struct dcache *afs_freeDSList; /*!< Free list for disk slots */
54 struct dcache *afs_Initial_freeDSList; /*!< Initial list for above */
55 afs_dcache_id_t cacheInode; /*!< Inode for CacheItems file */
56 struct osi_file *afs_cacheInodep = 0; /*!< file for CacheItems inode */
57 struct afs_q afs_DLRU; /*!< dcache LRU */
58 afs_int32 afs_dhashsize = 1024;
59 afs_int32 *afs_dvhashTbl; /*!< Data cache hash table: hashed by FID + chunk number. */
60 afs_int32 *afs_dchashTbl; /*!< Data cache hash table: hashed by FID. */
61 afs_int32 *afs_dvnextTbl; /*!< Dcache hash table links */
62 afs_int32 *afs_dcnextTbl; /*!< Dcache hash table links */
63 struct dcache **afs_indexTable; /*!< Pointers to dcache entries */
64 afs_hyper_t *afs_indexTimes; /*!< Dcache entry Access times */
65 afs_int32 *afs_indexUnique; /*!< dcache entry Fid.Unique */
66 unsigned char *afs_indexFlags; /*!< (only one) Is there data there? */
67 afs_hyper_t afs_indexCounter; /*!< Fake time for marking index
69 afs_int32 afs_cacheFiles = 0; /*!< Size of afs_indexTable */
70 afs_int32 afs_cacheBlocks; /*!< 1K blocks in cache */
71 afs_int32 afs_cacheStats; /*!< Stat entries in cache */
72 afs_int32 afs_blocksUsed; /*!< Number of blocks in use */
73 afs_int32 afs_blocksDiscarded; /*!<Blocks freed but not truncated */
74 afs_int32 afs_fsfragsize = AFS_MIN_FRAGSIZE; /*!< Underlying Filesystem minimum unit
75 *of disk allocation usually 1K
76 *this value is (truefrag -1 ) to
77 *save a bunch of subtracts... */
78 #ifdef AFS_64BIT_CLIENT
79 #ifdef AFS_VM_RDWR_ENV
80 afs_size_t afs_vmMappingEnd; /* !< For large files (>= 2GB) the VM
81 * mapping an 32bit addressing machines
82 * can only be used below the 2 GB
83 * line. From this point upwards we
84 * must do direct I/O into the cache
85 * files. The value should be on a
87 #endif /* AFS_VM_RDWR_ENV */
88 #endif /* AFS_64BIT_CLIENT */
90 /* The following is used to ensure that new dcache's aren't obtained when
91 * the cache is nearly full.
93 int afs_WaitForCacheDrain = 0;
94 int afs_TruncateDaemonRunning = 0;
95 int afs_CacheTooFull = 0;
97 afs_int32 afs_dcentries; /*!< In-memory dcache entries */
100 int dcacheDisabled = 0;
102 struct afs_cacheOps afs_UfsCacheOps = {
103 #ifndef HAVE_STRUCT_LABEL_SUPPORT
116 .truncate = osi_UFSTruncate,
117 .fread = afs_osi_Read,
118 .fwrite = afs_osi_Write,
119 .close = osi_UFSClose,
120 .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 afs_FreeDiscardedDCache();
465 /* See if we need to continue to run. Someone may have
466 * signalled us while we were executing.
468 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
469 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
470 /* Collect statistics on truncate daemon. */
471 CTD_stats.CTD_nSleeps++;
472 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
473 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
474 CTD_stats.CTD_beforeSleep);
475 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
477 afs_TruncateDaemonRunning = 0;
478 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
479 afs_TruncateDaemonRunning = 1;
481 osi_GetuTime(&CTD_stats.CTD_afterSleep);
482 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
483 CTD_stats.CTD_afterSleep);
484 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
486 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
487 afs_termState = AFSOP_STOP_AFSDB;
488 afs_osi_Wakeup(&afs_termState);
496 * Make adjustment for the new size in the disk cache entry
498 * \note Major Assumptions Here:
499 * Assumes that frag size is an integral power of two, less one,
500 * and that this is a two's complement machine. I don't
501 * know of any filesystems which violate this assumption...
503 * \param adc Ptr to dcache entry.
504 * \param anewsize New size desired.
509 afs_AdjustSize(struct dcache *adc, afs_int32 newSize)
513 AFS_STATCNT(afs_AdjustSize);
515 adc->dflags |= DFEntryMod;
516 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
517 adc->f.chunkBytes = newSize;
520 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
521 afs_DCAdjustSize(adc, oldSize, newSize);
522 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
524 /* We're growing the file, wakeup the daemon */
525 afs_MaybeWakeupTruncateDaemon();
527 afs_blocksUsed += (newSize - oldSize);
528 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
533 * This routine is responsible for moving at least one entry (but up
534 * to some number of them) from the LRU queue to the free queue.
536 * \param anumber Number of entries that should ideally be moved.
537 * \param aneedSpace How much space we need (1K blocks);
540 * The anumber parameter is just a hint; at least one entry MUST be
541 * moved, or we'll panic. We must be called with afs_xdcache
542 * write-locked. We should try to satisfy both anumber and aneedspace,
543 * whichever is more demanding - need to do several things:
544 * 1. only grab up to anumber victims if aneedSpace <= 0, not
545 * the whole set of MAXATONCE.
546 * 2. dynamically choose MAXATONCE to reflect severity of
547 * demand: something like (*aneedSpace >> (logChunk - 9))
549 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
550 * indicates that the cache is not properly configured/tuned or
551 * something. We should be able to automatically correct that problem.
554 #define MAXATONCE 16 /* max we can obtain at once */
556 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
560 struct VenusFid *afid;
565 afs_uint32 victims[MAXATONCE];
566 struct dcache *victimDCs[MAXATONCE];
567 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
568 afs_uint32 victimPtr; /* next free item in victim arrays */
569 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
570 afs_uint32 maxVictimPtr; /* where it is */
574 AFS_STATCNT(afs_GetDownD);
576 if (CheckLock(&afs_xdcache) != -1)
577 osi_Panic("getdownd nolock");
578 /* decrement anumber first for all dudes in free list */
579 /* SHOULD always decrement anumber first, even if aneedSpace >0,
580 * because we should try to free space even if anumber <=0 */
581 if (!aneedSpace || *aneedSpace <= 0) {
582 anumber -= afs_freeDCCount;
584 return; /* enough already free */
588 /* bounds check parameter */
589 if (anumber > MAXATONCE)
590 anumber = MAXATONCE; /* all we can do */
592 /* rewrite so phases include a better eligiblity for gc test*/
594 * The phase variable manages reclaims. Set to 0, the first pass,
595 * we don't reclaim active entries, or other than target bucket.
596 * Set to 1, we reclaim even active ones in target bucket.
597 * Set to 2, we reclaim any inactive one.
598 * Set to 3, we reclaim even active ones. On Solaris, we also reclaim
599 * entries whose corresponding vcache has a nonempty multiPage list, when
608 for (i = 0; i < afs_cacheFiles; i++)
609 /* turn off all flags */
610 afs_indexFlags[i] &= ~IFFlag;
612 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
613 /* find oldest entries for reclamation */
614 maxVictimPtr = victimPtr = 0;
615 hzero(maxVictimTime);
616 curbucket = afs_DCWhichBucket(phase, buckethint);
617 /* select victims from access time array */
618 for (i = 0; i < afs_cacheFiles; i++) {
619 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
620 /* skip if dirty or already free */
623 tdc = afs_indexTable[i];
624 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
626 /* Wrong bucket; can't use it! */
629 if (tdc && (tdc->refCount != 0)) {
630 /* Referenced; can't use it! */
633 hset(vtime, afs_indexTimes[i]);
635 /* if we've already looked at this one, skip it */
636 if (afs_indexFlags[i] & IFFlag)
639 if (victimPtr < MAXATONCE) {
640 /* if there's at least one free victim slot left */
641 victims[victimPtr] = i;
642 hset(victimTimes[victimPtr], vtime);
643 if (hcmp(vtime, maxVictimTime) > 0) {
644 hset(maxVictimTime, vtime);
645 maxVictimPtr = victimPtr;
648 } else if (hcmp(vtime, maxVictimTime) < 0) {
650 * We're older than youngest victim, so we replace at
653 /* find youngest (largest LRU) victim */
656 osi_Panic("getdownd local");
658 hset(victimTimes[j], vtime);
659 /* recompute maxVictimTime */
660 hset(maxVictimTime, vtime);
661 for (j = 0; j < victimPtr; j++)
662 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
663 hset(maxVictimTime, victimTimes[j]);
669 /* now really reclaim the victims */
670 j = 0; /* flag to track if we actually got any of the victims */
671 /* first, hold all the victims, since we're going to release the lock
672 * during the truncate operation.
674 for (i = 0; i < victimPtr; i++) {
675 tdc = afs_GetValidDSlot(victims[i]);
676 /* We got tdc->tlock(R) here */
677 if (tdc && tdc->refCount == 1)
682 ReleaseReadLock(&tdc->tlock);
687 for (i = 0; i < victimPtr; i++) {
688 /* q is first elt in dcache entry */
690 /* now, since we're dropping the afs_xdcache lock below, we
691 * have to verify, before proceeding, that there are no other
692 * references to this dcache entry, even now. Note that we
693 * compare with 1, since we bumped it above when we called
694 * afs_GetValidDSlot to preserve the entry's identity.
696 if (tdc && tdc->refCount == 1) {
697 unsigned char chunkFlags;
698 afs_size_t tchunkoffset = 0;
700 /* xdcache is lower than the xvcache lock */
701 ReleaseWriteLock(&afs_xdcache);
702 ObtainReadLock(&afs_xvcache);
703 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
704 ReleaseReadLock(&afs_xvcache);
705 ObtainWriteLock(&afs_xdcache, 527);
707 if (tdc->refCount > 1)
710 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
711 chunkFlags = afs_indexFlags[tdc->index];
712 if (((phase & 1) == 0) && osi_Active(tvc))
714 if (((phase & 1) == 1) && osi_Active(tvc)
715 && (tvc->f.states & CDCLock)
716 && (chunkFlags & IFAnyPages))
718 if (chunkFlags & IFDataMod)
720 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
721 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
722 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
723 ICL_HANDLE_OFFSET(tchunkoffset));
725 #if defined(AFS_SUN5_ENV)
727 * Now we try to invalidate pages. We do this only for
728 * Solaris. For other platforms, it's OK to recycle a
729 * dcache entry out from under a page, because the strategy
730 * function can call afs_GetDCache().
732 if (!skip && (chunkFlags & IFAnyPages)) {
735 ReleaseWriteLock(&afs_xdcache);
736 ObtainWriteLock(&tvc->vlock, 543);
737 if (!QEmpty(&tvc->multiPage)) {
738 if (phase < 3 || osi_VM_MultiPageConflict(tvc, tdc)) {
743 /* block locking pages */
744 tvc->vstates |= VPageCleaning;
745 /* block getting new pages */
747 ReleaseWriteLock(&tvc->vlock);
748 /* One last recheck */
749 ObtainWriteLock(&afs_xdcache, 333);
750 chunkFlags = afs_indexFlags[tdc->index];
751 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
752 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
753 && (chunkFlags & IFAnyPages))) {
755 ReleaseWriteLock(&afs_xdcache);
758 ReleaseWriteLock(&afs_xdcache);
760 code = osi_VM_GetDownD(tvc, tdc);
762 ObtainWriteLock(&afs_xdcache, 269);
763 /* we actually removed all pages, clean and dirty */
765 afs_indexFlags[tdc->index] &=
766 ~(IFDirtyPages | IFAnyPages);
769 ReleaseWriteLock(&afs_xdcache);
771 ObtainWriteLock(&tvc->vlock, 544);
772 if (--tvc->activeV == 0
773 && (tvc->vstates & VRevokeWait)) {
774 tvc->vstates &= ~VRevokeWait;
775 afs_osi_Wakeup((char *)&tvc->vstates);
778 if (tvc->vstates & VPageCleaning) {
779 tvc->vstates &= ~VPageCleaning;
780 afs_osi_Wakeup((char *)&tvc->vstates);
783 ReleaseWriteLock(&tvc->vlock);
785 #endif /* AFS_SUN5_ENV */
787 ReleaseWriteLock(&afs_xdcache);
790 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
791 ObtainWriteLock(&afs_xdcache, 528);
792 if (afs_indexFlags[tdc->index] &
793 (IFDataMod | IFDirtyPages | IFAnyPages))
795 if (tdc->refCount > 1)
798 #if defined(AFS_SUN5_ENV)
800 /* no vnode, so IFDirtyPages is spurious (we don't
801 * sweep dcaches on vnode recycling, so we can have
802 * DIRTYPAGES set even when all pages are gone). Just
804 * Hold vcache lock to prevent vnode from being
805 * created while we're clearing IFDirtyPages.
807 afs_indexFlags[tdc->index] &=
808 ~(IFDirtyPages | IFAnyPages);
812 /* skip this guy and mark him as recently used */
813 afs_indexFlags[tdc->index] |= IFFlag;
814 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
815 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
816 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
817 ICL_HANDLE_OFFSET(tchunkoffset));
819 /* flush this dude from the data cache and reclaim;
820 * first, make sure no one will care that we damage
821 * it, by removing it from all hash tables. Then,
822 * melt it down for parts. Note that any concurrent
823 * (new possibility!) calls to GetDownD won't touch
824 * this guy because his reference count is > 0. */
825 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
826 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
827 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
828 ICL_HANDLE_OFFSET(tchunkoffset));
829 AFS_STATCNT(afs_gget);
830 afs_HashOutDCache(tdc, 1);
831 if (tdc->f.chunkBytes != 0) {
835 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
840 afs_DiscardDCache(tdc);
845 j = 1; /* we reclaimed at least one victim */
850 } /* end of for victims loop */
853 /* Phase is 0 and no one was found, so try phase 1 (ignore
854 * osi_Active flag) */
857 for (i = 0; i < afs_cacheFiles; i++)
858 /* turn off all flags */
859 afs_indexFlags[i] &= ~IFFlag;
862 /* found no one in phases 0-5, we're hosed */
866 } /* big while loop */
874 * Remove adc from any hash tables that would allow it to be located
875 * again by afs_FindDCache or afs_GetDCache.
877 * \param adc Pointer to dcache entry to remove from hash tables.
879 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
883 afs_HashOutDCache(struct dcache *adc, int zap)
887 AFS_STATCNT(afs_glink);
889 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
891 /* if this guy is in the hash table, pull him out */
892 if (adc->f.fid.Fid.Volume != 0) {
893 /* remove entry from first hash chains */
894 i = DCHash(&adc->f.fid, adc->f.chunk);
895 us = afs_dchashTbl[i];
896 if (us == adc->index) {
897 /* first dude in the list */
898 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
900 /* somewhere on the chain */
901 while (us != NULLIDX) {
902 if (afs_dcnextTbl[us] == adc->index) {
903 /* found item pointing at the one to delete */
904 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
907 us = afs_dcnextTbl[us];
910 osi_Panic("dcache hc");
912 /* remove entry from *other* hash chain */
913 i = DVHash(&adc->f.fid);
914 us = afs_dvhashTbl[i];
915 if (us == adc->index) {
916 /* first dude in the list */
917 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
919 /* somewhere on the chain */
920 while (us != NULLIDX) {
921 if (afs_dvnextTbl[us] == adc->index) {
922 /* found item pointing at the one to delete */
923 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
926 us = afs_dvnextTbl[us];
929 osi_Panic("dcache hv");
934 /* prevent entry from being found on a reboot (it is already out of
935 * the hash table, but after a crash, we just look at fid fields of
936 * stable (old) entries).
938 adc->f.fid.Fid.Volume = 0; /* invalid */
940 /* mark entry as modified */
941 adc->dflags |= DFEntryMod;
946 } /*afs_HashOutDCache */
949 * Flush the given dcache entry, pulling it from hash chains
950 * and truncating the associated cache file.
952 * \param adc Ptr to dcache entry to flush.
955 * This routine must be called with the afs_xdcache lock held
959 afs_FlushDCache(struct dcache *adc)
961 AFS_STATCNT(afs_FlushDCache);
963 * Bump the number of cache files flushed.
965 afs_stats_cmperf.cacheFlushes++;
967 /* remove from all hash tables */
968 afs_HashOutDCache(adc, 1);
970 /* Free its space; special case null operation, since truncate operation
971 * in UFS is slow even in this case, and this allows us to pre-truncate
972 * these files at more convenient times with fewer locks set
973 * (see afs_GetDownD).
975 if (adc->f.chunkBytes != 0) {
976 afs_DiscardDCache(adc);
977 afs_MaybeWakeupTruncateDaemon();
982 if (afs_WaitForCacheDrain) {
983 if (afs_blocksUsed <=
984 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
985 afs_WaitForCacheDrain = 0;
986 afs_osi_Wakeup(&afs_WaitForCacheDrain);
989 } /*afs_FlushDCache */
993 * Put a dcache entry on the free dcache entry list.
995 * \param adc dcache entry to free.
997 * \note Environment: called with afs_xdcache lock write-locked.
1000 afs_FreeDCache(struct dcache *adc)
1002 /* Thread on free list, update free list count and mark entry as
1003 * freed in its indexFlags element. Also, ensure DCache entry gets
1004 * written out (set DFEntryMod).
1007 afs_dvnextTbl[adc->index] = afs_freeDCList;
1008 afs_freeDCList = adc->index;
1010 afs_indexFlags[adc->index] |= IFFree;
1011 adc->dflags |= DFEntryMod;
1013 if (afs_WaitForCacheDrain) {
1014 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1015 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1016 afs_WaitForCacheDrain = 0;
1017 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1020 } /* afs_FreeDCache */
1023 * Discard the cache element by moving it to the discardDCList.
1024 * This puts the cache element into a quasi-freed state, where
1025 * the space may be reused, but the file has not been truncated.
1027 * \note Major Assumptions Here:
1028 * Assumes that frag size is an integral power of two, less one,
1029 * and that this is a two's complement machine. I don't
1030 * know of any filesystems which violate this assumption...
1032 * \param adr Ptr to dcache entry.
1034 * \note Environment:
1035 * Must be called with afs_xdcache write-locked.
1039 afs_DiscardDCache(struct dcache *adc)
1043 AFS_STATCNT(afs_DiscardDCache);
1045 osi_Assert(adc->refCount == 1);
1047 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1048 afs_blocksDiscarded += size;
1049 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1051 afs_dvnextTbl[adc->index] = afs_discardDCList;
1052 afs_discardDCList = adc->index;
1053 afs_discardDCCount++;
1055 adc->f.fid.Fid.Volume = 0;
1056 adc->dflags |= DFEntryMod;
1057 afs_indexFlags[adc->index] |= IFDiscarded;
1059 if (afs_WaitForCacheDrain) {
1060 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1061 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1062 afs_WaitForCacheDrain = 0;
1063 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1067 } /*afs_DiscardDCache */
1070 * Free the next element on the list of discarded cache elements.
1073 afs_FreeDiscardedDCache(void)
1076 struct osi_file *tfile;
1079 AFS_STATCNT(afs_FreeDiscardedDCache);
1081 ObtainWriteLock(&afs_xdcache, 510);
1082 if (!afs_blocksDiscarded) {
1083 ReleaseWriteLock(&afs_xdcache);
1088 * Get an entry from the list of discarded cache elements
1090 tdc = afs_GetUnusedDSlot(afs_discardDCList);
1092 osi_Assert(tdc->refCount == 1);
1093 ReleaseReadLock(&tdc->tlock);
1095 afs_discardDCList = afs_dvnextTbl[tdc->index];
1096 afs_dvnextTbl[tdc->index] = NULLIDX;
1097 afs_discardDCCount--;
1098 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1099 afs_blocksDiscarded -= size;
1100 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1101 /* We can lock because we just took it off the free list */
1102 ObtainWriteLock(&tdc->lock, 626);
1103 ReleaseWriteLock(&afs_xdcache);
1106 * Truncate the element to reclaim its space
1108 tfile = afs_CFileOpen(&tdc->f.inode);
1109 afs_CFileTruncate(tfile, 0);
1110 afs_CFileClose(tfile);
1111 afs_AdjustSize(tdc, 0);
1112 afs_DCMoveBucket(tdc, 0, 0);
1115 * Free the element we just truncated
1117 ObtainWriteLock(&afs_xdcache, 511);
1118 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1119 afs_FreeDCache(tdc);
1120 tdc->f.states &= ~(DRO|DBackup|DRW);
1121 ReleaseWriteLock(&tdc->lock);
1123 ReleaseWriteLock(&afs_xdcache);
1127 * Free as many entries from the list of discarded cache elements
1128 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1133 afs_MaybeFreeDiscardedDCache(void)
1136 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1138 while (afs_blocksDiscarded
1139 && (afs_blocksUsed >
1140 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1141 afs_FreeDiscardedDCache();
1147 * Try to free up a certain number of disk slots.
1149 * \param anumber Targeted number of disk slots to free up.
1151 * \note Environment:
1152 * Must be called with afs_xdcache write-locked.
1156 afs_GetDownDSlot(int anumber)
1158 struct afs_q *tq, *nq;
1163 AFS_STATCNT(afs_GetDownDSlot);
1164 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1165 osi_Panic("diskless getdowndslot");
1167 if (CheckLock(&afs_xdcache) != -1)
1168 osi_Panic("getdowndslot nolock");
1170 /* decrement anumber first for all dudes in free list */
1171 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1174 return; /* enough already free */
1176 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1178 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1179 nq = QPrev(tq); /* in case we remove it */
1180 if (tdc->refCount == 0) {
1181 if ((ix = tdc->index) == NULLIDX)
1182 osi_Panic("getdowndslot");
1183 /* pull the entry out of the lruq and put it on the free list */
1184 QRemove(&tdc->lruq);
1186 /* write-through if modified */
1187 if (tdc->dflags & DFEntryMod) {
1188 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1190 * ask proxy to do this for us - we don't have the stack space
1192 while (tdc->dflags & DFEntryMod) {
1195 s = SPLOCK(afs_sgibklock);
1196 if (afs_sgibklist == NULL) {
1197 /* if slot is free, grab it. */
1198 afs_sgibklist = tdc;
1199 SV_SIGNAL(&afs_sgibksync);
1201 /* wait for daemon to (start, then) finish. */
1202 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1206 tdc->dflags &= ~DFEntryMod;
1207 osi_Assert(afs_WriteDCache(tdc, 1) == 0);
1211 /* finally put the entry in the free list */
1212 afs_indexTable[ix] = NULL;
1213 afs_indexFlags[ix] &= ~IFEverUsed;
1214 tdc->index = NULLIDX;
1215 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1216 afs_freeDSList = tdc;
1220 } /*afs_GetDownDSlot */
1227 * Increment the reference count on a disk cache entry,
1228 * which already has a non-zero refcount. In order to
1229 * increment the refcount of a zero-reference entry, you
1230 * have to hold afs_xdcache.
1233 * adc : Pointer to the dcache entry to increment.
1236 * Nothing interesting.
1239 afs_RefDCache(struct dcache *adc)
1241 ObtainWriteLock(&adc->tlock, 627);
1242 if (adc->refCount < 0)
1243 osi_Panic("RefDCache: negative refcount");
1245 ReleaseWriteLock(&adc->tlock);
1254 * Decrement the reference count on a disk cache entry.
1257 * ad : Ptr to the dcache entry to decrement.
1260 * Nothing interesting.
1263 afs_PutDCache(struct dcache *adc)
1265 AFS_STATCNT(afs_PutDCache);
1266 ObtainWriteLock(&adc->tlock, 276);
1267 if (adc->refCount <= 0)
1268 osi_Panic("putdcache");
1270 ReleaseWriteLock(&adc->tlock);
1279 * Try to discard all data associated with this file from the
1283 * avc : Pointer to the cache info for the file.
1286 * Both pvnLock and lock are write held.
1289 afs_TryToSmush(struct vcache *avc, afs_ucred_t *acred, int sync)
1294 AFS_STATCNT(afs_TryToSmush);
1295 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1296 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1297 sync = 1; /* XX Temp testing XX */
1299 #if defined(AFS_SUN5_ENV)
1300 ObtainWriteLock(&avc->vlock, 573);
1301 avc->activeV++; /* block new getpages */
1302 ReleaseWriteLock(&avc->vlock);
1305 /* Flush VM pages */
1306 osi_VM_TryToSmush(avc, acred, sync);
1309 * Get the hash chain containing all dce's for this fid
1311 i = DVHash(&avc->f.fid);
1312 ObtainWriteLock(&afs_xdcache, 277);
1313 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1314 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1315 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1316 int releaseTlock = 1;
1317 tdc = afs_GetValidDSlot(index);
1318 if (!tdc) osi_Panic("afs_TryToSmush tdc");
1319 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1321 if ((afs_indexFlags[index] & IFDataMod) == 0
1322 && tdc->refCount == 1) {
1323 ReleaseReadLock(&tdc->tlock);
1325 afs_FlushDCache(tdc);
1328 afs_indexTable[index] = 0;
1331 ReleaseReadLock(&tdc->tlock);
1335 #if defined(AFS_SUN5_ENV)
1336 ObtainWriteLock(&avc->vlock, 545);
1337 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1338 avc->vstates &= ~VRevokeWait;
1339 afs_osi_Wakeup((char *)&avc->vstates);
1341 ReleaseWriteLock(&avc->vlock);
1343 ReleaseWriteLock(&afs_xdcache);
1345 * It's treated like a callback so that when we do lookups we'll
1346 * invalidate the unique bit if any
1347 * trytoSmush occured during the lookup call
1353 * afs_DCacheMissingChunks
1356 * Given the cached info for a file, return the number of chunks that
1357 * are not available from the dcache.
1360 * avc: Pointer to the (held) vcache entry to look in.
1363 * The number of chunks which are not currently cached.
1366 * The vcache entry is held upon entry.
1370 afs_DCacheMissingChunks(struct vcache *avc)
1373 afs_size_t totalLength = 0;
1374 afs_uint32 totalChunks = 0;
1377 totalLength = avc->f.m.Length;
1378 if (avc->f.truncPos < totalLength)
1379 totalLength = avc->f.truncPos;
1381 /* Length is 0, no chunk missing. */
1382 if (totalLength == 0)
1385 /* If totalLength is a multiple of chunksize, the last byte appears
1386 * as being part of the next chunk, which does not exist.
1387 * Decrementing totalLength by one fixes that.
1390 totalChunks = (AFS_CHUNK(totalLength) + 1);
1392 /* If we're a directory, we only ever have one chunk, regardless of
1393 * the size of the dir.
1395 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1399 printf("Should have %d chunks for %u bytes\n",
1400 totalChunks, (totalLength + 1));
1402 i = DVHash(&avc->f.fid);
1403 ObtainWriteLock(&afs_xdcache, 1001);
1404 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1405 i = afs_dvnextTbl[index];
1406 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1407 tdc = afs_GetValidDSlot(index);
1409 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1412 ReleaseReadLock(&tdc->tlock);
1417 ReleaseWriteLock(&afs_xdcache);
1419 /*printf("Missing %d chunks\n", totalChunks);*/
1421 return (totalChunks);
1428 * Given the cached info for a file and a byte offset into the
1429 * file, make sure the dcache entry for that file and containing
1430 * the given byte is available, returning it to our caller.
1433 * avc : Pointer to the (held) vcache entry to look in.
1434 * abyte : Which byte we want to get to.
1437 * Pointer to the dcache entry covering the file & desired byte,
1438 * or NULL if not found.
1441 * The vcache entry is held upon entry.
1445 afs_FindDCache(struct vcache *avc, afs_size_t abyte)
1449 struct dcache *tdc = NULL;
1451 AFS_STATCNT(afs_FindDCache);
1452 chunk = AFS_CHUNK(abyte);
1455 * Hash on the [fid, chunk] and get the corresponding dcache index
1456 * after write-locking the dcache.
1458 i = DCHash(&avc->f.fid, chunk);
1459 ObtainWriteLock(&afs_xdcache, 278);
1460 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1461 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1462 tdc = afs_GetValidDSlot(index);
1463 if (!tdc) osi_Panic("afs_FindDCache tdc");
1464 ReleaseReadLock(&tdc->tlock);
1465 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1466 break; /* leaving refCount high for caller */
1470 index = afs_dcnextTbl[index];
1472 if (index != NULLIDX) {
1473 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1474 hadd32(afs_indexCounter, 1);
1475 ReleaseWriteLock(&afs_xdcache);
1478 ReleaseWriteLock(&afs_xdcache);
1480 } /*afs_FindDCache */
1484 * Get a fresh dcache from the free or discarded list.
1486 * \param avc Who's dcache is this going to be?
1487 * \param chunk The position where it will be placed in.
1488 * \param lock How are locks held.
1489 * \param ashFid If this dcache going to be used for a shadow dir,
1492 * \note Required locks:
1494 * - avc (R if (lock & 1) set and W otherwise)
1495 * \note It write locks the new dcache. The caller must unlock it.
1497 * \return The new dcache.
1500 afs_AllocDCache(struct vcache *avc, afs_int32 chunk, afs_int32 lock,
1501 struct VenusFid *ashFid)
1503 struct dcache *tdc = NULL;
1504 afs_uint32 size = 0;
1505 struct osi_file *file;
1507 if (afs_discardDCList == NULLIDX
1508 || ((lock & 2) && afs_freeDCList != NULLIDX)) {
1510 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1511 tdc = afs_GetUnusedDSlot(afs_freeDCList);
1513 osi_Assert(tdc->refCount == 1);
1514 ReleaseReadLock(&tdc->tlock);
1515 ObtainWriteLock(&tdc->lock, 604);
1516 afs_freeDCList = afs_dvnextTbl[tdc->index];
1519 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1520 tdc = afs_GetUnusedDSlot(afs_discardDCList);
1522 osi_Assert(tdc->refCount == 1);
1523 ReleaseReadLock(&tdc->tlock);
1524 ObtainWriteLock(&tdc->lock, 605);
1525 afs_discardDCList = afs_dvnextTbl[tdc->index];
1526 afs_discardDCCount--;
1528 ((tdc->f.chunkBytes +
1529 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1530 tdc->f.states &= ~(DRO|DBackup|DRW);
1531 afs_DCMoveBucket(tdc, size, 0);
1532 afs_blocksDiscarded -= size;
1533 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1535 /* Truncate the chunk so zeroes get filled properly */
1536 file = afs_CFileOpen(&tdc->f.inode);
1537 afs_CFileTruncate(file, 0);
1538 afs_CFileClose(file);
1539 afs_AdjustSize(tdc, 0);
1545 * avc->lock(R) if setLocks
1546 * avc->lock(W) if !setLocks
1552 * Fill in the newly-allocated dcache record.
1554 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1556 /* Use shadow fid if provided. */
1557 tdc->f.fid = *ashFid;
1559 /* Use normal vcache's fid otherwise. */
1560 tdc->f.fid = avc->f.fid;
1561 if (avc->f.states & CRO)
1562 tdc->f.states = DRO;
1563 else if (avc->f.states & CBackup)
1564 tdc->f.states = DBackup;
1566 tdc->f.states = DRW;
1567 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1568 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1570 hones(tdc->f.versionNo); /* invalid value */
1571 tdc->f.chunk = chunk;
1572 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1574 if (tdc->lruq.prev == &tdc->lruq)
1575 osi_Panic("lruq 1");
1584 * This function is called to obtain a reference to data stored in
1585 * the disk cache, locating a chunk of data containing the desired
1586 * byte and returning a reference to the disk cache entry, with its
1587 * reference count incremented.
1591 * avc : Ptr to a vcache entry (unlocked)
1592 * abyte : Byte position in the file desired
1593 * areq : Request structure identifying the requesting user.
1594 * aflags : Settings as follows:
1596 * 2 : Return after creating entry.
1597 * 4 : called from afs_vnop_write.c
1598 * *alen contains length of data to be written.
1600 * aoffset : Set to the offset within the chunk where the resident
1602 * alen : Set to the number of bytes of data after the desired
1603 * byte (including the byte itself) which can be read
1607 * The vcache entry pointed to by avc is unlocked upon entry.
1611 * Update the vnode-to-dcache hint if we can get the vnode lock
1612 * right away. Assumes dcache entry is at least read-locked.
1615 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1617 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1618 if (hsame(v->f.m.DataVersion, d->f.versionNo) && v->callback)
1621 ReleaseWriteLock(&v->lock);
1625 /* avc - Write-locked unless aflags & 1 */
1627 afs_GetDCache(struct vcache *avc, afs_size_t abyte,
1628 struct vrequest *areq, afs_size_t * aoffset,
1629 afs_size_t * alen, int aflags)
1631 afs_int32 i, code, shortcut;
1632 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1633 afs_int32 adjustsize = 0;
1639 afs_size_t Position = 0;
1640 afs_int32 size, tlen; /* size of segment to transfer */
1641 struct afs_FetchOutput *tsmall = 0;
1643 struct osi_file *file;
1644 struct afs_conn *tc;
1646 struct server *newCallback = NULL;
1647 char setNewCallback;
1648 char setVcacheStatus;
1649 char doVcacheUpdate;
1651 int doAdjustSize = 0;
1652 int doReallyAdjustSize = 0;
1653 int overWriteWholeChunk = 0;
1654 struct rx_connection *rxconn;
1657 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1658 int fromReplica; /*Are we reading from a replica? */
1659 int numFetchLoops; /*# times around the fetch/analyze loop */
1660 #endif /* AFS_NOSTATS */
1662 AFS_STATCNT(afs_GetDCache);
1666 setLocks = aflags & 1;
1669 * Determine the chunk number and offset within the chunk corresponding
1670 * to the desired byte.
1672 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1675 chunk = AFS_CHUNK(abyte);
1678 /* come back to here if we waited for the cache to drain. */
1681 setNewCallback = setVcacheStatus = 0;
1685 ObtainWriteLock(&avc->lock, 616);
1687 ObtainReadLock(&avc->lock);
1692 * avc->lock(R) if setLocks && !slowPass
1693 * avc->lock(W) if !setLocks || slowPass
1698 /* check hints first! (might could use bcmp or some such...) */
1699 if ((tdc = avc->dchint)) {
1703 * The locking order between afs_xdcache and dcache lock matters.
1704 * The hint dcache entry could be anywhere, even on the free list.
1705 * Locking afs_xdcache ensures that noone is trying to pull dcache
1706 * entries from the free list, and thereby assuming them to be not
1707 * referenced and not locked.
1709 ObtainReadLock(&afs_xdcache);
1710 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1712 if (dcLocked && (tdc->index != NULLIDX)
1713 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
1714 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1715 /* got the right one. It might not be the right version, and it
1716 * might be fetching, but it's the right dcache entry.
1718 /* All this code should be integrated better with what follows:
1719 * I can save a good bit more time under a write lock if I do..
1721 ObtainWriteLock(&tdc->tlock, 603);
1723 ReleaseWriteLock(&tdc->tlock);
1725 ReleaseReadLock(&afs_xdcache);
1728 if (hsame(tdc->f.versionNo, avc->f.m.DataVersion)
1729 && !(tdc->dflags & DFFetching)) {
1731 afs_stats_cmperf.dcacheHits++;
1732 ObtainWriteLock(&afs_xdcache, 559);
1733 QRemove(&tdc->lruq);
1734 QAdd(&afs_DLRU, &tdc->lruq);
1735 ReleaseWriteLock(&afs_xdcache);
1738 * avc->lock(R) if setLocks && !slowPass
1739 * avc->lock(W) if !setLocks || slowPass
1746 ReleaseSharedLock(&tdc->lock);
1747 ReleaseReadLock(&afs_xdcache);
1755 * avc->lock(R) if setLocks && !slowPass
1756 * avc->lock(W) if !setLocks || slowPass
1757 * tdc->lock(S) if tdc
1760 if (!tdc) { /* If the hint wasn't the right dcache entry */
1762 * Hash on the [fid, chunk] and get the corresponding dcache index
1763 * after write-locking the dcache.
1768 * avc->lock(R) if setLocks && !slowPass
1769 * avc->lock(W) if !setLocks || slowPass
1772 i = DCHash(&avc->f.fid, chunk);
1773 /* check to make sure our space is fine */
1774 afs_MaybeWakeupTruncateDaemon();
1776 ObtainWriteLock(&afs_xdcache, 280);
1778 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1779 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1780 tdc = afs_GetValidDSlot(index);
1782 ReleaseWriteLock(&afs_xdcache);
1785 ReleaseReadLock(&tdc->tlock);
1788 * avc->lock(R) if setLocks && !slowPass
1789 * avc->lock(W) if !setLocks || slowPass
1792 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1793 /* Move it up in the beginning of the list */
1794 if (afs_dchashTbl[i] != index) {
1795 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1796 afs_dcnextTbl[index] = afs_dchashTbl[i];
1797 afs_dchashTbl[i] = index;
1799 ReleaseWriteLock(&afs_xdcache);
1800 ObtainSharedLock(&tdc->lock, 606);
1801 break; /* leaving refCount high for caller */
1807 index = afs_dcnextTbl[index];
1811 * If we didn't find the entry, we'll create one.
1813 if (index == NULLIDX) {
1816 * avc->lock(R) if setLocks
1817 * avc->lock(W) if !setLocks
1820 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1821 avc, ICL_TYPE_INT32, chunk);
1823 /* Make sure there is a free dcache entry for us to use */
1824 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1827 avc->f.states |= CDCLock;
1828 /* just need slots */
1829 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1831 avc->f.states &= ~CDCLock;
1832 if (afs_discardDCList != NULLIDX
1833 || afs_freeDCList != NULLIDX)
1835 /* If we can't get space for 5 mins we give up and panic */
1836 if (++downDCount > 300) {
1837 osi_Panic("getdcache");
1839 ReleaseWriteLock(&afs_xdcache);
1842 * avc->lock(R) if setLocks
1843 * avc->lock(W) if !setLocks
1845 afs_osi_Wait(1000, 0, 0);
1850 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
1853 * Now add to the two hash chains - note that i is still set
1854 * from the above DCHash call.
1856 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1857 afs_dchashTbl[i] = tdc->index;
1858 i = DVHash(&avc->f.fid);
1859 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1860 afs_dvhashTbl[i] = tdc->index;
1861 tdc->dflags = DFEntryMod;
1863 afs_MaybeWakeupTruncateDaemon();
1864 ReleaseWriteLock(&afs_xdcache);
1865 ConvertWToSLock(&tdc->lock);
1870 /* vcache->dcache hint failed */
1873 * avc->lock(R) if setLocks && !slowPass
1874 * avc->lock(W) if !setLocks || slowPass
1877 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1878 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
1879 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
1880 hgetlo(avc->f.m.DataVersion));
1882 * Here we have the entry in tdc, with its refCount incremented.
1883 * Note: we don't use the S-lock on avc; it costs concurrency when
1884 * storing a file back to the server.
1888 * Not a newly created file so we need to check the file's length and
1889 * compare data versions since someone could have changed the data or we're
1890 * reading a file written elsewhere. We only want to bypass doing no-op
1891 * read rpcs on newly created files (dv of 0) since only then we guarantee
1892 * that this chunk's data hasn't been filled by another client.
1894 size = AFS_CHUNKSIZE(abyte);
1895 if (aflags & 4) /* called from write */
1897 else /* called from read */
1898 tlen = tdc->validPos - abyte;
1899 Position = AFS_CHUNKTOBASE(chunk);
1900 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
1901 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
1902 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
1903 ICL_HANDLE_OFFSET(Position));
1904 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
1906 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
1907 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
1908 overWriteWholeChunk = 1;
1909 if (doAdjustSize || overWriteWholeChunk) {
1910 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1912 #ifdef AFS_SGI64_ENV
1915 #else /* AFS_SGI64_ENV */
1918 #endif /* AFS_SGI64_ENV */
1919 #else /* AFS_SGI_ENV */
1922 #endif /* AFS_SGI_ENV */
1923 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
1924 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1925 #if defined(AFS_SUN5_ENV)
1926 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
1928 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
1930 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1931 !hsame(avc->f.m.DataVersion, tdc->f.versionNo))
1932 doReallyAdjustSize = 1;
1934 if (doReallyAdjustSize || overWriteWholeChunk) {
1935 /* no data in file to read at this position */
1936 UpgradeSToWLock(&tdc->lock, 607);
1937 file = afs_CFileOpen(&tdc->f.inode);
1938 afs_CFileTruncate(file, 0);
1939 afs_CFileClose(file);
1940 afs_AdjustSize(tdc, 0);
1941 hset(tdc->f.versionNo, avc->f.m.DataVersion);
1942 tdc->dflags |= DFEntryMod;
1944 ConvertWToSLock(&tdc->lock);
1949 * We must read in the whole chunk if the version number doesn't
1953 /* don't need data, just a unique dcache entry */
1954 ObtainWriteLock(&afs_xdcache, 608);
1955 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1956 hadd32(afs_indexCounter, 1);
1957 ReleaseWriteLock(&afs_xdcache);
1959 updateV2DC(setLocks, avc, tdc, 553);
1960 if (vType(avc) == VDIR)
1963 *aoffset = AFS_CHUNKOFFSET(abyte);
1964 if (tdc->validPos < abyte)
1965 *alen = (afs_size_t) 0;
1967 *alen = tdc->validPos - abyte;
1968 ReleaseSharedLock(&tdc->lock);
1971 ReleaseWriteLock(&avc->lock);
1973 ReleaseReadLock(&avc->lock);
1975 return tdc; /* check if we're done */
1980 * avc->lock(R) if setLocks && !slowPass
1981 * avc->lock(W) if !setLocks || slowPass
1984 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
1986 setNewCallback = setVcacheStatus = 0;
1990 * avc->lock(R) if setLocks && !slowPass
1991 * avc->lock(W) if !setLocks || slowPass
1994 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
1996 * Version number mismatch.
1999 * If we are disconnected, then we can't do much of anything
2000 * because the data doesn't match the file.
2002 if (AFS_IS_DISCONNECTED) {
2003 ReleaseSharedLock(&tdc->lock);
2006 ReleaseWriteLock(&avc->lock);
2008 ReleaseReadLock(&avc->lock);
2010 /* Flush the Dcache */
2015 UpgradeSToWLock(&tdc->lock, 609);
2018 * If data ever existed for this vnode, and this is a text object,
2019 * do some clearing. Now, you'd think you need only do the flush
2020 * when VTEXT is on, but VTEXT is turned off when the text object
2021 * is freed, while pages are left lying around in memory marked
2022 * with this vnode. If we would reactivate (create a new text
2023 * object from) this vnode, we could easily stumble upon some of
2024 * these old pages in pagein. So, we always flush these guys.
2025 * Sun has a wonderful lack of useful invariants in this system.
2027 * avc->flushDV is the data version # of the file at the last text
2028 * flush. Clearly, at least, we don't have to flush the file more
2029 * often than it changes
2031 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2033 * By here, the cache entry is always write-locked. We can
2034 * deadlock if we call osi_Flush with the cache entry locked...
2035 * Unlock the dcache too.
2037 ReleaseWriteLock(&tdc->lock);
2038 if (setLocks && !slowPass)
2039 ReleaseReadLock(&avc->lock);
2041 ReleaseWriteLock(&avc->lock);
2045 * Call osi_FlushPages in open, read/write, and map, since it
2046 * is too hard here to figure out if we should lock the
2049 if (setLocks && !slowPass)
2050 ObtainReadLock(&avc->lock);
2052 ObtainWriteLock(&avc->lock, 66);
2053 ObtainWriteLock(&tdc->lock, 610);
2058 * avc->lock(R) if setLocks && !slowPass
2059 * avc->lock(W) if !setLocks || slowPass
2063 /* Watch for standard race condition around osi_FlushText */
2064 if (hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
2065 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2066 afs_stats_cmperf.dcacheHits++;
2067 ConvertWToSLock(&tdc->lock);
2071 /* Sleep here when cache needs to be drained. */
2072 if (setLocks && !slowPass
2073 && (afs_blocksUsed >
2074 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2075 /* Make sure truncate daemon is running */
2076 afs_MaybeWakeupTruncateDaemon();
2077 ObtainWriteLock(&tdc->tlock, 614);
2078 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2079 ReleaseWriteLock(&tdc->tlock);
2080 ReleaseWriteLock(&tdc->lock);
2081 ReleaseReadLock(&avc->lock);
2082 while ((afs_blocksUsed - afs_blocksDiscarded) >
2083 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2084 afs_WaitForCacheDrain = 1;
2085 afs_osi_Sleep(&afs_WaitForCacheDrain);
2087 afs_MaybeFreeDiscardedDCache();
2088 /* need to check if someone else got the chunk first. */
2089 goto RetryGetDCache;
2092 Position = AFS_CHUNKBASE(abyte);
2093 if (vType(avc) == VDIR) {
2094 size = avc->f.m.Length;
2095 if (size > tdc->f.chunkBytes) {
2096 /* pre-reserve space for file */
2097 afs_AdjustSize(tdc, size);
2099 size = 999999999; /* max size for transfer */
2101 afs_size_t maxGoodLength;
2103 /* estimate how much data we're expecting back from the server,
2104 * and reserve space in the dcache entry for it */
2106 maxGoodLength = avc->f.m.Length;
2107 if (avc->f.truncPos < maxGoodLength)
2108 maxGoodLength = avc->f.truncPos;
2110 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2111 if (Position + size > maxGoodLength)
2112 size = maxGoodLength - Position;
2114 size = 0; /* Handle random races */
2115 if (size > tdc->f.chunkBytes) {
2116 /* pre-reserve estimated space for file */
2117 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2121 /* For the actual fetch, do not limit the request to the
2122 * length of the file. If this results in a read past EOF on
2123 * the server, the server will just reply with less data than
2124 * requested. If we limit ourselves to only requesting data up
2125 * to the avc file length, we open ourselves up to races if the
2126 * file is extended on the server at about the same time.
2128 * However, we must restrict ourselves to the avc->f.truncPos
2129 * length, since this represents an outstanding local
2130 * truncation of the file that will be committed to the
2131 * fileserver when we actually write the fileserver contents.
2132 * If we do not restrict the fetch length based on
2133 * avc->f.truncPos, a different truncate operation extending
2134 * the file length could cause the old data after
2135 * avc->f.truncPos to reappear, instead of extending the file
2136 * with NUL bytes. */
2137 size = AFS_CHUNKSIZE(abyte);
2138 if (Position + size > avc->f.truncPos) {
2139 size = avc->f.truncPos - Position;
2146 if (afs_mariner && !tdc->f.chunk)
2147 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2149 * Right now, we only have one tool, and it's a hammer. So, we
2150 * fetch the whole file.
2152 DZap(tdc); /* pages in cache may be old */
2153 file = afs_CFileOpen(&tdc->f.inode);
2154 afs_RemoveVCB(&avc->f.fid);
2155 tdc->f.states |= DWriting;
2156 tdc->dflags |= DFFetching;
2157 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2158 if (tdc->mflags & DFFetchReq) {
2159 tdc->mflags &= ~DFFetchReq;
2160 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2161 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2162 __FILE__, ICL_TYPE_INT32, __LINE__,
2163 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2166 tsmall = osi_AllocLargeSpace(sizeof(struct afs_FetchOutput));
2167 setVcacheStatus = 0;
2170 * Remember if we are doing the reading from a replicated volume,
2171 * and how many times we've zipped around the fetch/analyze loop.
2173 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2175 accP = &(afs_stats_cmfullperf.accessinf);
2177 (accP->replicatedRefs)++;
2179 (accP->unreplicatedRefs)++;
2180 #endif /* AFS_NOSTATS */
2181 /* this is a cache miss */
2182 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2183 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2184 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2187 afs_stats_cmperf.dcacheMisses++;
2190 * Dynamic root support: fetch data from local memory.
2192 if (afs_IsDynroot(avc)) {
2196 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2198 dynrootDir += Position;
2199 dynrootLen -= Position;
2200 if (size > dynrootLen)
2204 code = afs_CFileWrite(file, 0, dynrootDir, size);
2212 tdc->validPos = Position + size;
2213 afs_CFileTruncate(file, size); /* prune it */
2214 } else if (afs_IsDynrootMount(avc)) {
2218 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2220 dynrootDir += Position;
2221 dynrootLen -= Position;
2222 if (size > dynrootLen)
2226 code = afs_CFileWrite(file, 0, dynrootDir, size);
2234 tdc->validPos = Position + size;
2235 afs_CFileTruncate(file, size); /* prune it */
2238 * Not a dynamic vnode: do the real fetch.
2243 * avc->lock(R) if setLocks && !slowPass
2244 * avc->lock(W) if !setLocks || slowPass
2248 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
2253 (accP->numReplicasAccessed)++;
2255 #endif /* AFS_NOSTATS */
2256 if (!setLocks || slowPass) {
2257 avc->callback = tc->parent->srvr->server;
2259 newCallback = tc->parent->srvr->server;
2263 code = afs_CacheFetchProc(tc, rxconn, file, Position, tdc,
2269 /* callback could have been broken (or expired) in a race here,
2270 * but we return the data anyway. It's as good as we knew about
2271 * when we started. */
2273 * validPos is updated by CacheFetchProc, and can only be
2274 * modifed under a dcache write lock, which we've blocked out
2276 size = tdc->validPos - Position; /* actual segment size */
2279 afs_CFileTruncate(file, size); /* prune it */
2281 if (!setLocks || slowPass) {
2282 ObtainWriteLock(&afs_xcbhash, 453);
2283 afs_DequeueCallback(avc);
2284 avc->f.states &= ~(CStatd | CUnique);
2285 avc->callback = NULL;
2286 ReleaseWriteLock(&afs_xcbhash);
2287 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2288 osi_dnlc_purgedp(avc);
2290 /* Something lost. Forget about performance, and go
2291 * back with a vcache write lock.
2293 afs_CFileTruncate(file, 0);
2294 afs_AdjustSize(tdc, 0);
2295 afs_CFileClose(file);
2296 osi_FreeLargeSpace(tsmall);
2298 ReleaseWriteLock(&tdc->lock);
2301 ReleaseReadLock(&avc->lock);
2303 goto RetryGetDCache;
2307 } while (afs_Analyze
2308 (tc, rxconn, code, &avc->f.fid, areq,
2309 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2313 * avc->lock(R) if setLocks && !slowPass
2314 * avc->lock(W) if !setLocks || slowPass
2320 * In the case of replicated access, jot down info on the number of
2321 * attempts it took before we got through or gave up.
2324 if (numFetchLoops <= 1)
2325 (accP->refFirstReplicaOK)++;
2326 if (numFetchLoops > accP->maxReplicasPerRef)
2327 accP->maxReplicasPerRef = numFetchLoops;
2329 #endif /* AFS_NOSTATS */
2331 tdc->dflags &= ~DFFetching;
2332 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2333 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2334 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2335 tdc, ICL_TYPE_INT32, tdc->dflags);
2336 if (avc->execsOrWriters == 0)
2337 tdc->f.states &= ~DWriting;
2339 /* now, if code != 0, we have an error and should punt.
2340 * note that we have the vcache write lock, either because
2341 * !setLocks or slowPass.
2344 afs_CFileTruncate(file, 0);
2345 afs_AdjustSize(tdc, 0);
2346 afs_CFileClose(file);
2347 ZapDCE(tdc); /* sets DFEntryMod */
2348 if (vType(avc) == VDIR) {
2351 tdc->f.states &= ~(DRO|DBackup|DRW);
2352 afs_DCMoveBucket(tdc, 0, 0);
2353 ReleaseWriteLock(&tdc->lock);
2355 if (!afs_IsDynroot(avc)) {
2356 ObtainWriteLock(&afs_xcbhash, 454);
2357 afs_DequeueCallback(avc);
2358 avc->f.states &= ~(CStatd | CUnique);
2359 ReleaseWriteLock(&afs_xcbhash);
2360 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2361 osi_dnlc_purgedp(avc);
2364 * avc->lock(W); assert(!setLocks || slowPass)
2366 osi_Assert(!setLocks || slowPass);
2372 /* otherwise we copy in the just-fetched info */
2373 afs_CFileClose(file);
2374 afs_AdjustSize(tdc, size); /* new size */
2376 * Copy appropriate fields into vcache. Status is
2377 * copied later where we selectively acquire the
2378 * vcache write lock.
2381 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2383 setVcacheStatus = 1;
2384 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2385 tsmall->OutStatus.DataVersion);
2386 tdc->dflags |= DFEntryMod;
2387 afs_indexFlags[tdc->index] |= IFEverUsed;
2388 ConvertWToSLock(&tdc->lock);
2389 } /*Data version numbers don't match */
2392 * Data version numbers match.
2394 afs_stats_cmperf.dcacheHits++;
2395 } /*Data version numbers match */
2397 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2401 * avc->lock(R) if setLocks && !slowPass
2402 * avc->lock(W) if !setLocks || slowPass
2403 * tdc->lock(S) if tdc
2407 * See if this was a reference to a file in the local cell.
2409 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2410 afs_stats_cmperf.dlocalAccesses++;
2412 afs_stats_cmperf.dremoteAccesses++;
2414 /* Fix up LRU info */
2417 ObtainWriteLock(&afs_xdcache, 602);
2418 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2419 hadd32(afs_indexCounter, 1);
2420 ReleaseWriteLock(&afs_xdcache);
2422 /* return the data */
2423 if (vType(avc) == VDIR)
2426 *aoffset = AFS_CHUNKOFFSET(abyte);
2427 *alen = (tdc->f.chunkBytes - *aoffset);
2428 ReleaseSharedLock(&tdc->lock);
2433 * avc->lock(R) if setLocks && !slowPass
2434 * avc->lock(W) if !setLocks || slowPass
2437 /* Fix up the callback and status values in the vcache */
2439 if (setLocks && !slowPass) {
2442 * This is our dirty little secret to parallel fetches.
2443 * We don't write-lock the vcache while doing the fetch,
2444 * but potentially we'll need to update the vcache after
2445 * the fetch is done.
2447 * Drop the read lock and try to re-obtain the write
2448 * lock. If the vcache still has the same DV, it's
2449 * ok to go ahead and install the new data.
2451 afs_hyper_t currentDV, statusDV;
2453 hset(currentDV, avc->f.m.DataVersion);
2455 if (setNewCallback && avc->callback != newCallback)
2459 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2460 tsmall->OutStatus.DataVersion);
2462 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2464 if (setVcacheStatus && !hsame(currentDV, statusDV))
2468 ReleaseReadLock(&avc->lock);
2470 if (doVcacheUpdate) {
2471 ObtainWriteLock(&avc->lock, 615);
2472 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2473 /* We lose. Someone will beat us to it. */
2475 ReleaseWriteLock(&avc->lock);
2480 /* With slow pass, we've already done all the updates */
2482 ReleaseWriteLock(&avc->lock);
2485 /* Check if we need to perform any last-minute fixes with a write-lock */
2486 if (!setLocks || doVcacheUpdate) {
2488 avc->callback = newCallback;
2489 if (tsmall && setVcacheStatus)
2490 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2492 ReleaseWriteLock(&avc->lock);
2496 osi_FreeLargeSpace(tsmall);
2499 } /*afs_GetDCache */
2503 * afs_WriteThroughDSlots
2506 * Sweep through the dcache slots and write out any modified
2507 * in-memory data back on to our caching store.
2513 * The afs_xdcache is write-locked through this whole affair.
2516 afs_WriteThroughDSlots(void)
2519 afs_int32 i, touchedit = 0;
2521 struct afs_q DirtyQ, *tq;
2523 AFS_STATCNT(afs_WriteThroughDSlots);
2526 * Because of lock ordering, we can't grab dcache locks while
2527 * holding afs_xdcache. So we enter xdcache, get a reference
2528 * for every dcache entry, and exit xdcache.
2530 ObtainWriteLock(&afs_xdcache, 283);
2532 for (i = 0; i < afs_cacheFiles; i++) {
2533 tdc = afs_indexTable[i];
2535 /* Grab tlock in case the existing refcount isn't zero */
2536 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2537 ObtainWriteLock(&tdc->tlock, 623);
2539 ReleaseWriteLock(&tdc->tlock);
2541 QAdd(&DirtyQ, &tdc->dirty);
2544 ReleaseWriteLock(&afs_xdcache);
2547 * Now, for each dcache entry we found, check if it's dirty.
2548 * If so, get write-lock, get afs_xdcache, which protects
2549 * afs_cacheInodep, and flush it. Don't forget to put back
2553 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2555 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2557 if (tdc->dflags & DFEntryMod) {
2560 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2562 /* Now that we have the write lock, double-check */
2563 if (wrLock && (tdc->dflags & DFEntryMod)) {
2564 tdc->dflags &= ~DFEntryMod;
2565 ObtainWriteLock(&afs_xdcache, 620);
2566 osi_Assert(afs_WriteDCache(tdc, 1) == 0);
2567 ReleaseWriteLock(&afs_xdcache);
2571 ReleaseWriteLock(&tdc->lock);
2577 ObtainWriteLock(&afs_xdcache, 617);
2578 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2579 /* Touch the file to make sure that the mtime on the file is kept
2580 * up-to-date to avoid losing cached files on cold starts because
2581 * their mtime seems old...
2583 struct afs_fheader theader;
2585 theader.magic = AFS_FHMAGIC;
2586 theader.firstCSize = AFS_FIRSTCSIZE;
2587 theader.otherCSize = AFS_OTHERCSIZE;
2588 theader.version = AFS_CI_VERSION;
2589 theader.dataSize = sizeof(struct fcache);
2590 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2592 ReleaseWriteLock(&afs_xdcache);
2599 * Return a pointer to an freshly initialized dcache entry using
2600 * a memory-based cache. The tlock will be read-locked.
2603 * aslot : Dcache slot to look at.
2604 * needvalid : Whether the specified slot should already exist
2607 * Must be called with afs_xdcache write-locked.
2611 afs_MemGetDSlot(afs_int32 aslot, int indexvalid, int datavalid)
2616 AFS_STATCNT(afs_MemGetDSlot);
2617 if (CheckLock(&afs_xdcache) != -1)
2618 osi_Panic("getdslot nolock");
2619 if (aslot < 0 || aslot >= afs_cacheFiles)
2620 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2621 tdc = afs_indexTable[aslot];
2623 QRemove(&tdc->lruq); /* move to queue head */
2624 QAdd(&afs_DLRU, &tdc->lruq);
2625 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2626 ObtainWriteLock(&tdc->tlock, 624);
2628 ConvertWToRLock(&tdc->tlock);
2632 /* if 'indexvalid' is true, the slot must already exist and be populated
2633 * somewhere. for memcache, the only place that dcache entries exist is
2634 * in memory, so if we did not find it above, something is very wrong. */
2635 osi_Assert(!indexvalid);
2637 if (!afs_freeDSList)
2638 afs_GetDownDSlot(4);
2639 if (!afs_freeDSList) {
2640 /* none free, making one is better than a panic */
2641 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2642 tdc = afs_osi_Alloc(sizeof(struct dcache));
2643 osi_Assert(tdc != NULL);
2644 #ifdef KERNEL_HAVE_PIN
2645 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2648 tdc = afs_freeDSList;
2649 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2652 tdc->dflags = 0; /* up-to-date, not in free q */
2654 QAdd(&afs_DLRU, &tdc->lruq);
2655 if (tdc->lruq.prev == &tdc->lruq)
2656 osi_Panic("lruq 3");
2658 /* initialize entry */
2659 tdc->f.fid.Cell = 0;
2660 tdc->f.fid.Fid.Volume = 0;
2662 hones(tdc->f.versionNo);
2663 tdc->f.inode.mem = aslot;
2664 tdc->dflags |= DFEntryMod;
2667 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2670 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2671 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2672 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2675 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2676 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2677 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2678 ObtainReadLock(&tdc->tlock);
2680 afs_indexTable[aslot] = tdc;
2683 } /*afs_MemGetDSlot */
2685 unsigned int last_error = 0, lasterrtime = 0;
2691 * Return a pointer to an freshly initialized dcache entry using
2692 * a UFS-based disk cache. The dcache tlock will be read-locked.
2695 * aslot : Dcache slot to look at.
2696 * indexvalid : 1 if we know the slot we're giving is valid, and thus
2697 * reading the dcache from the disk index should succeed. 0
2698 * if we are initializing a new dcache, and so reading from
2699 * the disk index may fail.
2700 * datavalid : 0 if we are loading a dcache entry from the free or
2701 * discard list, so we know the data in the given dcache is
2702 * not valid. 1 if we are loading a known used dcache, so the
2703 * data in the dcache must be valid.
2706 * afs_xdcache lock write-locked.
2709 afs_UFSGetDSlot(afs_int32 aslot, int indexvalid, int datavalid)
2717 AFS_STATCNT(afs_UFSGetDSlot);
2718 if (CheckLock(&afs_xdcache) != -1)
2719 osi_Panic("getdslot nolock");
2720 if (aslot < 0 || aslot >= afs_cacheFiles)
2721 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2722 tdc = afs_indexTable[aslot];
2724 QRemove(&tdc->lruq); /* move to queue head */
2725 QAdd(&afs_DLRU, &tdc->lruq);
2726 /* Grab tlock in case refCount != 0 */
2727 ObtainWriteLock(&tdc->tlock, 625);
2729 ConvertWToRLock(&tdc->tlock);
2733 /* otherwise we should read it in from the cache file */
2734 if (!afs_freeDSList)
2735 afs_GetDownDSlot(4);
2736 if (!afs_freeDSList) {
2737 /* none free, making one is better than a panic */
2738 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2739 tdc = afs_osi_Alloc(sizeof(struct dcache));
2740 osi_Assert(tdc != NULL);
2741 #ifdef KERNEL_HAVE_PIN
2742 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2745 tdc = afs_freeDSList;
2746 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2749 tdc->dflags = 0; /* up-to-date, not in free q */
2751 QAdd(&afs_DLRU, &tdc->lruq);
2752 if (tdc->lruq.prev == &tdc->lruq)
2753 osi_Panic("lruq 3");
2756 * Seek to the aslot'th entry and read it in.
2758 off = sizeof(struct fcache)*aslot + sizeof(struct afs_fheader);
2760 afs_osi_Read(afs_cacheInodep,
2761 off, (char *)(&tdc->f),
2762 sizeof(struct fcache));
2764 if (code != sizeof(struct fcache)) {
2766 #if defined(KERNEL_HAVE_UERROR)
2767 last_error = getuerror();
2771 lasterrtime = osi_Time();
2773 struct osi_stat tstat;
2774 if (afs_osi_Stat(afs_cacheInodep, &tstat)) {
2777 afs_warn("afs: disk cache read error in CacheItems slot %d "
2778 "off %d/%d code %d/%d\n",
2780 off, (int)tstat.size,
2781 (int)code, (int)sizeof(struct fcache));
2782 /* put tdc back on the free dslot list */
2783 QRemove(&tdc->lruq);
2784 tdc->index = NULLIDX;
2785 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
2786 afs_freeDSList = tdc;
2790 if (!afs_CellNumValid(tdc->f.fid.Cell)) {
2793 osi_Panic("afs: needed valid dcache but index %d off %d has "
2794 "invalid cell num %d\n",
2795 (int)aslot, off, (int)tdc->f.fid.Cell);
2799 if (datavalid && tdc->f.fid.Fid.Volume == 0) {
2800 osi_Panic("afs: invalid zero-volume dcache entry at slot %d off %d",
2804 if (!entryok || !datavalid) {
2805 tdc->f.fid.Cell = 0;
2806 tdc->f.fid.Fid.Volume = 0;
2808 hones(tdc->f.versionNo);
2809 tdc->dflags |= DFEntryMod;
2810 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2811 tdc->f.states &= ~(DRO|DBackup|DRW);
2812 afs_DCMoveBucket(tdc, 0, 0);
2815 if (tdc->f.states & DRO) {
2816 afs_DCMoveBucket(tdc, 0, 2);
2817 } else if (tdc->f.states & DBackup) {
2818 afs_DCMoveBucket(tdc, 0, 1);
2820 afs_DCMoveBucket(tdc, 0, 1);
2826 if (tdc->f.chunk >= 0)
2827 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
2832 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2833 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2834 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2837 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2838 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2839 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2840 ObtainReadLock(&tdc->tlock);
2843 * If we didn't read into a temporary dcache region, update the
2844 * slot pointer table.
2846 afs_indexTable[aslot] = tdc;
2849 } /*afs_UFSGetDSlot */
2854 * Write a particular dcache entry back to its home in the
2857 * \param adc Pointer to the dcache entry to write.
2858 * \param atime If true, set the modtime on the file to the current time.
2860 * \note Environment:
2861 * Must be called with the afs_xdcache lock at least read-locked,
2862 * and dcache entry at least read-locked.
2863 * The reference count is not changed.
2867 afs_WriteDCache(struct dcache *adc, int atime)
2871 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2873 AFS_STATCNT(afs_WriteDCache);
2874 osi_Assert(WriteLocked(&afs_xdcache));
2876 adc->f.modTime = osi_Time();
2878 if ((afs_indexFlags[adc->index] & (IFFree | IFDiscarded)) == 0 &&
2879 adc->f.fid.Fid.Volume == 0) {
2880 /* If a dcache slot is not on the free or discard list, it must be
2881 * in the hash table. Thus, the volume must be non-zero, since that
2882 * is how we determine whether or not to unhash the entry when kicking
2883 * it out of the cache. Do this check now, since otherwise this can
2884 * cause hash table corruption and a panic later on after we read the
2886 osi_Panic("afs_WriteDCache zero volume index %d flags 0x%x\n",
2887 adc->index, (unsigned)afs_indexFlags[adc->index]);
2891 * Seek to the right dcache slot and write the in-memory image out to disk.
2893 afs_cellname_write();
2895 afs_osi_Write(afs_cacheInodep,
2896 sizeof(struct fcache) * adc->index +
2897 sizeof(struct afs_fheader), (char *)(&adc->f),
2898 sizeof(struct fcache));
2899 if (code != sizeof(struct fcache)) {
2900 afs_warn("afs: failed to write to CacheItems off %ld code %d/%d\n",
2901 (long)(sizeof(struct fcache) * adc->index + sizeof(struct afs_fheader)),
2902 (int)code, (int)sizeof(struct fcache));
2911 * Wake up users of a particular file waiting for stores to take
2914 * \param avc Ptr to related vcache entry.
2916 * \note Environment:
2917 * Nothing interesting.
2920 afs_wakeup(struct vcache *avc)
2923 struct brequest *tb;
2925 AFS_STATCNT(afs_wakeup);
2926 for (i = 0; i < NBRS; i++, tb++) {
2927 /* if request is valid and for this file, we've found it */
2928 if (tb->refCount > 0 && avc == tb->vc) {
2931 * If CSafeStore is on, then we don't awaken the guy
2932 * waiting for the store until the whole store has finished.
2933 * Otherwise, we do it now. Note that if CSafeStore is on,
2934 * the BStore routine actually wakes up the user, instead
2936 * I think this is redundant now because this sort of thing
2937 * is already being handled by the higher-level code.
2939 if ((avc->f.states & CSafeStore) == 0) {
2941 tb->flags |= BUVALID;
2942 if (tb->flags & BUWAIT) {
2943 tb->flags &= ~BUWAIT;
2954 * Given a file name and inode, set up that file to be an
2955 * active member in the AFS cache. This also involves checking
2956 * the usability of its data.
2958 * \param afile Name of the cache file to initialize.
2959 * \param ainode Inode of the file.
2961 * \note Environment:
2962 * This function is called only during initialization.
2965 afs_InitCacheFile(char *afile, ino_t ainode)
2970 struct osi_file *tfile;
2971 struct osi_stat tstat;
2974 AFS_STATCNT(afs_InitCacheFile);
2975 index = afs_stats_cmperf.cacheNumEntries;
2976 if (index >= afs_cacheFiles)
2979 ObtainWriteLock(&afs_xdcache, 282);
2980 tdc = afs_GetNewDSlot(index);
2981 ReleaseReadLock(&tdc->tlock);
2982 ReleaseWriteLock(&afs_xdcache);
2984 ObtainWriteLock(&tdc->lock, 621);
2985 ObtainWriteLock(&afs_xdcache, 622);
2986 if (!afile && !ainode) {
2991 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
2993 ReleaseWriteLock(&afs_xdcache);
2994 ReleaseWriteLock(&tdc->lock);
2999 /* Add any other 'complex' inode types here ... */
3000 #if !defined(AFS_LINUX26_ENV) && !defined(AFS_CACHE_VNODE_PATH)
3001 tdc->f.inode.ufs = ainode;
3003 osi_Panic("Can't init cache with inode numbers when complex inodes are "
3008 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3010 tfile = osi_UFSOpen(&tdc->f.inode);
3011 code = afs_osi_Stat(tfile, &tstat);
3013 osi_Panic("initcachefile stat");
3016 * If file size doesn't match the cache info file, it's probably bad.
3018 if (tdc->f.chunkBytes != tstat.size)
3021 * If file changed within T (120?) seconds of cache info file, it's
3022 * probably bad. In addition, if slot changed within last T seconds,
3023 * the cache info file may be incorrectly identified, and so slot
3026 if (cacheInfoModTime < tstat.mtime + 120)
3028 if (cacheInfoModTime < tdc->f.modTime + 120)
3030 /* In case write through is behind, make sure cache items entry is
3031 * at least as new as the chunk.
3033 if (tdc->f.modTime < tstat.mtime)
3036 tdc->f.chunkBytes = 0;
3039 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3040 if (tfile && tstat.size != 0)
3041 osi_UFSTruncate(tfile, 0);
3042 tdc->f.states &= ~(DRO|DBackup|DRW);
3043 afs_DCMoveBucket(tdc, 0, 0);
3044 /* put entry in free cache slot list */
3045 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3046 afs_freeDCList = index;
3048 afs_indexFlags[index] |= IFFree;
3049 afs_indexUnique[index] = 0;
3052 * We must put this entry in the appropriate hash tables.
3053 * Note that i is still set from the above DCHash call
3055 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3056 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3057 afs_dchashTbl[code] = tdc->index;
3058 code = DVHash(&tdc->f.fid);
3059 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3060 afs_dvhashTbl[code] = tdc->index;
3061 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3063 /* has nontrivial amt of data */
3064 afs_indexFlags[index] |= IFEverUsed;
3065 afs_stats_cmperf.cacheFilesReused++;
3067 * Initialize index times to file's mod times; init indexCounter
3070 hset32(afs_indexTimes[index], tstat.atime);
3071 if (hgetlo(afs_indexCounter) < tstat.atime) {
3072 hset32(afs_indexCounter, tstat.atime);
3074 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3075 } /*File is not bad */
3078 osi_UFSClose(tfile);
3079 tdc->f.states &= ~DWriting;
3080 tdc->dflags &= ~DFEntryMod;
3081 /* don't set f.modTime; we're just cleaning up */
3082 osi_Assert(afs_WriteDCache(tdc, 0) == 0);
3083 ReleaseWriteLock(&afs_xdcache);
3084 ReleaseWriteLock(&tdc->lock);
3086 afs_stats_cmperf.cacheNumEntries++;
3091 /*Max # of struct dcache's resident at any time*/
3093 * If 'dchint' is enabled then in-memory dcache min is increased because of
3099 * Initialize dcache related variables.
3109 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3115 afs_freeDCList = NULLIDX;
3116 afs_discardDCList = NULLIDX;
3117 afs_freeDCCount = 0;
3118 afs_freeDSList = NULL;
3119 hzero(afs_indexCounter);
3121 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3127 if (achunk < 0 || achunk > 30)
3128 achunk = 13; /* Use default */
3129 AFS_SETCHUNKSIZE(achunk);
3135 if (aDentries > 512)
3136 afs_dhashsize = 2048;
3137 /* initialize hash tables */
3138 afs_dvhashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3139 osi_Assert(afs_dvhashTbl != NULL);
3140 afs_dchashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3141 osi_Assert(afs_dchashTbl != NULL);
3142 for (i = 0; i < afs_dhashsize; i++) {
3143 afs_dvhashTbl[i] = NULLIDX;
3144 afs_dchashTbl[i] = NULLIDX;
3146 afs_dvnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3147 osi_Assert(afs_dvnextTbl != NULL);
3148 afs_dcnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3149 osi_Assert(afs_dcnextTbl != NULL);
3150 for (i = 0; i < afiles; i++) {
3151 afs_dvnextTbl[i] = NULLIDX;
3152 afs_dcnextTbl[i] = NULLIDX;
3155 /* Allocate and zero the pointer array to the dcache entries */
3156 afs_indexTable = afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3157 osi_Assert(afs_indexTable != NULL);
3158 memset(afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3159 afs_indexTimes = afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3160 osi_Assert(afs_indexTimes != NULL);
3161 memset(afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3162 afs_indexUnique = afs_osi_Alloc(afiles * sizeof(afs_uint32));
3163 osi_Assert(afs_indexUnique != NULL);
3164 memset(afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3165 afs_indexFlags = afs_osi_Alloc(afiles * sizeof(u_char));
3166 osi_Assert(afs_indexFlags != NULL);
3167 memset(afs_indexFlags, 0, afiles * sizeof(char));
3169 /* Allocate and thread the struct dcache entries themselves */
3170 tdp = afs_Initial_freeDSList =
3171 afs_osi_Alloc(aDentries * sizeof(struct dcache));
3172 osi_Assert(tdp != NULL);
3173 memset(tdp, 0, aDentries * sizeof(struct dcache));
3174 #ifdef KERNEL_HAVE_PIN
3175 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3176 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3177 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3178 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3179 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3180 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3181 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3182 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3183 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3186 afs_freeDSList = &tdp[0];
3187 for (i = 0; i < aDentries - 1; i++) {
3188 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3189 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3190 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3191 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3193 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3194 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3195 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3196 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3198 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3199 afs_cacheBlocks = ablocks;
3200 afs_ComputeCacheParms(); /* compute parms based on cache size */
3202 afs_dcentries = aDentries;
3204 afs_stats_cmperf.cacheBucket0_Discarded =
3205 afs_stats_cmperf.cacheBucket1_Discarded =
3206 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3210 if (aflags & AFSCALL_INIT_MEMCACHE) {
3212 * Use a memory cache instead of a disk cache
3214 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3215 afs_cacheType = &afs_MemCacheOps;
3216 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3217 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3218 /* ablocks is reported in 1K blocks */
3219 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3221 afs_warn("afsd: memory cache too large for available memory.\n");
3222 afs_warn("afsd: AFS files cannot be accessed.\n\n");
3224 afiles = ablocks = 0;
3226 afs_warn("Memory cache: Allocating %d dcache entries...",
3229 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3230 afs_cacheType = &afs_UfsCacheOps;
3235 * Shuts down the cache.
3239 shutdown_dcache(void)
3243 #ifdef AFS_CACHE_VNODE_PATH
3244 if (cacheDiskType != AFS_FCACHE_TYPE_MEM) {
3246 for (i = 0; i < afs_cacheFiles; i++) {
3247 tdc = afs_indexTable[i];
3249 afs_osi_FreeStr(tdc->f.inode.ufs);
3255 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3256 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3257 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3258 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3259 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3260 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3261 afs_osi_Free(afs_Initial_freeDSList,
3262 afs_dcentries * sizeof(struct dcache));
3263 #ifdef KERNEL_HAVE_PIN
3264 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3265 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3266 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3267 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3268 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3269 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3270 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3274 for (i = 0; i < afs_dhashsize; i++) {
3275 afs_dvhashTbl[i] = NULLIDX;
3276 afs_dchashTbl[i] = NULLIDX;
3279 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3280 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3282 afs_blocksUsed = afs_dcentries = 0;
3283 afs_stats_cmperf.cacheBucket0_Discarded =
3284 afs_stats_cmperf.cacheBucket1_Discarded =
3285 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3286 hzero(afs_indexCounter);
3288 afs_freeDCCount = 0;
3289 afs_freeDCList = NULLIDX;
3290 afs_discardDCList = NULLIDX;
3291 afs_freeDSList = afs_Initial_freeDSList = 0;
3293 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3299 * Get a dcache ready for writing, respecting the current cache size limits
3301 * len is required because afs_GetDCache with flag == 4 expects the length
3302 * field to be filled. It decides from this whether it's necessary to fetch
3303 * data into the chunk before writing or not (when the whole chunk is
3306 * \param avc The vcache to fetch a dcache for
3307 * \param filePos The start of the section to be written
3308 * \param len The length of the section to be written
3312 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3313 * must be released and afs_PutDCache() called to free dcache.
3316 * \note avc->lock must be held on entry. Function may release and reobtain
3317 * avc->lock and GLOCK.
3321 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3322 afs_size_t len, struct vrequest *areq,
3325 struct dcache *tdc = NULL;
3328 /* read the cached info */
3330 tdc = afs_FindDCache(avc, filePos);
3332 ObtainWriteLock(&tdc->lock, 657);
3333 } else if (afs_blocksUsed >
3334 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3335 tdc = afs_FindDCache(avc, filePos);
3337 ObtainWriteLock(&tdc->lock, 658);
3338 if (!hsame(tdc->f.versionNo, avc->f.m.DataVersion)
3339 || (tdc->dflags & DFFetching)) {
3340 ReleaseWriteLock(&tdc->lock);
3346 afs_MaybeWakeupTruncateDaemon();
3347 while (afs_blocksUsed >
3348 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3349 ReleaseWriteLock(&avc->lock);
3350 if (afs_blocksUsed - afs_blocksDiscarded >
3351 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3352 afs_WaitForCacheDrain = 1;
3353 afs_osi_Sleep(&afs_WaitForCacheDrain);
3355 afs_MaybeFreeDiscardedDCache();
3356 afs_MaybeWakeupTruncateDaemon();
3357 ObtainWriteLock(&avc->lock, 509);
3359 avc->f.states |= CDirty;
3360 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3362 ObtainWriteLock(&tdc->lock, 659);
3365 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3367 ObtainWriteLock(&tdc->lock, 660);
3370 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3371 afs_stats_cmperf.cacheCurrDirtyChunks++;
3372 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3374 if (!(tdc->f.states & DWriting)) {
3375 /* don't mark entry as mod if we don't have to */
3376 tdc->f.states |= DWriting;
3377 tdc->dflags |= DFEntryMod;
3384 * Make a shadow copy of a dir's dcache. It's used for disconnected
3385 * operations like remove/create/rename to keep the original directory data.
3386 * On reconnection, we can diff the original data with the server and get the
3387 * server changes and with the local data to get the local changes.
3389 * \param avc The dir vnode.
3390 * \param adc The dir dcache.
3392 * \return 0 for success.
3394 * \note The vcache entry must be write locked.
3395 * \note The dcache entry must be read locked.
3398 afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3400 int i, code, ret_code = 0, written, trans_size;
3401 struct dcache *new_dc = NULL;
3402 struct osi_file *tfile_src, *tfile_dst;
3403 struct VenusFid shadow_fid;
3406 /* Is this a dir? */
3407 if (vType(avc) != VDIR)
3410 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3413 /* Generate a fid for the shadow dir. */
3414 shadow_fid.Cell = avc->f.fid.Cell;
3415 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3416 afs_GenShadowFid(&shadow_fid);
3418 ObtainWriteLock(&afs_xdcache, 716);
3420 /* Get a fresh dcache. */
3421 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3423 ObtainReadLock(&adc->mflock);
3425 /* Set up the new fid. */
3426 /* Copy interesting data from original dir dcache. */
3427 new_dc->mflags = adc->mflags;
3428 new_dc->dflags = adc->dflags;
3429 new_dc->f.modTime = adc->f.modTime;
3430 new_dc->f.versionNo = adc->f.versionNo;
3431 new_dc->f.states = adc->f.states;
3432 new_dc->f.chunk= adc->f.chunk;
3433 new_dc->f.chunkBytes = adc->f.chunkBytes;
3435 ReleaseReadLock(&adc->mflock);
3437 /* Now add to the two hash chains */
3438 i = DCHash(&shadow_fid, 0);
3439 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[i];
3440 afs_dchashTbl[i] = new_dc->index;
3442 i = DVHash(&shadow_fid);
3443 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[i];
3444 afs_dvhashTbl[i] = new_dc->index;
3446 ReleaseWriteLock(&afs_xdcache);
3448 /* Alloc a 4k block. */
3449 data = afs_osi_Alloc(4096);
3451 afs_warn("afs_MakeShadowDir: could not alloc data\n");
3456 /* Open the files. */
3457 tfile_src = afs_CFileOpen(&adc->f.inode);
3458 tfile_dst = afs_CFileOpen(&new_dc->f.inode);
3460 /* And now copy dir dcache data into this dcache,
3464 while (written < adc->f.chunkBytes) {
3465 trans_size = adc->f.chunkBytes - written;
3466 if (trans_size > 4096)
3469 /* Read a chunk from the dcache. */
3470 code = afs_CFileRead(tfile_src, written, data, trans_size);
3471 if (code < trans_size) {
3476 /* Write it to the new dcache. */
3477 code = afs_CFileWrite(tfile_dst, written, data, trans_size);
3478 if (code < trans_size) {
3483 written+=trans_size;
3486 afs_CFileClose(tfile_dst);
3487 afs_CFileClose(tfile_src);
3489 afs_osi_Free(data, 4096);
3491 ReleaseWriteLock(&new_dc->lock);
3492 afs_PutDCache(new_dc);
3495 ObtainWriteLock(&afs_xvcache, 763);
3496 ObtainWriteLock(&afs_disconDirtyLock, 765);
3497 QAdd(&afs_disconShadow, &avc->shadowq);
3498 osi_Assert((afs_RefVCache(avc) == 0));
3499 ReleaseWriteLock(&afs_disconDirtyLock);
3500 ReleaseWriteLock(&afs_xvcache);
3502 avc->f.shadow.vnode = shadow_fid.Fid.Vnode;
3503 avc->f.shadow.unique = shadow_fid.Fid.Unique;
3511 * Delete the dcaches of a shadow dir.
3513 * \param avc The vcache containing the shadow fid.
3515 * \note avc must be write locked.
3518 afs_DeleteShadowDir(struct vcache *avc)
3521 struct VenusFid shadow_fid;
3523 shadow_fid.Cell = avc->f.fid.Cell;
3524 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3525 shadow_fid.Fid.Vnode = avc->f.shadow.vnode;
3526 shadow_fid.Fid.Unique = avc->f.shadow.unique;
3528 tdc = afs_FindDCacheByFid(&shadow_fid);
3530 afs_HashOutDCache(tdc, 1);
3531 afs_DiscardDCache(tdc);
3534 avc->f.shadow.vnode = avc->f.shadow.unique = 0;
3535 ObtainWriteLock(&afs_disconDirtyLock, 708);
3536 QRemove(&avc->shadowq);
3537 ReleaseWriteLock(&afs_disconDirtyLock);
3538 afs_PutVCache(avc); /* Because we held it when we added to the queue */
3542 * Populate a dcache with empty chunks up to a given file size,
3543 * used before extending a file in order to avoid 'holes' which
3544 * we can't access in disconnected mode.
3546 * \param avc The vcache which is being extended (locked)
3547 * \param alen The new length of the file
3551 afs_PopulateDCache(struct vcache *avc, afs_size_t apos, struct vrequest *areq)
3554 afs_size_t len, offset;
3555 afs_int32 start, end;
3557 /* We're doing this to deal with the situation where we extend
3558 * by writing after lseek()ing past the end of the file . If that
3559 * extension skips chunks, then those chunks won't be created, and
3560 * GetDCache will assume that they have to be fetched from the server.
3561 * So, for each chunk between the current file position, and the new
3562 * length we GetDCache for that chunk.
3565 if (AFS_CHUNK(apos) == 0 || apos <= avc->f.m.Length)
3568 if (avc->f.m.Length == 0)
3571 start = AFS_CHUNK(avc->f.m.Length)+1;
3573 end = AFS_CHUNK(apos);
3576 len = AFS_CHUNKTOSIZE(start);
3577 tdc = afs_GetDCache(avc, AFS_CHUNKTOBASE(start), areq, &offset, &len, 4);