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 = {
104 .truncate = osi_UFSTruncate,
105 .fread = afs_osi_Read,
106 .fwrite = afs_osi_Write,
107 .close = osi_UFSClose,
108 .vread = afs_UFSRead,
109 .vwrite = afs_UFSWrite,
110 .GetDSlot = afs_UFSGetDSlot,
111 .GetVolSlot = afs_UFSGetVolSlot,
112 .HandleLink = afs_UFSHandleLink,
115 struct afs_cacheOps afs_MemCacheOps = {
116 .open = afs_MemCacheOpen,
117 .truncate = afs_MemCacheTruncate,
118 .fread = afs_MemReadBlk,
119 .fwrite = afs_MemWriteBlk,
120 .close = afs_MemCacheClose,
121 .vread = afs_MemRead,
122 .vwrite = afs_MemWrite,
123 .GetDSlot = afs_MemGetDSlot,
124 .GetVolSlot = afs_MemGetVolSlot,
125 .HandleLink = afs_MemHandleLink,
128 int cacheDiskType; /*Type of backing disk for cache */
129 struct afs_cacheOps *afs_cacheType;
132 * Where is this vcache's entry associated dcache located/
133 * \param avc The vcache entry.
134 * \return Bucket index:
139 afs_DCGetBucket(struct vcache *avc)
144 /* This should be replaced with some sort of user configurable function */
145 if (avc->f.states & CRO) {
147 } else if (avc->f.states & CBackup) {
157 * Readjust a dcache's size.
159 * \param adc The dcache to be adjusted.
160 * \param oldSize Old size for the dcache.
161 * \param newSize The new size to be adjusted to.
165 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
167 afs_int32 adjustSize = newSize - oldSize;
175 afs_blocksUsed_0 += adjustSize;
176 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
179 afs_blocksUsed_1 += adjustSize;
180 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
183 afs_blocksUsed_2 += adjustSize;
184 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
192 * Move a dcache from one bucket to another.
194 * \param adc Operate on this dcache.
195 * \param size Size in bucket (?).
196 * \param newBucket Destination bucket.
200 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
205 /* Substract size from old bucket. */
209 afs_blocksUsed_0 -= size;
212 afs_blocksUsed_1 -= size;
215 afs_blocksUsed_2 -= size;
219 /* Set new bucket and increase destination bucket size. */
220 adc->bucket = newBucket;
225 afs_blocksUsed_0 += size;
228 afs_blocksUsed_1 += size;
231 afs_blocksUsed_2 += size;
239 * Init split caches size.
244 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
253 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
258 afs_pct1 = afs_blocksUsed_1 / (afs_cacheBlocks / 100);
259 afs_pct2 = afs_blocksUsed_2 / (afs_cacheBlocks / 100);
261 /* Short cut: if we don't know about it, try to kill it */
262 if (phase < 2 && afs_blocksUsed_0)
265 if (afs_pct1 > afs_tpct1)
267 if (afs_pct2 > afs_tpct2)
269 return 0; /* unlikely */
274 * Warn about failing to store a file.
276 * \param acode Associated error code.
277 * \param avolume Volume involved.
278 * \param aflags How to handle the output:
279 * aflags & 1: Print out on console
280 * aflags & 2: Print out on controlling tty
282 * \note Environment: Call this from close call when vnodeops is RCS unlocked.
286 afs_StoreWarn(register afs_int32 acode, afs_int32 avolume,
287 register afs_int32 aflags)
289 static char problem_fmt[] =
290 "afs: failed to store file in volume %d (%s)\n";
291 static char problem_fmt_w_error[] =
292 "afs: failed to store file in volume %d (error %d)\n";
293 static char netproblems[] = "network problems";
294 static char partfull[] = "partition full";
295 static char overquota[] = "over quota";
297 AFS_STATCNT(afs_StoreWarn);
303 afs_warn(problem_fmt, avolume, netproblems);
305 afs_warnuser(problem_fmt, avolume, netproblems);
306 } else if (acode == ENOSPC) {
311 afs_warn(problem_fmt, avolume, partfull);
313 afs_warnuser(problem_fmt, avolume, partfull);
316 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
317 * Instead ENOSPC will be sent...
319 if (acode == EDQUOT) {
324 afs_warn(problem_fmt, avolume, overquota);
326 afs_warnuser(problem_fmt, avolume, overquota);
334 afs_warn(problem_fmt_w_error, avolume, acode);
336 afs_warnuser(problem_fmt_w_error, avolume, acode);
341 * Try waking up truncation daemon, if it's worth it.
344 afs_MaybeWakeupTruncateDaemon(void)
346 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
347 afs_CacheTooFull = 1;
348 if (!afs_TruncateDaemonRunning)
349 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
350 } else if (!afs_TruncateDaemonRunning
351 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
352 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
359 * Keep statistics on run time for afs_CacheTruncateDaemon. This is a
360 * struct so we need only export one symbol for AIX.
362 static struct CTD_stats {
363 osi_timeval_t CTD_beforeSleep;
364 osi_timeval_t CTD_afterSleep;
365 osi_timeval_t CTD_sleepTime;
366 osi_timeval_t CTD_runTime;
370 u_int afs_min_cache = 0;
373 * Keeps the cache clean and free by truncating uneeded files, when used.
378 afs_CacheTruncateDaemon(void)
380 osi_timeval_t CTD_tmpTime;
384 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
386 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
388 osi_GetuTime(&CTD_stats.CTD_afterSleep);
389 afs_TruncateDaemonRunning = 1;
391 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
392 ObtainWriteLock(&afs_xdcache, 266);
393 if (afs_CacheTooFull) {
394 int space_needed, slots_needed;
395 /* if we get woken up, we should try to clean something out */
396 for (counter = 0; counter < 10; counter++) {
398 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
400 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
401 afs_GetDownD(slots_needed, &space_needed, 0);
402 if ((space_needed <= 0) && (slots_needed <= 0)) {
405 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
408 if (!afs_CacheIsTooFull())
409 afs_CacheTooFull = 0;
410 } /* end of cache cleanup */
411 ReleaseWriteLock(&afs_xdcache);
414 * This is a defensive check to try to avoid starving threads
415 * that may need the global lock so thay can help free some
416 * cache space. If this thread won't be sleeping or truncating
417 * any cache files then give up the global lock so other
418 * threads get a chance to run.
420 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
421 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
422 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
426 * This is where we free the discarded cache elements.
428 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
429 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
430 afs_FreeDiscardedDCache();
433 /* See if we need to continue to run. Someone may have
434 * signalled us while we were executing.
436 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
437 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
438 /* Collect statistics on truncate daemon. */
439 CTD_stats.CTD_nSleeps++;
440 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
441 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
442 CTD_stats.CTD_beforeSleep);
443 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
445 afs_TruncateDaemonRunning = 0;
446 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
447 afs_TruncateDaemonRunning = 1;
449 osi_GetuTime(&CTD_stats.CTD_afterSleep);
450 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
451 CTD_stats.CTD_afterSleep);
452 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
454 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
455 afs_termState = AFSOP_STOP_AFSDB;
456 afs_osi_Wakeup(&afs_termState);
464 * Make adjustment for the new size in the disk cache entry
466 * \note Major Assumptions Here:
467 * Assumes that frag size is an integral power of two, less one,
468 * and that this is a two's complement machine. I don't
469 * know of any filesystems which violate this assumption...
471 * \param adc Ptr to dcache entry.
472 * \param anewsize New size desired.
477 afs_AdjustSize(register struct dcache *adc, register afs_int32 newSize)
479 register afs_int32 oldSize;
481 AFS_STATCNT(afs_AdjustSize);
483 adc->dflags |= DFEntryMod;
484 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
485 adc->f.chunkBytes = newSize;
488 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
489 afs_DCAdjustSize(adc, oldSize, newSize);
490 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
492 /* We're growing the file, wakeup the daemon */
493 afs_MaybeWakeupTruncateDaemon();
495 afs_blocksUsed += (newSize - oldSize);
496 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
501 * This routine is responsible for moving at least one entry (but up
502 * to some number of them) from the LRU queue to the free queue.
504 * \param anumber Number of entries that should ideally be moved.
505 * \param aneedSpace How much space we need (1K blocks);
508 * The anumber parameter is just a hint; at least one entry MUST be
509 * moved, or we'll panic. We must be called with afs_xdcache
510 * write-locked. We should try to satisfy both anumber and aneedspace,
511 * whichever is more demanding - need to do several things:
512 * 1. only grab up to anumber victims if aneedSpace <= 0, not
513 * the whole set of MAXATONCE.
514 * 2. dynamically choose MAXATONCE to reflect severity of
515 * demand: something like (*aneedSpace >> (logChunk - 9))
517 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
518 * indicates that the cache is not properly configured/tuned or
519 * something. We should be able to automatically correct that problem.
522 #define MAXATONCE 16 /* max we can obtain at once */
524 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
528 struct VenusFid *afid;
532 register struct vcache *tvc;
533 afs_uint32 victims[MAXATONCE];
534 struct dcache *victimDCs[MAXATONCE];
535 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
536 afs_uint32 victimPtr; /* next free item in victim arrays */
537 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
538 afs_uint32 maxVictimPtr; /* where it is */
541 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
545 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
546 vfslocked = VFS_LOCK_GIANT(afs_globalVFS);
549 AFS_STATCNT(afs_GetDownD);
551 if (CheckLock(&afs_xdcache) != -1)
552 osi_Panic("getdownd nolock");
553 /* decrement anumber first for all dudes in free list */
554 /* SHOULD always decrement anumber first, even if aneedSpace >0,
555 * because we should try to free space even if anumber <=0 */
556 if (!aneedSpace || *aneedSpace <= 0) {
557 anumber -= afs_freeDCCount;
559 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
560 VFS_UNLOCK_GIANT(vfslocked);
562 return; /* enough already free */
566 /* bounds check parameter */
567 if (anumber > MAXATONCE)
568 anumber = MAXATONCE; /* all we can do */
570 /* rewrite so phases include a better eligiblity for gc test*/
572 * The phase variable manages reclaims. Set to 0, the first pass,
573 * we don't reclaim active entries, or other than target bucket.
574 * Set to 1, we reclaim even active ones in target bucket.
575 * Set to 2, we reclaim any inactive one.
576 * Set to 3, we reclaim even active ones.
584 for (i = 0; i < afs_cacheFiles; i++)
585 /* turn off all flags */
586 afs_indexFlags[i] &= ~IFFlag;
588 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
589 /* find oldest entries for reclamation */
590 maxVictimPtr = victimPtr = 0;
591 hzero(maxVictimTime);
592 curbucket = afs_DCWhichBucket(phase, buckethint);
593 /* select victims from access time array */
594 for (i = 0; i < afs_cacheFiles; i++) {
595 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
596 /* skip if dirty or already free */
599 tdc = afs_indexTable[i];
600 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
602 /* Wrong bucket; can't use it! */
605 if (tdc && (tdc->refCount != 0)) {
606 /* Referenced; can't use it! */
609 hset(vtime, afs_indexTimes[i]);
611 /* if we've already looked at this one, skip it */
612 if (afs_indexFlags[i] & IFFlag)
615 if (victimPtr < MAXATONCE) {
616 /* if there's at least one free victim slot left */
617 victims[victimPtr] = i;
618 hset(victimTimes[victimPtr], vtime);
619 if (hcmp(vtime, maxVictimTime) > 0) {
620 hset(maxVictimTime, vtime);
621 maxVictimPtr = victimPtr;
624 } else if (hcmp(vtime, maxVictimTime) < 0) {
626 * We're older than youngest victim, so we replace at
629 /* find youngest (largest LRU) victim */
632 osi_Panic("getdownd local");
634 hset(victimTimes[j], vtime);
635 /* recompute maxVictimTime */
636 hset(maxVictimTime, vtime);
637 for (j = 0; j < victimPtr; j++)
638 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
639 hset(maxVictimTime, victimTimes[j]);
645 /* now really reclaim the victims */
646 j = 0; /* flag to track if we actually got any of the victims */
647 /* first, hold all the victims, since we're going to release the lock
648 * during the truncate operation.
650 for (i = 0; i < victimPtr; i++) {
651 tdc = afs_GetDSlot(victims[i], 0);
652 /* We got tdc->tlock(R) here */
653 if (tdc->refCount == 1)
657 ReleaseReadLock(&tdc->tlock);
661 for (i = 0; i < victimPtr; i++) {
662 /* q is first elt in dcache entry */
664 /* now, since we're dropping the afs_xdcache lock below, we
665 * have to verify, before proceeding, that there are no other
666 * references to this dcache entry, even now. Note that we
667 * compare with 1, since we bumped it above when we called
668 * afs_GetDSlot to preserve the entry's identity.
670 if (tdc && tdc->refCount == 1) {
671 unsigned char chunkFlags;
672 afs_size_t tchunkoffset = 0;
674 /* xdcache is lower than the xvcache lock */
675 ReleaseWriteLock(&afs_xdcache);
676 ObtainReadLock(&afs_xvcache);
677 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
678 ReleaseReadLock(&afs_xvcache);
679 ObtainWriteLock(&afs_xdcache, 527);
681 if (tdc->refCount > 1)
684 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
685 chunkFlags = afs_indexFlags[tdc->index];
686 if (((phase & 1) == 0) && osi_Active(tvc))
688 if (((phase & 1) == 1) && osi_Active(tvc)
689 && (tvc->f.states & CDCLock)
690 && (chunkFlags & IFAnyPages))
692 if (chunkFlags & IFDataMod)
694 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
695 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
696 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
697 ICL_HANDLE_OFFSET(tchunkoffset));
699 #if defined(AFS_SUN5_ENV)
701 * Now we try to invalidate pages. We do this only for
702 * Solaris. For other platforms, it's OK to recycle a
703 * dcache entry out from under a page, because the strategy
704 * function can call afs_GetDCache().
706 if (!skip && (chunkFlags & IFAnyPages)) {
709 ReleaseWriteLock(&afs_xdcache);
710 ObtainWriteLock(&tvc->vlock, 543);
711 if (tvc->multiPage) {
715 /* block locking pages */
716 tvc->vstates |= VPageCleaning;
717 /* block getting new pages */
719 ReleaseWriteLock(&tvc->vlock);
720 /* One last recheck */
721 ObtainWriteLock(&afs_xdcache, 333);
722 chunkFlags = afs_indexFlags[tdc->index];
723 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
724 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
725 && (chunkFlags & IFAnyPages))) {
727 ReleaseWriteLock(&afs_xdcache);
730 ReleaseWriteLock(&afs_xdcache);
732 code = osi_VM_GetDownD(tvc, tdc);
734 ObtainWriteLock(&afs_xdcache, 269);
735 /* we actually removed all pages, clean and dirty */
737 afs_indexFlags[tdc->index] &=
738 ~(IFDirtyPages | IFAnyPages);
741 ReleaseWriteLock(&afs_xdcache);
743 ObtainWriteLock(&tvc->vlock, 544);
744 if (--tvc->activeV == 0
745 && (tvc->vstates & VRevokeWait)) {
746 tvc->vstates &= ~VRevokeWait;
747 afs_osi_Wakeup((char *)&tvc->vstates);
750 if (tvc->vstates & VPageCleaning) {
751 tvc->vstates &= ~VPageCleaning;
752 afs_osi_Wakeup((char *)&tvc->vstates);
755 ReleaseWriteLock(&tvc->vlock);
757 #endif /* AFS_SUN5_ENV */
759 ReleaseWriteLock(&afs_xdcache);
762 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
763 ObtainWriteLock(&afs_xdcache, 528);
764 if (afs_indexFlags[tdc->index] &
765 (IFDataMod | IFDirtyPages | IFAnyPages))
767 if (tdc->refCount > 1)
770 #if defined(AFS_SUN5_ENV)
772 /* no vnode, so IFDirtyPages is spurious (we don't
773 * sweep dcaches on vnode recycling, so we can have
774 * DIRTYPAGES set even when all pages are gone). Just
776 * Hold vcache lock to prevent vnode from being
777 * created while we're clearing IFDirtyPages.
779 afs_indexFlags[tdc->index] &=
780 ~(IFDirtyPages | IFAnyPages);
784 /* skip this guy and mark him as recently used */
785 afs_indexFlags[tdc->index] |= IFFlag;
786 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
787 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
788 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
789 ICL_HANDLE_OFFSET(tchunkoffset));
791 /* flush this dude from the data cache and reclaim;
792 * first, make sure no one will care that we damage
793 * it, by removing it from all hash tables. Then,
794 * melt it down for parts. Note that any concurrent
795 * (new possibility!) calls to GetDownD won't touch
796 * this guy because his reference count is > 0. */
797 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
798 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
799 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
800 ICL_HANDLE_OFFSET(tchunkoffset));
801 AFS_STATCNT(afs_gget);
802 afs_HashOutDCache(tdc, 1);
803 if (tdc->f.chunkBytes != 0) {
807 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
812 afs_DiscardDCache(tdc);
817 j = 1; /* we reclaimed at least one victim */
821 } /* end of for victims loop */
824 /* Phase is 0 and no one was found, so try phase 1 (ignore
825 * osi_Active flag) */
828 for (i = 0; i < afs_cacheFiles; i++)
829 /* turn off all flags */
830 afs_indexFlags[i] &= ~IFFlag;
833 /* found no one in phases 0-5, we're hosed */
837 } /* big while loop */
839 #if defined(AFS_FBSD80_ENV) && !defined(UKERNEL)
840 VFS_UNLOCK_GIANT(vfslocked);
849 * Remove adc from any hash tables that would allow it to be located
850 * again by afs_FindDCache or afs_GetDCache.
852 * \param adc Pointer to dcache entry to remove from hash tables.
854 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
858 afs_HashOutDCache(struct dcache *adc, int zap)
862 AFS_STATCNT(afs_glink);
864 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
866 /* if this guy is in the hash table, pull him out */
867 if (adc->f.fid.Fid.Volume != 0) {
868 /* remove entry from first hash chains */
869 i = DCHash(&adc->f.fid, adc->f.chunk);
870 us = afs_dchashTbl[i];
871 if (us == adc->index) {
872 /* first dude in the list */
873 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
875 /* somewhere on the chain */
876 while (us != NULLIDX) {
877 if (afs_dcnextTbl[us] == adc->index) {
878 /* found item pointing at the one to delete */
879 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
882 us = afs_dcnextTbl[us];
885 osi_Panic("dcache hc");
887 /* remove entry from *other* hash chain */
888 i = DVHash(&adc->f.fid);
889 us = afs_dvhashTbl[i];
890 if (us == adc->index) {
891 /* first dude in the list */
892 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
894 /* somewhere on the chain */
895 while (us != NULLIDX) {
896 if (afs_dvnextTbl[us] == adc->index) {
897 /* found item pointing at the one to delete */
898 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
901 us = afs_dvnextTbl[us];
904 osi_Panic("dcache hv");
909 /* prevent entry from being found on a reboot (it is already out of
910 * the hash table, but after a crash, we just look at fid fields of
911 * stable (old) entries).
913 adc->f.fid.Fid.Volume = 0; /* invalid */
915 /* mark entry as modified */
916 adc->dflags |= DFEntryMod;
921 } /*afs_HashOutDCache */
924 * Flush the given dcache entry, pulling it from hash chains
925 * and truncating the associated cache file.
927 * \param adc Ptr to dcache entry to flush.
930 * This routine must be called with the afs_xdcache lock held
934 afs_FlushDCache(register struct dcache *adc)
936 AFS_STATCNT(afs_FlushDCache);
938 * Bump the number of cache files flushed.
940 afs_stats_cmperf.cacheFlushes++;
942 /* remove from all hash tables */
943 afs_HashOutDCache(adc, 1);
945 /* Free its space; special case null operation, since truncate operation
946 * in UFS is slow even in this case, and this allows us to pre-truncate
947 * these files at more convenient times with fewer locks set
948 * (see afs_GetDownD).
950 if (adc->f.chunkBytes != 0) {
951 afs_DiscardDCache(adc);
952 afs_MaybeWakeupTruncateDaemon();
957 if (afs_WaitForCacheDrain) {
958 if (afs_blocksUsed <=
959 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
960 afs_WaitForCacheDrain = 0;
961 afs_osi_Wakeup(&afs_WaitForCacheDrain);
964 } /*afs_FlushDCache */
968 * Put a dcache entry on the free dcache entry list.
970 * \param adc dcache entry to free.
972 * \note Environment: called with afs_xdcache lock write-locked.
975 afs_FreeDCache(register struct dcache *adc)
977 /* Thread on free list, update free list count and mark entry as
978 * freed in its indexFlags element. Also, ensure DCache entry gets
979 * written out (set DFEntryMod).
982 afs_dvnextTbl[adc->index] = afs_freeDCList;
983 afs_freeDCList = adc->index;
985 afs_indexFlags[adc->index] |= IFFree;
986 adc->dflags |= DFEntryMod;
988 if (afs_WaitForCacheDrain) {
989 if ((afs_blocksUsed - afs_blocksDiscarded) <=
990 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
991 afs_WaitForCacheDrain = 0;
992 afs_osi_Wakeup(&afs_WaitForCacheDrain);
995 } /* afs_FreeDCache */
998 * Discard the cache element by moving it to the discardDCList.
999 * This puts the cache element into a quasi-freed state, where
1000 * the space may be reused, but the file has not been truncated.
1002 * \note Major Assumptions Here:
1003 * Assumes that frag size is an integral power of two, less one,
1004 * and that this is a two's complement machine. I don't
1005 * know of any filesystems which violate this assumption...
1007 * \param adr Ptr to dcache entry.
1009 * \note Environment:
1010 * Must be called with afs_xdcache write-locked.
1014 afs_DiscardDCache(register struct dcache *adc)
1016 register afs_int32 size;
1018 AFS_STATCNT(afs_DiscardDCache);
1020 osi_Assert(adc->refCount == 1);
1022 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1023 afs_blocksDiscarded += size;
1024 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1026 afs_dvnextTbl[adc->index] = afs_discardDCList;
1027 afs_discardDCList = adc->index;
1028 afs_discardDCCount++;
1030 adc->f.fid.Fid.Volume = 0;
1031 adc->dflags |= DFEntryMod;
1032 afs_indexFlags[adc->index] |= IFDiscarded;
1034 if (afs_WaitForCacheDrain) {
1035 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1036 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1037 afs_WaitForCacheDrain = 0;
1038 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1042 } /*afs_DiscardDCache */
1045 * Free the next element on the list of discarded cache elements.
1048 afs_FreeDiscardedDCache(void)
1050 register struct dcache *tdc;
1051 register struct osi_file *tfile;
1052 register afs_int32 size;
1054 AFS_STATCNT(afs_FreeDiscardedDCache);
1056 ObtainWriteLock(&afs_xdcache, 510);
1057 if (!afs_blocksDiscarded) {
1058 ReleaseWriteLock(&afs_xdcache);
1063 * Get an entry from the list of discarded cache elements
1065 tdc = afs_GetDSlot(afs_discardDCList, 0);
1066 osi_Assert(tdc->refCount == 1);
1067 ReleaseReadLock(&tdc->tlock);
1069 afs_discardDCList = afs_dvnextTbl[tdc->index];
1070 afs_dvnextTbl[tdc->index] = NULLIDX;
1071 afs_discardDCCount--;
1072 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1073 afs_blocksDiscarded -= size;
1074 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1075 /* We can lock because we just took it off the free list */
1076 ObtainWriteLock(&tdc->lock, 626);
1077 ReleaseWriteLock(&afs_xdcache);
1080 * Truncate the element to reclaim its space
1082 tfile = afs_CFileOpen(&tdc->f.inode);
1083 afs_CFileTruncate(tfile, 0);
1084 afs_CFileClose(tfile);
1085 afs_AdjustSize(tdc, 0);
1086 afs_DCMoveBucket(tdc, 0, 0);
1089 * Free the element we just truncated
1091 ObtainWriteLock(&afs_xdcache, 511);
1092 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1093 afs_FreeDCache(tdc);
1094 tdc->f.states &= ~(DRO|DBackup|DRW);
1095 ReleaseWriteLock(&tdc->lock);
1097 ReleaseWriteLock(&afs_xdcache);
1101 * Free as many entries from the list of discarded cache elements
1102 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1107 afs_MaybeFreeDiscardedDCache(void)
1110 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1112 while (afs_blocksDiscarded
1113 && (afs_blocksUsed >
1114 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1115 afs_FreeDiscardedDCache();
1121 * Try to free up a certain number of disk slots.
1123 * \param anumber Targeted number of disk slots to free up.
1125 * \note Environment:
1126 * Must be called with afs_xdcache write-locked.
1130 afs_GetDownDSlot(int anumber)
1132 struct afs_q *tq, *nq;
1137 AFS_STATCNT(afs_GetDownDSlot);
1138 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1139 osi_Panic("diskless getdowndslot");
1141 if (CheckLock(&afs_xdcache) != -1)
1142 osi_Panic("getdowndslot nolock");
1144 /* decrement anumber first for all dudes in free list */
1145 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1148 return; /* enough already free */
1150 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1152 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1153 nq = QPrev(tq); /* in case we remove it */
1154 if (tdc->refCount == 0) {
1155 if ((ix = tdc->index) == NULLIDX)
1156 osi_Panic("getdowndslot");
1157 /* pull the entry out of the lruq and put it on the free list */
1158 QRemove(&tdc->lruq);
1160 /* write-through if modified */
1161 if (tdc->dflags & DFEntryMod) {
1162 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1164 * ask proxy to do this for us - we don't have the stack space
1166 while (tdc->dflags & DFEntryMod) {
1169 s = SPLOCK(afs_sgibklock);
1170 if (afs_sgibklist == NULL) {
1171 /* if slot is free, grab it. */
1172 afs_sgibklist = tdc;
1173 SV_SIGNAL(&afs_sgibksync);
1175 /* wait for daemon to (start, then) finish. */
1176 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1180 tdc->dflags &= ~DFEntryMod;
1181 afs_WriteDCache(tdc, 1);
1185 /* finally put the entry in the free list */
1186 afs_indexTable[ix] = NULL;
1187 afs_indexFlags[ix] &= ~IFEverUsed;
1188 tdc->index = NULLIDX;
1189 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1190 afs_freeDSList = tdc;
1194 } /*afs_GetDownDSlot */
1201 * Increment the reference count on a disk cache entry,
1202 * which already has a non-zero refcount. In order to
1203 * increment the refcount of a zero-reference entry, you
1204 * have to hold afs_xdcache.
1207 * adc : Pointer to the dcache entry to increment.
1210 * Nothing interesting.
1213 afs_RefDCache(struct dcache *adc)
1215 ObtainWriteLock(&adc->tlock, 627);
1216 if (adc->refCount < 0)
1217 osi_Panic("RefDCache: negative refcount");
1219 ReleaseWriteLock(&adc->tlock);
1228 * Decrement the reference count on a disk cache entry.
1231 * ad : Ptr to the dcache entry to decrement.
1234 * Nothing interesting.
1237 afs_PutDCache(register struct dcache *adc)
1239 AFS_STATCNT(afs_PutDCache);
1240 ObtainWriteLock(&adc->tlock, 276);
1241 if (adc->refCount <= 0)
1242 osi_Panic("putdcache");
1244 ReleaseWriteLock(&adc->tlock);
1253 * Try to discard all data associated with this file from the
1257 * avc : Pointer to the cache info for the file.
1260 * Both pvnLock and lock are write held.
1263 afs_TryToSmush(register struct vcache *avc, afs_ucred_t *acred, int sync)
1265 register struct dcache *tdc;
1268 AFS_STATCNT(afs_TryToSmush);
1269 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1270 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1271 sync = 1; /* XX Temp testing XX */
1273 #if defined(AFS_SUN5_ENV)
1274 ObtainWriteLock(&avc->vlock, 573);
1275 avc->activeV++; /* block new getpages */
1276 ReleaseWriteLock(&avc->vlock);
1279 /* Flush VM pages */
1280 osi_VM_TryToSmush(avc, acred, sync);
1283 * Get the hash chain containing all dce's for this fid
1285 i = DVHash(&avc->f.fid);
1286 ObtainWriteLock(&afs_xdcache, 277);
1287 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1288 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1289 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1290 int releaseTlock = 1;
1291 tdc = afs_GetDSlot(index, NULL);
1292 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1294 if ((afs_indexFlags[index] & IFDataMod) == 0
1295 && tdc->refCount == 1) {
1296 ReleaseReadLock(&tdc->tlock);
1298 afs_FlushDCache(tdc);
1301 afs_indexTable[index] = 0;
1304 ReleaseReadLock(&tdc->tlock);
1308 #if defined(AFS_SUN5_ENV)
1309 ObtainWriteLock(&avc->vlock, 545);
1310 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1311 avc->vstates &= ~VRevokeWait;
1312 afs_osi_Wakeup((char *)&avc->vstates);
1314 ReleaseWriteLock(&avc->vlock);
1316 ReleaseWriteLock(&afs_xdcache);
1318 * It's treated like a callback so that when we do lookups we'll
1319 * invalidate the unique bit if any
1320 * trytoSmush occured during the lookup call
1326 * afs_DCacheMissingChunks
1329 * Given the cached info for a file, return the number of chunks that
1330 * are not available from the dcache.
1333 * avc: Pointer to the (held) vcache entry to look in.
1336 * The number of chunks which are not currently cached.
1339 * The vcache entry is held upon entry.
1343 afs_DCacheMissingChunks(struct vcache *avc)
1346 afs_size_t totalLength = 0;
1347 afs_uint32 totalChunks = 0;
1350 totalLength = avc->f.m.Length;
1351 if (avc->f.truncPos < totalLength)
1352 totalLength = avc->f.truncPos;
1354 /* Length is 0, no chunk missing. */
1355 if (totalLength == 0)
1358 /* If totalLength is a multiple of chunksize, the last byte appears
1359 * as being part of the next chunk, which does not exist.
1360 * Decrementing totalLength by one fixes that.
1363 totalChunks = (AFS_CHUNK(totalLength) + 1);
1365 /* If we're a directory, we only ever have one chunk, regardless of
1366 * the size of the dir.
1368 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1372 printf("Should have %d chunks for %u bytes\n",
1373 totalChunks, (totalLength + 1));
1375 i = DVHash(&avc->f.fid);
1376 ObtainWriteLock(&afs_xdcache, 1001);
1377 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1378 i = afs_dvnextTbl[index];
1379 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1380 tdc = afs_GetDSlot(index, NULL);
1381 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1384 ReleaseReadLock(&tdc->tlock);
1388 ReleaseWriteLock(&afs_xdcache);
1390 /*printf("Missing %d chunks\n", totalChunks);*/
1392 return (totalChunks);
1399 * Given the cached info for a file and a byte offset into the
1400 * file, make sure the dcache entry for that file and containing
1401 * the given byte is available, returning it to our caller.
1404 * avc : Pointer to the (held) vcache entry to look in.
1405 * abyte : Which byte we want to get to.
1408 * Pointer to the dcache entry covering the file & desired byte,
1409 * or NULL if not found.
1412 * The vcache entry is held upon entry.
1416 afs_FindDCache(register struct vcache *avc, afs_size_t abyte)
1419 register afs_int32 i, index;
1420 register struct dcache *tdc = NULL;
1422 AFS_STATCNT(afs_FindDCache);
1423 chunk = AFS_CHUNK(abyte);
1426 * Hash on the [fid, chunk] and get the corresponding dcache index
1427 * after write-locking the dcache.
1429 i = DCHash(&avc->f.fid, chunk);
1430 ObtainWriteLock(&afs_xdcache, 278);
1431 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1432 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1433 tdc = afs_GetDSlot(index, NULL);
1434 ReleaseReadLock(&tdc->tlock);
1435 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1436 break; /* leaving refCount high for caller */
1440 index = afs_dcnextTbl[index];
1442 if (index != NULLIDX) {
1443 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1444 hadd32(afs_indexCounter, 1);
1445 ReleaseWriteLock(&afs_xdcache);
1448 ReleaseWriteLock(&afs_xdcache);
1450 } /*afs_FindDCache */
1454 * Get a fresh dcache from the free or discarded list.
1456 * \param avc Who's dcache is this going to be?
1457 * \param chunk The position where it will be placed in.
1458 * \param lock How are locks held.
1459 * \param ashFid If this dcache going to be used for a shadow dir,
1462 * \note Required locks:
1464 * - avc (R if (lock & 1) set and W otherwise)
1465 * \note It write locks the new dcache. The caller must unlock it.
1467 * \return The new dcache.
1469 struct dcache *afs_AllocDCache(struct vcache *avc,
1472 struct VenusFid *ashFid)
1474 struct dcache *tdc = NULL;
1475 afs_uint32 size = 0;
1476 struct osi_file *file;
1478 if (afs_discardDCList == NULLIDX
1479 || ((lock & 2) && afs_freeDCList != NULLIDX)) {
1481 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1482 tdc = afs_GetDSlot(afs_freeDCList, 0);
1483 osi_Assert(tdc->refCount == 1);
1484 ReleaseReadLock(&tdc->tlock);
1485 ObtainWriteLock(&tdc->lock, 604);
1486 afs_freeDCList = afs_dvnextTbl[tdc->index];
1489 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1490 tdc = afs_GetDSlot(afs_discardDCList, 0);
1491 osi_Assert(tdc->refCount == 1);
1492 ReleaseReadLock(&tdc->tlock);
1493 ObtainWriteLock(&tdc->lock, 605);
1494 afs_discardDCList = afs_dvnextTbl[tdc->index];
1495 afs_discardDCCount--;
1497 ((tdc->f.chunkBytes +
1498 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1499 tdc->f.states &= ~(DRO|DBackup|DRW);
1500 afs_DCMoveBucket(tdc, size, 0);
1501 afs_blocksDiscarded -= size;
1502 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1504 /* Truncate the chunk so zeroes get filled properly */
1505 file = afs_CFileOpen(&tdc->f.inode);
1506 afs_CFileTruncate(file, 0);
1507 afs_CFileClose(file);
1508 afs_AdjustSize(tdc, 0);
1514 * avc->lock(R) if setLocks
1515 * avc->lock(W) if !setLocks
1521 * Fill in the newly-allocated dcache record.
1523 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1525 /* Use shadow fid if provided. */
1526 tdc->f.fid = *ashFid;
1528 /* Use normal vcache's fid otherwise. */
1529 tdc->f.fid = avc->f.fid;
1530 if (avc->f.states & CRO)
1531 tdc->f.states = DRO;
1532 else if (avc->f.states & CBackup)
1533 tdc->f.states = DBackup;
1535 tdc->f.states = DRW;
1536 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1537 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1539 hones(tdc->f.versionNo); /* invalid value */
1540 tdc->f.chunk = chunk;
1541 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1543 if (tdc->lruq.prev == &tdc->lruq)
1544 osi_Panic("lruq 1");
1553 * This function is called to obtain a reference to data stored in
1554 * the disk cache, locating a chunk of data containing the desired
1555 * byte and returning a reference to the disk cache entry, with its
1556 * reference count incremented.
1560 * avc : Ptr to a vcache entry (unlocked)
1561 * abyte : Byte position in the file desired
1562 * areq : Request structure identifying the requesting user.
1563 * aflags : Settings as follows:
1565 * 2 : Return after creating entry.
1566 * 4 : called from afs_vnop_write.c
1567 * *alen contains length of data to be written.
1569 * aoffset : Set to the offset within the chunk where the resident
1571 * alen : Set to the number of bytes of data after the desired
1572 * byte (including the byte itself) which can be read
1576 * The vcache entry pointed to by avc is unlocked upon entry.
1580 * Update the vnode-to-dcache hint if we can get the vnode lock
1581 * right away. Assumes dcache entry is at least read-locked.
1584 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1586 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1587 if (hsame(v->f.m.DataVersion, d->f.versionNo) && v->callback)
1590 ReleaseWriteLock(&v->lock);
1594 /* avc - Write-locked unless aflags & 1 */
1596 afs_GetDCache(register struct vcache *avc, afs_size_t abyte,
1597 register struct vrequest *areq, afs_size_t * aoffset,
1598 afs_size_t * alen, int aflags)
1600 register afs_int32 i, code, shortcut;
1601 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1602 register afs_int32 adjustsize = 0;
1608 afs_size_t maxGoodLength; /* amount of good data at server */
1609 afs_size_t Position = 0;
1610 afs_int32 size, tlen; /* size of segment to transfer */
1611 struct afs_FetchOutput *tsmall = 0;
1612 register struct dcache *tdc;
1613 register struct osi_file *file;
1614 register struct afs_conn *tc;
1616 struct server *newCallback = NULL;
1617 char setNewCallback;
1618 char setVcacheStatus;
1619 char doVcacheUpdate;
1621 int doAdjustSize = 0;
1622 int doReallyAdjustSize = 0;
1623 int overWriteWholeChunk = 0;
1626 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1627 int fromReplica; /*Are we reading from a replica? */
1628 int numFetchLoops; /*# times around the fetch/analyze loop */
1629 #endif /* AFS_NOSTATS */
1631 AFS_STATCNT(afs_GetDCache);
1635 setLocks = aflags & 1;
1638 * Determine the chunk number and offset within the chunk corresponding
1639 * to the desired byte.
1641 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1644 chunk = AFS_CHUNK(abyte);
1647 /* come back to here if we waited for the cache to drain. */
1650 setNewCallback = setVcacheStatus = 0;
1654 ObtainWriteLock(&avc->lock, 616);
1656 ObtainReadLock(&avc->lock);
1661 * avc->lock(R) if setLocks && !slowPass
1662 * avc->lock(W) if !setLocks || slowPass
1667 /* check hints first! (might could use bcmp or some such...) */
1668 if ((tdc = avc->dchint)) {
1672 * The locking order between afs_xdcache and dcache lock matters.
1673 * The hint dcache entry could be anywhere, even on the free list.
1674 * Locking afs_xdcache ensures that noone is trying to pull dcache
1675 * entries from the free list, and thereby assuming them to be not
1676 * referenced and not locked.
1678 ObtainReadLock(&afs_xdcache);
1679 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1681 if (dcLocked && (tdc->index != NULLIDX)
1682 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
1683 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1684 /* got the right one. It might not be the right version, and it
1685 * might be fetching, but it's the right dcache entry.
1687 /* All this code should be integrated better with what follows:
1688 * I can save a good bit more time under a write lock if I do..
1690 ObtainWriteLock(&tdc->tlock, 603);
1692 ReleaseWriteLock(&tdc->tlock);
1694 ReleaseReadLock(&afs_xdcache);
1697 if (hsame(tdc->f.versionNo, avc->f.m.DataVersion)
1698 && !(tdc->dflags & DFFetching)) {
1700 afs_stats_cmperf.dcacheHits++;
1701 ObtainWriteLock(&afs_xdcache, 559);
1702 QRemove(&tdc->lruq);
1703 QAdd(&afs_DLRU, &tdc->lruq);
1704 ReleaseWriteLock(&afs_xdcache);
1707 * avc->lock(R) if setLocks && !slowPass
1708 * avc->lock(W) if !setLocks || slowPass
1715 ReleaseSharedLock(&tdc->lock);
1716 ReleaseReadLock(&afs_xdcache);
1724 * avc->lock(R) if setLocks && !slowPass
1725 * avc->lock(W) if !setLocks || slowPass
1726 * tdc->lock(S) if tdc
1729 if (!tdc) { /* If the hint wasn't the right dcache entry */
1731 * Hash on the [fid, chunk] and get the corresponding dcache index
1732 * after write-locking the dcache.
1737 * avc->lock(R) if setLocks && !slowPass
1738 * avc->lock(W) if !setLocks || slowPass
1741 i = DCHash(&avc->f.fid, chunk);
1742 /* check to make sure our space is fine */
1743 afs_MaybeWakeupTruncateDaemon();
1745 ObtainWriteLock(&afs_xdcache, 280);
1747 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1748 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1749 tdc = afs_GetDSlot(index, NULL);
1750 ReleaseReadLock(&tdc->tlock);
1753 * avc->lock(R) if setLocks && !slowPass
1754 * avc->lock(W) if !setLocks || slowPass
1757 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1758 /* Move it up in the beginning of the list */
1759 if (afs_dchashTbl[i] != index) {
1760 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1761 afs_dcnextTbl[index] = afs_dchashTbl[i];
1762 afs_dchashTbl[i] = index;
1764 ReleaseWriteLock(&afs_xdcache);
1765 ObtainSharedLock(&tdc->lock, 606);
1766 break; /* leaving refCount high for caller */
1772 index = afs_dcnextTbl[index];
1776 * If we didn't find the entry, we'll create one.
1778 if (index == NULLIDX) {
1781 * avc->lock(R) if setLocks
1782 * avc->lock(W) if !setLocks
1785 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1786 avc, ICL_TYPE_INT32, chunk);
1788 /* Make sure there is a free dcache entry for us to use */
1789 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1792 avc->f.states |= CDCLock;
1793 /* just need slots */
1794 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1796 avc->f.states &= ~CDCLock;
1797 if (afs_discardDCList != NULLIDX
1798 || afs_freeDCList != NULLIDX)
1800 /* If we can't get space for 5 mins we give up and panic */
1801 if (++downDCount > 300) {
1802 #if defined(AFS_CACHE_BYPASS)
1803 afs_warn("GetDCache calling osi_Panic: No space in five minutes.\n downDCount: %d\n aoffset: %d alen: %d\n", downDCount, aoffset, alen);
1805 osi_Panic("getdcache");
1807 ReleaseWriteLock(&afs_xdcache);
1810 * avc->lock(R) if setLocks
1811 * avc->lock(W) if !setLocks
1813 afs_osi_Wait(1000, 0, 0);
1818 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
1821 * Now add to the two hash chains - note that i is still set
1822 * from the above DCHash call.
1824 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1825 afs_dchashTbl[i] = tdc->index;
1826 i = DVHash(&avc->f.fid);
1827 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1828 afs_dvhashTbl[i] = tdc->index;
1829 tdc->dflags = DFEntryMod;
1831 afs_MaybeWakeupTruncateDaemon();
1832 ReleaseWriteLock(&afs_xdcache);
1833 ConvertWToSLock(&tdc->lock);
1838 /* vcache->dcache hint failed */
1841 * avc->lock(R) if setLocks && !slowPass
1842 * avc->lock(W) if !setLocks || slowPass
1845 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1846 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
1847 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
1848 hgetlo(avc->f.m.DataVersion));
1850 * Here we have the entry in tdc, with its refCount incremented.
1851 * Note: we don't use the S-lock on avc; it costs concurrency when
1852 * storing a file back to the server.
1856 * Not a newly created file so we need to check the file's length and
1857 * compare data versions since someone could have changed the data or we're
1858 * reading a file written elsewhere. We only want to bypass doing no-op
1859 * read rpcs on newly created files (dv of 0) since only then we guarantee
1860 * that this chunk's data hasn't been filled by another client.
1862 size = AFS_CHUNKSIZE(abyte);
1863 if (aflags & 4) /* called from write */
1865 else /* called from read */
1866 tlen = tdc->validPos - abyte;
1867 Position = AFS_CHUNKTOBASE(chunk);
1868 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
1869 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
1870 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
1871 ICL_HANDLE_OFFSET(Position));
1872 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
1874 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
1875 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
1876 overWriteWholeChunk = 1;
1877 if (doAdjustSize || overWriteWholeChunk) {
1878 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1880 #ifdef AFS_SGI64_ENV
1883 #else /* AFS_SGI64_ENV */
1886 #endif /* AFS_SGI64_ENV */
1887 #else /* AFS_SGI_ENV */
1890 #endif /* AFS_SGI_ENV */
1891 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
1892 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1893 #if defined(AFS_SUN5_ENV)
1894 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
1896 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
1898 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1899 !hsame(avc->f.m.DataVersion, tdc->f.versionNo))
1900 doReallyAdjustSize = 1;
1902 if (doReallyAdjustSize || overWriteWholeChunk) {
1903 /* no data in file to read at this position */
1904 UpgradeSToWLock(&tdc->lock, 607);
1905 file = afs_CFileOpen(&tdc->f.inode);
1906 afs_CFileTruncate(file, 0);
1907 afs_CFileClose(file);
1908 afs_AdjustSize(tdc, 0);
1909 hset(tdc->f.versionNo, avc->f.m.DataVersion);
1910 tdc->dflags |= DFEntryMod;
1912 ConvertWToSLock(&tdc->lock);
1917 * We must read in the whole chunk if the version number doesn't
1921 /* don't need data, just a unique dcache entry */
1922 ObtainWriteLock(&afs_xdcache, 608);
1923 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1924 hadd32(afs_indexCounter, 1);
1925 ReleaseWriteLock(&afs_xdcache);
1927 updateV2DC(setLocks, avc, tdc, 553);
1928 if (vType(avc) == VDIR)
1931 *aoffset = AFS_CHUNKOFFSET(abyte);
1932 if (tdc->validPos < abyte)
1933 *alen = (afs_size_t) 0;
1935 *alen = tdc->validPos - abyte;
1936 ReleaseSharedLock(&tdc->lock);
1939 ReleaseWriteLock(&avc->lock);
1941 ReleaseReadLock(&avc->lock);
1943 return tdc; /* check if we're done */
1948 * avc->lock(R) if setLocks && !slowPass
1949 * avc->lock(W) if !setLocks || slowPass
1952 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
1954 setNewCallback = setVcacheStatus = 0;
1958 * avc->lock(R) if setLocks && !slowPass
1959 * avc->lock(W) if !setLocks || slowPass
1962 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
1964 * Version number mismatch.
1967 * If we are disconnected, then we can't do much of anything
1968 * because the data doesn't match the file.
1970 if (AFS_IS_DISCONNECTED) {
1971 ReleaseSharedLock(&tdc->lock);
1974 ReleaseWriteLock(&avc->lock);
1976 ReleaseReadLock(&avc->lock);
1978 /* Flush the Dcache */
1983 UpgradeSToWLock(&tdc->lock, 609);
1986 * If data ever existed for this vnode, and this is a text object,
1987 * do some clearing. Now, you'd think you need only do the flush
1988 * when VTEXT is on, but VTEXT is turned off when the text object
1989 * is freed, while pages are left lying around in memory marked
1990 * with this vnode. If we would reactivate (create a new text
1991 * object from) this vnode, we could easily stumble upon some of
1992 * these old pages in pagein. So, we always flush these guys.
1993 * Sun has a wonderful lack of useful invariants in this system.
1995 * avc->flushDV is the data version # of the file at the last text
1996 * flush. Clearly, at least, we don't have to flush the file more
1997 * often than it changes
1999 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2001 * By here, the cache entry is always write-locked. We can
2002 * deadlock if we call osi_Flush with the cache entry locked...
2003 * Unlock the dcache too.
2005 ReleaseWriteLock(&tdc->lock);
2006 if (setLocks && !slowPass)
2007 ReleaseReadLock(&avc->lock);
2009 ReleaseWriteLock(&avc->lock);
2013 * Call osi_FlushPages in open, read/write, and map, since it
2014 * is too hard here to figure out if we should lock the
2017 if (setLocks && !slowPass)
2018 ObtainReadLock(&avc->lock);
2020 ObtainWriteLock(&avc->lock, 66);
2021 ObtainWriteLock(&tdc->lock, 610);
2026 * avc->lock(R) if setLocks && !slowPass
2027 * avc->lock(W) if !setLocks || slowPass
2031 /* Watch for standard race condition around osi_FlushText */
2032 if (hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
2033 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2034 afs_stats_cmperf.dcacheHits++;
2035 ConvertWToSLock(&tdc->lock);
2039 /* Sleep here when cache needs to be drained. */
2040 if (setLocks && !slowPass
2041 && (afs_blocksUsed >
2042 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2043 /* Make sure truncate daemon is running */
2044 afs_MaybeWakeupTruncateDaemon();
2045 ObtainWriteLock(&tdc->tlock, 614);
2046 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2047 ReleaseWriteLock(&tdc->tlock);
2048 ReleaseWriteLock(&tdc->lock);
2049 ReleaseReadLock(&avc->lock);
2050 while ((afs_blocksUsed - afs_blocksDiscarded) >
2051 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2052 afs_WaitForCacheDrain = 1;
2053 afs_osi_Sleep(&afs_WaitForCacheDrain);
2055 afs_MaybeFreeDiscardedDCache();
2056 /* need to check if someone else got the chunk first. */
2057 goto RetryGetDCache;
2060 /* Do not fetch data beyond truncPos. */
2061 maxGoodLength = avc->f.m.Length;
2062 if (avc->f.truncPos < maxGoodLength)
2063 maxGoodLength = avc->f.truncPos;
2064 Position = AFS_CHUNKBASE(abyte);
2065 if (vType(avc) == VDIR) {
2066 size = avc->f.m.Length;
2067 if (size > tdc->f.chunkBytes) {
2068 /* pre-reserve space for file */
2069 afs_AdjustSize(tdc, size);
2071 size = 999999999; /* max size for transfer */
2073 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2074 /* don't read past end of good data on server */
2075 if (Position + size > maxGoodLength)
2076 size = maxGoodLength - Position;
2078 size = 0; /* Handle random races */
2079 if (size > tdc->f.chunkBytes) {
2080 /* pre-reserve space for file */
2081 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2082 /* max size for transfer still in size */
2085 if (afs_mariner && !tdc->f.chunk)
2086 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2088 * Right now, we only have one tool, and it's a hammer. So, we
2089 * fetch the whole file.
2091 DZap(tdc); /* pages in cache may be old */
2092 file = afs_CFileOpen(&tdc->f.inode);
2093 afs_RemoveVCB(&avc->f.fid);
2094 tdc->f.states |= DWriting;
2095 tdc->dflags |= DFFetching;
2096 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2097 if (tdc->mflags & DFFetchReq) {
2098 tdc->mflags &= ~DFFetchReq;
2099 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2100 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2101 __FILE__, ICL_TYPE_INT32, __LINE__,
2102 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2106 (struct afs_FetchOutput *)osi_AllocLargeSpace(sizeof(struct afs_FetchOutput));
2107 setVcacheStatus = 0;
2110 * Remember if we are doing the reading from a replicated volume,
2111 * and how many times we've zipped around the fetch/analyze loop.
2113 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2115 accP = &(afs_stats_cmfullperf.accessinf);
2117 (accP->replicatedRefs)++;
2119 (accP->unreplicatedRefs)++;
2120 #endif /* AFS_NOSTATS */
2121 /* this is a cache miss */
2122 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2123 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2124 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2127 afs_stats_cmperf.dcacheMisses++;
2130 * Dynamic root support: fetch data from local memory.
2132 if (afs_IsDynroot(avc)) {
2136 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2138 dynrootDir += Position;
2139 dynrootLen -= Position;
2140 if (size > dynrootLen)
2144 code = afs_CFileWrite(file, 0, dynrootDir, size);
2152 tdc->validPos = Position + size;
2153 afs_CFileTruncate(file, size); /* prune it */
2154 } else if (afs_IsDynrootMount(avc)) {
2158 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2160 dynrootDir += Position;
2161 dynrootLen -= Position;
2162 if (size > dynrootLen)
2166 code = afs_CFileWrite(file, 0, dynrootDir, size);
2174 tdc->validPos = Position + size;
2175 afs_CFileTruncate(file, size); /* prune it */
2178 * Not a dynamic vnode: do the real fetch.
2183 * avc->lock(R) if setLocks && !slowPass
2184 * avc->lock(W) if !setLocks || slowPass
2188 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
2193 (accP->numReplicasAccessed)++;
2195 #endif /* AFS_NOSTATS */
2196 if (!setLocks || slowPass) {
2197 avc->callback = tc->srvr->server;
2199 newCallback = tc->srvr->server;
2203 code = afs_CacheFetchProc(tc, file, Position, tdc,
2209 /* callback could have been broken (or expired) in a race here,
2210 * but we return the data anyway. It's as good as we knew about
2211 * when we started. */
2213 * validPos is updated by CacheFetchProc, and can only be
2214 * modifed under a dcache write lock, which we've blocked out
2216 size = tdc->validPos - Position; /* actual segment size */
2219 afs_CFileTruncate(file, size); /* prune it */
2221 if (!setLocks || slowPass) {
2222 ObtainWriteLock(&afs_xcbhash, 453);
2223 afs_DequeueCallback(avc);
2224 avc->f.states &= ~(CStatd | CUnique);
2225 avc->callback = NULL;
2226 ReleaseWriteLock(&afs_xcbhash);
2227 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2228 osi_dnlc_purgedp(avc);
2230 /* Something lost. Forget about performance, and go
2231 * back with a vcache write lock.
2233 afs_CFileTruncate(file, 0);
2234 afs_AdjustSize(tdc, 0);
2235 afs_CFileClose(file);
2236 osi_FreeLargeSpace(tsmall);
2238 ReleaseWriteLock(&tdc->lock);
2241 ReleaseReadLock(&avc->lock);
2243 goto RetryGetDCache;
2247 } while (afs_Analyze
2248 (tc, code, &avc->f.fid, areq,
2249 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2253 * avc->lock(R) if setLocks && !slowPass
2254 * avc->lock(W) if !setLocks || slowPass
2260 * In the case of replicated access, jot down info on the number of
2261 * attempts it took before we got through or gave up.
2264 if (numFetchLoops <= 1)
2265 (accP->refFirstReplicaOK)++;
2266 if (numFetchLoops > accP->maxReplicasPerRef)
2267 accP->maxReplicasPerRef = numFetchLoops;
2269 #endif /* AFS_NOSTATS */
2271 tdc->dflags &= ~DFFetching;
2272 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2273 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2274 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2275 tdc, ICL_TYPE_INT32, tdc->dflags);
2276 if (avc->execsOrWriters == 0)
2277 tdc->f.states &= ~DWriting;
2279 /* now, if code != 0, we have an error and should punt.
2280 * note that we have the vcache write lock, either because
2281 * !setLocks or slowPass.
2284 afs_CFileTruncate(file, 0);
2285 afs_AdjustSize(tdc, 0);
2286 afs_CFileClose(file);
2287 ZapDCE(tdc); /* sets DFEntryMod */
2288 if (vType(avc) == VDIR) {
2291 tdc->f.states &= ~(DRO|DBackup|DRW);
2292 afs_DCMoveBucket(tdc, 0, 0);
2293 ReleaseWriteLock(&tdc->lock);
2295 if (!afs_IsDynroot(avc)) {
2296 ObtainWriteLock(&afs_xcbhash, 454);
2297 afs_DequeueCallback(avc);
2298 avc->f.states &= ~(CStatd | CUnique);
2299 ReleaseWriteLock(&afs_xcbhash);
2300 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2301 osi_dnlc_purgedp(avc);
2304 * avc->lock(W); assert(!setLocks || slowPass)
2306 osi_Assert(!setLocks || slowPass);
2312 /* otherwise we copy in the just-fetched info */
2313 afs_CFileClose(file);
2314 afs_AdjustSize(tdc, size); /* new size */
2316 * Copy appropriate fields into vcache. Status is
2317 * copied later where we selectively acquire the
2318 * vcache write lock.
2321 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2323 setVcacheStatus = 1;
2324 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2325 tsmall->OutStatus.DataVersion);
2326 tdc->dflags |= DFEntryMod;
2327 afs_indexFlags[tdc->index] |= IFEverUsed;
2328 ConvertWToSLock(&tdc->lock);
2329 } /*Data version numbers don't match */
2332 * Data version numbers match.
2334 afs_stats_cmperf.dcacheHits++;
2335 } /*Data version numbers match */
2337 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2341 * avc->lock(R) if setLocks && !slowPass
2342 * avc->lock(W) if !setLocks || slowPass
2343 * tdc->lock(S) if tdc
2347 * See if this was a reference to a file in the local cell.
2349 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2350 afs_stats_cmperf.dlocalAccesses++;
2352 afs_stats_cmperf.dremoteAccesses++;
2354 /* Fix up LRU info */
2357 ObtainWriteLock(&afs_xdcache, 602);
2358 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2359 hadd32(afs_indexCounter, 1);
2360 ReleaseWriteLock(&afs_xdcache);
2362 /* return the data */
2363 if (vType(avc) == VDIR)
2366 *aoffset = AFS_CHUNKOFFSET(abyte);
2367 *alen = (tdc->f.chunkBytes - *aoffset);
2368 ReleaseSharedLock(&tdc->lock);
2373 * avc->lock(R) if setLocks && !slowPass
2374 * avc->lock(W) if !setLocks || slowPass
2377 /* Fix up the callback and status values in the vcache */
2379 if (setLocks && !slowPass) {
2382 * This is our dirty little secret to parallel fetches.
2383 * We don't write-lock the vcache while doing the fetch,
2384 * but potentially we'll need to update the vcache after
2385 * the fetch is done.
2387 * Drop the read lock and try to re-obtain the write
2388 * lock. If the vcache still has the same DV, it's
2389 * ok to go ahead and install the new data.
2391 afs_hyper_t currentDV, statusDV;
2393 hset(currentDV, avc->f.m.DataVersion);
2395 if (setNewCallback && avc->callback != newCallback)
2399 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2400 tsmall->OutStatus.DataVersion);
2402 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2404 if (setVcacheStatus && !hsame(currentDV, statusDV))
2408 ReleaseReadLock(&avc->lock);
2410 if (doVcacheUpdate) {
2411 ObtainWriteLock(&avc->lock, 615);
2412 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2413 /* We lose. Someone will beat us to it. */
2415 ReleaseWriteLock(&avc->lock);
2420 /* With slow pass, we've already done all the updates */
2422 ReleaseWriteLock(&avc->lock);
2425 /* Check if we need to perform any last-minute fixes with a write-lock */
2426 if (!setLocks || doVcacheUpdate) {
2428 avc->callback = newCallback;
2429 if (tsmall && setVcacheStatus)
2430 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2432 ReleaseWriteLock(&avc->lock);
2436 osi_FreeLargeSpace(tsmall);
2439 } /*afs_GetDCache */
2443 * afs_WriteThroughDSlots
2446 * Sweep through the dcache slots and write out any modified
2447 * in-memory data back on to our caching store.
2453 * The afs_xdcache is write-locked through this whole affair.
2456 afs_WriteThroughDSlots(void)
2458 register struct dcache *tdc;
2459 register afs_int32 i, touchedit = 0;
2461 struct afs_q DirtyQ, *tq;
2463 AFS_STATCNT(afs_WriteThroughDSlots);
2466 * Because of lock ordering, we can't grab dcache locks while
2467 * holding afs_xdcache. So we enter xdcache, get a reference
2468 * for every dcache entry, and exit xdcache.
2470 ObtainWriteLock(&afs_xdcache, 283);
2472 for (i = 0; i < afs_cacheFiles; i++) {
2473 tdc = afs_indexTable[i];
2475 /* Grab tlock in case the existing refcount isn't zero */
2476 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2477 ObtainWriteLock(&tdc->tlock, 623);
2479 ReleaseWriteLock(&tdc->tlock);
2481 QAdd(&DirtyQ, &tdc->dirty);
2484 ReleaseWriteLock(&afs_xdcache);
2487 * Now, for each dcache entry we found, check if it's dirty.
2488 * If so, get write-lock, get afs_xdcache, which protects
2489 * afs_cacheInodep, and flush it. Don't forget to put back
2493 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2495 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2497 if (tdc->dflags & DFEntryMod) {
2500 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2502 /* Now that we have the write lock, double-check */
2503 if (wrLock && (tdc->dflags & DFEntryMod)) {
2504 tdc->dflags &= ~DFEntryMod;
2505 ObtainWriteLock(&afs_xdcache, 620);
2506 afs_WriteDCache(tdc, 1);
2507 ReleaseWriteLock(&afs_xdcache);
2511 ReleaseWriteLock(&tdc->lock);
2517 ObtainWriteLock(&afs_xdcache, 617);
2518 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2519 /* Touch the file to make sure that the mtime on the file is kept
2520 * up-to-date to avoid losing cached files on cold starts because
2521 * their mtime seems old...
2523 struct afs_fheader theader;
2525 theader.magic = AFS_FHMAGIC;
2526 theader.firstCSize = AFS_FIRSTCSIZE;
2527 theader.otherCSize = AFS_OTHERCSIZE;
2528 theader.version = AFS_CI_VERSION;
2529 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2531 ReleaseWriteLock(&afs_xdcache);
2538 * Return a pointer to an freshly initialized dcache entry using
2539 * a memory-based cache. The tlock will be read-locked.
2542 * aslot : Dcache slot to look at.
2543 * tmpdc : Ptr to dcache entry.
2546 * Must be called with afs_xdcache write-locked.
2550 afs_MemGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2552 register struct dcache *tdc;
2555 AFS_STATCNT(afs_MemGetDSlot);
2556 if (CheckLock(&afs_xdcache) != -1)
2557 osi_Panic("getdslot nolock");
2558 if (aslot < 0 || aslot >= afs_cacheFiles)
2559 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2560 tdc = afs_indexTable[aslot];
2562 QRemove(&tdc->lruq); /* move to queue head */
2563 QAdd(&afs_DLRU, &tdc->lruq);
2564 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2565 ObtainWriteLock(&tdc->tlock, 624);
2567 ConvertWToRLock(&tdc->tlock);
2570 if (tmpdc == NULL) {
2571 if (!afs_freeDSList)
2572 afs_GetDownDSlot(4);
2573 if (!afs_freeDSList) {
2574 /* none free, making one is better than a panic */
2575 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2576 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2577 #ifdef KERNEL_HAVE_PIN
2578 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2581 tdc = afs_freeDSList;
2582 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2585 tdc->dflags = 0; /* up-to-date, not in free q */
2587 QAdd(&afs_DLRU, &tdc->lruq);
2588 if (tdc->lruq.prev == &tdc->lruq)
2589 osi_Panic("lruq 3");
2595 /* initialize entry */
2596 tdc->f.fid.Cell = 0;
2597 tdc->f.fid.Fid.Volume = 0;
2599 hones(tdc->f.versionNo);
2600 tdc->f.inode.mem = aslot;
2601 tdc->dflags |= DFEntryMod;
2604 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2607 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2608 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2609 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2612 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2613 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2614 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2615 ObtainReadLock(&tdc->tlock);
2618 afs_indexTable[aslot] = tdc;
2621 } /*afs_MemGetDSlot */
2623 unsigned int last_error = 0, lasterrtime = 0;
2629 * Return a pointer to an freshly initialized dcache entry using
2630 * a UFS-based disk cache. The dcache tlock will be read-locked.
2633 * aslot : Dcache slot to look at.
2634 * tmpdc : Ptr to dcache entry.
2637 * afs_xdcache lock write-locked.
2640 afs_UFSGetDSlot(register afs_int32 aslot, register struct dcache *tmpdc)
2642 register afs_int32 code;
2643 register struct dcache *tdc;
2647 AFS_STATCNT(afs_UFSGetDSlot);
2648 if (CheckLock(&afs_xdcache) != -1)
2649 osi_Panic("getdslot nolock");
2650 if (aslot < 0 || aslot >= afs_cacheFiles)
2651 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2652 tdc = afs_indexTable[aslot];
2654 QRemove(&tdc->lruq); /* move to queue head */
2655 QAdd(&afs_DLRU, &tdc->lruq);
2656 /* Grab tlock in case refCount != 0 */
2657 ObtainWriteLock(&tdc->tlock, 625);
2659 ConvertWToRLock(&tdc->tlock);
2662 /* otherwise we should read it in from the cache file */
2664 * If we weren't passed an in-memory region to place the file info,
2665 * we have to allocate one.
2667 if (tmpdc == NULL) {
2668 if (!afs_freeDSList)
2669 afs_GetDownDSlot(4);
2670 if (!afs_freeDSList) {
2671 /* none free, making one is better than a panic */
2672 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2673 tdc = (struct dcache *)afs_osi_Alloc(sizeof(struct dcache));
2674 #ifdef KERNEL_HAVE_PIN
2675 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2678 tdc = afs_freeDSList;
2679 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2682 tdc->dflags = 0; /* up-to-date, not in free q */
2684 QAdd(&afs_DLRU, &tdc->lruq);
2685 if (tdc->lruq.prev == &tdc->lruq)
2686 osi_Panic("lruq 3");
2693 * Seek to the aslot'th entry and read it in.
2696 afs_osi_Read(afs_cacheInodep,
2697 sizeof(struct fcache) * aslot +
2698 sizeof(struct afs_fheader), (char *)(&tdc->f),
2699 sizeof(struct fcache));
2701 if (code != sizeof(struct fcache))
2703 if (!afs_CellNumValid(tdc->f.fid.Cell))
2707 tdc->f.fid.Cell = 0;
2708 tdc->f.fid.Fid.Volume = 0;
2710 hones(tdc->f.versionNo);
2711 tdc->dflags |= DFEntryMod;
2712 #if defined(KERNEL_HAVE_UERROR)
2713 last_error = getuerror();
2715 lasterrtime = osi_Time();
2716 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2717 tdc->f.states &= ~(DRO|DBackup|DRW);
2718 afs_DCMoveBucket(tdc, 0, 0);
2721 if (tdc->f.states & DRO) {
2722 afs_DCMoveBucket(tdc, 0, 2);
2723 } else if (tdc->f.states & DBackup) {
2724 afs_DCMoveBucket(tdc, 0, 1);
2726 afs_DCMoveBucket(tdc, 0, 1);
2732 if (tdc->f.chunk >= 0)
2733 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
2738 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2739 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2740 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2743 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2744 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2745 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2746 ObtainReadLock(&tdc->tlock);
2749 * If we didn't read into a temporary dcache region, update the
2750 * slot pointer table.
2753 afs_indexTable[aslot] = tdc;
2756 } /*afs_UFSGetDSlot */
2761 * Write a particular dcache entry back to its home in the
2764 * \param adc Pointer to the dcache entry to write.
2765 * \param atime If true, set the modtime on the file to the current time.
2767 * \note Environment:
2768 * Must be called with the afs_xdcache lock at least read-locked,
2769 * and dcache entry at least read-locked.
2770 * The reference count is not changed.
2774 afs_WriteDCache(register struct dcache *adc, int atime)
2776 register afs_int32 code;
2778 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2780 AFS_STATCNT(afs_WriteDCache);
2781 osi_Assert(WriteLocked(&afs_xdcache));
2783 adc->f.modTime = osi_Time();
2785 * Seek to the right dcache slot and write the in-memory image out to disk.
2787 afs_cellname_write();
2789 afs_osi_Write(afs_cacheInodep,
2790 sizeof(struct fcache) * adc->index +
2791 sizeof(struct afs_fheader), (char *)(&adc->f),
2792 sizeof(struct fcache));
2793 if (code != sizeof(struct fcache))
2801 * Wake up users of a particular file waiting for stores to take
2804 * \param avc Ptr to related vcache entry.
2806 * \note Environment:
2807 * Nothing interesting.
2810 afs_wakeup(register struct vcache *avc)
2813 register struct brequest *tb;
2815 AFS_STATCNT(afs_wakeup);
2816 for (i = 0; i < NBRS; i++, tb++) {
2817 /* if request is valid and for this file, we've found it */
2818 if (tb->refCount > 0 && avc == tb->vc) {
2821 * If CSafeStore is on, then we don't awaken the guy
2822 * waiting for the store until the whole store has finished.
2823 * Otherwise, we do it now. Note that if CSafeStore is on,
2824 * the BStore routine actually wakes up the user, instead
2826 * I think this is redundant now because this sort of thing
2827 * is already being handled by the higher-level code.
2829 if ((avc->f.states & CSafeStore) == 0) {
2831 tb->flags |= BUVALID;
2832 if (tb->flags & BUWAIT) {
2833 tb->flags &= ~BUWAIT;
2845 * Given a file name and inode, set up that file to be an
2846 * active member in the AFS cache. This also involves checking
2847 * the usability of its data.
2849 * \param afile Name of the cache file to initialize.
2850 * \param ainode Inode of the file.
2852 * \note Environment:
2853 * This function is called only during initialization.
2856 afs_InitCacheFile(char *afile, ino_t ainode)
2858 register afs_int32 code;
2861 struct osi_file *tfile;
2862 struct osi_stat tstat;
2863 register struct dcache *tdc;
2865 AFS_STATCNT(afs_InitCacheFile);
2866 index = afs_stats_cmperf.cacheNumEntries;
2867 if (index >= afs_cacheFiles)
2870 ObtainWriteLock(&afs_xdcache, 282);
2871 tdc = afs_GetDSlot(index, NULL);
2872 ReleaseReadLock(&tdc->tlock);
2873 ReleaseWriteLock(&afs_xdcache);
2875 ObtainWriteLock(&tdc->lock, 621);
2876 ObtainWriteLock(&afs_xdcache, 622);
2878 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
2880 ReleaseWriteLock(&afs_xdcache);
2881 ReleaseWriteLock(&tdc->lock);
2886 /* Add any other 'complex' inode types here ... */
2887 #if defined(UKERNEL) || !defined(LINUX_USE_FH)
2888 tdc->f.inode.ufs = ainode;
2890 osi_Panic("Can't init cache with inode numbers when complex inodes are "
2895 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
2897 tfile = osi_UFSOpen(&tdc->f.inode);
2898 code = afs_osi_Stat(tfile, &tstat);
2900 osi_Panic("initcachefile stat");
2903 * If file size doesn't match the cache info file, it's probably bad.
2905 if (tdc->f.chunkBytes != tstat.size)
2907 tdc->f.chunkBytes = 0;
2910 * If file changed within T (120?) seconds of cache info file, it's
2911 * probably bad. In addition, if slot changed within last T seconds,
2912 * the cache info file may be incorrectly identified, and so slot
2915 if (cacheInfoModTime < tstat.mtime + 120)
2917 if (cacheInfoModTime < tdc->f.modTime + 120)
2919 /* In case write through is behind, make sure cache items entry is
2920 * at least as new as the chunk.
2922 if (tdc->f.modTime < tstat.mtime)
2925 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
2926 if (tstat.size != 0)
2927 osi_UFSTruncate(tfile, 0);
2928 tdc->f.states &= ~(DRO|DBackup|DRW);
2929 afs_DCMoveBucket(tdc, 0, 0);
2930 /* put entry in free cache slot list */
2931 afs_dvnextTbl[tdc->index] = afs_freeDCList;
2932 afs_freeDCList = index;
2934 afs_indexFlags[index] |= IFFree;
2935 afs_indexUnique[index] = 0;
2938 * We must put this entry in the appropriate hash tables.
2939 * Note that i is still set from the above DCHash call
2941 code = DCHash(&tdc->f.fid, tdc->f.chunk);
2942 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
2943 afs_dchashTbl[code] = tdc->index;
2944 code = DVHash(&tdc->f.fid);
2945 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
2946 afs_dvhashTbl[code] = tdc->index;
2947 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
2949 /* has nontrivial amt of data */
2950 afs_indexFlags[index] |= IFEverUsed;
2951 afs_stats_cmperf.cacheFilesReused++;
2953 * Initialize index times to file's mod times; init indexCounter
2956 hset32(afs_indexTimes[index], tstat.atime);
2957 if (hgetlo(afs_indexCounter) < tstat.atime) {
2958 hset32(afs_indexCounter, tstat.atime);
2960 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
2961 } /*File is not bad */
2963 osi_UFSClose(tfile);
2964 tdc->f.states &= ~DWriting;
2965 tdc->dflags &= ~DFEntryMod;
2966 /* don't set f.modTime; we're just cleaning up */
2967 afs_WriteDCache(tdc, 0);
2968 ReleaseWriteLock(&afs_xdcache);
2969 ReleaseWriteLock(&tdc->lock);
2971 afs_stats_cmperf.cacheNumEntries++;
2976 /*Max # of struct dcache's resident at any time*/
2978 * If 'dchint' is enabled then in-memory dcache min is increased because of
2984 * Initialize dcache related variables.
2994 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
2996 register struct dcache *tdp;
3000 afs_freeDCList = NULLIDX;
3001 afs_discardDCList = NULLIDX;
3002 afs_freeDCCount = 0;
3003 afs_freeDSList = NULL;
3004 hzero(afs_indexCounter);
3006 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3012 if (achunk < 0 || achunk > 30)
3013 achunk = 13; /* Use default */
3014 AFS_SETCHUNKSIZE(achunk);
3020 if (aflags & AFSCALL_INIT_MEMCACHE) {
3022 * Use a memory cache instead of a disk cache
3024 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3025 afs_cacheType = &afs_MemCacheOps;
3026 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3027 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3028 /* ablocks is reported in 1K blocks */
3029 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3031 printf("afsd: memory cache too large for available memory.\n");
3032 printf("afsd: AFS files cannot be accessed.\n\n");
3034 afiles = ablocks = 0;
3036 printf("Memory cache: Allocating %d dcache entries...",
3039 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3040 afs_cacheType = &afs_UfsCacheOps;
3043 if (aDentries > 512)
3044 afs_dhashsize = 2048;
3045 /* initialize hash tables */
3047 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3049 (afs_int32 *) afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3050 for (i = 0; i < afs_dhashsize; i++) {
3051 afs_dvhashTbl[i] = NULLIDX;
3052 afs_dchashTbl[i] = NULLIDX;
3054 afs_dvnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3055 afs_dcnextTbl = (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_int32));
3056 for (i = 0; i < afiles; i++) {
3057 afs_dvnextTbl[i] = NULLIDX;
3058 afs_dcnextTbl[i] = NULLIDX;
3061 /* Allocate and zero the pointer array to the dcache entries */
3062 afs_indexTable = (struct dcache **)
3063 afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3064 memset(afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3066 (afs_hyper_t *) afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3067 memset(afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3069 (afs_int32 *) afs_osi_Alloc(afiles * sizeof(afs_uint32));
3070 memset(afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3071 afs_indexFlags = (u_char *) afs_osi_Alloc(afiles * sizeof(u_char));
3072 memset(afs_indexFlags, 0, afiles * sizeof(char));
3074 /* Allocate and thread the struct dcache entries themselves */
3075 tdp = afs_Initial_freeDSList =
3076 (struct dcache *)afs_osi_Alloc(aDentries * sizeof(struct dcache));
3077 memset(tdp, 0, aDentries * sizeof(struct dcache));
3078 #ifdef KERNEL_HAVE_PIN
3079 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3080 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3081 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3082 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3083 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3084 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3085 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3086 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3087 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3090 afs_freeDSList = &tdp[0];
3091 for (i = 0; i < aDentries - 1; i++) {
3092 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3093 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3094 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3095 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3097 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3098 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3099 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3100 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3102 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3103 afs_cacheBlocks = ablocks;
3104 afs_ComputeCacheParms(); /* compute parms based on cache size */
3106 afs_dcentries = aDentries;
3108 afs_stats_cmperf.cacheBucket0_Discarded =
3109 afs_stats_cmperf.cacheBucket1_Discarded =
3110 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3116 * Shuts down the cache.
3120 shutdown_dcache(void)
3124 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3125 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3126 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3127 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3128 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3129 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3130 afs_osi_Free(afs_Initial_freeDSList,
3131 afs_dcentries * sizeof(struct dcache));
3132 #ifdef KERNEL_HAVE_PIN
3133 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3134 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3135 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3136 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3137 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3138 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3139 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3143 for (i = 0; i < afs_dhashsize; i++) {
3144 afs_dvhashTbl[i] = NULLIDX;
3145 afs_dchashTbl[i] = NULLIDX;
3148 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3149 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3151 afs_blocksUsed = afs_dcentries = 0;
3152 afs_stats_cmperf.cacheBucket0_Discarded =
3153 afs_stats_cmperf.cacheBucket1_Discarded =
3154 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3155 hzero(afs_indexCounter);
3157 afs_freeDCCount = 0;
3158 afs_freeDCList = NULLIDX;
3159 afs_discardDCList = NULLIDX;
3160 afs_freeDSList = afs_Initial_freeDSList = 0;
3162 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3168 * Get a dcache ready for writing, respecting the current cache size limits
3170 * len is required because afs_GetDCache with flag == 4 expects the length
3171 * field to be filled. It decides from this whether it's necessary to fetch
3172 * data into the chunk before writing or not (when the whole chunk is
3175 * \param avc The vcache to fetch a dcache for
3176 * \param filePos The start of the section to be written
3177 * \param len The length of the section to be written
3181 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3182 * must be released and afs_PutDCache() called to free dcache.
3185 * \note avc->lock must be held on entry. Function may release and reobtain
3186 * avc->lock and GLOCK.
3190 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3191 afs_size_t len, struct vrequest *areq,
3193 struct dcache *tdc = NULL;
3196 /* read the cached info */
3198 tdc = afs_FindDCache(avc, filePos);
3200 ObtainWriteLock(&tdc->lock, 657);
3201 } else if (afs_blocksUsed >
3202 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3203 tdc = afs_FindDCache(avc, filePos);
3205 ObtainWriteLock(&tdc->lock, 658);
3206 if (!hsame(tdc->f.versionNo, avc->f.m.DataVersion)
3207 || (tdc->dflags & DFFetching)) {
3208 ReleaseWriteLock(&tdc->lock);
3214 afs_MaybeWakeupTruncateDaemon();
3215 while (afs_blocksUsed >
3216 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3217 ReleaseWriteLock(&avc->lock);
3218 if (afs_blocksUsed - afs_blocksDiscarded >
3219 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3220 afs_WaitForCacheDrain = 1;
3221 afs_osi_Sleep(&afs_WaitForCacheDrain);
3223 afs_MaybeFreeDiscardedDCache();
3224 afs_MaybeWakeupTruncateDaemon();
3225 ObtainWriteLock(&avc->lock, 509);
3227 avc->f.states |= CDirty;
3228 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3230 ObtainWriteLock(&tdc->lock, 659);
3233 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3235 ObtainWriteLock(&tdc->lock, 660);
3238 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3239 afs_stats_cmperf.cacheCurrDirtyChunks++;
3240 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3242 if (!(tdc->f.states & DWriting)) {
3243 /* don't mark entry as mod if we don't have to */
3244 tdc->f.states |= DWriting;
3245 tdc->dflags |= DFEntryMod;
3251 #if defined(AFS_DISCON_ENV)
3254 * Make a shadow copy of a dir's dcache. It's used for disconnected
3255 * operations like remove/create/rename to keep the original directory data.
3256 * On reconnection, we can diff the original data with the server and get the
3257 * server changes and with the local data to get the local changes.
3259 * \param avc The dir vnode.
3260 * \param adc The dir dcache.
3262 * \return 0 for success.
3264 * \note The vcache entry must be write locked.
3265 * \note The dcache entry must be read locked.
3268 afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3270 int i, code, ret_code = 0, written, trans_size;
3271 struct dcache *new_dc = NULL;
3272 struct osi_file *tfile_src, *tfile_dst;
3273 struct VenusFid shadow_fid;
3276 /* Is this a dir? */
3277 if (vType(avc) != VDIR)
3280 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3283 /* Generate a fid for the shadow dir. */
3284 shadow_fid.Cell = avc->f.fid.Cell;
3285 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3286 afs_GenShadowFid(&shadow_fid);
3288 ObtainWriteLock(&afs_xdcache, 716);
3290 /* Get a fresh dcache. */
3291 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3293 ObtainReadLock(&adc->mflock);
3295 /* Set up the new fid. */
3296 /* Copy interesting data from original dir dcache. */
3297 new_dc->mflags = adc->mflags;
3298 new_dc->dflags = adc->dflags;
3299 new_dc->f.modTime = adc->f.modTime;
3300 new_dc->f.versionNo = adc->f.versionNo;
3301 new_dc->f.states = adc->f.states;
3302 new_dc->f.chunk= adc->f.chunk;
3303 new_dc->f.chunkBytes = adc->f.chunkBytes;
3305 ReleaseReadLock(&adc->mflock);
3307 /* Now add to the two hash chains */
3308 i = DCHash(&shadow_fid, 0);
3309 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[i];
3310 afs_dchashTbl[i] = new_dc->index;
3312 i = DVHash(&shadow_fid);
3313 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[i];
3314 afs_dvhashTbl[i] = new_dc->index;
3316 ReleaseWriteLock(&afs_xdcache);
3318 /* Alloc a 4k block. */
3319 data = (char *) afs_osi_Alloc(4096);
3321 printf("afs_MakeShadowDir: could not alloc data\n");
3326 /* Open the files. */
3327 tfile_src = afs_CFileOpen(&adc->f.inode);
3328 tfile_dst = afs_CFileOpen(&new_dc->f.inode);
3330 /* And now copy dir dcache data into this dcache,
3334 while (written < adc->f.chunkBytes) {
3335 trans_size = adc->f.chunkBytes - written;
3336 if (trans_size > 4096)
3339 /* Read a chunk from the dcache. */
3340 code = afs_CFileRead(tfile_src, written, data, trans_size);
3341 if (code < trans_size) {
3346 /* Write it to the new dcache. */
3347 code = afs_CFileWrite(tfile_dst, written, data, trans_size);
3348 if (code < trans_size) {
3353 written+=trans_size;
3356 afs_CFileClose(tfile_dst);
3357 afs_CFileClose(tfile_src);
3359 afs_osi_Free(data, 4096);
3361 ReleaseWriteLock(&new_dc->lock);
3362 afs_PutDCache(new_dc);
3365 ObtainWriteLock(&afs_xvcache, 763);
3366 ObtainWriteLock(&afs_disconDirtyLock, 765);
3367 QAdd(&afs_disconShadow, &avc->shadowq);
3369 ReleaseWriteLock(&afs_disconDirtyLock);
3370 ReleaseWriteLock(&afs_xvcache);
3372 avc->f.shadow.vnode = shadow_fid.Fid.Vnode;
3373 avc->f.shadow.unique = shadow_fid.Fid.Unique;
3381 * Delete the dcaches of a shadow dir.
3383 * \param avc The vcache containing the shadow fid.
3385 * \note avc must be write locked.
3388 afs_DeleteShadowDir(struct vcache *avc)
3391 struct VenusFid shadow_fid;
3393 shadow_fid.Cell = avc->f.fid.Cell;
3394 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3395 shadow_fid.Fid.Vnode = avc->f.shadow.vnode;
3396 shadow_fid.Fid.Unique = avc->f.shadow.unique;
3398 tdc = afs_FindDCacheByFid(&shadow_fid);
3400 afs_HashOutDCache(tdc, 1);
3401 afs_DiscardDCache(tdc);
3404 avc->f.shadow.vnode = avc->f.shadow.unique = 0;
3405 ObtainWriteLock(&afs_disconDirtyLock, 708);
3406 QRemove(&avc->shadowq);
3407 ReleaseWriteLock(&afs_disconDirtyLock);
3408 afs_PutVCache(avc); /* Because we held it when we added to the queue */
3412 * Populate a dcache with empty chunks up to a given file size,
3413 * used before extending a file in order to avoid 'holes' which
3414 * we can't access in disconnected mode.
3416 * \param avc The vcache which is being extended (locked)
3417 * \param alen The new length of the file
3421 afs_PopulateDCache(struct vcache *avc, afs_size_t apos, struct vrequest *areq)
3424 afs_size_t len, offset;
3425 afs_int32 start, end;
3427 /* We're doing this to deal with the situation where we extend
3428 * by writing after lseek()ing past the end of the file . If that
3429 * extension skips chunks, then those chunks won't be created, and
3430 * GetDCache will assume that they have to be fetched from the server.
3431 * So, for each chunk between the current file position, and the new
3432 * length we GetDCache for that chunk.
3435 if (AFS_CHUNK(apos) == 0 || apos <= avc->f.m.Length)
3438 if (avc->f.m.Length == 0)
3441 start = AFS_CHUNK(avc->f.m.Length)+1;
3443 end = AFS_CHUNK(apos);
3446 len = AFS_CHUNKTOSIZE(start);
3447 tdc = afs_GetDCache(avc, AFS_CHUNKTOBASE(start), areq, &offset, &len, 4);