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->refCount == 1)
681 ReleaseReadLock(&tdc->tlock);
685 for (i = 0; i < victimPtr; i++) {
686 /* q is first elt in dcache entry */
688 /* now, since we're dropping the afs_xdcache lock below, we
689 * have to verify, before proceeding, that there are no other
690 * references to this dcache entry, even now. Note that we
691 * compare with 1, since we bumped it above when we called
692 * afs_GetValidDSlot to preserve the entry's identity.
694 if (tdc && tdc->refCount == 1) {
695 unsigned char chunkFlags;
696 afs_size_t tchunkoffset = 0;
698 /* xdcache is lower than the xvcache lock */
699 ReleaseWriteLock(&afs_xdcache);
700 ObtainReadLock(&afs_xvcache);
701 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
702 ReleaseReadLock(&afs_xvcache);
703 ObtainWriteLock(&afs_xdcache, 527);
705 if (tdc->refCount > 1)
708 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
709 chunkFlags = afs_indexFlags[tdc->index];
710 if (((phase & 1) == 0) && osi_Active(tvc))
712 if (((phase & 1) == 1) && osi_Active(tvc)
713 && (tvc->f.states & CDCLock)
714 && (chunkFlags & IFAnyPages))
716 if (chunkFlags & IFDataMod)
718 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
719 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
720 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
721 ICL_HANDLE_OFFSET(tchunkoffset));
723 #if defined(AFS_SUN5_ENV)
725 * Now we try to invalidate pages. We do this only for
726 * Solaris. For other platforms, it's OK to recycle a
727 * dcache entry out from under a page, because the strategy
728 * function can call afs_GetDCache().
730 if (!skip && (chunkFlags & IFAnyPages)) {
733 ReleaseWriteLock(&afs_xdcache);
734 ObtainWriteLock(&tvc->vlock, 543);
735 if (!QEmpty(&tvc->multiPage)) {
736 if (phase < 3 || osi_VM_MultiPageConflict(tvc, tdc)) {
741 /* block locking pages */
742 tvc->vstates |= VPageCleaning;
743 /* block getting new pages */
745 ReleaseWriteLock(&tvc->vlock);
746 /* One last recheck */
747 ObtainWriteLock(&afs_xdcache, 333);
748 chunkFlags = afs_indexFlags[tdc->index];
749 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
750 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
751 && (chunkFlags & IFAnyPages))) {
753 ReleaseWriteLock(&afs_xdcache);
756 ReleaseWriteLock(&afs_xdcache);
758 code = osi_VM_GetDownD(tvc, tdc);
760 ObtainWriteLock(&afs_xdcache, 269);
761 /* we actually removed all pages, clean and dirty */
763 afs_indexFlags[tdc->index] &=
764 ~(IFDirtyPages | IFAnyPages);
767 ReleaseWriteLock(&afs_xdcache);
769 ObtainWriteLock(&tvc->vlock, 544);
770 if (--tvc->activeV == 0
771 && (tvc->vstates & VRevokeWait)) {
772 tvc->vstates &= ~VRevokeWait;
773 afs_osi_Wakeup((char *)&tvc->vstates);
776 if (tvc->vstates & VPageCleaning) {
777 tvc->vstates &= ~VPageCleaning;
778 afs_osi_Wakeup((char *)&tvc->vstates);
781 ReleaseWriteLock(&tvc->vlock);
783 #endif /* AFS_SUN5_ENV */
785 ReleaseWriteLock(&afs_xdcache);
788 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
789 ObtainWriteLock(&afs_xdcache, 528);
790 if (afs_indexFlags[tdc->index] &
791 (IFDataMod | IFDirtyPages | IFAnyPages))
793 if (tdc->refCount > 1)
796 #if defined(AFS_SUN5_ENV)
798 /* no vnode, so IFDirtyPages is spurious (we don't
799 * sweep dcaches on vnode recycling, so we can have
800 * DIRTYPAGES set even when all pages are gone). Just
802 * Hold vcache lock to prevent vnode from being
803 * created while we're clearing IFDirtyPages.
805 afs_indexFlags[tdc->index] &=
806 ~(IFDirtyPages | IFAnyPages);
810 /* skip this guy and mark him as recently used */
811 afs_indexFlags[tdc->index] |= IFFlag;
812 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
813 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
814 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
815 ICL_HANDLE_OFFSET(tchunkoffset));
817 /* flush this dude from the data cache and reclaim;
818 * first, make sure no one will care that we damage
819 * it, by removing it from all hash tables. Then,
820 * melt it down for parts. Note that any concurrent
821 * (new possibility!) calls to GetDownD won't touch
822 * this guy because his reference count is > 0. */
823 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
824 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
825 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
826 ICL_HANDLE_OFFSET(tchunkoffset));
827 AFS_STATCNT(afs_gget);
828 afs_HashOutDCache(tdc, 1);
829 if (tdc->f.chunkBytes != 0) {
833 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
838 afs_DiscardDCache(tdc);
843 j = 1; /* we reclaimed at least one victim */
848 } /* end of for victims loop */
851 /* Phase is 0 and no one was found, so try phase 1 (ignore
852 * osi_Active flag) */
855 for (i = 0; i < afs_cacheFiles; i++)
856 /* turn off all flags */
857 afs_indexFlags[i] &= ~IFFlag;
860 /* found no one in phases 0-5, we're hosed */
864 } /* big while loop */
872 * Remove adc from any hash tables that would allow it to be located
873 * again by afs_FindDCache or afs_GetDCache.
875 * \param adc Pointer to dcache entry to remove from hash tables.
877 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
881 afs_HashOutDCache(struct dcache *adc, int zap)
885 AFS_STATCNT(afs_glink);
887 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
889 /* if this guy is in the hash table, pull him out */
890 if (adc->f.fid.Fid.Volume != 0) {
891 /* remove entry from first hash chains */
892 i = DCHash(&adc->f.fid, adc->f.chunk);
893 us = afs_dchashTbl[i];
894 if (us == adc->index) {
895 /* first dude in the list */
896 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
898 /* somewhere on the chain */
899 while (us != NULLIDX) {
900 if (afs_dcnextTbl[us] == adc->index) {
901 /* found item pointing at the one to delete */
902 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
905 us = afs_dcnextTbl[us];
908 osi_Panic("dcache hc");
910 /* remove entry from *other* hash chain */
911 i = DVHash(&adc->f.fid);
912 us = afs_dvhashTbl[i];
913 if (us == adc->index) {
914 /* first dude in the list */
915 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
917 /* somewhere on the chain */
918 while (us != NULLIDX) {
919 if (afs_dvnextTbl[us] == adc->index) {
920 /* found item pointing at the one to delete */
921 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
924 us = afs_dvnextTbl[us];
927 osi_Panic("dcache hv");
932 /* prevent entry from being found on a reboot (it is already out of
933 * the hash table, but after a crash, we just look at fid fields of
934 * stable (old) entries).
936 adc->f.fid.Fid.Volume = 0; /* invalid */
938 /* mark entry as modified */
939 adc->dflags |= DFEntryMod;
944 } /*afs_HashOutDCache */
947 * Flush the given dcache entry, pulling it from hash chains
948 * and truncating the associated cache file.
950 * \param adc Ptr to dcache entry to flush.
953 * This routine must be called with the afs_xdcache lock held
957 afs_FlushDCache(struct dcache *adc)
959 AFS_STATCNT(afs_FlushDCache);
961 * Bump the number of cache files flushed.
963 afs_stats_cmperf.cacheFlushes++;
965 /* remove from all hash tables */
966 afs_HashOutDCache(adc, 1);
968 /* Free its space; special case null operation, since truncate operation
969 * in UFS is slow even in this case, and this allows us to pre-truncate
970 * these files at more convenient times with fewer locks set
971 * (see afs_GetDownD).
973 if (adc->f.chunkBytes != 0) {
974 afs_DiscardDCache(adc);
975 afs_MaybeWakeupTruncateDaemon();
980 if (afs_WaitForCacheDrain) {
981 if (afs_blocksUsed <=
982 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
983 afs_WaitForCacheDrain = 0;
984 afs_osi_Wakeup(&afs_WaitForCacheDrain);
987 } /*afs_FlushDCache */
991 * Put a dcache entry on the free dcache entry list.
993 * \param adc dcache entry to free.
995 * \note Environment: called with afs_xdcache lock write-locked.
998 afs_FreeDCache(struct dcache *adc)
1000 /* Thread on free list, update free list count and mark entry as
1001 * freed in its indexFlags element. Also, ensure DCache entry gets
1002 * written out (set DFEntryMod).
1005 afs_dvnextTbl[adc->index] = afs_freeDCList;
1006 afs_freeDCList = adc->index;
1008 afs_indexFlags[adc->index] |= IFFree;
1009 adc->dflags |= DFEntryMod;
1011 if (afs_WaitForCacheDrain) {
1012 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1013 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1014 afs_WaitForCacheDrain = 0;
1015 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1018 } /* afs_FreeDCache */
1021 * Discard the cache element by moving it to the discardDCList.
1022 * This puts the cache element into a quasi-freed state, where
1023 * the space may be reused, but the file has not been truncated.
1025 * \note Major Assumptions Here:
1026 * Assumes that frag size is an integral power of two, less one,
1027 * and that this is a two's complement machine. I don't
1028 * know of any filesystems which violate this assumption...
1030 * \param adr Ptr to dcache entry.
1032 * \note Environment:
1033 * Must be called with afs_xdcache write-locked.
1037 afs_DiscardDCache(struct dcache *adc)
1041 AFS_STATCNT(afs_DiscardDCache);
1043 osi_Assert(adc->refCount == 1);
1045 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1046 afs_blocksDiscarded += size;
1047 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1049 afs_dvnextTbl[adc->index] = afs_discardDCList;
1050 afs_discardDCList = adc->index;
1051 afs_discardDCCount++;
1053 adc->f.fid.Fid.Volume = 0;
1054 adc->dflags |= DFEntryMod;
1055 afs_indexFlags[adc->index] |= IFDiscarded;
1057 if (afs_WaitForCacheDrain) {
1058 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1059 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1060 afs_WaitForCacheDrain = 0;
1061 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1065 } /*afs_DiscardDCache */
1068 * Free the next element on the list of discarded cache elements.
1071 afs_FreeDiscardedDCache(void)
1074 struct osi_file *tfile;
1077 AFS_STATCNT(afs_FreeDiscardedDCache);
1079 ObtainWriteLock(&afs_xdcache, 510);
1080 if (!afs_blocksDiscarded) {
1081 ReleaseWriteLock(&afs_xdcache);
1086 * Get an entry from the list of discarded cache elements
1088 tdc = afs_GetNewDSlot(afs_discardDCList);
1089 osi_Assert(tdc->refCount == 1);
1090 ReleaseReadLock(&tdc->tlock);
1092 afs_discardDCList = afs_dvnextTbl[tdc->index];
1093 afs_dvnextTbl[tdc->index] = NULLIDX;
1094 afs_discardDCCount--;
1095 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1096 afs_blocksDiscarded -= size;
1097 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1098 /* We can lock because we just took it off the free list */
1099 ObtainWriteLock(&tdc->lock, 626);
1100 ReleaseWriteLock(&afs_xdcache);
1103 * Truncate the element to reclaim its space
1105 tfile = afs_CFileOpen(&tdc->f.inode);
1106 afs_CFileTruncate(tfile, 0);
1107 afs_CFileClose(tfile);
1108 afs_AdjustSize(tdc, 0);
1109 afs_DCMoveBucket(tdc, 0, 0);
1112 * Free the element we just truncated
1114 ObtainWriteLock(&afs_xdcache, 511);
1115 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1116 afs_FreeDCache(tdc);
1117 tdc->f.states &= ~(DRO|DBackup|DRW);
1118 ReleaseWriteLock(&tdc->lock);
1120 ReleaseWriteLock(&afs_xdcache);
1124 * Free as many entries from the list of discarded cache elements
1125 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1130 afs_MaybeFreeDiscardedDCache(void)
1133 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1135 while (afs_blocksDiscarded
1136 && (afs_blocksUsed >
1137 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1138 afs_FreeDiscardedDCache();
1144 * Try to free up a certain number of disk slots.
1146 * \param anumber Targeted number of disk slots to free up.
1148 * \note Environment:
1149 * Must be called with afs_xdcache write-locked.
1153 afs_GetDownDSlot(int anumber)
1155 struct afs_q *tq, *nq;
1160 AFS_STATCNT(afs_GetDownDSlot);
1161 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1162 osi_Panic("diskless getdowndslot");
1164 if (CheckLock(&afs_xdcache) != -1)
1165 osi_Panic("getdowndslot nolock");
1167 /* decrement anumber first for all dudes in free list */
1168 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1171 return; /* enough already free */
1173 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1175 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1176 nq = QPrev(tq); /* in case we remove it */
1177 if (tdc->refCount == 0) {
1178 if ((ix = tdc->index) == NULLIDX)
1179 osi_Panic("getdowndslot");
1180 /* pull the entry out of the lruq and put it on the free list */
1181 QRemove(&tdc->lruq);
1183 /* write-through if modified */
1184 if (tdc->dflags & DFEntryMod) {
1185 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1187 * ask proxy to do this for us - we don't have the stack space
1189 while (tdc->dflags & DFEntryMod) {
1192 s = SPLOCK(afs_sgibklock);
1193 if (afs_sgibklist == NULL) {
1194 /* if slot is free, grab it. */
1195 afs_sgibklist = tdc;
1196 SV_SIGNAL(&afs_sgibksync);
1198 /* wait for daemon to (start, then) finish. */
1199 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1203 tdc->dflags &= ~DFEntryMod;
1204 afs_WriteDCache(tdc, 1);
1208 /* finally put the entry in the free list */
1209 afs_indexTable[ix] = NULL;
1210 afs_indexFlags[ix] &= ~IFEverUsed;
1211 tdc->index = NULLIDX;
1212 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1213 afs_freeDSList = tdc;
1217 } /*afs_GetDownDSlot */
1224 * Increment the reference count on a disk cache entry,
1225 * which already has a non-zero refcount. In order to
1226 * increment the refcount of a zero-reference entry, you
1227 * have to hold afs_xdcache.
1230 * adc : Pointer to the dcache entry to increment.
1233 * Nothing interesting.
1236 afs_RefDCache(struct dcache *adc)
1238 ObtainWriteLock(&adc->tlock, 627);
1239 if (adc->refCount < 0)
1240 osi_Panic("RefDCache: negative refcount");
1242 ReleaseWriteLock(&adc->tlock);
1251 * Decrement the reference count on a disk cache entry.
1254 * ad : Ptr to the dcache entry to decrement.
1257 * Nothing interesting.
1260 afs_PutDCache(struct dcache *adc)
1262 AFS_STATCNT(afs_PutDCache);
1263 ObtainWriteLock(&adc->tlock, 276);
1264 if (adc->refCount <= 0)
1265 osi_Panic("putdcache");
1267 ReleaseWriteLock(&adc->tlock);
1276 * Try to discard all data associated with this file from the
1280 * avc : Pointer to the cache info for the file.
1283 * Both pvnLock and lock are write held.
1286 afs_TryToSmush(struct vcache *avc, afs_ucred_t *acred, int sync)
1291 AFS_STATCNT(afs_TryToSmush);
1292 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1293 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1294 sync = 1; /* XX Temp testing XX */
1296 #if defined(AFS_SUN5_ENV)
1297 ObtainWriteLock(&avc->vlock, 573);
1298 avc->activeV++; /* block new getpages */
1299 ReleaseWriteLock(&avc->vlock);
1302 /* Flush VM pages */
1303 osi_VM_TryToSmush(avc, acred, sync);
1306 * Get the hash chain containing all dce's for this fid
1308 i = DVHash(&avc->f.fid);
1309 ObtainWriteLock(&afs_xdcache, 277);
1310 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1311 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1312 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1313 int releaseTlock = 1;
1314 tdc = afs_GetValidDSlot(index);
1315 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1317 if ((afs_indexFlags[index] & IFDataMod) == 0
1318 && tdc->refCount == 1) {
1319 ReleaseReadLock(&tdc->tlock);
1321 afs_FlushDCache(tdc);
1324 afs_indexTable[index] = 0;
1327 ReleaseReadLock(&tdc->tlock);
1331 #if defined(AFS_SUN5_ENV)
1332 ObtainWriteLock(&avc->vlock, 545);
1333 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1334 avc->vstates &= ~VRevokeWait;
1335 afs_osi_Wakeup((char *)&avc->vstates);
1337 ReleaseWriteLock(&avc->vlock);
1339 ReleaseWriteLock(&afs_xdcache);
1341 * It's treated like a callback so that when we do lookups we'll
1342 * invalidate the unique bit if any
1343 * trytoSmush occured during the lookup call
1349 * afs_DCacheMissingChunks
1352 * Given the cached info for a file, return the number of chunks that
1353 * are not available from the dcache.
1356 * avc: Pointer to the (held) vcache entry to look in.
1359 * The number of chunks which are not currently cached.
1362 * The vcache entry is held upon entry.
1366 afs_DCacheMissingChunks(struct vcache *avc)
1369 afs_size_t totalLength = 0;
1370 afs_uint32 totalChunks = 0;
1373 totalLength = avc->f.m.Length;
1374 if (avc->f.truncPos < totalLength)
1375 totalLength = avc->f.truncPos;
1377 /* Length is 0, no chunk missing. */
1378 if (totalLength == 0)
1381 /* If totalLength is a multiple of chunksize, the last byte appears
1382 * as being part of the next chunk, which does not exist.
1383 * Decrementing totalLength by one fixes that.
1386 totalChunks = (AFS_CHUNK(totalLength) + 1);
1388 /* If we're a directory, we only ever have one chunk, regardless of
1389 * the size of the dir.
1391 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1395 printf("Should have %d chunks for %u bytes\n",
1396 totalChunks, (totalLength + 1));
1398 i = DVHash(&avc->f.fid);
1399 ObtainWriteLock(&afs_xdcache, 1001);
1400 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1401 i = afs_dvnextTbl[index];
1402 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1403 tdc = afs_GetValidDSlot(index);
1404 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1407 ReleaseReadLock(&tdc->tlock);
1411 ReleaseWriteLock(&afs_xdcache);
1413 /*printf("Missing %d chunks\n", totalChunks);*/
1415 return (totalChunks);
1422 * Given the cached info for a file and a byte offset into the
1423 * file, make sure the dcache entry for that file and containing
1424 * the given byte is available, returning it to our caller.
1427 * avc : Pointer to the (held) vcache entry to look in.
1428 * abyte : Which byte we want to get to.
1431 * Pointer to the dcache entry covering the file & desired byte,
1432 * or NULL if not found.
1435 * The vcache entry is held upon entry.
1439 afs_FindDCache(struct vcache *avc, afs_size_t abyte)
1443 struct dcache *tdc = NULL;
1445 AFS_STATCNT(afs_FindDCache);
1446 chunk = AFS_CHUNK(abyte);
1449 * Hash on the [fid, chunk] and get the corresponding dcache index
1450 * after write-locking the dcache.
1452 i = DCHash(&avc->f.fid, chunk);
1453 ObtainWriteLock(&afs_xdcache, 278);
1454 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1455 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1456 tdc = afs_GetValidDSlot(index);
1457 ReleaseReadLock(&tdc->tlock);
1458 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1459 break; /* leaving refCount high for caller */
1463 index = afs_dcnextTbl[index];
1465 if (index != NULLIDX) {
1466 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1467 hadd32(afs_indexCounter, 1);
1468 ReleaseWriteLock(&afs_xdcache);
1471 ReleaseWriteLock(&afs_xdcache);
1473 } /*afs_FindDCache */
1477 * Get a fresh dcache from the free or discarded list.
1479 * \param avc Who's dcache is this going to be?
1480 * \param chunk The position where it will be placed in.
1481 * \param lock How are locks held.
1482 * \param ashFid If this dcache going to be used for a shadow dir,
1485 * \note Required locks:
1487 * - avc (R if (lock & 1) set and W otherwise)
1488 * \note It write locks the new dcache. The caller must unlock it.
1490 * \return The new dcache.
1493 afs_AllocDCache(struct vcache *avc, afs_int32 chunk, afs_int32 lock,
1494 struct VenusFid *ashFid)
1496 struct dcache *tdc = NULL;
1497 afs_uint32 size = 0;
1498 struct osi_file *file;
1500 if (afs_discardDCList == NULLIDX
1501 || ((lock & 2) && afs_freeDCList != NULLIDX)) {
1503 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1504 tdc = afs_GetNewDSlot(afs_freeDCList);
1505 osi_Assert(tdc->refCount == 1);
1506 ReleaseReadLock(&tdc->tlock);
1507 ObtainWriteLock(&tdc->lock, 604);
1508 afs_freeDCList = afs_dvnextTbl[tdc->index];
1511 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1512 tdc = afs_GetNewDSlot(afs_discardDCList);
1513 osi_Assert(tdc->refCount == 1);
1514 ReleaseReadLock(&tdc->tlock);
1515 ObtainWriteLock(&tdc->lock, 605);
1516 afs_discardDCList = afs_dvnextTbl[tdc->index];
1517 afs_discardDCCount--;
1519 ((tdc->f.chunkBytes +
1520 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1521 tdc->f.states &= ~(DRO|DBackup|DRW);
1522 afs_DCMoveBucket(tdc, size, 0);
1523 afs_blocksDiscarded -= size;
1524 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1526 /* Truncate the chunk so zeroes get filled properly */
1527 file = afs_CFileOpen(&tdc->f.inode);
1528 afs_CFileTruncate(file, 0);
1529 afs_CFileClose(file);
1530 afs_AdjustSize(tdc, 0);
1536 * avc->lock(R) if setLocks
1537 * avc->lock(W) if !setLocks
1543 * Fill in the newly-allocated dcache record.
1545 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1547 /* Use shadow fid if provided. */
1548 tdc->f.fid = *ashFid;
1550 /* Use normal vcache's fid otherwise. */
1551 tdc->f.fid = avc->f.fid;
1552 if (avc->f.states & CRO)
1553 tdc->f.states = DRO;
1554 else if (avc->f.states & CBackup)
1555 tdc->f.states = DBackup;
1557 tdc->f.states = DRW;
1558 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1559 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1561 hones(tdc->f.versionNo); /* invalid value */
1562 tdc->f.chunk = chunk;
1563 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1565 if (tdc->lruq.prev == &tdc->lruq)
1566 osi_Panic("lruq 1");
1575 * This function is called to obtain a reference to data stored in
1576 * the disk cache, locating a chunk of data containing the desired
1577 * byte and returning a reference to the disk cache entry, with its
1578 * reference count incremented.
1582 * avc : Ptr to a vcache entry (unlocked)
1583 * abyte : Byte position in the file desired
1584 * areq : Request structure identifying the requesting user.
1585 * aflags : Settings as follows:
1587 * 2 : Return after creating entry.
1588 * 4 : called from afs_vnop_write.c
1589 * *alen contains length of data to be written.
1591 * aoffset : Set to the offset within the chunk where the resident
1593 * alen : Set to the number of bytes of data after the desired
1594 * byte (including the byte itself) which can be read
1598 * The vcache entry pointed to by avc is unlocked upon entry.
1602 * Update the vnode-to-dcache hint if we can get the vnode lock
1603 * right away. Assumes dcache entry is at least read-locked.
1606 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1608 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1609 if (hsame(v->f.m.DataVersion, d->f.versionNo) && v->callback)
1612 ReleaseWriteLock(&v->lock);
1616 /* avc - Write-locked unless aflags & 1 */
1618 afs_GetDCache(struct vcache *avc, afs_size_t abyte,
1619 struct vrequest *areq, afs_size_t * aoffset,
1620 afs_size_t * alen, int aflags)
1622 afs_int32 i, code, shortcut;
1623 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1624 afs_int32 adjustsize = 0;
1630 afs_size_t maxGoodLength; /* amount of good data at server */
1631 afs_size_t Position = 0;
1632 afs_int32 size, tlen; /* size of segment to transfer */
1633 struct afs_FetchOutput *tsmall = 0;
1635 struct osi_file *file;
1636 struct afs_conn *tc;
1638 struct server *newCallback = NULL;
1639 char setNewCallback;
1640 char setVcacheStatus;
1641 char doVcacheUpdate;
1643 int doAdjustSize = 0;
1644 int doReallyAdjustSize = 0;
1645 int overWriteWholeChunk = 0;
1646 struct rx_connection *rxconn;
1649 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1650 int fromReplica; /*Are we reading from a replica? */
1651 int numFetchLoops; /*# times around the fetch/analyze loop */
1652 #endif /* AFS_NOSTATS */
1654 AFS_STATCNT(afs_GetDCache);
1658 setLocks = aflags & 1;
1661 * Determine the chunk number and offset within the chunk corresponding
1662 * to the desired byte.
1664 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1667 chunk = AFS_CHUNK(abyte);
1670 /* come back to here if we waited for the cache to drain. */
1673 setNewCallback = setVcacheStatus = 0;
1677 ObtainWriteLock(&avc->lock, 616);
1679 ObtainReadLock(&avc->lock);
1684 * avc->lock(R) if setLocks && !slowPass
1685 * avc->lock(W) if !setLocks || slowPass
1690 /* check hints first! (might could use bcmp or some such...) */
1691 if ((tdc = avc->dchint)) {
1695 * The locking order between afs_xdcache and dcache lock matters.
1696 * The hint dcache entry could be anywhere, even on the free list.
1697 * Locking afs_xdcache ensures that noone is trying to pull dcache
1698 * entries from the free list, and thereby assuming them to be not
1699 * referenced and not locked.
1701 ObtainReadLock(&afs_xdcache);
1702 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1704 if (dcLocked && (tdc->index != NULLIDX)
1705 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
1706 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1707 /* got the right one. It might not be the right version, and it
1708 * might be fetching, but it's the right dcache entry.
1710 /* All this code should be integrated better with what follows:
1711 * I can save a good bit more time under a write lock if I do..
1713 ObtainWriteLock(&tdc->tlock, 603);
1715 ReleaseWriteLock(&tdc->tlock);
1717 ReleaseReadLock(&afs_xdcache);
1720 if (hsame(tdc->f.versionNo, avc->f.m.DataVersion)
1721 && !(tdc->dflags & DFFetching)) {
1723 afs_stats_cmperf.dcacheHits++;
1724 ObtainWriteLock(&afs_xdcache, 559);
1725 QRemove(&tdc->lruq);
1726 QAdd(&afs_DLRU, &tdc->lruq);
1727 ReleaseWriteLock(&afs_xdcache);
1730 * avc->lock(R) if setLocks && !slowPass
1731 * avc->lock(W) if !setLocks || slowPass
1738 ReleaseSharedLock(&tdc->lock);
1739 ReleaseReadLock(&afs_xdcache);
1747 * avc->lock(R) if setLocks && !slowPass
1748 * avc->lock(W) if !setLocks || slowPass
1749 * tdc->lock(S) if tdc
1752 if (!tdc) { /* If the hint wasn't the right dcache entry */
1754 * Hash on the [fid, chunk] and get the corresponding dcache index
1755 * after write-locking the dcache.
1760 * avc->lock(R) if setLocks && !slowPass
1761 * avc->lock(W) if !setLocks || slowPass
1764 i = DCHash(&avc->f.fid, chunk);
1765 /* check to make sure our space is fine */
1766 afs_MaybeWakeupTruncateDaemon();
1768 ObtainWriteLock(&afs_xdcache, 280);
1770 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1771 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1772 tdc = afs_GetValidDSlot(index);
1773 ReleaseReadLock(&tdc->tlock);
1776 * avc->lock(R) if setLocks && !slowPass
1777 * avc->lock(W) if !setLocks || slowPass
1780 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1781 /* Move it up in the beginning of the list */
1782 if (afs_dchashTbl[i] != index) {
1783 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1784 afs_dcnextTbl[index] = afs_dchashTbl[i];
1785 afs_dchashTbl[i] = index;
1787 ReleaseWriteLock(&afs_xdcache);
1788 ObtainSharedLock(&tdc->lock, 606);
1789 break; /* leaving refCount high for caller */
1795 index = afs_dcnextTbl[index];
1799 * If we didn't find the entry, we'll create one.
1801 if (index == NULLIDX) {
1804 * avc->lock(R) if setLocks
1805 * avc->lock(W) if !setLocks
1808 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1809 avc, ICL_TYPE_INT32, chunk);
1811 /* Make sure there is a free dcache entry for us to use */
1812 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1815 avc->f.states |= CDCLock;
1816 /* just need slots */
1817 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1819 avc->f.states &= ~CDCLock;
1820 if (afs_discardDCList != NULLIDX
1821 || afs_freeDCList != NULLIDX)
1823 /* If we can't get space for 5 mins we give up and panic */
1824 if (++downDCount > 300) {
1825 osi_Panic("getdcache");
1827 ReleaseWriteLock(&afs_xdcache);
1830 * avc->lock(R) if setLocks
1831 * avc->lock(W) if !setLocks
1833 afs_osi_Wait(1000, 0, 0);
1838 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
1841 * Now add to the two hash chains - note that i is still set
1842 * from the above DCHash call.
1844 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1845 afs_dchashTbl[i] = tdc->index;
1846 i = DVHash(&avc->f.fid);
1847 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1848 afs_dvhashTbl[i] = tdc->index;
1849 tdc->dflags = DFEntryMod;
1851 afs_MaybeWakeupTruncateDaemon();
1852 ReleaseWriteLock(&afs_xdcache);
1853 ConvertWToSLock(&tdc->lock);
1858 /* vcache->dcache hint failed */
1861 * avc->lock(R) if setLocks && !slowPass
1862 * avc->lock(W) if !setLocks || slowPass
1865 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1866 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
1867 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
1868 hgetlo(avc->f.m.DataVersion));
1870 * Here we have the entry in tdc, with its refCount incremented.
1871 * Note: we don't use the S-lock on avc; it costs concurrency when
1872 * storing a file back to the server.
1876 * Not a newly created file so we need to check the file's length and
1877 * compare data versions since someone could have changed the data or we're
1878 * reading a file written elsewhere. We only want to bypass doing no-op
1879 * read rpcs on newly created files (dv of 0) since only then we guarantee
1880 * that this chunk's data hasn't been filled by another client.
1882 size = AFS_CHUNKSIZE(abyte);
1883 if (aflags & 4) /* called from write */
1885 else /* called from read */
1886 tlen = tdc->validPos - abyte;
1887 Position = AFS_CHUNKTOBASE(chunk);
1888 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
1889 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
1890 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
1891 ICL_HANDLE_OFFSET(Position));
1892 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
1894 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
1895 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
1896 overWriteWholeChunk = 1;
1897 if (doAdjustSize || overWriteWholeChunk) {
1898 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1900 #ifdef AFS_SGI64_ENV
1903 #else /* AFS_SGI64_ENV */
1906 #endif /* AFS_SGI64_ENV */
1907 #else /* AFS_SGI_ENV */
1910 #endif /* AFS_SGI_ENV */
1911 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
1912 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1913 #if defined(AFS_SUN5_ENV)
1914 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
1916 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
1918 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1919 !hsame(avc->f.m.DataVersion, tdc->f.versionNo))
1920 doReallyAdjustSize = 1;
1922 if (doReallyAdjustSize || overWriteWholeChunk) {
1923 /* no data in file to read at this position */
1924 UpgradeSToWLock(&tdc->lock, 607);
1925 file = afs_CFileOpen(&tdc->f.inode);
1926 afs_CFileTruncate(file, 0);
1927 afs_CFileClose(file);
1928 afs_AdjustSize(tdc, 0);
1929 hset(tdc->f.versionNo, avc->f.m.DataVersion);
1930 tdc->dflags |= DFEntryMod;
1932 ConvertWToSLock(&tdc->lock);
1937 * We must read in the whole chunk if the version number doesn't
1941 /* don't need data, just a unique dcache entry */
1942 ObtainWriteLock(&afs_xdcache, 608);
1943 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1944 hadd32(afs_indexCounter, 1);
1945 ReleaseWriteLock(&afs_xdcache);
1947 updateV2DC(setLocks, avc, tdc, 553);
1948 if (vType(avc) == VDIR)
1951 *aoffset = AFS_CHUNKOFFSET(abyte);
1952 if (tdc->validPos < abyte)
1953 *alen = (afs_size_t) 0;
1955 *alen = tdc->validPos - abyte;
1956 ReleaseSharedLock(&tdc->lock);
1959 ReleaseWriteLock(&avc->lock);
1961 ReleaseReadLock(&avc->lock);
1963 return tdc; /* check if we're done */
1968 * avc->lock(R) if setLocks && !slowPass
1969 * avc->lock(W) if !setLocks || slowPass
1972 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
1974 setNewCallback = setVcacheStatus = 0;
1978 * avc->lock(R) if setLocks && !slowPass
1979 * avc->lock(W) if !setLocks || slowPass
1982 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
1984 * Version number mismatch.
1987 * If we are disconnected, then we can't do much of anything
1988 * because the data doesn't match the file.
1990 if (AFS_IS_DISCONNECTED) {
1991 ReleaseSharedLock(&tdc->lock);
1994 ReleaseWriteLock(&avc->lock);
1996 ReleaseReadLock(&avc->lock);
1998 /* Flush the Dcache */
2003 UpgradeSToWLock(&tdc->lock, 609);
2006 * If data ever existed for this vnode, and this is a text object,
2007 * do some clearing. Now, you'd think you need only do the flush
2008 * when VTEXT is on, but VTEXT is turned off when the text object
2009 * is freed, while pages are left lying around in memory marked
2010 * with this vnode. If we would reactivate (create a new text
2011 * object from) this vnode, we could easily stumble upon some of
2012 * these old pages in pagein. So, we always flush these guys.
2013 * Sun has a wonderful lack of useful invariants in this system.
2015 * avc->flushDV is the data version # of the file at the last text
2016 * flush. Clearly, at least, we don't have to flush the file more
2017 * often than it changes
2019 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2021 * By here, the cache entry is always write-locked. We can
2022 * deadlock if we call osi_Flush with the cache entry locked...
2023 * Unlock the dcache too.
2025 ReleaseWriteLock(&tdc->lock);
2026 if (setLocks && !slowPass)
2027 ReleaseReadLock(&avc->lock);
2029 ReleaseWriteLock(&avc->lock);
2033 * Call osi_FlushPages in open, read/write, and map, since it
2034 * is too hard here to figure out if we should lock the
2037 if (setLocks && !slowPass)
2038 ObtainReadLock(&avc->lock);
2040 ObtainWriteLock(&avc->lock, 66);
2041 ObtainWriteLock(&tdc->lock, 610);
2046 * avc->lock(R) if setLocks && !slowPass
2047 * avc->lock(W) if !setLocks || slowPass
2051 /* Watch for standard race condition around osi_FlushText */
2052 if (hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
2053 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2054 afs_stats_cmperf.dcacheHits++;
2055 ConvertWToSLock(&tdc->lock);
2059 /* Sleep here when cache needs to be drained. */
2060 if (setLocks && !slowPass
2061 && (afs_blocksUsed >
2062 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2063 /* Make sure truncate daemon is running */
2064 afs_MaybeWakeupTruncateDaemon();
2065 ObtainWriteLock(&tdc->tlock, 614);
2066 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2067 ReleaseWriteLock(&tdc->tlock);
2068 ReleaseWriteLock(&tdc->lock);
2069 ReleaseReadLock(&avc->lock);
2070 while ((afs_blocksUsed - afs_blocksDiscarded) >
2071 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2072 afs_WaitForCacheDrain = 1;
2073 afs_osi_Sleep(&afs_WaitForCacheDrain);
2075 afs_MaybeFreeDiscardedDCache();
2076 /* need to check if someone else got the chunk first. */
2077 goto RetryGetDCache;
2080 /* Do not fetch data beyond truncPos. */
2081 maxGoodLength = avc->f.m.Length;
2082 if (avc->f.truncPos < maxGoodLength)
2083 maxGoodLength = avc->f.truncPos;
2084 Position = AFS_CHUNKBASE(abyte);
2085 if (vType(avc) == VDIR) {
2086 size = avc->f.m.Length;
2087 if (size > tdc->f.chunkBytes) {
2088 /* pre-reserve space for file */
2089 afs_AdjustSize(tdc, size);
2091 size = 999999999; /* max size for transfer */
2093 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2094 /* don't read past end of good data on server */
2095 if (Position + size > maxGoodLength)
2096 size = maxGoodLength - Position;
2098 size = 0; /* Handle random races */
2099 if (size > tdc->f.chunkBytes) {
2100 /* pre-reserve space for file */
2101 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2102 /* max size for transfer still in size */
2105 if (afs_mariner && !tdc->f.chunk)
2106 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2108 * Right now, we only have one tool, and it's a hammer. So, we
2109 * fetch the whole file.
2111 DZap(tdc); /* pages in cache may be old */
2112 file = afs_CFileOpen(&tdc->f.inode);
2113 afs_RemoveVCB(&avc->f.fid);
2114 tdc->f.states |= DWriting;
2115 tdc->dflags |= DFFetching;
2116 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2117 if (tdc->mflags & DFFetchReq) {
2118 tdc->mflags &= ~DFFetchReq;
2119 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2120 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2121 __FILE__, ICL_TYPE_INT32, __LINE__,
2122 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2126 (struct afs_FetchOutput *)osi_AllocLargeSpace(sizeof(struct afs_FetchOutput));
2127 setVcacheStatus = 0;
2130 * Remember if we are doing the reading from a replicated volume,
2131 * and how many times we've zipped around the fetch/analyze loop.
2133 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2135 accP = &(afs_stats_cmfullperf.accessinf);
2137 (accP->replicatedRefs)++;
2139 (accP->unreplicatedRefs)++;
2140 #endif /* AFS_NOSTATS */
2141 /* this is a cache miss */
2142 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2143 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2144 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2147 afs_stats_cmperf.dcacheMisses++;
2150 * Dynamic root support: fetch data from local memory.
2152 if (afs_IsDynroot(avc)) {
2156 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2158 dynrootDir += Position;
2159 dynrootLen -= Position;
2160 if (size > dynrootLen)
2164 code = afs_CFileWrite(file, 0, dynrootDir, size);
2172 tdc->validPos = Position + size;
2173 afs_CFileTruncate(file, size); /* prune it */
2174 } else if (afs_IsDynrootMount(avc)) {
2178 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2180 dynrootDir += Position;
2181 dynrootLen -= Position;
2182 if (size > dynrootLen)
2186 code = afs_CFileWrite(file, 0, dynrootDir, size);
2194 tdc->validPos = Position + size;
2195 afs_CFileTruncate(file, size); /* prune it */
2198 * Not a dynamic vnode: do the real fetch.
2203 * avc->lock(R) if setLocks && !slowPass
2204 * avc->lock(W) if !setLocks || slowPass
2208 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
2213 (accP->numReplicasAccessed)++;
2215 #endif /* AFS_NOSTATS */
2216 if (!setLocks || slowPass) {
2217 avc->callback = tc->parent->srvr->server;
2219 newCallback = tc->parent->srvr->server;
2223 code = afs_CacheFetchProc(tc, rxconn, file, Position, tdc,
2229 /* callback could have been broken (or expired) in a race here,
2230 * but we return the data anyway. It's as good as we knew about
2231 * when we started. */
2233 * validPos is updated by CacheFetchProc, and can only be
2234 * modifed under a dcache write lock, which we've blocked out
2236 size = tdc->validPos - Position; /* actual segment size */
2239 afs_CFileTruncate(file, size); /* prune it */
2241 if (!setLocks || slowPass) {
2242 ObtainWriteLock(&afs_xcbhash, 453);
2243 afs_DequeueCallback(avc);
2244 avc->f.states &= ~(CStatd | CUnique);
2245 avc->callback = NULL;
2246 ReleaseWriteLock(&afs_xcbhash);
2247 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2248 osi_dnlc_purgedp(avc);
2250 /* Something lost. Forget about performance, and go
2251 * back with a vcache write lock.
2253 afs_CFileTruncate(file, 0);
2254 afs_AdjustSize(tdc, 0);
2255 afs_CFileClose(file);
2256 osi_FreeLargeSpace(tsmall);
2258 ReleaseWriteLock(&tdc->lock);
2261 ReleaseReadLock(&avc->lock);
2263 goto RetryGetDCache;
2267 } while (afs_Analyze
2268 (tc, rxconn, code, &avc->f.fid, areq,
2269 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2273 * avc->lock(R) if setLocks && !slowPass
2274 * avc->lock(W) if !setLocks || slowPass
2280 * In the case of replicated access, jot down info on the number of
2281 * attempts it took before we got through or gave up.
2284 if (numFetchLoops <= 1)
2285 (accP->refFirstReplicaOK)++;
2286 if (numFetchLoops > accP->maxReplicasPerRef)
2287 accP->maxReplicasPerRef = numFetchLoops;
2289 #endif /* AFS_NOSTATS */
2291 tdc->dflags &= ~DFFetching;
2292 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2293 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2294 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2295 tdc, ICL_TYPE_INT32, tdc->dflags);
2296 if (avc->execsOrWriters == 0)
2297 tdc->f.states &= ~DWriting;
2299 /* now, if code != 0, we have an error and should punt.
2300 * note that we have the vcache write lock, either because
2301 * !setLocks or slowPass.
2304 afs_CFileTruncate(file, 0);
2305 afs_AdjustSize(tdc, 0);
2306 afs_CFileClose(file);
2307 ZapDCE(tdc); /* sets DFEntryMod */
2308 if (vType(avc) == VDIR) {
2311 tdc->f.states &= ~(DRO|DBackup|DRW);
2312 afs_DCMoveBucket(tdc, 0, 0);
2313 ReleaseWriteLock(&tdc->lock);
2315 if (!afs_IsDynroot(avc)) {
2316 ObtainWriteLock(&afs_xcbhash, 454);
2317 afs_DequeueCallback(avc);
2318 avc->f.states &= ~(CStatd | CUnique);
2319 ReleaseWriteLock(&afs_xcbhash);
2320 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2321 osi_dnlc_purgedp(avc);
2324 * avc->lock(W); assert(!setLocks || slowPass)
2326 osi_Assert(!setLocks || slowPass);
2332 /* otherwise we copy in the just-fetched info */
2333 afs_CFileClose(file);
2334 afs_AdjustSize(tdc, size); /* new size */
2336 * Copy appropriate fields into vcache. Status is
2337 * copied later where we selectively acquire the
2338 * vcache write lock.
2341 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2343 setVcacheStatus = 1;
2344 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2345 tsmall->OutStatus.DataVersion);
2346 tdc->dflags |= DFEntryMod;
2347 afs_indexFlags[tdc->index] |= IFEverUsed;
2348 ConvertWToSLock(&tdc->lock);
2349 } /*Data version numbers don't match */
2352 * Data version numbers match.
2354 afs_stats_cmperf.dcacheHits++;
2355 } /*Data version numbers match */
2357 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2361 * avc->lock(R) if setLocks && !slowPass
2362 * avc->lock(W) if !setLocks || slowPass
2363 * tdc->lock(S) if tdc
2367 * See if this was a reference to a file in the local cell.
2369 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2370 afs_stats_cmperf.dlocalAccesses++;
2372 afs_stats_cmperf.dremoteAccesses++;
2374 /* Fix up LRU info */
2377 ObtainWriteLock(&afs_xdcache, 602);
2378 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2379 hadd32(afs_indexCounter, 1);
2380 ReleaseWriteLock(&afs_xdcache);
2382 /* return the data */
2383 if (vType(avc) == VDIR)
2386 *aoffset = AFS_CHUNKOFFSET(abyte);
2387 *alen = (tdc->f.chunkBytes - *aoffset);
2388 ReleaseSharedLock(&tdc->lock);
2393 * avc->lock(R) if setLocks && !slowPass
2394 * avc->lock(W) if !setLocks || slowPass
2397 /* Fix up the callback and status values in the vcache */
2399 if (setLocks && !slowPass) {
2402 * This is our dirty little secret to parallel fetches.
2403 * We don't write-lock the vcache while doing the fetch,
2404 * but potentially we'll need to update the vcache after
2405 * the fetch is done.
2407 * Drop the read lock and try to re-obtain the write
2408 * lock. If the vcache still has the same DV, it's
2409 * ok to go ahead and install the new data.
2411 afs_hyper_t currentDV, statusDV;
2413 hset(currentDV, avc->f.m.DataVersion);
2415 if (setNewCallback && avc->callback != newCallback)
2419 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2420 tsmall->OutStatus.DataVersion);
2422 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2424 if (setVcacheStatus && !hsame(currentDV, statusDV))
2428 ReleaseReadLock(&avc->lock);
2430 if (doVcacheUpdate) {
2431 ObtainWriteLock(&avc->lock, 615);
2432 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2433 /* We lose. Someone will beat us to it. */
2435 ReleaseWriteLock(&avc->lock);
2440 /* With slow pass, we've already done all the updates */
2442 ReleaseWriteLock(&avc->lock);
2445 /* Check if we need to perform any last-minute fixes with a write-lock */
2446 if (!setLocks || doVcacheUpdate) {
2448 avc->callback = newCallback;
2449 if (tsmall && setVcacheStatus)
2450 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2452 ReleaseWriteLock(&avc->lock);
2456 osi_FreeLargeSpace(tsmall);
2459 } /*afs_GetDCache */
2463 * afs_WriteThroughDSlots
2466 * Sweep through the dcache slots and write out any modified
2467 * in-memory data back on to our caching store.
2473 * The afs_xdcache is write-locked through this whole affair.
2476 afs_WriteThroughDSlots(void)
2479 afs_int32 i, touchedit = 0;
2481 struct afs_q DirtyQ, *tq;
2483 AFS_STATCNT(afs_WriteThroughDSlots);
2486 * Because of lock ordering, we can't grab dcache locks while
2487 * holding afs_xdcache. So we enter xdcache, get a reference
2488 * for every dcache entry, and exit xdcache.
2490 ObtainWriteLock(&afs_xdcache, 283);
2492 for (i = 0; i < afs_cacheFiles; i++) {
2493 tdc = afs_indexTable[i];
2495 /* Grab tlock in case the existing refcount isn't zero */
2496 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2497 ObtainWriteLock(&tdc->tlock, 623);
2499 ReleaseWriteLock(&tdc->tlock);
2501 QAdd(&DirtyQ, &tdc->dirty);
2504 ReleaseWriteLock(&afs_xdcache);
2507 * Now, for each dcache entry we found, check if it's dirty.
2508 * If so, get write-lock, get afs_xdcache, which protects
2509 * afs_cacheInodep, and flush it. Don't forget to put back
2513 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2515 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2517 if (tdc->dflags & DFEntryMod) {
2520 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2522 /* Now that we have the write lock, double-check */
2523 if (wrLock && (tdc->dflags & DFEntryMod)) {
2524 tdc->dflags &= ~DFEntryMod;
2525 ObtainWriteLock(&afs_xdcache, 620);
2526 afs_WriteDCache(tdc, 1);
2527 ReleaseWriteLock(&afs_xdcache);
2531 ReleaseWriteLock(&tdc->lock);
2537 ObtainWriteLock(&afs_xdcache, 617);
2538 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2539 /* Touch the file to make sure that the mtime on the file is kept
2540 * up-to-date to avoid losing cached files on cold starts because
2541 * their mtime seems old...
2543 struct afs_fheader theader;
2545 theader.magic = AFS_FHMAGIC;
2546 theader.firstCSize = AFS_FIRSTCSIZE;
2547 theader.otherCSize = AFS_OTHERCSIZE;
2548 theader.version = AFS_CI_VERSION;
2549 theader.dataSize = sizeof(struct fcache);
2550 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2552 ReleaseWriteLock(&afs_xdcache);
2559 * Return a pointer to an freshly initialized dcache entry using
2560 * a memory-based cache. The tlock will be read-locked.
2563 * aslot : Dcache slot to look at.
2566 * Must be called with afs_xdcache write-locked.
2570 afs_MemGetDSlot(afs_int32 aslot, int needvalid)
2575 AFS_STATCNT(afs_MemGetDSlot);
2576 if (CheckLock(&afs_xdcache) != -1)
2577 osi_Panic("getdslot nolock");
2578 if (aslot < 0 || aslot >= afs_cacheFiles)
2579 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2580 tdc = afs_indexTable[aslot];
2582 QRemove(&tdc->lruq); /* move to queue head */
2583 QAdd(&afs_DLRU, &tdc->lruq);
2584 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2585 ObtainWriteLock(&tdc->tlock, 624);
2587 ConvertWToRLock(&tdc->tlock);
2591 osi_Assert(!needvalid);
2593 if (!afs_freeDSList)
2594 afs_GetDownDSlot(4);
2595 if (!afs_freeDSList) {
2596 /* none free, making one is better than a panic */
2597 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2598 tdc = afs_osi_Alloc(sizeof(struct dcache));
2599 osi_Assert(tdc != NULL);
2600 #ifdef KERNEL_HAVE_PIN
2601 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2604 tdc = afs_freeDSList;
2605 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2608 tdc->dflags = 0; /* up-to-date, not in free q */
2610 QAdd(&afs_DLRU, &tdc->lruq);
2611 if (tdc->lruq.prev == &tdc->lruq)
2612 osi_Panic("lruq 3");
2614 /* initialize entry */
2615 tdc->f.fid.Cell = 0;
2616 tdc->f.fid.Fid.Volume = 0;
2618 hones(tdc->f.versionNo);
2619 tdc->f.inode.mem = aslot;
2620 tdc->dflags |= DFEntryMod;
2623 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2626 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2627 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2628 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2631 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2632 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2633 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2634 ObtainReadLock(&tdc->tlock);
2636 afs_indexTable[aslot] = tdc;
2639 } /*afs_MemGetDSlot */
2641 unsigned int last_error = 0, lasterrtime = 0;
2647 * Return a pointer to an freshly initialized dcache entry using
2648 * a UFS-based disk cache. The dcache tlock will be read-locked.
2651 * aslot : Dcache slot to look at.
2654 * afs_xdcache lock write-locked.
2657 afs_UFSGetDSlot(afs_int32 aslot, int needvalid)
2665 AFS_STATCNT(afs_UFSGetDSlot);
2666 if (CheckLock(&afs_xdcache) != -1)
2667 osi_Panic("getdslot nolock");
2668 if (aslot < 0 || aslot >= afs_cacheFiles)
2669 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2670 tdc = afs_indexTable[aslot];
2672 QRemove(&tdc->lruq); /* move to queue head */
2673 QAdd(&afs_DLRU, &tdc->lruq);
2674 /* Grab tlock in case refCount != 0 */
2675 ObtainWriteLock(&tdc->tlock, 625);
2677 ConvertWToRLock(&tdc->tlock);
2681 /* otherwise we should read it in from the cache file */
2682 if (!afs_freeDSList)
2683 afs_GetDownDSlot(4);
2684 if (!afs_freeDSList) {
2685 /* none free, making one is better than a panic */
2686 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2687 tdc = afs_osi_Alloc(sizeof(struct dcache));
2688 osi_Assert(tdc != NULL);
2689 #ifdef KERNEL_HAVE_PIN
2690 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2693 tdc = afs_freeDSList;
2694 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2697 tdc->dflags = 0; /* up-to-date, not in free q */
2699 QAdd(&afs_DLRU, &tdc->lruq);
2700 if (tdc->lruq.prev == &tdc->lruq)
2701 osi_Panic("lruq 3");
2704 * Seek to the aslot'th entry and read it in.
2706 off = sizeof(struct fcache)*aslot + sizeof(struct afs_fheader);
2708 afs_osi_Read(afs_cacheInodep,
2709 off, (char *)(&tdc->f),
2710 sizeof(struct fcache));
2712 if (code != sizeof(struct fcache)) {
2714 #if defined(KERNEL_HAVE_UERROR)
2715 last_error = getuerror();
2717 lasterrtime = osi_Time();
2719 struct osi_stat tstat;
2720 if (afs_osi_Stat(afs_cacheInodep, &tstat)) {
2723 afs_warn("afs: disk cache read error in CacheItems off %d/%d "
2725 off, (int)tstat.size,
2726 (int)code, (int)sizeof(struct fcache));
2727 /* put tdc back on the free dslot list */
2728 QRemove(&tdc->lruq);
2729 tdc->index = NULLIDX;
2730 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
2731 afs_freeDSList = tdc;
2735 if (!afs_CellNumValid(tdc->f.fid.Cell)) {
2738 osi_Panic("afs: needed valid dcache but index %d off %d has "
2739 "invalid cell num %d\n",
2740 (int)aslot, off, (int)tdc->f.fid.Cell);
2744 if (needvalid && tdc->f.fid.Fid.Volume == 0) {
2745 osi_Panic("afs: invalid zero-volume dcache entry at slot %d off %d",
2750 tdc->f.fid.Cell = 0;
2751 tdc->f.fid.Fid.Volume = 0;
2753 hones(tdc->f.versionNo);
2754 tdc->dflags |= DFEntryMod;
2755 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2756 tdc->f.states &= ~(DRO|DBackup|DRW);
2757 afs_DCMoveBucket(tdc, 0, 0);
2760 if (tdc->f.states & DRO) {
2761 afs_DCMoveBucket(tdc, 0, 2);
2762 } else if (tdc->f.states & DBackup) {
2763 afs_DCMoveBucket(tdc, 0, 1);
2765 afs_DCMoveBucket(tdc, 0, 1);
2771 if (tdc->f.chunk >= 0)
2772 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
2777 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2778 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2779 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2782 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2783 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2784 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2785 ObtainReadLock(&tdc->tlock);
2788 * If we didn't read into a temporary dcache region, update the
2789 * slot pointer table.
2791 afs_indexTable[aslot] = tdc;
2794 } /*afs_UFSGetDSlot */
2799 * Write a particular dcache entry back to its home in the
2802 * \param adc Pointer to the dcache entry to write.
2803 * \param atime If true, set the modtime on the file to the current time.
2805 * \note Environment:
2806 * Must be called with the afs_xdcache lock at least read-locked,
2807 * and dcache entry at least read-locked.
2808 * The reference count is not changed.
2812 afs_WriteDCache(struct dcache *adc, int atime)
2816 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2818 AFS_STATCNT(afs_WriteDCache);
2819 osi_Assert(WriteLocked(&afs_xdcache));
2821 adc->f.modTime = osi_Time();
2823 * Seek to the right dcache slot and write the in-memory image out to disk.
2825 afs_cellname_write();
2827 afs_osi_Write(afs_cacheInodep,
2828 sizeof(struct fcache) * adc->index +
2829 sizeof(struct afs_fheader), (char *)(&adc->f),
2830 sizeof(struct fcache));
2831 if (code != sizeof(struct fcache))
2839 * Wake up users of a particular file waiting for stores to take
2842 * \param avc Ptr to related vcache entry.
2844 * \note Environment:
2845 * Nothing interesting.
2848 afs_wakeup(struct vcache *avc)
2851 struct brequest *tb;
2853 AFS_STATCNT(afs_wakeup);
2854 for (i = 0; i < NBRS; i++, tb++) {
2855 /* if request is valid and for this file, we've found it */
2856 if (tb->refCount > 0 && avc == tb->vc) {
2859 * If CSafeStore is on, then we don't awaken the guy
2860 * waiting for the store until the whole store has finished.
2861 * Otherwise, we do it now. Note that if CSafeStore is on,
2862 * the BStore routine actually wakes up the user, instead
2864 * I think this is redundant now because this sort of thing
2865 * is already being handled by the higher-level code.
2867 if ((avc->f.states & CSafeStore) == 0) {
2869 tb->flags |= BUVALID;
2870 if (tb->flags & BUWAIT) {
2871 tb->flags &= ~BUWAIT;
2883 * Given a file name and inode, set up that file to be an
2884 * active member in the AFS cache. This also involves checking
2885 * the usability of its data.
2887 * \param afile Name of the cache file to initialize.
2888 * \param ainode Inode of the file.
2890 * \note Environment:
2891 * This function is called only during initialization.
2894 afs_InitCacheFile(char *afile, ino_t ainode)
2899 struct osi_file *tfile;
2900 struct osi_stat tstat;
2903 AFS_STATCNT(afs_InitCacheFile);
2904 index = afs_stats_cmperf.cacheNumEntries;
2905 if (index >= afs_cacheFiles)
2908 ObtainWriteLock(&afs_xdcache, 282);
2909 tdc = afs_GetNewDSlot(index);
2910 ReleaseReadLock(&tdc->tlock);
2911 ReleaseWriteLock(&afs_xdcache);
2913 ObtainWriteLock(&tdc->lock, 621);
2914 ObtainWriteLock(&afs_xdcache, 622);
2916 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
2918 ReleaseWriteLock(&afs_xdcache);
2919 ReleaseWriteLock(&tdc->lock);
2924 /* Add any other 'complex' inode types here ... */
2925 #if !defined(AFS_LINUX26_ENV) && !defined(AFS_CACHE_VNODE_PATH)
2926 tdc->f.inode.ufs = ainode;
2928 osi_Panic("Can't init cache with inode numbers when complex inodes are "
2933 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
2935 tfile = osi_UFSOpen(&tdc->f.inode);
2936 code = afs_osi_Stat(tfile, &tstat);
2938 osi_Panic("initcachefile stat");
2941 * If file size doesn't match the cache info file, it's probably bad.
2943 if (tdc->f.chunkBytes != tstat.size)
2945 tdc->f.chunkBytes = 0;
2948 * If file changed within T (120?) seconds of cache info file, it's
2949 * probably bad. In addition, if slot changed within last T seconds,
2950 * the cache info file may be incorrectly identified, and so slot
2953 if (cacheInfoModTime < tstat.mtime + 120)
2955 if (cacheInfoModTime < tdc->f.modTime + 120)
2957 /* In case write through is behind, make sure cache items entry is
2958 * at least as new as the chunk.
2960 if (tdc->f.modTime < tstat.mtime)
2963 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
2964 if (tstat.size != 0)
2965 osi_UFSTruncate(tfile, 0);
2966 tdc->f.states &= ~(DRO|DBackup|DRW);
2967 afs_DCMoveBucket(tdc, 0, 0);
2968 /* put entry in free cache slot list */
2969 afs_dvnextTbl[tdc->index] = afs_freeDCList;
2970 afs_freeDCList = index;
2972 afs_indexFlags[index] |= IFFree;
2973 afs_indexUnique[index] = 0;
2976 * We must put this entry in the appropriate hash tables.
2977 * Note that i is still set from the above DCHash call
2979 code = DCHash(&tdc->f.fid, tdc->f.chunk);
2980 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
2981 afs_dchashTbl[code] = tdc->index;
2982 code = DVHash(&tdc->f.fid);
2983 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
2984 afs_dvhashTbl[code] = tdc->index;
2985 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
2987 /* has nontrivial amt of data */
2988 afs_indexFlags[index] |= IFEverUsed;
2989 afs_stats_cmperf.cacheFilesReused++;
2991 * Initialize index times to file's mod times; init indexCounter
2994 hset32(afs_indexTimes[index], tstat.atime);
2995 if (hgetlo(afs_indexCounter) < tstat.atime) {
2996 hset32(afs_indexCounter, tstat.atime);
2998 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
2999 } /*File is not bad */
3001 osi_UFSClose(tfile);
3002 tdc->f.states &= ~DWriting;
3003 tdc->dflags &= ~DFEntryMod;
3004 /* don't set f.modTime; we're just cleaning up */
3005 afs_WriteDCache(tdc, 0);
3006 ReleaseWriteLock(&afs_xdcache);
3007 ReleaseWriteLock(&tdc->lock);
3009 afs_stats_cmperf.cacheNumEntries++;
3014 /*Max # of struct dcache's resident at any time*/
3016 * If 'dchint' is enabled then in-memory dcache min is increased because of
3022 * Initialize dcache related variables.
3032 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3038 afs_freeDCList = NULLIDX;
3039 afs_discardDCList = NULLIDX;
3040 afs_freeDCCount = 0;
3041 afs_freeDSList = NULL;
3042 hzero(afs_indexCounter);
3044 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3050 if (achunk < 0 || achunk > 30)
3051 achunk = 13; /* Use default */
3052 AFS_SETCHUNKSIZE(achunk);
3058 if (aflags & AFSCALL_INIT_MEMCACHE) {
3060 * Use a memory cache instead of a disk cache
3062 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3063 afs_cacheType = &afs_MemCacheOps;
3064 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3065 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3066 /* ablocks is reported in 1K blocks */
3067 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3069 afs_warn("afsd: memory cache too large for available memory.\n");
3070 afs_warn("afsd: AFS files cannot be accessed.\n\n");
3072 afiles = ablocks = 0;
3074 afs_warn("Memory cache: Allocating %d dcache entries...",
3077 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3078 afs_cacheType = &afs_UfsCacheOps;
3081 if (aDentries > 512)
3082 afs_dhashsize = 2048;
3083 /* initialize hash tables */
3084 afs_dvhashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3085 osi_Assert(afs_dvhashTbl != NULL);
3086 afs_dchashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3087 osi_Assert(afs_dchashTbl != NULL);
3088 for (i = 0; i < afs_dhashsize; i++) {
3089 afs_dvhashTbl[i] = NULLIDX;
3090 afs_dchashTbl[i] = NULLIDX;
3092 afs_dvnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3093 osi_Assert(afs_dvnextTbl != NULL);
3094 afs_dcnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3095 osi_Assert(afs_dcnextTbl != NULL);
3096 for (i = 0; i < afiles; i++) {
3097 afs_dvnextTbl[i] = NULLIDX;
3098 afs_dcnextTbl[i] = NULLIDX;
3101 /* Allocate and zero the pointer array to the dcache entries */
3102 afs_indexTable = afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3103 osi_Assert(afs_indexTable != NULL);
3104 memset(afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3105 afs_indexTimes = afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3106 osi_Assert(afs_indexTimes != NULL);
3107 memset(afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3108 afs_indexUnique = afs_osi_Alloc(afiles * sizeof(afs_uint32));
3109 osi_Assert(afs_indexUnique != NULL);
3110 memset(afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3111 afs_indexFlags = afs_osi_Alloc(afiles * sizeof(u_char));
3112 osi_Assert(afs_indexFlags != NULL);
3113 memset(afs_indexFlags, 0, afiles * sizeof(char));
3115 /* Allocate and thread the struct dcache entries themselves */
3116 tdp = afs_Initial_freeDSList =
3117 afs_osi_Alloc(aDentries * sizeof(struct dcache));
3118 osi_Assert(tdp != NULL);
3119 memset(tdp, 0, aDentries * sizeof(struct dcache));
3120 #ifdef KERNEL_HAVE_PIN
3121 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3122 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3123 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3124 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3125 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3126 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3127 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3128 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3129 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3132 afs_freeDSList = &tdp[0];
3133 for (i = 0; i < aDentries - 1; i++) {
3134 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3135 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3136 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3137 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3139 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3140 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3141 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3142 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3144 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3145 afs_cacheBlocks = ablocks;
3146 afs_ComputeCacheParms(); /* compute parms based on cache size */
3148 afs_dcentries = aDentries;
3150 afs_stats_cmperf.cacheBucket0_Discarded =
3151 afs_stats_cmperf.cacheBucket1_Discarded =
3152 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3158 * Shuts down the cache.
3162 shutdown_dcache(void)
3166 #ifdef AFS_CACHE_VNODE_PATH
3167 if (cacheDiskType != AFS_FCACHE_TYPE_MEM) {
3169 for (i = 0; i < afs_cacheFiles; i++) {
3170 tdc = afs_indexTable[i];
3172 afs_osi_FreeStr(tdc->f.inode.ufs);
3178 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3179 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3180 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3181 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3182 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3183 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3184 afs_osi_Free(afs_Initial_freeDSList,
3185 afs_dcentries * sizeof(struct dcache));
3186 #ifdef KERNEL_HAVE_PIN
3187 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3188 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3189 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3190 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3191 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3192 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3193 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3197 for (i = 0; i < afs_dhashsize; i++) {
3198 afs_dvhashTbl[i] = NULLIDX;
3199 afs_dchashTbl[i] = NULLIDX;
3202 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3203 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3205 afs_blocksUsed = afs_dcentries = 0;
3206 afs_stats_cmperf.cacheBucket0_Discarded =
3207 afs_stats_cmperf.cacheBucket1_Discarded =
3208 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3209 hzero(afs_indexCounter);
3211 afs_freeDCCount = 0;
3212 afs_freeDCList = NULLIDX;
3213 afs_discardDCList = NULLIDX;
3214 afs_freeDSList = afs_Initial_freeDSList = 0;
3216 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3222 * Get a dcache ready for writing, respecting the current cache size limits
3224 * len is required because afs_GetDCache with flag == 4 expects the length
3225 * field to be filled. It decides from this whether it's necessary to fetch
3226 * data into the chunk before writing or not (when the whole chunk is
3229 * \param avc The vcache to fetch a dcache for
3230 * \param filePos The start of the section to be written
3231 * \param len The length of the section to be written
3235 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3236 * must be released and afs_PutDCache() called to free dcache.
3239 * \note avc->lock must be held on entry. Function may release and reobtain
3240 * avc->lock and GLOCK.
3244 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3245 afs_size_t len, struct vrequest *areq,
3248 struct dcache *tdc = NULL;
3251 /* read the cached info */
3253 tdc = afs_FindDCache(avc, filePos);
3255 ObtainWriteLock(&tdc->lock, 657);
3256 } else if (afs_blocksUsed >
3257 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3258 tdc = afs_FindDCache(avc, filePos);
3260 ObtainWriteLock(&tdc->lock, 658);
3261 if (!hsame(tdc->f.versionNo, avc->f.m.DataVersion)
3262 || (tdc->dflags & DFFetching)) {
3263 ReleaseWriteLock(&tdc->lock);
3269 afs_MaybeWakeupTruncateDaemon();
3270 while (afs_blocksUsed >
3271 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3272 ReleaseWriteLock(&avc->lock);
3273 if (afs_blocksUsed - afs_blocksDiscarded >
3274 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3275 afs_WaitForCacheDrain = 1;
3276 afs_osi_Sleep(&afs_WaitForCacheDrain);
3278 afs_MaybeFreeDiscardedDCache();
3279 afs_MaybeWakeupTruncateDaemon();
3280 ObtainWriteLock(&avc->lock, 509);
3282 avc->f.states |= CDirty;
3283 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3285 ObtainWriteLock(&tdc->lock, 659);
3288 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3290 ObtainWriteLock(&tdc->lock, 660);
3293 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3294 afs_stats_cmperf.cacheCurrDirtyChunks++;
3295 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3297 if (!(tdc->f.states & DWriting)) {
3298 /* don't mark entry as mod if we don't have to */
3299 tdc->f.states |= DWriting;
3300 tdc->dflags |= DFEntryMod;
3307 * Make a shadow copy of a dir's dcache. It's used for disconnected
3308 * operations like remove/create/rename to keep the original directory data.
3309 * On reconnection, we can diff the original data with the server and get the
3310 * server changes and with the local data to get the local changes.
3312 * \param avc The dir vnode.
3313 * \param adc The dir dcache.
3315 * \return 0 for success.
3317 * \note The vcache entry must be write locked.
3318 * \note The dcache entry must be read locked.
3321 afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3323 int i, code, ret_code = 0, written, trans_size;
3324 struct dcache *new_dc = NULL;
3325 struct osi_file *tfile_src, *tfile_dst;
3326 struct VenusFid shadow_fid;
3329 /* Is this a dir? */
3330 if (vType(avc) != VDIR)
3333 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3336 /* Generate a fid for the shadow dir. */
3337 shadow_fid.Cell = avc->f.fid.Cell;
3338 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3339 afs_GenShadowFid(&shadow_fid);
3341 ObtainWriteLock(&afs_xdcache, 716);
3343 /* Get a fresh dcache. */
3344 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3346 ObtainReadLock(&adc->mflock);
3348 /* Set up the new fid. */
3349 /* Copy interesting data from original dir dcache. */
3350 new_dc->mflags = adc->mflags;
3351 new_dc->dflags = adc->dflags;
3352 new_dc->f.modTime = adc->f.modTime;
3353 new_dc->f.versionNo = adc->f.versionNo;
3354 new_dc->f.states = adc->f.states;
3355 new_dc->f.chunk= adc->f.chunk;
3356 new_dc->f.chunkBytes = adc->f.chunkBytes;
3358 ReleaseReadLock(&adc->mflock);
3360 /* Now add to the two hash chains */
3361 i = DCHash(&shadow_fid, 0);
3362 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[i];
3363 afs_dchashTbl[i] = new_dc->index;
3365 i = DVHash(&shadow_fid);
3366 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[i];
3367 afs_dvhashTbl[i] = new_dc->index;
3369 ReleaseWriteLock(&afs_xdcache);
3371 /* Alloc a 4k block. */
3372 data = afs_osi_Alloc(4096);
3374 afs_warn("afs_MakeShadowDir: could not alloc data\n");
3379 /* Open the files. */
3380 tfile_src = afs_CFileOpen(&adc->f.inode);
3381 tfile_dst = afs_CFileOpen(&new_dc->f.inode);
3383 /* And now copy dir dcache data into this dcache,
3387 while (written < adc->f.chunkBytes) {
3388 trans_size = adc->f.chunkBytes - written;
3389 if (trans_size > 4096)
3392 /* Read a chunk from the dcache. */
3393 code = afs_CFileRead(tfile_src, written, data, trans_size);
3394 if (code < trans_size) {
3399 /* Write it to the new dcache. */
3400 code = afs_CFileWrite(tfile_dst, written, data, trans_size);
3401 if (code < trans_size) {
3406 written+=trans_size;
3409 afs_CFileClose(tfile_dst);
3410 afs_CFileClose(tfile_src);
3412 afs_osi_Free(data, 4096);
3414 ReleaseWriteLock(&new_dc->lock);
3415 afs_PutDCache(new_dc);
3418 ObtainWriteLock(&afs_xvcache, 763);
3419 ObtainWriteLock(&afs_disconDirtyLock, 765);
3420 QAdd(&afs_disconShadow, &avc->shadowq);
3421 osi_Assert((afs_RefVCache(avc) == 0));
3422 ReleaseWriteLock(&afs_disconDirtyLock);
3423 ReleaseWriteLock(&afs_xvcache);
3425 avc->f.shadow.vnode = shadow_fid.Fid.Vnode;
3426 avc->f.shadow.unique = shadow_fid.Fid.Unique;
3434 * Delete the dcaches of a shadow dir.
3436 * \param avc The vcache containing the shadow fid.
3438 * \note avc must be write locked.
3441 afs_DeleteShadowDir(struct vcache *avc)
3444 struct VenusFid shadow_fid;
3446 shadow_fid.Cell = avc->f.fid.Cell;
3447 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3448 shadow_fid.Fid.Vnode = avc->f.shadow.vnode;
3449 shadow_fid.Fid.Unique = avc->f.shadow.unique;
3451 tdc = afs_FindDCacheByFid(&shadow_fid);
3453 afs_HashOutDCache(tdc, 1);
3454 afs_DiscardDCache(tdc);
3457 avc->f.shadow.vnode = avc->f.shadow.unique = 0;
3458 ObtainWriteLock(&afs_disconDirtyLock, 708);
3459 QRemove(&avc->shadowq);
3460 ReleaseWriteLock(&afs_disconDirtyLock);
3461 afs_PutVCache(avc); /* Because we held it when we added to the queue */
3465 * Populate a dcache with empty chunks up to a given file size,
3466 * used before extending a file in order to avoid 'holes' which
3467 * we can't access in disconnected mode.
3469 * \param avc The vcache which is being extended (locked)
3470 * \param alen The new length of the file
3474 afs_PopulateDCache(struct vcache *avc, afs_size_t apos, struct vrequest *areq)
3477 afs_size_t len, offset;
3478 afs_int32 start, end;
3480 /* We're doing this to deal with the situation where we extend
3481 * by writing after lseek()ing past the end of the file . If that
3482 * extension skips chunks, then those chunks won't be created, and
3483 * GetDCache will assume that they have to be fetched from the server.
3484 * So, for each chunk between the current file position, and the new
3485 * length we GetDCache for that chunk.
3488 if (AFS_CHUNK(apos) == 0 || apos <= avc->f.m.Length)
3491 if (avc->f.m.Length == 0)
3494 start = AFS_CHUNK(avc->f.m.Length)+1;
3496 end = AFS_CHUNK(apos);
3499 len = AFS_CHUNKTOSIZE(start);
3500 tdc = afs_GetDCache(avc, AFS_CHUNKTOBASE(start), areq, &offset, &len, 4);