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"
25 /* Forward declarations. */
26 static void afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint);
27 static int afs_FreeDiscardedDCache(void);
28 static void afs_DiscardDCache(struct dcache *);
29 static void afs_FreeDCache(struct dcache *);
31 static afs_int32 afs_DCGetBucket(struct vcache *);
32 static void afs_DCAdjustSize(struct dcache *, afs_int32, afs_int32);
33 static void afs_DCMoveBucket(struct dcache *, afs_int32, afs_int32);
34 static void afs_DCSizeInit(void);
35 static afs_int32 afs_DCWhichBucket(afs_int32, afs_int32);
38 * --------------------- Exported definitions ---------------------
41 afs_int32 afs_blocksUsed_0; /*!< 1K blocks in cache - in theory is zero */
42 afs_int32 afs_blocksUsed_1; /*!< 1K blocks in cache */
43 afs_int32 afs_blocksUsed_2; /*!< 1K blocks in cache */
44 afs_int32 afs_pct1 = -1;
45 afs_int32 afs_pct2 = -1;
46 afs_uint32 afs_tpct1 = 0;
47 afs_uint32 afs_tpct2 = 0;
48 afs_uint32 splitdcache = 0;
50 afs_lock_t afs_xdcache; /*!< Lock: alloc new disk cache entries */
51 afs_int32 afs_freeDCList; /*!< Free list for disk cache entries */
52 afs_int32 afs_freeDCCount; /*!< Count of elts in freeDCList */
53 afs_int32 afs_discardDCList; /*!< Discarded disk cache entries */
54 afs_int32 afs_discardDCCount; /*!< Count of elts in discardDCList */
55 struct dcache *afs_freeDSList; /*!< Free list for disk slots */
56 struct dcache *afs_Initial_freeDSList; /*!< Initial list for above */
57 afs_dcache_id_t cacheInode; /*!< Inode for CacheItems file */
58 struct osi_file *afs_cacheInodep = 0; /*!< file for CacheItems inode */
59 struct afs_q afs_DLRU; /*!< dcache LRU */
60 afs_int32 afs_dhashsize = 1024;
61 afs_int32 *afs_dvhashTbl; /*!< Data cache hash table: hashed by FID + chunk number. */
62 afs_int32 *afs_dchashTbl; /*!< Data cache hash table: hashed by FID. */
63 afs_int32 *afs_dvnextTbl; /*!< Dcache hash table links */
64 afs_int32 *afs_dcnextTbl; /*!< Dcache hash table links */
65 struct dcache **afs_indexTable; /*!< Pointers to dcache entries */
66 afs_hyper_t *afs_indexTimes; /*!< Dcache entry Access times */
67 afs_int32 *afs_indexUnique; /*!< dcache entry Fid.Unique */
68 unsigned char *afs_indexFlags; /*!< (only one) Is there data there? */
69 afs_hyper_t afs_indexCounter; /*!< Fake time for marking index
71 afs_int32 afs_cacheFiles = 0; /*!< Size of afs_indexTable */
72 afs_int32 afs_cacheBlocks; /*!< 1K blocks in cache */
73 afs_int32 afs_cacheStats; /*!< Stat entries in cache */
74 afs_int32 afs_blocksUsed; /*!< Number of blocks in use */
75 afs_int32 afs_blocksDiscarded; /*!<Blocks freed but not truncated */
76 afs_int32 afs_fsfragsize = AFS_MIN_FRAGSIZE; /*!< Underlying Filesystem minimum unit
77 *of disk allocation usually 1K
78 *this value is (truefrag -1 ) to
79 *save a bunch of subtracts... */
80 #ifdef AFS_64BIT_CLIENT
81 #ifdef AFS_VM_RDWR_ENV
82 afs_size_t afs_vmMappingEnd; /* !< For large files (>= 2GB) the VM
83 * mapping an 32bit addressing machines
84 * can only be used below the 2 GB
85 * line. From this point upwards we
86 * must do direct I/O into the cache
87 * files. The value should be on a
89 #endif /* AFS_VM_RDWR_ENV */
90 #endif /* AFS_64BIT_CLIENT */
92 /* The following is used to ensure that new dcache's aren't obtained when
93 * the cache is nearly full.
95 int afs_WaitForCacheDrain = 0;
96 int afs_TruncateDaemonRunning = 0;
97 int afs_CacheTooFull = 0;
98 afs_uint32 afs_CacheTooFullCount = 0;
99 afs_uint32 afs_WaitForCacheDrainCount = 0;
101 afs_int32 afs_dcentries; /*!< In-memory dcache entries */
104 int dcacheDisabled = 0;
106 struct afs_cacheOps afs_UfsCacheOps = {
107 #ifndef HAVE_STRUCT_LABEL_SUPPORT
120 .truncate = osi_UFSTruncate,
121 .fread = afs_osi_Read,
122 .fwrite = afs_osi_Write,
123 .close = osi_UFSClose,
124 .vreadUIO = afs_UFSReadUIO,
125 .vwriteUIO = afs_UFSWriteUIO,
126 .GetDSlot = afs_UFSGetDSlot,
127 .GetVolSlot = afs_UFSGetVolSlot,
128 .HandleLink = afs_UFSHandleLink,
132 struct afs_cacheOps afs_MemCacheOps = {
133 #ifndef HAVE_STRUCT_LABEL_SUPPORT
135 afs_MemCacheTruncate,
145 .open = afs_MemCacheOpen,
146 .truncate = afs_MemCacheTruncate,
147 .fread = afs_MemReadBlk,
148 .fwrite = afs_MemWriteBlk,
149 .close = afs_MemCacheClose,
150 .vreadUIO = afs_MemReadUIO,
151 .vwriteUIO = afs_MemWriteUIO,
152 .GetDSlot = afs_MemGetDSlot,
153 .GetVolSlot = afs_MemGetVolSlot,
154 .HandleLink = afs_MemHandleLink,
158 int cacheDiskType; /*Type of backing disk for cache */
159 struct afs_cacheOps *afs_cacheType;
161 /* calculate number of 1k blocks needed, rounded up to nearest afs_fsfragsize */
162 static_inline afs_int32
163 afs_round_to_fsfragsize(afs_int32 bytes)
165 return (((bytes + afs_fsfragsize) ^ afs_fsfragsize) >> 10);
169 * The PFlush algorithm makes use of the fact that Fid.Unique is not used in
170 * below hash algorithms. Change it if need be so that flushing algorithm
171 * doesn't move things from one hash chain to another.
173 /*Vnode, Chunk -> Hash table index */
174 int DCHash(struct VenusFid *fid, afs_int32 chunk)
178 buf[0] = fid->Fid.Volume;
179 buf[1] = fid->Fid.Vnode;
181 return opr_jhash(buf, 3, 0) & (afs_dhashsize - 1);
183 /*Vnode -> Other hash table index */
184 int DVHash(struct VenusFid *fid)
186 return opr_jhash_int2(fid->Fid.Volume, fid->Fid.Vnode, 0) &
191 * Where is this vcache's entry associated dcache located/
192 * \param avc The vcache entry.
193 * \return Bucket index:
198 afs_DCGetBucket(struct vcache *avc)
203 /* This should be replaced with some sort of user configurable function */
204 if (avc->f.states & CRO) {
206 } else if (avc->f.states & CBackup) {
216 * Readjust a dcache's size.
218 * \param adc The dcache to be adjusted.
219 * \param oldSize Old size for the dcache.
220 * \param newSize The new size to be adjusted to.
224 afs_DCAdjustSize(struct dcache *adc, afs_int32 oldSize, afs_int32 newSize)
226 afs_int32 adjustSize = newSize - oldSize;
234 afs_blocksUsed_0 += adjustSize;
235 afs_stats_cmperf.cacheBucket0_Discarded += oldSize;
238 afs_blocksUsed_1 += adjustSize;
239 afs_stats_cmperf.cacheBucket1_Discarded += oldSize;
242 afs_blocksUsed_2 += adjustSize;
243 afs_stats_cmperf.cacheBucket2_Discarded += oldSize;
251 * Move a dcache from one bucket to another.
253 * \param adc Operate on this dcache.
254 * \param size Size in bucket (?).
255 * \param newBucket Destination bucket.
259 afs_DCMoveBucket(struct dcache *adc, afs_int32 size, afs_int32 newBucket)
264 /* Substract size from old bucket. */
268 afs_blocksUsed_0 -= size;
271 afs_blocksUsed_1 -= size;
274 afs_blocksUsed_2 -= size;
278 /* Set new bucket and increase destination bucket size. */
279 adc->bucket = newBucket;
284 afs_blocksUsed_0 += size;
287 afs_blocksUsed_1 += size;
290 afs_blocksUsed_2 += size;
298 * Init split caches size.
303 afs_blocksUsed_0 = afs_blocksUsed_1 = afs_blocksUsed_2 = 0;
312 afs_DCWhichBucket(afs_int32 phase, afs_int32 bucket)
317 afs_pct1 = afs_blocksUsed_1 / (afs_cacheBlocks / 100);
318 afs_pct2 = afs_blocksUsed_2 / (afs_cacheBlocks / 100);
320 /* Short cut: if we don't know about it, try to kill it */
321 if (phase < 2 && afs_blocksUsed_0)
324 if (afs_pct1 > afs_tpct1)
326 if (afs_pct2 > afs_tpct2)
328 return 0; /* unlikely */
333 * Warn about failing to store a file.
335 * \param acode Associated error code.
336 * \param avolume Volume involved.
337 * \param aflags How to handle the output:
338 * aflags & 1: Print out on console
339 * aflags & 2: Print out on controlling tty
341 * \note Environment: Call this from close call when vnodeops is RCS unlocked.
345 afs_StoreWarn(afs_int32 acode, afs_int32 avolume,
348 static char problem_fmt[] =
349 "afs: failed to store file in volume %d (%s)\n";
350 static char problem_fmt_w_error[] =
351 "afs: failed to store file in volume %d (error %d)\n";
352 static char netproblems[] = "network problems";
353 static char partfull[] = "partition full";
354 static char overquota[] = "over quota";
356 AFS_STATCNT(afs_StoreWarn);
362 afs_warn(problem_fmt, avolume, netproblems);
364 afs_warnuser(problem_fmt, avolume, netproblems);
365 } else if (acode == ENOSPC) {
370 afs_warn(problem_fmt, avolume, partfull);
372 afs_warnuser(problem_fmt, avolume, partfull);
375 /* EDQUOT doesn't exist on solaris and won't be sent by the server.
376 * Instead ENOSPC will be sent...
378 if (acode == EDQUOT) {
383 afs_warn(problem_fmt, avolume, overquota);
385 afs_warnuser(problem_fmt, avolume, overquota);
393 afs_warn(problem_fmt_w_error, avolume, acode);
395 afs_warnuser(problem_fmt_w_error, avolume, acode);
400 * Try waking up truncation daemon, if it's worth it.
403 afs_MaybeWakeupTruncateDaemon(void)
405 if (!afs_CacheTooFull && afs_CacheIsTooFull()) {
406 afs_CacheTooFullCount++;
407 afs_CacheTooFull = 1;
408 if (!afs_TruncateDaemonRunning)
409 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
410 } else if (!afs_TruncateDaemonRunning
411 && afs_blocksDiscarded > CM_MAXDISCARDEDCHUNKS) {
412 afs_osi_Wakeup((int *)afs_CacheTruncateDaemon);
417 * Wait for cache drain if conditions warrant.
420 afs_MaybeWaitForCacheDrain(void)
422 if (afs_blocksUsed - afs_blocksDiscarded >
423 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
424 if (afs_WaitForCacheDrain == 0)
425 afs_WaitForCacheDrainCount++;
426 afs_WaitForCacheDrain = 1;
427 afs_osi_Sleep(&afs_WaitForCacheDrain);
432 * Keep statistics on run time for afs_CacheTruncateDaemon.
434 struct afs_CTD_stats CTD_stats;
436 u_int afs_min_cache = 0;
439 * If there are waiters for the cache to drain, wake them if
440 * the number of free or discarded cache blocks reaches the
441 * CM_CACHESIZEDDRAINEDPCT limit.
444 * This routine must be called with the afs_xdcache lock held
448 afs_WakeCacheWaitersIfDrained(void)
450 if (afs_WaitForCacheDrain) {
451 if ((afs_blocksUsed - afs_blocksDiscarded) <=
452 PERCENT(CM_CACHESIZEDRAINEDPCT, afs_cacheBlocks)) {
453 afs_WaitForCacheDrain = 0;
454 afs_osi_Wakeup(&afs_WaitForCacheDrain);
460 * Keeps the cache clean and free by truncating uneeded files, when used.
465 afs_CacheTruncateDaemon(void)
467 osi_timeval32_t CTD_tmpTime;
468 struct afs_CTD_stats *ctd_stats = &CTD_stats;
472 PERCENT((100 - CM_DCACHECOUNTFREEPCT + CM_DCACHEEXTRAPCT), afs_cacheFiles);
475 (((10 * AFS_CHUNKSIZE(0)) + afs_fsfragsize) & ~afs_fsfragsize) >> 10;
477 osi_GetTime(&ctd_stats->CTD_afterSleep);
478 afs_TruncateDaemonRunning = 1;
480 cb_lowat = PERCENT((CM_DCACHESPACEFREEPCT - CM_DCACHEEXTRAPCT), afs_cacheBlocks);
481 ObtainWriteLock(&afs_xdcache, 266);
482 if (afs_CacheTooFull || afs_WaitForCacheDrain) {
483 int space_needed, slots_needed;
484 /* if we get woken up, we should try to clean something out */
485 for (counter = 0; counter < 10; counter++) {
487 afs_blocksUsed - afs_blocksDiscarded - cb_lowat;
488 if (space_needed < 0)
491 dc_hiwat - afs_freeDCCount - afs_discardDCCount;
492 if (slots_needed < 0)
494 if (slots_needed || space_needed)
495 afs_GetDownD(slots_needed, &space_needed, 0);
496 if ((space_needed <= 0) && (slots_needed <= 0)) {
499 if (afs_termState == AFSOP_STOP_TRUNCDAEMON)
502 if (!afs_CacheIsTooFull()) {
503 afs_CacheTooFull = 0;
504 afs_WakeCacheWaitersIfDrained();
506 } /* end of cache cleanup */
507 ReleaseWriteLock(&afs_xdcache);
510 * This is a defensive check to try to avoid starving threads
511 * that may need the global lock so thay can help free some
512 * cache space. If this thread won't be sleeping or truncating
513 * any cache files then give up the global lock so other
514 * threads get a chance to run.
516 if ((afs_termState != AFSOP_STOP_TRUNCDAEMON) && afs_CacheTooFull
517 && (!afs_blocksDiscarded || afs_WaitForCacheDrain)) {
518 afs_osi_Wait(100, 0, 0); /* 100 milliseconds */
522 * This is where we free the discarded cache elements.
524 while (afs_blocksDiscarded && !afs_WaitForCacheDrain
525 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
526 int code = afs_FreeDiscardedDCache();
528 /* If we can't free any discarded dcache entries, that's okay.
529 * We're just doing this in the background; if someone needs
530 * discarded entries freed, they will try it themselves and/or
531 * signal us that the cache is too full. In any case, we'll
532 * try doing this again the next time we run through the loop.
538 /* See if we need to continue to run. Someone may have
539 * signalled us while we were executing.
541 if (!afs_WaitForCacheDrain && !afs_CacheTooFull
542 && (afs_termState != AFSOP_STOP_TRUNCDAEMON)) {
543 /* Collect statistics on truncate daemon. */
544 ctd_stats->CTD_nSleeps++;
545 osi_GetTime(&ctd_stats->CTD_beforeSleep);
546 afs_stats_GetDiff(CTD_tmpTime, ctd_stats->CTD_afterSleep,
547 ctd_stats->CTD_beforeSleep);
548 afs_stats_AddTo(ctd_stats->CTD_runTime, CTD_tmpTime);
550 afs_TruncateDaemonRunning = 0;
551 afs_osi_Sleep((int *)afs_CacheTruncateDaemon);
552 afs_TruncateDaemonRunning = 1;
554 osi_GetTime(&ctd_stats->CTD_afterSleep);
555 afs_stats_GetDiff(CTD_tmpTime, ctd_stats->CTD_beforeSleep,
556 ctd_stats->CTD_afterSleep);
557 afs_stats_AddTo(ctd_stats->CTD_sleepTime, CTD_tmpTime);
559 if (afs_termState == AFSOP_STOP_TRUNCDAEMON) {
560 afs_termState = AFSOP_STOP_AFSDB;
561 afs_osi_Wakeup(&afs_termState);
569 * Make adjustment for the new size in the disk cache entry
571 * \note Major Assumptions Here:
572 * Assumes that frag size is an integral power of two, less one,
573 * and that this is a two's complement machine. I don't
574 * know of any filesystems which violate this assumption...
576 * \param adc Ptr to dcache entry.
577 * \param anewsize New size desired.
582 afs_AdjustSize(struct dcache *adc, afs_int32 newSize)
586 AFS_STATCNT(afs_AdjustSize);
588 if (newSize > afs_OtherCSize && !(adc->f.fid.Fid.Vnode & 1)) {
589 /* No non-dir cache files should be larger than the chunk size.
590 * (Directory blobs are fetched in a single chunk file, so directories
591 * can be larger.) If someone is requesting that a chunk is larger than
592 * the chunk size, something strange is happening. Log a message about
593 * it, to give a hint to subsequent strange behavior, if any occurs. */
597 afs_warn("afs: Warning: dcache %d is very large (%d > %d). This "
598 "should not happen, but trying to continue regardless. If "
599 "AFS starts hanging or behaving strangely, this might be "
601 adc->index, newSize, afs_OtherCSize);
605 adc->dflags |= DFEntryMod;
606 oldSize = afs_round_to_fsfragsize(adc->f.chunkBytes);
607 adc->f.chunkBytes = newSize;
610 newSize = afs_round_to_fsfragsize(newSize);
611 afs_DCAdjustSize(adc, oldSize, newSize);
612 if ((newSize > oldSize) && !AFS_IS_DISCONNECTED) {
614 /* We're growing the file, wakeup the daemon */
615 afs_MaybeWakeupTruncateDaemon();
617 afs_blocksUsed += (newSize - oldSize);
618 afs_stats_cmperf.cacheBlocksInUse = afs_blocksUsed; /* XXX */
623 * This routine is responsible for moving at least one entry (but up
624 * to some number of them) from the LRU queue to the free queue.
626 * \param anumber Number of entries that should ideally be moved.
627 * \param aneedSpace How much space we need (1K blocks);
630 * The anumber parameter is just a hint; at least one entry MUST be
631 * moved, or we'll panic. We must be called with afs_xdcache
632 * write-locked. We should try to satisfy both anumber and aneedspace,
633 * whichever is more demanding - need to do several things:
634 * 1. only grab up to anumber victims if aneedSpace <= 0, not
635 * the whole set of MAXATONCE.
636 * 2. dynamically choose MAXATONCE to reflect severity of
637 * demand: something like (*aneedSpace >> (logChunk - 9))
639 * \note N.B. if we're called with aneedSpace <= 0 and anumber > 0, that
640 * indicates that the cache is not properly configured/tuned or
641 * something. We should be able to automatically correct that problem.
644 #define MAXATONCE 16 /* max we can obtain at once */
646 afs_GetDownD(int anumber, int *aneedSpace, afs_int32 buckethint)
650 struct VenusFid *afid;
655 afs_uint32 victims[MAXATONCE];
656 struct dcache *victimDCs[MAXATONCE];
657 afs_hyper_t victimTimes[MAXATONCE]; /* youngest (largest LRU time) first */
658 afs_uint32 victimPtr; /* next free item in victim arrays */
659 afs_hyper_t maxVictimTime; /* youngest (largest LRU time) victim */
660 afs_uint32 maxVictimPtr; /* where it is */
664 AFS_STATCNT(afs_GetDownD);
666 if (CheckLock(&afs_xdcache) != -1)
667 osi_Panic("getdownd nolock");
668 /* decrement anumber first for all dudes in free list */
669 /* SHOULD always decrement anumber first, even if aneedSpace >0,
670 * because we should try to free space even if anumber <=0 */
671 if (!aneedSpace || *aneedSpace <= 0) {
672 anumber -= afs_freeDCCount;
674 return; /* enough already free */
678 /* bounds check parameter */
679 if (anumber > MAXATONCE)
680 anumber = MAXATONCE; /* all we can do */
682 /* rewrite so phases include a better eligiblity for gc test*/
684 * The phase variable manages reclaims. Set to 0, the first pass,
685 * we don't reclaim active entries, or other than target bucket.
686 * Set to 1, we reclaim even active ones in target bucket.
687 * Set to 2, we reclaim any inactive one.
688 * Set to 3, we reclaim even active ones. On Solaris, we also reclaim
689 * entries whose corresponding vcache has a nonempty multiPage list, when
698 for (i = 0; i < afs_cacheFiles; i++)
699 /* turn off all flags */
700 afs_indexFlags[i] &= ~IFFlag;
702 while (anumber > 0 || (aneedSpace && *aneedSpace > 0)) {
703 /* find oldest entries for reclamation */
704 maxVictimPtr = victimPtr = 0;
705 hzero(maxVictimTime);
706 curbucket = afs_DCWhichBucket(phase, buckethint);
707 /* select victims from access time array */
708 for (i = 0; i < afs_cacheFiles; i++) {
709 if (afs_indexFlags[i] & (IFDataMod | IFFree | IFDiscarded)) {
710 /* skip if dirty or already free */
713 tdc = afs_indexTable[i];
714 if (tdc && (curbucket != tdc->bucket) && (phase < 4))
716 /* Wrong bucket; can't use it! */
719 if (tdc && (tdc->refCount != 0)) {
720 /* Referenced; can't use it! */
723 hset(vtime, afs_indexTimes[i]);
725 /* if we've already looked at this one, skip it */
726 if (afs_indexFlags[i] & IFFlag)
729 if (victimPtr < MAXATONCE) {
730 /* if there's at least one free victim slot left */
731 victims[victimPtr] = i;
732 hset(victimTimes[victimPtr], vtime);
733 if (hcmp(vtime, maxVictimTime) > 0) {
734 hset(maxVictimTime, vtime);
735 maxVictimPtr = victimPtr;
738 } else if (hcmp(vtime, maxVictimTime) < 0) {
740 * We're older than youngest victim, so we replace at
743 /* find youngest (largest LRU) victim */
746 osi_Panic("getdownd local");
748 hset(victimTimes[j], vtime);
749 /* recompute maxVictimTime */
750 hset(maxVictimTime, vtime);
751 for (j = 0; j < victimPtr; j++)
752 if (hcmp(maxVictimTime, victimTimes[j]) < 0) {
753 hset(maxVictimTime, victimTimes[j]);
759 /* now really reclaim the victims */
760 j = 0; /* flag to track if we actually got any of the victims */
761 /* first, hold all the victims, since we're going to release the lock
762 * during the truncate operation.
764 for (i = 0; i < victimPtr; i++) {
765 tdc = afs_GetValidDSlot(victims[i]);
766 /* We got tdc->tlock(R) here */
767 if (tdc && tdc->refCount == 1)
772 ReleaseReadLock(&tdc->tlock);
777 for (i = 0; i < victimPtr; i++) {
778 /* q is first elt in dcache entry */
780 /* now, since we're dropping the afs_xdcache lock below, we
781 * have to verify, before proceeding, that there are no other
782 * references to this dcache entry, even now. Note that we
783 * compare with 1, since we bumped it above when we called
784 * afs_GetValidDSlot to preserve the entry's identity.
786 if (tdc && tdc->refCount == 1) {
787 unsigned char chunkFlags;
788 afs_size_t tchunkoffset = 0;
790 /* xdcache is lower than the xvcache lock */
791 ReleaseWriteLock(&afs_xdcache);
792 ObtainReadLock(&afs_xvcache);
793 tvc = afs_FindVCache(afid, 0 /* no stats, no vlru */ );
794 ReleaseReadLock(&afs_xvcache);
795 ObtainWriteLock(&afs_xdcache, 527);
797 if (tdc->refCount > 1)
800 tchunkoffset = AFS_CHUNKTOBASE(tdc->f.chunk);
801 chunkFlags = afs_indexFlags[tdc->index];
802 if (((phase & 1) == 0) && osi_Active(tvc))
804 if (((phase & 1) == 1) && osi_Active(tvc)
805 && (tvc->f.states & CDCLock)
806 && (chunkFlags & IFAnyPages))
808 if (chunkFlags & IFDataMod)
810 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
811 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, skip,
812 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
813 ICL_HANDLE_OFFSET(tchunkoffset));
815 #if defined(AFS_SUN5_ENV)
817 * Now we try to invalidate pages. We do this only for
818 * Solaris. For other platforms, it's OK to recycle a
819 * dcache entry out from under a page, because the strategy
820 * function can call afs_GetDCache().
822 if (!skip && (chunkFlags & IFAnyPages)) {
825 ReleaseWriteLock(&afs_xdcache);
826 ObtainWriteLock(&tvc->vlock, 543);
827 if (!QEmpty(&tvc->multiPage)) {
828 if (phase < 3 || osi_VM_MultiPageConflict(tvc, tdc)) {
833 /* block locking pages */
834 tvc->vstates |= VPageCleaning;
835 /* block getting new pages */
837 ReleaseWriteLock(&tvc->vlock);
838 /* One last recheck */
839 ObtainWriteLock(&afs_xdcache, 333);
840 chunkFlags = afs_indexFlags[tdc->index];
841 if (tdc->refCount > 1 || (chunkFlags & IFDataMod)
842 || (osi_Active(tvc) && (tvc->f.states & CDCLock)
843 && (chunkFlags & IFAnyPages))) {
845 ReleaseWriteLock(&afs_xdcache);
848 ReleaseWriteLock(&afs_xdcache);
850 code = osi_VM_GetDownD(tvc, tdc);
852 ObtainWriteLock(&afs_xdcache, 269);
853 /* we actually removed all pages, clean and dirty */
855 afs_indexFlags[tdc->index] &=
856 ~(IFDirtyPages | IFAnyPages);
859 ReleaseWriteLock(&afs_xdcache);
861 ObtainWriteLock(&tvc->vlock, 544);
862 if (--tvc->activeV == 0
863 && (tvc->vstates & VRevokeWait)) {
864 tvc->vstates &= ~VRevokeWait;
865 afs_osi_Wakeup((char *)&tvc->vstates);
868 if (tvc->vstates & VPageCleaning) {
869 tvc->vstates &= ~VPageCleaning;
870 afs_osi_Wakeup((char *)&tvc->vstates);
873 ReleaseWriteLock(&tvc->vlock);
875 #endif /* AFS_SUN5_ENV */
877 ReleaseWriteLock(&afs_xdcache);
880 afs_PutVCache(tvc); /*XXX was AFS_FAST_RELE?*/
881 ObtainWriteLock(&afs_xdcache, 528);
882 if (afs_indexFlags[tdc->index] &
883 (IFDataMod | IFDirtyPages | IFAnyPages))
885 if (tdc->refCount > 1)
888 #if defined(AFS_SUN5_ENV)
890 /* no vnode, so IFDirtyPages is spurious (we don't
891 * sweep dcaches on vnode recycling, so we can have
892 * DIRTYPAGES set even when all pages are gone). Just
894 * Hold vcache lock to prevent vnode from being
895 * created while we're clearing IFDirtyPages.
897 afs_indexFlags[tdc->index] &=
898 ~(IFDirtyPages | IFAnyPages);
902 /* skip this guy and mark him as recently used */
903 afs_indexFlags[tdc->index] |= IFFlag;
904 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
905 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 2,
906 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
907 ICL_HANDLE_OFFSET(tchunkoffset));
909 /* flush this dude from the data cache and reclaim;
910 * first, make sure no one will care that we damage
911 * it, by removing it from all hash tables. Then,
912 * melt it down for parts. Note that any concurrent
913 * (new possibility!) calls to GetDownD won't touch
914 * this guy because his reference count is > 0. */
915 afs_Trace4(afs_iclSetp, CM_TRACE_GETDOWND,
916 ICL_TYPE_POINTER, tvc, ICL_TYPE_INT32, 3,
917 ICL_TYPE_INT32, tdc->index, ICL_TYPE_OFFSET,
918 ICL_HANDLE_OFFSET(tchunkoffset));
919 AFS_STATCNT(afs_gget);
920 afs_HashOutDCache(tdc, 1);
921 if (tdc->f.chunkBytes != 0) {
925 (tdc->f.chunkBytes + afs_fsfragsize) >> 10;
930 afs_DiscardDCache(tdc);
935 j = 1; /* we reclaimed at least one victim */
940 } /* end of for victims loop */
943 /* Phase is 0 and no one was found, so try phase 1 (ignore
944 * osi_Active flag) */
947 for (i = 0; i < afs_cacheFiles; i++)
948 /* turn off all flags */
949 afs_indexFlags[i] &= ~IFFlag;
952 /* found no one in phases 0-5, we're hosed */
956 } /* big while loop */
964 * Remove adc from any hash tables that would allow it to be located
965 * again by afs_FindDCache or afs_GetDCache.
967 * \param adc Pointer to dcache entry to remove from hash tables.
969 * \note Locks: Must have the afs_xdcache lock write-locked to call this function.
973 afs_HashOutDCache(struct dcache *adc, int zap)
977 AFS_STATCNT(afs_glink);
979 /* we know this guy's in the LRUQ. We'll move dude into DCQ below */
981 /* if this guy is in the hash table, pull him out */
982 if (adc->f.fid.Fid.Volume != 0) {
983 /* remove entry from first hash chains */
984 i = DCHash(&adc->f.fid, adc->f.chunk);
985 us = afs_dchashTbl[i];
986 if (us == adc->index) {
987 /* first dude in the list */
988 afs_dchashTbl[i] = afs_dcnextTbl[adc->index];
990 /* somewhere on the chain */
991 while (us != NULLIDX) {
992 if (afs_dcnextTbl[us] == adc->index) {
993 /* found item pointing at the one to delete */
994 afs_dcnextTbl[us] = afs_dcnextTbl[adc->index];
997 us = afs_dcnextTbl[us];
1000 osi_Panic("dcache hc");
1002 /* remove entry from *other* hash chain */
1003 i = DVHash(&adc->f.fid);
1004 us = afs_dvhashTbl[i];
1005 if (us == adc->index) {
1006 /* first dude in the list */
1007 afs_dvhashTbl[i] = afs_dvnextTbl[adc->index];
1009 /* somewhere on the chain */
1010 while (us != NULLIDX) {
1011 if (afs_dvnextTbl[us] == adc->index) {
1012 /* found item pointing at the one to delete */
1013 afs_dvnextTbl[us] = afs_dvnextTbl[adc->index];
1016 us = afs_dvnextTbl[us];
1019 osi_Panic("dcache hv");
1024 /* prevent entry from being found on a reboot (it is already out of
1025 * the hash table, but after a crash, we just look at fid fields of
1026 * stable (old) entries).
1028 adc->f.fid.Fid.Volume = 0; /* invalid */
1030 /* mark entry as modified */
1031 adc->dflags |= DFEntryMod;
1036 } /*afs_HashOutDCache */
1039 * Flush the given dcache entry, pulling it from hash chains
1040 * and truncating the associated cache file.
1042 * \param adc Ptr to dcache entry to flush.
1044 * \note Environment:
1045 * This routine must be called with the afs_xdcache lock held
1049 afs_FlushDCache(struct dcache *adc)
1051 AFS_STATCNT(afs_FlushDCache);
1053 * Bump the number of cache files flushed.
1055 afs_stats_cmperf.cacheFlushes++;
1057 /* remove from all hash tables */
1058 afs_HashOutDCache(adc, 1);
1060 /* Free its space; special case null operation, since truncate operation
1061 * in UFS is slow even in this case, and this allows us to pre-truncate
1062 * these files at more convenient times with fewer locks set
1063 * (see afs_GetDownD).
1065 if (adc->f.chunkBytes != 0) {
1066 afs_DiscardDCache(adc);
1067 afs_MaybeWakeupTruncateDaemon();
1069 afs_FreeDCache(adc);
1071 } /*afs_FlushDCache */
1075 * Put a dcache entry on the free dcache entry list.
1077 * \param adc dcache entry to free.
1079 * \note Environment: called with afs_xdcache lock write-locked.
1082 afs_FreeDCache(struct dcache *adc)
1084 /* Thread on free list, update free list count and mark entry as
1085 * freed in its indexFlags element. Also, ensure DCache entry gets
1086 * written out (set DFEntryMod).
1089 afs_dvnextTbl[adc->index] = afs_freeDCList;
1090 afs_freeDCList = adc->index;
1092 afs_indexFlags[adc->index] |= IFFree;
1093 adc->dflags |= DFEntryMod;
1095 afs_WakeCacheWaitersIfDrained();
1096 } /* afs_FreeDCache */
1099 * Discard the cache element by moving it to the discardDCList.
1100 * This puts the cache element into a quasi-freed state, where
1101 * the space may be reused, but the file has not been truncated.
1103 * \note Major Assumptions Here:
1104 * Assumes that frag size is an integral power of two, less one,
1105 * and that this is a two's complement machine. I don't
1106 * know of any filesystems which violate this assumption...
1108 * \param adr Ptr to dcache entry.
1110 * \note Environment:
1111 * Must be called with afs_xdcache write-locked.
1115 afs_DiscardDCache(struct dcache *adc)
1119 AFS_STATCNT(afs_DiscardDCache);
1121 osi_Assert(adc->refCount == 1);
1123 size = afs_round_to_fsfragsize(adc->f.chunkBytes);
1124 afs_blocksDiscarded += size;
1125 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1127 afs_dvnextTbl[adc->index] = afs_discardDCList;
1128 afs_discardDCList = adc->index;
1129 afs_discardDCCount++;
1131 adc->f.fid.Fid.Volume = 0;
1132 adc->dflags |= DFEntryMod;
1133 afs_indexFlags[adc->index] |= IFDiscarded;
1135 afs_WakeCacheWaitersIfDrained();
1136 } /*afs_DiscardDCache */
1139 * Get a dcache entry from the discard or free list
1141 * @param[out] adc On success, a dcache from the given list. Otherwise, NULL.
1142 * @param[in] indexp A pointer to the head of the dcache free list or discard
1143 * list (afs_freeDCList, or afs_discardDCList)
1145 * @return 0 on success. If there are no dcache slots available, return ENOSPC.
1146 * If we encountered an error in disk i/o while trying to find a
1147 * dcache, return EIO.
1149 * @pre afs_xdcache is write-locked
1152 afs_GetDSlotFromList(struct dcache **adc, afs_int32 *indexp)
1158 if (*indexp == NULLIDX) {
1162 tdc = afs_GetUnusedDSlot(*indexp);
1167 osi_Assert(tdc->refCount == 1);
1168 ReleaseReadLock(&tdc->tlock);
1169 *indexp = afs_dvnextTbl[tdc->index];
1170 afs_dvnextTbl[tdc->index] = NULLIDX;
1177 * Free the next element on the list of discarded cache elements.
1179 * Returns -1 if we encountered an error preventing us from freeing a
1180 * discarded dcache, or 0 on success.
1183 afs_FreeDiscardedDCache(void)
1186 struct osi_file *tfile;
1189 AFS_STATCNT(afs_FreeDiscardedDCache);
1191 ObtainWriteLock(&afs_xdcache, 510);
1192 if (!afs_blocksDiscarded) {
1193 ReleaseWriteLock(&afs_xdcache);
1198 * Get an entry from the list of discarded cache elements
1200 (void)afs_GetDSlotFromList(&tdc, &afs_discardDCList);
1202 ReleaseWriteLock(&afs_xdcache);
1206 afs_discardDCCount--;
1207 size = afs_round_to_fsfragsize(tdc->f.chunkBytes);
1208 afs_blocksDiscarded -= size;
1209 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1210 /* We can lock because we just took it off the free list */
1211 ObtainWriteLock(&tdc->lock, 626);
1212 ReleaseWriteLock(&afs_xdcache);
1215 * Truncate the element to reclaim its space
1217 tfile = afs_CFileOpen(&tdc->f.inode);
1219 afs_CFileTruncate(tfile, 0);
1220 afs_CFileClose(tfile);
1221 afs_AdjustSize(tdc, 0);
1222 afs_DCMoveBucket(tdc, 0, 0);
1225 * Free the element we just truncated
1227 ObtainWriteLock(&afs_xdcache, 511);
1228 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1229 afs_FreeDCache(tdc);
1230 tdc->f.states &= ~(DRO|DBackup|DRW);
1231 ReleaseWriteLock(&tdc->lock);
1233 ReleaseWriteLock(&afs_xdcache);
1239 * Free as many entries from the list of discarded cache elements
1240 * as we need to get the free space down below CM_WAITFORDRAINPCT (98%).
1245 afs_MaybeFreeDiscardedDCache(void)
1248 AFS_STATCNT(afs_MaybeFreeDiscardedDCache);
1250 while (afs_blocksDiscarded
1251 && (afs_blocksUsed >
1252 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
1253 int code = afs_FreeDiscardedDCache();
1255 /* Callers depend on us to get the afs_blocksDiscarded count down.
1256 * If we cannot do that, the callers can spin by calling us over
1257 * and over. Panic for now until we can figure out something
1259 osi_Panic("Error freeing discarded dcache");
1266 * Try to free up a certain number of disk slots.
1268 * \param anumber Targeted number of disk slots to free up.
1270 * \note Environment:
1271 * Must be called with afs_xdcache write-locked.
1275 afs_GetDownDSlot(int anumber)
1277 struct afs_q *tq, *nq;
1282 AFS_STATCNT(afs_GetDownDSlot);
1283 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
1284 osi_Panic("diskless getdowndslot");
1286 if (CheckLock(&afs_xdcache) != -1)
1287 osi_Panic("getdowndslot nolock");
1289 /* decrement anumber first for all dudes in free list */
1290 for (tdc = afs_freeDSList; tdc; tdc = (struct dcache *)tdc->lruq.next)
1293 return; /* enough already free */
1295 for (cnt = 0, tq = afs_DLRU.prev; tq != &afs_DLRU && anumber > 0;
1297 tdc = (struct dcache *)tq; /* q is first elt in dcache entry */
1298 nq = QPrev(tq); /* in case we remove it */
1299 if (tdc->refCount == 0) {
1300 if ((ix = tdc->index) == NULLIDX)
1301 osi_Panic("getdowndslot");
1303 /* write-through if modified */
1304 if (tdc->dflags & DFEntryMod) {
1305 #if defined(AFS_SGI_ENV) && defined(AFS_SGI_SHORTSTACK)
1307 * ask proxy to do this for us - we don't have the stack space
1309 while (tdc->dflags & DFEntryMod) {
1312 s = SPLOCK(afs_sgibklock);
1313 if (afs_sgibklist == NULL) {
1314 /* if slot is free, grab it. */
1315 afs_sgibklist = tdc;
1316 SV_SIGNAL(&afs_sgibksync);
1318 /* wait for daemon to (start, then) finish. */
1319 SP_WAIT(afs_sgibklock, s, &afs_sgibkwait, PINOD);
1325 code = afs_WriteDCache(tdc, 1);
1328 * We couldn't flush it at this time; return early because
1329 * if afs_WriteDCache() failed once it is likely to
1330 * continue failing for subsequent dcaches.
1334 tdc->dflags &= ~DFEntryMod;
1338 /* pull the entry out of the lruq and put it on the free list */
1339 QRemove(&tdc->lruq);
1340 afs_indexTable[ix] = NULL;
1341 afs_indexFlags[ix] &= ~IFEverUsed;
1342 tdc->index = NULLIDX;
1343 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
1344 afs_freeDSList = tdc;
1348 } /*afs_GetDownDSlot */
1355 * Increment the reference count on a disk cache entry,
1356 * which already has a non-zero refcount. In order to
1357 * increment the refcount of a zero-reference entry, you
1358 * have to hold afs_xdcache.
1361 * adc : Pointer to the dcache entry to increment.
1364 * Nothing interesting.
1367 afs_RefDCache(struct dcache *adc)
1369 ObtainWriteLock(&adc->tlock, 627);
1370 if (adc->refCount < 0)
1371 osi_Panic("RefDCache: negative refcount");
1373 ReleaseWriteLock(&adc->tlock);
1382 * Decrement the reference count on a disk cache entry.
1385 * ad : Ptr to the dcache entry to decrement.
1388 * Nothing interesting.
1391 afs_PutDCache(struct dcache *adc)
1393 AFS_STATCNT(afs_PutDCache);
1394 ObtainWriteLock(&adc->tlock, 276);
1395 if (adc->refCount <= 0)
1396 osi_Panic("putdcache");
1398 ReleaseWriteLock(&adc->tlock);
1407 * Try to discard all data associated with this file from the
1411 * avc : Pointer to the cache info for the file.
1414 * Both pvnLock and lock are write held.
1417 afs_TryToSmush(struct vcache *avc, afs_ucred_t *acred, int sync)
1422 AFS_STATCNT(afs_TryToSmush);
1423 afs_Trace2(afs_iclSetp, CM_TRACE_TRYTOSMUSH, ICL_TYPE_POINTER, avc,
1424 ICL_TYPE_OFFSET, ICL_HANDLE_OFFSET(avc->f.m.Length));
1425 sync = 1; /* XX Temp testing XX */
1427 #if defined(AFS_SUN5_ENV)
1428 ObtainWriteLock(&avc->vlock, 573);
1429 avc->activeV++; /* block new getpages */
1430 ReleaseWriteLock(&avc->vlock);
1433 /* Flush VM pages */
1434 osi_VM_TryToSmush(avc, acred, sync);
1437 * Get the hash chain containing all dce's for this fid
1439 i = DVHash(&avc->f.fid);
1440 ObtainWriteLock(&afs_xdcache, 277);
1441 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1442 i = afs_dvnextTbl[index]; /* next pointer this hash table */
1443 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1444 int releaseTlock = 1;
1445 tdc = afs_GetValidDSlot(index);
1447 /* afs_TryToSmush is best-effort; we may not actually discard
1448 * everything, so failure to discard dcaches due to an i/o
1452 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1454 if ((afs_indexFlags[index] & IFDataMod) == 0
1455 && tdc->refCount == 1) {
1456 ReleaseReadLock(&tdc->tlock);
1458 afs_FlushDCache(tdc);
1461 afs_indexTable[index] = 0;
1464 ReleaseReadLock(&tdc->tlock);
1468 #if defined(AFS_SUN5_ENV)
1469 ObtainWriteLock(&avc->vlock, 545);
1470 if (--avc->activeV == 0 && (avc->vstates & VRevokeWait)) {
1471 avc->vstates &= ~VRevokeWait;
1472 afs_osi_Wakeup((char *)&avc->vstates);
1474 ReleaseWriteLock(&avc->vlock);
1476 ReleaseWriteLock(&afs_xdcache);
1478 * It's treated like a callback so that when we do lookups we'll
1479 * invalidate the unique bit if any
1480 * trytoSmush occured during the lookup call
1486 * afs_DCacheMissingChunks
1489 * Given the cached info for a file, return the number of chunks that
1490 * are not available from the dcache.
1493 * avc: Pointer to the (held) vcache entry to look in.
1496 * The number of chunks which are not currently cached.
1499 * The vcache entry is held upon entry.
1503 afs_DCacheMissingChunks(struct vcache *avc)
1506 afs_size_t totalLength = 0;
1507 afs_uint32 totalChunks = 0;
1510 totalLength = avc->f.m.Length;
1511 if (avc->f.truncPos < totalLength)
1512 totalLength = avc->f.truncPos;
1514 /* Length is 0, no chunk missing. */
1515 if (totalLength == 0)
1518 /* If totalLength is a multiple of chunksize, the last byte appears
1519 * as being part of the next chunk, which does not exist.
1520 * Decrementing totalLength by one fixes that.
1523 totalChunks = (AFS_CHUNK(totalLength) + 1);
1525 /* If we're a directory, we only ever have one chunk, regardless of
1526 * the size of the dir.
1528 if (avc->f.fid.Fid.Vnode & 1 || vType(avc) == VDIR)
1532 printf("Should have %d chunks for %u bytes\n",
1533 totalChunks, (totalLength + 1));
1535 i = DVHash(&avc->f.fid);
1536 ObtainWriteLock(&afs_xdcache, 1001);
1537 for (index = afs_dvhashTbl[i]; index != NULLIDX; index = i) {
1538 i = afs_dvnextTbl[index];
1539 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1540 tdc = afs_GetValidDSlot(index);
1544 if (!FidCmp(&tdc->f.fid, &avc->f.fid)) {
1547 ReleaseReadLock(&tdc->tlock);
1551 ReleaseWriteLock(&afs_xdcache);
1553 /*printf("Missing %d chunks\n", totalChunks);*/
1555 return (totalChunks);
1562 * Given the cached info for a file and a byte offset into the
1563 * file, make sure the dcache entry for that file and containing
1564 * the given byte is available, returning it to our caller.
1567 * avc : Pointer to the (held) vcache entry to look in.
1568 * abyte : Which byte we want to get to.
1571 * Pointer to the dcache entry covering the file & desired byte,
1572 * or NULL if not found.
1575 * The vcache entry is held upon entry.
1579 afs_FindDCache(struct vcache *avc, afs_size_t abyte)
1583 struct dcache *tdc = NULL;
1585 AFS_STATCNT(afs_FindDCache);
1586 chunk = AFS_CHUNK(abyte);
1589 * Hash on the [fid, chunk] and get the corresponding dcache index
1590 * after write-locking the dcache.
1592 i = DCHash(&avc->f.fid, chunk);
1593 ObtainWriteLock(&afs_xdcache, 278);
1594 for (index = afs_dchashTbl[i]; index != NULLIDX; index = afs_dcnextTbl[index]) {
1595 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
1596 tdc = afs_GetValidDSlot(index);
1598 /* afs_FindDCache is best-effort; we may not find the given
1599 * file/offset, so if we cannot find the given dcache due to
1600 * i/o errors, that is okay. */
1604 ReleaseReadLock(&tdc->tlock);
1605 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
1606 break; /* leaving refCount high for caller */
1611 if (index != NULLIDX) {
1612 hset(afs_indexTimes[tdc->index], afs_indexCounter);
1613 hadd32(afs_indexCounter, 1);
1614 ReleaseWriteLock(&afs_xdcache);
1617 ReleaseWriteLock(&afs_xdcache);
1619 } /*afs_FindDCache */
1621 /* only call these from afs_AllocDCache() */
1623 afs_AllocFreeDSlot(struct dcache **adc)
1628 code = afs_GetDSlotFromList(&tdc, &afs_freeDCList);
1632 afs_indexFlags[tdc->index] &= ~IFFree;
1633 ObtainWriteLock(&tdc->lock, 604);
1640 afs_AllocDiscardDSlot(struct dcache **adc, afs_int32 lock)
1644 afs_uint32 size = 0;
1645 struct osi_file *file;
1647 code = afs_GetDSlotFromList(&tdc, &afs_discardDCList);
1651 afs_indexFlags[tdc->index] &= ~IFDiscarded;
1652 ObtainWriteLock(&tdc->lock, 605);
1653 afs_discardDCCount--;
1654 size = afs_round_to_fsfragsize(tdc->f.chunkBytes);
1655 tdc->f.states &= ~(DRO|DBackup|DRW);
1656 afs_DCMoveBucket(tdc, size, 0);
1657 afs_blocksDiscarded -= size;
1658 afs_stats_cmperf.cacheBlocksDiscarded = afs_blocksDiscarded;
1660 /* Truncate the chunk so zeroes get filled properly */
1661 file = afs_CFileOpen(&tdc->f.inode);
1663 afs_CFileTruncate(file, 0);
1664 afs_CFileClose(file);
1665 afs_AdjustSize(tdc, 0);
1673 * Get a fresh dcache from the free or discarded list.
1675 * \param adc Set to the new dcache on success, and NULL on error.
1676 * \param avc Who's dcache is this going to be?
1677 * \param chunk The position where it will be placed in.
1678 * \param lock How are locks held.
1679 * \param ashFid If this dcache going to be used for a shadow dir,
1682 * \note Required locks:
1684 * - avc (R if (lock & 1) set and W otherwise)
1685 * \note It write locks the new dcache. The caller must unlock it.
1687 * \return If we're out of dslots, ENOSPC. If we encountered disk errors, EIO.
1688 * On success, return 0.
1691 afs_AllocDCache(struct dcache **adc, struct vcache *avc, afs_int32 chunk,
1692 afs_int32 lock, struct VenusFid *ashFid)
1695 struct dcache *tdc = NULL;
1699 /* if (lock & 2), prefer 'free' dcaches; otherwise, prefer 'discard'
1700 * dcaches. In either case, try both if our first choice doesn't work due
1703 code = afs_AllocFreeDSlot(&tdc);
1704 if (code == ENOSPC) {
1705 code = afs_AllocDiscardDSlot(&tdc, lock);
1708 code = afs_AllocDiscardDSlot(&tdc, lock);
1709 if (code == ENOSPC) {
1710 code = afs_AllocFreeDSlot(&tdc);
1719 * avc->lock(R) if setLocks
1720 * avc->lock(W) if !setLocks
1726 * Fill in the newly-allocated dcache record.
1728 afs_indexFlags[tdc->index] &= ~(IFDirtyPages | IFAnyPages);
1730 /* Use shadow fid if provided. */
1731 tdc->f.fid = *ashFid;
1733 /* Use normal vcache's fid otherwise. */
1734 tdc->f.fid = avc->f.fid;
1735 if (avc->f.states & CRO)
1736 tdc->f.states = DRO;
1737 else if (avc->f.states & CBackup)
1738 tdc->f.states = DBackup;
1740 tdc->f.states = DRW;
1741 afs_DCMoveBucket(tdc, 0, afs_DCGetBucket(avc));
1742 afs_indexUnique[tdc->index] = tdc->f.fid.Fid.Unique;
1744 hones(tdc->f.versionNo); /* invalid value */
1745 tdc->f.chunk = chunk;
1746 tdc->validPos = AFS_CHUNKTOBASE(chunk);
1748 if (tdc->lruq.prev == &tdc->lruq)
1749 osi_Panic("lruq 1");
1756 IsDCacheSizeOK(struct dcache *adc, struct vcache *avc, afs_int32 chunk_bytes,
1757 afs_size_t file_length, afs_uint32 versionNo, int from_net)
1759 afs_size_t expected_bytes;
1760 afs_size_t chunk_start = AFS_CHUNKTOBASE(adc->f.chunk);
1762 if (vType(avc) == VDIR) {
1764 * Directory blobs may be constructed locally (see afs_LocalHero), and
1765 * the size of the blob may differ slightly compared to what's on the
1766 * fileserver. So, skip size checks for directories.
1771 if ((avc->f.states & CDirty)) {
1773 * Our vcache may have writes that are local to our cache, but not yet
1774 * written to the fileserver. In such a situation, we may have dcaches
1775 * for that file that are "short". For example:
1777 * Say we have a file that is 0 bytes long. A process opens that file,
1778 * and writes some data to offset 5M (keeping the file open). Another
1779 * process comes along and reads data from offset 1M. We'll try to
1780 * fetch data at offset 1M, and the fileserver will respond with 0
1781 * bytes, since our locally-written data hasn't been written to the
1782 * fileserver yet (on the fileserver, the file is still 0-bytes long).
1783 * So our dcache at offset 1M will have 0 bytes.
1785 * So if CDirty is set, don't do any size/length checks at all, since
1786 * we have no idea if the avc length is valid.
1791 if (!from_net && (adc->f.states & DRW)) {
1793 * The dcache data we're looking at is from our local cache (not from a
1794 * fileserver), and it's for data in an RW volume. For cached RW data,
1795 * there are some edge cases that can cause the below length checks to
1796 * trigger false positives.
1798 * For example: if the local client writes 4 bytes to a new file at
1799 * offset 0, and then 4 bytes at offset 0x400000, the file will be
1800 * 0x400004 bytes long, but the first dcache chunk will only contain 4
1801 * bytes. If such a file is fetched from a fileserver, the first chunk
1802 * will have a full chunk of data (most of it zeroes), but on the
1803 * client that did the write, the sparse data will not appear in the
1806 * Such false positives should only be possible with RW data, since
1807 * non-RW data is never generated locally. So to avoid the false
1808 * positives, assume the dcache length is OK for RW data if the dcache
1809 * came from our local cache (and not directly from a fileserver).
1814 if (file_length < chunk_start) {
1818 expected_bytes = file_length - chunk_start;
1820 if (vType(avc) != VDIR && expected_bytes > AFS_CHUNKTOSIZE(adc->f.chunk)) {
1821 /* A non-dir chunk cannot have more bytes than the chunksize. */
1822 expected_bytes = AFS_CHUNKTOSIZE(adc->f.chunk);
1826 if (chunk_bytes != expected_bytes) {
1827 static const afs_uint32 one_hour = 60 * 60;
1828 static afs_uint32 last_warn;
1829 afs_uint32 now = osi_Time();
1831 if (now < last_warn) {
1832 /* clock went backwards */
1836 if (now - last_warn > one_hour) {
1837 unsigned int mtime = adc->f.modTime;
1843 * The dcache we're looking at didn't come from the cache, but is
1844 * being populated from the net. Don't print out its mtime in that
1845 * case; that would be misleading since that's the mtime from the
1846 * last time this dcache slot was written to.
1851 afs_warn("afs: Detected corrupt dcache for file %d.%u.%u.%u: chunk %d "
1852 "(offset %lu) has %d bytes, but it should have %lu bytes\n",
1854 adc->f.fid.Fid.Volume,
1855 adc->f.fid.Fid.Vnode,
1856 adc->f.fid.Fid.Unique,
1858 (unsigned long)chunk_start,
1860 (unsigned long)expected_bytes);
1861 afs_warn("afs: (dcache %p, file length %lu, DV %u, dcache mtime %u, "
1862 "index %d, dflags 0x%x, mflags 0x%x, states 0x%x, vcache "
1865 (unsigned long)file_length,
1869 (unsigned)adc->dflags,
1870 (unsigned)adc->mflags,
1871 (unsigned)adc->f.states,
1873 afs_warn("afs: Ignoring the dcache for now, but this may indicate "
1874 "corruption in the AFS cache, or a bug.\n");
1882 * Check if a dcache is "fresh". That is, if the dcache's DV matches the DV of
1883 * the vcache for that file, and the dcache looks "sane" (its length makes
1884 * sense, when considering the length of the given avc).
1886 * \param adc The dcache to check
1887 * \param avc The vcache for adc
1889 * \return 1 if the dcache is "fresh". 0 otherwise.
1892 afs_IsDCacheFresh(struct dcache *adc, struct vcache *avc)
1894 if (!hsame(adc->f.versionNo, avc->f.m.DataVersion)) {
1899 * If we've reached here, the DV in adc matches the DV of our avc. Check if
1900 * the number of bytes in adc agrees with the avc file length, as a sanity
1901 * check. If they don't match, we'll pretend the DVs don't match, so the
1902 * bad dcache data will not be used, and we'll probably re-fetch the chunk
1903 * data, replacing the bad chunk.
1906 if (!IsDCacheSizeOK(adc, avc, adc->f.chunkBytes, avc->f.m.Length,
1907 hgetlo(adc->f.versionNo), 0)) {
1918 * This function is called to obtain a reference to data stored in
1919 * the disk cache, locating a chunk of data containing the desired
1920 * byte and returning a reference to the disk cache entry, with its
1921 * reference count incremented.
1925 * avc : Ptr to a vcache entry (unlocked)
1926 * abyte : Byte position in the file desired
1927 * areq : Request structure identifying the requesting user.
1928 * aflags : Settings as follows:
1930 * 2 : Return after creating entry.
1931 * 4 : called from afs_vnop_write.c
1932 * *alen contains length of data to be written.
1934 * aoffset : Set to the offset within the chunk where the resident
1936 * alen : Set to the number of bytes of data after the desired
1937 * byte (including the byte itself) which can be read
1941 * The vcache entry pointed to by avc is unlocked upon entry.
1945 * Update the vnode-to-dcache hint if we can get the vnode lock
1946 * right away. Assumes dcache entry is at least read-locked.
1949 updateV2DC(int lockVc, struct vcache *v, struct dcache *d, int src)
1951 if (!lockVc || 0 == NBObtainWriteLock(&v->lock, src)) {
1952 if (afs_IsDCacheFresh(d, v) && v->callback)
1955 ReleaseWriteLock(&v->lock);
1959 /* avc - Write-locked unless aflags & 1 */
1961 afs_GetDCache(struct vcache *avc, afs_size_t abyte,
1962 struct vrequest *areq, afs_size_t * aoffset,
1963 afs_size_t * alen, int aflags)
1965 afs_int32 i, code, shortcut;
1966 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
1967 afs_int32 adjustsize = 0;
1973 afs_size_t Position = 0;
1974 afs_int32 size, tlen; /* size of segment to transfer */
1975 struct afs_FetchOutput *tsmall = 0;
1977 struct osi_file *file;
1978 struct afs_conn *tc;
1980 struct server *newCallback = NULL;
1981 char setNewCallback;
1982 char setVcacheStatus;
1983 char doVcacheUpdate;
1985 int doAdjustSize = 0;
1986 int doReallyAdjustSize = 0;
1987 int overWriteWholeChunk = 0;
1988 struct rx_connection *rxconn;
1991 struct afs_stats_AccessInfo *accP; /*Ptr to access record in stats */
1992 int fromReplica; /*Are we reading from a replica? */
1993 int numFetchLoops; /*# times around the fetch/analyze loop */
1994 #endif /* AFS_NOSTATS */
1996 AFS_STATCNT(afs_GetDCache);
2000 setLocks = aflags & 1;
2003 * Determine the chunk number and offset within the chunk corresponding
2004 * to the desired byte.
2006 if (avc->f.fid.Fid.Vnode & 1) { /* if (vType(avc) == VDIR) */
2009 chunk = AFS_CHUNK(abyte);
2012 /* come back to here if we waited for the cache to drain. */
2015 setNewCallback = setVcacheStatus = 0;
2019 ObtainWriteLock(&avc->lock, 616);
2021 ObtainReadLock(&avc->lock);
2026 * avc->lock(R) if setLocks && !slowPass
2027 * avc->lock(W) if !setLocks || slowPass
2032 /* check hints first! (might could use bcmp or some such...) */
2033 if ((tdc = avc->dchint)) {
2037 * The locking order between afs_xdcache and dcache lock matters.
2038 * The hint dcache entry could be anywhere, even on the free list.
2039 * Locking afs_xdcache ensures that noone is trying to pull dcache
2040 * entries from the free list, and thereby assuming them to be not
2041 * referenced and not locked.
2043 ObtainReadLock(&afs_xdcache);
2044 dcLocked = (0 == NBObtainSharedLock(&tdc->lock, 601));
2046 if (dcLocked && (tdc->index != NULLIDX)
2047 && !FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk
2048 && !(afs_indexFlags[tdc->index] & (IFFree | IFDiscarded))) {
2049 /* got the right one. It might not be the right version, and it
2050 * might be fetching, but it's the right dcache entry.
2052 /* All this code should be integrated better with what follows:
2053 * I can save a good bit more time under a write lock if I do..
2055 ObtainWriteLock(&tdc->tlock, 603);
2057 ReleaseWriteLock(&tdc->tlock);
2059 ReleaseReadLock(&afs_xdcache);
2062 if (afs_IsDCacheFresh(tdc, avc)
2063 && !(tdc->dflags & DFFetching)) {
2065 afs_stats_cmperf.dcacheHits++;
2066 ObtainWriteLock(&afs_xdcache, 559);
2067 QRemove(&tdc->lruq);
2068 QAdd(&afs_DLRU, &tdc->lruq);
2069 ReleaseWriteLock(&afs_xdcache);
2072 * avc->lock(R) if setLocks && !slowPass
2073 * avc->lock(W) if !setLocks || slowPass
2080 ReleaseSharedLock(&tdc->lock);
2081 ReleaseReadLock(&afs_xdcache);
2089 * avc->lock(R) if setLocks && !slowPass
2090 * avc->lock(W) if !setLocks || slowPass
2091 * tdc->lock(S) if tdc
2094 if (!tdc) { /* If the hint wasn't the right dcache entry */
2095 int dslot_error = 0;
2097 * Hash on the [fid, chunk] and get the corresponding dcache index
2098 * after write-locking the dcache.
2103 * avc->lock(R) if setLocks && !slowPass
2104 * avc->lock(W) if !setLocks || slowPass
2107 i = DCHash(&avc->f.fid, chunk);
2108 /* check to make sure our space is fine */
2109 afs_MaybeWakeupTruncateDaemon();
2111 ObtainWriteLock(&afs_xdcache, 280);
2113 for (index = afs_dchashTbl[i]; index != NULLIDX; us = index, index = afs_dcnextTbl[index]) {
2114 if (afs_indexUnique[index] == avc->f.fid.Fid.Unique) {
2115 tdc = afs_GetValidDSlot(index);
2117 /* we got an i/o error when trying to get the given dslot.
2118 * it's possible the dslot we're looking for is elsewhere,
2119 * but most likely the disk cache is currently unusable, so
2120 * all afs_GetValidDSlot calls will fail, so just bail out. */
2125 ReleaseReadLock(&tdc->tlock);
2128 * avc->lock(R) if setLocks && !slowPass
2129 * avc->lock(W) if !setLocks || slowPass
2132 if (!FidCmp(&tdc->f.fid, &avc->f.fid) && chunk == tdc->f.chunk) {
2133 /* Move it up in the beginning of the list */
2134 if (afs_dchashTbl[i] != index) {
2135 afs_dcnextTbl[us] = afs_dcnextTbl[index];
2136 afs_dcnextTbl[index] = afs_dchashTbl[i];
2137 afs_dchashTbl[i] = index;
2139 ReleaseWriteLock(&afs_xdcache);
2140 ObtainSharedLock(&tdc->lock, 606);
2141 break; /* leaving refCount high for caller */
2149 * If we didn't find the entry, we'll create one.
2151 if (index == NULLIDX) {
2154 * avc->lock(R) if setLocks
2155 * avc->lock(W) if !setLocks
2158 afs_Trace2(afs_iclSetp, CM_TRACE_GETDCACHE1, ICL_TYPE_POINTER,
2159 avc, ICL_TYPE_INT32, chunk);
2162 /* We couldn't find the dcache we want, but we hit some i/o
2163 * errors when trying to find it, so we're not sure if the
2164 * dcache we want is in the cache or not. Error out, so we
2165 * don't try to possibly create 2 separate dcaches for the
2166 * same exact data. */
2167 ReleaseWriteLock(&afs_xdcache);
2171 if (afs_discardDCList == NULLIDX && afs_freeDCList == NULLIDX) {
2173 avc->f.states |= CDCLock;
2174 /* just need slots */
2175 afs_GetDownD(5, (int *)0, afs_DCGetBucket(avc));
2177 avc->f.states &= ~CDCLock;
2179 code = afs_AllocDCache(&tdc, avc, chunk, aflags, NULL);
2181 ReleaseWriteLock(&afs_xdcache);
2182 if (code == ENOSPC) {
2183 /* It looks like afs_AllocDCache failed because we don't
2184 * have any free dslots to use. Maybe if we wait a little
2185 * while, we'll be able to free up some slots, so try for 5
2186 * minutes, then bail out. */
2187 if (++downDCount > 300) {
2188 afs_warn("afs: Unable to get free cache space for file "
2189 "%u:%u.%u.%u for 5 minutes; failing with an i/o error\n",
2191 avc->f.fid.Fid.Volume,
2192 avc->f.fid.Fid.Vnode,
2193 avc->f.fid.Fid.Unique);
2196 afs_osi_Wait(1000, 0, 0);
2200 /* afs_AllocDCache failed, but not because we're out of free
2201 * dslots. Something must be screwy with the cache, so bail out
2202 * immediately without waiting. */
2203 afs_warn("afs: Error while alloc'ing cache slot for file "
2204 "%u:%u.%u.%u; failing with an i/o error\n",
2206 avc->f.fid.Fid.Volume,
2207 avc->f.fid.Fid.Vnode,
2208 avc->f.fid.Fid.Unique);
2214 * avc->lock(R) if setLocks
2215 * avc->lock(W) if !setLocks
2221 * Now add to the two hash chains - note that i is still set
2222 * from the above DCHash call.
2224 afs_dcnextTbl[tdc->index] = afs_dchashTbl[i];
2225 afs_dchashTbl[i] = tdc->index;
2226 i = DVHash(&avc->f.fid);
2227 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[i];
2228 afs_dvhashTbl[i] = tdc->index;
2229 tdc->dflags = DFEntryMod;
2231 afs_MaybeWakeupTruncateDaemon();
2232 ReleaseWriteLock(&afs_xdcache);
2233 ConvertWToSLock(&tdc->lock);
2238 /* vcache->dcache hint failed */
2241 * avc->lock(R) if setLocks && !slowPass
2242 * avc->lock(W) if !setLocks || slowPass
2245 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE2, ICL_TYPE_POINTER, avc,
2246 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2247 hgetlo(tdc->f.versionNo), ICL_TYPE_INT32,
2248 hgetlo(avc->f.m.DataVersion));
2250 * Here we have the entry in tdc, with its refCount incremented.
2251 * Note: we don't use the S-lock on avc; it costs concurrency when
2252 * storing a file back to the server.
2256 * Not a newly created file so we need to check the file's length and
2257 * compare data versions since someone could have changed the data or we're
2258 * reading a file written elsewhere. We only want to bypass doing no-op
2259 * read rpcs on newly created files (dv of 0) since only then we guarantee
2260 * that this chunk's data hasn't been filled by another client.
2262 size = AFS_CHUNKSIZE(abyte);
2263 if (aflags & 4) /* called from write */
2265 else /* called from read */
2266 tlen = tdc->validPos - abyte;
2267 Position = AFS_CHUNKTOBASE(chunk);
2268 afs_Trace4(afs_iclSetp, CM_TRACE_GETDCACHE3, ICL_TYPE_INT32, tlen,
2269 ICL_TYPE_INT32, aflags, ICL_TYPE_OFFSET,
2270 ICL_HANDLE_OFFSET(abyte), ICL_TYPE_OFFSET,
2271 ICL_HANDLE_OFFSET(Position));
2272 if ((aflags & 4) && (hiszero(avc->f.m.DataVersion)))
2274 if ((AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length) ||
2275 ((aflags & 4) && (abyte == Position) && (tlen >= size)))
2276 overWriteWholeChunk = 1;
2277 if (doAdjustSize || overWriteWholeChunk) {
2278 #if defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV)
2282 #else /* AFS_SGI_ENV */
2285 #endif /* AFS_SGI_ENV */
2286 if (AFS_CHUNKTOBASE(chunk) + adjustsize >= avc->f.m.Length &&
2287 #else /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2288 #if defined(AFS_SUN5_ENV)
2289 if ((doAdjustSize || (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length)) &&
2291 if (AFS_CHUNKTOBASE(chunk) >= avc->f.m.Length &&
2293 #endif /* defined(AFS_AIX32_ENV) || defined(AFS_SGI_ENV) */
2294 !afs_IsDCacheFresh(tdc, avc))
2295 doReallyAdjustSize = 1;
2297 if (doReallyAdjustSize || overWriteWholeChunk) {
2298 /* no data in file to read at this position */
2299 UpgradeSToWLock(&tdc->lock, 607);
2300 file = afs_CFileOpen(&tdc->f.inode);
2302 afs_CFileTruncate(file, 0);
2303 afs_CFileClose(file);
2304 afs_AdjustSize(tdc, 0);
2305 hset(tdc->f.versionNo, avc->f.m.DataVersion);
2306 tdc->dflags |= DFEntryMod;
2308 ConvertWToSLock(&tdc->lock);
2313 * We must read in the whole chunk if the version number doesn't
2317 /* don't need data, just a unique dcache entry */
2318 ObtainWriteLock(&afs_xdcache, 608);
2319 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2320 hadd32(afs_indexCounter, 1);
2321 ReleaseWriteLock(&afs_xdcache);
2323 updateV2DC(setLocks, avc, tdc, 553);
2324 if (vType(avc) == VDIR)
2327 *aoffset = AFS_CHUNKOFFSET(abyte);
2328 if (tdc->validPos < abyte)
2329 *alen = (afs_size_t) 0;
2331 *alen = tdc->validPos - abyte;
2332 ReleaseSharedLock(&tdc->lock);
2335 ReleaseWriteLock(&avc->lock);
2337 ReleaseReadLock(&avc->lock);
2339 return tdc; /* check if we're done */
2344 * avc->lock(R) if setLocks && !slowPass
2345 * avc->lock(W) if !setLocks || slowPass
2348 osi_Assert((setLocks && !slowPass) || WriteLocked(&avc->lock));
2350 setNewCallback = setVcacheStatus = 0;
2354 * avc->lock(R) if setLocks && !slowPass
2355 * avc->lock(W) if !setLocks || slowPass
2358 if (!afs_IsDCacheFresh(tdc, avc) && !overWriteWholeChunk) {
2360 * Version number mismatch.
2363 * If we are disconnected, then we can't do much of anything
2364 * because the data doesn't match the file.
2366 if (AFS_IS_DISCONNECTED) {
2367 ReleaseSharedLock(&tdc->lock);
2370 ReleaseWriteLock(&avc->lock);
2372 ReleaseReadLock(&avc->lock);
2374 /* Flush the Dcache */
2379 UpgradeSToWLock(&tdc->lock, 609);
2382 * If data ever existed for this vnode, and this is a text object,
2383 * do some clearing. Now, you'd think you need only do the flush
2384 * when VTEXT is on, but VTEXT is turned off when the text object
2385 * is freed, while pages are left lying around in memory marked
2386 * with this vnode. If we would reactivate (create a new text
2387 * object from) this vnode, we could easily stumble upon some of
2388 * these old pages in pagein. So, we always flush these guys.
2389 * Sun has a wonderful lack of useful invariants in this system.
2391 * avc->flushDV is the data version # of the file at the last text
2392 * flush. Clearly, at least, we don't have to flush the file more
2393 * often than it changes
2395 if (hcmp(avc->flushDV, avc->f.m.DataVersion) < 0) {
2397 * By here, the cache entry is always write-locked. We can
2398 * deadlock if we call osi_Flush with the cache entry locked...
2399 * Unlock the dcache too.
2401 ReleaseWriteLock(&tdc->lock);
2402 if (setLocks && !slowPass)
2403 ReleaseReadLock(&avc->lock);
2405 ReleaseWriteLock(&avc->lock);
2409 * Call osi_FlushPages in open, read/write, and map, since it
2410 * is too hard here to figure out if we should lock the
2413 if (setLocks && !slowPass)
2414 ObtainReadLock(&avc->lock);
2416 ObtainWriteLock(&avc->lock, 66);
2417 ObtainWriteLock(&tdc->lock, 610);
2422 * avc->lock(R) if setLocks && !slowPass
2423 * avc->lock(W) if !setLocks || slowPass
2427 /* Watch for standard race condition around osi_FlushText */
2428 if (afs_IsDCacheFresh(tdc, avc)) {
2429 updateV2DC(setLocks, avc, tdc, 569); /* set hint */
2430 afs_stats_cmperf.dcacheHits++;
2431 ConvertWToSLock(&tdc->lock);
2435 /* Sleep here when cache needs to be drained. */
2436 if (setLocks && !slowPass
2437 && (afs_blocksUsed >
2438 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks))) {
2439 /* Make sure truncate daemon is running */
2440 afs_MaybeWakeupTruncateDaemon();
2441 ObtainWriteLock(&tdc->tlock, 614);
2442 tdc->refCount--; /* we'll re-obtain the dcache when we re-try. */
2443 ReleaseWriteLock(&tdc->tlock);
2444 ReleaseWriteLock(&tdc->lock);
2445 ReleaseReadLock(&avc->lock);
2446 while ((afs_blocksUsed - afs_blocksDiscarded) >
2447 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
2448 afs_MaybeWaitForCacheDrain();
2450 afs_MaybeFreeDiscardedDCache();
2451 /* need to check if someone else got the chunk first. */
2452 goto RetryGetDCache;
2455 Position = AFS_CHUNKBASE(abyte);
2456 if (vType(avc) == VDIR) {
2457 size = avc->f.m.Length;
2458 if (size > tdc->f.chunkBytes) {
2459 /* pre-reserve space for file */
2460 afs_AdjustSize(tdc, size);
2462 size = 999999999; /* max size for transfer */
2464 afs_size_t maxGoodLength;
2466 /* estimate how much data we're expecting back from the server,
2467 * and reserve space in the dcache entry for it */
2469 maxGoodLength = avc->f.m.Length;
2470 if (avc->f.truncPos < maxGoodLength)
2471 maxGoodLength = avc->f.truncPos;
2473 size = AFS_CHUNKSIZE(abyte); /* expected max size */
2474 if (Position > maxGoodLength) { /* If we're beyond EOF */
2476 } else if (Position + size > maxGoodLength) {
2477 size = maxGoodLength - Position;
2479 osi_Assert(size >= 0);
2481 if (size > tdc->f.chunkBytes) {
2482 /* pre-reserve estimated space for file */
2483 afs_AdjustSize(tdc, size); /* changes chunkBytes */
2487 /* For the actual fetch, do not limit the request to the
2488 * length of the file. If this results in a read past EOF on
2489 * the server, the server will just reply with less data than
2490 * requested. If we limit ourselves to only requesting data up
2491 * to the avc file length, we open ourselves up to races if the
2492 * file is extended on the server at about the same time.
2494 * However, we must restrict ourselves to the avc->f.truncPos
2495 * length, since this represents an outstanding local
2496 * truncation of the file that will be committed to the
2497 * fileserver when we actually write the fileserver contents.
2498 * If we do not restrict the fetch length based on
2499 * avc->f.truncPos, a different truncate operation extending
2500 * the file length could cause the old data after
2501 * avc->f.truncPos to reappear, instead of extending the file
2502 * with NUL bytes. */
2503 size = AFS_CHUNKSIZE(abyte);
2504 if (Position > avc->f.truncPos) {
2506 } else if (Position + size > avc->f.truncPos) {
2507 size = avc->f.truncPos - Position;
2509 osi_Assert(size >= 0);
2512 if (afs_mariner && !tdc->f.chunk)
2513 afs_MarinerLog("fetch$Fetching", avc); /* , Position, size, afs_indexCounter ); */
2515 * Right now, we only have one tool, and it's a hammer. So, we
2516 * fetch the whole file.
2518 DZap(tdc); /* pages in cache may be old */
2519 file = afs_CFileOpen(&tdc->f.inode);
2521 /* We can't access the file in the disk cache backing this dcache;
2523 ReleaseWriteLock(&tdc->lock);
2528 afs_RemoveVCB(&avc->f.fid);
2529 tdc->f.states |= DWriting;
2530 tdc->dflags |= DFFetching;
2531 tdc->validPos = Position; /* which is AFS_CHUNKBASE(abyte) */
2532 if (tdc->mflags & DFFetchReq) {
2533 tdc->mflags &= ~DFFetchReq;
2534 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2535 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2536 __FILE__, ICL_TYPE_INT32, __LINE__,
2537 ICL_TYPE_POINTER, tdc, ICL_TYPE_INT32,
2540 tsmall = osi_AllocLargeSpace(sizeof(struct afs_FetchOutput));
2541 setVcacheStatus = 0;
2544 * Remember if we are doing the reading from a replicated volume,
2545 * and how many times we've zipped around the fetch/analyze loop.
2547 fromReplica = (avc->f.states & CRO) ? 1 : 0;
2549 accP = &(afs_stats_cmfullperf.accessinf);
2551 (accP->replicatedRefs)++;
2553 (accP->unreplicatedRefs)++;
2554 #endif /* AFS_NOSTATS */
2555 /* this is a cache miss */
2556 afs_Trace4(afs_iclSetp, CM_TRACE_FETCHPROC, ICL_TYPE_POINTER, avc,
2557 ICL_TYPE_FID, &(avc->f.fid), ICL_TYPE_OFFSET,
2558 ICL_HANDLE_OFFSET(Position), ICL_TYPE_INT32, size);
2561 afs_stats_cmperf.dcacheMisses++;
2564 * Dynamic root support: fetch data from local memory.
2566 if (afs_IsDynroot(avc)) {
2570 afs_GetDynroot(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2572 dynrootDir += Position;
2573 dynrootLen -= Position;
2574 if (size > dynrootLen)
2578 code = afs_CFileWrite(file, 0, dynrootDir, size);
2586 tdc->validPos = Position + size;
2587 afs_CFileTruncate(file, size); /* prune it */
2588 } else if (afs_IsDynrootMount(avc)) {
2592 afs_GetDynrootMount(&dynrootDir, &dynrootLen, &tsmall->OutStatus);
2594 dynrootDir += Position;
2595 dynrootLen -= Position;
2596 if (size > dynrootLen)
2600 code = afs_CFileWrite(file, 0, dynrootDir, size);
2608 tdc->validPos = Position + size;
2609 afs_CFileTruncate(file, size); /* prune it */
2612 * Not a dynamic vnode: do the real fetch.
2617 * avc->lock(R) if setLocks && !slowPass
2618 * avc->lock(W) if !setLocks || slowPass
2622 tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
2627 (accP->numReplicasAccessed)++;
2629 #endif /* AFS_NOSTATS */
2630 if (!setLocks || slowPass) {
2631 avc->callback = tc->parent->srvr->server;
2633 newCallback = tc->parent->srvr->server;
2637 code = afs_CacheFetchProc(tc, rxconn, file, Position, tdc,
2643 /* callback could have been broken (or expired) in a race here,
2644 * but we return the data anyway. It's as good as we knew about
2645 * when we started. */
2647 * validPos is updated by CacheFetchProc, and can only be
2648 * modifed under a dcache write lock, which we've blocked out
2652 size = tdc->validPos - Position; /* actual segment size */
2655 afs_CFileTruncate(file, size); /* prune it */
2657 /* Check that the amount of data that we fetched for the
2658 * dcache makes sense. */
2659 FillInt64(length, tsmall->OutStatus.Length_hi, tsmall->OutStatus.Length);
2660 if (!IsDCacheSizeOK(tdc, avc, size,
2662 tsmall->OutStatus.DataVersion, 1)) {
2667 if (!setLocks || slowPass) {
2668 afs_StaleVCacheFlags(avc, AFS_STALEVC_CLEARCB, CUnique);
2670 /* Something lost. Forget about performance, and go
2671 * back with a vcache write lock.
2673 afs_CFileTruncate(file, 0);
2674 afs_AdjustSize(tdc, 0);
2675 afs_CFileClose(file);
2676 osi_FreeLargeSpace(tsmall);
2678 ReleaseWriteLock(&tdc->lock);
2683 * Call afs_Analyze to manage the connection references
2684 * and handle the error code (possibly mark servers
2685 * down, etc). We are going to retry getting the
2686 * dcache regardless, so we just ignore the retry hint
2687 * returned by afs_Analyze on this call.
2689 (void)afs_Analyze(tc, rxconn, code, &avc->f.fid, areq,
2690 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL);
2692 ReleaseReadLock(&avc->lock);
2695 goto RetryGetDCache;
2699 } while (afs_Analyze
2700 (tc, rxconn, code, &avc->f.fid, areq,
2701 AFS_STATS_FS_RPCIDX_FETCHDATA, SHARED_LOCK, NULL));
2705 * avc->lock(R) if setLocks && !slowPass
2706 * avc->lock(W) if !setLocks || slowPass
2712 * In the case of replicated access, jot down info on the number of
2713 * attempts it took before we got through or gave up.
2716 if (numFetchLoops <= 1)
2717 (accP->refFirstReplicaOK)++;
2718 if (numFetchLoops > accP->maxReplicasPerRef)
2719 accP->maxReplicasPerRef = numFetchLoops;
2721 #endif /* AFS_NOSTATS */
2723 tdc->dflags &= ~DFFetching;
2724 if (afs_osi_Wakeup(&tdc->validPos) == 0)
2725 afs_Trace4(afs_iclSetp, CM_TRACE_DCACHEWAKE, ICL_TYPE_STRING,
2726 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2727 tdc, ICL_TYPE_INT32, tdc->dflags);
2728 if (avc->execsOrWriters == 0)
2729 tdc->f.states &= ~DWriting;
2731 /* now, if code != 0, we have an error and should punt.
2732 * note that we have the vcache write lock, either because
2733 * !setLocks or slowPass.
2736 afs_CFileTruncate(file, 0);
2737 afs_AdjustSize(tdc, 0);
2738 afs_CFileClose(file);
2739 ZapDCE(tdc); /* sets DFEntryMod */
2740 if (vType(avc) == VDIR) {
2743 tdc->f.states &= ~(DRO|DBackup|DRW);
2744 afs_DCMoveBucket(tdc, 0, 0);
2745 ReleaseWriteLock(&tdc->lock);
2747 if (!afs_IsDynroot(avc)) {
2748 afs_StaleVCacheFlags(avc, 0, CUnique);
2751 * avc->lock(W); assert(!setLocks || slowPass)
2753 osi_Assert(!setLocks || slowPass);
2759 /* otherwise we copy in the just-fetched info */
2760 afs_CFileClose(file);
2761 afs_AdjustSize(tdc, size); /* new size */
2763 * Copy appropriate fields into vcache. Status is
2764 * copied later where we selectively acquire the
2765 * vcache write lock.
2768 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2770 setVcacheStatus = 1;
2771 hset64(tdc->f.versionNo, tsmall->OutStatus.dataVersionHigh,
2772 tsmall->OutStatus.DataVersion);
2773 tdc->dflags |= DFEntryMod;
2774 afs_indexFlags[tdc->index] |= IFEverUsed;
2775 ConvertWToSLock(&tdc->lock);
2776 } /*Data version numbers don't match */
2779 * Data version numbers match.
2781 afs_stats_cmperf.dcacheHits++;
2782 } /*Data version numbers match */
2784 updateV2DC(setLocks, avc, tdc, 335); /* set hint */
2788 * avc->lock(R) if setLocks && !slowPass
2789 * avc->lock(W) if !setLocks || slowPass
2790 * tdc->lock(S) if tdc
2794 * See if this was a reference to a file in the local cell.
2796 if (afs_IsPrimaryCellNum(avc->f.fid.Cell))
2797 afs_stats_cmperf.dlocalAccesses++;
2799 afs_stats_cmperf.dremoteAccesses++;
2801 /* Fix up LRU info */
2804 ObtainWriteLock(&afs_xdcache, 602);
2805 hset(afs_indexTimes[tdc->index], afs_indexCounter);
2806 hadd32(afs_indexCounter, 1);
2807 ReleaseWriteLock(&afs_xdcache);
2809 /* return the data */
2810 if (vType(avc) == VDIR)
2813 *aoffset = AFS_CHUNKOFFSET(abyte);
2814 *alen = (tdc->f.chunkBytes - *aoffset);
2815 ReleaseSharedLock(&tdc->lock);
2820 * avc->lock(R) if setLocks && !slowPass
2821 * avc->lock(W) if !setLocks || slowPass
2824 /* Fix up the callback and status values in the vcache */
2826 if (setLocks && !slowPass) {
2829 * This is our dirty little secret to parallel fetches.
2830 * We don't write-lock the vcache while doing the fetch,
2831 * but potentially we'll need to update the vcache after
2832 * the fetch is done.
2834 * Drop the read lock and try to re-obtain the write
2835 * lock. If the vcache still has the same DV, it's
2836 * ok to go ahead and install the new data.
2838 afs_hyper_t currentDV, statusDV;
2840 hset(currentDV, avc->f.m.DataVersion);
2842 if (setNewCallback && avc->callback != newCallback)
2846 hset64(statusDV, tsmall->OutStatus.dataVersionHigh,
2847 tsmall->OutStatus.DataVersion);
2849 if (setVcacheStatus && avc->f.m.Length != tsmall->OutStatus.Length)
2851 if (setVcacheStatus && !hsame(currentDV, statusDV))
2855 ReleaseReadLock(&avc->lock);
2857 if (doVcacheUpdate) {
2858 ObtainWriteLock(&avc->lock, 615);
2859 if (!hsame(avc->f.m.DataVersion, currentDV)) {
2860 /* We lose. Someone will beat us to it. */
2862 ReleaseWriteLock(&avc->lock);
2867 /* With slow pass, we've already done all the updates */
2869 ReleaseWriteLock(&avc->lock);
2872 /* Check if we need to perform any last-minute fixes with a write-lock */
2873 if (!setLocks || doVcacheUpdate) {
2875 avc->callback = newCallback;
2876 if (tsmall && setVcacheStatus)
2877 afs_ProcessFS(avc, &tsmall->OutStatus, areq);
2879 ReleaseWriteLock(&avc->lock);
2883 osi_FreeLargeSpace(tsmall);
2886 } /*afs_GetDCache */
2890 * afs_WriteThroughDSlots
2893 * Sweep through the dcache slots and write out any modified
2894 * in-memory data back on to our caching store.
2900 * The afs_xdcache is write-locked through this whole affair.
2903 afs_WriteThroughDSlots(void)
2906 afs_int32 i, touchedit = 0;
2909 struct afs_q DirtyQ, *tq;
2911 AFS_STATCNT(afs_WriteThroughDSlots);
2914 * Because of lock ordering, we can't grab dcache locks while
2915 * holding afs_xdcache. So we enter xdcache, get a reference
2916 * for every dcache entry, and exit xdcache.
2918 ObtainWriteLock(&afs_xdcache, 283);
2920 for (i = 0; i < afs_cacheFiles; i++) {
2921 tdc = afs_indexTable[i];
2923 /* Grab tlock in case the existing refcount isn't zero */
2924 if (tdc && !(afs_indexFlags[i] & (IFFree | IFDiscarded))) {
2925 ObtainWriteLock(&tdc->tlock, 623);
2927 ReleaseWriteLock(&tdc->tlock);
2929 QAdd(&DirtyQ, &tdc->dirty);
2932 ReleaseWriteLock(&afs_xdcache);
2935 * Now, for each dcache entry we found, check if it's dirty.
2936 * If so, get write-lock, get afs_xdcache, which protects
2937 * afs_cacheInodep, and flush it. Don't forget to put back
2941 #define DQTODC(q) ((struct dcache *)(((char *) (q)) - sizeof(struct afs_q)))
2943 for (tq = DirtyQ.prev; tq != &DirtyQ && code == 0; tq = QPrev(tq)) {
2945 if (tdc->dflags & DFEntryMod) {
2948 wrLock = (0 == NBObtainWriteLock(&tdc->lock, 619));
2950 /* Now that we have the write lock, double-check */
2951 if (wrLock && (tdc->dflags & DFEntryMod)) {
2952 tdc->dflags &= ~DFEntryMod;
2953 ObtainWriteLock(&afs_xdcache, 620);
2954 code = afs_WriteDCache(tdc, 1);
2955 ReleaseWriteLock(&afs_xdcache);
2957 /* We didn't successfully write out the dslot; make sure we
2958 * try again later */
2959 tdc->dflags |= DFEntryMod;
2965 ReleaseWriteLock(&tdc->lock);
2975 ObtainWriteLock(&afs_xdcache, 617);
2976 if (!touchedit && (cacheDiskType != AFS_FCACHE_TYPE_MEM)) {
2977 /* Touch the file to make sure that the mtime on the file is kept
2978 * up-to-date to avoid losing cached files on cold starts because
2979 * their mtime seems old...
2981 struct afs_fheader theader;
2983 afs_InitFHeader(&theader);
2984 afs_osi_Write(afs_cacheInodep, 0, &theader, sizeof(theader));
2986 ReleaseWriteLock(&afs_xdcache);
2994 * Return a pointer to an freshly initialized dcache entry using
2995 * a memory-based cache. The tlock will be read-locked.
2998 * aslot : Dcache slot to look at.
2999 * type : What 'type' of dslot to get; see the dslot_state enum
3002 * Must be called with afs_xdcache write-locked.
3006 afs_MemGetDSlot(afs_int32 aslot, dslot_state type)
3011 AFS_STATCNT(afs_MemGetDSlot);
3012 if (CheckLock(&afs_xdcache) != -1)
3013 osi_Panic("getdslot nolock");
3014 if (aslot < 0 || aslot >= afs_cacheFiles)
3015 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3016 tdc = afs_indexTable[aslot];
3018 QRemove(&tdc->lruq); /* move to queue head */
3019 QAdd(&afs_DLRU, &tdc->lruq);
3020 /* We're holding afs_xdcache, but get tlock in case refCount != 0 */
3021 ObtainWriteLock(&tdc->tlock, 624);
3023 ConvertWToRLock(&tdc->tlock);
3027 /* if we got here, the given slot is not in memory in our list of known
3028 * slots. for memcache, the only place a dslot can exist is in memory, so
3029 * if the caller is expecting to get back a known dslot, and we've reached
3030 * here, something is very wrong. DSLOT_NEW is the only type of dslot that
3031 * may not exist; for all others, the caller assumes the given dslot
3032 * already exists. so, 'type' had better be DSLOT_NEW here, or something is
3034 osi_Assert(type == DSLOT_NEW);
3036 if (!afs_freeDSList)
3037 afs_GetDownDSlot(4);
3038 if (!afs_freeDSList) {
3039 /* none free, making one is better than a panic */
3040 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
3041 tdc = afs_osi_Alloc(sizeof(struct dcache));
3042 osi_Assert(tdc != NULL);
3043 #ifdef KERNEL_HAVE_PIN
3044 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
3047 tdc = afs_freeDSList;
3048 afs_freeDSList = (struct dcache *)tdc->lruq.next;
3051 tdc->dflags = 0; /* up-to-date, not in free q */
3053 QAdd(&afs_DLRU, &tdc->lruq);
3054 if (tdc->lruq.prev == &tdc->lruq)
3055 osi_Panic("lruq 3");
3057 /* initialize entry */
3058 tdc->f.fid.Cell = 0;
3059 tdc->f.fid.Fid.Volume = 0;
3061 hones(tdc->f.versionNo);
3062 tdc->f.inode.mem = aslot;
3063 tdc->dflags |= DFEntryMod;
3066 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3069 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3070 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3071 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3074 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
3075 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3076 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
3077 ObtainReadLock(&tdc->tlock);
3079 afs_indexTable[aslot] = tdc;
3082 } /*afs_MemGetDSlot */
3085 LogCacheError(int aslot, int off, int code, int target_size)
3087 struct osi_stat tstat;
3090 if (afs_osi_Stat(afs_cacheInodep, &tstat)) {
3094 procname = osi_AllocSmallSpace(AFS_SMALLOCSIZ);
3095 if (procname != NULL) {
3096 osi_procname(procname, AFS_SMALLOCSIZ);
3097 procname[AFS_SMALLOCSIZ-1] = '\0';
3100 afs_warn("afs: disk cache read error in CacheItems slot %d "
3101 "off %d/%d code %d/%d pid %d (%s)\n",
3102 aslot, off, (int)tstat.size, code, target_size,
3103 (int)MyPidxx2Pid(MyPidxx),
3104 procname ? procname : "");
3106 if (procname != NULL) {
3107 osi_FreeSmallSpace(procname);
3112 unsigned int last_error = 0, lasterrtime = 0;
3118 * Return a pointer to an freshly initialized dcache entry using
3119 * a UFS-based disk cache. The dcache tlock will be read-locked.
3122 * aslot : Dcache slot to look at.
3123 * type : What 'type' of dslot to get; see the dslot_state enum
3126 * afs_xdcache lock write-locked.
3129 afs_UFSGetDSlot(afs_int32 aslot, dslot_state type)
3137 AFS_STATCNT(afs_UFSGetDSlot);
3138 if (CheckLock(&afs_xdcache) != -1)
3139 osi_Panic("getdslot nolock");
3140 if (aslot < 0 || aslot >= afs_cacheFiles)
3141 osi_Panic("getdslot slot %d (of %d)", aslot, afs_cacheFiles);
3142 tdc = afs_indexTable[aslot];
3144 QRemove(&tdc->lruq); /* move to queue head */
3145 QAdd(&afs_DLRU, &tdc->lruq);
3146 /* Grab tlock in case refCount != 0 */
3147 ObtainWriteLock(&tdc->tlock, 625);
3149 ConvertWToRLock(&tdc->tlock);
3153 /* otherwise we should read it in from the cache file */
3154 if (!afs_freeDSList)
3155 afs_GetDownDSlot(4);
3156 if (!afs_freeDSList) {
3157 /* none free, making one is better than a panic */
3158 afs_stats_cmperf.dcacheXAllocs++; /* count in case we have a leak */
3159 tdc = afs_osi_Alloc(sizeof(struct dcache));
3160 osi_Assert(tdc != NULL);
3161 #ifdef KERNEL_HAVE_PIN
3162 pin((char *)tdc, sizeof(struct dcache)); /* XXX */
3165 tdc = afs_freeDSList;
3166 afs_freeDSList = (struct dcache *)tdc->lruq.next;
3169 tdc->dflags = 0; /* up-to-date, not in free q */
3171 QAdd(&afs_DLRU, &tdc->lruq);
3172 if (tdc->lruq.prev == &tdc->lruq)
3173 osi_Panic("lruq 3");
3176 * Seek to the aslot'th entry and read it in.
3178 off = sizeof(struct fcache)*aslot + sizeof(struct afs_fheader);
3180 afs_osi_Read(afs_cacheInodep,
3181 off, (char *)(&tdc->f),
3182 sizeof(struct fcache));
3184 if (code != sizeof(struct fcache)) {
3186 #if defined(KERNEL_HAVE_UERROR)
3187 last_error = getuerror();
3191 lasterrtime = osi_Time();
3192 if (type != DSLOT_NEW) {
3193 /* If we are requesting a non-DSLOT_NEW slot, this is an error.
3194 * non-DSLOT_NEW slots are supposed to already exist, so if we
3195 * failed to read in the slot, something is wrong. */
3196 LogCacheError(aslot, off, code, sizeof(struct fcache));
3198 /* put tdc back on the free dslot list */
3199 QRemove(&tdc->lruq);
3200 tdc->index = NULLIDX;
3201 tdc->lruq.next = (struct afs_q *)afs_freeDSList;
3202 afs_freeDSList = tdc;
3206 if (!afs_CellNumValid(tdc->f.fid.Cell)) {
3208 if (type == DSLOT_VALID) {
3209 osi_Panic("afs: needed valid dcache but index %d off %d has "
3210 "invalid cell num %d\n",
3211 (int)aslot, off, (int)tdc->f.fid.Cell);
3215 if (type == DSLOT_VALID && tdc->f.fid.Fid.Volume == 0) {
3216 osi_Panic("afs: invalid zero-volume dcache entry at slot %d off %d",
3220 if (type == DSLOT_UNUSED) {
3221 /* the requested dslot is known to exist, but contain invalid data
3222 * (this happens when we're using a dslot from the free or discard
3223 * list). be sure not to re-use the data in it, so force invalidation.
3229 tdc->f.fid.Cell = 0;
3230 tdc->f.fid.Fid.Volume = 0;
3232 hones(tdc->f.versionNo);
3233 tdc->dflags |= DFEntryMod;
3234 afs_indexUnique[aslot] = tdc->f.fid.Fid.Unique;
3235 tdc->f.states &= ~(DRO|DBackup|DRW);
3236 afs_DCMoveBucket(tdc, 0, 0);
3238 if (tdc->f.states & DRO) {
3239 afs_DCMoveBucket(tdc, 0, 2);
3240 } else if (tdc->f.states & DBackup) {
3241 afs_DCMoveBucket(tdc, 0, 1);
3243 afs_DCMoveBucket(tdc, 0, 1);
3248 if (tdc->f.chunk >= 0)
3249 tdc->validPos = AFS_CHUNKTOBASE(tdc->f.chunk) + tdc->f.chunkBytes;
3254 osi_Assert(0 == NBObtainWriteLock(&tdc->lock, 674));
3255 osi_Assert(0 == NBObtainWriteLock(&tdc->mflock, 675));
3256 osi_Assert(0 == NBObtainWriteLock(&tdc->tlock, 676));
3259 AFS_RWLOCK_INIT(&tdc->lock, "dcache lock");
3260 AFS_RWLOCK_INIT(&tdc->tlock, "dcache tlock");
3261 AFS_RWLOCK_INIT(&tdc->mflock, "dcache flock");
3262 ObtainReadLock(&tdc->tlock);
3265 * If we didn't read into a temporary dcache region, update the
3266 * slot pointer table.
3268 afs_indexTable[aslot] = tdc;
3271 } /*afs_UFSGetDSlot */
3276 * Write a particular dcache entry back to its home in the
3279 * \param adc Pointer to the dcache entry to write.
3280 * \param atime If true, set the modtime on the file to the current time.
3282 * \note Environment:
3283 * Must be called with the afs_xdcache lock at least read-locked,
3284 * and dcache entry at least read-locked.
3285 * The reference count is not changed.
3289 afs_WriteDCache(struct dcache *adc, int atime)
3293 if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
3295 AFS_STATCNT(afs_WriteDCache);
3296 osi_Assert(WriteLocked(&afs_xdcache));
3298 adc->f.modTime = osi_Time();
3300 if ((afs_indexFlags[adc->index] & (IFFree | IFDiscarded)) == 0 &&
3301 adc->f.fid.Fid.Volume == 0) {
3302 /* If a dcache slot is not on the free or discard list, it must be
3303 * in the hash table. Thus, the volume must be non-zero, since that
3304 * is how we determine whether or not to unhash the entry when kicking
3305 * it out of the cache. Do this check now, since otherwise this can
3306 * cause hash table corruption and a panic later on after we read the
3308 osi_Panic("afs_WriteDCache zero volume index %d flags 0x%x\n",
3309 adc->index, (unsigned)afs_indexFlags[adc->index]);
3313 * Seek to the right dcache slot and write the in-memory image out to disk.
3315 afs_cellname_write();
3317 afs_osi_Write(afs_cacheInodep,
3318 sizeof(struct fcache) * adc->index +
3319 sizeof(struct afs_fheader), (char *)(&adc->f),
3320 sizeof(struct fcache));
3321 if (code != sizeof(struct fcache)) {
3322 afs_warn("afs: failed to write to CacheItems off %ld code %d/%d\n",
3323 (long)(sizeof(struct fcache) * adc->index + sizeof(struct afs_fheader)),
3324 (int)code, (int)sizeof(struct fcache));
3333 * Wake up users of a particular file waiting for stores to take
3336 * \param avc Ptr to related vcache entry.
3338 * \note Environment:
3339 * Nothing interesting.
3342 afs_wakeup(struct vcache *avc)
3345 struct brequest *tb;
3347 AFS_STATCNT(afs_wakeup);
3348 for (i = 0; i < NBRS; i++, tb++) {
3349 /* if request is valid and for this file, we've found it */
3350 if (tb->refCount > 0 && avc == tb->vc) {
3353 * If CSafeStore is on, then we don't awaken the guy
3354 * waiting for the store until the whole store has finished.
3355 * Otherwise, we do it now. Note that if CSafeStore is on,
3356 * the BStore routine actually wakes up the user, instead
3358 * I think this is redundant now because this sort of thing
3359 * is already being handled by the higher-level code.
3361 if ((avc->f.states & CSafeStore) == 0) {
3362 tb->code_raw = tb->code_checkcode = 0;
3363 tb->flags |= BUVALID;
3364 if (tb->flags & BUWAIT) {
3365 tb->flags &= ~BUWAIT;
3376 * Given a file name and inode, set up that file to be an
3377 * active member in the AFS cache. This also involves checking
3378 * the usability of its data.
3380 * \param afile Name of the cache file to initialize.
3381 * \param ainode Inode of the file.
3383 * \note Environment:
3384 * This function is called only during initialization.
3387 afs_InitCacheFile(char *afile, ino_t ainode)
3392 struct osi_file *tfile;
3393 struct osi_stat tstat;
3396 AFS_STATCNT(afs_InitCacheFile);
3397 index = afs_stats_cmperf.cacheNumEntries;
3398 if (index >= afs_cacheFiles)
3401 ObtainWriteLock(&afs_xdcache, 282);
3402 tdc = afs_GetNewDSlot(index);
3403 ReleaseReadLock(&tdc->tlock);
3404 ReleaseWriteLock(&afs_xdcache);
3406 ObtainWriteLock(&tdc->lock, 621);
3407 ObtainWriteLock(&afs_xdcache, 622);
3408 if (!afile && !ainode) {
3413 code = afs_LookupInodeByPath(afile, &tdc->f.inode.ufs, NULL);
3415 ReleaseWriteLock(&afs_xdcache);
3416 ReleaseWriteLock(&tdc->lock);
3421 /* Add any other 'complex' inode types here ... */
3422 #if !defined(AFS_LINUX_ENV) && !defined(AFS_CACHE_VNODE_PATH)
3423 tdc->f.inode.ufs = ainode;
3425 osi_Panic("Can't init cache with inode numbers when complex inodes are "
3430 if ((tdc->f.states & DWriting) || tdc->f.fid.Fid.Volume == 0)
3432 tfile = osi_UFSOpen(&tdc->f.inode);
3434 ReleaseWriteLock(&afs_xdcache);
3435 ReleaseWriteLock(&tdc->lock);
3440 code = afs_osi_Stat(tfile, &tstat);
3442 osi_Panic("initcachefile stat");
3445 * If file size doesn't match the cache info file, it's probably bad.
3447 if (tdc->f.chunkBytes != tstat.size)
3450 * If file changed within T (120?) seconds of cache info file, it's
3451 * probably bad. In addition, if slot changed within last T seconds,
3452 * the cache info file may be incorrectly identified, and so slot
3455 if (cacheInfoModTime < tstat.mtime + 120)
3457 if (cacheInfoModTime < tdc->f.modTime + 120)
3459 /* In case write through is behind, make sure cache items entry is
3460 * at least as new as the chunk.
3462 if (tdc->f.modTime < tstat.mtime)
3465 tdc->f.chunkBytes = 0;
3468 tdc->f.fid.Fid.Volume = 0; /* not in the hash table */
3469 if (tfile && tstat.size != 0)
3470 osi_UFSTruncate(tfile, 0);
3471 tdc->f.states &= ~(DRO|DBackup|DRW);
3472 afs_DCMoveBucket(tdc, 0, 0);
3473 /* put entry in free cache slot list */
3474 afs_dvnextTbl[tdc->index] = afs_freeDCList;
3475 afs_freeDCList = index;
3477 afs_indexFlags[index] |= IFFree;
3478 afs_indexUnique[index] = 0;
3481 * We must put this entry in the appropriate hash tables.
3482 * Note that i is still set from the above DCHash call
3484 code = DCHash(&tdc->f.fid, tdc->f.chunk);
3485 afs_dcnextTbl[tdc->index] = afs_dchashTbl[code];
3486 afs_dchashTbl[code] = tdc->index;
3487 code = DVHash(&tdc->f.fid);
3488 afs_dvnextTbl[tdc->index] = afs_dvhashTbl[code];
3489 afs_dvhashTbl[code] = tdc->index;
3490 afs_AdjustSize(tdc, tstat.size); /* adjust to new size */
3492 /* has nontrivial amt of data */
3493 afs_indexFlags[index] |= IFEverUsed;
3494 afs_stats_cmperf.cacheFilesReused++;
3496 * Initialize index times to file's mod times; init indexCounter
3499 hset32(afs_indexTimes[index], tstat.atime);
3500 if (hgetlo(afs_indexCounter) < tstat.atime) {
3501 hset32(afs_indexCounter, tstat.atime);
3503 afs_indexUnique[index] = tdc->f.fid.Fid.Unique;
3504 } /*File is not bad */
3507 osi_UFSClose(tfile);
3508 tdc->f.states &= ~DWriting;
3509 tdc->dflags &= ~DFEntryMod;
3510 /* don't set f.modTime; we're just cleaning up */
3511 osi_Assert(afs_WriteDCache(tdc, 0) == 0);
3512 ReleaseWriteLock(&afs_xdcache);
3513 ReleaseWriteLock(&tdc->lock);
3515 afs_stats_cmperf.cacheNumEntries++;
3520 /*Max # of struct dcache's resident at any time*/
3522 * If 'dchint' is enabled then in-memory dcache min is increased because of
3528 * Initialize dcache related variables.
3538 afs_dcacheInit(int afiles, int ablocks, int aDentries, int achunk, int aflags)
3545 afs_freeDCList = NULLIDX;
3546 afs_discardDCList = NULLIDX;
3547 afs_freeDCCount = 0;
3548 afs_freeDSList = NULL;
3549 hzero(afs_indexCounter);
3551 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3557 if (achunk < 0 || achunk > 30)
3558 achunk = 13; /* Use default */
3559 AFS_SETCHUNKSIZE(achunk);
3565 /* afs_dhashsize defaults to 1024 */
3566 if (aDentries > 512)
3567 afs_dhashsize = 2048;
3568 /* Try to keep the average chain length around two unless the table
3569 * would be ridiculously big. */
3570 if (aDentries > 4096) {
3571 afs_dhashbits = opr_fls(aDentries) - 3;
3572 /* Cap the hash tables to 32k entries. */
3573 if (afs_dhashbits > 15)
3575 afs_dhashsize = opr_jhash_size(afs_dhashbits);
3577 /* initialize hash tables */
3578 afs_dvhashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3579 osi_Assert(afs_dvhashTbl != NULL);
3580 afs_dchashTbl = afs_osi_Alloc(afs_dhashsize * sizeof(afs_int32));
3581 osi_Assert(afs_dchashTbl != NULL);
3582 for (i = 0; i < afs_dhashsize; i++) {
3583 afs_dvhashTbl[i] = NULLIDX;
3584 afs_dchashTbl[i] = NULLIDX;
3586 afs_dvnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3587 osi_Assert(afs_dvnextTbl != NULL);
3588 afs_dcnextTbl = afs_osi_Alloc(afiles * sizeof(afs_int32));
3589 osi_Assert(afs_dcnextTbl != NULL);
3590 for (i = 0; i < afiles; i++) {
3591 afs_dvnextTbl[i] = NULLIDX;
3592 afs_dcnextTbl[i] = NULLIDX;
3595 /* Allocate and zero the pointer array to the dcache entries */
3596 afs_indexTable = afs_osi_Alloc(sizeof(struct dcache *) * afiles);
3597 osi_Assert(afs_indexTable != NULL);
3598 memset(afs_indexTable, 0, sizeof(struct dcache *) * afiles);
3599 afs_indexTimes = afs_osi_Alloc(afiles * sizeof(afs_hyper_t));
3600 osi_Assert(afs_indexTimes != NULL);
3601 memset(afs_indexTimes, 0, afiles * sizeof(afs_hyper_t));
3602 afs_indexUnique = afs_osi_Alloc(afiles * sizeof(afs_uint32));
3603 osi_Assert(afs_indexUnique != NULL);
3604 memset(afs_indexUnique, 0, afiles * sizeof(afs_uint32));
3605 afs_indexFlags = afs_osi_Alloc(afiles * sizeof(u_char));
3606 osi_Assert(afs_indexFlags != NULL);
3607 memset(afs_indexFlags, 0, afiles * sizeof(char));
3609 /* Allocate and thread the struct dcache entries themselves */
3610 tdp = afs_Initial_freeDSList =
3611 afs_osi_Alloc(aDentries * sizeof(struct dcache));
3612 osi_Assert(tdp != NULL);
3613 memset(tdp, 0, aDentries * sizeof(struct dcache));
3614 #ifdef KERNEL_HAVE_PIN
3615 pin((char *)afs_indexTable, sizeof(struct dcache *) * afiles); /* XXX */
3616 pin((char *)afs_indexTimes, sizeof(afs_hyper_t) * afiles); /* XXX */
3617 pin((char *)afs_indexFlags, sizeof(char) * afiles); /* XXX */
3618 pin((char *)afs_indexUnique, sizeof(afs_int32) * afiles); /* XXX */
3619 pin((char *)tdp, aDentries * sizeof(struct dcache)); /* XXX */
3620 pin((char *)afs_dvhashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3621 pin((char *)afs_dchashTbl, sizeof(afs_int32) * afs_dhashsize); /* XXX */
3622 pin((char *)afs_dcnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3623 pin((char *)afs_dvnextTbl, sizeof(afs_int32) * afiles); /* XXX */
3626 afs_freeDSList = &tdp[0];
3627 for (i = 0; i < aDentries - 1; i++) {
3628 tdp[i].lruq.next = (struct afs_q *)(&tdp[i + 1]);
3629 AFS_RWLOCK_INIT(&tdp[i].lock, "dcache lock");
3630 AFS_RWLOCK_INIT(&tdp[i].tlock, "dcache tlock");
3631 AFS_RWLOCK_INIT(&tdp[i].mflock, "dcache flock");
3633 tdp[aDentries - 1].lruq.next = (struct afs_q *)0;
3634 AFS_RWLOCK_INIT(&tdp[aDentries - 1].lock, "dcache lock");
3635 AFS_RWLOCK_INIT(&tdp[aDentries - 1].tlock, "dcache tlock");
3636 AFS_RWLOCK_INIT(&tdp[aDentries - 1].mflock, "dcache flock");
3638 afs_stats_cmperf.cacheBlocksOrig = afs_stats_cmperf.cacheBlocksTotal =
3639 afs_cacheBlocks = ablocks;
3640 afs_ComputeCacheParms(); /* compute parms based on cache size */
3642 afs_dcentries = aDentries;
3644 afs_stats_cmperf.cacheBucket0_Discarded =
3645 afs_stats_cmperf.cacheBucket1_Discarded =
3646 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3650 if (aflags & AFSCALL_INIT_MEMCACHE) {
3652 * Use a memory cache instead of a disk cache
3654 cacheDiskType = AFS_FCACHE_TYPE_MEM;
3655 afs_cacheType = &afs_MemCacheOps;
3656 afiles = (afiles < aDentries) ? afiles : aDentries; /* min */
3657 ablocks = afiles * (AFS_FIRSTCSIZE / 1024);
3658 /* ablocks is reported in 1K blocks */
3659 code = afs_InitMemCache(afiles, AFS_FIRSTCSIZE, aflags);
3661 afs_warn("afsd: memory cache too large for available memory.\n");
3662 afs_warn("afsd: AFS files cannot be accessed.\n\n");
3666 afs_warn("Memory cache: Allocating %d dcache entries...",
3669 cacheDiskType = AFS_FCACHE_TYPE_UFS;
3670 afs_cacheType = &afs_UfsCacheOps;
3676 * Shuts down the cache.
3680 shutdown_dcache(void)
3684 #ifdef AFS_CACHE_VNODE_PATH
3685 if (cacheDiskType != AFS_FCACHE_TYPE_MEM) {
3687 for (i = 0; i < afs_cacheFiles; i++) {
3688 tdc = afs_indexTable[i];
3690 afs_osi_FreeStr(tdc->f.inode.ufs);
3696 afs_osi_Free(afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3697 afs_osi_Free(afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3698 afs_osi_Free(afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3699 afs_osi_Free(afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3700 afs_osi_Free(afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3701 afs_osi_Free(afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3702 afs_osi_Free(afs_Initial_freeDSList,
3703 afs_dcentries * sizeof(struct dcache));
3704 #ifdef KERNEL_HAVE_PIN
3705 unpin((char *)afs_dcnextTbl, afs_cacheFiles * sizeof(afs_int32));
3706 unpin((char *)afs_dvnextTbl, afs_cacheFiles * sizeof(afs_int32));
3707 unpin((char *)afs_indexTable, afs_cacheFiles * sizeof(struct dcache *));
3708 unpin((char *)afs_indexTimes, afs_cacheFiles * sizeof(afs_hyper_t));
3709 unpin((char *)afs_indexUnique, afs_cacheFiles * sizeof(afs_uint32));
3710 unpin((u_char *) afs_indexFlags, afs_cacheFiles * sizeof(u_char));
3711 unpin(afs_Initial_freeDSList, afs_dcentries * sizeof(struct dcache));
3715 for (i = 0; i < afs_dhashsize; i++) {
3716 afs_dvhashTbl[i] = NULLIDX;
3717 afs_dchashTbl[i] = NULLIDX;
3720 afs_osi_Free(afs_dvhashTbl, afs_dhashsize * sizeof(afs_int32));
3721 afs_osi_Free(afs_dchashTbl, afs_dhashsize * sizeof(afs_int32));
3723 afs_blocksUsed = afs_dcentries = 0;
3724 afs_stats_cmperf.cacheBucket0_Discarded =
3725 afs_stats_cmperf.cacheBucket1_Discarded =
3726 afs_stats_cmperf.cacheBucket2_Discarded = 0;
3727 hzero(afs_indexCounter);
3729 afs_freeDCCount = 0;
3730 afs_freeDCList = NULLIDX;
3731 afs_discardDCList = NULLIDX;
3732 afs_freeDSList = afs_Initial_freeDSList = 0;
3734 LOCK_INIT(&afs_xdcache, "afs_xdcache");
3740 * Get a dcache ready for writing, respecting the current cache size limits
3742 * len is required because afs_GetDCache with flag == 4 expects the length
3743 * field to be filled. It decides from this whether it's necessary to fetch
3744 * data into the chunk before writing or not (when the whole chunk is
3747 * \param avc The vcache to fetch a dcache for
3748 * \param filePos The start of the section to be written
3749 * \param len The length of the section to be written
3753 * \return If successful, a reference counted dcache with tdc->lock held. Lock
3754 * must be released and afs_PutDCache() called to free dcache.
3757 * \note avc->lock must be held on entry. Function may release and reobtain
3758 * avc->lock and GLOCK.
3762 afs_ObtainDCacheForWriting(struct vcache *avc, afs_size_t filePos,
3763 afs_size_t len, struct vrequest *areq,
3766 struct dcache *tdc = NULL;
3769 /* read the cached info */
3771 tdc = afs_FindDCache(avc, filePos);
3773 ObtainWriteLock(&tdc->lock, 657);
3774 } else if (afs_blocksUsed >
3775 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3776 tdc = afs_FindDCache(avc, filePos);
3778 ObtainWriteLock(&tdc->lock, 658);
3779 if (!afs_IsDCacheFresh(tdc, avc)
3780 || (tdc->dflags & DFFetching)) {
3781 ReleaseWriteLock(&tdc->lock);
3787 afs_MaybeWakeupTruncateDaemon();
3788 while (afs_blocksUsed >
3789 PERCENT(CM_WAITFORDRAINPCT, afs_cacheBlocks)) {
3790 ReleaseWriteLock(&avc->lock);
3791 afs_MaybeWaitForCacheDrain();
3792 afs_MaybeFreeDiscardedDCache();
3793 afs_MaybeWakeupTruncateDaemon();
3794 ObtainWriteLock(&avc->lock, 509);
3796 avc->f.states |= CDirty;
3797 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3799 ObtainWriteLock(&tdc->lock, 659);
3802 tdc = afs_GetDCache(avc, filePos, areq, &offset, &len, 4);
3804 ObtainWriteLock(&tdc->lock, 660);
3807 if (!(afs_indexFlags[tdc->index] & IFDataMod)) {
3808 afs_stats_cmperf.cacheCurrDirtyChunks++;
3809 afs_indexFlags[tdc->index] |= IFDataMod; /* so it doesn't disappear */
3811 if (!(tdc->f.states & DWriting)) {
3812 /* don't mark entry as mod if we don't have to */
3813 tdc->f.states |= DWriting;
3814 tdc->dflags |= DFEntryMod;
3821 * Make a shadow copy of a dir's dcache. It's used for disconnected
3822 * operations like remove/create/rename to keep the original directory data.
3823 * On reconnection, we can diff the original data with the server and get the
3824 * server changes and with the local data to get the local changes.
3826 * \param avc The dir vnode.
3827 * \param adc The dir dcache.
3829 * \return 0 for success.
3831 * \note The vcache entry must be write locked.
3832 * \note The dcache entry must be read locked.
3835 afs_MakeShadowDir(struct vcache *avc, struct dcache *adc)
3837 int i, code, ret_code = 0, written, trans_size;
3838 struct dcache *new_dc = NULL;
3839 struct osi_file *tfile_src = NULL, *tfile_dst = NULL;
3840 struct VenusFid shadow_fid;
3843 /* Is this a dir? */
3844 if (vType(avc) != VDIR)
3847 if (avc->f.shadow.vnode || avc->f.shadow.unique)
3850 /* Generate a fid for the shadow dir. */
3851 shadow_fid.Cell = avc->f.fid.Cell;
3852 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3853 afs_GenShadowFid(&shadow_fid);
3855 ObtainWriteLock(&afs_xdcache, 716);
3857 /* Get a fresh dcache. */
3858 (void)afs_AllocDCache(&new_dc, avc, 0, 0, &shadow_fid);
3861 ObtainReadLock(&adc->mflock);
3863 /* Set up the new fid. */
3864 /* Copy interesting data from original dir dcache. */
3865 new_dc->mflags = adc->mflags;
3866 new_dc->dflags = adc->dflags;
3867 new_dc->f.modTime = adc->f.modTime;
3868 new_dc->f.versionNo = adc->f.versionNo;
3869 new_dc->f.states = adc->f.states;
3870 new_dc->f.chunk= adc->f.chunk;
3871 new_dc->f.chunkBytes = adc->f.chunkBytes;
3873 ReleaseReadLock(&adc->mflock);
3875 /* Now add to the two hash chains */
3876 i = DCHash(&shadow_fid, 0);
3877 afs_dcnextTbl[new_dc->index] = afs_dchashTbl[i];
3878 afs_dchashTbl[i] = new_dc->index;
3880 i = DVHash(&shadow_fid);
3881 afs_dvnextTbl[new_dc->index] = afs_dvhashTbl[i];
3882 afs_dvhashTbl[i] = new_dc->index;
3884 ReleaseWriteLock(&afs_xdcache);
3886 /* Alloc a 4k block. */
3887 data = afs_osi_Alloc(4096);
3889 afs_warn("afs_MakeShadowDir: could not alloc data\n");
3894 /* Open the files. */
3895 tfile_src = afs_CFileOpen(&adc->f.inode);
3901 tfile_dst = afs_CFileOpen(&new_dc->f.inode);
3907 /* And now copy dir dcache data into this dcache,
3911 while (written < adc->f.chunkBytes) {
3912 trans_size = adc->f.chunkBytes - written;
3913 if (trans_size > 4096)
3916 /* Read a chunk from the dcache. */
3917 code = afs_CFileRead(tfile_src, written, data, trans_size);
3918 if (code < trans_size) {
3923 /* Write it to the new dcache. */
3924 code = afs_CFileWrite(tfile_dst, written, data, trans_size);
3925 if (code < trans_size) {
3930 written+=trans_size;
3935 afs_CFileClose(tfile_dst);
3937 afs_CFileClose(tfile_src);
3940 afs_osi_Free(data, 4096);
3942 ReleaseWriteLock(&new_dc->lock);
3943 afs_PutDCache(new_dc);
3946 ObtainWriteLock(&afs_xvcache, 763);
3947 ObtainWriteLock(&afs_disconDirtyLock, 765);
3948 QAdd(&afs_disconShadow, &avc->shadowq);
3949 osi_Assert((afs_RefVCache(avc) == 0));
3950 ReleaseWriteLock(&afs_disconDirtyLock);
3951 ReleaseWriteLock(&afs_xvcache);
3953 avc->f.shadow.vnode = shadow_fid.Fid.Vnode;
3954 avc->f.shadow.unique = shadow_fid.Fid.Unique;
3961 * Delete the dcaches of a shadow dir.
3963 * \param avc The vcache containing the shadow fid.
3965 * \note avc must be write locked.
3968 afs_DeleteShadowDir(struct vcache *avc)
3971 struct VenusFid shadow_fid;
3973 shadow_fid.Cell = avc->f.fid.Cell;
3974 shadow_fid.Fid.Volume = avc->f.fid.Fid.Volume;
3975 shadow_fid.Fid.Vnode = avc->f.shadow.vnode;
3976 shadow_fid.Fid.Unique = avc->f.shadow.unique;
3978 tdc = afs_FindDCacheByFid(&shadow_fid);
3980 afs_HashOutDCache(tdc, 1);
3981 afs_DiscardDCache(tdc);
3984 avc->f.shadow.vnode = avc->f.shadow.unique = 0;
3985 ObtainWriteLock(&afs_disconDirtyLock, 708);
3986 QRemove(&avc->shadowq);
3987 ReleaseWriteLock(&afs_disconDirtyLock);
3988 afs_PutVCache(avc); /* Because we held it when we added to the queue */
3992 * Populate a dcache with empty chunks up to a given file size,
3993 * used before extending a file in order to avoid 'holes' which
3994 * we can't access in disconnected mode.
3996 * \param avc The vcache which is being extended (locked)
3997 * \param alen The new length of the file
4001 afs_PopulateDCache(struct vcache *avc, afs_size_t apos, struct vrequest *areq)
4004 afs_size_t len, offset;
4005 afs_int32 start, end;
4007 /* We're doing this to deal with the situation where we extend
4008 * by writing after lseek()ing past the end of the file . If that
4009 * extension skips chunks, then those chunks won't be created, and
4010 * GetDCache will assume that they have to be fetched from the server.
4011 * So, for each chunk between the current file position, and the new
4012 * length we GetDCache for that chunk.
4015 if (AFS_CHUNK(apos) == 0 || apos <= avc->f.m.Length)
4018 if (avc->f.m.Length == 0)
4021 start = AFS_CHUNK(avc->f.m.Length)+1;
4023 end = AFS_CHUNK(apos);
4026 len = AFS_CHUNKTOSIZE(start);
4027 tdc = afs_GetDCache(avc, AFS_CHUNKTOBASE(start), areq, &offset, &len, 4);