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;
426 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
427 afs_GetDownD(slots_needed, &space_needed, 0);
428 if ((space_needed <= 0) && (slots_needed <= 0)) {
431 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
434 if (!afs_CacheIsTooFull())
435 afs_CacheTooFull = 0;
436 } /* end of cache cleanup */
437 ReleaseWriteLock(&afs_xdcache);
440 * This is a defensive check to try to avoid starving threads
441 * that may need the global lock so thay can help free some
442 * cache space. If this thread won't be sleeping or truncating
443 * any cache files then give up the global lock so other
444 * threads get a chance to run.
446 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
447 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
448 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
452 * This is where we free the discarded cache elements.
454 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
455 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
456 afs_FreeDiscardedDCache();
459 /* See if we need to continue to run. Someone may have
460 * signalled us while we were executing.
462 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
463 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
464 /* Collect statistics on truncate daemon. */
465 CTD_stats.CTD_nSleeps++;
466 osi_GetuTime(&CTD_stats.CTD_beforeSleep);
467 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_afterSleep,
468 CTD_stats.CTD_beforeSleep);
469 afs_stats_AddTo(CTD_stats.CTD_runTime, CTD_tmpTime);
471 afs_TruncateDaemonRunning = 0;
472 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
473 afs_TruncateDaemonRunning = 1;
475 osi_GetuTime(&CTD_stats.CTD_afterSleep);
476 afs_stats_GetDiff(CTD_tmpTime, CTD_stats.CTD_beforeSleep,
477 CTD_stats.CTD_afterSleep);
478 afs_stats_AddTo(CTD_stats.CTD_sleepTime, CTD_tmpTime);
480 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
481 afs_termState = AFSOP_STOP_AFSDB;
482 afs_osi_Wakeup(&afs_termState);
490 * Make adjustment for the new size in the disk cache entry
492 * \note Major Assumptions Here:
493 * Assumes that frag size is an integral power of two, less one,
494 * and that this is a two's complement machine. I don't
495 * know of any filesystems which violate this assumption...
497 * \param adc Ptr to dcache entry.
498 * \param anewsize New size desired.
503 afs_AdjustSize(struct dcache *adc, afs_int32 newSize)
507 AFS_STATCNT(afs_AdjustSize);
509 adc->dflags |= DFEntryMod;
510 oldSize = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
511 adc->f.chunkBytes = newSize;
514 newSize = ((newSize + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
515 afs_DCAdjustSize(adc, oldSize, newSize);
516 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
518 /* We're growing the file, wakeup the daemon */
519 afs_MaybeWakeupTruncateDaemon();
521 afs_blocksUsed += (newSize - oldSize);
522 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
527 * This routine is responsible for moving at least one entry (but up
528 * to some number of them) from the LRU queue to the free queue.
530 * \param anumber Number of entries that should ideally be moved.
531 * \param aneedSpace How much space we need (1K blocks);
534 * The anumber parameter is just a hint; at least one entry MUST be
535 * moved, or we'll panic. We must be called with afs_xdcache
536 * write-locked. We should try to satisfy both anumber and aneedspace,
537 * whichever is more demanding - need to do several things:
538 * 1. only grab up to anumber victims if aneedSpace <= 0, not
539 * the whole set of MAXATONCE.
540 * 2. dynamically choose MAXATONCE to reflect severity of
541 * demand: something like (*aneedSpace >> (logChunk - 9))
543 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
544 * indicates that the cache is not properly configured/tuned or
545 * something. We should be able to automatically correct that problem.
548 #define MAXATONCE 16 /* max we can obtain at once */
550 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
554 struct VenusFid *afid;
559 afs_uint32 victims[MAXATONCE];
560 struct dcache *victimDCs[MAXATONCE];
561 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
562 afs_uint32 victimPtr; /* next free item in victim arrays */
563 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
564 afs_uint32 maxVictimPtr; /* where it is */
568 AFS_STATCNT(afs_GetDownD);
570 if (CheckLock(&afs_xdcache) != -1)
571 osi_Panic("getdownd nolock");
572 /* decrement anumber first for all dudes in free list */
573 /* SHOULD always decrement anumber first, even if aneedSpace >0,
574 * because we should try to free space even if anumber <=0 */
575 if (!aneedSpace || *aneedSpace <= 0) {
576 anumber -= afs_freeDCCount;
578 return; /* enough already free */
582 /* bounds check parameter */
583 if (anumber > MAXATONCE)
584 anumber = MAXATONCE; /* all we can do */
586 /* rewrite so phases include a better eligiblity for gc test*/
588 * The phase variable manages reclaims. Set to 0, the first pass,
589 * we don't reclaim active entries, or other than target bucket.
590 * Set to 1, we reclaim even active ones in target bucket.
591 * Set to 2, we reclaim any inactive one.
592 * Set to 3, we reclaim even active ones.
600 for (i = 0; i < afs_cacheFiles; i++)
601 /* turn off all flags */
602 afs_indexFlags[i] &= ~IFFlag;
604 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
605 /* find oldest entries for reclamation */
606 maxVictimPtr = victimPtr = 0;
607 hzero(maxVictimTime);
608 curbucket = afs_DCWhichBucket(phase, buckethint);
609 /* select victims from access time array */
610 for (i = 0; i < afs_cacheFiles; i++) {
611 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
612 /* skip if dirty or already free */
615 tdc = afs_indexTable[i];
616 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
618 /* Wrong bucket; can't use it! */
621 if (tdc && (tdc->refCount != 0)) {
622 /* Referenced; can't use it! */
625 hset(vtime, afs_indexTimes[i]);
627 /* if we've already looked at this one, skip it */
628 if (afs_indexFlags[i] & IFFlag)
631 if (victimPtr < MAXATONCE) {
632 /* if there's at least one free victim slot left */
633 victims[victimPtr] = i;
634 hset(victimTimes[victimPtr], vtime);
635 if (hcmp(vtime, maxVictimTime) > 0) {
636 hset(maxVictimTime, vtime);
637 maxVictimPtr = victimPtr;
640 } else if (hcmp(vtime, maxVictimTime) < 0) {
642 * We're older than youngest victim, so we replace at
645 /* find youngest (largest LRU) victim */
648 osi_Panic("getdownd local");
650 hset(victimTimes[j], vtime);
651 /* recompute maxVictimTime */
652 hset(maxVictimTime, vtime);
653 for (j = 0; j < victimPtr; j++)
654 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
655 hset(maxVictimTime, victimTimes[j]);
661 /* now really reclaim the victims */
662 j = 0; /* flag to track if we actually got any of the victims */
663 /* first, hold all the victims, since we're going to release the lock
664 * during the truncate operation.
666 for (i = 0; i < victimPtr; i++) {
667 tdc = afs_GetDSlot(victims[i], 0);
668 /* We got tdc->tlock(R) here */
669 if (tdc->refCount == 1)
673 ReleaseReadLock(&tdc->tlock);
677 for (i = 0; i < victimPtr; i++) {
678 /* q is first elt in dcache entry */
680 /* now, since we're dropping the afs_xdcache lock below, we
681 * have to verify, before proceeding, that there are no other
682 * references to this dcache entry, even now. Note that we
683 * compare with 1, since we bumped it above when we called
684 * afs_GetDSlot to preserve the entry's identity.
686 if (tdc && tdc->refCount == 1) {
687 unsigned char chunkFlags;
688 afs_size_t tchunkoffset = 0;
690 /* xdcache is lower than the xvcache lock */
691 ReleaseWriteLock(&afs_xdcache);
692 ObtainReadLock(&afs_xvcache);
693 tvc = afs_FindVCache(afid, 0, 0 /* no stats, no vlru */ );
694 ReleaseReadLock(&afs_xvcache);
695 ObtainWriteLock(&afs_xdcache, 527);
697 if (tdc->refCount > 1)
700 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
701 chunkFlags = afs_indexFlags[tdc->index];
702 if (((phase & 1) == 0) && osi_Active(tvc))
704 if (((phase & 1) == 1) && osi_Active(tvc)
705 && (tvc->f.states & CDCLock)
706 && (chunkFlags & IFAnyPages))
708 if (chunkFlags & IFDataMod)
710 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
711 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
712 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
713 ICL_HANDLE_OFFSET(tchunkoffset));
715 #if defined(AFS_SUN5_ENV)
717 * Now we try to invalidate pages. We do this only for
718 * Solaris. For other platforms, it's OK to recycle a
719 * dcache entry out from under a page, because the strategy
720 * function can call afs_GetDCache().
722 if (!skip && (chunkFlags & IFAnyPages)) {
725 ReleaseWriteLock(&afs_xdcache);
726 ObtainWriteLock(&tvc->vlock, 543);
727 if (tvc->multiPage) {
731 /* block locking pages */
732 tvc->vstates |= VPageCleaning;
733 /* block getting new pages */
735 ReleaseWriteLock(&tvc->vlock);
736 /* One last recheck */
737 ObtainWriteLock(&afs_xdcache, 333);
738 chunkFlags = afs_indexFlags[tdc->index];
739 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
740 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
741 && (chunkFlags & IFAnyPages))) {
743 ReleaseWriteLock(&afs_xdcache);
746 ReleaseWriteLock(&afs_xdcache);
748 code = osi_VM_GetDownD(tvc, tdc);
750 ObtainWriteLock(&afs_xdcache, 269);
751 /* we actually removed all pages, clean and dirty */
753 afs_indexFlags[tdc->index] &=
754 ~(IFDirtyPages | IFAnyPages);
757 ReleaseWriteLock(&afs_xdcache);
759 ObtainWriteLock(&tvc->vlock, 544);
760 if (--tvc->activeV == 0
761 && (tvc->vstates & VRevokeWait)) {
762 tvc->vstates &= ~VRevokeWait;
763 afs_osi_Wakeup((char *)&tvc->vstates);
766 if (tvc->vstates & VPageCleaning) {
767 tvc->vstates &= ~VPageCleaning;
768 afs_osi_Wakeup((char *)&tvc->vstates);
771 ReleaseWriteLock(&tvc->vlock);
773 #endif /* AFS_SUN5_ENV */
775 ReleaseWriteLock(&afs_xdcache);
778 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
779 ObtainWriteLock(&afs_xdcache, 528);
780 if (afs_indexFlags[tdc->index] &
781 (IFDataMod | IFDirtyPages | IFAnyPages))
783 if (tdc->refCount > 1)
786 #if defined(AFS_SUN5_ENV)
788 /* no vnode, so IFDirtyPages is spurious (we don't
789 * sweep dcaches on vnode recycling, so we can have
790 * DIRTYPAGES set even when all pages are gone). Just
792 * Hold vcache lock to prevent vnode from being
793 * created while we're clearing IFDirtyPages.
795 afs_indexFlags[tdc->index] &=
796 ~(IFDirtyPages | IFAnyPages);
800 /* skip this guy and mark him as recently used */
801 afs_indexFlags[tdc->index] |= IFFlag;
802 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
803 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
804 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
805 ICL_HANDLE_OFFSET(tchunkoffset));
807 /* flush this dude from the data cache and reclaim;
808 * first, make sure no one will care that we damage
809 * it, by removing it from all hash tables. Then,
810 * melt it down for parts. Note that any concurrent
811 * (new possibility!) calls to GetDownD won't touch
812 * this guy because his reference count is > 0. */
813 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
814 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
815 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
816 ICL_HANDLE_OFFSET(tchunkoffset));
817 AFS_STATCNT(afs_gget);
818 afs_HashOutDCache(tdc, 1);
819 if (tdc->f.chunkBytes != 0) {
823 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
828 afs_DiscardDCache(tdc);
833 j = 1; /* we reclaimed at least one victim */
837 } /* end of for victims loop */
840 /* Phase is 0 and no one was found, so try phase 1 (ignore
841 * osi_Active flag) */
844 for (i = 0; i < afs_cacheFiles; i++)
845 /* turn off all flags */
846 afs_indexFlags[i] &= ~IFFlag;
849 /* found no one in phases 0-5, we're hosed */
853 } /* big while loop */
861 * Remove adc from any hash tables that would allow it to be located
862 * again by afs_FindDCache or afs_GetDCache.
864 * \param adc Pointer to dcache entry to remove from hash tables.
866 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
870 afs_HashOutDCache(struct dcache *adc, int zap)
874 AFS_STATCNT(afs_glink);
876 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
878 /* if this guy is in the hash table, pull him out */
879 if (adc->f.fid.Fid.Volume != 0) {
880 /* remove entry from first hash chains */
881 i = DCHash(&adc->f.fid, adc->f.chunk);
882 us = afs_dchashTbl[i];
883 if (us == adc->index) {
884 /* first dude in the list */
885 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
887 /* somewhere on the chain */
888 while (us != NULLIDX) {
889 if (afs_dcnextTbl[us] == adc->index) {
890 /* found item pointing at the one to delete */
891 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
894 us = afs_dcnextTbl[us];
897 osi_Panic("dcache hc");
899 /* remove entry from *other* hash chain */
900 i = DVHash(&adc->f.fid);
901 us = afs_dvhashTbl[i];
902 if (us == adc->index) {
903 /* first dude in the list */
904 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
906 /* somewhere on the chain */
907 while (us != NULLIDX) {
908 if (afs_dvnextTbl[us] == adc->index) {
909 /* found item pointing at the one to delete */
910 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
913 us = afs_dvnextTbl[us];
916 osi_Panic("dcache hv");
921 /* prevent entry from being found on a reboot (it is already out of
922 * the hash table, but after a crash, we just look at fid fields of
923 * stable (old) entries).
925 adc->f.fid.Fid.Volume = 0; /* invalid */
927 /* mark entry as modified */
928 adc->dflags |= DFEntryMod;
933 } /*afs_HashOutDCache */
936 * Flush the given dcache entry, pulling it from hash chains
937 * and truncating the associated cache file.
939 * \param adc Ptr to dcache entry to flush.
942 * This routine must be called with the afs_xdcache lock held
946 afs_FlushDCache(struct dcache *adc)
948 AFS_STATCNT(afs_FlushDCache);
950 * Bump the number of cache files flushed.
952 afs_stats_cmperf.cacheFlushes++;
954 /* remove from all hash tables */
955 afs_HashOutDCache(adc, 1);
957 /* Free its space; special case null operation, since truncate operation
958 * in UFS is slow even in this case, and this allows us to pre-truncate
959 * these files at more convenient times with fewer locks set
960 * (see afs_GetDownD).
962 if (adc->f.chunkBytes != 0) {
963 afs_DiscardDCache(adc);
964 afs_MaybeWakeupTruncateDaemon();
969 if (afs_WaitForCacheDrain) {
970 if (afs_blocksUsed <=
971 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
972 afs_WaitForCacheDrain = 0;
973 afs_osi_Wakeup(&afs_WaitForCacheDrain);
976 } /*afs_FlushDCache */
980 * Put a dcache entry on the free dcache entry list.
982 * \param adc dcache entry to free.
984 * \note Environment: called with afs_xdcache lock write-locked.
987 afs_FreeDCache(struct dcache *adc)
989 /* Thread on free list, update free list count and mark entry as
990 * freed in its indexFlags element. Also, ensure DCache entry gets
991 * written out (set DFEntryMod).
994 afs_dvnextTbl[adc->index] = afs_freeDCList;
995 afs_freeDCList = adc->index;
997 afs_indexFlags[adc->index] |= IFFree;
998 adc->dflags |= DFEntryMod;
1000 if (afs_WaitForCacheDrain) {
1001 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1002 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1003 afs_WaitForCacheDrain = 0;
1004 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1007 } /* afs_FreeDCache */
1010 * Discard the cache element by moving it to the discardDCList.
1011 * This puts the cache element into a quasi-freed state, where
1012 * the space may be reused, but the file has not been truncated.
1014 * \note Major Assumptions Here:
1015 * Assumes that frag size is an integral power of two, less one,
1016 * and that this is a two's complement machine. I don't
1017 * know of any filesystems which violate this assumption...
1019 * \param adr Ptr to dcache entry.
1021 * \note Environment:
1022 * Must be called with afs_xdcache write-locked.
1026 afs_DiscardDCache(struct dcache *adc)
1030 AFS_STATCNT(afs_DiscardDCache);
1032 osi_Assert(adc->refCount == 1);
1034 size = ((adc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1035 afs_blocksDiscarded += size;
1036 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1038 afs_dvnextTbl[adc->index] = afs_discardDCList;
1039 afs_discardDCList = adc->index;
1040 afs_discardDCCount++;
1042 adc->f.fid.Fid.Volume = 0;
1043 adc->dflags |= DFEntryMod;
1044 afs_indexFlags[adc->index] |= IFDiscarded;
1046 if (afs_WaitForCacheDrain) {
1047 if ((afs_blocksUsed - afs_blocksDiscarded) <=
1048 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
1049 afs_WaitForCacheDrain = 0;
1050 afs_osi_Wakeup(&afs_WaitForCacheDrain);
1054 } /*afs_DiscardDCache */
1057 * Free the next element on the list of discarded cache elements.
1060 afs_FreeDiscardedDCache(void)
1063 struct osi_file *tfile;
1066 AFS_STATCNT(afs_FreeDiscardedDCache);
1068 ObtainWriteLock(&afs_xdcache, 510);
1069 if (!afs_blocksDiscarded) {
1070 ReleaseWriteLock(&afs_xdcache);
1075 * Get an entry from the list of discarded cache elements
1077 tdc = afs_GetDSlot(afs_discardDCList, 0);
1078 osi_Assert(tdc->refCount == 1);
1079 ReleaseReadLock(&tdc->tlock);
1081 afs_discardDCList = afs_dvnextTbl[tdc->index];
1082 afs_dvnextTbl[tdc->index] = NULLIDX;
1083 afs_discardDCCount--;
1084 size = ((tdc->f.chunkBytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10; /* round up */
1085 afs_blocksDiscarded -= size;
1086 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1087 /* We can lock because we just took it off the free list */
1088 ObtainWriteLock(&tdc->lock, 626);
1089 ReleaseWriteLock(&afs_xdcache);
1092 * Truncate the element to reclaim its space
1094 tfile = afs_CFileOpen(&tdc->f.inode);
1095 afs_CFileTruncate(tfile, 0);
1096 afs_CFileClose(tfile);
1097 afs_AdjustSize(tdc, 0);
1098 afs_DCMoveBucket(tdc, 0, 0);
1101 * Free the element we just truncated
1103 ObtainWriteLock(&afs_xdcache, 511);
1104 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1105 afs_FreeDCache(tdc);
1106 tdc->f.states &= ~(DRO|DBackup|DRW);
1107 ReleaseWriteLock(&tdc->lock);
1109 ReleaseWriteLock(&afs_xdcache);
1113 * Free as many entries from the list of discarded cache elements
1114 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1119 afs_MaybeFreeDiscardedDCache(void)
1122 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1124 while (afs_blocksDiscarded
1125 && (afs_blocksUsed >
1126 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1127 afs_FreeDiscardedDCache();
1133 * Try to free up a certain number of disk slots.
1135 * \param anumber Targeted number of disk slots to free up.
1137 * \note Environment:
1138 * Must be called with afs_xdcache write-locked.
1142 afs_GetDownDSlot(int anumber)
1144 struct afs_q *tq, *nq;
1149 AFS_STATCNT(afs_GetDownDSlot);
1150 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1151 osi_Panic("diskless getdowndslot");
1153 if (CheckLock(&afs_xdcache) != -1)
1154 osi_Panic("getdowndslot nolock");
1156 /* decrement anumber first for all dudes in free list */
1157 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1160 return; /* enough already free */
1162 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1164 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1165 nq = QPrev(tq); /* in case we remove it */
1166 if (tdc->refCount == 0) {
1167 if ((ix = tdc->index) == NULLIDX)
1168 osi_Panic("getdowndslot");
1169 /* pull the entry out of the lruq and put it on the free list */
1170 QRemove(&tdc->lruq);
1172 /* write-through if modified */
1173 if (tdc->dflags & DFEntryMod) {
1174 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1176 * ask proxy to do this for us - we don't have the stack space
1178 while (tdc->dflags & DFEntryMod) {
1181 s = SPLOCK(afs_sgibklock);
1182 if (afs_sgibklist == NULL) {
1183 /* if slot is free, grab it. */
1184 afs_sgibklist = tdc;
1185 SV_SIGNAL(&afs_sgibksync);
1187 /* wait for daemon to (start, then) finish. */
1188 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1192 tdc->dflags &= ~DFEntryMod;
1193 afs_WriteDCache(tdc, 1);
1197 /* finally put the entry in the free list */
1198 afs_indexTable[ix] = NULL;
1199 afs_indexFlags[ix] &= ~IFEverUsed;
1200 tdc->index = NULLIDX;
1201 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1202 afs_freeDSList = tdc;
1206 } /*afs_GetDownDSlot */
1213 * Increment the reference count on a disk cache entry,
1214 * which already has a non-zero refcount. In order to
1215 * increment the refcount of a zero-reference entry, you
1216 * have to hold afs_xdcache.
1219 * adc : Pointer to the dcache entry to increment.
1222 * Nothing interesting.
1225 afs_RefDCache(struct dcache *adc)
1227 ObtainWriteLock(&adc->tlock, 627);
1228 if (adc->refCount < 0)
1229 osi_Panic("RefDCache: negative refcount");
1231 ReleaseWriteLock(&adc->tlock);
1240 * Decrement the reference count on a disk cache entry.
1243 * ad : Ptr to the dcache entry to decrement.
1246 * Nothing interesting.
1249 afs_PutDCache(struct dcache *adc)
1251 AFS_STATCNT(afs_PutDCache);
1252 ObtainWriteLock(&adc->tlock, 276);
1253 if (adc->refCount <= 0)
1254 osi_Panic("putdcache");
1256 ReleaseWriteLock(&adc->tlock);
1265 * Try to discard all data associated with this file from the
1269 * avc : Pointer to the cache info for the file.
1272 * Both pvnLock and lock are write held.
1275 afs_TryToSmush(struct vcache *avc, afs_ucred_t *acred, int sync)
1280 AFS_STATCNT(afs_TryToSmush);
1281 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1282 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1283 sync = 1; /* XX Temp testing XX */
1285 #if defined(AFS_SUN5_ENV)
1286 ObtainWriteLock(&avc->vlock, 573);
1287 avc->activeV++; /* block new getpages */
1288 ReleaseWriteLock(&avc->vlock);
1291 /* Flush VM pages */
1292 osi_VM_TryToSmush(avc, acred, sync);
1295 * Get the hash chain containing all dce's for this fid
1297 i = DVHash(&avc->f.fid);
1298 ObtainWriteLock(&afs_xdcache, 277);
1299 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1300 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1301 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1302 int releaseTlock = 1;
1303 tdc = afs_GetDSlot(index, NULL);
1304 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1306 if ((afs_indexFlags[index] & IFDataMod) == 0
1307 && tdc->refCount == 1) {
1308 ReleaseReadLock(&tdc->tlock);
1310 afs_FlushDCache(tdc);
1313 afs_indexTable[index] = 0;
1316 ReleaseReadLock(&tdc->tlock);
1320 #if defined(AFS_SUN5_ENV)
1321 ObtainWriteLock(&avc->vlock, 545);
1322 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1323 avc->vstates &= ~VRevokeWait;
1324 afs_osi_Wakeup((char *)&avc->vstates);
1326 ReleaseWriteLock(&avc->vlock);
1328 ReleaseWriteLock(&afs_xdcache);
1330 * It's treated like a callback so that when we do lookups we'll
1331 * invalidate the unique bit if any
1332 * trytoSmush occured during the lookup call
1338 * afs_DCacheMissingChunks
1341 * Given the cached info for a file, return the number of chunks that
1342 * are not available from the dcache.
1345 * avc: Pointer to the (held) vcache entry to look in.
1348 * The number of chunks which are not currently cached.
1351 * The vcache entry is held upon entry.
1355 afs_DCacheMissingChunks(struct vcache *avc)
1358 afs_size_t totalLength = 0;
1359 afs_uint32 totalChunks = 0;
1362 totalLength = avc->f.m.Length;
1363 if (avc->f.truncPos < totalLength)
1364 totalLength = avc->f.truncPos;
1366 /* Length is 0, no chunk missing. */
1367 if (totalLength == 0)
1370 /* If totalLength is a multiple of chunksize, the last byte appears
1371 * as being part of the next chunk, which does not exist.
1372 * Decrementing totalLength by one fixes that.
1375 totalChunks = (AFS_CHUNK(totalLength) + 1);
1377 /* If we're a directory, we only ever have one chunk, regardless of
1378 * the size of the dir.
1380 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1384 printf("Should have %d chunks for %u bytes\n",
1385 totalChunks, (totalLength + 1));
1387 i = DVHash(&avc->f.fid);
1388 ObtainWriteLock(&afs_xdcache, 1001);
1389 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1390 i = afs_dvnextTbl[index];
1391 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1392 tdc = afs_GetDSlot(index, NULL);
1393 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1396 ReleaseReadLock(&tdc->tlock);
1400 ReleaseWriteLock(&afs_xdcache);
1402 /*printf("Missing %d chunks\n", totalChunks);*/
1404 return (totalChunks);
1411 * Given the cached info for a file and a byte offset into the
1412 * file, make sure the dcache entry for that file and containing
1413 * the given byte is available, returning it to our caller.
1416 * avc : Pointer to the (held) vcache entry to look in.
1417 * abyte : Which byte we want to get to.
1420 * Pointer to the dcache entry covering the file & desired byte,
1421 * or NULL if not found.
1424 * The vcache entry is held upon entry.
1428 afs_FindDCache(struct vcache *avc, afs_size_t abyte)
1432 struct dcache *tdc = NULL;
1434 AFS_STATCNT(afs_FindDCache);
1435 chunk = AFS_CHUNK(abyte);
1438 * Hash on the [fid, chunk] and get the corresponding dcache index
1439 * after write-locking the dcache.
1441 i = DCHash(&avc->f.fid, chunk);
1442 ObtainWriteLock(&afs_xdcache, 278);
1443 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1444 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1445 tdc = afs_GetDSlot(index, NULL);
1446 ReleaseReadLock(&tdc->tlock);
1447 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1448 break; /* leaving refCount high for caller */
1452 index = afs_dcnextTbl[index];
1454 if (index != NULLIDX) {
1455 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1456 hadd32(afs_indexCounter, 1);
1457 ReleaseWriteLock(&afs_xdcache);
1460 ReleaseWriteLock(&afs_xdcache);
1462 } /*afs_FindDCache */
1466 * Get a fresh dcache from the free or discarded list.
1468 * \param avc Who's dcache is this going to be?
1469 * \param chunk The position where it will be placed in.
1470 * \param lock How are locks held.
1471 * \param ashFid If this dcache going to be used for a shadow dir,
1474 * \note Required locks:
1476 * - avc (R if (lock & 1) set and W otherwise)
1477 * \note It write locks the new dcache. The caller must unlock it.
1479 * \return The new dcache.
1482 afs_AllocDCache(struct vcache *avc, afs_int32 chunk, afs_int32 lock,
1483 struct VenusFid *ashFid)
1485 struct dcache *tdc = NULL;
1486 afs_uint32 size = 0;
1487 struct osi_file *file;
1489 if (afs_discardDCList == NULLIDX
1490 || ((lock & 2) && afs_freeDCList != NULLIDX)) {
1492 afs_indexFlags[afs_freeDCList] &= ~IFFree;
1493 tdc = afs_GetDSlot(afs_freeDCList, 0);
1494 osi_Assert(tdc->refCount == 1);
1495 ReleaseReadLock(&tdc->tlock);
1496 ObtainWriteLock(&tdc->lock, 604);
1497 afs_freeDCList = afs_dvnextTbl[tdc->index];
1500 afs_indexFlags[afs_discardDCList] &= ~IFDiscarded;
1501 tdc = afs_GetDSlot(afs_discardDCList, 0);
1502 osi_Assert(tdc->refCount == 1);
1503 ReleaseReadLock(&tdc->tlock);
1504 ObtainWriteLock(&tdc->lock, 605);
1505 afs_discardDCList = afs_dvnextTbl[tdc->index];
1506 afs_discardDCCount--;
1508 ((tdc->f.chunkBytes +
1509 afs_fsfragsize) ^ afs_fsfragsize) >> 10;
1510 tdc->f.states &= ~(DRO|DBackup|DRW);
1511 afs_DCMoveBucket(tdc, size, 0);
1512 afs_blocksDiscarded -= size;
1513 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1515 /* Truncate the chunk so zeroes get filled properly */
1516 file = afs_CFileOpen(&tdc->f.inode);
1517 afs_CFileTruncate(file, 0);
1518 afs_CFileClose(file);
1519 afs_AdjustSize(tdc, 0);
1525 * avc->lock(R) if setLocks
1526 * avc->lock(W) if !setLocks
1532 * Fill in the newly-allocated dcache record.
1534 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1536 /* Use shadow fid if provided. */
1537 tdc->f.fid = *ashFid;
1539 /* Use normal vcache's fid otherwise. */
1540 tdc->f.fid = avc->f.fid;
1541 if (avc->f.states & CRO)
1542 tdc->f.states = DRO;
1543 else if (avc->f.states & CBackup)
1544 tdc->f.states = DBackup;
1546 tdc->f.states = DRW;
1547 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1548 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1550 hones(tdc->f.versionNo); /* invalid value */
1551 tdc->f.chunk = chunk;
1552 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1554 if (tdc->lruq.prev == &tdc->lruq)
1555 osi_Panic("lruq 1");
1564 * This function is called to obtain a reference to data stored in
1565 * the disk cache, locating a chunk of data containing the desired
1566 * byte and returning a reference to the disk cache entry, with its
1567 * reference count incremented.
1571 * avc : Ptr to a vcache entry (unlocked)
1572 * abyte : Byte position in the file desired
1573 * areq : Request structure identifying the requesting user.
1574 * aflags : Settings as follows:
1576 * 2 : Return after creating entry.
1577 * 4 : called from afs_vnop_write.c
1578 * *alen contains length of data to be written.
1580 * aoffset : Set to the offset within the chunk where the resident
1582 * alen : Set to the number of bytes of data after the desired
1583 * byte (including the byte itself) which can be read
1587 * The vcache entry pointed to by avc is unlocked upon entry.
1591 * Update the vnode-to-dcache hint if we can get the vnode lock
1592 * right away. Assumes dcache entry is at least read-locked.
1595 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1597 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1598 if (hsame(v->f.m.DataVersion, d->f.versionNo) && v->callback)
1601 ReleaseWriteLock(&v->lock);
1605 /* avc - Write-locked unless aflags & 1 */
1607 afs_GetDCache(struct vcache *avc, afs_size_t abyte,
1608 struct vrequest *areq, afs_size_t * aoffset,
1609 afs_size_t * alen, int aflags)
1611 afs_int32 i, code, shortcut;
1612 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1613 afs_int32 adjustsize = 0;
1619 afs_size_t maxGoodLength; /* amount of good data at server */
1620 afs_size_t Position = 0;
1621 afs_int32 size, tlen; /* size of segment to transfer */
1622 struct afs_FetchOutput *tsmall = 0;
1624 struct osi_file *file;
1625 struct afs_conn *tc;
1627 struct server *newCallback = NULL;
1628 char setNewCallback;
1629 char setVcacheStatus;
1630 char doVcacheUpdate;
1632 int doAdjustSize = 0;
1633 int doReallyAdjustSize = 0;
1634 int overWriteWholeChunk = 0;
1635 struct rx_connection *rxconn;
1638 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1639 int fromReplica; /*Are we reading from a replica? */
1640 int numFetchLoops; /*# times around the fetch/analyze loop */
1641 #endif /* AFS_NOSTATS */
1643 AFS_STATCNT(afs_GetDCache);
1647 setLocks = aflags & 1;
1650 * Determine the chunk number and offset within the chunk corresponding
1651 * to the desired byte.
1653 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
1656 chunk = AFS_CHUNK(abyte);
1659 /* come back to here if we waited for the cache to drain. */
1662 setNewCallback = setVcacheStatus = 0;
1666 ObtainWriteLock(&avc->lock, 616);
1668 ObtainReadLock(&avc->lock);
1673 * avc->lock(R) if setLocks && !slowPass
1674 * avc->lock(W) if !setLocks || slowPass
1679 /* check hints first! (might could use bcmp or some such...) */
1680 if ((tdc = avc->dchint)) {
1684 * The locking order between afs_xdcache and dcache lock matters.
1685 * The hint dcache entry could be anywhere, even on the free list.
1686 * Locking afs_xdcache ensures that noone is trying to pull dcache
1687 * entries from the free list, and thereby assuming them to be not
1688 * referenced and not locked.
1690 ObtainReadLock(&afs_xdcache);
1691 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
1693 if (dcLocked && (tdc->index != NULLIDX)
1694 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
1695 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
1696 /* got the right one. It might not be the right version, and it
1697 * might be fetching, but it's the right dcache entry.
1699 /* All this code should be integrated better with what follows:
1700 * I can save a good bit more time under a write lock if I do..
1702 ObtainWriteLock(&tdc->tlock, 603);
1704 ReleaseWriteLock(&tdc->tlock);
1706 ReleaseReadLock(&afs_xdcache);
1709 if (hsame(tdc->f.versionNo, avc->f.m.DataVersion)
1710 && !(tdc->dflags & DFFetching)) {
1712 afs_stats_cmperf.dcacheHits++;
1713 ObtainWriteLock(&afs_xdcache, 559);
1714 QRemove(&tdc->lruq);
1715 QAdd(&afs_DLRU, &tdc->lruq);
1716 ReleaseWriteLock(&afs_xdcache);
1719 * avc->lock(R) if setLocks && !slowPass
1720 * avc->lock(W) if !setLocks || slowPass
1727 ReleaseSharedLock(&tdc->lock);
1728 ReleaseReadLock(&afs_xdcache);
1736 * avc->lock(R) if setLocks && !slowPass
1737 * avc->lock(W) if !setLocks || slowPass
1738 * tdc->lock(S) if tdc
1741 if (!tdc) { /* If the hint wasn't the right dcache entry */
1743 * Hash on the [fid, chunk] and get the corresponding dcache index
1744 * after write-locking the dcache.
1749 * avc->lock(R) if setLocks && !slowPass
1750 * avc->lock(W) if !setLocks || slowPass
1753 i = DCHash(&avc->f.fid, chunk);
1754 /* check to make sure our space is fine */
1755 afs_MaybeWakeupTruncateDaemon();
1757 ObtainWriteLock(&afs_xdcache, 280);
1759 for (index = afs_dchashTbl[i]; index != NULLIDX;) {
1760 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1761 tdc = afs_GetDSlot(index, NULL);
1762 ReleaseReadLock(&tdc->tlock);
1765 * avc->lock(R) if setLocks && !slowPass
1766 * avc->lock(W) if !setLocks || slowPass
1769 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1770 /* Move it up in the beginning of the list */
1771 if (afs_dchashTbl[i] != index) {
1772 afs_dcnextTbl[us] = afs_dcnextTbl[index];
1773 afs_dcnextTbl[index] = afs_dchashTbl[i];
1774 afs_dchashTbl[i] = index;
1776 ReleaseWriteLock(&afs_xdcache);
1777 ObtainSharedLock(&tdc->lock, 606);
1778 break; /* leaving refCount high for caller */
1784 index = afs_dcnextTbl[index];
1788 * If we didn't find the entry, we'll create one.
1790 if (index == NULLIDX) {
1793 * avc->lock(R) if setLocks
1794 * avc->lock(W) if !setLocks
1797 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
1798 avc, ICL_TYPE_INT32, chunk);
1800 /* Make sure there is a free dcache entry for us to use */
1801 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
1804 avc->f.states |= CDCLock;
1805 /* just need slots */
1806 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
1808 avc->f.states &= ~CDCLock;
1809 if (afs_discardDCList != NULLIDX
1810 || afs_freeDCList != NULLIDX)
1812 /* If we can't get space for 5 mins we give up and panic */
1813 if (++downDCount > 300) {
1814 osi_Panic("getdcache");
1816 ReleaseWriteLock(&afs_xdcache);
1819 * avc->lock(R) if setLocks
1820 * avc->lock(W) if !setLocks
1822 afs_osi_Wait(1000, 0, 0);
1827 tdc = afs_AllocDCache(avc, chunk, aflags, NULL);
1830 * Now add to the two hash chains - note that i is still set
1831 * from the above DCHash call.
1833 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
1834 afs_dchashTbl[i] = tdc->index;
1835 i = DVHash(&avc->f.fid);
1836 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
1837 afs_dvhashTbl[i] = tdc->index;
1838 tdc->dflags = DFEntryMod;
1840 afs_MaybeWakeupTruncateDaemon();
1841 ReleaseWriteLock(&afs_xdcache);
1842 ConvertWToSLock(&tdc->lock);
1847 /* vcache->dcache hint failed */
1850 * avc->lock(R) if setLocks && !slowPass
1851 * avc->lock(W) if !setLocks || slowPass
1854 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
1855 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
1856 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
1857 hgetlo(avc->f.m.DataVersion));
1859 * Here we have the entry in tdc, with its refCount incremented.
1860 * Note: we don't use the S-lock on avc; it costs concurrency when
1861 * storing a file back to the server.
1865 * Not a newly created file so we need to check the file's length and
1866 * compare data versions since someone could have changed the data or we're
1867 * reading a file written elsewhere. We only want to bypass doing no-op
1868 * read rpcs on newly created files (dv of 0) since only then we guarantee
1869 * that this chunk's data hasn't been filled by another client.
1871 size = AFS_CHUNKSIZE(abyte);
1872 if (aflags & 4) /* called from write */
1874 else /* called from read */
1875 tlen = tdc->validPos - abyte;
1876 Position = AFS_CHUNKTOBASE(chunk);
1877 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
1878 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
1879 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
1880 ICL_HANDLE_OFFSET(Position));
1881 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
1883 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
1884 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
1885 overWriteWholeChunk = 1;
1886 if (doAdjustSize || overWriteWholeChunk) {
1887 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1889 #ifdef AFS_SGI64_ENV
1892 #else /* AFS_SGI64_ENV */
1895 #endif /* AFS_SGI64_ENV */
1896 #else /* AFS_SGI_ENV */
1899 #endif /* AFS_SGI_ENV */
1900 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
1901 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1902 #if defined(AFS_SUN5_ENV)
1903 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
1905 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
1907 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
1908 !hsame(avc->f.m.DataVersion, tdc->f.versionNo))
1909 doReallyAdjustSize = 1;
1911 if (doReallyAdjustSize || overWriteWholeChunk) {
1912 /* no data in file to read at this position */
1913 UpgradeSToWLock(&tdc->lock, 607);
1914 file = afs_CFileOpen(&tdc->f.inode);
1915 afs_CFileTruncate(file, 0);
1916 afs_CFileClose(file);
1917 afs_AdjustSize(tdc, 0);
1918 hset(tdc->f.versionNo, avc->f.m.DataVersion);
1919 tdc->dflags |= DFEntryMod;
1921 ConvertWToSLock(&tdc->lock);
1926 * We must read in the whole chunk if the version number doesn't
1930 /* don't need data, just a unique dcache entry */
1931 ObtainWriteLock(&afs_xdcache, 608);
1932 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1933 hadd32(afs_indexCounter, 1);
1934 ReleaseWriteLock(&afs_xdcache);
1936 updateV2DC(setLocks, avc, tdc, 553);
1937 if (vType(avc) == VDIR)
1940 *aoffset = AFS_CHUNKOFFSET(abyte);
1941 if (tdc->validPos < abyte)
1942 *alen = (afs_size_t) 0;
1944 *alen = tdc->validPos - abyte;
1945 ReleaseSharedLock(&tdc->lock);
1948 ReleaseWriteLock(&avc->lock);
1950 ReleaseReadLock(&avc->lock);
1952 return tdc; /* check if we're done */
1957 * avc->lock(R) if setLocks && !slowPass
1958 * avc->lock(W) if !setLocks || slowPass
1961 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
1963 setNewCallback = setVcacheStatus = 0;
1967 * avc->lock(R) if setLocks && !slowPass
1968 * avc->lock(W) if !setLocks || slowPass
1971 if (!hsame(avc->f.m.DataVersion, tdc->f.versionNo) && !overWriteWholeChunk) {
1973 * Version number mismatch.
1976 * If we are disconnected, then we can't do much of anything
1977 * because the data doesn't match the file.
1979 if (AFS_IS_DISCONNECTED) {
1980 ReleaseSharedLock(&tdc->lock);
1983 ReleaseWriteLock(&avc->lock);
1985 ReleaseReadLock(&avc->lock);
1987 /* Flush the Dcache */
1992 UpgradeSToWLock(&tdc->lock, 609);
1995 * If data ever existed for this vnode, and this is a text object,
1996 * do some clearing. Now, you'd think you need only do the flush
1997 * when VTEXT is on, but VTEXT is turned off when the text object
1998 * is freed, while pages are left lying around in memory marked
1999 * with this vnode. If we would reactivate (create a new text
2000 * object from) this vnode, we could easily stumble upon some of
2001 * these old pages in pagein. So, we always flush these guys.
2002 * Sun has a wonderful lack of useful invariants in this system.
2004 * avc->flushDV is the data version # of the file at the last text
2005 * flush. Clearly, at least, we don't have to flush the file more
2006 * often than it changes
2008 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2010 * By here, the cache entry is always write-locked. We can
2011 * deadlock if we call osi_Flush with the cache entry locked...
2012 * Unlock the dcache too.
2014 ReleaseWriteLock(&tdc->lock);
2015 if (setLocks && !slowPass)
2016 ReleaseReadLock(&avc->lock);
2018 ReleaseWriteLock(&avc->lock);
2022 * Call osi_FlushPages in open, read/write, and map, since it
2023 * is too hard here to figure out if we should lock the
2026 if (setLocks && !slowPass)
2027 ObtainReadLock(&avc->lock);
2029 ObtainWriteLock(&avc->lock, 66);
2030 ObtainWriteLock(&tdc->lock, 610);
2035 * avc->lock(R) if setLocks && !slowPass
2036 * avc->lock(W) if !setLocks || slowPass
2040 /* Watch for standard race condition around osi_FlushText */
2041 if (hsame(avc->f.m.DataVersion, tdc->f.versionNo)) {
2042 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2043 afs_stats_cmperf.dcacheHits++;
2044 ConvertWToSLock(&tdc->lock);
2048 /* Sleep here when cache needs to be drained. */
2049 if (setLocks && !slowPass
2050 && (afs_blocksUsed >
2051 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2052 /* Make sure truncate daemon is running */
2053 afs_MaybeWakeupTruncateDaemon();
2054 ObtainWriteLock(&tdc->tlock, 614);
2055 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2056 ReleaseWriteLock(&tdc->tlock);
2057 ReleaseWriteLock(&tdc->lock);
2058 ReleaseReadLock(&avc->lock);
2059 while ((afs_blocksUsed - afs_blocksDiscarded) >
2060 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2061 afs_WaitForCacheDrain = 1;
2062 afs_osi_Sleep(&afs_WaitForCacheDrain);
2064 afs_MaybeFreeDiscardedDCache();
2065 /* need to check if someone else got the chunk first. */
2066 goto RetryGetDCache;
2069 /* Do not fetch data beyond truncPos. */
2070 maxGoodLength = avc->f.m.Length;
2071 if (avc->f.truncPos < maxGoodLength)
2072 maxGoodLength = avc->f.truncPos;
2073 Position = AFS_CHUNKBASE(abyte);
2074 if (vType(avc) == VDIR) {
2075 size = avc->f.m.Length;
2076 if (size > tdc->f.chunkBytes) {
2077 /* pre-reserve space for file */
2078 afs_AdjustSize(tdc, size);
2080 size = 999999999; /* max size for transfer */
2082 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2083 /* don't read past end of good data on server */
2084 if (Position + size > maxGoodLength)
2085 size = maxGoodLength - Position;
2087 size = 0; /* Handle random races */
2088 if (size > tdc->f.chunkBytes) {
2089 /* pre-reserve space for file */
2090 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2091 /* max size for transfer still in size */
2094 if (afs_mariner && !tdc->f.chunk)
2095 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2097 * Right now, we only have one tool, and it's a hammer. So, we
2098 * fetch the whole file.
2100 DZap(tdc); /* pages in cache may be old */
2101 file = afs_CFileOpen(&tdc->f.inode);
2102 afs_RemoveVCB(&avc->f.fid);
2103 tdc->f.states |= DWriting;
2104 tdc->dflags |= DFFetching;
2105 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2106 if (tdc->mflags & DFFetchReq) {
2107 tdc->mflags &= ~DFFetchReq;
2108 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2109 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2110 __FILE__, ICL_TYPE_INT32, __LINE__,
2111 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2115 (struct afs_FetchOutput *)osi_AllocLargeSpace(sizeof(struct afs_FetchOutput));
2116 setVcacheStatus = 0;
2119 * Remember if we are doing the reading from a replicated volume,
2120 * and how many times we've zipped around the fetch/analyze loop.
2122 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2124 accP = &(afs_stats_cmfullperf.accessinf);
2126 (accP->replicatedRefs)++;
2128 (accP->unreplicatedRefs)++;
2129 #endif /* AFS_NOSTATS */
2130 /* this is a cache miss */
2131 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2132 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2133 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2136 afs_stats_cmperf.dcacheMisses++;
2139 * Dynamic root support: fetch data from local memory.
2141 if (afs_IsDynroot(avc)) {
2145 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2147 dynrootDir += Position;
2148 dynrootLen -= Position;
2149 if (size > dynrootLen)
2153 code = afs_CFileWrite(file, 0, dynrootDir, size);
2161 tdc->validPos = Position + size;
2162 afs_CFileTruncate(file, size); /* prune it */
2163 } else if (afs_IsDynrootMount(avc)) {
2167 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2169 dynrootDir += Position;
2170 dynrootLen -= Position;
2171 if (size > dynrootLen)
2175 code = afs_CFileWrite(file, 0, dynrootDir, size);
2183 tdc->validPos = Position + size;
2184 afs_CFileTruncate(file, size); /* prune it */
2187 * Not a dynamic vnode: do the real fetch.
2192 * avc->lock(R) if setLocks && !slowPass
2193 * avc->lock(W) if !setLocks || slowPass
2197 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
2202 (accP->numReplicasAccessed)++;
2204 #endif /* AFS_NOSTATS */
2205 if (!setLocks || slowPass) {
2206 avc->callback = tc->parent->srvr->server;
2208 newCallback = tc->parent->srvr->server;
2212 code = afs_CacheFetchProc(tc, rxconn, file, Position, tdc,
2218 /* callback could have been broken (or expired) in a race here,
2219 * but we return the data anyway. It's as good as we knew about
2220 * when we started. */
2222 * validPos is updated by CacheFetchProc, and can only be
2223 * modifed under a dcache write lock, which we've blocked out
2225 size = tdc->validPos - Position; /* actual segment size */
2228 afs_CFileTruncate(file, size); /* prune it */
2230 if (!setLocks || slowPass) {
2231 ObtainWriteLock(&afs_xcbhash, 453);
2232 afs_DequeueCallback(avc);
2233 avc->f.states &= ~(CStatd | CUnique);
2234 avc->callback = NULL;
2235 ReleaseWriteLock(&afs_xcbhash);
2236 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2237 osi_dnlc_purgedp(avc);
2239 /* Something lost. Forget about performance, and go
2240 * back with a vcache write lock.
2242 afs_CFileTruncate(file, 0);
2243 afs_AdjustSize(tdc, 0);
2244 afs_CFileClose(file);
2245 osi_FreeLargeSpace(tsmall);
2247 ReleaseWriteLock(&tdc->lock);
2250 ReleaseReadLock(&avc->lock);
2252 goto RetryGetDCache;
2256 } while (afs_Analyze
2257 (tc, rxconn, code, &avc->f.fid, areq,
2258 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2262 * avc->lock(R) if setLocks && !slowPass
2263 * avc->lock(W) if !setLocks || slowPass
2269 * In the case of replicated access, jot down info on the number of
2270 * attempts it took before we got through or gave up.
2273 if (numFetchLoops <= 1)
2274 (accP->refFirstReplicaOK)++;
2275 if (numFetchLoops > accP->maxReplicasPerRef)
2276 accP->maxReplicasPerRef = numFetchLoops;
2278 #endif /* AFS_NOSTATS */
2280 tdc->dflags &= ~DFFetching;
2281 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2282 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2283 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2284 tdc, ICL_TYPE_INT32, tdc->dflags);
2285 if (avc->execsOrWriters == 0)
2286 tdc->f.states &= ~DWriting;
2288 /* now, if code != 0, we have an error and should punt.
2289 * note that we have the vcache write lock, either because
2290 * !setLocks or slowPass.
2293 afs_CFileTruncate(file, 0);
2294 afs_AdjustSize(tdc, 0);
2295 afs_CFileClose(file);
2296 ZapDCE(tdc); /* sets DFEntryMod */
2297 if (vType(avc) == VDIR) {
2300 tdc->f.states &= ~(DRO|DBackup|DRW);
2301 afs_DCMoveBucket(tdc, 0, 0);
2302 ReleaseWriteLock(&tdc->lock);
2304 if (!afs_IsDynroot(avc)) {
2305 ObtainWriteLock(&afs_xcbhash, 454);
2306 afs_DequeueCallback(avc);
2307 avc->f.states &= ~(CStatd | CUnique);
2308 ReleaseWriteLock(&afs_xcbhash);
2309 if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2310 osi_dnlc_purgedp(avc);
2313 * avc->lock(W); assert(!setLocks || slowPass)
2315 osi_Assert(!setLocks || slowPass);
2321 /* otherwise we copy in the just-fetched info */
2322 afs_CFileClose(file);
2323 afs_AdjustSize(tdc, size); /* new size */
2325 * Copy appropriate fields into vcache. Status is
2326 * copied later where we selectively acquire the
2327 * vcache write lock.
2330 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2332 setVcacheStatus = 1;
2333 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2334 tsmall->OutStatus.DataVersion);
2335 tdc->dflags |= DFEntryMod;
2336 afs_indexFlags[tdc->index] |= IFEverUsed;
2337 ConvertWToSLock(&tdc->lock);
2338 } /*Data version numbers don't match */
2341 * Data version numbers match.
2343 afs_stats_cmperf.dcacheHits++;
2344 } /*Data version numbers match */
2346 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2350 * avc->lock(R) if setLocks && !slowPass
2351 * avc->lock(W) if !setLocks || slowPass
2352 * tdc->lock(S) if tdc
2356 * See if this was a reference to a file in the local cell.
2358 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2359 afs_stats_cmperf.dlocalAccesses++;
2361 afs_stats_cmperf.dremoteAccesses++;
2363 /* Fix up LRU info */
2366 ObtainWriteLock(&afs_xdcache, 602);
2367 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2368 hadd32(afs_indexCounter, 1);
2369 ReleaseWriteLock(&afs_xdcache);
2371 /* return the data */
2372 if (vType(avc) == VDIR)
2375 *aoffset = AFS_CHUNKOFFSET(abyte);
2376 *alen = (tdc->f.chunkBytes - *aoffset);
2377 ReleaseSharedLock(&tdc->lock);
2382 * avc->lock(R) if setLocks && !slowPass
2383 * avc->lock(W) if !setLocks || slowPass
2386 /* Fix up the callback and status values in the vcache */
2388 if (setLocks && !slowPass) {
2391 * This is our dirty little secret to parallel fetches.
2392 * We don't write-lock the vcache while doing the fetch,
2393 * but potentially we'll need to update the vcache after
2394 * the fetch is done.
2396 * Drop the read lock and try to re-obtain the write
2397 * lock. If the vcache still has the same DV, it's
2398 * ok to go ahead and install the new data.
2400 afs_hyper_t currentDV, statusDV;
2402 hset(currentDV, avc->f.m.DataVersion);
2404 if (setNewCallback && avc->callback != newCallback)
2408 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2409 tsmall->OutStatus.DataVersion);
2411 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2413 if (setVcacheStatus && !hsame(currentDV, statusDV))
2417 ReleaseReadLock(&avc->lock);
2419 if (doVcacheUpdate) {
2420 ObtainWriteLock(&avc->lock, 615);
2421 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2422 /* We lose. Someone will beat us to it. */
2424 ReleaseWriteLock(&avc->lock);
2429 /* With slow pass, we've already done all the updates */
2431 ReleaseWriteLock(&avc->lock);
2434 /* Check if we need to perform any last-minute fixes with a write-lock */
2435 if (!setLocks || doVcacheUpdate) {
2437 avc->callback = newCallback;
2438 if (tsmall && setVcacheStatus)
2439 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2441 ReleaseWriteLock(&avc->lock);
2445 osi_FreeLargeSpace(tsmall);
2448 } /*afs_GetDCache */
2452 * afs_WriteThroughDSlots
2455 * Sweep through the dcache slots and write out any modified
2456 * in-memory data back on to our caching store.
2462 * The afs_xdcache is write-locked through this whole affair.
2465 afs_WriteThroughDSlots(void)
2468 afs_int32 i, touchedit = 0;
2470 struct afs_q DirtyQ, *tq;
2472 AFS_STATCNT(afs_WriteThroughDSlots);
2475 * Because of lock ordering, we can't grab dcache locks while
2476 * holding afs_xdcache. So we enter xdcache, get a reference
2477 * for every dcache entry, and exit xdcache.
2479 ObtainWriteLock(&afs_xdcache, 283);
2481 for (i = 0; i < afs_cacheFiles; i++) {
2482 tdc = afs_indexTable[i];
2484 /* Grab tlock in case the existing refcount isn't zero */
2485 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2486 ObtainWriteLock(&tdc->tlock, 623);
2488 ReleaseWriteLock(&tdc->tlock);
2490 QAdd(&DirtyQ, &tdc->dirty);
2493 ReleaseWriteLock(&afs_xdcache);
2496 * Now, for each dcache entry we found, check if it's dirty.
2497 * If so, get write-lock, get afs_xdcache, which protects
2498 * afs_cacheInodep, and flush it. Don't forget to put back
2502 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2504 for (tq = DirtyQ.prev; tq != &DirtyQ; tq = QPrev(tq)) {
2506 if (tdc->dflags & DFEntryMod) {
2509 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2511 /* Now that we have the write lock, double-check */
2512 if (wrLock && (tdc->dflags & DFEntryMod)) {
2513 tdc->dflags &= ~DFEntryMod;
2514 ObtainWriteLock(&afs_xdcache, 620);
2515 afs_WriteDCache(tdc, 1);
2516 ReleaseWriteLock(&afs_xdcache);
2520 ReleaseWriteLock(&tdc->lock);
2526 ObtainWriteLock(&afs_xdcache, 617);
2527 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2528 /* Touch the file to make sure that the mtime on the file is kept
2529 * up-to-date to avoid losing cached files on cold starts because
2530 * their mtime seems old...
2532 struct afs_fheader theader;
2534 theader.magic = AFS_FHMAGIC;
2535 theader.firstCSize = AFS_FIRSTCSIZE;
2536 theader.otherCSize = AFS_OTHERCSIZE;
2537 theader.version = AFS_CI_VERSION;
2538 theader.dataSize = sizeof(struct fcache);
2539 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2541 ReleaseWriteLock(&afs_xdcache);
2548 * Return a pointer to an freshly initialized dcache entry using
2549 * a memory-based cache. The tlock will be read-locked.
2552 * aslot : Dcache slot to look at.
2553 * tmpdc : Ptr to dcache entry.
2556 * Must be called with afs_xdcache write-locked.
2560 afs_MemGetDSlot(afs_int32 aslot, struct dcache *tmpdc)
2565 AFS_STATCNT(afs_MemGetDSlot);
2566 if (CheckLock(&afs_xdcache) != -1)
2567 osi_Panic("getdslot nolock");
2568 if (aslot < 0 || aslot >= afs_cacheFiles)
2569 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2570 tdc = afs_indexTable[aslot];
2572 QRemove(&tdc->lruq); /* move to queue head */
2573 QAdd(&afs_DLRU, &tdc->lruq);
2574 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
2575 ObtainWriteLock(&tdc->tlock, 624);
2577 ConvertWToRLock(&tdc->tlock);
2580 if (tmpdc == NULL) {
2581 if (!afs_freeDSList)
2582 afs_GetDownDSlot(4);
2583 if (!afs_freeDSList) {
2584 /* none free, making one is better than a panic */
2585 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2586 tdc = afs_osi_Alloc(sizeof(struct dcache));
2587 osi_Assert(tdc != NULL);
2588 #ifdef KERNEL_HAVE_PIN
2589 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2592 tdc = afs_freeDSList;
2593 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2596 tdc->dflags = 0; /* up-to-date, not in free q */
2598 QAdd(&afs_DLRU, &tdc->lruq);
2599 if (tdc->lruq.prev == &tdc->lruq)
2600 osi_Panic("lruq 3");
2606 /* initialize entry */
2607 tdc->f.fid.Cell = 0;
2608 tdc->f.fid.Fid.Volume = 0;
2610 hones(tdc->f.versionNo);
2611 tdc->f.inode.mem = aslot;
2612 tdc->dflags |= DFEntryMod;
2615 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2618 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2619 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2620 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2623 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2624 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2625 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2626 ObtainReadLock(&tdc->tlock);
2629 afs_indexTable[aslot] = tdc;
2632 } /*afs_MemGetDSlot */
2634 unsigned int last_error = 0, lasterrtime = 0;
2640 * Return a pointer to an freshly initialized dcache entry using
2641 * a UFS-based disk cache. The dcache tlock will be read-locked.
2644 * aslot : Dcache slot to look at.
2645 * tmpdc : Ptr to dcache entry.
2648 * afs_xdcache lock write-locked.
2651 afs_UFSGetDSlot(afs_int32 aslot, struct dcache *tmpdc)
2658 AFS_STATCNT(afs_UFSGetDSlot);
2659 if (CheckLock(&afs_xdcache) != -1)
2660 osi_Panic("getdslot nolock");
2661 if (aslot < 0 || aslot >= afs_cacheFiles)
2662 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
2663 tdc = afs_indexTable[aslot];
2665 QRemove(&tdc->lruq); /* move to queue head */
2666 QAdd(&afs_DLRU, &tdc->lruq);
2667 /* Grab tlock in case refCount != 0 */
2668 ObtainWriteLock(&tdc->tlock, 625);
2670 ConvertWToRLock(&tdc->tlock);
2673 /* otherwise we should read it in from the cache file */
2675 * If we weren't passed an in-memory region to place the file info,
2676 * we have to allocate one.
2678 if (tmpdc == NULL) {
2679 if (!afs_freeDSList)
2680 afs_GetDownDSlot(4);
2681 if (!afs_freeDSList) {
2682 /* none free, making one is better than a panic */
2683 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
2684 tdc = afs_osi_Alloc(sizeof(struct dcache));
2685 osi_Assert(tdc != NULL);
2686 #ifdef KERNEL_HAVE_PIN
2687 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
2690 tdc = afs_freeDSList;
2691 afs_freeDSList = (struct dcache *)tdc->lruq.next;
2694 tdc->dflags = 0; /* up-to-date, not in free q */
2696 QAdd(&afs_DLRU, &tdc->lruq);
2697 if (tdc->lruq.prev == &tdc->lruq)
2698 osi_Panic("lruq 3");
2705 * Seek to the aslot'th entry and read it in.
2708 afs_osi_Read(afs_cacheInodep,
2709 sizeof(struct fcache) * aslot +
2710 sizeof(struct afs_fheader), (char *)(&tdc->f),
2711 sizeof(struct fcache));
2713 if (code != sizeof(struct fcache))
2715 if (!afs_CellNumValid(tdc->f.fid.Cell))
2719 tdc->f.fid.Cell = 0;
2720 tdc->f.fid.Fid.Volume = 0;
2722 hones(tdc->f.versionNo);
2723 tdc->dflags |= DFEntryMod;
2724 #if defined(KERNEL_HAVE_UERROR)
2725 last_error = getuerror();
2727 lasterrtime = osi_Time();
2728 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
2729 tdc->f.states &= ~(DRO|DBackup|DRW);
2730 afs_DCMoveBucket(tdc, 0, 0);
2733 if (tdc->f.states & DRO) {
2734 afs_DCMoveBucket(tdc, 0, 2);
2735 } else if (tdc->f.states & DBackup) {
2736 afs_DCMoveBucket(tdc, 0, 1);
2738 afs_DCMoveBucket(tdc, 0, 1);
2744 if (tdc->f.chunk >= 0)
2745 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
2750 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
2751 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
2752 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
2755 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
2756 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
2757 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
2758 ObtainReadLock(&tdc->tlock);
2761 * If we didn't read into a temporary dcache region, update the
2762 * slot pointer table.
2765 afs_indexTable[aslot] = tdc;
2768 } /*afs_UFSGetDSlot */
2773 * Write a particular dcache entry back to its home in the
2776 * \param adc Pointer to the dcache entry to write.
2777 * \param atime If true, set the modtime on the file to the current time.
2779 * \note Environment:
2780 * Must be called with the afs_xdcache lock at least read-locked,
2781 * and dcache entry at least read-locked.
2782 * The reference count is not changed.
2786 afs_WriteDCache(struct dcache *adc, int atime)
2790 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2792 AFS_STATCNT(afs_WriteDCache);
2793 osi_Assert(WriteLocked(&afs_xdcache));
2795 adc->f.modTime = osi_Time();
2797 * Seek to the right dcache slot and write the in-memory image out to disk.
2799 afs_cellname_write();
2801 afs_osi_Write(afs_cacheInodep,
2802 sizeof(struct fcache) * adc->index +
2803 sizeof(struct afs_fheader), (char *)(&adc->f),
2804 sizeof(struct fcache));
2805 if (code != sizeof(struct fcache))
2813 * Wake up users of a particular file waiting for stores to take
2816 * \param avc Ptr to related vcache entry.
2818 * \note Environment:
2819 * Nothing interesting.
2822 afs_wakeup(struct vcache *avc)
2825 struct brequest *tb;
2827 AFS_STATCNT(afs_wakeup);
2828 for (i = 0; i < NBRS; i++, tb++) {
2829 /* if request is valid and for this file, we've found it */
2830 if (tb->refCount > 0 && avc == tb->vc) {
2833 * If CSafeStore is on, then we don't awaken the guy
2834 * waiting for the store until the whole store has finished.
2835 * Otherwise, we do it now. Note that if CSafeStore is on,
2836 * the BStore routine actually wakes up the user, instead
2838 * I think this is redundant now because this sort of thing
2839 * is already being handled by the higher-level code.
2841 if ((avc->f.states & CSafeStore) == 0) {
2843 tb->flags |= BUVALID;
2844 if (tb->flags & BUWAIT) {
2845 tb->flags &= ~BUWAIT;
2857 * Given a file name and inode, set up that file to be an
2858 * active member in the AFS cache. This also involves checking
2859 * the usability of its data.
2861 * \param afile Name of the cache file to initialize.
2862 * \param ainode Inode of the file.
2864 * \note Environment:
2865 * This function is called only during initialization.
2868 afs_InitCacheFile(char *afile, ino_t ainode)
2873 struct osi_file *tfile;
2874 struct osi_stat tstat;
2877 AFS_STATCNT(afs_InitCacheFile);
2878 index = afs_stats_cmperf.cacheNumEntries;
2879 if (index >= afs_cacheFiles)
2882 ObtainWriteLock(&afs_xdcache, 282);
2883 tdc = afs_GetDSlot(index, NULL);
2884 ReleaseReadLock(&tdc->tlock);
2885 ReleaseWriteLock(&afs_xdcache);
2887 ObtainWriteLock(&tdc->lock, 621);
2888 ObtainWriteLock(&afs_xdcache, 622);
2890 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
2892 ReleaseWriteLock(&afs_xdcache);
2893 ReleaseWriteLock(&tdc->lock);
2898 /* Add any other 'complex' inode types here ... */
2899 #if !defined(AFS_LINUX26_ENV) && !defined(AFS_CACHE_VNODE_PATH)
2900 tdc->f.inode.ufs = ainode;
2902 osi_Panic("Can't init cache with inode numbers when complex inodes are "
2907 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
2909 tfile = osi_UFSOpen(&tdc->f.inode);
2910 code = afs_osi_Stat(tfile, &tstat);
2912 osi_Panic("initcachefile stat");
2915 * If file size doesn't match the cache info file, it's probably bad.
2917 if (tdc->f.chunkBytes != tstat.size)
2919 tdc->f.chunkBytes = 0;
2922 * If file changed within T (120?) seconds of cache info file, it's
2923 * probably bad. In addition, if slot changed within last T seconds,
2924 * the cache info file may be incorrectly identified, and so slot
2927 if (cacheInfoModTime < tstat.mtime + 120)
2929 if (cacheInfoModTime < tdc->f.modTime + 120)
2931 /* In case write through is behind, make sure cache items entry is
2932 * at least as new as the chunk.
2934 if (tdc->f.modTime < tstat.mtime)
2937 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
2938 if (tstat.size != 0)
2939 osi_UFSTruncate(tfile, 0);
2940 tdc->f.states &= ~(DRO|DBackup|DRW);
2941 afs_DCMoveBucket(tdc, 0, 0);
2942 /* put entry in free cache slot list */
2943 afs_dvnextTbl[tdc->index] = afs_freeDCList;
2944 afs_freeDCList = index;
2946 afs_indexFlags[index] |= IFFree;
2947 afs_indexUnique[index] = 0;
2950 * We must put this entry in the appropriate hash tables.
2951 * Note that i is still set from the above DCHash call
2953 code = DCHash(&tdc->f.fid, tdc->f.chunk);
2954 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
2955 afs_dchashTbl[code] = tdc->index;
2956 code = DVHash(&tdc->f.fid);
2957 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
2958 afs_dvhashTbl[code] = tdc->index;
2959 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
2961 /* has nontrivial amt of data */
2962 afs_indexFlags[index] |= IFEverUsed;
2963 afs_stats_cmperf.cacheFilesReused++;
2965 * Initialize index times to file's mod times; init indexCounter
2968 hset32(afs_indexTimes[index], tstat.atime);
2969 if (hgetlo(afs_indexCounter) < tstat.atime) {
2970 hset32(afs_indexCounter, tstat.atime);
2972 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
2973 } /*File is not bad */
2975 osi_UFSClose(tfile);
2976 tdc->f.states &= ~DWriting;
2977 tdc->dflags &= ~DFEntryMod;
2978 /* don't set f.modTime; we're just cleaning up */
2979 afs_WriteDCache(tdc, 0);
2980 ReleaseWriteLock(&afs_xdcache);
2981 ReleaseWriteLock(&tdc->lock);
2983 afs_stats_cmperf.cacheNumEntries++;
2988 /*Max # of struct dcache's resident at any time*/
2990 * If 'dchint' is enabled then in-memory dcache min is increased because of
2996 * Initialize dcache related variables.
3006 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3012 afs_freeDCList = NULLIDX;
3013 afs_discardDCList = NULLIDX;
3014 afs_freeDCCount = 0;
3015 afs_freeDSList = NULL;
3016 hzero(afs_indexCounter);
3018 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3024 if (achunk < 0 || achunk > 30)
3025 achunk = 13; /* Use default */
3026 AFS_SETCHUNKSIZE(achunk);
3032 if (aflags & AFSCALL_INIT_MEMCACHE) {
3034 * Use a memory cache instead of a disk cache
3036 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3037 afs_cacheType = &afs_MemCacheOps;
3038 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3039 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3040 /* ablocks is reported in 1K blocks */
3041 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3043 afs_warn("afsd: memory cache too large for available memory.\n");
3044 afs_warn("afsd: AFS files cannot be accessed.\n\n");
3046 afiles = ablocks = 0;
3048 afs_warn("Memory cache: Allocating %d dcache entries...",
3051 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3052 afs_cacheType = &afs_UfsCacheOps;
3055 if (aDentries > 512)
3056 afs_dhashsize = 2048;
3057 /* initialize hash tables */
3058 afs_dvhashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3059 osi_Assert(afs_dvhashTbl != NULL);
3060 afs_dchashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3061 osi_Assert(afs_dchashTbl != NULL);
3062 for (i = 0; i < afs_dhashsize; i++) {
3063 afs_dvhashTbl[i] = NULLIDX;
3064 afs_dchashTbl[i] = NULLIDX;
3066 afs_dvnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3067 osi_Assert(afs_dvnextTbl != NULL);
3068 afs_dcnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3069 osi_Assert(afs_dcnextTbl != NULL);
3070 for (i = 0; i < afiles; i++) {
3071 afs_dvnextTbl[i] = NULLIDX;
3072 afs_dcnextTbl[i] = NULLIDX;
3075 /* Allocate and zero the pointer array to the dcache entries */
3076 afs_indexTable = afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3077 osi_Assert(afs_indexTable != NULL);
3078 memset(afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3079 afs_indexTimes = afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3080 osi_Assert(afs_indexTimes != NULL);
3081 memset(afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3082 afs_indexUnique = afs_osi_Alloc(afiles * sizeof(afs_uint32));
3083 osi_Assert(afs_indexUnique != NULL);
3084 memset(afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3085 afs_indexFlags = afs_osi_Alloc(afiles * sizeof(u_char));
3086 osi_Assert(afs_indexFlags != NULL);
3087 memset(afs_indexFlags, 0, afiles * sizeof(char));
3089 /* Allocate and thread the struct dcache entries themselves */
3090 tdp = afs_Initial_freeDSList =
3091 afs_osi_Alloc(aDentries * sizeof(struct dcache));
3092 osi_Assert(tdp != NULL);
3093 memset(tdp, 0, aDentries * sizeof(struct dcache));
3094 #ifdef KERNEL_HAVE_PIN
3095 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3096 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3097 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3098 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3099 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3100 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3101 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3102 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3103 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3106 afs_freeDSList = &tdp[0];
3107 for (i = 0; i < aDentries - 1; i++) {
3108 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3109 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3110 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3111 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3113 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3114 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3115 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3116 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3118 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3119 afs_cacheBlocks = ablocks;
3120 afs_ComputeCacheParms(); /* compute parms based on cache size */
3122 afs_dcentries = aDentries;
3124 afs_stats_cmperf.cacheBucket0_Discarded =
3125 afs_stats_cmperf.cacheBucket1_Discarded =
3126 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3132 * Shuts down the cache.
3136 shutdown_dcache(void)
3140 #ifdef AFS_CACHE_VNODE_PATH
3141 if (cacheDiskType != AFS_FCACHE_TYPE_MEM) {
3143 for (i = 0; i < afs_cacheFiles; i++) {
3144 tdc = afs_indexTable[i];
3146 afs_osi_FreeStr(tdc->f.inode.ufs);
3152 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3153 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3154 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3155 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3156 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3157 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3158 afs_osi_Free(afs_Initial_freeDSList,
3159 afs_dcentries * sizeof(struct dcache));
3160 #ifdef KERNEL_HAVE_PIN
3161 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3162 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3163 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3164 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3165 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3166 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3167 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3171 for (i = 0; i < afs_dhashsize; i++) {
3172 afs_dvhashTbl[i] = NULLIDX;
3173 afs_dchashTbl[i] = NULLIDX;
3176 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3177 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3179 afs_blocksUsed = afs_dcentries = 0;
3180 afs_stats_cmperf.cacheBucket0_Discarded =
3181 afs_stats_cmperf.cacheBucket1_Discarded =
3182 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3183 hzero(afs_indexCounter);
3185 afs_freeDCCount = 0;
3186 afs_freeDCList = NULLIDX;
3187 afs_discardDCList = NULLIDX;
3188 afs_freeDSList = afs_Initial_freeDSList = 0;
3190 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3196 * Get a dcache ready for writing, respecting the current cache size limits
3198 * len is required because afs_GetDCache with flag == 4 expects the length
3199 * field to be filled. It decides from this whether it's necessary to fetch
3200 * data into the chunk before writing or not (when the whole chunk is
3203 * \param avc The vcache to fetch a dcache for
3204 * \param filePos The start of the section to be written
3205 * \param len The length of the section to be written
3209 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3210 * must be released and afs_PutDCache() called to free dcache.
3213 * \note avc->lock must be held on entry. Function may release and reobtain
3214 * avc->lock and GLOCK.
3218 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3219 afs_size_t len, struct vrequest *areq,
3222 struct dcache *tdc = NULL;
3225 /* read the cached info */
3227 tdc = afs_FindDCache(avc, filePos);
3229 ObtainWriteLock(&tdc->lock, 657);
3230 } else if (afs_blocksUsed >
3231 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3232 tdc = afs_FindDCache(avc, filePos);
3234 ObtainWriteLock(&tdc->lock, 658);
3235 if (!hsame(tdc->f.versionNo, avc->f.m.DataVersion)
3236 || (tdc->dflags & DFFetching)) {
3237 ReleaseWriteLock(&tdc->lock);
3243 afs_MaybeWakeupTruncateDaemon();
3244 while (afs_blocksUsed >
3245 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3246 ReleaseWriteLock(&avc->lock);
3247 if (afs_blocksUsed - afs_blocksDiscarded >
3248 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3249 afs_WaitForCacheDrain = 1;
3250 afs_osi_Sleep(&afs_WaitForCacheDrain);
3252 afs_MaybeFreeDiscardedDCache();
3253 afs_MaybeWakeupTruncateDaemon();
3254 ObtainWriteLock(&avc->lock, 509);
3256 avc->f.states |= CDirty;
3257 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3259 ObtainWriteLock(&tdc->lock, 659);
3262 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3264 ObtainWriteLock(&tdc->lock, 660);
3267 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3268 afs_stats_cmperf.cacheCurrDirtyChunks++;
3269 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3271 if (!(tdc->f.states & DWriting)) {
3272 /* don't mark entry as mod if we don't have to */
3273 tdc->f.states |= DWriting;
3274 tdc->dflags |= DFEntryMod;
3281 * Make a shadow copy of a dir's dcache. It's used for disconnected
3282 * operations like remove/create/rename to keep the original directory data.
3283 * On reconnection, we can diff the original data with the server and get the
3284 * server changes and with the local data to get the local changes.
3286 * \param avc The dir vnode.
3287 * \param adc The dir dcache.
3289 * \return 0 for success.
3291 * \note The vcache entry must be write locked.
3292 * \note The dcache entry must be read locked.
3295 afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3297 int i, code, ret_code = 0, written, trans_size;
3298 struct dcache *new_dc = NULL;
3299 struct osi_file *tfile_src, *tfile_dst;
3300 struct VenusFid shadow_fid;
3303 /* Is this a dir? */
3304 if (vType(avc) != VDIR)
3307 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3310 /* Generate a fid for the shadow dir. */
3311 shadow_fid.Cell = avc->f.fid.Cell;
3312 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3313 afs_GenShadowFid(&shadow_fid);
3315 ObtainWriteLock(&afs_xdcache, 716);
3317 /* Get a fresh dcache. */
3318 new_dc = afs_AllocDCache(avc, 0, 0, &shadow_fid);
3320 ObtainReadLock(&adc->mflock);
3322 /* Set up the new fid. */
3323 /* Copy interesting data from original dir dcache. */
3324 new_dc->mflags = adc->mflags;
3325 new_dc->dflags = adc->dflags;
3326 new_dc->f.modTime = adc->f.modTime;
3327 new_dc->f.versionNo = adc->f.versionNo;
3328 new_dc->f.states = adc->f.states;
3329 new_dc->f.chunk= adc->f.chunk;
3330 new_dc->f.chunkBytes = adc->f.chunkBytes;
3332 ReleaseReadLock(&adc->mflock);
3334 /* Now add to the two hash chains */
3335 i = DCHash(&shadow_fid, 0);
3336 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[i];
3337 afs_dchashTbl[i] = new_dc->index;
3339 i = DVHash(&shadow_fid);
3340 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[i];
3341 afs_dvhashTbl[i] = new_dc->index;
3343 ReleaseWriteLock(&afs_xdcache);
3345 /* Alloc a 4k block. */
3346 data = afs_osi_Alloc(4096);
3348 afs_warn("afs_MakeShadowDir: could not alloc data\n");
3353 /* Open the files. */
3354 tfile_src = afs_CFileOpen(&adc->f.inode);
3355 tfile_dst = afs_CFileOpen(&new_dc->f.inode);
3357 /* And now copy dir dcache data into this dcache,
3361 while (written < adc->f.chunkBytes) {
3362 trans_size = adc->f.chunkBytes - written;
3363 if (trans_size > 4096)
3366 /* Read a chunk from the dcache. */
3367 code = afs_CFileRead(tfile_src, written, data, trans_size);
3368 if (code < trans_size) {
3373 /* Write it to the new dcache. */
3374 code = afs_CFileWrite(tfile_dst, written, data, trans_size);
3375 if (code < trans_size) {
3380 written+=trans_size;
3383 afs_CFileClose(tfile_dst);
3384 afs_CFileClose(tfile_src);
3386 afs_osi_Free(data, 4096);
3388 ReleaseWriteLock(&new_dc->lock);
3389 afs_PutDCache(new_dc);
3392 ObtainWriteLock(&afs_xvcache, 763);
3393 ObtainWriteLock(&afs_disconDirtyLock, 765);
3394 QAdd(&afs_disconShadow, &avc->shadowq);
3395 osi_Assert((afs_RefVCache(avc) == 0));
3396 ReleaseWriteLock(&afs_disconDirtyLock);
3397 ReleaseWriteLock(&afs_xvcache);
3399 avc->f.shadow.vnode = shadow_fid.Fid.Vnode;
3400 avc->f.shadow.unique = shadow_fid.Fid.Unique;
3408 * Delete the dcaches of a shadow dir.
3410 * \param avc The vcache containing the shadow fid.
3412 * \note avc must be write locked.
3415 afs_DeleteShadowDir(struct vcache *avc)
3418 struct VenusFid shadow_fid;
3420 shadow_fid.Cell = avc->f.fid.Cell;
3421 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3422 shadow_fid.Fid.Vnode = avc->f.shadow.vnode;
3423 shadow_fid.Fid.Unique = avc->f.shadow.unique;
3425 tdc = afs_FindDCacheByFid(&shadow_fid);
3427 afs_HashOutDCache(tdc, 1);
3428 afs_DiscardDCache(tdc);
3431 avc->f.shadow.vnode = avc->f.shadow.unique = 0;
3432 ObtainWriteLock(&afs_disconDirtyLock, 708);
3433 QRemove(&avc->shadowq);
3434 ReleaseWriteLock(&afs_disconDirtyLock);
3435 afs_PutVCache(avc); /* Because we held it when we added to the queue */
3439 * Populate a dcache with empty chunks up to a given file size,
3440 * used before extending a file in order to avoid 'holes' which
3441 * we can't access in disconnected mode.
3443 * \param avc The vcache which is being extended (locked)
3444 * \param alen The new length of the file
3448 afs_PopulateDCache(struct vcache *avc, afs_size_t apos, struct vrequest *areq)
3451 afs_size_t len, offset;
3452 afs_int32 start, end;
3454 /* We're doing this to deal with the situation where we extend
3455 * by writing after lseek()ing past the end of the file . If that
3456 * extension skips chunks, then those chunks won't be created, and
3457 * GetDCache will assume that they have to be fetched from the server.
3458 * So, for each chunk between the current file position, and the new
3459 * length we GetDCache for that chunk.
3462 if (AFS_CHUNK(apos) == 0 || apos <= avc->f.m.Length)
3465 if (avc->f.m.Length == 0)
3468 start = AFS_CHUNK(avc->f.m.Length)+1;
3470 end = AFS_CHUNK(apos);
3473 len = AFS_CHUNKTOSIZE(start);
3474 tdc = afs_GetDCache(avc, AFS_CHUNKTOBASE(start), areq, &offset, &len, 4);